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>',});面向 TypeScript 的 OpenAI Agents SDK 让您以轻量、易用、极少抽象的方式构建智能体应用。它是我们此前面向智能体的实验项目 Swarm 的生产级升级版本,并且也提供 Python 版本。Agents SDK 只包含一小套基本组件:
- 智能体(Agents):配备 instructions 和 tools 的 LLM
- Agents as tools / 交接:让智能体将特定任务委派给其他智能体
- 护栏(Guardrails):对进入智能体的输入进行校验
结合 TypeScript,这些基本组件足以表达工具与智能体之间的复杂关系,让您无需陡峭学习曲线即可构建真实世界的应用。此外,SDK 内置 追踪(tracing),便于可视化和调试智能体流程,并支持评估、以及为您的应用微调模型。
为什么使用 Agents SDK
Section titled “为什么使用 Agents SDK”该 SDK 的两大设计原则:
- 功能足够实用,但基本组件足够少,便于快速上手。
- 开箱即用体验优秀,同时允许您精确自定义执行过程。
主要特性包括:
- 智能体循环(Agent loop):内置循环处理工具调用,将结果返回给 LLM,并持续执行直至任务完成。
- TypeScript 优先(TypeScript-first):使用原生 TypeScript 语言特性来编排与串联智能体,无需学习新抽象。
- Agents as tools / 交接:强大的机制,用于在多个智能体间协调与委派工作。
- 护栏(Guardrails):与智能体执行并行进行输入校验与安全检查,未通过时快速失败。
- 函数工具(Function tools):将任意 TypeScript 函数转换为工具,自动生成 schema,并通过 Zod 进行校验。
- MCP 服务器工具调用(MCP server tool calling):内置 MCP 服务器工具集成,其用法与函数工具相同。
- 会话(Sessions):在智能体循环内维护工作上下文的持久内存层。
- 人工干预(Human in the loop):内置机制,可在智能体运行过程中引入人工参与。
- 追踪(Tracing):内置追踪用于可视化、调试与监控工作流,并支持 OpenAI 的评估、微调与蒸馏工具套件。
- 实时智能体(Realtime Agents):构建强大的语音智能体,具备自动打断检测、上下文管理、护栏等特性。
npm install @openai/agents zod@3Hello 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-...