DEV Community

Maestro Morty
Maestro Morty

Posted on

OpenAI Agents API Guide: How to Use It, Best Prompts & Use Cases (2026)

TL;DR: The OpenAI Agents API is a managed service that gives you the same agent harness running Codex and ChatGPT for Work — durable sessions, automatic context compaction, parallel subagents, and hosted sandboxes — in a single API call. This OpenAI Agents API guide covers what it does, how to use it, the best prompts, and how to make money with it.


What Is the OpenAI Agents API? (And Why Everyone's Talking About It)

On September 10, 2026, OpenAI shipped the Agents API in public beta. This OpenAI Agents API guide exists because the launch changes a specific, expensive thing about building agents: you no longer write the loop.

Here's the problem it kills. If you wanted an agent that ran for hours instead of seconds, you built the plumbing yourself. Session state. Context compaction. Retry logic when a tool call died halfway. Sandbox provisioning. Subagent orchestration. Crash recovery. Most teams spent the majority of their engineering time there, and the remainder on what actually made their product different.

The Agents API deletes the scaffolding. You describe an agent — model, instructions, tools, MCP servers — pick an environment, send an input, and OpenAI runs the loop. It is the same infrastructure OpenAI scaled to run Codex for millions of people, exposed through client.beta.agents.sessions.create.


Who Is the OpenAI Agents API For?

This is a developer product, but the audience is wider than "backend engineers at AI startups." Anyone who has hand-rolled an agent loop is the target:

  • Backend and platform engineers maintaining custom agent harnesses they'd rather delete
  • Technical founders needing production agents without an infrastructure hire
  • AI consultants and agencies billing for agent builds, who just got a better margin
  • DevOps and SRE teams wanting agents that investigate incidents, not just page humans
  • Data engineers running reconciliation, extraction, and migration jobs that outlast a chat turn
  • Solo builders shipping vertical AI products where infrastructure was the blocker

If your agent finishes in under thirty seconds and uses two tools, you probably don't need this. The value shows up in long-running agentic workflows, multi-step task execution, and anything where an autonomous AI agent needs to survive a crash and pick back up.


Key Features of the OpenAI Agents API

Durable, Long-Running Sessions

A session is a durable agent instance, not a request. It works on tasks, responds to new input, and keeps running across hours or days — because models now work for hours, and a stateless request model can't express that. Nash.ai runs thousands of long-running agents on it across global logistics networks.

Automatic Context Compaction

As a session approaches its context limit, the Agents API automatically compacts earlier context while preserving what the agent needs to continue. You build workflows that span multiple context windows without writing your own compaction logic — historically one of the ugliest pieces of any custom harness.

Parallel Subagents

Multi-agent support splits complex tasks into independent pieces and delegates them to subagents running in parallel. Each subagent keeps its own context while the main agent coordinates and merges results. Enable with multi_agent: { enabled: true, max_concurrent_subagents: 3 }. Ciridae reported a 4x latency reduction out of the box.

Tool Search and Programmatic Tool Calling

Tool search loads tool definitions only as needed, cutting token usage while preserving cache. Programmatic tool calling lets agents run calls in parallel, chain operations, and filter results in code — so an agent churns through large volumes of data and brings only the relevant slice back into context. MCP, custom functions, and built-in tools like web search are all supported.

Flexible Environments

An environment is the sandbox where your agent runs code, edits files, and reads output. Three options: OpenAI hosted, self-hosted, or a partner sandbox from Blaxel, Cloudflare, Daytona, DigitalOcean, E2B, Modal, Oracle, Runloop, or Vercel. Self-hosted runs codex exec-server inside your network over an outbound WebSocket — no inbound firewall holes.


How to Get Started with the OpenAI Agents API in 5 Minutes

Here's how to use the OpenAI Agents API from zero. This is the OpenAI Agents API tutorial section — five concrete steps, real UI and code actions.

  1. Update your SDK. The Agents API lives under the beta namespace: client.beta.agents.sessions.create. Run npm install openai@latest (or pip install --upgrade openai). On an older version the namespace simply won't exist, which produces a confusing undefined error rather than a clear one.

  2. Pick your model. Use gpt-6-astra. It's the reference model in OpenAI's own examples and the one the harness is tuned against. Benchmark cheaper models later, once your workflow is stable — not while you're still debugging structure.

  3. Choose an environment. Start with environment: { type: "openai_hosted" }. Zero infrastructure work, same sandboxing that powers Codex and ChatGPT. You can configure it with your files, packages, skills, and plugins. Move to a partner sandbox only when you need specific GPU, memory, or VPC characteristics.

  4. Attach your tools. The agent object takes a tools array. For MCP, pass type: "mcp", a server_label, and an http transport with your server_url. Custom functions and built-in tools follow the same shape. Beginner tip: start with zero tools. Get one session running first, then add tools one at a time.

  5. Create the session and stream events. Pass agent, environment, and input. Events stream the agent's work as it happens; items are the inputs you send and outputs it produces. Have the agent write results to a known path — /workspace/outputs is OpenAI's convention — then collect them when the session completes.

Your first run should be boring: one agent, gpt-6-astra, hosted environment, no MCP servers, one instruction ending in "save your findings to /workspace/outputs/report.md". If that works, everything else is addition.


7 Best Use Cases for the OpenAI Agents API

1. Incident Investigation

Point an agent at your observability MCP server and tell it to investigate an elevated 5xx rate. Delegate deployment history, error clustering, and dependency latency to three subagents in parallel. The main agent correlates and writes one mitigation recommendation. The subagent split matters here because the three analyses genuinely don't need each other's context.

2. Repo-Wide Code Migration

A framework upgrade across 400 files isn't a chat turn, it's a two-day job. Durable sessions plus automatic compaction mean an agent works the whole repo without you writing a chunking strategy. Have it log progress after every file so an interrupted run resumes instead of restarting.

3. Bursty Batch Workloads

Fan out hundreds of independent agents asynchronously, let them finish on their own schedule, collect results later. Dwelly's CTO specifically called out that this removes idle infrastructure between peaks — you're not paying for capacity that sits waiting for the next spike.

4. Document and Case Review

Insurance claims, contract review, compliance checks. One agent per case, running in a sandbox with documents mounted, writing a structured verdict file. SafetyKit migrated its case review workflow and reported a 60% reduction in cost per case with performance held constant.

5. Data Reconciliation

Two systems disagree about the same records. An agent with read access to both, a shell tool, and permission to write a diff report handles the boring 90% and escalates the ambiguous remainder — three files out, plus a summary of which mismatches look systematic.

6. Research Briefs with Verification

Main agent decomposes the question, subagents each take a branch with web search, main agent synthesizes with citations. Then add a hostile fact-checker subagent over the draft. Separate contexts are the point: the checker doesn't inherit the writer's assumptions.

7. Internal Tool Replacement

McKinsey found nearly a third of surveyed organizations decided against buying software because they could build it with coding agents. A durable-session agent owning one internal workflow end-to-end is now a real alternative to a niche SaaS license.


5 Copy-Paste Prompts for the OpenAI Agents API

These are the best OpenAI Agents API prompts to start with. Each assumes a sandbox environment with write access to /workspace/outputs. Replace bracketed values.

Prompt 1: Incident Triage Agent

You are an on-call SRE agent. Investigate the elevated 5xx error rate on
[SERVICE_NAME] over the last [TIME_WINDOW]. Use the observability MCP server to
pull error rates, recent deploys, and dependency health. Delegate three parallel
subagents: one for deployment history, one for error clustering by stack trace,
one for upstream dependency latency. Correlate their findings. Write
/workspace/outputs/incident.md containing: timeline, most likely root cause with
confidence level, evidence for and against, and a specific recommended
mitigation. Do not take any remediating action yourself.
Enter fullscreen mode Exit fullscreen mode

Prompt 2: Repo-Wide Migration Agent

You are migrating this repository from [OLD_FRAMEWORK] to [NEW_FRAMEWORK]. Work
file by file. For each file: read it, apply the migration, run the test suite for
that module, record the result. If tests fail twice on the same file, skip it and
log why. Maintain a running progress file at /workspace/outputs/migration-log.md
after every file so work is recoverable. When finished, summarize files migrated,
files skipped, and the exact reason for each skip.
Enter fullscreen mode Exit fullscreen mode

Prompt 3: Parallel Research Brief Agent

Research this question: [QUESTION]. Decompose it into three to five independent
sub-questions. Delegate each to a subagent instructed to use web search and
return findings with source URLs and publication dates. As the main agent,
synthesize into /workspace/outputs/brief.md with: a two-sentence answer up front,
evidence per sub-question, explicit disagreements between sources, and a
confidence rating. Flag anything sourced before [DATE_CUTOFF].
Enter fullscreen mode Exit fullscreen mode

Prompt 4: Data Reconciliation Agent

Compare records between [SYSTEM_A] and [SYSTEM_B] for [DATE_RANGE]. Match on
[KEY_FIELD]. Produce three files in /workspace/outputs: matched.csv,
mismatched.csv with a column explaining each mismatch, and unmatched.csv for
records present in only one system. Then write reconciliation-summary.md with
counts, the top five mismatch patterns, and which look systematic rather than
one-off. Do not modify either source system.
Enter fullscreen mode Exit fullscreen mode

Prompt 5: Draft and Verify Content Agent

Write a [CONTENT_TYPE] about [TOPIC] for an audience of [AUDIENCE]. Target
[WORD_COUNT] words. When your draft is complete, delegate a subagent with this
instruction: "You are a hostile fact-checker. Verify every factual claim, number,
date, and name in the attached draft using web search. Return a list of claims
that are wrong, unsupported, or outdated, with sources." Revise using the
subagent's findings. Save the final version and the fact-check log separately in
/workspace/outputs.
Enter fullscreen mode Exit fullscreen mode

OpenAI Agents API vs. LangGraph: Which Should You Use?

LangGraph gives you explicit control over the graph — nodes, edges, state transitions — running anywhere against any model. For workflows with complex branching you want to reason about visually, it remains the better tool, and it's model-agnostic if multi-provider support is a hard requirement.

The Agents API trades that control for managed infrastructure. You don't define the loop; OpenAI runs it, improves the harness alongside each model launch, and gives you versioned access to those improvements. The honest tradeoff is vendor lock-in — your agents run on OpenAI models inside an OpenAI-operated harness. Choose LangGraph when the orchestration logic is your product or you need provider flexibility. Choose the Agents API when the orchestration is undifferentiated work you'd rather stop maintaining. Notably, the underlying Codex harness is open source, so you can inspect what's actually coordinating your model calls.


How to Make Money with the OpenAI Agents API

1. Agent Migration Sprints

Every team that hand-rolled an agent loop in 2025 and 2026 now maintains a liability. Sell a fixed-scope two-week engagement: audit the harness, port sessions and tool calls to the Agents API, hand back a before-and-after benchmark. SafetyKit reported 60% lower cost per case; Hypha, 86% fewer failed responses. Price against a share of annual inference savings, not your hours.

2. Vertical Agent Products

With the harness free and managed, the defensible part of an agent product is the tools, domain knowledge, and interface — not infrastructure. Pick a narrow vertical with document-heavy or reconciliation-heavy workflows, wire three or four industry-specific MCP tools, sell it as a product. Build time drops from quarters to days, which changes which verticals are large enough to be worth entering at all.

3. Templates, Evals, and Cost Tuning

Almost nobody has a working mental model of sessions, environments, compaction, and subagents yet. Ship production-ready session templates cheap to build a list. The higher-ticket offer follows: eval harnesses for subagent delegation quality, and sandbox cost tuning. Every team adopting this hits a surprise compute bill within sixty days and starts looking for someone who already solved it.


Frequently Asked Questions About the OpenAI Agents API

Is the OpenAI Agents API free?

There are no additional fees for the Agents API itself. You pay for the tokens and tools your agents consume, just as you do with any other OpenAI API. If you use an OpenAI hosted sandbox you pay for that compute separately; if you self-host or use a partner sandbox, you pay that provider. The orchestration layer is the free part.

Is the OpenAI Agents API safe to use?

Agents run in isolated sandboxes rather than directly on your infrastructure, and self-hosted environments connect outbound over WebSocket with a restricted key, so you never open inbound ports. That said, the 2026 conversation about agent safety is loud for good reason — scope credentials narrowly, log actions to storage the agent can't modify, and gate irreversible actions behind human approval.

What is the OpenAI Agents API best for?

Long-running, multi-step work that would otherwise require your own orchestration: incident investigation, repo-wide migrations, document review at volume, data reconciliation, and research that benefits from parallel subagents. If your task completes in one model call, you don't need it.

How does the OpenAI Agents API compare to LangGraph?

LangGraph gives you explicit, model-agnostic control over the execution graph and runs anywhere. The Agents API gives you a managed, continuously improved harness at the cost of running on OpenAI models. Pick LangGraph when orchestration logic is your differentiator or you need multiple providers. Pick the Agents API when orchestration is undifferentiated maintenance burden.

Can beginners use the OpenAI Agents API?

Yes, and it's easier than the alternatives because the hardest parts — session management, compaction, retries, sandboxing — are handled for you. You need to be comfortable with an SDK and API docs, but not distributed systems. Start with a hosted environment, no tools, one instruction, then add complexity one piece at a time.


Final Verdict

The OpenAI Agents API isn't a new capability so much as a new division of labor. The model could already do this work. What changed is that the unglamorous infrastructure around it — sessions that survive crashes, context that compacts itself, subagents that fan out and report back — is now someone else's problem, and free.

Use it if you've written an agent loop and resented it, or if you're a solo builder blocked on infrastructure rather than ideas. Skip it if orchestration logic is genuinely your product, or if provider independence is non-negotiable. The lock-in is real, though the open-source Codex harness underneath softens it more than most managed services do.

The window here is timing, not technology. Very few people have a working mental model of how sessions, environments, compaction, and subagents fit together. That gap closes fast.

Want the complete OpenAI Agents API prompt pack + monetization playbook? I put together a full guide with 10 copy-paste prompts, all 10 use cases mapped out, and a step-by-step monetization playbook. Grab it on Gumroad for $19 →


Published: 2026-09-14 | Updated: 2026-09-14

Top comments (0)