このページでは、SDK を使ってエージェントを動かすまでの最短手順を紹介します。以下の例では、JavaScript でも Python でも基本的な流れは同じです。まずエージェントを定義して実行し、ワークフローの拡張に合わせてツールや専門エージェントを追加します。
SDK のインストール
プロジェクトを作成し、SDK をインストールして、API キーを設定します。
API キーを作成
# JavaScript
npm install @openai/agents zod
# Python
pip install openai-agents
export OPENAI_API_KEY=sk-...
最初のエージェントの作成と実行
まずは役割を絞ったエージェントを 1 つ作成し、1 ターンだけ実行します。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);ターミナルに簡潔な回答が表示されます。この流れが動作することを確認したら、最初から複数のエージェントで大規模な構成を組むのではなく、今の構成のまま段階的に機能を追加していきます。
次のターンへの状態の引き継ぎ
初回の実行結果をもとに、2 ターン目にどの状態を引き継ぐかを決めます。
| 目的 | 使用するもの |
|---|---|
| アプリケーションで履歴全体を保持する | result.history |
| 履歴の読み込みと保存を SDK に任せる | セッション |
| 実行を継続するための状態管理を OpenAI に任せる | サーバーが管理する継続 ID |
| 承認待ちや割り込みで一時停止した実行を再開する | result.stateinterruptions の組み合わせ |
ハンドオフの後も同じ専門エージェントに会話を任せる場合は、次のターンで 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 を通常どおり実行すると、トレースが記録されます。初回の実行に成功したら、プロンプトの調整を始める前に、トレースダッシュボードを開き、モデルやツールの呼び出し、ハンドオフ、ガードレールの動作を確認してください。
次のステップ
初回の実行に成功したら、次に追加したい機能に合ったガイドに進んでください。