智能体
智能体是 OpenAI Agents SDK 的主要构建块。一个 Agent 是经过以下配置的大型语言模型(LLM):
- Instructions——告诉模型“它是谁”和“应如何回答”的系统提示。
- Model——要调用的 OpenAI 模型,以及可选的模型调优参数。
- Tools——LLM 可调用以完成任务的函数或 API 列表。
import { Agent } from '@openai/agents';
const agent = new Agent({ name: 'Haiku Agent', instructions: 'Always respond in haiku form.', model: 'gpt-5-nano', // optional – falls back to the default model});本页的其余部分将更详细地介绍每个 Agent 特性。
Agent 基础
Section titled “Agent 基础”Agent 构造函数接收单个配置对象。最常用的属性如下所示。
| Property | Required | Description |
|---|---|---|
name | yes | 简短、可读的人类标识符。 |
instructions | yes | 系统提示(字符串或函数——参见 动态 instructions)。 |
prompt | no | OpenAI Responses API 的提示配置。参见 Prompt。 |
handoffDescription | no | 当此智能体作为交接工具提供时使用的简短描述。 |
model | no | 模型名称或自定义的 Model 实现。 |
modelSettings | no | 调优参数(temperature、top_p 等)。如果你需要的属性不在顶层,可以将它们放在 providerData 下。 |
tools | no | 模型可调用的 Tool 实例数组。 |
mcpServers | no | 为智能体提供工具的 MCP 服务器。参见 MCP 指南。 |
resetToolChoice | no | 在工具调用后将 toolChoice 重置为默认值(默认:true),以防止工具使用循环。参见 强制使用工具。 |
handoffOutputTypeWarningEnabled | no | 当交接的输出类型不同时发出警告(默认:true)。 |
import { Agent, tool } from '@openai/agents';import { z } from 'zod';
const getWeather = tool({ name: 'get_weather', description: 'Return the weather for a given city.', parameters: z.object({ city: z.string() }), async execute({ city }) { return `The weather in ${city} is sunny.`; },});
const agent = new Agent({ name: 'Weather bot', instructions: 'You are a helpful weather bot.', model: 'gpt-4.1', tools: [getWeather],});智能体对其上下文类型是泛型的——即 Agent<TContext, TOutput>。该上下文是你创建并传递给 Runner.run() 的依赖注入对象。它会被转发到每个工具、护栏、交接等,对于存储状态或提供共享服务(数据库连接、用户元数据、功能开关等)很有用。
import { Agent } from '@openai/agents';
interface Purchase { id: string; uid: string; deliveryStatus: string;}interface UserContext { uid: string; isProUser: boolean;
// this function can be used within tools fetchPurchases(): Promise<Purchase[]>;}
const agent = new Agent<UserContext>({ name: 'Personal shopper', instructions: 'Recommend products the user will love.',});
// Laterimport { run } from '@openai/agents';
const result = await run(agent, 'Find me a new pair of running shoes', { context: { uid: 'abc', isProUser: true, fetchPurchases: async () => [] },});默认情况下,Agent 返回纯文本(string)。如果你希望模型返回结构化对象,可以指定 outputType 属性。SDK 接受:
- Zod 模式(
z.object({...}))。 - 任何兼容 JSON Schema 的对象。
import { Agent } from '@openai/agents';import { z } from 'zod';
const CalendarEvent = z.object({ name: z.string(), date: z.string(), participants: z.array(z.string()),});
const extractor = new Agent({ name: 'Calendar extractor', instructions: 'Extract calendar events from the supplied text.', outputType: CalendarEvent,});当提供 outputType 时,SDK 会自动使用
structured outputs 而不是纯文本。
多智能体系统设计模式
Section titled “多智能体系统设计模式”组合智能体的方式很多。在生产应用中我们经常看到两种模式:
- Manager (agents as tools)——一个中心智能体掌控对话,并调用以工具形式暴露的专业智能体。
- 交接(Handoffs)——初始智能体在识别出用户请求后,将整个对话委派给专家智能体。
这两种方法是互补的。Manager 让你可以在一个地方实施护栏或速率限制,而交接则让每个智能体专注于单一任务,而无需持续控制对话。
Manager (agents as tools)
Section titled “Manager (agents as tools)”在这种模式下,manager 从不移交控制权——LLM 使用工具,manager 总结最终答案。详见 工具指南。
import { Agent } from '@openai/agents';
const bookingAgent = new Agent({ name: 'Booking expert', instructions: 'Answer booking questions and modify reservations.',});
const refundAgent = new Agent({ name: 'Refund expert', instructions: 'Help customers process refunds and credits.',});
const customerFacingAgent = new Agent({ name: 'Customer-facing agent', instructions: 'Talk to the user directly. When they need booking or refund help, call the matching tool.', tools: [ bookingAgent.asTool({ toolName: 'booking_expert', toolDescription: 'Handles booking questions and requests.', }), refundAgent.asTool({ toolName: 'refund_expert', toolDescription: 'Handles refund questions and requests.', }), ],});在交接中,分诊智能体负责路由请求,但一旦发生交接,专家智能体将拥有对话的控制权,直到其产生最终输出。这样可以保持提示简短,并让你可以独立地推理每个智能体。了解更多参见交接指南。
import { Agent } from '@openai/agents';
const bookingAgent = new Agent({ name: 'Booking Agent', instructions: 'Help users with booking requests.',});
const refundAgent = new Agent({ name: 'Refund Agent', instructions: 'Process refund requests politely and efficiently.',});
// Use Agent.create method to ensure the finalOutput type considers handoffsconst triageAgent = Agent.create({ name: 'Triage Agent', instructions: `Help the user with their questions. If the user asks about booking, hand off to the booking agent. If the user asks about refunds, hand off to the refund agent.`.trimStart(), handoffs: [bookingAgent, refundAgent],});高级配置与运行时控制
Section titled “高级配置与运行时控制”动态 instructions
Section titled “动态 instructions”instructions 可以是函数而不是字符串。该函数接收当前的 RunContext 和 Agent 实例,并可以返回字符串或 Promise<string>。
import { Agent, RunContext } from '@openai/agents';
interface UserContext { name: string;}
function buildInstructions(runContext: RunContext<UserContext>) { return `The user's name is ${runContext.context.name}. Be extra friendly!`;}
const agent = new Agent<UserContext>({ name: 'Personalized helper', instructions: buildInstructions,});同时支持同步和 async 函数。
生命周期钩子
Section titled “生命周期钩子”对于高级用例,你可以通过监听事件来观察 Agent 的生命周期。
Agent 实例会为该特定实例发出生命周期事件,而 Runner 会在整个运行过程中以单个流的方式发出相同的事件名称。这对于你希望在一个地方观察交接和工具调用的多智能体工作流很有用。
共享事件名称如下:
| Event | Agent hook arguments | Runner hook arguments |
|---|---|---|
agent_start | (context, agent, turnInput?) | (context, agent, turnInput?) |
agent_end | (context, output) | (context, agent, output) |
agent_handoff | (context, nextAgent) | (context, fromAgent, toAgent) |
agent_tool_start | (context, tool, { toolCall }) | (context, agent, tool, { toolCall }) |
agent_tool_end | (context, tool, result, { toolCall }) | (context, agent, tool, result, { toolCall }) |
import { Agent } from '@openai/agents';
const agent = new Agent({ name: 'Verbose agent', instructions: 'Explain things thoroughly.',});
agent.on('agent_start', (ctx, agent) => { console.log(`[${agent.name}] started`);});agent.on('agent_end', (ctx, output) => { console.log(`[agent] produced:`, output);});护栏允许你验证或转换用户输入和智能体输出。它们通过 inputGuardrails 和 outputGuardrails 数组进行配置。详情参见护栏指南。
克隆 / 复制智能体
Section titled “克隆 / 复制智能体”需要现有智能体的轻微变体?使用 clone() 方法,它会返回一个全新的 Agent 实例。
import { Agent } from '@openai/agents';
const pirateAgent = new Agent({ name: 'Pirate', instructions: 'Respond like a pirate – lots of “Arrr!”', model: 'gpt-5-mini',});
const robotAgent = pirateAgent.clone({ name: 'Robot', instructions: 'Respond like a robot – be precise and factual.',});强制使用工具
Section titled “强制使用工具”提供工具并不保证 LLM 会调用它。你可以通过 modelSettings.toolChoice 强制使用工具:
'auto'(默认)——LLM 决定是否使用工具。'required'——LLM 必须 调用某个工具(可自行选择)。'none'——LLM 必须不调用工具。- 指定工具名,例如
'calculator'——LLM 必须调用该特定工具。
import { Agent, tool } from '@openai/agents';import { z } from 'zod';
const calculatorTool = tool({ name: 'Calculator', description: 'Use this tool to answer questions about math problems.', parameters: z.object({ question: z.string() }), execute: async (input) => { throw new Error('TODO: implement this'); },});
const agent = new Agent({ name: 'Strict tool user', instructions: 'Always answer using the calculator tool.', tools: [calculatorTool], modelSettings: { toolChoice: 'auto' },});防止无限循环
Section titled “防止无限循环”在工具调用后,SDK 会自动将 toolChoice 重置回 'auto'。这可防止模型陷入反复尝试调用工具的无限循环。你可以通过 resetToolChoice 标志或配置 toolUseBehavior 来覆盖此行为:
'run_llm_again'(默认)——使用工具结果再次运行 LLM。'stop_on_first_tool'——将第一个工具结果视为最终答案。{ stopAtToolNames: ['my_tool'] }——当调用任一列出的工具时停止。(context, toolResults) => ...——返回是否应结束运行的自定义函数。
const agent = new Agent({ ..., toolUseBehavior: 'stop_on_first_tool',});注意:toolUseBehavior 仅适用于函数工具。托管工具总是会返回给模型进行处理。