44 lines
1.3 KiB
Python
44 lines
1.3 KiB
Python
# app/services/openai_service.py
|
|
import openai
|
|
import os
|
|
from openai import OpenAI
|
|
from openai import OpenAIError
|
|
from app.core.config import DEEPSEEK_API_BASE, DEEPSEEK_MODEL, DEEPSEEK_API_KEY
|
|
|
|
# Ensure the API key is properly set
|
|
if not DEEPSEEK_API_KEY:
|
|
raise ValueError("DEEPSEEK_API_KEY is not set in environment variables")
|
|
|
|
# Initialize the client with proper configuration
|
|
client = OpenAI(
|
|
api_key=DEEPSEEK_API_KEY,
|
|
base_url=DEEPSEEK_API_BASE
|
|
)
|
|
|
|
async def chat_with_openai(messages: list):
|
|
if not messages:
|
|
raise ValueError("Messages list cannot be empty")
|
|
|
|
try:
|
|
response = client.chat.completions.create(
|
|
model=DEEPSEEK_MODEL,
|
|
messages=messages,
|
|
max_tokens=1000,
|
|
temperature=0.7,
|
|
stream=False
|
|
)
|
|
|
|
if not response.choices or not response.choices[0].message.content:
|
|
return "No response content from the model"
|
|
|
|
return response.choices[0].message.content
|
|
|
|
except OpenAIError as e:
|
|
error_msg = f"DeepSeek API Error: {str(e)}"
|
|
print(error_msg)
|
|
raise Exception(error_msg) from e
|
|
except Exception as e:
|
|
error_msg = f"Unexpected error: {str(e)}"
|
|
print(error_msg)
|
|
raise Exception(error_msg) from e
|