fix: enhance OpenAI client for OpenRouter compatibility while maintaining configuration

This commit is contained in:
2025-03-25 17:21:06 +00:00
parent d1ef966e65
commit bef445baf4

View File

@@ -6,18 +6,30 @@ class OpenAIClient:
def __init__(self): def __init__(self):
self.config = configparser.ConfigParser() self.config = configparser.ConfigParser()
self.config.read('config/config.ini') self.config.read('config/config.ini')
# Configure OpenAI client with OpenRouter-specific headers
self.client = OpenAI( self.client = OpenAI(
api_key=self.config['openai']['api_key'], api_key=self.config['openai']['api_key'],
base_url=self.config['openai']['base_url'] base_url=self.config['openai']['base_url'],
default_headers={
"HTTP-Referer": "https://streamlit-chat-app.com", # Required by OpenRouter
"X-Title": "Streamlit Chat App" # Optional, helps with analytics
}
) )
def get_chat_response(self, messages): def get_chat_response(self, messages):
try: try:
# Ensure messages are correctly formatted
formatted_messages = [{"role": msg["role"], "content": msg["content"]} for msg in messages]
# Make API request
response = self.client.chat.completions.create( response = self.client.chat.completions.create(
model=self.config['openai']['model'], model=self.config['openai']['model'],
messages=messages, messages=formatted_messages,
stream=True stream=True
) )
return response return response
except Exception as e: except Exception as e:
# Enhanced error logging
print(f"Error details: {e}")
raise Exception(f"OpenAI API error: {str(e)}") raise Exception(f"OpenAI API error: {str(e)}")