如需完整的文件索引,請參閱 llms.txt。在文件頁面的網址末尾加上 .md ,即可取得該頁面的 Markdown 版本。
主要導覽
主題

快速入門

使用 TypeScript 或 Python 搭配 Agents SDK 建立你的第一個智慧體。

這份指南帶你用最少的步驟建立可執行的 SDK 智慧體。以下 TypeScript 和 Python 範例採用相同的做法:先定義並執行一個智慧體,再隨著工作流程擴充,加入工具與專責智慧體。

安裝 SDK

建立專案、安裝 SDK,並設定 API 金鑰。

建立 API 金鑰

# TypeScript
npm install @openai/agents zod

# Python
pip install openai-agents

export OPENAI_API_KEY=sk-...

建立並執行你的第一個智慧體

先建立一個職責明確的智慧體,執行一輪對話。SDK 會呼叫模型,並傳回包含最終輸出與執行歷程的結果物件。

建立並執行智慧體
import { Agent, run } from "@openai/agents";

const agent = new Agent({
  name: "History tutor",
  instructions: "You answer history questions clearly and concisely.",
  model: "gpt-6-astra",
});

const result = await run(agent, "When did the Roman Empire fall?");
console.log(result.finalOutput);

你應該會在終端看到簡短的回答。確認這個迴圈能正常運作後,沿用同樣的架構逐步加入功能,不必一開始就設計大型多智慧體系統。

將狀態帶入下一輪對話

你也可以根據第一輪的執行結果,決定第二輪要沿用哪些狀態。

需求 可使用的方式
在應用程式中保留完整歷程 result.history
讓 SDK 載入並儲存歷程 工作階段
讓 OpenAI 管理接續對話所需的狀態 由伺服器管理的接續 ID
繼續先前因等待核准或遇到中斷而暫停的執行流程 result.state 搭配 interruptions

交接後,如果下一輪仍應由接手的專責智慧體主導,請沿用 lastAgent。

為智慧體加入工具

為智慧體擴充功能時,通常會先加入函式工具,或使用 OpenAI 託管的工具,例如網頁搜尋或檔案搜尋。

加入函式工具
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);

如果你需要使用託管工具、搜尋可用的工具,或將智慧體當作工具使用,請參閱通用的使用工具指南。

加入專責智慧體

接下來,常見的做法是把工作流程拆成多項任務,再由負責路由的智慧體透過交接,將任務交給對應的專責智慧體處理。

將任務分派給專責智慧體
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);

及早檢查追蹤記錄

在伺服器端以一般方式執行 SDK 時,SDK 會記錄執行過程。首次執行成功後,請開啟追蹤儀表板,先檢查模型呼叫、工具呼叫、交接與防護機制的運作情形,再開始調整提示詞。

後續步驟

首次執行成功後,可依接下來想加入的功能,選讀對應的指南。