OpenAI Agents API Tutorial: Build a Sandboxed Agent
Hands-on OpenAI Agents API tutorial: scope API keys, define an agent, run a sandboxed session, pick hosted vs self-hosted, and feed in live trend data.

This OpenAI Agents API tutorial walks through one complete build: scoping an API key, defining an agent, creating a session, letting the agent write and run code in a managed sandbox, tearing it down, and then feeding it real-time trend data. Treat it as a build guide, not a specification sheet — the OpenAI documentation is the authority on syntax, and this article flags exactly where you should go confirm details before shipping.
What is verified: OpenAI released the Agents API as a public beta on September 10, 2026, according to OpenAI Developers and Promptfoo. It runs agents on the same managed Codex harness that powers Codex and ChatGPT, including managed sandboxes and conversation state, and it targets developers and enterprises that want long-running cloud agents executing code and processing files without building orchestration and sandbox layers themselves. According to developers.openai.com, the quickstart builds a coding assistant that writes tree.py, runs it, and prints a directory tree, with OpenAI managing the agent, conversation and sandbox.
Prerequisites: API key scopes before any code
According to the OpenAI Developers quickstart, the key must be granted api.agents.read and api.agents.write for session operations, plus api.responses.write for model inference. That split is deliberate and worth designing around. A key that only reads is fine for monitoring; session creation and message sending need write; every model turn needs Responses write.
- Read-only monitoring:
api.agents.readalone covers inspection. - Running agents: all three scopes, since sessions and inference both fire.
- Multiple services: issue separate keys per service so a leaked dashboard key cannot start sessions.
The permission model is one of the details official docs treat briefly and production teams usually learn the hard way. Decide scope at key creation, because retrofitting a permissive key for a convenience script is how agents get write access they were never supposed to have.
Define the agent once, reuse the configuration
Per developers.openai.com, an agent configuration combines model and instructions with tools and controls, and you can either supply it when creating a session or save it for reuse. Saving a configuration is the production default: one reviewed definition, many sessions.
The quickstart's example uses the model name gpt-6-astra and the sandbox type openai_hosted. The Python and JavaScript examples cited in research are your starting point; the exact request shape should be checked against the current quickstart, because beta endpoints change. Treat any snippet, including the structure below, as a shape to confirm rather than a contract.
# Shape of the configuration described by the OpenAI quickstart.
# Confirm field names and endpoint paths against developers.openai.com
# before running this.
{
"model": "gpt-6-astra",
"instructions": "Write and run Python to produce the requested artifact.",
"tools": [ /* see your provider's tool schema */ ],
"sandbox": { "type": "openai_hosted" }
}One naming trap deserves its own callout: the hosted Agents API is not the openai-agents or openai-agents-mcp packages. Promptfoo states that applications built with the JavaScript @openai/agents package should use the Agents SDK provider (openai:agents:*) instead of the Agents API provider. If you are reading a tutorial about the SDK, you are reading a different product. Decide which one you are adopting before copying code.
Session lifecycle: create, run, collect, delete
Promptfoo describes the provider's behavior precisely: each provider call creates a fresh session, waits for the root agent's turn, collects the final answer, then deletes the session. That is the lifecycle to copy in your own integration, because it prevents orphaned sessions and makes each run reproducible.
# Lifecycle to implement against the Agents API, per Promptfoo's provider:
# 1. create session with a saved agent configuration
# 2. submit the user task
# 3. wait for the root agent's turn to finish
# 4. collect the final answer
# 5. delete the session
#
# Run this inside a job with explicit timeouts; do not hold a session open
# while waiting for a human review.Where this gets operationally difficult is long-running work. The sandbox is therefore not free infrastructure you can leave parked between async steps. The mitigation is straightforward: keep the lifecycle short and synchronous at the job level, persist what you need outside the session, and re-create rather than resume when in doubt. If you need long-lived continuity, address it deliberately and verify the current keep-alive behavior in OpenAI's docs.
Hosted or self-hosted sandbox: a decision table
This is the trade-off the ranking pages usually skip. The quickstart's openai_hosted sandbox is the path of least work; self-hosted options exist for teams with constraints. Research mentions a self_hosted sandbox type and a self-hosted codex exec-server, plus a partner ecosystem that includes Blaxel, Cloudflare, Daytona, DigitalOcean, E2B, Modal, Oracle, Runloop and Vercel, and self-hosted options such as AWS Lambda MicroVMs. Commercial availability of each partner is not something this article can confirm.
| Factor | OpenAI-hosted sandbox | Self-hosted sandbox |
|---|---|---|
| Setup effort | Lowest — managed by OpenAI | You run the exec-server and networking |
| Code and data location | Inside OpenAI's managed environment | Inside your own boundary |
| Network egress control | Constrained by the hosted environment | Yours to define |
| Lock-in | Configuration is OpenAI-specific | Portable but more work to operate |
| Scaling | Bounded by the hosted service | Bounded by your infrastructure |
| Cost | Confirm in OpenAI's current terms | Your compute bill, plus operations time |
Pick hosted when you want the Codex harness to handle orchestration and isolation and your data can live there. Pick self-hosted when data residency, custom dependencies or egress rules are hard requirements — and budget for the operational burden, because that is the cost you are trading for control.
Verify behavior in CI, not by eyeballing runs
Third-party tooling and coverage show fast practitioner uptake of the new API. That matters for one reason: an agent that writes and executes code needs an eval step, not a demo. Because each provider call is a fresh session that ends with a deleted session, the API fits CI cleanly — every test run starts from a known state and leaves nothing behind.
Write assertions on the observable artifact (the file exists, the tree output is expected) rather than on free-form prose. Then run the same task repeatedly to catch flakiness before users do. This is also where you would insert a trend-data dependency, which brings us to the TrendsAGI part of the build.
Feeding real-time trend data into the agent
TrendsAGI is a real-time trend intelligence platform: it detects topics gaining attention on social platforms, measures velocity as posts per hour from stored snapshots, and pairs each topic with AI insights covering summary, key themes, sentiment, audience and marketing angles. The REST API base is https://api.trendsagi.com; authenticate with X-API-Key: <key> or Authorization: Bearer <key>, and create keys in the account profile.
For a code-executing agent, the practical integration is to give the sandbox a narrow, read-only data surface. Fetch trends in your orchestrator, then pass the results in as context instead of handing the agent your API key.
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.get("trends", []):
print(t["id"], t["name"], t.get("velocity"))
# Pull the reasoning behind a single topic
trend_id = trends["trends"][0]["id"]
insights = client.get_ai_insights(trend_id)
analytics = client.get_trend_analytics(trend_id, period="7d")Install with pip install trendsagi (version 0.12.0+). Because velocity is a measured snapshot rate, not a forecast or a unique-user count, tell the agent exactly that in its instructions. Vague instructions produce confident nonsense about trend magnitude.
Connecting the agent through MCP or the SDK tools
If your agent runtime speaks MCP, the cleanest path is the hosted server at https://api.trendsagi.com/mcp (Streamable HTTP, OAuth 2.1 sign-in or an API key as a Bearer token, read-only tools). Add it in Claude Code with claude mcp add --transport http trendsagi https://api.trendsagi.com/mcp. Each connection is its own API key and each tool call counts as one API request.
For Python agents, the SDK ships tool wrappers that map directly onto a tool-calling loop:
import os
from trendsagi import TrendsAGIClient, TrendsAGITools
client = TrendsAGIClient(api_key=os.environ["TRENDSAGI_API_KEY"])
tools = TrendsAGITools(client) # read-only by default
schemas = tools.openai() # or tools.openai_responses() for the Responses API
result = tools.call("list_trends", {"category": "Technology"})
if "error" in result:
print(result["error"], result.get("detail"))
else:
first_id = result["result"]["trends"][0]["id"]
insight = tools.call("get_trend_ai_insights", {"trend_id": first_id})Note the error contract: call returns {"result": ...} on success and {"error": ..., "detail": ...} on failure instead of raising, so your loop must branch rather than rely on exceptions. Reads stay read-only unless you construct with allow_writes=True, which adds add_to_watchlist and update_recommendation.
What to confirm before you commit
Several things this article deliberately does not assert: pricing for the Agents API, sandboxes or session usage; rate limits and quotas; data retention and privacy terms for conversations or sandbox files; model availability beyond the gpt-6-astra mention; language coverage beyond the Python and JavaScript examples; whether the API is still in public beta as of October 22, 2026; commercial availability of each listed sandbox partner; and any latency or performance benchmark. Confirm each in OpenAI's own docs and terms. Beta APIs change, and a tutorial that pretends otherwise is a liability.
Frequently asked questions
What exactly is the OpenAI Agents API and how does it differ from the Agents SDK?
The Agents API is OpenAI's hosted product, released as a public beta on September 10, 2026, that runs agents on the managed Codex harness with sandboxes and conversation state. The Agents SDK is a separate package; Promptfoo notes that JavaScript apps using @openai/agents should use the Agents SDK provider (openai:agents:*), not the Agents API provider.
Which API key permissions do I need and how do I set them up?
Per the OpenAI Developers quickstart, grant api.agents.read and api.agents.write for session operations plus api.responses.write for model inference. Create scoped keys per service so monitoring keys cannot start sessions.
How do I define an agent and reuse its configuration across sessions?
A configuration is model, instructions, tools and controls, and can be supplied at session creation or saved for reuse, according to developers.openai.com. Save it, review it once, and reference it from every session.
How do I create a session, run it, and retrieve the final output?
Follow the Promptfoo-described lifecycle: create a session, submit the task, wait for the root agent's turn, collect the final answer, then delete the session. Check the OpenAI quickstart for the current Python and JavaScript request shapes.
Should I use an OpenAI-hosted sandbox or a self-hosted one?
Hosted means less setup and OpenAI-managed isolation; self-hosted means your own data boundary and networking at the cost of running the exec-server. Choose based on residency and egress requirements.
What happens to an idle session or sandbox if I don't keep it alive?
Research treats idle sandbox deletion after roughly an hour without keep-alives as a known behavior rather than a documented guarantee. Keep job lifecycles short, persist outputs outside the session, and verify current retention in OpenAI's docs.
How we researched this
Prepared by TrendsAGI Research. Facts checked on 22 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 |
|---|---|---|
| The OpenAI Agents API quickstart builds a coding assistant that writes tree.py, runs it, and shows a directory tree, with OpenAI managing the agent, conversation and sandbox. | Agents API public beta | developers.openai.com |
| The API key must be granted api.agents.read and api.agents.write for session operations plus api.responses.write for model inference. | Agents API public beta | developers.openai.com |
| Session calls in the quickstart use the model name "gpt-6-astra" and the sandbox type "openai_hosted". | quickstart example | developers.openai.com |
| An agent configuration is defined by model and instructions plus tools and controls, and can be supplied when creating a session or saved for reuse. | Agents API public beta | developers.openai.com |
| The OpenAI Agents API runs agents using OpenAI's managed Codex harness, and each provider call creates a fresh session, waits for the root agent's turn, collects the final answer, then deletes the session. | openai:agents-api provider | promptfoo.dev |
| Applications built with the JavaScript @openai/agents package should use the Agents SDK provider (openai:agents:*) instead of the Agents API provider. | openai:agents:* provider | promptfoo.dev |
Sources
- Agents API quickstart | OpenAI API (OpenAI Developers) — developers.openai.com
- OpenAI Agents API | Promptfoo — promptfoo.dev