运行智能体
智能体不会自行执行——您需要使用 Runner 类或 run() 工具来运行它们。
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.当您不需要自定义 runner 时,也可以使用 run() 工具,它会运行一个单例的默认 Runner 实例。
或者,您也可以创建自己的 runner 实例:
import { Agent, Runner } from '@openai/agents';
const agent = new Agent({ name: 'Assistant', instructions: 'You are a helpful assistant',});
// You can pass custom configuration to the runnerconst runner = new Runner();
const result = await runner.run( agent, 'Write a haiku about recursion in programming.',);console.log(result.finalOutput);
// Code within the code,// Functions calling themselves,// Infinite loop's dance.运行智能体后,您将收到一个运行结果对象,其中包含最终输出和完整的运行历史。
当您在 Runner 中使用 run 方法时,需要传入一个起始智能体和输入。输入可以是字符串(被视为用户消息),也可以是输入项列表,即 OpenAI Responses API 中的项目。
runner 会执行如下循环:
- 使用当前输入调用当前智能体的模型。
- 检查 LLM 响应。
- 最终输出 → 返回。
- 交接 → 切换到新智能体,保留累积的对话历史,回到步骤 1。
- 工具调用 → 执行工具,将其结果追加到对话中,回到步骤 1。
- 一旦达到
maxTurns,抛出MaxTurnsExceededError。
Runner 生命周期
Section titled “Runner 生命周期”在应用启动时创建一个 Runner 并在请求间复用。该实例存储全局配置,如模型提供方和追踪选项。只有在需要完全不同的设置时才创建另一个 Runner。对于简单脚本,您也可以直接调用 run(),它会在内部使用默认 runner。
run() 方法的输入包括用于启动运行的初始智能体、运行的输入以及一组选项。
输入可以是字符串(被视为用户消息)、输入项列表,或在构建人机协作智能体时使用的 RunState 对象。
其他选项包括:
| 选项 | 默认值 | 说明 |
|---|---|---|
stream | false | 若为 true,调用将返回 StreamedRunResult 并在事件从模型到达时发出这些事件。 |
context | – | 传递给每个 tool / guardrail / handoff 的上下文对象。详见上下文管理指南。 |
maxTurns | 10 | 安全限制——达到时抛出 MaxTurnsExceededError。 |
signal | – | 用于取消的 AbortSignal。 |
流式传输允许您在 LLM 运行时接收额外的流式事件。一旦流开始,StreamedRunResult 将包含关于本次运行的完整信息,包括所有新产生的输出。您可以使用 for await 循环迭代这些流式事件。参阅流式传输指南。
如果您要创建自己的 Runner 实例,可以传入一个 RunConfig 对象来配置 runner。
| 字段 | 类型 | 目的 |
|---|---|---|
model | string | Model | 为运行中的所有智能体强制指定特定模型。 |
modelProvider | ModelProvider | 解析模型名称——默认为 OpenAI 提供方。 |
modelSettings | ModelSettings | 全局调参,覆盖每个智能体的设置。 |
handoffInputFilter | HandoffInputFilter | 进行交接时变换输入项(若交接本身未定义该行为)。 |
inputGuardrails | InputGuardrail[] | 应用于“初始”用户输入的护栏。 |
outputGuardrails | OutputGuardrail[] | 应用于“最终”输出的护栏。 |
tracingDisabled | boolean | 完全禁用 OpenAI 追踪。 |
traceIncludeSensitiveData | boolean | 在仍然发出 span 的同时,将 LLM/工具的输入与输出从追踪中排除。 |
workflowName | string | 显示在 Traces 仪表盘中——有助于分组相关运行。 |
traceId / groupId | string | 手动指定 trace 或 group ID,而不是由 SDK 自动生成。 |
traceMetadata | Record<string, any> | 要附加到每个 span 的任意元数据。 |
会话 / 聊天线程
Section titled “会话 / 聊天线程”每次调用 runner.run()(或 run() 工具)代表您应用层对话中的一个轮次。您可自行决定展示多少 RunResult 给终端用户——有时仅展示 finalOutput,有时展示每个生成的项目。
import { Agent, run } from '@openai/agents';import type { AgentInputItem } from '@openai/agents';
let thread: AgentInputItem[] = [];
const agent = new Agent({ name: 'Assistant',});
async function userSays(text: string) { const result = await run( agent, thread.concat({ role: 'user', content: text }), );
thread = result.history; // Carry over history + newly generated items return result.finalOutput;}
await userSays('What city is the Golden Gate Bridge in?');// -> "San Francisco"
await userSays('What state is it in?');// -> "California"交互式版本参见聊天示例。
服务器托管的会话
Section titled “服务器托管的会话”您可以让 OpenAI Responses API 为您持久化对话历史,而无需在每一轮发送整个本地记录。这在协调长对话或多个服务时很有用。详情参见对话状态指南。
OpenAI 提供两种复用服务器端状态的方式:
1. 针对整个会话的 conversationId
Section titled “1. 针对整个会话的 conversationId”您可以使用 Conversations API 创建一次会话,然后在每一轮复用其 ID。SDK 会自动仅包含新生成的项目。
import { Agent, run } from '@openai/agents';import { OpenAI } from 'openai';
const agent = new Agent({ name: 'Assistant', instructions: 'Reply very concisely.',});
async function main() { // Create a server-managed conversation: const client = new OpenAI(); const { id: conversationId } = await client.conversations.create({});
const first = await run(agent, 'What city is the Golden Gate Bridge in?', { conversationId, }); console.log(first.finalOutput); // -> "San Francisco"
const second = await run(agent, 'What state is it in?', { conversationId }); console.log(second.finalOutput); // -> "California"}
main().catch(console.error);2. 使用 previousResponseId 从上一轮继续
Section titled “2. 使用 previousResponseId 从上一轮继续”如果您只想从 Responses API 开始,也可以使用前一个响应返回的 ID 串联每次请求。在不创建完整会话资源的情况下跨轮次保持上下文。
import { Agent, run } from '@openai/agents';
const agent = new Agent({ name: 'Assistant', instructions: 'Reply very concisely.',});
async function main() { const first = await run(agent, 'What city is the Golden Gate Bridge in?'); console.log(first.finalOutput); // -> "San Francisco"
const previousResponseId = first.lastResponseId; const second = await run(agent, 'What state is it in?', { previousResponseId, }); console.log(second.finalOutput); // -> "California"}
main().catch(console.error);SDK 会抛出一小组可捕获的错误:
MaxTurnsExceededError– 达到maxTurns。ModelBehaviorError– 模型生成了无效输出(例如格式错误的 JSON、未知工具)。InputGuardrailTripwireTriggered/OutputGuardrailTripwireTriggered– 违反护栏。GuardrailExecutionError– 护栏执行失败。ToolCallError– 任一函数工具调用失败。UserError– 基于配置或用户输入抛出的错误。
这些错误均继承自基础类 AgentsError,该类可能提供 state 属性以访问当前运行状态。
以下是一个处理 GuardrailExecutionError 的示例代码:
import { Agent, run, GuardrailExecutionError, InputGuardrail, InputGuardrailTripwireTriggered,} from '@openai/agents';import { z } from 'zod';
const guardrailAgent = new Agent({ name: 'Guardrail check', instructions: 'Check if the user is asking you to do their math homework.', outputType: z.object({ isMathHomework: z.boolean(), reasoning: z.string(), }),});
const unstableGuardrail: InputGuardrail = { name: 'Math Homework Guardrail (unstable)', execute: async () => { throw new Error('Something is wrong!'); },};
const fallbackGuardrail: InputGuardrail = { name: 'Math Homework Guardrail (fallback)', execute: async ({ input, context }) => { const result = await run(guardrailAgent, input, { context }); return { outputInfo: result.finalOutput, tripwireTriggered: result.finalOutput?.isMathHomework ?? false, }; },};
const agent = new Agent({ name: 'Customer support agent', instructions: 'You are a customer support agent. You help customers with their questions.', inputGuardrails: [unstableGuardrail],});
async function main() { try { const input = 'Hello, can you help me solve for x: 2x + 3 = 11?'; const result = await run(agent, input); console.log(result.finalOutput); } catch (e) { if (e instanceof GuardrailExecutionError) { console.error(`Guardrail execution failed: ${e}`); // If you want to retry the execution with different settings, // you can reuse the runner's latest state this way: if (e.state) { try { agent.inputGuardrails = [fallbackGuardrail]; // fallback const result = await run(agent, e.state); console.log(result.finalOutput); } catch (ee) { if (ee instanceof InputGuardrailTripwireTriggered) { console.log('Math homework guardrail tripped'); } } } } else { throw e; } }}
main().catch(console.error);运行上述示例时,您将看到如下输出:
Guardrail execution failed: Error: Input guardrail failed to complete: Error: Something is wrong!Math homework guardrail tripped