Examples and guides for using the OpenAI API
Update Agents API examples for the official Python SDK (#3081)
Abdulrahman Alfozan82cb1f5e0ebe
diff --git a/examples/agents_api/README.md b/examples/agents_api/README.mdindex c11e163e..dde7c6ad 100644--- a/examples/agents_api/README.md+++ b/examples/agents_api/README.md@@ -30,9 +30,8 @@ their dependencies inline for [uv](https://docs.astral.sh/uv/).The application examples require Python 3.14. Provider examples declare theirsupported Python version in each script.-These examples target the upcoming OpenAI Python SDK with `client.beta.agents`-and `sessions.stream()`. The inline dependencies target `openai>=3.12.0`; wait-for the Agents API SDK release before running them from PyPI.+These examples use the official OpenAI Python SDK's `client.beta.agents`+and `sessions.stream()`, available in `openai>=3.13.0` on PyPI.Create sessions with the standard client:@@ -55,6 +54,8 @@ and clean up. Async applications use `AsyncOpenAI` with the sameKeep credentials in environment variables or the example's local `.env` file.Use a separate restricted `OPENAI_EXECUTOR_API_KEY` for sandbox execution. Followthe [executor authentication requirements](https://developers.openai.com/api/docs/guides/agents-api/environments/self-hosted#authentication).+The executor key needs `api.agents.environments.connect`, and its IP restrictions+must allow requests from your sandbox's outbound network.## Documentationdiff --git a/examples/agents_api/apps/data_analyst/agent.py b/examples/agents_api/apps/data_analyst/agent.pyindex 6d291137..94522075 100644--- a/examples/agents_api/apps/data_analyst/agent.py+++ b/examples/agents_api/apps/data_analyst/agent.py@@ -3,13 +3,14 @@from __future__ import annotationsimport asyncio+import jsonimport os-from collections.abc import Mapping+import sys+from collections.abc import Callable, Mappingfrom typing import Anyfrom uuid import uuid4from openai import AsyncOpenAI-from openai.lib.streaming.agents import AsyncToolHandlerfrom openai.types.beta import AgentToolParamfrom openai.types.beta.agent_tool_param import AgentToolConfigParamFunctionfrom openai.types.beta.agents.session_create_params import Agent@@ -110,7 +111,7 @@ class DataAnalyst:queries.append(str(result["sql"]))return result- handlers: dict[str, AsyncToolHandler] = {+ handlers: dict[str, Callable[[dict[str, Any]], dict[str, Any]]] = {"search_tables": self.warehouse.search_tables,"search_context": lambda arguments: self.warehouse.search_context(arguments, user_id=user_id@@ -121,9 +122,12 @@ class DataAnalyst:),}- if conversation_id in self.sessions:- session = await self.client.beta.agents.sessions.retrieve(- self.sessions[conversation_id]+ first_turn = conversation_id not in self.sessions+ session_id = self.sessions.get(conversation_id)+ if session_id is not None:+ session = await self.client.beta.agents.sessions.retrieve(session_id)+ events = self.client.beta.agents.sessions.stream(+ session.id, input=question, tool_handlers=handlers)else:agent: Agent = {@@ -132,20 +136,57 @@ class DataAnalyst:"reasoning": {"effort": "high"},"tools": TOOLS,}- session = await self.client.beta.agents.sessions.create(+ # Conversation-only sessions need input at creation, not in a later call.+ events = await self.client.beta.agents.sessions.create(agent=agent,environment={"type": "none"},+ input=question,+ stream=True,)- self.sessions[conversation_id] = session.id- self.owners[conversation_id] = user_id- session_id = session.idparts: list[str] = []- async with self.client.beta.agents.sessions.stream(- session_id, input=question, tool_handlers=handlers- ) as events:+ completed = False+ handled_calls: set[tuple[str, str]] = set()+ async with events:async for event in events:- if event.type == "agent.session.turn.output_text.delta":+ if event.type == "agent.session.created":+ session_id = event.session.id+ self.sessions[conversation_id] = session_id+ self.owners[conversation_id] = user_id+ elif first_turn and event.type == "agent.session.requires_action":+ # Creation streams expose pending calls; follow-ups use SDK handlers.+ for action in event.session.required_actions:+ if action.type != "function_call":+ continue+ call = (action.turn_id, action.call_id)+ if call in handled_calls:+ continue+ try:+ arguments = action.arguments+ if isinstance(arguments, str):+ arguments = json.loads(arguments)+ if not isinstance(arguments, dict):+ raise ValueError("Function arguments must be an object")+ output = json.dumps(handlers[action.name](arguments))+ success, error = True, None+ except Exception:+ output, success, error = None, False, "Tool handler failed."+ await self.client.beta.agents.sessions.events.create(+ event.session.id,+ events=[+ {+ "type": "agent.session.input.tool_result",+ "turn_id": action.turn_id,+ "call_id": action.call_id,+ "success": success,+ "output": output,+ "error": error,+ }+ ],+ idempotency_key=str(uuid4()),+ )+ handled_calls.add(call)+ elif event.type == "agent.session.turn.output_text.delta":parts.append(event.delta)elif event.type == "agent.session.turn.output_text.done" and not parts:parts.append(event.text)@@ -157,6 +198,13 @@ class DataAnalyst:raise RuntimeError(f"Data investigation failed: {event.to_dict()}")elif event.type == "agent.session.turn.cancelled":raise RuntimeError("Data investigation was cancelled.")+ elif (+ event.type == "agent.session.turn.completed"+ and event.turn.subagent_id is None+ ):+ completed = True+ if not completed or session_id is None:+ raise RuntimeError("Stream ended without a completed investigation.")answer = "".join(parts)return {@@ -169,16 +217,20 @@ class DataAnalyst:}async def close(self) -> None:+ original_error = sys.exception()+ session_ids = list(set(self.sessions.values()))try:results = await asyncio.gather(- *(- self.client.beta.agents.sessions.delete(sid)- for sid in set(self.sessions.values())- ),+ *(self.client.beta.agents.sessions.delete(sid) for sid in session_ids),return_exceptions=True,)- for result in results:+ for session_id, result in zip(session_ids, results):if isinstance(result, BaseException):+ if original_error is not None:+ original_error.add_note(+ f"Could not delete session {session_id}: {result}"+ )+ continueraise resultfinally:self.sessions.clear()diff --git a/examples/agents_api/apps/data_analyst/main.py b/examples/agents_api/apps/data_analyst/main.pyindex a1d041a3..159b05a8 100644--- a/examples/agents_api/apps/data_analyst/main.py+++ b/examples/agents_api/apps/data_analyst/main.py@@ -1,7 +1,7 @@# /// script# requires-python = ">=3.14"# dependencies = [-# "openai>=3.12.0",+# "openai>=3.13.0",# "fastapi",# "psycopg[binary]",# "python-dotenv",diff --git a/examples/agents_api/apps/document_review/main.py b/examples/agents_api/apps/document_review/main.pyindex 3ff2a43a..e8dc9847 100644--- a/examples/agents_api/apps/document_review/main.py+++ b/examples/agents_api/apps/document_review/main.py@@ -1,7 +1,7 @@# /// script# requires-python = ">=3.14"# dependencies = [-# "openai>=3.12.0",+# "openai>=3.13.0",# "docker",# "python-dotenv",# ]diff --git a/examples/agents_api/apps/github_issues/main.py b/examples/agents_api/apps/github_issues/main.pyindex 8cbfce10..af892896 100644--- a/examples/agents_api/apps/github_issues/main.py+++ b/examples/agents_api/apps/github_issues/main.py@@ -1,7 +1,7 @@# /// script# requires-python = ">=3.14"# dependencies = [-# "openai>=3.12.0",+# "openai>=3.13.0",# "docker",# "fastapi",# "python-dotenv",diff --git a/examples/agents_api/apps/sev_bot/main.py b/examples/agents_api/apps/sev_bot/main.pyindex cf103b60..a4f844d0 100644--- a/examples/agents_api/apps/sev_bot/main.py+++ b/examples/agents_api/apps/sev_bot/main.py@@ -1,7 +1,7 @@# /// script# requires-python = ">=3.14"# dependencies = [-# "openai>=3.12.0",+# "openai>=3.13.0",# "aiohttp",# "docker",# "fastapi",diff --git a/examples/agents_api/apps/slack_bot/main.py b/examples/agents_api/apps/slack_bot/main.pyindex b333bc74..9290100e 100644--- a/examples/agents_api/apps/slack_bot/main.py+++ b/examples/agents_api/apps/slack_bot/main.py@@ -1,7 +1,7 @@# /// script# requires-python = ">=3.14"# dependencies = [-# "openai>=3.12.0",+# "openai>=3.13.0",# "aiohttp",# "docker",# "python-dotenv",diff --git a/examples/agents_api/sandboxes/application_managed/blaxel/main.py b/examples/agents_api/sandboxes/application_managed/blaxel/main.pyindex 63c3c493..13e2ddc1 100644--- a/examples/agents_api/sandboxes/application_managed/blaxel/main.py+++ b/examples/agents_api/sandboxes/application_managed/blaxel/main.py@@ -1,7 +1,7 @@# /// script# requires-python = ">=3.11"# dependencies = [-# "openai>=3.12.0",+# "openai>=3.13.0",# "blaxel>=0.4.3",# ]# ///diff --git a/examples/agents_api/sandboxes/application_managed/cloudflare/main.py b/examples/agents_api/sandboxes/application_managed/cloudflare/main.pyindex 5f1b3d86..b0395688 100644--- a/examples/agents_api/sandboxes/application_managed/cloudflare/main.py+++ b/examples/agents_api/sandboxes/application_managed/cloudflare/main.py@@ -1,6 +1,6 @@# /// script# requires-python = ">=3.11"-# dependencies = ["openai>=3.12.0", "httpx>=0.27"]+# dependencies = ["openai>=3.13.0", "httpx>=0.27"]# ///"""Provision a Cloudflare sandbox through your Worker, without webhooks."""diff --git a/examples/agents_api/sandboxes/application_managed/daytona/main.py b/examples/agents_api/sandboxes/application_managed/daytona/main.pyindex ce052f5e..f9f023f4 100644--- a/examples/agents_api/sandboxes/application_managed/daytona/main.py+++ b/examples/agents_api/sandboxes/application_managed/daytona/main.py@@ -1,7 +1,7 @@# /// script# requires-python = ">=3.11"# dependencies = [-# "openai>=3.12.0",+# "openai>=3.13.0",# "daytona>=0.207.0",# ]# ///diff --git a/examples/agents_api/sandboxes/application_managed/digitalocean/main.py b/examples/agents_api/sandboxes/application_managed/digitalocean/main.pyindex 900879cb..196ae68a 100644--- a/examples/agents_api/sandboxes/application_managed/digitalocean/main.py+++ b/examples/agents_api/sandboxes/application_managed/digitalocean/main.py@@ -1,7 +1,7 @@# /// script# requires-python = ">=3.11"# dependencies = [-# "openai>=3.12.0",+# "openai>=3.13.0",# "pydo[aio]>=0.40.0b7",# ]# pydo = { url = "https://github.com/digitalocean/pydo/releases/download/v0.40.0-beta.7/pydo-0.40.0b7-py3-none-any.whl" }diff --git a/examples/agents_api/sandboxes/application_managed/docker/main.py b/examples/agents_api/sandboxes/application_managed/docker/main.pyindex 9109a3ec..ea6f834e 100644--- a/examples/agents_api/sandboxes/application_managed/docker/main.py+++ b/examples/agents_api/sandboxes/application_managed/docker/main.py@@ -1,7 +1,7 @@# /// script# requires-python = ">=3.11"# dependencies = [-# "openai>=3.12.0",+# "openai>=3.13.0",# ]# ///diff --git a/examples/agents_api/sandboxes/application_managed/e2b/main.py b/examples/agents_api/sandboxes/application_managed/e2b/main.pyindex 6bd8ac6c..0d1fc1d1 100644--- a/examples/agents_api/sandboxes/application_managed/e2b/main.py+++ b/examples/agents_api/sandboxes/application_managed/e2b/main.py@@ -1,7 +1,7 @@# /// script# requires-python = ">=3.11"# dependencies = [-# "openai>=3.12.0",+# "openai>=3.13.0",# "e2b>=2.45.1",# ]# ///diff --git a/examples/agents_api/sandboxes/application_managed/modal/main.py b/examples/agents_api/sandboxes/application_managed/modal/main.pyindex 92c83dd2..bf68c40a 100644--- a/examples/agents_api/sandboxes/application_managed/modal/main.py+++ b/examples/agents_api/sandboxes/application_managed/modal/main.py@@ -1,7 +1,7 @@# /// script# requires-python = ">=3.11"# dependencies = [-# "openai>=3.12.0",+# "openai>=3.13.0",# "modal[api-proxy-support]>=1.3.4,<2",# ]# ///diff --git a/examples/agents_api/sandboxes/application_managed/oci/main.py b/examples/agents_api/sandboxes/application_managed/oci/main.pyindex 20012603..401bd949 100644--- a/examples/agents_api/sandboxes/application_managed/oci/main.py+++ b/examples/agents_api/sandboxes/application_managed/oci/main.py@@ -1,6 +1,6 @@# /// script# requires-python = ">=3.11"-# dependencies = ["openai>=3.12.0"]+# dependencies = ["openai>=3.13.0"]# ///"""Run an Agents API task in an application-managed OCI GenAI Sandbox."""diff --git a/examples/agents_api/sandboxes/application_managed/runloop/main.py b/examples/agents_api/sandboxes/application_managed/runloop/main.pyindex c8bd7d8d..c59ab770 100644--- a/examples/agents_api/sandboxes/application_managed/runloop/main.py+++ b/examples/agents_api/sandboxes/application_managed/runloop/main.py@@ -1,7 +1,7 @@# /// script# requires-python = ">=3.11"# dependencies = [-# "openai>=3.12.0",+# "openai>=3.13.0",# "runloop-api-client>=1.31.0",# ]# ///diff --git a/examples/agents_api/sandboxes/application_managed/vercel/main.py b/examples/agents_api/sandboxes/application_managed/vercel/main.pyindex f76eb3dc..6ae51c05 100644--- a/examples/agents_api/sandboxes/application_managed/vercel/main.py+++ b/examples/agents_api/sandboxes/application_managed/vercel/main.py@@ -1,7 +1,7 @@# /// script# requires-python = ">=3.11"# dependencies = [-# "openai>=3.12.0",+# "openai>=3.13.0",# "vercel>=0.10.0",# ]# ///diff --git a/examples/agents_api/sandboxes/webhook_managed/blaxel/handler.py b/examples/agents_api/sandboxes/webhook_managed/blaxel/handler.pyindex 28630f3c..88238819 100644--- a/examples/agents_api/sandboxes/webhook_managed/blaxel/handler.py+++ b/examples/agents_api/sandboxes/webhook_managed/blaxel/handler.py@@ -4,7 +4,7 @@# "blaxel",# "fastapi[standard]",# "httpx",-# "openai>=3.12.0",+# "openai>=3.13.0",# "uvicorn",# ]# ///diff --git a/examples/agents_api/sandboxes/webhook_managed/client.py b/examples/agents_api/sandboxes/webhook_managed/client.pyindex edf86605..fb62b24f 100644--- a/examples/agents_api/sandboxes/webhook_managed/client.py+++ b/examples/agents_api/sandboxes/webhook_managed/client.py@@ -1,7 +1,7 @@# /// script# requires-python = ">=3.11"# dependencies = [-# "openai>=3.12.0",+# "openai>=3.13.0",# ]# ///diff --git a/examples/agents_api/sandboxes/webhook_managed/cloudflare/src/index.ts b/examples/agents_api/sandboxes/webhook_managed/cloudflare/src/index.tsindex 6191ad11..a2a987e8 100644--- a/examples/agents_api/sandboxes/webhook_managed/cloudflare/src/index.ts+++ b/examples/agents_api/sandboxes/webhook_managed/cloudflare/src/index.ts@@ -78,7 +78,10 @@ export class SessionController extends DurableObject<Env> {const response = await fetch(`https://api.openai.com/v1/agents/sessions/${encodeURIComponent(sessionId)}`,{- headers: { Authorization: `Bearer ${this.env.OPENAI_API_KEY}` },+ headers: {+ Authorization: `Bearer ${this.env.OPENAI_API_KEY}`,+ "OpenAI-Beta": "agents=v1",+ },signal: AbortSignal.timeout(30_000),},);diff --git a/examples/agents_api/sandboxes/webhook_managed/daytona/handler.py b/examples/agents_api/sandboxes/webhook_managed/daytona/handler.pyindex 9adc6324..fb84b257 100644--- a/examples/agents_api/sandboxes/webhook_managed/daytona/handler.py+++ b/examples/agents_api/sandboxes/webhook_managed/daytona/handler.py@@ -5,7 +5,7 @@# "fastapi>=0.115,<1",# "uvicorn>=0.30,<1",# "httpx>=0.27,<1",-# "openai>=3.12.0",+# "openai>=3.13.0",# ]# ///diff --git a/examples/agents_api/sandboxes/webhook_managed/digitalocean/handler.py b/examples/agents_api/sandboxes/webhook_managed/digitalocean/handler.pyindex 4f99e8d9..1ea8bd22 100644--- a/examples/agents_api/sandboxes/webhook_managed/digitalocean/handler.py+++ b/examples/agents_api/sandboxes/webhook_managed/digitalocean/handler.py@@ -1,7 +1,7 @@# /// script# requires-python = ">=3.11"# dependencies = [-# "openai>=3.12.0",+# "openai>=3.13.0",# "pydo[aio]>=0.40.0b7,!=0.40.0",# "fastapi[standard]",# ]diff --git a/examples/agents_api/sandboxes/webhook_managed/e2b/handler.py b/examples/agents_api/sandboxes/webhook_managed/e2b/handler.pyindex 61dc2cd3..fd404985 100644--- a/examples/agents_api/sandboxes/webhook_managed/e2b/handler.py+++ b/examples/agents_api/sandboxes/webhook_managed/e2b/handler.py@@ -5,7 +5,7 @@# "fastapi>=0.115,<1",# "uvicorn>=0.30,<1",# "httpx>=0.27,<1",-# "openai>=3.12.0",+# "openai>=3.13.0",# ]# ///diff --git a/examples/agents_api/sandboxes/webhook_managed/modal/handler.py b/examples/agents_api/sandboxes/webhook_managed/modal/handler.pyindex 7d8d9004..fdbfa88a 100644--- a/examples/agents_api/sandboxes/webhook_managed/modal/handler.py+++ b/examples/agents_api/sandboxes/webhook_managed/modal/handler.py@@ -1,7 +1,7 @@# /// script# requires-python = ">=3.11"# dependencies = [-# "openai>=3.12.0",+# "openai>=3.13.0",# "modal>=1.5.4,<2",# "fastapi[standard]",# ]@@ -28,7 +28,7 @@ executor_image = (.run_commands("npm install -g @openai/codex@alpha", f"mkdir -p {WORKSPACE}").workdir(WORKSPACE))-controller_image = executor_image.pip_install("fastapi[standard]", "openai>=3.12.0")+controller_image = executor_image.pip_install("fastapi[standard]", "openai>=3.13.0")@app.function(diff --git a/examples/agents_api/sandboxes/webhook_managed/vercel/api/provision.ts b/examples/agents_api/sandboxes/webhook_managed/vercel/api/provision.tsindex 185d5bb9..83215637 100644--- a/examples/agents_api/sandboxes/webhook_managed/vercel/api/provision.ts+++ b/examples/agents_api/sandboxes/webhook_managed/vercel/api/provision.ts@@ -8,7 +8,10 @@ export default queue.handleNodeCallback<{ sessionId: string }>(const response = await fetch(`https://api.openai.com/v1/agents/sessions/${encodeURIComponent(sessionId)}`,{- headers: { Authorization: `Bearer ${process.env.OPENAI_API_KEY}` },+ headers: {+ Authorization: `Bearer ${process.env.OPENAI_API_KEY}`,+ "OpenAI-Beta": "agents=v1",+ },signal: AbortSignal.timeout(30_000),},);