add voice in openai api (not tested)

This commit is contained in:
bladeclara42
2025-06-30 09:57:40 +07:00
parent fa567efd3a
commit 64dc8d2517
5 changed files with 52 additions and 2 deletions

View File

@@ -11,4 +11,5 @@ OPENAI_API_BASE = os.getenv("OPENAI_API_BASE", "https://api.openai.com/v1")
DEEPSEEK_API_KEY = os.getenv("DEEPSEEK_API_KEY", "")
DEEPSEEK_API_BASE = os.getenv("DEEPSEEK_API_BASE", "https://api.deepseek.com/v1")
DEEPSEEK_MODEL = os.getenv("DEEPSEEK_MODEL", "deepseek-chat")
OPENAI_AUDIO_MODEL = os.getenv("OPENAI_AUDIO_MODEL", "")

View File

@@ -0,0 +1,39 @@
import openai
from openai import OpenAI
from openai import OpenAIError
from app.core.config import OPENAI_API_KEY, OPENAI_AUDIO_MODEL, OPENAI_API_BASE
# Ensure the API key is properly set
if not OPENAI_API_KEY:
raise ValueError("OPENAI_API_KEY is not set in environment variables")
# Initialize the client with proper configuration
client = OpenAI(
api_key=OPENAI_API_KEY,
base_url=OPENAI_API_BASE
)
async def generate_voice(messages: list):
if not messages:
raise ValueError("Messages list cannot be empty")
try:
response = client.chat.completions.create(
model=OPENAI_AUDIO_MODEL,
response_format="mp3",
messages=messages,
)
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"OpenAI 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