- Published on
Getting Started with OpenAI’s Agents SDK for TypeScript
- Authors
- Name
- Ali Ibrahim
Early this year, OpenAI released the Agents SDK, a software development tool that facilitates building AI agents using OpenAI models. Initially, the SDK only supported Python. Recently, however, they announced the release of the TypeScript version of the SDK, a game changer for developers in the JavaScript ecosystem.
In a recent article, I wrote about LlamaIndex vs. LangGraph:
"But as JavaScript and TypeScript continue to dominate full-stack development, there’s a growing need for agent frameworks built natively for JS, without forcing developers to switch stacks or work around language mismatches."
This release validates that point. In this short article, we’ll walk through a hello world example using the SDK and explore its core concepts and architecture.
Concepts
Agents
Agents are the main building block of the OpenAI Agents SDK. An Agent is a Large Language Model (LLM) that has been configured with:
- Instructions : the system prompt that tells the model who it is and how it should respond.
- Model : which OpenAI model to use, with optional tuning parameters.
- Tools : functions or APIs the LLM can invoke to complete a task.
Simple agent definition:
import { Agent } from '@openai/agents'
const agent = new Agent({
name: 'Haiku Agent',
instructions: 'Always respond in haiku form.',
model: 'o4-mini', // optional
})
Context
The context is a dependency injection object passed to run()
. It is forwarded to tools, guardrails, handoffs, etc., and is useful for storing state or shared services (e.g., DB connections, user metadata).
import { Agent, run } from '@openai/agents'
interface UserContext {
uid: string
isProUser: boolean
fetchPurchases(): Promise<any[]>
}
const agent = new Agent<UserContext>({
name: 'Personal shopper',
instructions: 'Recommend products the user will love.',
})
const result = await run(agent, 'Find me new running shoes', {
context: {
uid: 'abc',
isProUser: true,
fetchPurchases: async () => [], // this function can be called in any agent that has access to the context
},
})
Handoffs
Agents can delegate tasks to other agents using handoffs
. A common use case is triaging tasks to specialized sub-agents.
import { Agent, handoff } from '@openai/agents'
const billingAgent = new Agent({ name: 'Billing agent' })
const refundAgent = new Agent({ name: 'Refund agent' })
const triageAgent = Agent.create({
name: 'Triage agent',
handoffs: [billingAgent, handoff(refundAgent)],
})
Guardrails
Guardrails run in parallel with agents to validate inputs or outputs. You can use them to detect malicious usage or prevent unnecessary API calls.
- Input guardrails validate user input.
- Output guardrails validate agent output.
More info: Guardrails documentation
Human in the Loop
Pause an agent’s execution to wait for human input. Useful for approval workflows. Implemented using tools.
import { tool } from '@openai/agents'
import z from 'zod'
const cancelOrder = tool({
name: 'cancelOrder',
description: 'Cancel order',
parameters: z.object({ orderId: z.number() }),
needsApproval: true,
execute: async ({ orderId }) => {
// prepare order return
},
})
const sendEmail = tool({
name: 'sendEmail',
description: 'Send an email',
parameters: z.object({ to: z.string(), subject: z.string(), body: z.string() }),
needsApproval: async (_ctx, { subject }) => subject.includes('spam'),
execute: async ({ to, subject, body }) => {
// send email
},
})
Getting Started
Before following the examples, ensure you have Node.js and npm\pnpm
installed, an OpenAI API KEY exported as an environment variable. You should also init a new Node.js project if you haven't already:
mkdir my-agent-project
cd my-agent-project
npm init -y
Note : The full code examples are available in the GitHub repository.
Installations
Install the SDK:
pnpm install @openai/agents zod
# or
npm install @openai/agents zod
Hello World Example
import { Agent, run } from '@openai/agents'
const agent = new Agent({
name: 'Assistant',
instructions: 'You are a helpful assistant.',
})
const result = await run(agent, 'Write a haiku about recursion in programming.')
console.log(result.finalOutput)
Handoff Example
Here I'm using handoffs to delegate tasks to a writer agent and a planner agent. I'm also using zod to define the output types of the agents.
import { Agent, run } from '@openai/agents'
import { z } from 'zod'
const writerOutput = z.object({
content: z.string(),
plan: z.string(),
})
const finalOutput = z.object({
content: z.string(),
critique: z.string(),
plan: z.string(),
})
const writerAgent = new Agent({
name: 'Agentailor Writer',
model: 'gpt-4o',
instructions: 'Write concise LinkedIn content.',
outputType: writerOutput,
})
const plannerAgent = new Agent({
name: 'Agentailor Planner',
model: 'gpt-4o-mini',
instructions: 'Plan LinkedIn content.',
outputType: finalOutput,
handoffs: [writerAgent],
})
const result = await run(plannerAgent, 'Post about LangGraph for AI dev')
console.log(result.finalOutput)
Conclusion
The OpenAI Agents SDK for TypeScript simplifies building robust, safe, and extensible AI agents. With features like guardrails, human-in-the-loop, and seamless handoffs, it's well-suited for modern JavaScript applications, especially if you prefer using only one model provider.
If you need more flexibility or want to use multiple models, checkout my latest article on LangGraph vs. LlamaIndex to see which framework fits your needs best.
Next Steps
If you want to get started quickly, check out the Agent Initializr to scaffold a production-grade backend for your agents, or use the Agent Playground to test and evaluate agents in a chat interface.