import os
import uuid
from openai import OpenAI
client = OpenAI(
api_key=os.environ["API_KEY"],
base_url=os.environ["API_BASE_URL"],
max_retries=0,
)
response = client.responses.create(
model=os.environ["MODEL_ALIAS"],
input="یک پاسخ کوتاه بده",
extra_headers={"Idempotency-Key": str(uuid.uuid4())},
)
print(response.output_text)
import OpenAI from "openai";
import { randomUUID } from "node:crypto";
const client = new OpenAI({
apiKey: process.env.API_KEY,
baseURL: process.env.API_BASE_URL.replace(/\/$/, ""),
maxRetries: 0
});
const input = [{ role: "user", content: "Propose setting my display name to Demo; do not execute." }];
const tools = [{
type: "function", name: "propose_setup_action", strict: false,
description: "Propose an action for approval only.",
parameters: { type: "object", properties: {
action_type: { type: "string", enum: ["configure_profile"] },
summary: { type: "string" }, values: { type: "object" }
}, required: ["action_type", "summary", "values"] }
}];
const first = await client.responses.create({
model: process.env.TEXT_MODEL_ALIAS, input, tools, max_output_tokens: 500
}, { headers: { "Idempotency-Key": randomUUID() } });
input.push(...first.output);
for (const call of first.output.filter(item => item.type === "function_call")) {
if (call.name !== "propose_setup_action") throw new Error("Unknown function");
const args = JSON.parse(call.arguments);
if (args.action_type !== "configure_profile") throw new Error("Invalid action");
// Your backend must also validate all fields, permissions and current state.
input.push({ type: "function_call_output", call_id: call.call_id,
output: JSON.stringify({ executed: false, status: "awaiting_user_confirmation" }) });
}
const final = await client.responses.create({
model: process.env.TEXT_MODEL_ALIAS, input, max_output_tokens: 500
}, { headers: { "Idempotency-Key": randomUUID() } });
console.log(final.output_text);
import os
import uuid
from openai import OpenAI
client = OpenAI(api_key=os.environ["API_KEY"],
base_url=os.environ["API_BASE_URL"].rstrip("/"), max_retries=0)
completed = None
try:
with client.responses.create(
model=os.environ["TEXT_MODEL_ALIAS"], input="Say hello briefly.",
max_output_tokens=200, stream=True,
extra_headers={"Idempotency-Key": str(uuid.uuid4())}
) as events:
for event in events:
if event.type in {"error", "response.failed", "response.incomplete"}:
raise RuntimeError("Stream failed or incomplete")
if event.type == "response.output_text.delta":
print(event.delta, end="", flush=True)
if event.type == "response.completed":
completed = event.response
except Exception:
# Record a safe request ID; do not automatically retry with a new key.
raise
if completed is None or completed.usage is None:
raise RuntimeError("No final response/usage: reconcile before retry")