typicaleoxx/code-explainer-ai
0
1# this module communicates with the OpenRouter API2# it sends prompts to a language model and returns the generated explanation3 4 5import os6import requests7from dotenv import load_dotenv8 9 10# load environment variables from the .env file11load_dotenv()12 13 14# retrieve the OpenRouter API key15API_KEY = os.getenv("OPENROUTER_API_KEY")16 17 18# OpenRouter endpoint used for chat completions19API_URL = "https://openrouter.ai/api/v1/chat/completions"20 21 22# function that sends the prompt to the model and returns the explanation23def generate_explanation(prompt: str) -> str:24 25 headers = {"Authorization": f"Bearer {API_KEY}", "Content-Type": "application/json"}26 27 payload = {28 # use a stable model available through OpenRouter29 "model": "openai/gpt-4o-mini",30 # messages follow the standard chat format used by modern LLM APIs31 "messages": [{"role": "user", "content": prompt}],32 }33 34 try:35 36 # send the HTTP request to the OpenRouter API37 response = requests.post(API_URL, headers=headers, json=payload)38 39 # convert the API response into JSON format40 data = response.json()41 42 # ensure the expected response structure exists before accessing it43 if "choices" in data:44 return data["choices"][0]["message"]["content"]45 46 # if something unexpected happens return the raw response for debugging47 return str(data)48 49 except Exception as e:50 51 # return a readable error message52 return f"API request failed: {str(e)}"53 