OpenAI Agents API Tutorial: Build a Production Agent
OpenAI Agents API tutorial: create scoped keys, run a first task, add tool calling, and give your agent a live TrendsAGI trend tool.

The OpenAI Agents API is a public beta, launched September 10, 2026, that moves the Codex harness into an API so developers can run cloud agents that work for hours, execute code, process files, manage context automatically, use tools in parallel and delegate to subagents (OpenAI Developers). This tutorial takes you from a project key with the right scopes to a first task, then adds tool calling and a live trend-intelligence tool from TrendsAGI, and closes with the production decisions the quickstart pages do not cover. Everything below uses only documented capabilities; where details are not published, you will be told to confirm them in OpenAI's own docs.
What makes this worth learning now: the Agents API is the same infrastructure behind Codex and ChatGPT, so prior familiarity transfers directly, and within weeks of launch Promptfoo, CoreWeave and Apidog published integration and quickstart guides, which is a strong signal of practitioner adoption. What is not verified, and what you must confirm yourself: pricing for sessions, tokens or sandboxes; rate limits and concurrency caps; session lifetimes and whether long runs can be resumed; the exact syntax for tools, parallel tool use and subagent delegation; and whether the managed API and the open-source Agents SDK interoperate.
OpenAI Agents API vs. the open-source Agents SDK
OpenAI Developers describes the model simply: you start with a model and instructions, then add the tools and controls the task needs, and save the agent configuration so it can be reused across sessions. With the managed API, OpenAI runs the agent, holds the conversation and provides the sandbox where it works. That is the core trade: you give up local control of orchestration and execution in exchange for managed context handling, parallel tools and subagent delegation without building the harness.
The open-source Agents SDK is the opposite posture: you run and control the loop. This tutorial does not claim how the two interoperate, because that is not verified. As a rule of thumb, prototype on the managed API when the value is in the task rather than the orchestration, and keep the open-source route in mind when you need to own execution end to end. The managed API's orchestration is worth giving up local control when your agent needs long-running execution, automatic context management and hands-off sandboxing; it is not worth it if you need to run inside your own network boundary with no external execution environment.
Step 1: Create the key and set the beta header
Per OpenAI Developers, an application API key needs api.agents.read and api.agents.write for session operations, plus api.responses.write for model inference. Requests require the OpenAI-Beta: agents=v1 header; the OpenAI SDKs add it automatically. Create the key in your account, store it outside the agent's sandbox, and read it from the environment in every example below.
export OPENAI_API_KEY="sk-..."
export TRENDSAGI_API_KEY="your-trendsagi-key"
That separation matters. OpenAI's docs explicitly warn to keep the API key outside the agent's sandbox, and the self-hosted sandbox option uses a separate environment key that connects outbound. Treat the model-inference credential and the sandbox-environment credential as different secrets with different blast radii.
Step 2: Understand agents, sessions and sandboxes
Three objects explain the whole request flow. An agent is the saved configuration: model, instructions, tools and controls. A session is one conversation with that agent; session operations are what your api.agents.read/write scopes authorize. A sandbox is where code runs and files live, and OpenAI manages it in the hosted setup. In one flow: you create a session against a saved agent, send a task, the agent works inside its sandbox and returns a final answer, and the session carries the conversation for subsequent turns.
Session lifecycle is the detail most tutorials skip. Promptfoo's openai:agents-api provider shows a clean, reproducible pattern: create a fresh session per call, wait for the root agent's turn to finish, collect the final answer, then delete the session. If you are wiring the Agents API into an evaluation harness, copy that four-step discipline rather than reusing a session and hoping state does not leak between test cases.
Step 3: Run your first task
The verified quickstart from OpenAI Developers centers on code execution and file output. This article will not invent endpoint paths, request bodies or SDK method signatures for the Agents API, so use the exact snippets from the OpenAI quickstart and add the header if you call REST directly rather than through an SDK:
curl https://api.openai.com/v1/... \
-H "Authorization: Bearer $OPENAI_API_KEY" \
-H "OpenAI-Beta: agents=v1" \
-H "Content-Type: application/json" \
-d @task.json
Replace the path and body with the ones in the quickstart for your chosen language; the SDK versions add the beta header for you. The design rule to carry forward: keep the agent configuration in one place, keep the task payload small, and record the session ID for every run so failed or long-running tasks can be investigated.
Step 4: Give the agent a real-time trend tool with TrendsAGI
This is the part the quickstart does not give you: an agent is only as useful as its tools. TrendsAGI is a real-time trend intelligence platform that detects topics gaining attention, measures velocity as posts per hour from stored snapshots, and explains each trend with AI insights (summary, key themes, sentiment, audience, marketing angles). One honesty note before you build: velocity is a measured snapshot rate, not a forecast or a unique-user count, and recommendation confidence measures evidence completeness, not probability of success.
Install the Python SDK and pull live trends to decide what your agent should investigate:
pip install trendsagi
import os
from trendsagi import TrendsAGIClient
client = TrendsAGIClient(api_key=os.environ["TRENDSAGI_API_KEY"])
trends = client.get_trends(category="Technology", sort_by="velocity", limit=5)
for t in trends["trends"]:
print(t["id"], t["name"], t["volume"])
If you are driving the REST API instead, the same query is GET https://api.trendsagi.com/api/trends?category=Technology&sort_by=velocity&limit=5 with X-API-Key: <key> or Authorization: Bearer <key>. Then fetch the evidence your agent will reason over:
trend_id = trends["trends"][0]["id"]
insights = client.get_ai_insights(trend_id)
analytics = client.get_trend_analytics(trend_id, period="7d")
related = client.search_insights(key_theme_contains="AI chips")
high_priority = client.get_recommendations(limit=10, priority="high")
Because the exact tool-definition syntax for the managed Agents API is not verified here, do not paste invented schemas. Two honest options: follow the tool-definition snippet in the OpenAI quickstart, or, if you are using the SDK's agent tools locally, use the documented tool wrappers. TrendsAGI ships agent tools that return OpenAI Chat Completions tool definitions, Anthropic tool use, LangChain and WebMCP descriptors:
from trendsagi import TrendsAGITools
tools = TrendsAGITools(client) # read-only by default
openai_tools = tools.openai() # tool definitions to pass to your agent
result = tools.call("list_trends", {"category": "Technology"})
trend_id = result["result"]["trends"][0]["id"]
Tool calls return {"result": <data>} on success and {"error": "...", "detail": "..."} on failure instead of raising, which makes them easy to surface to an agent as tool output. Read-only tool names include list_trends, get_trend_ai_insights, get_trend_analytics, search_trend_insights, list_recommendations and list_crisis_events; add writes only deliberately with TrendsAGITools(client, allow_writes=True).
Step 5: Tool calling, parallel use and subagents in practice
The verified capability statement is that managed agents use tools in parallel and delegate to subagents. The verified syntax for defining tools, parallel tool use and subagent delegation in the managed API is not published in the sources used here, so confirm it in OpenAI Developers before shipping. What you can plan for regardless of syntax:
- Make tools independent and idempotent so parallel invocation is safe; a trend lookup should not mutate state.
- Return compact, structured tool output (IDs, names, volumes, timestamps) so the agent can chain calls without re-fetching.
- Split delegation by domain: one subagent for trend discovery, one for evidence gathering, one for recommendation review.
- Log every tool call and its payload so a failed call mid-run is reproducible.
For teams evaluating the build itself, Promptfoo's provider makes the managed API testable in CI, and CoreWeave documents using its Sandboxes as the execution environment with a Codex executor inside the sandbox connecting to OpenAI. That gives you a concrete comparison point for the sandbox decision below.
Production concerns: sandboxes, credentials, context and lifetimes
Sandbox choice. OpenAI-hosted sandboxes are the default and require no infrastructure. Self-hosting is documented by Apidog: run codex exec-server on a laptop, container or remote sandbox that connects outbound with a separate environment key. Launch sandbox partners listed by Apidog include Blaxel, Cloudflare, Daytona, DigitalOcean, E2B, Modal, Oracle, Runloop and Vercel, with AWS Lambda MicroVMs in the self-hosted guide. This article will not rank them on cost, latency, data residency or limits, because no verified comparison exists; request those figures directly and benchmark with one representative task before committing.
Credential boundaries. Keep the model-inference key outside the sandbox. Use a distinct environment key for outbound connections. Never place a TrendsAGI API key or another third-party credential inside code the agent can read; proxy sensitive calls through your own service so the agent sees data, not secrets.
Context and lifetimes. OpenAI manages conversation context automatically, which is the main reason to pick the managed API. Session and sandbox persistence limits and resume behavior are unconfirmed, so design assuming a run may need restarting: checkpoint task progress outside the sandbox and make each step resumable from stored state.
Failure modes. A tool call that fails mid-run should return a structured error the agent can react to, which is exactly how TrendsAGI tools behave. A session that dies should not lose your output; persist the final answer and intermediate artifacts as they arrive.
Why trend data belongs in your agent stack
The Agents API launch is itself a market signal. Tracking which sandbox partners, evaluation tools and providers adopt it week by week tells you where the ecosystem is heading before your team commits. You can watch that with a TrendsAGI watchlist:
client.create_topic_interest(
keyword="OpenAI Agents API",
alert_condition_type="volume_threshold",
volume_threshold_value=500,
)
The same pattern works inside the agent: expose trend tools so it can check whether a topic is accelerating before recommending an action, and use the recommendation and crisis-event endpoints as evidence-backed inputs rather than guesses. A runnable build plus live market signal gives you something a static tutorial cannot.
Frequently asked questions
What exactly is the OpenAI Agents API, and how does it differ from the open-source Agents SDK?
The Agents API is OpenAI's managed public beta, launched September 10, 2026, that runs cloud agents which execute code, process files, manage context, use tools in parallel and delegate to subagents. OpenAI manages the agent, conversation and sandbox; the open-source Agents SDK leaves that orchestration and execution under your control. Whether, and how, the two can be combined is not verified here, so confirm it in OpenAI's docs.
Which API key permissions and headers do I need before my first request?
According to OpenAI Developers, the key needs api.agents.read and api.agents.write for session operations plus api.responses.write for model inference. Requests require the OpenAI-Beta: agents=v1 header, which the official SDKs add automatically.
What are agents, sessions and sandboxes, and how do they fit together in one request flow?
An agent is the saved configuration of model, instructions, tools and controls; a session is one conversation with that agent; a sandbox is where the agent executes code and handles files. You create a session for a saved agent, send a task, and the agent works in its sandbox and returns a final answer, with the session carrying the conversation forward.
How do I run a first task end to end in Python and via the SDKs?
Start with a model and instructions, add the tools and controls your task needs, and save the agent configuration for reuse, as described in the OpenAI developers quickstart. Then create a session with a key holding the scopes above and send your task through the SDK, which attaches the beta header; because the exact request shapes are not reproduced here, follow the quickstart snippet for your language.
How does tool calling, parallel tool use and subagent delegation work in practice?
Managed agents can use tools in parallel and delegate to subagents, and a practical pattern is to give each subagent a narrow domain and make every tool idempotent so parallel calls are safe. The exact tool-definition and delegation syntax is not verified in these sources, so confirm it in OpenAI's documentation before building on it.
What should I plan for in production: sandbox choice, credential boundaries, context management and resource lifetimes?
Choose hosted sandboxes for simplicity or self-hosted and partner sandboxes when you need your own environment, and benchmark before committing since no verified cost or latency comparison exists. Keep the API key outside the sandbox, use a separate environment key for outbound connections, and checkpoint progress externally because session lifetime and resume behavior are unconfirmed.
How we researched this
Prepared by TrendsAGI Research. Facts checked on 25 October 2026 against the sources listed below.
We read the official OpenAI Agents API documentation listed below. The TrendsAGI steps and code use its documented REST API and Python SDK; confirm the OpenAI Agents API side against its current documentation, since third-party products change.
| Claim | Applies to | Source |
|---|---|---|
| Building an agent starts with a model and instructions, then adds the tools and controls the task needs, and a saved agent configuration can be reused across sessions. | All plans | developers.openai.com |
| OpenAI manages the agent, its conversation and the sandbox where it works. | Public beta | developers.openai.com |
| An application API key needs api.agents.read and api.agents.write for session operations plus api.responses.write for model inference. | Public beta | developers.openai.com |
| Requests require the OpenAI-Beta: agents=v1 header, and the OpenAI SDKs add it automatically. | Public beta | developers.openai.com |
| The API key should be kept outside the agent's sandbox. | Public beta | developers.openai.com |
| A sandbox can be self-hosted by running codex exec-server on a laptop, container or remote sandbox that connects outbound with a separate environment key. | Self-hosted sandbox option | apidog.com |
| Launch sandbox partners include Blaxel, Cloudflare, Daytona, DigitalOcean, E2B, Modal, Oracle, Runloop and Vercel, and the self-hosted guide adds AWS Lambda MicroVMs. | Public beta | apidog.com |
| The Promptfoo provider for the Agents API creates a fresh session per call, waits for the root agent's turn to finish, collects the final answer and deletes the session. | Promptfoo openai:agents-api provider | promptfoo.dev |
| CoreWeave Sandboxes can serve as the execution environment for an OpenAI-managed agent, with a Codex executor inside the sandbox connecting to OpenAI and running the agent's commands. | CoreWeave Sandboxes | docs.coreweave.com |
Sources
- Agents API quickstart | OpenAI API (OpenAI Developers) — developers.openai.com
- How to use the OpenAI Agents API ? (Apidog) — apidog.com
- OpenAI Agents API | Promptfoo — promptfoo.dev
- Run OpenAI Agents API on Sandboxes - CoreWeave Docs — docs.coreweave.com