chatbot3 / app /services /openai_service.py
MuhammadSaad16's picture
Add application file
600f3a7
raw
history blame contribute delete
868 Bytes
from openai import OpenAI
from app.config import settings
from typing import List
import httpx
import asyncio
class OpenAIService:
def __init__(self):
# Use httpx client without problematic kwargs
http_client = httpx.Client()
self.client = OpenAI(api_key=settings.OPENAI_API_KEY, http_client=http_client)
self.model = "gpt-4o-mini"
async def get_chat_response(self, prompt: str, history: List[dict] = None) -> str:
messages = []
if history:
messages.extend(history)
messages.append({"role": "user", "content": prompt})
# Run the blocking OpenAI call in a thread pool
response = await asyncio.to_thread(
self.client.chat.completions.create,
model=self.model,
messages=messages
)
return response.choices[0].message.content