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 和工具的 LLM
- 交接(Handoffs):允许智能体将特定任务委派给其他智能体
- 护栏(Guardrails):用于验证智能体的输入
配合 TypeScript,这些基本组件足以表达工具与智能体之间的复杂关系,让你在没有陡峭学习曲线的情况下构建真实应用。此外,SDK 内置追踪(tracing),可用于可视化和调试你的智能体流程,并进行评估,甚至为你的应用微调模型。
为什么使用 Agents SDK
Section titled “为什么使用 Agents SDK”该 SDK 的两条设计原则:
- 功能足够有用,但基本组件足够少,便于快速上手。
- 开箱即用效果佳,同时又可精确自定义行为。
主要特性如下:
- 智能体循环(Agent loop):内置循环,负责调用工具、把结果发送给 LLM,并循环直到 LLM 完成。
- TypeScript 优先(TypeScript-first):使用语言内置特性来编排与串联智能体,无需学习新抽象。
- 交接(Handoffs):在多个智能体之间进行协调与委派的强大能力。
- 护栏(Guardrails):与智能体并行执行输入验证与检查,失败时可提前中断。
- 函数工具(Function tools):将任意 TypeScript 函数变为工具,自动生成模式并通过 Zod 验证。
- 追踪(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-...