运行智能体
智能体本身不会执行任何操作——需要通过 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 对象。
其他选项包括:
| Option | Default | Description |
|---|---|---|
stream | false | 如果为 true,调用将返回 StreamedRunResult,并在模型产生事件时实时发出。 |
context | – | 转发给每个 tool / guardrail / handoff 的上下文对象。详见上下文管理。 |
maxTurns | 10 | 安全上限——达到时抛出 MaxTurnsExceededError。 |
signal | – | 用于取消的 AbortSignal。 |
流式传输允许你在 LLM 运行期间额外接收流式事件。流启动后,StreamedRunResult 将包含关于此次运行的完整信息,包括所有新产生的输出。你可以使用 for await 循环遍历流式事件。详见流式传输。
如果你在创建自己的 Runner 实例时,可以传入 RunConfig 对象来配置 runner。
| Field | Type | Purpose |
|---|---|---|
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