67 lines
2.1 KiB
Python
67 lines
2.1 KiB
Python
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,
|
|
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"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
|
|
|
|
async def generate_transcription(audio_file_path: str) -> str:
|
|
if not audio_file_path:
|
|
raise ValueError("Audio file path cannot be empty")
|
|
|
|
try:
|
|
response = client.audio.transcriptions.create(
|
|
model=OPENAI_AUDIO_MODEL,
|
|
file=audio_file_path,
|
|
response_format="text",
|
|
language="id"
|
|
)
|
|
|
|
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 |