Skip to content

Examples and guides for using the OpenAI API

Update Agents API examples (#3083)

Abdulrahman Alfozan3326f7e8648b
diff --git a/examples/agents_api/apps/document_review/README.md b/examples/agents_api/apps/document_review/README.md
index 5996e6f1..7b8b7668 100644
--- a/examples/agents_api/apps/document_review/README.md
+++ b/examples/agents_api/apps/document_review/README.md
@@ -63,20 +63,30 @@ The source folder and policy skill are mounted read-only; reports are written to
The command logs the session, sandbox, mounted directories, specialist subagents, and generated artifacts as the review progresses.
+Invoice reports include extracted line items and a calculation. The application
+checks the arithmetic before returning a report. A person must still verify that
+the extracted amounts match the source document and review the recommendation.
+
Use an empty output folder for each run and unique document stems, such as `invoice-104.txt` and `contract-208.txt`. The names `summary` and `review-activity` are reserved.
## Inspect retained command activity
-Before deleting the session, the app exports retained commands and their turn IDs to `review-activity.json`. Retained item history currently includes coordinator commands, not the specialists' full activity. A `null` subagent ID identifies the coordinator.
+Before deleting the session, the app exports retained commands from the coordinator
+and each specialist to `review-activity.json`. A `null` subagent ID identifies the
+coordinator. Specialist commands come from their own item histories:
```python
-turn = await client.beta.agents.sessions.turns.retrieve(
- command["turn_id"], session_id=session.id
-)
-print(turn.subagent_id, command["command"])
+async for subagent in client.beta.agents.sessions.subagents.list(session.id):
+ async for item in client.beta.agents.sessions.subagents.items.list(
+ subagent.id, session_id=session.id
+ ):
+ if item.type == "command_execution":
+ print(subagent.id, item.command)
```
-These records come from API history, not model-written reviewer names. They are not a complete audit of specialist work. Protect this file like the reports: commands can contain document content.
+These records come from retained API history, not model-written reviewer names.
+They are not a complete security audit. Protect this file like the reports:
+commands can contain document content.
## How the policy skill works
diff --git a/examples/agents_api/apps/document_review/agent.py b/examples/agents_api/apps/document_review/agent.py
index 8fc91118..971d67d0 100644
--- a/examples/agents_api/apps/document_review/agent.py
+++ b/examples/agents_api/apps/document_review/agent.py
@@ -7,6 +7,7 @@ import json
import logging
import os
import sys
+from decimal import Decimal, InvalidOperation
from pathlib import Path
from typing import Any
@@ -25,7 +26,9 @@ larger batches. Do not review source documents yourself.
Each specialist must discover and apply $expense-review-policy before inspecting its
assigned documents. Follow the skill's arithmetic checks, decision rules, and required
-report fields. Each specialist writes /workspace/output/<document-stem>.json.
+report fields. Each specialist writes only its /workspace/output/<document-stem>.json,
+including the extracted line items and calculation for invoices. Specialists must not
+write summary.json. Check their arithmetic and document coverage before summarizing.
Wait for every specialist to finish, then write /workspace/output/summary.json with
document_count, reviews, and recommendation. Never approve a payment or sign a contract.
@@ -35,30 +38,71 @@ document_count, reviews, and recommendation. Never approve a payment or sign a c
async def review_activity(client: AsyncOpenAI, session_id: str) -> list[dict[str, Any]]:
"""Export sandbox commands available in retained item history."""
commands: list[dict[str, Any]] = []
- owners: dict[str, str | None] = {}
- async for item in client.beta.agents.sessions.items.list(
- session_id, limit=100, order="asc"
- ):
- if item.type != "command_execution":
- continue
- turn_id = item.turn_id
- if turn_id not in owners:
- turn = await client.beta.agents.sessions.turns.retrieve(
- turn_id, session_id=session_id
+ subagent_ids: list[str | None] = [None]
+ subagent_ids.extend(
+ [
+ subagent.id
+ async for subagent in client.beta.agents.sessions.subagents.list(session_id)
+ ]
+ )
+ for subagent_id in subagent_ids:
+ items = (
+ client.beta.agents.sessions.items.list(session_id, limit=100, order="asc")
+ if subagent_id is None
+ else client.beta.agents.sessions.subagents.items.list(
+ subagent_id, session_id=session_id, limit=100, order="asc"
)
- owners[turn_id] = turn.subagent_id
- commands.append(
- {
- "item_id": item.id,
- "turn_id": turn_id,
- "subagent_id": owners[turn_id],
- "command": item.command,
- "status": item.status,
- }
)
+ async for item in items:
+ if item.type == "command_execution":
+ commands.append(
+ {
+ "item_id": item.id,
+ "turn_id": item.turn_id,
+ "subagent_id": subagent_id,
+ "command": item.command,
+ "status": item.status,
+ }
+ )
return commands
+def validate_review(report: dict[str, Any], document: str) -> None:
+ """Reject incomplete reports and inconsistent invoice arithmetic."""
+ if (
+ report.get("document") != document
+ or not report.get("policy_id")
+ or report.get("document_type") not in {"invoice", "contract"}
+ or report.get("decision")
+ not in {"needs_info", "escalated", "ready_for_approval"}
+ ):
+ raise ValueError(f"{document}: incomplete policy review")
+ if report["document_type"] != "invoice":
+ return
+ try:
+ calculation = report["calculation"]
+ line_items = calculation["line_items"]
+ if not line_items:
+ raise ValueError("No invoice line items were extracted")
+ amounts = [
+ Decimal(str(item["quantity"])) * Decimal(str(item["unit_price"]))
+ for item in line_items
+ ]
+ shipping = Decimal(str(calculation["shipping"]))
+ stated = Decimal(str(report["amount"]))
+ calculated = Decimal(str(calculation["calculated_total"]))
+ difference = Decimal(str(calculation["difference"]))
+ if not all(
+ value.is_finite()
+ for value in [*amounts, shipping, stated, calculated, difference]
+ ):
+ raise ValueError("Invoice amounts must be finite")
+ if sum(amounts) + shipping != calculated or stated - calculated != difference:
+ raise ValueError("Invoice totals do not match the extracted line items")
+ except (KeyError, TypeError, ValueError, InvalidOperation) as error:
+ raise ValueError(f"{document}: invalid invoice calculation: {error}") from error
+
+
async def review_documents(
input_directory: Path, output_directory: Path
) -> dict[str, Any]:
@@ -124,7 +168,7 @@ async def review_documents(
)
logger.info("Sandbox started: %s", container.short_id)
parts: list[str] = []
- subagents = 0
+ subagents: set[str] = set()
prompt = f"""\
Review all {len(documents)} documents in /workspace/input.
First spawn specialist subagents and assign the documents to them.
@@ -136,10 +180,13 @@ and summarize the most important findings for the human approver.
session.id, input=prompt
) as events:
async for event in events:
- if event.type == "agent.session.subagent.created":
- subagents += 1
+ if (
+ event.type == "agent.session.subagent.created"
+ and event.subagent.id not in subagents
+ ):
+ subagents.add(event.subagent.id)
logger.info(
- "Specialist started: %s/%s", subagents, len(documents)
+ "Specialist started: %s/%s", len(subagents), len(documents)
)
elif (
event.type == "agent.session.turn.item.done"
@@ -166,7 +213,7 @@ and summarize the most important findings for the human approver.
"Document review was cancelled; reports may be incomplete."
)
- if len(documents) > 1 and subagents == 0:
+ if len(documents) > 1 and not subagents:
raise RuntimeError(
"The document batch was not delegated to specialist subagents."
)
@@ -187,10 +234,7 @@ and summarize the most important findings for the human approver.
f"The agent did not create {document_report.name}."
)
report = json.loads(document_report.read_text())
- if not report.get("policy_id") or not report.get("decision"):
- raise RuntimeError(
- f"{document_report.name} does not include its policy decision."
- )
+ validate_review(report, document.name)
reviews.append(
{
"document": document.name,
@@ -215,7 +259,7 @@ and summarize the most important findings for the human approver.
"reviews": reviews,
"status": "awaiting_approval",
"session_id": session.id,
- "subagents": subagents,
+ "subagents": len(subagents),
"activity": activity,
"output_directory": str(output_directory),
}
diff --git a/examples/agents_api/apps/document_review/skills/expense-review-policy/SKILL.md b/examples/agents_api/apps/document_review/skills/expense-review-policy/SKILL.md
index 95816d7a..b0a7ba01 100644
--- a/examples/agents_api/apps/document_review/skills/expense-review-policy/SKILL.md
+++ b/examples/agents_api/apps/document_review/skills/expense-review-policy/SKILL.md
@@ -12,8 +12,9 @@ Apply this policy to invoices, expense receipts, and service contracts.
## Invoices and expenses
- Read the entire invoice, including the vendor and every line item.
-- Use Python to multiply quantities by unit prices and add every line total plus shipping.
-- Strip currency separators, compare the result with `Total amount due`, and report the exact difference.
+- Extract every line item's quantity and unit price before calculating. Check the extracted list against every source line; an empty list is an error, not a zero subtotal.
+- Use Python's `decimal.Decimal` to multiply quantities by unit prices and sum the line totals. Compare this subtotal with the printed subtotal, then add shipping to calculate the total.
+- Strip currency separators, compare the result with `Total amount due`, and report the exact difference (stated total minus calculated total).
- Require a purchase order or another documented approval.
- Flag missing receipts, unsupported charges, and changed payment instructions.
- Escalate incorrect totals and unverified changes to bank details.
@@ -37,15 +38,27 @@ Write `/workspace/output/<document-stem>.json` with the following fields:
```json
{
"document": "invoice.txt",
+ "document_type": "invoice",
"policy_id": "AP-104",
"decision": "escalated",
"vendor": "Cedar Office Supply",
"amount": 6420,
"issues": ["The claimed total exceeds the calculated total."],
- "recommendation": "Escalate for human review."
+ "recommendation": "Escalate for human review.",
+ "calculation": {
+ "line_items": [{"quantity": 2, "unit_price": 100}],
+ "shipping": 20,
+ "calculated_total": 220,
+ "difference": 6200
+ }
}
```
Every `issues` entry must be a plain-English string, not a nested object.
+Use the actual document values, not the illustrative numbers above. Include every
+invoice line item in `calculation`; `amount` is the stated total. For contracts,
+set `document_type` to `contract` and `calculation` to `null`.
+
+Only the coordinator writes `summary.json`. A specialist writes its assigned report.
Never approve payments, sign contracts, or take external actions.
diff --git a/examples/agents_api/sandboxes/application_managed/blaxel/main.py b/examples/agents_api/sandboxes/application_managed/blaxel/main.py
index 13e2ddc1..a0b3b9d1 100644
--- a/examples/agents_api/sandboxes/application_managed/blaxel/main.py
+++ b/examples/agents_api/sandboxes/application_managed/blaxel/main.py
@@ -83,13 +83,6 @@ async def main() -> None:
raise RuntimeError(f"Agent failed: {event.type}")
if event.type == "agent.session.turn.output_text.delta":
print(event.delta, end="", flush=True)
- if (
- event.type == "agent.session.turn.completed"
- and event.turn.subagent_id is None
- ):
- break
- else:
- raise RuntimeError("Stream ended without a completed turn")
plan = await sandbox.fs.read(f"{WORKSPACE}/plan.md")
if not plan.strip():
diff --git a/examples/agents_api/sandboxes/application_managed/cloudflare/main.py b/examples/agents_api/sandboxes/application_managed/cloudflare/main.py
index b0395688..989f681b 100644
--- a/examples/agents_api/sandboxes/application_managed/cloudflare/main.py
+++ b/examples/agents_api/sandboxes/application_managed/cloudflare/main.py
@@ -55,13 +55,6 @@ async def main() -> None:
raise RuntimeError(f"Agent failed: {event.type}")
if event.type == "agent.session.turn.output_text.delta":
print(event.delta, end="", flush=True)
- if (
- event.type == "agent.session.turn.completed"
- and event.turn.subagent_id is None
- ):
- break
- else:
- raise RuntimeError("Stream ended without a completed turn")
response = await worker.get(f"{path}/plan")
response.raise_for_status()
diff --git a/examples/agents_api/sandboxes/application_managed/daytona/main.py b/examples/agents_api/sandboxes/application_managed/daytona/main.py
index f9f023f4..3d19e213 100644
--- a/examples/agents_api/sandboxes/application_managed/daytona/main.py
+++ b/examples/agents_api/sandboxes/application_managed/daytona/main.py
@@ -82,13 +82,6 @@ async def main() -> None:
raise RuntimeError(f"Agent failed: {event.type}")
if event.type == "agent.session.turn.output_text.delta":
print(event.delta, end="", flush=True)
- if (
- event.type == "agent.session.turn.completed"
- and event.turn.subagent_id is None
- ):
- break
- else:
- raise RuntimeError("Stream ended without a completed turn")
plan = (await sandbox.fs.download_file(f"{WORKSPACE}/plan.md")).decode(
"utf-8"
diff --git a/examples/agents_api/sandboxes/application_managed/digitalocean/main.py b/examples/agents_api/sandboxes/application_managed/digitalocean/main.py
index 196ae68a..9758d408 100644
--- a/examples/agents_api/sandboxes/application_managed/digitalocean/main.py
+++ b/examples/agents_api/sandboxes/application_managed/digitalocean/main.py
@@ -2,9 +2,8 @@
# requires-python = ">=3.11"
# dependencies = [
# "openai>=3.13.0",
-# "pydo[aio]>=0.40.0b7",
+# "pydo[aio] @ https://github.com/digitalocean/pydo/releases/download/v0.40.0-beta.7/pydo-0.40.0b7-py3-none-any.whl",
# ]
-# pydo = { url = "https://github.com/digitalocean/pydo/releases/download/v0.40.0-beta.7/pydo-0.40.0b7-py3-none-any.whl" }
# ///
"""Run an Agents API task in a DigitalOcean sandbox and clean up both resources."""
@@ -67,13 +66,6 @@ async def main() -> None:
raise RuntimeError(f"Agent failed: {event.type}")
if event.type == "agent.session.turn.output_text.delta":
print(event.delta, end="", flush=True)
- if (
- event.type == "agent.session.turn.completed"
- and event.turn.subagent_id is None
- ):
- break
- else:
- raise RuntimeError("Stream ended without a completed turn")
download = await digitalocean.agents.sessions.workspace_download(
sandbox_id, path="plan.md", timeout=60
diff --git a/examples/agents_api/sandboxes/application_managed/docker/main.py b/examples/agents_api/sandboxes/application_managed/docker/main.py
index ea6f834e..9c5419ef 100644
--- a/examples/agents_api/sandboxes/application_managed/docker/main.py
+++ b/examples/agents_api/sandboxes/application_managed/docker/main.py
@@ -62,7 +62,7 @@ _DOCKER_PROVISIONING: ContextVar[_DockerProvisioning | None] = ContextVar(
async def main() -> int:
api_key = os.environ["OPENAI_API_KEY"]
- executor_api_key = os.environ.get("OPENAI_EXECUTOR_API_KEY", api_key)
+ executor_api_key = os.environ["OPENAI_EXECUTOR_API_KEY"]
container_name: str | None = None
provisioner: asyncio.Task[str] | None = None
session: AgentSession | None = None
diff --git a/examples/agents_api/sandboxes/application_managed/e2b/main.py b/examples/agents_api/sandboxes/application_managed/e2b/main.py
index 0d1fc1d1..7766b0eb 100644
--- a/examples/agents_api/sandboxes/application_managed/e2b/main.py
+++ b/examples/agents_api/sandboxes/application_managed/e2b/main.py
@@ -74,13 +74,6 @@ async def main() -> None:
raise RuntimeError(f"Agent failed: {event.type}")
if event.type == "agent.session.turn.output_text.delta":
print(event.delta, end="", flush=True)
- if (
- event.type == "agent.session.turn.completed"
- and event.turn.subagent_id is None
- ):
- break
- else:
- raise RuntimeError("Stream ended without a completed turn")
plan = await sandbox.files.read(f"{WORKSPACE}/plan.md", user="root")
if not plan.strip():
diff --git a/examples/agents_api/sandboxes/application_managed/modal/main.py b/examples/agents_api/sandboxes/application_managed/modal/main.py
index bf68c40a..ae583862 100644
--- a/examples/agents_api/sandboxes/application_managed/modal/main.py
+++ b/examples/agents_api/sandboxes/application_managed/modal/main.py
@@ -43,7 +43,7 @@ SANDBOX_STARTUP_TIMEOUT_SECONDS = 120.0
async def main() -> int:
api_key = os.environ["OPENAI_API_KEY"]
- executor_api_key = os.environ.get("OPENAI_EXECUTOR_API_KEY", api_key)
+ executor_api_key = os.environ["OPENAI_EXECUTOR_API_KEY"]
sandbox: modal.Sandbox | None = None
session: AgentSession | None = None
overall_deadline = time.monotonic() + OVERALL_EXECUTION_TIMEOUT_SECONDS
diff --git a/examples/agents_api/sandboxes/application_managed/oci/main.py b/examples/agents_api/sandboxes/application_managed/oci/main.py
index 401bd949..27202b6c 100644
--- a/examples/agents_api/sandboxes/application_managed/oci/main.py
+++ b/examples/agents_api/sandboxes/application_managed/oci/main.py
@@ -250,13 +250,6 @@ async def main() -> None:
raise RuntimeError(f"Agent failed: {event.type}")
if event.type == "agent.session.turn.output_text.delta":
print(event.delta, end="", flush=True)
- if (
- event.type == "agent.session.turn.completed"
- and event.turn.subagent_id is None
- ):
- break
- else:
- raise RuntimeError("Stream ended without a completed turn")
plan = await asyncio.to_thread(
read_text_file, sandbox_client, sandbox_id, f"{WORKSPACE}/plan.md"
diff --git a/examples/agents_api/sandboxes/application_managed/runloop/main.py b/examples/agents_api/sandboxes/application_managed/runloop/main.py
index c59ab770..2fe542f5 100644
--- a/examples/agents_api/sandboxes/application_managed/runloop/main.py
+++ b/examples/agents_api/sandboxes/application_managed/runloop/main.py
@@ -78,13 +78,6 @@ async def main() -> None:
raise RuntimeError(f"Agent failed: {event.type}")
if event.type == "agent.session.turn.output_text.delta":
print(event.delta, end="", flush=True)
- if (
- event.type == "agent.session.turn.completed"
- and event.turn.subagent_id is None
- ):
- break
- else:
- raise RuntimeError("Stream ended without a completed turn")
plan = await devbox.file.read(file_path=f"{WORKSPACE}/plan.md")
if not plan.strip():
diff --git a/examples/agents_api/sandboxes/application_managed/vercel/main.py b/examples/agents_api/sandboxes/application_managed/vercel/main.py
index 6ae51c05..1f5a4ac7 100644
--- a/examples/agents_api/sandboxes/application_managed/vercel/main.py
+++ b/examples/agents_api/sandboxes/application_managed/vercel/main.py
@@ -84,13 +84,6 @@ async def main() -> None:
raise RuntimeError(f"Agent failed: {event.type}")
if event.type == "agent.session.turn.output_text.delta":
print(event.delta, end="", flush=True)
- if (
- event.type == "agent.session.turn.completed"
- and event.turn.subagent_id is None
- ):
- break
- else:
- raise RuntimeError("Stream ended without a completed turn")
plan = await sandbox.fs.read_text(f"{WORKSPACE}/plan.md")
if not plan.strip():
diff --git a/examples/agents_api/sandboxes/webhook_managed/cloudflare/src/index.ts b/examples/agents_api/sandboxes/webhook_managed/cloudflare/src/index.ts
index a2a987e8..93693a60 100644
--- a/examples/agents_api/sandboxes/webhook_managed/cloudflare/src/index.ts
+++ b/examples/agents_api/sandboxes/webhook_managed/cloudflare/src/index.ts
@@ -91,7 +91,7 @@ export class SessionController extends DurableObject<Env> {
const session = (await response.json()) as {
status: string;
agent: { id: string };
- environment: { type: string };
+ environment: { type: string; id: string; remote_url: string };
required_actions: { type: string; environment_id?: string }[];
};
if (
@@ -123,9 +123,9 @@ export class SessionController extends DurableObject<Env> {
"codex",
"exec-server",
"--remote",
- "https://api.openai.com/v1/agents/api",
+ session.environment.remote_url,
"--environment-id",
- action.environment_id,
+ session.environment.id,
]
.map((arg) => `'${arg.replaceAll("'", "'\\''")}'`)
.join(" ");
diff --git a/examples/agents_api/sandboxes/webhook_managed/digitalocean/README.md b/examples/agents_api/sandboxes/webhook_managed/digitalocean/README.md
index a4986583..c36f8c06 100644
--- a/examples/agents_api/sandboxes/webhook_managed/digitalocean/README.md
+++ b/examples/agents_api/sandboxes/webhook_managed/digitalocean/README.md
@@ -19,12 +19,12 @@ Idle sandboxes are paused automatically and resumed on reconnect.
Use Python 3.11+ and a DigitalOcean account with MARS access. Create the agent
using the [shared setup](../README.md#set-up-once).
-MARS session support ships in the pydo pre-release. Install it explicitly —
-without `--pre`, pip resolves to a stable release whose client has no `agents`
-resource:
+MARS session support ships in the PyDo beta release. The script's inline
+dependencies select its release wheel; the stable `0.40.0` client has no
+`agents` resource. To install the beta separately:
```bash
-pip install "pydo[aio]==0.40.0b7" --pre
+pip install "pydo[aio] @ https://github.com/digitalocean/pydo/releases/download/v0.40.0-beta.7/pydo-0.40.0b7-py3-none-any.whl"
```
App Platform deploys from a Git repository. Push a copy of these examples
@@ -33,7 +33,7 @@ to your own repository, preserving the `examples/agents_api/` paths. Set
[Dockerfile](Dockerfile) builds from the repository root and installs dependencies
at build time; credentials are available only at runtime.
-This recipe requires the upcoming OpenAI Python SDK release with `beta.agents`.
+This recipe uses OpenAI Python SDK `3.13.0` or later with `client.beta.agents`.
Do not add API keys or Git tokens to the Dockerfile or build context.
```bash
@@ -45,7 +45,7 @@ Configure these variables on the service:
- `OPENAI_API_KEY`: controller/session-read credential.
- `OPENAI_AGENT_ID`: agent ID from the shared setup.
- `OPENAI_EXECUTOR_API_KEY`: restricted executor credential, scoped to
- `api.agent.environment.connect`.
+ `api.agents.environments.connect`.
- `OPENAI_WEBHOOK_SECRET`: generated by OpenAI when registering the endpoint.
- `DIGITALOCEAN_TOKEN`: API token that can manage MARS sessions.
diff --git a/examples/agents_api/sandboxes/webhook_managed/digitalocean/handler.py b/examples/agents_api/sandboxes/webhook_managed/digitalocean/handler.py
index 1ea8bd22..3db28688 100644
--- a/examples/agents_api/sandboxes/webhook_managed/digitalocean/handler.py
+++ b/examples/agents_api/sandboxes/webhook_managed/digitalocean/handler.py
@@ -2,7 +2,7 @@
# requires-python = ">=3.11"
# dependencies = [
# "openai>=3.13.0",
-# "pydo[aio]>=0.40.0b7,!=0.40.0",
+# "pydo[aio] @ https://github.com/digitalocean/pydo/releases/download/v0.40.0-beta.7/pydo-0.40.0b7-py3-none-any.whl",
# "fastapi[standard]",
# ]
# ///
diff --git a/examples/agents_api/sandboxes/webhook_managed/vercel/api/provision.ts b/examples/agents_api/sandboxes/webhook_managed/vercel/api/provision.ts
index 83215637..3cc2c5d3 100644
--- a/examples/agents_api/sandboxes/webhook_managed/vercel/api/provision.ts
+++ b/examples/agents_api/sandboxes/webhook_managed/vercel/api/provision.ts
@@ -65,9 +65,9 @@ export default queue.handleNodeCallback<{ sessionId: string }>(
"codex",
"exec-server",
"--remote",
- "https://api.openai.com/v1/agents/api",
+ session.environment.remote_url,
"--environment-id",
- action.environment_id,
+ session.environment.id,
],
cwd: "/workspace",
detached: true,