1. What Is an AI Agent?
Before diving into the Agents SDK, let’s answer the most basic question first.
Plain AI Chat vs. an AI Agent
When you chat with ChatGPT or Claude, it works like this:
You → AI → text replyThe AI can talk, but it can’t act.
An AI agent, on the other hand, works like this:
You → AI → thinks → calls tools (queries a database, sends email, reads/writes files...) → returns the resultAn agent can perceive its environment, use tools, and make its own decisions. It’s no longer a chatbot that can only “talk” — it’s an assistant that can actually do things.
An Analogy
| Role | Analogy | Capability |
|---|---|---|
| Plain AI chat | Call-center agent | Can only answer questions verbally |
| AI agent | On-site repair technician | Shows up at your door with a toolbox and fixes the problem |
2. What Is the OpenAI Agents SDK?
The OpenAI Agents SDK is a lightweight, official framework from OpenAI that helps you build agent applications quickly.
Why Do You Need It?
Without a framework, you’d have to handle all of this yourself:
- How do you let the AI call tools?
- Once a tool call finishes, how do you feed the result back to the AI?
- When the AI says “I want to call tool A”, how do you parse that intent?
- How do multiple agents collaborate?
The Agents SDK wraps all of this up, so you can focus on your business logic.
Which Languages Does It Support?
- TypeScript (
@openai/agents) - Python (
openai-agents)
This post uses TypeScript.
Installation
npm install @openai/agentsSet your API key:
export OPENAI_API_KEY="sk-your-key-here"NOTEYou’ll need an OpenAI API key, which you can get at platform.openai.com.
3. Core Concepts at a Glance
Get the big picture first; we’ll unpack each piece later.
┌─────────────────────────────────────────────┐│ Your Application ││ ││ ┌─────────┐ ┌─────────┐ ││ │ Agent A │────▶│ Agent B │ Handoff: ││ └────┬────┘ └─────────┘ hand over ││ │ control ││ │ call tools ││ ▼ ││ ┌──────────┐ ┌──────────┐ ┌────────┐ ││ │ Search │ │ Database │ │ MCP │ ││ └──────────┘ └──────────┘ └────────┘ ││ ││ Runner ─── the engine that runs the loop ││ Guardrails ─── safety checks on I/O ││ Context ─── shared data passed to tools │└──────────────────────────────────────────────┘| Concept | In One Sentence |
|---|---|
| Agent | A configured AI with a name, instructions, and tools |
| Runner | The execution engine that runs an agent until it produces a final result |
| Tools | What the agent can use (search, databases, custom functions, etc.) |
| Handoffs | Agent-to-agent handover — passing control of the conversation to another agent |
| Guardrails | Safety checks that intercept inappropriate input or output |
| Context | Shared data accessible to all tools and guardrails |
4. Agent — Your First Intelligent Agent
A Minimal Example
import { Agent, Runner } from '@openai/agents';
// Create an agentconst agent = new Agent({ name: 'Assistant', instructions: 'You are a friendly assistant. Answer questions helpfully.',});
// Run itconst runner = new Runner();const result = await runner.run(agent, 'What is machine learning?');
console.log(result.finalOutput);That’s a complete agent program, in three steps:
- Create the Agent — tell it its name and how it should behave
- Create a Runner — set up the execution engine
- Run — pass in user input and get a result back
Agent Configuration Options
const agent = new Agent({ // Required name: 'Agent name', // used for logging and tracing
// Recommended instructions: 'system prompt', // tells the Agent how to behave
// Optional model: 'gpt-4.1', // which model to use; defaults to gpt-4.1 tools: [], // list of available tools handoffs: [], // list of agents it can hand off to outputType: undefined, // structured output schema inputGuardrails: [], // input guardrails outputGuardrails: [], // output guardrails});Dynamic Instructions
Sometimes the prompt needs to change with context. instructions can be a function:
const agent = new Agent({ name: 'Support Assistant', instructions: (context) => { const user = context.getContext('userInfo'); return `You are a support assistant. Current user: ${user.name}, membership tier: ${user.level}.Provide service appropriate to the user's tier.`; },});5. Runner — Getting the Agent to Run
What Does the Runner Do?
The Runner’s job is a loop:
Turn 1: send the user input to the AI ↓ The AI replies: "I need to call the search tool" ↓ The Runner executes the search tool and feeds the result back to the AI ↓Turn 2: the AI continues its reply based on the search results ↓ The AI says: "Based on the search results, the answer is..." ↓ No more tool calls → stop and return the final resultThree Ways to Run
const runner = new Runner();
// 1. Plain run — wait for the full resultconst result = await runner.run(agent, 'Hello');
// 2. Streaming — get output in real time (great for typewriter-style UIs)const streamResult = runner.runStreamed(agent, 'Write a poem');for await (const event of streamResult) { if (event.type === 'text_delta') { process.stdout.write(event.data); }}
// 3. Single turn — execute just one step, no automatic loopingconst turnResult = await runner.runTurn(agent, 'Hello');Run Options
const result = await runner.run(agent, userInput, { context: { userId: '123' }, // shared data passed to tools maxTurns: 10, // cap the loop at 10 turns (guards against infinite loops)});TIPSetting
maxTurnsis a good habit. If the agent gets stuck in a loop of tool calls,maxTurnswill force it to stop.
6. Tools — Equipping Your Agent
An agent without tools is all talk. Give it tools, and it can actually get things done.
The SDK offers four kinds of tools:
1. Hosted Tools (Provided by OpenAI)
The simplest tools — one line to enable:
import { webSearch } from '@openai/agents/tools';
const agent = new Agent({ name: 'Search Assistant', tools: [webSearch()], // enable web search});Available hosted tools:
| Tool | Purpose |
|---|---|
webSearch() | Search the internet |
fileSearch(['vector_store_id']) | Search uploaded files (RAG) |
codeInterpreter() | Execute Python code |
imageGeneration() | Generate images |
2. Custom Function Tools (the Most Common)
These are functions you write yourself that the agent can call:
import { tool } from '@openai/agents';import { z } from 'zod';
// Define a weather lookup toolconst weatherTool = tool({ name: 'get_weather', description: 'Get the current weather for a given city', parameters: z.object({ city: z.string().describe('City name, e.g. "Beijing"'), }), execute: async ({ city }) => { // Call a real weather API here const res = await fetch(`https://api.weather.com?city=${city}`); const data = await res.json(); return `${city}: currently ${data.temp}°C, ${data.condition}`; },});
const agent = new Agent({ name: 'Weather Assistant', instructions: 'Help the user check the weather. Keep answers brief.', tools: [weatherTool],});Key points:
nameanddescriptionhelp the AI understand when to call the toolparametersdefines the argument types with Zod (TypeScript type safety)executeis the function that actually runs
What is Zod?Zod is a TypeScript-first validation library. It lets you define data structures concisely while getting type inference for free. Every
z.object()andz.string()in this post’s code comes from Zod.
3. Agents as Tools
You can use one agent as another agent’s tool:
const translateAgent = new Agent({ name: 'Translation Expert', instructions: 'Translate any content into English. Output only the translation.',});
const mainAgent = new Agent({ name: 'Main Assistant', instructions: 'You are a general-purpose assistant. Use the translation tool whenever translation is needed.', tools: [translateAgent.asTool()], // use the translation agent as a tool});4. MCP Server Tools
MCP (Model Context Protocol) is a standard protocol that lets your agent plug into external tool services:
import { MCPServerStdio } from '@openai/agents/mcp';
const fileServer = new MCPServerStdio({ name: 'File Service', command: 'npx', args: ['-y', '@modelcontextprotocol/server-filesystem', './data'],});
const agent = new Agent({ name: 'File Assistant', tools: [fileServer], // the agent can now read and write the ./data directory});About MCPMCP is an open protocol introduced by Anthropic that standardizes how AI applications connect to external tools and data sources. Think of it as “USB for AI” — as long as a tool supports MCP, an agent can use it directly.
7. Handoffs — Passing the Baton Between Agents
Why Hand Off?
Picture a customer service system:
User: "I want to return this" → routing agent classifies it as after-sales → hands off to the after-sales agent
User: "How do I install this?" → routing agent classifies it as technical → hands off to the tech support agentHow to Implement It
const afterSalesAgent = new Agent({ name: 'After-sales Support', instructions: 'You handle returns, exchanges, refunds, and other after-sales issues.',});
const techAgent = new Agent({ name: 'Tech Support', instructions: 'You handle product usage, installation, and other technical issues.',});
const triageAgent = new Agent({ name: 'Support Router', instructions: `You are the support router. Pick the right agent based on the user's question:- Returns / exchanges / refunds → hand off to After-sales Support- Installation / usage / troubleshooting → hand off to Tech Support- Anything else → answer it yourself`, handoffs: [afterSalesAgent, techAgent], // handoff targets});Handoff vs. Agent-as-Tool
These two patterns are easy to confuse. The core difference is who holds control:
Handoff: Agent A ──hands over control──▶ Agent B B handles the entire rest of the conversation
Manager (Agent-as-Tool): Agent A ──calls──▶ Agent B ──returns result──▶ Agent A A stays in charge the whole time; B is just A's "hired gun"| Handoff | Manager pattern (asTool) | |
|---|---|---|
| Control | Transferred to the target agent | Main agent stays in control |
| Follow-up turns | Target agent owns them | Main agent decides the next step |
| Best for | Clearly separated domains | Coordinating results from multiple agents |
When to use which?
- Handoff: each agent owns a completely different domain, and the user won’t need to come back to the main agent afterward
- Manager: the main agent needs to synthesize results from several agents to make a decision
8. Guardrails — Safety Rails
With tools, an agent can get things done — but are the things it does safe? Guardrails are the safety inspectors.
Three Places to Guard
User input ──▶ [input guardrail] ──▶ Agent processing ──▶ [output guardrail] ──▶ result returned │ [tool guardrail] (before/after tool calls)Input Guardrails: Check User Input
import { guardrail } from '@openai/agents';
const noHarmfulContent = guardrail({ name: 'Harmful content detection', execute: async (input) => { const isHarmful = await checkContent(input); if (isHarmful) { return { tripwire: true, reason: 'Input contains inappropriate content' }; } return { tripwire: false }; },});
const agent = new Agent({ name: 'Safe Assistant', inputGuardrails: [noHarmfulContent],});When a guardrail trips (tripwire: true), the Runner throws a GuardrailTripwireTriggered exception and stops execution.
Output Guardrails: Check Agent Replies
const noSecretLeak = guardrail({ name: 'Sensitive information check', execute: async (output) => { if (containsSecret(output)) { return { tripwire: true, reason: 'Output contains sensitive information' }; } return { tripwire: false }; },});
const agent = new Agent({ name: 'Safe Assistant', outputGuardrails: [noSecretLeak],});Tool Guardrails: Check Tool Calls
Add validation directly in the tool definition:
const dbTool = tool({ name: 'query_database', description: 'Query the database', parameters: z.object({ sql: z.string() }), execute: async ({ sql }) => { return executeSQL(sql); }, // Tool guardrail: check the SQL before executing validateInput: async (input) => { if (input.sql.toLowerCase().includes('drop')) { throw new Error('DROP operations are not allowed'); } if (input.sql.toLowerCase().includes('delete') && !input.sql.includes('where')) { throw new Error('DELETE must have a WHERE clause'); } },});WARNINGGuardrails aren’t a silver bullet. They’re the last line of defense, not a replacement for other safety measures (database permissions, API authentication, and so on).
9. Context — Sharing Data Across Tools
The Problem
Your agent has several tools, and they all need to know “who is the current user”:
Tool A (query orders) needs userIdTool B (query balance) needs userIdTool C (send notification) needs userIdSurely you’re not going to make the user provide it to every single tool?
Solution: RunContext
// 1. Define the context typeinterface AppContext { userId: string; userName: string; permissions: string[];}
// 2. Access the context inside a toolconst orderTool = tool({ name: 'query_orders', description: "Query the current user's orders", parameters: z.object({ keyword: z.string().optional() }), execute: async ({ keyword }, context) => { // context is automatically inferred as RunContext<AppContext> console.log(`Querying orders for user ${context.userId}`);
if (!context.permissions.includes('order_read')) { throw new Error('No permission to view orders'); }
return queryOrders(context.userId, keyword); },});
// 3. Pass the context at run timeconst result = await runner.run(agent, 'Show my orders', { context: { userId: 'user_123', userName: 'Xiaoming', permissions: ['order_read', 'balance_read'], },});Context is essentially dependency injection — shared data is injected at run time, and every tool and guardrail can access it.
10. Structured Output
Sometimes you don’t want a blob of text — you want a structured data object.
Using outputType
import { z } from 'zod';
const analysisAgent = new Agent({ name: 'Sentiment Analysis', instructions: 'Analyze the sentiment of the user text.', outputType: z.object({ sentiment: z.enum(['positive', 'negative', 'neutral']), confidence: z.number().min(0).max(1), keywords: z.array(z.string()), summary: z.string(), }),});
const result = await runner.run(analysisAgent, 'This product is amazing — highly recommended!');
// The type of result.finalOutput is:// { sentiment: 'positive', confidence: 0.95, keywords: ['amazing', 'recommended'], summary: '...' }console.log(result.finalOutput.sentiment); // "positive"TIPOnce you set
outputType, the SDK handles JSON parsing and type validation internally. If the AI returns a malformed response, it retries automatically.
11. State Management — Giving the Agent a Memory
By default, every runner.run() is independent. Real applications, though, need multi-turn conversations.
Option 1: Pass History Manually (Most Flexible)
const result1 = await runner.run(agent, 'My name is Xiaoming');// Agent replies: "Hello Xiaoming!"
const result2 = await runner.run(agent, 'What is my name?', { history: result1.history, // pass in the previous conversation history});// Agent replies: "Your name is Xiaoming."Option 2: Use a Session (Simplest)
import { Session } from '@openai/agents';
const session = new Session();
// Session manages conversation history automaticallyawait session.run(agent, 'My name is Xiaoming');await session.run(agent, 'What is my name?'); // it remembers: XiaomingWhich One to Pick?
| Scenario | Recommendation |
|---|---|
| Quick prototypes, simple apps | Session |
| Precise control over history contents | Pass history manually |
| Persisting to a database | Manual, store and retrieve it yourself |
12. Putting It Together: A Multi-Agent Support System
Time to tie everything together into one complete example.
Requirements
Build an intelligent customer service system that can:
- Automatically route to specialized agents
- Query orders and weather
- Check user permissions
- Return structured replies
Full Code
import { Agent, Runner, tool, guardrail,} from '@openai/agents';import { z } from 'zod';
// ==========================================// 1. Define the context type// ==========================================interface AppContext { userId: string; permissions: string[];}
// ==========================================// 2. Define the tools// ==========================================const queryOrders = tool({ name: 'query_orders', description: "Query the user's orders", parameters: z.object({ status: z.enum(['all', 'pending', 'shipped', 'completed']).optional(), }), execute: async ({ status }, context) => { if (!context.permissions.includes('order_read')) { return 'Error: no permission to view orders'; } // Simulated query return `Orders for user ${context.userId} (${status ?? 'all'}): order #001 (shipped), order #002 (pending)`; },});
const getWeather = tool({ name: 'get_weather', description: "Look up a city's weather", parameters: z.object({ city: z.string().describe('City name'), }), execute: async ({ city }) => { return `${city}: sunny today, 25°C — good day to go out`; },});
// ==========================================// 3. Define the guardrail// ==========================================const inputGuard = guardrail({ name: 'Input check', execute: async (input) => { if (input.length > 500) { return { tripwire: true, reason: 'Input too long; please keep it under 500 characters' }; } return { tripwire: false }; },});
// ==========================================// 4. Define the specialized agents// ==========================================const orderAgent = new Agent<AppContext>({ name: 'Order Support', instructions: 'You handle order-related questions such as order lookups and shipment tracking. Answer in a brief, friendly tone.', tools: [queryOrders],});
const infoAgent = new Agent<AppContext>({ name: 'Info Assistant', instructions: 'You handle everyday information questions such as weather lookups. Answer concisely.', tools: [getWeather],});
// ==========================================// 5. Define the routing agent (main entry point)// ==========================================const routerAgent = new Agent<AppContext>({ name: 'Smart Support', instructions: `You are the routing hub of the support system. Pick the right agent based on the user's question:- Orders / shipping / returns → hand off to Order Support- Weather / everyday info → hand off to the Info Assistant- Simple greetings / small talk → answer it yourselfDecide quickly; don't hesitate.`, handoffs: [orderAgent, infoAgent], inputGuardrails: [inputGuard], outputType: z.object({ answer: z.string(), routedTo: z.string().optional(), }),});
// ==========================================// 6. Run it// ==========================================async function main() { const runner = new Runner();
// Scenario 1: order inquiry const result1 = await runner.run(routerAgent, 'Where is my order?', { context: { userId: 'user_001', permissions: ['order_read'] }, }); console.log('Scenario 1:', result1.finalOutput); // { answer: '...', routedTo: 'Order Support' }
// Scenario 2: weather lookup const result2 = await runner.run(routerAgent, "What's the weather in Beijing today?", { context: { userId: 'user_001', permissions: ['order_read'] }, }); console.log('Scenario 2:', result2.finalOutput);
// Scenario 3: simple greeting const result3 = await runner.run(routerAgent, 'Hello!', { context: { userId: 'user_001', permissions: ['order_read'] }, }); console.log('Scenario 3:', result3.finalOutput);}
main();How the Run Unfolds
Using scenario 1, “Where is my order?”, as the example:
1. Runner checks the input guardrail → passes2. Router agent receives the message → classifies it as an order question3. Router agent triggers a handoff → passes control to Order Support4. Order Support receives the message → decides to call the query_orders tool5. Runner executes query_orders → queries the database → returns the result6. Order Support generates a reply based on the result7. Runner checks the output guardrail → passes8. Returns the structured result { answer: '...', routedTo: 'Order Support' }13. Wrap-up and a Learning Path
The Core Concepts on One Page
Agent ├── instructions ── its soul: how it should behave ├── tools ── its hands: what it can do ├── handoffs ── its social skills: who it can pass work to ├── guardrails ── its bottom line: keeping it in check ├── outputType ── its mold: giving output structure └── context ── its memory: data shared across tools
Runner (execution engine) ├── run() ── plain run ├── runStreamed() ── streaming run └── runTurn() ── single-step run
Tools, in four flavors ├── Hosted tools ── provided by OpenAI ├── Function tools ── written by you ├── Agent-as-Tool ── an agent used as a tool └── MCP tools ── external services via MCP
State management ├── history ── manual └── Session ── automaticA Recommended Learning Path
Step 1: get the minimal example running (Agent + Runner) ↓Step 2: add one custom function tool ↓Step 3: implement a handoff between two agents ↓Step 4: add guardrails for safety checks ↓Step 5: pass user info through Context ↓Step 6: try structured output with outputType ↓Step 7: build a full multi-agent systemWhere to Go Next
Once you’re comfortable with the basics:
- Streaming: real-time output, great for typewriter-style UIs
- Tracing: visualize agent call chains for debugging and monitoring
- Voice agents: real-time voice interaction with
RealtimeAgent - Sandbox agents: execute code safely in an isolated environment
- The MCP ecosystem: hook up more and more MCP tool servers