Examples and guides for using the OpenAI API
Add Agents API application walkthroughs (#3106)
Abdulrahman Alfozan9a8e9f07dd8b
diff --git a/examples/agents_api/README.md b/examples/agents_api/README.mdindex dde7c6ad..88bacab6 100644--- a/examples/agents_api/README.md+++ b/examples/agents_api/README.md@@ -1,25 +1,26 @@# Agents API examples-Complete applications and sandbox integrations for the Agents API.+Complete applications and sandbox integrations for the Agents API. Each application+README walks through the implementation and explains how to run it.## Applications| Example | What it does || --- | --- |-| [Incident response](apps/sev_bot/README.md) | Investigate alerts and request approval for recovery actions. |-| [Slack bot](apps/slack_bot/README.md) | Answer requests using conversation history and connected workplace tools. |-| [Data analyst](apps/data_analyst/README.md) | Answer questions with read-only warehouse queries. |-| [GitHub issue investigator](apps/github_issues/README.md) | Reproduce reported bugs and prepare findings for GitHub. |-| [Document reviewer](apps/document_review/README.md) | Review invoices and contracts with policy skills and specialist agents. |+| [SRE bot](https://github.com/openai/openai-cookbook/tree/main/examples/agents_api/apps/sev_bot) | Investigate alerts and request approval for recovery actions. |+| [Slack bot](https://github.com/openai/openai-cookbook/tree/main/examples/agents_api/apps/slack_bot) | Answer requests using conversation history and connected workplace tools. |+| [Data analyst](https://github.com/openai/openai-cookbook/tree/main/examples/agents_api/apps/data_analyst) | Answer questions with read-only warehouse queries. |+| [GitHub issue investigator](https://github.com/openai/openai-cookbook/tree/main/examples/agents_api/apps/github_issues) | Reproduce reported bugs and prepare findings for GitHub. |+| [Document reviewer](https://github.com/openai/openai-cookbook/tree/main/examples/agents_api/apps/document_review) | Review invoices and contracts with policy skills and specialist agents. |## Sandbox integrations-- [Application-managed](sandboxes/application_managed/README.md): your application+- [Application-managed](https://github.com/openai/openai-cookbook/tree/main/examples/agents_api/sandboxes/application_managed): your applicationstarts and stops the sandbox directly.-- [Webhook-managed](sandboxes/webhook_managed/README.md): a deployed handler+- [Webhook-managed](https://github.com/openai/openai-cookbook/tree/main/examples/agents_api/sandboxes/webhook_managed): a deployed handlerprovisions the sandbox while a shared client calls the Agents API.-See the [sandbox overview](sandboxes/README.md) to choose a provisioning mode.+See the [sandbox overview](https://github.com/openai/openai-cookbook/tree/main/examples/agents_api/sandboxes) to choose a provisioning mode.## Run an examplediff --git a/examples/agents_api/apps/data_analyst/README.md b/examples/agents_api/apps/data_analyst/README.mdindex b41cc79d..186e745a 100644--- a/examples/agents_api/apps/data_analyst/README.md+++ b/examples/agents_api/apps/data_analyst/README.md@@ -1,7 +1,18 @@-# Data agent+# Build a data analyst with the Agents APIAsk questions about your own business data. The agent finds relevant warehouse tables, checks metric definitions and past analyses, runs read-only SQL, and remembers useful corrections for future investigations.+## Why use the Agents API?++A useful investigation usually takes several queries and follow-up questions.+The Agents API keeps that work in one session and lets the model call your+application's tools. Your application owns database access and decides which+context and saved corrections the analyst can see.++This example draws on [OpenAI's in-house data agent](https://openai.com/index/inside-our-in-house-data-agent/):+ground the analysis in real schemas, supply business context, expose the SQL,+and reuse corrections the team has explicitly saved.+```mermaidsequenceDiagramparticipant Person@@ -79,9 +90,217 @@ The `save_memory` tool is discovered on demand with `tool_search`. ProgrammaticUse a read-only warehouse role. The application also starts PostgreSQL connections in read-only mode, applies a query timeout, and shows every executed query. The included browser interface represents one local analyst. In a multi-user application, derive analyst identity from your authentication layer, not a request body or query parameter.+## Follow the implementation++The following excerpts explain [agent.py](https://github.com/openai/openai-cookbook/blob/main/examples/agents_api/apps/data_analyst/agent.py) and [warehouse.py](https://github.com/openai/openai-cookbook/blob/main/examples/agents_api/apps/data_analyst/warehouse.py).+The application above includes the tool-dispatch loop, error handling, and cleanup.++### 1. Discover tables before writing SQL++Load the example's environment, then create the warehouse adapter. Discovery+returns actual table columns, along with any ownership and freshness notes you+have supplied in the context file.++```python+from dotenv import load_dotenv+from examples.agents_api.apps.data_analyst.warehouse import Warehouse++load_dotenv("examples/agents_api/apps/data_analyst/.env")+warehouse = Warehouse()+tables = warehouse.search_tables({"query": "paid conversion"})+for table in tables["tables"]:+ print(table["columns"])+```++### 2. Add definitions and trusted queries++Use `DATA_AGENT_CONTEXT` to point to a JSON file containing `tables`, `metrics`,+`documents`, and `query_history`. For example, a metric record can define both+the calculation and the filters your team expects:++```json+{+ "metrics": [{+ "name": "paid_conversion_rate",+ "definition": "Paid subscriptions divided by eligible signups.",+ "filters": [+ "Exclude employees and test accounts.",+ "Exclude the current incomplete day."+ ]+ }],+ "documents": [{+ "title": "Checkout tracking migration",+ "text": "Mobile checkout tracking changed on August 18."+ }]+}+```++Replace those illustrative definitions with your team's reviewed definitions.+`query_history` records pair a `description` with a reviewed `sql` query, so the+agent can reuse established joins. A prior all-time query still needs an+explicit date range before it can answer a weekly question.++### 3. Register four tools++[agent.py](https://github.com/openai/openai-cookbook/blob/main/examples/agents_api/apps/data_analyst/agent.py) defines a schema for each tool, then enables tool search and+programmatic tool calling. Memory writing is deferred until the agent needs it:++```python+from examples.agents_api.apps.data_analyst.agent import define_tool++tools = [+ define_tool("search_tables", "Find tables and inspect schemas.",+ {"query": {"type": "string"}}),+ define_tool("search_context", "Find definitions, previous queries, and memories.",+ {"query": {"type": "string"}}),+ define_tool("query_warehouse", "Run read-only SQL.",+ {"sql": {"type": "string"}}),+ define_tool("save_memory", "Save a correction only when explicitly requested.",+ {"note": {"type": "string"},+ "scope": {"type": "string", "enum": ["personal", "team"]}},+ defer_loading=True),+ {"type": "tool_search"},+ {"type": "programmatic_tool_calling", "enabled": True},+]++handlers = {+ "search_tables": warehouse.search_tables,+ "search_context": warehouse.search_context,+ "query_warehouse": warehouse.query,+ "save_memory": warehouse.memory.save,+}+```++The model can combine discovery, context, and several queries before answering.+It never receives `WAREHOUSE_URL`. Query execution stays in your application,+under the read-only database role.++### 4. Start an investigation without a sandbox++A conversation-only session starts with input in the creation request:++```python+from openai import AsyncOpenAI++client = AsyncOpenAI()+instructions = """\+Find relevant tables and metric definitions.+Check previous analyses and saved corrections.+Run read-only queries and explain your findings, assumptions, and SQL.+Save memory only when the user explicitly asks.+"""++events = await client.beta.agents.sessions.create(+ agent={+ "model": "gpt-5.6-luna",+ "instructions": instructions,+ "reasoning": {"effort": "high"},+ "tools": tools,+ },+ environment={"type": "none"},+ input="Why did paid conversions drop last week?",+ stream=True,+)+```++Read `agent.session.created` to save `event.session.id`. When the creation+stream emits `agent.session.requires_action`, dispatch each pending function+call to its handler and return a result:++```python+import json++arguments = action.arguments+if isinstance(arguments, str):+ arguments = json.loads(arguments)+output = handlers[action.name](arguments)+await client.beta.agents.sessions.events.create(+ session_id,+ events=[{+ "type": "agent.session.input.tool_result",+ "turn_id": action.turn_id,+ "call_id": action.call_id,+ "success": True,+ "output": json.dumps(output),+ }],+)+```++Continue consuming the stream until the coordinator's turn completes. The+application deduplicates calls by turn and call ID, returns a generic error on+tool failure, and records every executed SQL query alongside the answer.++To use that complete loop without rebuilding it:++```python+from examples.agents_api.apps.data_analyst.agent import DataAnalyst++analyst = DataAnalyst(client, warehouse)+result = await analyst.answer("Why did paid conversions drop last week?")+print(result["answer"])+print(result["queries"])+```++Use either the low-level flow or `DataAnalyst`, not both for the same request.++### 5. Continue the same investigation++The application maps `conversation_id` to the saved API session. Pass it back+for the follow-up:++```python+follow_up = await analyst.answer(+ "Only include enterprise customers.",+ conversation_id=result["conversation_id"],+)+print(follow_up["answer"])+```++Internally, follow-ups use `client.beta.agents.sessions.stream(session_id,+input=question, tool_handlers=handlers)`. Unlike the creation stream, this SDK+helper dispatches the function handlers for you.++### 6. Save an explicit correction++Ask the agent to remember a rule, for example: "Remember that enterprise+conversion excludes manually provisioned accounts." The `save_memory` tool+writes the note with a personal or team scope:++```python+warehouse.memory.save({+ "note": "Enterprise conversion excludes manually provisioned accounts.",+ "scope": "team",+})+remembered = warehouse.search_context({"query": "enterprise conversion"})+print(remembered["memories"])+```++Session history retains the current conversation. Cross-session memory is+application-owned: [memory.py](https://github.com/openai/openai-cookbook/blob/main/examples/agents_api/apps/data_analyst/memory.py) saves corrections in `memories.json`.+Move that store to your application database when serving multiple users.++### 7. Inspect the evidence and clean up++A useful answer includes the result, the tables queried, the SQL, and any+assumptions. Treat the narrative as a conclusion to verify against those records,+not as a substitute for them. Results depend on your warehouse; this example+does not ship a fixed business dataset.++Delete the sessions and close the warehouse when the analyst is done:++```python+try:+ await analyst.close()+finally:+ await client.close()+```++The browser application performs this cleanup on shutdown. It keeps active+conversation mappings in memory, while saved corrections survive restarts.+## Files-- [main.py](main.py): Web routes, UI, and the command-line entrypoint.-- [agent.py](agent.py): Agent configuration, tools, and conversation flow.-- [warehouse.py](warehouse.py): Read-only queries, schemas, and business context.-- [memory.py](memory.py): Saved personal and team corrections.+- [main.py](https://github.com/openai/openai-cookbook/blob/main/examples/agents_api/apps/data_analyst/main.py): Web routes, UI, and the command-line entrypoint.+- [agent.py](https://github.com/openai/openai-cookbook/blob/main/examples/agents_api/apps/data_analyst/agent.py): Agent configuration, tools, and conversation flow.+- [warehouse.py](https://github.com/openai/openai-cookbook/blob/main/examples/agents_api/apps/data_analyst/warehouse.py): Read-only queries, schemas, and business context.+- [memory.py](https://github.com/openai/openai-cookbook/blob/main/examples/agents_api/apps/data_analyst/memory.py): Saved personal and team corrections.diff --git a/examples/agents_api/apps/document_review/README.md b/examples/agents_api/apps/document_review/README.mdindex 7b8b7668..e27ee64a 100644--- a/examples/agents_api/apps/document_review/README.md+++ b/examples/agents_api/apps/document_review/README.md@@ -2,6 +2,14 @@Mount a folder of invoices and contracts alongside a reusable accounts-payable policy skill. A `gpt-5.6-luna` agent delegates each document to a specialist subagent, applies the discovered skill, writes individual reports plus a consolidated summary, and leaves every approval to a person.+## Why use the Agents API?++A batch review needs more than one answer in a chat. The Agents API coordinates+specialist agents against a shared workspace and retains their command activity.+Mounted files keep inputs separate from outputs, and a discovered skill gives+each reviewer the same policy. Your application validates the reports and+decides what happens next.+```mermaidsequenceDiagramparticipant Person@@ -69,6 +77,139 @@ 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.+## Follow the implementation++The excerpts below follow [agent.py](https://github.com/openai/openai-cookbook/blob/main/examples/agents_api/apps/document_review/agent.py) and [sandbox.py](https://github.com/openai/openai-cookbook/blob/main/examples/agents_api/apps/document_review/sandbox.py).+Run the command above for the complete validation, activity export, and cleanup.++### 1. Create a multi-agent review session++The coordinator delegates documents to specialists. All reviewers discover the+same mounted policy through `capability_directories`.++```python+from openai import AsyncOpenAI++client = AsyncOpenAI()+instructions = """\+Coordinate a batch review of invoices and contracts in /workspace/input.+Delegate documents to specialist subagents before reviewing them.+Each specialist must apply $expense-review-policy and write its JSON report+to /workspace/output/<document-stem>.json.+Wait for all reviewers, then write /workspace/output/summary.json.+Never approve a payment or sign a contract.+"""+session = await client.beta.agents.sessions.create(+ agent={+ "model": "gpt-5.6-luna",+ "instructions": instructions,+ "reasoning": {"effort": "high"},+ "multi_agent": {"enabled": True, "max_concurrent_subagents": 4},+ },+ environment={+ "type": "self_hosted",+ "workspace_directory": "/workspace",+ "capability_directories": ["/workspace/skills"],+ },+)+```++### 2. Mount inputs, policy, and outputs separately++`start_executor` mounts the input folder and `skills/` read-only. Only the output+folder is writable. The output directory stays on the host after cleanup.++```python+import asyncio+from pathlib import Path+from examples.agents_api.apps.document_review.sandbox import start_executor++input_directory = Path("examples/agents_api/apps/document_review/sample_documents")+output_directory = Path("review-output")+output_directory.mkdir(exist_ok=True)++environment = session.environment+assert environment.type == "self_hosted"+container = await asyncio.to_thread(+ start_executor,+ input_directory,+ output_directory,+ environment.id,+ environment.remote_url,+)+```++The helper runs `codex exec-server` with the returned connection values and+injects `OPENAI_EXECUTOR_API_KEY` as `CODEX_API_KEY`. Replacing the mounted policy+does not require rebuilding the image.++### 3. Delegate the batch and follow progress++Send the review task and watch for specialist creation and output events:++```python+prompt = """\+Review every document in /workspace/input using specialist subagents.+Each specialist must apply $expense-review-policy and include its policy_id+and decision in the report. Wait for every review, write the consolidated+summary, and explain the findings to the human approver.+"""+async with client.beta.agents.sessions.stream(session.id, input=prompt) as events:+ async for event in events:+ if event.type == "agent.session.subagent.created":+ print(f"Specialist started: {event.subagent.id}")+ elif event.type == "agent.session.turn.output_text.delta":+ print(event.delta, end="", flush=True)+ elif event.type in {+ "agent.session.failed", "agent.session.turn.failed", "error",+ "agent.session.turn.cancelled",+ }:+ raise RuntimeError(f"Review did not finish: {event.to_dict()}")+```++The app checks that specialists were created and that every source document has+a report. Enabling multi-agent execution is not, by itself, proof that work was+delegated.++### 4. Validate the reports before presenting them++Load the generated JSON and apply the application's validation:++```python+import json+from examples.agents_api.apps.document_review.agent import validate_review++reviews = []+for document in sorted(input_directory.iterdir()):+ if not document.is_file():+ continue+ report = json.loads((output_directory / f"{document.stem}.json").read_text())+ validate_review(report, document.name)+ reviews.append({"report": report, "status": "awaiting_approval"})++summary = json.loads((output_directory / "summary.json").read_text())+```++For invoices, validation recomputes the total from extracted line items and+shipping. It cannot establish that extraction matched the original document;+that still needs review. The included invoice should flag a $900 overcharge,+a missing purchase order, and changed bank details.++### 5. Keep the artifacts and release compute++Export retained command activity before deleting the session, as shown below.+Then attempt both cleanup operations:++```python+try:+ await client.beta.agents.sessions.delete(session.id)+finally:+ await asyncio.to_thread(container.remove, force=True)+```++Close the OpenAI client after cleanup. Reports remain in `review-output`; a+person reviews them before any payment or contract decision.+## Inspect retained command activityBefore deleting the session, the app exports retained commands from the coordinator@@ -114,6 +255,6 @@ Replace the included skill with your team's own accounts-payable or contract-rev## Files-- [main.py](main.py): Command-line arguments and the batch summary.-- [agent.py](agent.py): Specialist reviews, report validation, and activity export.-- [sandbox.py](sandbox.py): Document, artifact, and skill mounts.+- [main.py](https://github.com/openai/openai-cookbook/blob/main/examples/agents_api/apps/document_review/main.py): Command-line arguments and the batch summary.+- [agent.py](https://github.com/openai/openai-cookbook/blob/main/examples/agents_api/apps/document_review/agent.py): Specialist reviews, report validation, and activity export.+- [sandbox.py](https://github.com/openai/openai-cookbook/blob/main/examples/agents_api/apps/document_review/sandbox.py): Document, artifact, and skill mounts.diff --git a/examples/agents_api/apps/github_issues/README.md b/examples/agents_api/apps/github_issues/README.mdindex 5e3ddeed..c28d4622 100644--- a/examples/agents_api/apps/github_issues/README.md+++ b/examples/agents_api/apps/github_issues/README.md@@ -2,6 +2,13 @@Someone opens an issue. Your agent checks out the repository, reproduces the problem in an isolated sandbox, and posts a useful investigation back to GitHub.+## Why use the Agents API?++The issue webhook starts the investigation without a developer opening a chat.+An Agents API session gives the agent access to the checked-out repository and+test commands. Your application verifies the trigger, posts the report, and+releases the workspace. Each issue gets its own sandbox.+```mermaidsequenceDiagramparticipant User@@ -65,8 +72,140 @@ The receiver verifies GitHub signatures, ignores duplicate deliveries, and releaFor deployment, persist delivery IDs and use a durable job queue so failed investigations can be retried after a restart.+## Follow the implementation++These excerpts follow [main.py](https://github.com/openai/openai-cookbook/blob/main/examples/agents_api/apps/github_issues/main.py), [agent.py](https://github.com/openai/openai-cookbook/blob/main/examples/agents_api/apps/github_issues/agent.py), and+[github.py](https://github.com/openai/openai-cookbook/blob/main/examples/agents_api/apps/github_issues/github.py). Use the runnable application for complete webhook+verification, background processing, and cleanup.++### 1. Accept the webhook and check out the repository++Verify GitHub's signature and deduplicate `X-GitHub-Delivery` before scheduling+work. The receiver accepts `issues.opened` events and acknowledges them while+the investigation runs in the background.++The worker clones the repository into a temporary directory:++```python+import asyncio+import tempfile+from pathlib import Path+from examples.agents_api.apps.github_issues.github import clone_repository+from examples.agents_api.apps.github_issues.agent import investigate_issue++app_directory = Path("examples/agents_api/apps/github_issues").resolve()+with tempfile.TemporaryDirectory(dir=app_directory) as directory:+ workspace = Path(directory) / "repository"+ await asyncio.to_thread(+ clone_repository, event["repository"]["clone_url"], workspace,+ )+ result = await investigate_issue(event["issue"], workspace)+```++`clone_repository` uses `GITHUB_TOKEN` for private repositories through the+subprocess environment, not a token embedded in the command or URL. Validate+repository access before processing untrusted issue content.++### 2. Create a session and attach the checkout++Inside `investigate_issue`, create a session with instructions to investigate,+not change, the repository:++```python+from openai import AsyncOpenAI++client = AsyncOpenAI()+instructions = """\+Investigate the reported bug and inspect the repository.+Run relevant tests and identify the likely root cause.+Write /workspace/investigation.md without modifying source files.+"""+session = await client.beta.agents.sessions.create(+ agent={+ "model": "gpt-5.6-sol",+ "instructions": instructions,+ "reasoning": {"effort": "high"},+ },+ environment={"type": "self_hosted", "workspace_directory": "/workspace"},+)+```++The Docker executor mounts the checkout at `/workspace` with write access so+tests and the report can create files. Instructions not to edit source are not+a filesystem permission boundary; use a disposable clone.++```python+from examples.agents_api.apps.github_issues.agent import start_executor++environment = session.environment+assert environment.type == "self_hosted"+container = await asyncio.to_thread(+ start_executor, workspace, environment.id, environment.remote_url,+)+```++The executor receives the restricted `OPENAI_EXECUTOR_API_KEY`; GitHub posting+credentials stay in the application.++### 3. Stream the investigation and read the report++Pass the issue title and body as input, then read the report from the mounted+directory after the turn succeeds:++```python+issue = event["issue"]+prompt = f"""\+Investigate issue #{issue['number']}: {issue['title']}++{issue.get('body', '')}++Run the relevant tests and write /workspace/investigation.md.+"""+async with client.beta.agents.sessions.stream(session.id, input=prompt) as events:+ async for stream_event in events:+ if stream_event.type == "agent.session.turn.output_text.delta":+ print(stream_event.delta, end="", flush=True)+ elif stream_event.type in {+ "agent.session.failed", "agent.session.turn.failed", "error",+ "agent.session.turn.cancelled",+ }:+ raise RuntimeError(f"Investigation did not finish: {stream_event.to_dict()}")++report = (workspace / "investigation.md").read_text()+```++The included issue should lead to findings like these:++```text+Express shipping becomes free for orders over $100.+Reproduction: shipping_cost(125, express=True) returns 0; expected 15.+Cause: the free-shipping condition runs before the express-shipping check.+Suggested fix: check express shipping first, then apply the standard discount.+```++Check the actual test output in the report before accepting the diagnosis.++### 4. Return the findings to GitHub and clean up++The application posts the report to the issue's comments endpoint, not through+an agent tool:++```python+from examples.agents_api.apps.github_issues.github import post_findings++await post_findings(issue, result["findings"])+```++`post_findings` sends credentials only to `https://api.github.com/` URLs.+The investigation's `finally` block removes the container and deletes its+session even if reporting fails. The temporary-directory context removes the+checkout after the report has been read into memory.++To extend this into a fix agent, add a separate, explicit approval step before+applying changes or opening a pull request. This example only posts findings.+## Files-- [main.py](main.py): Webhook handling and the included-issue entrypoint.-- [agent.py](agent.py): Sandbox investigation and report collection.-- [github.py](github.py): Signature verification, repository cloning, and comments.+- [main.py](https://github.com/openai/openai-cookbook/blob/main/examples/agents_api/apps/github_issues/main.py): Webhook handling and the included-issue entrypoint.+- [agent.py](https://github.com/openai/openai-cookbook/blob/main/examples/agents_api/apps/github_issues/agent.py): Sandbox investigation and report collection.+- [github.py](https://github.com/openai/openai-cookbook/blob/main/examples/agents_api/apps/github_issues/github.py): Signature verification, repository cloning, and comments.diff --git a/examples/agents_api/apps/sev_bot/README.md b/examples/agents_api/apps/sev_bot/README.mdindex 20f903eb..8eae85df 100644--- a/examples/agents_api/apps/sev_bot/README.md+++ b/examples/agents_api/apps/sev_bot/README.md@@ -1,7 +1,16 @@-# SRE agent for incident response+# Build an SRE agent for incident responseAn incident alert opens a Slack thread in `#oncall`. The agent investigates production telemetry, GitHub pull requests and commits, AWS infrastructure, and similar past incidents. It posts its findings and asks a responder to approve any rollback.+## Why use the Agents API?++An incident webhook starts the work; responders continue it in Slack. The Agents+API keeps the investigation in a persistent session, connects operational tools,+and pauses for application-owned decisions. Your application manages alert+deduplication, responder permissions, historical incident records, and cleanup.++This example records rollback approval but never executes a deployment.+```mermaidsequenceDiagramparticipant Alert as PagerDuty / incident.io@@ -43,14 +52,16 @@ The first run uses bundled metrics, logs, deployments, GitHub changes, AWS telem## Configure the Slack bot-From the repository root:+Clone the Cookbook, or run the remaining commands from your existing checkout:```bash+git clone https://github.com/openai/openai-cookbook.git+cd openai-cookbookcp examples/agents_api/apps/sev_bot/.env.example examples/agents_api/apps/sev_bot/.envdocker build -t agent-api-sev-sandbox:latest examples/agents_api/apps/sev_bot```-Create the Slack app from [`slack-app-manifest.yaml`](slack-app-manifest.yaml). Replace `https://your-app.example` with your application's HTTPS address, install the app, and invite it to `#oncall`.+Create the Slack app from [`slack-app-manifest.yaml`](https://github.com/openai/openai-cookbook/blob/main/examples/agents_api/apps/sev_bot/slack-app-manifest.yaml). Replace `https://your-app.example` with your application's HTTPS address, install the app, and invite it to `#oncall`.Add `OPENAI_API_KEY`, `OPENAI_EXECUTOR_API_KEY`, `SLACK_BOT_TOKEN`, and `SLACK_SIGNING_SECRET` to `examples/agents_api/apps/sev_bot/.env`. Use OpenAI keys with the same owner, organization, and project.@@ -60,7 +71,7 @@ Each incident gets a self-hosted sandbox running `codex exec-server`. The app paTo create an executor key with the required permission, open [Agents > Environments > Keys](https://platform.openai.com/agents?tab=environments&environment_view=keys) and select **Create**.-The app mounts [`runbooks/`](runbooks/) read-only at `/workspace/runbooks`. The agent reads `checkout-api.md` for mitigation steps and recovery checks. Add a runbook named after each service when connecting your own incidents.+The app mounts [`runbooks/`](https://github.com/openai/openai-cookbook/tree/main/examples/agents_api/apps/sev_bot/runbooks) read-only at `/workspace/runbooks`. The agent reads `checkout-api.md` for mitigation steps and recovery checks. Add a runbook named after each service when connecting your own incidents.## Connect Agents API approval webhooks@@ -109,6 +120,164 @@ The agent posts its sample investigation to `#oncall`, tracing the outage to theTo inspect a real repository, configure GitHub MCP below.+## Follow the implementation++These excerpts show the incident flow in [main.py](https://github.com/openai/openai-cookbook/blob/main/examples/agents_api/apps/sev_bot/main.py), [alerts.py](https://github.com/openai/openai-cookbook/blob/main/examples/agents_api/apps/sev_bot/alerts.py),+and [agent.py](https://github.com/openai/openai-cookbook/blob/main/examples/agents_api/apps/sev_bot/agent.py). Run the receiver above for the complete signature checks,+deduplication, approval handling, and cleanup.++### 1. Turn an alert into one investigation++The receiver normalizes provider payloads and queues investigations in the+background. An active alert fingerprint maps to one incident, Slack thread, and+agent session.++```python+from fastapi import BackgroundTasks, Request+from examples.agents_api.apps.sev_bot.alerts import queue_alerts+[email protected]("/webhooks/alerts")+async def receive_alert(request: Request, tasks: BackgroundTasks):+ # Authenticate the sender before accepting the payload.+ payload = await request.json()+ return queue_alerts(app.state.bot, payload, tasks)+```++`queue_alerts` also handles resolution events. The runnable receiver checks+`ALERT_WEBHOOK_TOKEN`; native PagerDuty or incident.io signatures must be verified+at your ingress before forwarding.++### 2. Create the incident session++The agent gets read-only evidence tools and a separate function for proposing+a rollback. GitHub and AWS MCP tools are added only when configured in `.env`.++```python+from openai import AsyncOpenAI+from examples.agents_api.apps.sev_bot.tools import configured_tools++client = AsyncOpenAI()+instructions = """\+Investigate the incident using service evidence, GitHub, AWS, and past incidents.+Consult /workspace/runbooks/<service>.md and explain impact, likely cause, and next steps.+Use read-only tools and distinguish sample data from live findings.+If a rollout caused the incident, propose a rollback to the previous healthy version.+Approval records a decision; it does not execute a rollback.+"""++session = await client.beta.agents.sessions.create(+ agent={+ "model": "gpt-5.6-sol",+ "instructions": instructions,+ "reasoning": {"effort": "high"},+ "multi_agent": {"enabled": True, "max_concurrent_subagents": 3},+ "tools": configured_tools(),+ },+ environment={"type": "self_hosted", "workspace_directory": "/workspace"},+)+incident.session_id = session.id+```++The app opens a message in `#oncall` and stores its timestamp on the incident.+All findings and follow-ups use that thread.++### 3. Attach the incident sandbox++The sandbox image contains the Codex CLI and AWS skills. `start_executor` mounts+the runbooks read-only and passes only `OPENAI_EXECUTOR_API_KEY` as+`CODEX_API_KEY`. Use the connection values returned by the session:++```python+import asyncio+from examples.agents_api.apps.sev_bot.agent import start_executor++environment = session.environment+assert environment.type == "self_hosted"+container = await asyncio.to_thread(+ start_executor, environment.id, environment.remote_url,+)+incident.sandbox = container+```++Skills supply investigation instructions; they do not grant AWS access. Live+GitHub and AWS credentials remain with the service-connected MCP tools.++### 4. Stream evidence and wait for approval++Only read-only tools have automatic handlers. Keep `propose_rollback` out of+the handler map so the function call remains pending until a responder decides.++```python+handlers = {+ "get_service_evidence": bot.get_service_evidence,+ "recall_incidents": bot.recall_incidents,+}+prompt = """\+Investigate the checkout-api error spike.+Correlate service metrics, deployments, code changes, and past incidents.+Explain customer impact and cite the evidence for your proposed next steps.+"""++async with client.beta.agents.sessions.stream(+ session.id, input=prompt, tool_handlers=handlers,+) as events:+ async for event in events:+ if event.type == "agent.session.turn.output_text.delta":+ print(event.delta, end="", flush=True)+ elif event.type in {"agent.session.failed", "agent.session.turn.failed", "error"}:+ raise RuntimeError(f"Investigation failed: {event.to_dict()}")+```++The application collects the answer and posts it to the incident's Slack thread.+If the agent proposes a rollback, the `agent.session.action_required` webhook+tells the receiver to retrieve the pending function call and show approval+buttons. The [approval callback](#connect-agents-api-approval-webhooks) returns+the decision using the pending turn and call IDs. Keep the stream and receiver+running while waiting for that decision.++### 5. Continue the incident, then save the resolution++A Slack follow-up retrieves `incident.session_id` and starts another turn with+the same tools and workspace. For example:++```text+Did this Redis connection-pool failure happen before?+What should we check after the rollback?+```++When a resolved alert arrives, the app saves the report through+[memory.py](https://github.com/openai/openai-cookbook/blob/main/examples/agents_api/apps/sev_bot/memory.py), posts a final update, and closes the runtime. The next+incident can find that report through `recall_incidents`.++Cleanup must attempt both resources even if one operation fails:++```python+try:+ await client.beta.agents.sessions.delete(session.id)+finally:+ await asyncio.to_thread(container.remove, force=True)+```++The app also attempts cleanup after investigation failures and on shutdown.+Close the OpenAI client after all incident runtimes have been released.++### Expected result++The bundled alert supplies evidence for a report like this; wording will vary:++```text+SEV-1: Checkout API error rate reached 18.7%+Evidence: bundled sample telemetry, not a live production diagnosis.++GitHub: PR #418 reduced the Redis connection pool from 64 to 8.+AWS: ElastiCache shows 143 waiting requests.+History: INC-0931 recorded a similar pool exhaustion incident.+Proposal: Roll back to 2026.08.26.3, pending responder approval.+```++Check that the findings cite the sample evidence and that approval records a+decision without contacting a deployment system.+## Connect incident alertsSend incident webhooks through your authenticated ingress to:@@ -137,7 +306,7 @@ The example parses these provider payloads but does not verify their native sign## Use AWS skills-The [Dockerfile](Dockerfile) installs the Codex CLI and all [AWS Agent Toolkit skills](https://github.com/aws/agent-toolkit-for-aws/tree/main/skills) during the image build. From `/workspace`, it runs:+The [Dockerfile](https://github.com/openai/openai-cookbook/blob/main/examples/agents_api/apps/sev_bot/Dockerfile) installs the Codex CLI and all [AWS Agent Toolkit skills](https://github.com/aws/agent-toolkit-for-aws/tree/main/skills) during the image build. From `/workspace`, it runs:```bashnpx --yes skills add aws/agent-toolkit-for-aws/skills \@@ -203,9 +372,9 @@ Only the first two have automatic handlers. The webhook and Slack callback compl## Files-- [main.py](main.py): Webhook routes and application startup.-- [agent.py](agent.py): Incident investigation, approval, resolution, and cleanup.-- [alerts.py](alerts.py): Alert normalization and background task scheduling.-- [tools.py](tools.py): Service evidence and GitHub/AWS MCP tools.-- [slack.py](slack.py): Slack messages, buttons, and callback verification.-- [memory.py](memory.py): Incident history loading, search, and atomic saves.+- [main.py](https://github.com/openai/openai-cookbook/blob/main/examples/agents_api/apps/sev_bot/main.py): Webhook routes and application startup.+- [agent.py](https://github.com/openai/openai-cookbook/blob/main/examples/agents_api/apps/sev_bot/agent.py): Incident investigation, approval, resolution, and cleanup.+- [alerts.py](https://github.com/openai/openai-cookbook/blob/main/examples/agents_api/apps/sev_bot/alerts.py): Alert normalization and background task scheduling.+- [tools.py](https://github.com/openai/openai-cookbook/blob/main/examples/agents_api/apps/sev_bot/tools.py): Service evidence and GitHub/AWS MCP tools.+- [slack.py](https://github.com/openai/openai-cookbook/blob/main/examples/agents_api/apps/sev_bot/slack.py): Slack messages, buttons, and callback verification.+- [memory.py](https://github.com/openai/openai-cookbook/blob/main/examples/agents_api/apps/sev_bot/memory.py): Incident history loading, search, and atomic saves.diff --git a/examples/agents_api/apps/slack_bot/README.md b/examples/agents_api/apps/slack_bot/README.mdindex a12728aa..7a7ab0ff 100644--- a/examples/agents_api/apps/slack_bot/README.md+++ b/examples/agents_api/apps/slack_bot/README.md@@ -1,9 +1,17 @@-# Build an AI teammate for Slack+# Build a Slack bot with the Agents APITag your bot in Slack to search conversations, investigate projects, analyze data,or prepare a GitHub pull request. Each Slack thread gets its own Agents APIsession and isolated workspace.+## Why use the Agents API?++Slack supplies the trigger and interface. The Agents API keeps the conversation+and tool results in a session, runs the agent, and streams its progress. Your+application controls Slack access, workplace credentials, and the sandbox+lifecycle. A follow-up can continue the investigation without repeating the+original context.+```mermaidsequenceDiagramparticipant Person@@ -86,6 +94,187 @@ The first message creates a `self_hosted` Agents API session and starts a Dockercontainer running `codex exec-server`. Replies reuse the same session andworkspace. Send `stop` to cancel an active request.+## Follow the implementation++The snippets below show the main steps in [main.py](https://github.com/openai/openai-cookbook/blob/main/examples/agents_api/apps/slack_bot/main.py), [agent.py](https://github.com/openai/openai-cookbook/blob/main/examples/agents_api/apps/slack_bot/agent.py),+and [connections.py](https://github.com/openai/openai-cookbook/blob/main/examples/agents_api/apps/slack_bot/connections.py). Run the application above for the complete+event handling and cleanup; the snippets are not a second application.++### 1. Map each Slack thread to a session++Use the workspace, channel, and original message timestamp as the conversation+key. Follow-up mentions in the same thread reuse that key.++```python[email protected]("app_mention")+async def on_mention(event, context, say):+ thread_ts = event.get("thread_ts") or event["ts"]+ thread_id = f"{context.team_id}:{event['channel']}:{thread_ts}"+ answer = await bot.answer(+ event["text"],+ thread_id=thread_id,+ team_id=context.team_id,+ channel_id=event["channel"],+ )+ await say(text=answer, thread_ts=thread_ts)+```++The runnable handler also removes the bot's own mention, ignores duplicate+deliveries, and routes messages received during an active request to steering+or cancellation.++### 2. Give the agent scoped tools++Slack tools run in your application with the bot token. [tools.py](https://github.com/openai/openai-cookbook/blob/main/examples/agents_api/apps/slack_bot/tools.py)+provides four functions: `search_slack_messages`, `read_slack_channel`,+`find_teammate`, and `list_slack_files`. Message and file access is bound to the+channel that triggered the request, not a model-selected channel.++For example, the search tool filters recent channel messages:++```python+async def search_slack_messages(arguments):+ response = await slack.conversations_history(channel=channel_id, limit=100)+ query = arguments["query"].casefold()+ return {+ "messages": [+ message for message in response["messages"]+ if query in message.get("text", "").casefold()+ ][:20]+ }+```++This searches recent history, not the entire Slack workspace. Optional Notion,+Google Drive, and GitHub connections use service-connected MCP tools instead.+See [Connect shared workplace tools](#connect-shared-workplace-tools) for setup.++### 3. Create the session and attach its sandbox++`Connections.get()` returns the tool definitions and optional vault for the+workspace. Create the session once, then save its ID under the thread key.++```python+from openai import AsyncOpenAI+from examples.agents_api.apps.slack_bot.connections import Connections++client = AsyncOpenAI()+connections = Connections(client)+vault_id, tools = await connections.get(team_id)++instructions = """\+Search connected tools and cite the records behind your answer.+Use your workspace to analyze data, inspect repositories, and prepare changes.+Change external systems only when the user explicitly asks.+Delegate complex investigations when helpful.+"""++session = await client.beta.agents.sessions.create(+ agent={+ "model": "gpt-5.6-sol",+ "instructions": instructions,+ "reasoning": {"effort": "medium"},+ "multi_agent": {"enabled": True, "max_concurrent_subagents": 3},+ "tools": tools,+ },+ environment={"type": "self_hosted", "workspace_directory": "/workspace"},+ vault_ids=[vault_id] if vault_id is not None else [],+)+sessions[thread_id] = session.id+```++Start `codex exec-server` using the returned connection URL and environment ID.+Only the restricted executor key enters the container.++```python+import asyncio+import os+import docker++environment = session.environment+assert environment.type == "self_hosted"+container = await asyncio.to_thread(+ docker.from_env().containers.run,+ "agent-api-sandbox:latest",+ [+ "codex", "exec-server",+ "--remote", environment.remote_url,+ "--environment-id", environment.id,+ ],+ environment={"CODEX_API_KEY": os.environ["OPENAI_EXECUTOR_API_KEY"]},+ detach=True,+ auto_remove=True,+ init=True,+)+```++### 4. Stream the investigation into Slack++Pass the application handlers when starting a turn. The SDK runs those handlers+for function calls; Agents API handles the service-connected MCP tools.++```python+from examples.agents_api.apps.slack_bot.tools import slack_handlers++parts = []+async with client.beta.agents.sessions.stream(+ session.id,+ input=question,+ tool_handlers=slack_handlers(slack, channel_id),+) as events:+ async for event in events:+ if event.type == "agent.session.turn.output_text.delta":+ parts.append(event.delta)+ elif event.type in {"agent.session.failed", "agent.session.turn.failed", "error"}:+ raise RuntimeError(f"Investigation failed: {event.to_dict()}")++await slack.chat_postMessage(+ channel=channel_id, thread_ts=thread_ts, text="".join(parts),+)+```++The app also uses `agent.session.turn.item.added` and+`agent.session.subagent.created` to update one progress message while tools and+specialists work. It does not post every text delta as a new Slack message.++### 5. Continue, steer, or cancel++When the thread is idle, start another stream with the saved session ID. During+an active turn, send a message event to steer the existing work:++```python+await client.beta.agents.sessions.events.create(+ sessions[thread_id],+ events=[{+ "type": "agent.session.input.message",+ "input": [{+ "role": "user",+ "content": [{"type": "input_text", "text": "Only include launch blockers."}],+ }],+ }],+)+```++For `stop`, send `{"type": "agent.session.input.cancel"}` instead. Cancellation+ends the active turn, not the conversation; later requests reuse the session+and workspace.++### 6. Release the conversation's resources++Keep the sandbox for follow-ups, then delete the session and remove the+container when the conversation expires. [SlackBot.close()](https://github.com/openai/openai-cookbook/blob/main/examples/agents_api/apps/slack_bot/agent.py) does this+on application shutdown. Add an expiry policy when deploying a long-running bot.++```python+try:+ await client.beta.agents.sessions.delete(session.id)+finally:+ await asyncio.to_thread(container.remove, force=True)+```++Close the OpenAI client after cleaning up all conversations. Session IDs,+sandbox handles, and thread mappings are kept in memory in this example. Persist+them if conversations must survive application restarts.+## Connect shared workplace toolsThe bot already has tools for searching the current Slack channel, reading recent@@ -105,6 +294,34 @@ workspace and connects the corresponding MCP servers:- Google Drive: `https://drivemcp.googleapis.com/mcp/v1`- GitHub: `https://api.githubcopilot.com/mcp/`+For example, the vault holds a GitHub token while the tool definition contains+only the server URL. Attach the vault ID to the session's `vault_ids`:++```python+vault = await client.beta.agents.vaults.create(+ name="Slack integrations",+ metadata={"slack_team_id": team_id, "owner": "slack_bot"},+)+await client.beta.agents.vaults.credentials.create(+ vault.id,+ name="GitHub",+ auth={+ "type": "static_bearer",+ "mcp_server_url": "https://api.githubcopilot.com/mcp/",+ "token": os.environ["GITHUB_TOKEN"],+ },+)+github_tool = {+ "type": "mcp",+ "server_label": "github",+ "connection_origin": "service",+ "transport": {"type": "http", "server_url": "https://api.githubcopilot.com/mcp/"},+}+```++Add `github_tool` to the agent's tools. The runnable app finds and reuses its+workspace vault rather than creating one for every thread.+Notion and Google Drive require OAuth access tokens for the shared account;Notion's hosted MCP server does not accept internal integration secrets. GitHubaccepts an appropriately scoped personal access token. Everyone who can use the@@ -130,7 +347,7 @@ Restarting the bot reuses the stored OAuth credential instead of replacing refre## Files-- [main.py](main.py): Slack events and application startup.-- [agent.py](agent.py): Agent sessions, sandboxes, streaming, and cleanup.-- [tools.py](tools.py): Slack search, channel, teammate, and file tools.-- [connections.py](connections.py): MCP connections and vault credentials.+- [main.py](https://github.com/openai/openai-cookbook/blob/main/examples/agents_api/apps/slack_bot/main.py): Slack events and application startup.+- [agent.py](https://github.com/openai/openai-cookbook/blob/main/examples/agents_api/apps/slack_bot/agent.py): Agent sessions, sandboxes, streaming, and cleanup.+- [tools.py](https://github.com/openai/openai-cookbook/blob/main/examples/agents_api/apps/slack_bot/tools.py): Slack search, channel, teammate, and file tools.+- [connections.py](https://github.com/openai/openai-cookbook/blob/main/examples/agents_api/apps/slack_bot/connections.py): MCP connections and vault credentials.diff --git a/registry.yaml b/registry.yamlindex f1c5ef8f..c2d3773d 100644--- a/registry.yaml+++ b/registry.yaml@@ -4,10 +4,10 @@# should build pages for, and indicates metadata such as tags, creation date and# authors for each page.-- title: Agents API applications and sandbox integrations- path: examples/agents_api/README.md- slug: agents-api-examples- description: Explore complete Agents API applications and application-managed or webhook-managed sandbox integrations.+- title: Build an SRE agent for incident response+ path: examples/agents_api/apps/sev_bot/README.md+ slug: agents-api-sev-bot+ description: Investigate incidents in Slack using service telemetry, GitHub, AWS, and past incident reports, with human review before recovery.date: 2026-09-10authors:- alfozan@@ -16,6 +16,29 @@- agents- sandbox+- title: Build a Slack bot with the Agents API+ path: examples/agents_api/apps/slack_bot/README.md+ slug: agents-api-slack-bot+ description: Connect Slack threads to persistent agent sessions, workplace tools, and isolated sandboxes.+ date: 2026-09-10+ authors:+ - alfozan+ tags:+ - agents-api+ - agents+ - sandbox++- title: Build a data analyst with the Agents API+ path: examples/agents_api/apps/data_analyst/README.md+ slug: agents-api-data-analyst+ description: Investigate warehouse questions with read-only SQL, business context, and saved analyst corrections.+ date: 2026-09-10+ authors:+ - alfozan+ tags:+ - agents-api+ - agents+- title: Combining security scanners with the Agents SDKpath: examples/agents_sdk/security_scanners_with_agents_sdk.ipynbslug: evidence-grounded-security-review-swarm