import os
from openai import OpenAI, APIConnectionError, APIStatusError
history = []
with OpenAI(base_url=os.environ["API_BASE_URL"].rstrip("/"),
api_key=os.environ["API_KEY"], timeout=60.0, max_retries=0) as client:
try:
for prompt in ["Suggest a short name for a coffee shop.", "Explain that name in one sentence."]:
history.append({"role": "user", "content": prompt})
result = client.responses.create(
model=os.environ["API_MODEL"], input=history,
instructions="Answer briefly in plain text.",
store=False, include=["reasoning.encrypted_content"],
)
if result.status != "completed" or not result.output_text.strip():
raise ValueError("No complete text reply.")
for item in result.output:
if item.type == "reasoning":
continue
if item.type != "message" or item.status != "completed":
raise ValueError("Unexpected or incomplete output item.")
if any(part.type != "output_text" for part in item.content):
raise ValueError("Refusal or unsupported message content.")
# Keep full output items, including encrypted reasoning and message metadata.
history.extend(item.model_dump(exclude_none=True) for item in result.output)
print(result.output_text)
except APIStatusError as error:
raise SystemExit(f"Request failed (HTTP {error.status_code}). No automatic retry.")
except APIConnectionError:
raise SystemExit("Connection failed. No automatic retry.")
except (ValueError, TypeError, AttributeError):
raise SystemExit("Conversation turn did not produce a complete text reply.")