Spaces:
Sleeping
Sleeping
File size: 1,345 Bytes
367cc0b 25f7a75 483491a 367cc0b 25f7a75 5ab4802 0e97127 367cc0b 70650cf 25f7a75 a6361a2 25f7a75 367cc0b 25f7a75 367cc0b 25f7a75 483491a 25f7a75 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
# helpers/ai_client.py
import os
from openai import OpenAI
from typing import Optional
import logging
# Set up logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
class AIClient:
def __init__(self):
# Initialize OpenAI client
self.client = OpenAI(api_key=os.getenv("OPENROUTER_API_KEY"), base_url="https://openrouter.ai/api/v1")
def chat(
self,
prompt: str,
system_message: str = "",
model_id: str = "openai/gpt-4o-mini",
conversation_id: str = "",
user_id: str = "string"
) -> str:
try:
messages = []
# Add system message if provided
if system_message:
messages.append({"role": "system", "content": system_message})
# Add user message
messages.append({"role": "user", "content": prompt})
# Create completion
completion = self.client.chat.completions.create(
model=model_id,
messages=messages
)
# Return the response text
return completion.choices[0].message.content
except Exception as e:
logger.error(f"Error in chat completion: {str(e)}")
raise Exception(f"Error from OpenRouter API: {str(e)}") |