agents/apiTHE ENCYCLOPEDIA
Getting started

Python Agents API example with a real tool loop

Create a session, handle a read-only function call, stream progress, and check the root turn outcome in one Python file.

Python client
Create session
Validate tool call
Return result
Read outcome

Prepare your account and environment

Use Python 3.10 or newer and an authorized OpenAI project with Agents API and gpt-6-astra access. Set OPENAI_API_KEY in your shell using your secret-management workflow. Do not paste credentials into the source file. The model and API requests are billable; the sample order is fictional and read-only.

Install and run

Download order_agent.py into a new project folder. The file includes the tool definition, validation, streaming loop, result submission, and command-line entry point. No database or sandbox is required for this fixture.

Example
python -m venv .venv
# Activate .venv using your shell's activation command.
python -m pip install --upgrade openai
# Set OPENAI_API_KEY in the environment before this command.
python order_agent.py

Read the request and response contract

lookup_order accepts exactly one order_id. The application provides the user identity separately, so the model cannot claim another user's identity in its arguments. Successful tool output is serialized JSON; a validation or ownership failure is returned as success: false with an error. The pending action supplies the turn and call identifiers.

Read the request and response contract
StepExpected data
Tool arguments{"order_id":"ORDER-100"}
Application identitydemo-user (fixture owned by server code)
Tool success{"order_id":"ORDER-100","status":"shipped"}
Final outputSession ID, assembled text, and tool_results
Interrupted runNon-zero exit; keep session ID and inspect state

Test before using business data

Change the fixture identity to another value and confirm the lookup is denied. Test an unknown tool name, extra arguments, a failed root turn, and a stream that ends early. A subagent completion and an idle event must not count as root success. The code handles final text without requiring deltas. Offline tests validate the control flow, not account availability or model behavior.

Reconnect without replaying a write

This read-only example keeps call results in memory for one run. A production worker should persist the session mapping and any side-effect results. Retrieve the existing session and pending actions after a disconnect. Query saved items and turns before deciding whether new input is needed. A generic catch-and-create-new-session loop can duplicate work.

Read the official reference

Check the source for current API fields, account requirements, and service limits.

OpenAI: functions Streaming events and items

38 matching topics

What is the OpenAI Agents API?FoundationsAgents API vs Agents SDK vs Responses APIComparisonsAgents API quickstartGetting startedSessions, turns & durable stateCore conceptsHosted vs self-hosted sandboxesInfrastructureConnect MCP servers to Agents APITools & integrationsFunction calling & application toolsTools & integrationsMulti-agent orchestrationCore conceptsStreaming, webhooks & event handlingIntegration guidesFiles, outputs & published artifactsCore conceptsVaults & MCP authenticationTools & integrationsAgent security & credential boundariesProductionTracing, usage & debuggingProductionAgents API pricing & cost planningProductionOpenAI Agents API with PythonGetting startedAgents API with TypeScript & Next.jsIntegration guidesWhat is the OpenAI Agents SDK?FoundationsResponses API in the agent stackFoundationsAgent Skills & SKILL.mdTools & integrationsProgrammatic Tool CallingTools & integrationsRAG, file search & vector storesTools & integrationsWeb search & source citationsTools & integrationsChatKit & Agent BuilderIntegration guidesAgent configuration & reusable definitionsCore conceptsPlugins: connect skills and MCP toolsTools & integrationsSandbox lifecycle & executor connectionsInfrastructureWebhook verification, queues & deduplicationIntegration guidesAgent retries, timeouts & failure recoveryProductionAgent evaluations & regression testingProductionWhich parts of the agent stack do you need?FoundationsAgents API contract quick referenceIntegration guidesOrder agent reference: approval, recovery & evaluationIntegration guidesBuild a Next.js order agent: server, tools & streamingIntegration guidesPython Agents API example with a real tool loopGetting startedHuman approval & prompt injection defensesProductionAgents API troubleshooting: symptoms, checks & recoveryProductionAgent tool support & runtime ownership matrixComparisonsAgent resources, relationships & task stateCore concepts
K to open Esc to close