OpenAI Agents SDK TypeScript
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);import { RealtimeAgent, RealtimeSession } from '@openai/agents/realtime';
const agent = new RealtimeAgent({ name: 'Assistant', instructions: 'You are a helpful assistant.',});
// Automatically connects your microphone and audio output in the browser via WebRTC.const session = new RealtimeSession(agent);await session.connect({ apiKey: '<client-api-key>',});OpenAI Agents SDK for TypeScript 让您以轻量、易用且抽象极少的方式构建具备智能体能力的 AI 应用。它是我们此前智能体实验项目 Swarm 的面向生产升级版本,并且也提供 Python 版本。Agents SDK 仅包含一小组基础组件:
- 智能体(Agents):配备 instructions 和 tools 的 LLM
- Agents as tools / 交接(Handoffs):允许智能体将特定任务委托给其他智能体
- 护栏(Guardrails):用于校验传入智能体的输入
结合 TypeScript,这些基础组件足以表达工具与智能体之间的复杂关系,帮助您以较低学习成本构建真实世界的应用。此外,SDK 内置了**追踪(tracing)**功能,可用于可视化与调试智能体流程,并支持对其进行评估,甚至为您的应用微调模型。
为什么使用 Agents SDK
Section titled “为什么使用 Agents SDK”该 SDK 的设计遵循两条原则:
- 功能足够有用,但基础组件足够少,便于快速上手。
- 开箱即用体验优秀,同时允许您精细定制每一步行为。
主要特性包括:
- 智能体循环(Agent loop):内置循环负责调用工具、将结果返回给 LLM,并持续迭代直至任务完成。
- TypeScript 优先(TypeScript-first):使用原生 TypeScript 语言特性编排与串联智能体,无需学习新的抽象。
- Agents as tools / 交接(Handoffs):用于跨多个智能体协调与委派工作的强大机制。
- 护栏(Guardrails):与智能体执行并行进行输入校验与安全检查,未通过时快速失败。
- 函数工具(Function tools):将任意 TypeScript 函数变为工具,自动生成 schema,并通过 Zod 驱动校验。
- MCP 服务器工具集成:内置 MCP 服务器工具集成,其用法与函数工具相同。
- 会话(Sessions):在智能体循环内维护工作上下文的持久化内存层。
- 人工干预(Human in the loop):跨智能体运行引入人工参与的内置机制。
- 追踪(Tracing):内置工作流可视化、调试与监控,支持 OpenAI 全套评估、微调与蒸馏工具。
- 实时智能体(Realtime Agents):构建强大的语音智能体,支持自动打断检测、上下文管理、护栏等特性。
npm install @openai/agents zodSDK 需要 Zod v4;通过 npm 安装 zod 会获取 v4 的最新版本。
Hello World 示例
Section titled “Hello World 示例”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);
// Code within the code,// Functions calling themselves,// Infinite loop's dance.(如果要运行此示例,请确保已设置 OPENAI_API_KEY 环境变量)
export OPENAI_API_KEY=sk-...