import os
from pathlib import Path
from openai import OpenAI, APIConnectionError, APIStatusError
with OpenAI(base_url=os.environ["API_BASE_URL"].rstrip("/"),
api_key=os.environ["API_KEY"], timeout=120.0, max_retries=0) as client:
try:
with client.audio.speech.with_streaming_response.create(
model=os.environ["API_MODEL"], voice=os.environ["API_VOICE"],
input="Welcome to our application.", response_format="mp3",
) as response:
media_type = response.headers.get("content-type", "").split(";")[0].lower()
if not (media_type.startswith("audio/") or media_type == "application/octet-stream"):
raise ValueError("Expected audio bytes.")
audio = bytearray()
for chunk in response.iter_bytes():
audio.extend(chunk)
if len(audio) > 16 * 1024 * 1024:
raise ValueError("Example output exceeds 16 MiB.")
if not audio:
raise ValueError("Empty audio.")
with Path("speech.mp3").open("xb") as target:
target.write(audio)
print("Saved speech.mp3")
except APIStatusError as error:
raise SystemExit(f"Request failed (HTTP {error.status_code}). Check the request logs.")
except APIConnectionError:
raise SystemExit("Connection failed; check before resubmitting speech.")
except (ValueError, OSError):
raise SystemExit("Cannot save speech. Check the content type, size, and output file.")