智慧體是以 SDK 建構工作流程的核心單元。每個智慧體都包含模型和指示,也可以設定執行時使用的工具、防護機制、MCP 伺服器、任務交接與結構化輸出。
智慧體應包含哪些設定
如果某項決策取決於個別智慧體的職責,就在該智慧體上設定:
| 屬性 | 用途 | 延伸閱讀 |
|---|---|---|
name |
在追蹤記錄、工具介面和交接介面中顯示易於辨識的名稱 | 本頁 |
instructions |
定義智慧體的任務、限制與風格 | 本頁 |
prompt |
在透過 Responses API 執行時使用已儲存的提示詞設定 | 模型與供應商 |
model 與模型設定 |
選擇模型並調整其行為 | 模型與供應商 |
tools |
指定智慧體可直接呼叫的工具 | 使用工具 |
handoffDescription |
說明其他智慧體何時應將任務交給這個智慧體 | 流程編排與任務交接 |
handoffs |
將任務交給其他智慧體 | 流程編排與任務交接 |
outputType |
以結構化輸出取代純文字回傳值 | 本頁 |
| 防護機制與核准 | 設定驗證、阻擋與審查流程 | 防護機制與人工審查 |
| MCP 伺服器與託管的 MCP 工具 | 加入透過 MCP 提供的功能 | 整合與可觀測性 |
從一個職責明確的智慧體開始
先定義一個任務明確的智慧體,只配置完成該任務所需的功能。只有在需要分工、使用不同的指示或工具介面,或採用不同的核准政策時,才新增智慧體。
定義單一智慧體
TypeScript
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-6-astra",
tools: [getWeather],
});設定指示、任務交接與輸出
以下三項設定需要特別留意:
- 先使用靜態
instructions。如果指示會因目前的使用者、租戶或執行時的上下文而異,請改用回呼函式動態產生指示,避免在呼叫處拼接字串。 的說明應簡短具體,讓負責路由的智慧體知道何時該選擇這個專責智慧體。handoffDescription- 如果下游程式碼需要具備明確型別的資料,而非自由格式的文字,請使用
。outputType
回傳結構化輸出
TypeScript
import { Agent, run } from "@openai/agents";
import { z } from "zod";
const calendarEvent = z.object({
name: z.string(),
date: z.string(),
participants: z.array(z.string()),
});
const agent = new Agent({
name: "Calendar extractor",
instructions: "Extract calendar events from text.",
outputType: calendarEvent,
});
const result = await run(agent, "Dinner with Priya and Sam on Friday.");
console.log(result.finalOutput);若要從 Responses API 引用已儲存的提示詞設定,請使用 prompt,這樣就不必將整段系統提示詞嵌入程式碼。
區分本機上下文與模型上下文
SDK 可讓你在執行時傳入應用程式狀態與相依項目,而無須將這些內容傳送給模型。這種做法適用於已驗證身分的使用者資訊、資料庫用戶端、日誌記錄器和輔助函式等。
將本機上下文傳給工具
TypeScript
import { Agent, run, tool, type RunContext } from "@openai/agents";
import { z } from "zod";
const fetchUserAge = tool({
name: "fetch_user_age",
description: "Return the age of the current user.",
parameters: z.object({}),
async execute(
_args: unknown,
runContext: RunContext<{ name: string; uid: number }> | undefined
) {
return `User ${runContext?.context.name} is 47 years old`;
},
});
const agent = new Agent({
name: "Assistant",
tools: [fetchUserAge],
});
const result = await run(agent, "What is the age of the user?", {
context: { name: "John", uid: 123 },
});
console.log(result.finalOutput);兩者的差別在於誰能讀取這些內容:
- 模型能讀取對話記錄。
- 程式碼能讀取執行上下文。
如果模型需要某項資訊,請將它寫入指示或輸入,或透過檢索或工具提供。如果只有執行環境需要這項資訊,就將它保留在本機上下文中。
何時將一個智慧體拆分為多個
如果整則回覆不宜由單一專責智慧體負責,或各項功能有實質差異,就可以拆分智慧體。常見原因包括:
- 某個專責智慧體需要不同的工具或 MCP 介面。
- 某個專責智慧體需要不同的核准政策或防護機制。
- 工作流程中的某個分支需要不同的模型或輸出風格。
- 你希望在追蹤記錄中清楚看到任務如何分派,而非由單一冗長的提示詞決定。
後續步驟
明確定義第一個專責智慧體後,請根據接下來要解決的設計問題,選讀相應的指南。