import os import configparser from openai import OpenAI class OpenAIClient: def __init__(self): self.config = configparser.ConfigParser() self.config.read('config/config.ini') # Configure OpenAI client with OpenRouter-specific headers self.client = OpenAI( api_key=self.config['openai']['api_key'], 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): 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( model=self.config['openai']['model'], messages=formatted_messages, stream=True ) return response except Exception as e: # Enhanced error logging print(f"Error details: {e}") raise Exception(f"OpenAI API error: {str(e)}")