コンテンツにスキップ

エージェント

OpenAI Agents SDK の主要な構成要素は エージェント です。Agent とは、次のように設定された Large Language Model (LLM) を指します。

  • Instructions – モデルに 自分が何者であるかどのように応答すべきか を伝えるシステムプロンプト
  • Model – 呼び出す OpenAI モデル名と、任意のモデルチューニングパラメーター
  • Tools – タスクを達成するために LLM が呼び出せる関数や API の一覧
Basic Agent definition
import { Agent } from '@openai/agents';
const agent = new Agent({
name: 'Haiku Agent',
instructions: 'Always respond in haiku form.',
model: 'o4-mini', // optional – falls back to the default model
});

以下では、エージェントの各機能を詳しく説明します。


Agent コンストラクターは 1 つの設定オブジェクトを受け取ります。よく利用されるプロパティは次のとおりです。

PropertyRequiredDescription
nameyes人間が読みやすい短い識別子
instructionsyesシステムプロンプト (文字列 または 関数 – 動的 instructions を参照)
modelnoモデル名 または カスタム Model 実装
modelSettingsnoチューニングパラメーター (temperature, top_p など)
toolsnoモデルが呼び出せる Tool インスタンスの配列
Agent with tools
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: 'o4-mini',
tools: [getWeather],
});

エージェントは コンテキスト型をジェネリック として受け取ります。つまり Agent<TContext, TOutput> です。コンテキスト はあなたが作成し Runner.run() に渡す依存性注入オブジェクトで、すべてのツール、ガードレール、ハンドオフなどに転送されます。状態の保持や共有サービス(データベース接続、ユーザーメタデータ、フィーチャーフラグなど)の提供に便利です。

Agent with context
import { Agent } from '@openai/agents';
interface Purchase {
id: string;
uid: string;
deliveryStatus: string;
}
interface UserContext {
uid: string;
isProUser: boolean;
// this function can be used within tools
fetchPurchases(): Promise<Purchase[]>;
}
const agent = new Agent<UserContext>({
name: 'Personal shopper',
instructions: 'Recommend products the user will love.',
});
// Later
import { run } from '@openai/agents';
const result = await run(agent, 'Find me a new pair of running shoes', {
context: { uid: 'abc', isProUser: true, fetchPurchases: async () => [] },
});

デフォルトでは、エージェントは プレーンテキスト (string) を返します。モデルに構造化オブジェクトを返させたい場合は outputType プロパティを指定します。SDK では次のいずれかを受け付けます。

  1. Zod スキーマ (z.object({...}))
  2. JSON-schema 互換オブジェクト
Structured output with Zod
import { Agent } from '@openai/agents';
import { z } from 'zod';
const CalendarEvent = z.object({
name: z.string(),
date: z.string(),
participants: z.array(z.string()),
});
const extractor = new Agent({
name: 'Calendar extractor',
instructions: 'Extract calendar events from the supplied text.',
outputType: CalendarEvent,
});

outputType が指定されると、SDK はプレーンテキストの代わりに structured outputs を自動的に使用します。


エージェントは handoffs プロパティを通じて他のエージェントへ 委譲 できます。一般的なパターンとして、トリアージエージェント が会話をより専門的なサブエージェントへルーティングします。

Agent with handoffs
import { Agent } from '@openai/agents';
const bookingAgent = new Agent({
name: 'Booking Agent',
instructions: 'Help users with booking requests.',
});
const refundAgent = new Agent({
name: 'Refund Agent',
instructions: 'Process refund requests politely and efficiently.',
});
// Use Agent.create method to ensure the finalOutput type considers handoffs
const triageAgent = Agent.create({
name: 'Triage Agent',
instructions: [
'Help the user with their questions.',
'If the user asks about booking, hand off to the booking agent.',
'If the user asks about refunds, hand off to the refund agent.',
].join('\n'),
handoffs: [bookingAgent, refundAgent],
});

このパターンの詳細は ハンドオフ を参照してください。


instructions は文字列の代わりに 関数 を受け取ることもできます。この関数には現在の RunContext と Agent インスタンスが渡され、文字列 または Promise<string> を返せます。

Agent with dynamic instructions
import { Agent, RunContext } from '@openai/agents';
interface UserContext {
name: string;
}
function buildInstructions(runContext: RunContext<UserContext>) {
return `The user's name is ${runContext.context.name}. Be extra friendly!`;
}
const agent = new Agent<UserContext>({
name: 'Personalized helper',
instructions: buildInstructions,
});

同期関数と async 関数の両方をサポートしています。


高度なユースケース向けに、イベントリスナーを通じてエージェントのライフサイクルを監視できます。

Agent with lifecycle hooks
import { Agent } from '@openai/agents';
const agent = new Agent({
name: 'Verbose agent',
instructions: 'Explain things thoroughly.',
});
agent.on('agent_start', (ctx, agent) => {
console.log(`[${agent.name}] started`);
});
agent.on('agent_end', (ctx, output) => {
console.log(`[agent] produced:`, output);
});

ガードレールを使用すると、ユーザー入力やエージェント出力の検証・変換が可能です。inputGuardrailsoutputGuardrails 配列で設定します。詳細は ガードレール をご覧ください。


エージェントのクローン/コピー

Section titled “エージェントのクローン/コピー”

既存エージェントを少しだけ変更したい場合は clone() メソッドを使用します。これにより、まったく新しい Agent インスタンスが返されます。

Cloning Agents
import { Agent } from '@openai/agents';
const pirateAgent = new Agent({
name: 'Pirate',
instructions: 'Respond like a pirate – lots of “Arrr!”',
model: 'o4-mini',
});
const robotAgent = pirateAgent.clone({
name: 'Robot',
instructions: 'Respond like a robot – be precise and factual.',
});

ツールを提供しても、LLM が必ずしも呼び出すとは限りません。modelSettings.tool_choice でツール使用を 強制 できます。

  1. 'auto' (デフォルト) – ツールを使うかどうかは LLM が判断
  2. 'required' – LLM は必ずツールを呼び出す (どのツールかは選択可)
  3. 'none' – LLM はツールを呼び出してはならない
  4. 具体的なツール名 (例: 'calculator') – LLM はそのツールを必ず呼び出す
Forcing tool use
import { Agent, tool } from '@openai/agents';
import { z } from 'zod';
const calculatorTool = tool({
name: 'Calculator',
description: 'Use this tool to answer questions about math problems.',
parameters: z.object({ question: z.string() }),
execute: async (input) => {
throw new Error('TODO: implement this');
},
});
const agent = new Agent({
name: 'Strict tool user',
instructions: 'Always answer using the calculator tool.',
tools: [calculatorTool],
modelSettings: { toolChoice: 'auto' },
});

ツール呼び出し後、SDK は自動的に tool_choice'auto' にリセットします。これにより、モデルがツールを繰り返し呼び出す無限ループを防ぎます。この挙動は resetToolChoice フラグ、または toolUseBehavior の設定で上書きできます。

  • 'run_llm_again' (デフォルト) – ツール結果を用いて再度 LLM を実行
  • 'stop_on_first_tool' – 最初のツール結果を最終回答として扱う
  • { stopAtToolNames: ['my_tool'] } – 指定ツールが呼び出されたら停止
  • (context, toolResults) => ... – 実行を終了すべきかを返すカスタム関数
const agent = new Agent({
...,
toolUseBehavior: 'stop_on_first_tool',
});