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

3
.gitignore vendored
View File

@@ -85,3 +85,6 @@ dmypy.json
_build/
docs/_build/
".env"
# Ignore all files in the pycache folder
__pycache__

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

View File

@@ -1,9 +1,9 @@
from fastapi import FastAPI
from app.api.v1 import translate
# from app.api.v1 import voice
from app.api.v1 import voice
app = FastAPI()
# Include your routes
app.include_router(translate.router, prefix="/api/v1/translate", tags=["translate"])
# app.include_router(voice.router, prefix="/api/v1/voice", tags=["voice"])
app.include_router(voice.router, prefix="/api/v1/voice", tags=["voice"])

7
app/services/voice.py Normal file
View File

@@ -0,0 +1,7 @@
from app.core.openai_voice_client import generate_voice
async def generate_voice(text: str) -> str:
voice = await generate_voice(text)
return voice