当您想要以最短路径构建基于 SDK 的智能体时,请参考此页面。以下示例在 TypeScript 和 Python 中使用相同的高级概念:定义智能体、运行它,然后在工作流增长时添加工具和专家智能体。
安装 SDK
创建一个项目,安装 SDK,并设置您的 API 密钥。
创建 API 密钥
1
2
3
4
5
6
7
# TypeScript
npm install @openai/agents zod
# Python
pip install openai-agents
export OPENAI_API_KEY=sk-...创建并运行您的第一个智能体
从一个目标明确的智能体和一轮对话开始。SDK 会处理模型调用并返回包含最终输出和运行历史记录的结果对象。
创建并运行智能体
typescript
1
2
3
4
5
6
7
8
9
10
11
import { Agent, run } from "@openai/agents";
const agent = new Agent({
name: "History tutor",
instructions:
"You answer history questions clearly and concisely.",
model: "gpt-5.5",
});
const result = await run(agent, "When did the Roman Empire fall?");
console.log(result.finalOutput);您应该会在终端中看到简洁的回答。一旦该循环正常工作,保持相同的架构并逐步增加功能,而不是从大型的多智能体设计开始。
将状态传递到下一轮
第一次运行的结果也是您决定第二轮应使用何种状态的依据。
| 如果您希望 | 对于复杂的推理和编码任务,请从 |
|---|---|
| 在应用程序中保留完整历史记录 | result.history |
| 让 SDK 为您加载和保存历史记录 | 会话 (Session) |
| 让 OpenAI 管理延续状态 | 服务器管理的延续 ID |
| 恢复因审批或中断而暂停的运行 | result.stateinterruptions(中断) |
在移交 (Handoff) 后,复用lastAgent
为智能体提供工具
您添加的第一个功能通常是函数工具或托管的 OpenAI 工具(如网页搜索或文件搜索)。
添加函数工具
typescript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import { Agent, run, tool } from "@openai/agents";
import { z } from "zod";
const historyFunFact = tool({
name: "history_fun_fact",
description: "Return a short history fact.",
parameters: z.object({}),
async execute() {
return "Sharks are older than trees.";
},
});
const agent = new Agent({
name: "History tutor",
instructions:
"Answer history questions clearly. Use history_fun_fact when it helps.",
tools: [historyFunFact],
});
const result = await run(
agent,
"Tell me something surprising about ancient life on Earth.",
);
console.log(result.finalOutput);当您需要托管工具、工具搜索或将智能体作为工具使用时,请参考共享的 使用工具 指南。
添加专家智能体
常见的下一步是将工作流拆分为不同的专家,并让路由器通过移交 (handoffs) 将任务委派给它们。
路由至专家智能体
typescript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import { Agent, run } from "@openai/agents";
const historyTutor = new Agent({
name: "History tutor",
instructions: "Answer history questions clearly and concisely.",
});
const mathTutor = new Agent({
name: "Math tutor",
instructions: "Explain math step by step and include worked examples.",
});
const triageAgent = Agent.create({
name: "Homework triage",
instructions: "Route each homework question to the right specialist.",
handoffs: [historyTutor, mathTutor],
});
const result = await run(
triageAgent,
"Who was the first president of the United States?",
);
console.log(result.finalOutput);
console.log(result.lastAgent?.name);尽早检查跟踪记录 (Traces)
正常的服务器端 SDK 路径包含跟踪记录。一旦首次运行成功,请打开 跟踪仪表板 来检查模型调用、工具调用、移交和护栏,然后再开始微调提示词。
后续步骤
一旦首次运行成功,请根据您想要添加的下一个功能,继续阅读相应的指南。