Back to blog posts

10 min

A developer's guide to the OpenAI Agents SDK

Learn how to build with the OpenAI Agents SDK in Python, from tools, handoffs, guardrails, and sessions to tracing, costs, and sandboxed code execution.

Nicolas LecomteNico is a founder of Blaxel, who usually writes about AI, agentics, and the future of AI runtimes.

OpenAI's Agents SDK is an open-source runtime for AI agents in Python and TypeScript. Every example targets openai-agents 0.24.0, which PyPI lists as released on October 15, 2026 (UTC). The SDK is still pre-1.0, and minor versions can carry breaking changes.

A working agent combines a function tool, a handoff, an input guardrail, a session, and traces. Things change once that agent writes code and runs it. Agent-generated code belongs inside an isolated sandbox.

Key takeaways

  • Each handoff passes the full conversation history by default, so budget runs with several agents separately from single agent tests.
  • Minor OpenAI Agents SDK releases can carry breaking changes before 1.0, so pin exact versions and test every upgrade.
  • Run code the agent generates in a microVM with its own kernel, away from the process holding your credentials.
  • Baseten Sandboxes are a first-class sandbox provider, and SandboxRunConfig attaches them at run time so agent definitions stay portable.

What is the OpenAI Agents SDK?

An AI agent is a model that decides which tools to call, and in what order, to finish a task. The OpenAI Agents SDK is OpenAI's runtime for those agents. It ships as openai-agents on PyPI and @openai/agents on npm. Both repositories carry the MIT license.

The docs describe agents as "LLMs equipped with instructions and tools." The SDK wraps them in a loop that runs until the task completes. By default, the SDK calls OpenAI models through the Responses API. The latest stable TypeScript release is 0.22.0, dated November 12 on the JS releases page.

Core primitives of the OpenAI Agents SDK

As of November 2026, the official Python and TypeScript docs describe these building blocks:

PrimitiveWhat it doesWhen to use it
AgentWraps a model with instructions, tools, handoffs, and guardrailsEvery build starts here
Tools (@tool, function_tool)Turns a Python function into a tool with a generated schema and Pydantic validationThe agent needs data or actions outside the model
Handoffs (handoff())Transfers the conversation to a specialist, which becomes the active agentA triage step routes requests
Agents as tools (Agent.as_tool())Lets a manager call specialists and keep controlBounded subtasks under one orchestrator
GuardrailsValidates input or output and halts the run when a tripwire firesBlocking off-topic or unsafe requests
Sessions (SQLiteSession and others)Stores conversation history between runsMulti-turn chat without manual history handling
TracingRecords model calls, tool calls, handoffs, and guardrailsDebugging, monitoring, and trace-based evals
Sandbox agents (SandboxAgent)Runs the agent in an isolated workspace with files, a shell, and resumable stateThe agent edits files or executes code

Start with an agent and one tool. Add a SandboxAgent only when the agent needs to touch files or run commands.

Prerequisites

You need three things before the first command:

  • Python 3.10 or newer. Version 0.9.0 dropped Python 3.9.
  • An OpenAI API key exported as OPENAI_API_KEY.
  • For the sandbox steps, a Baseten Sandbox account, the bl CLI, and values for BL_WORKSPACE and BL_API_KEY.

With those in place, start with the install.

How to build your first agent with the OpenAI Agents SDK in Python

You install one package, decorate a function as a tool, then add routing, validation, memory, and tracing. Every snippet in this OpenAI Agents SDK tutorial comes from the official Python docs or examples.

Install the SDK and set your API key

Shell
pip install openai-agents
export OPENAI_API_KEY=sk-...

On Windows PowerShell, use $env:OPENAI_API_KEY = "sk-...". The SDK reads the key when it first creates an OpenAI client. Set it before your first model call, or call set_default_openai_key() in code. Run pip show openai-agents to confirm you have 0.24.0, the version these examples assume.

The import name is agents. A local file called agents.py can shadow the installed package and produce ModuleNotFoundError: No module named 'agents'. A reply in one OpenAI community forum thread suggests this cause. Rename the file if you hit it.

Build a minimal agent with one tool

The official quickstart uses @tool, an alias for function_tool:

Python
import asyncio
from agents import Agent, Runner
from agents.decorators import tool

@tool
def history_fun_fact() -> str:
"""Return a short history fact."""
return "Sharks are older than trees."

agent = Agent(
name="History Tutor",
instructions="Answer history questions clearly. Use history_fun_fact when it helps.",
tools=[history_fun_fact],
)

async def main():
result = await Runner.run(
agent,
"Tell me something surprising about ancient life on Earth.",
)
print(result.final_output)

if __name__ == "__main__":
asyncio.run(main())

The decorator builds the tool schema from the signature and uses the docstring as the description. Runner.run calls the model, executes any tool call, and loops until a final output appears. If the run exceeds max_turns, the runner raises MaxTurnsExceeded. The printed result is the model's answer, so it varies between runs.

Add a handoff and an input guardrail

A handoff lets a triage agent pass the conversation to a specialist. The handoffs guide shows the pattern:

Python
from agents import Agent, handoff

billing_agent = Agent(name="Billing agent")
refund_agent = Agent(name="Refund agent")

triage_agent = Agent(name="Triage agent", handoffs=[billing_agent, handoff(refund_agent)])

The model sees each handoff as a tool. By default, the receiving agent sees the entire conversation history. Trim it with input_filter.

A guardrail returns a GuardrailFunctionOutput. If tripwire_triggered is true, the runner raises InputGuardrailTripwireTriggered and halts. The guardrails docs use a homework detector. Both snippets are excerpts, so copy the imports, guardrail_agent, agent, and main() from that page:

Python
@input_guardrail
async def math_guardrail(
ctx: RunContextWrapper[None], agent: Agent, input: str | list[TResponseInputItem]
) -> GuardrailFunctionOutput:
result = await Runner.run(guardrail_agent, input, context=ctx.context)

`return GuardrailFunctionOutput(`  
    `output_info=result.final_output,`  
    `tripwire_triggered=result.final_output.is_math_homework,`  
`)`

Python
try:
await Runner.run(agent, "Hello, can you help me solve for x: 2x + 3 = 11?")
print("Guardrail didn't trip - this is unexpected")

`except InputGuardrailTripwireTriggered:`  
    `print("Math homework guardrail tripped")`

When the except block catches the tripwire exception, the example prints Math homework guardrail tripped. Input guardrails run only for the first agent in a chain. By default, guardrails run in parallel with the agent, so the agent can spend tokens before cancellation. Set run_in_parallel=False to block until the check finishes.

Add a session for conversation memory

Sessions store conversation history so you don't need to pass .to_input_list() output between turns. The sessions overview shows SQLite. The last line uses await, so run it inside an async function such as main():

Python
from agents import SQLiteSession

# In-memory database (lost when process ends)
session = SQLiteSession("user_123")

# Persistent file-based database
session = SQLiteSession("user_123", "conversations.db")

# Use the session
result = await Runner.run(agent, "Hello", session=session)

The session persists conversation items keyed by session ID. If a run pauses for approval, resume it from a RunState, as the running agents docs describe. The session ID selects history but doesn't authenticate users, so your application must authorize access. For shared workers, the docs list RedisSession, SQLAlchemySession, MongoDBSession, and DaprSession. EncryptedSession wraps any backend.

Inspect runs with tracing

Tracing is on by default. Each run records model generations, tool calls, handoffs, guardrails, and custom spans. Open the Traces dashboard on the OpenAI platform to inspect them. Trace grading runs graders against selected traces.

You can turn tracing off in three ways:

  • Set OPENAI_AGENTS_DISABLE_TRACING=1 globally.
  • Call set_tracing_disabled(True) in code.
  • Set RunConfig.tracing_disabled for a single run.

trace_include_sensitive_data defaults to true, so spans store model and tool inputs and outputs. Set it to false to drop them. Per the tracing docs, tracing is unavailable for organizations using OpenAI's APIs under a Zero Data Retention (ZDR) policy. Those organizations can route spans to their own backend with set_trace_processors(). Check whether your organization falls under that policy before you rely on traces.

Why agent-generated code needs isolation

Agent-generated Python runs without any human review. OWASP (Open Worldwide Application Security Project) names this risk in LLM05:2025 Improper Output Handling. Its first example is model output passed straight into a shell, exec, or eval, which leads to remote code execution. Its guidance is to "Treat the model as any other user, adopting a zero-trust approach."

  • Running that code on the host exposes your API keys, filesystem, and network. Containers narrow the exposure but share the host kernel. A runc flaw, CVE-2024-21626, let a container process reach the host filesystem.
  • Firecracker microVMs give each workload its own guest kernel behind hardware virtualization. The Cloud Security Alliance (CSA) calls them "appropriate for agents executing untrusted code" in its Agentic Universe note.

Separate-kernel isolation has limits. A CSA research note says a microVM "still depends on host kernel hygiene." Isolation also can't stop an authorized process from sending data out. Pair it with an egress allowlist and proxy-based secret injection. The sandbox agents quickstart warns that the SDK's local UnixLocalSandboxClient adds no OS-level confinement on Linux.

Run generated code in a microVM, away from the process that holds your credentials.

How to run generated code in an OpenAI Agents SDK sandbox

Baseten Sandboxes are a first-class sandbox provider in the OpenAI Agents SDK. Configure credentials, connect the sandbox client, then run the agent and check its output.

Configure Baseten Sandbox credentials

The steps come from the Baseten Sandbox tutorial, last modified September 25, 2026:

Shell
bl login
mkdir sandbox-agent && cd sandbox-agent
python3 -m venv .venv && source .venv/bin/activate # if new project
pip install openai-agents[blaxel]

Shell
export OPENAI_API_KEY=your_key_here
export BL_API_KEY=your_key_here
export BL_WORKSPACE=your_workspace_name_here

The tutorial pins no SDK version. TypeScript users install @openai/agents-extensions @blaxel/core instead.

Connect the sandbox to your agent

Each Baseten Sandbox is a Firecracker microVM with its own kernel. The SDK client for Baseten Sandboxes keeps the name BlaxelSandboxClient. The sandbox clients page lists other hosted providers too. It notes that "the same SandboxAgent definition usually carries over and only the sandbox client changes in SandboxRunConfig."

The tutorial's main.py, verbatim:

Python
import asyncio
from agents import ModelSettings, Runner
from agents.run import RunConfig
from agents.sandbox import Manifest, SandboxAgent, SandboxRunConfig
from agents.extensions.sandbox import BlaxelSandboxClient, BlaxelSandboxClientOptions

async def main():

`agent = SandboxAgent(`  
    `name="Sandboxed agent",`  
    `model="gpt-5.4",`  
    `instructions=(`  
        `"You have access to a sandbox environment. You can execute commands, manage files, and inspect processes inside the sandbox."`  
    `),`  
    `model_settings=ModelSettings(tool_choice="auto"),`  
    `default_manifest=Manifest(root="/blaxel"),`  
`)`

`client = BlaxelSandboxClient()`  
`run_config = RunConfig(`  
    `sandbox=SandboxRunConfig(`  
        `client=client,`  
        `options=BlaxelSandboxClientOptions(`  
            `name="agent-sandbox-01",`  
            `image="blaxel/base-image",`  
            `region="us-pdx-1",`  
            `memory=4096,`  
        `),`  
    `)`  
`)`

`result = await Runner.run(agent, "Install a complete Go development environment. Once done, return the installed Go version number and Go environment variables.", run_config=run_config)`  
`print(result.final_output)`

`await client.close()`

if __name__ == "__main__":
asyncio.run(main())

Here's what each block does:

  • Agent definition: SandboxAgent adds a workspace rooted at /blaxel through default_manifest.
  • Client and options: BlaxelSandboxClient reads your credentials, and the options set the name, image, region, and memory in MB.
  • Run config: SandboxRunConfig attaches the client at run time, so the agent definition stays portable.
  • Cleanup: client.close() releases the client after the run.

The agent definition usually stays the same if you switch sandbox providers.

Run the agent and check the output

Run python main.py. The tutorial shows this partial output:

Go is installed and ready.

- Installed version: `go1.25.9`
- Command check: `go version` → `go version go1.25.9 linux/amd64`

The SDK deletes the sandbox when the run ends. Initial creation takes under a second.

The tutorial's coding-agent example passes pause_on_exit=True, which stops automatic deletion after the run. It also passes ttl="30m", which sets a 30-minute expiration that deletes the sandbox.

A Baseten Sandbox that persists after the run enters standby after about 15 seconds of network inactivity. It resumes from standby in under 25ms. Standby carries no compute charge.

Use Volumes for long-term storage.

Measure resume times on your own workload before you rely on the 25ms figure.

What the OpenAI Agents SDK costs to run

Pricing starts with the default model. The SDK's default became gpt-5.6-luna in v0.20.0. The OpenAI pricing page lists it at $0.20 input and $1.20 output per 1M tokens, as of November 16, 2026.

The run estimates use gpt-6.1-sol instead of the default, at Standard rates from that page as of November 2026. Input costs $2.00 and output costs $10.00 per 1M tokens. Token counts are illustrative assumptions:

Run shapeModel callsInput tokensOutput tokensCost per run
Single agent with one tool312,0001,500$0.024 + $0.015 = $0.039
Triage, guardrail and specialist525,0002,500$0.05 + $0.025 = $0.075

By default, each handoff receives the full conversation history, so include those repeated input tokens in multi-agent estimates. Hosted web search adds $10.00 per 1,000 calls. Hosted code interpreter containers start at $0.03 per 1 GB session. Eligible sessions bill per minute with a 5-minute minimum. Tracing itself is free, per the Python tracing docs. Baseten Sandboxes use usage-based pricing. They bill on allocated memory while active and charge no compute during standby.

Log per-request usage from request_usage_entries. Don't base a multi-agent budget on a single-agent test.

Is the OpenAI Agents SDK production-ready?

Teams can run the SDK in production today if they pin versions and test every upgrade.

  • The SDK is pre-1.0 and changes fast. The release policy says minor versions carry breaking changes. Version 0.21.0, for example, required custom http_client code to move from httpx to httpx2. PyPI's release history shows 11 releases in May 2026 and seven in July, by UTC upload date. Alpha previews ship through GitHub Releases only.
  • The SDK supports Model Context Protocol (MCP) through four MCP server options: HostedMCPTool, MCPServerStreamableHttp, MCPServerSse, and MCPServerStdio. The docs note that the MCP project has deprecated Server-Sent Events (SSE). Hosted MCP works only with OpenAI models that support the Responses API.
  • Non-OpenAI models can run through LiteLLM. The SDK supports it "on a best-effort, beta basis," per the models docs. Many providers lack the Responses API, so call set_default_openai_api("chat_completions"). A user-reported issue shows hosted tools failing under Chat Completions.

For tests, use ScriptedModel from agents.testing, the main utility in the testing docs. Trace grading works on whole traces. As of October 2025, Latent Space reported that per-span grading was still roadmap work. Watch the issue tracker for open bugs. Issue #5642, for example, reports that after a conversation_id run stops at max_turns, every later turn returns HTTP 400.

Conclusion

You now have a path from pip install openai-agents to an agent with a tool, handoff, guardrail, session, and traces. The same agent becomes a SandboxAgent when it needs to run code, with Baseten Sandboxes as the sandbox provider. Next, adapt the tutorial's main.py to your own task, with BL_WORKSPACE and BL_API_KEY set.

FAQs about the OpenAI Agents SDK

Is the OpenAI Agents SDK free?

Yes. The Python and TypeScript packages are open source under the MIT license. You pay for model tokens at OpenAI API rates. You also pay for hosted tools such as web search and code interpreter, plus any sandbox compute your agents use.

Can the OpenAI Agents SDK use non-OpenAI models?

Yes. Install openai-agents[litellm] and use litellm/... model names. The SDK supports that route on a beta basis. You can also point an OpenAI-compatible client at another provider. If the provider lacks the Responses API, switch to Chat Completions. Hosted tools and structured outputs then depend on the provider.

Should I use Python or TypeScript?

Use the language your team already ships. Both SDKs share the same primitives, from agents and handoffs to tracing and sandbox agents. Names differ slightly, such as function_tool in Python and tool() in TypeScript. The TypeScript SDK needs Node.js 22 or later, Deno, or Bun.

Which sandbox providers does the OpenAI Agents SDK support?

The Python sandbox clients page lists seven hosted platforms: Baseten Sandboxes, Cloudflare, Databricks, Daytona, E2B, Modal, and Vercel. Baseten Sandboxes are a first-class sandbox provider through the BlaxelSandboxClient class. For local work, the SDK ships UnixLocalSandboxClient and DockerSandboxClient. Runloop still ships in 0.24.0, but PR #5369 removed it from the main branch.

Is the OpenAI Agents SDK stable?

Not yet. Both SDKs are still pre-1.0. PyPI lists Python at 0.24.0 and the JS releases page lists TypeScript at 0.22.0, as of November 2026. Minor releases carry breaking changes under OpenAI's release policy. Pin an exact minor version, read the changelog, and run ScriptedModel tests on each upgrade.

Related articles