コンテンツにスキップ

ハンドオフ

ハンドオフを使用すると、あるエージェントが会話の一部を別のエージェントに委任できます。これは、エージェントごとに得意分野が異なる場合に便利です。たとえばカスタマーサポートアプリでは、予約、返金、FAQ を担当するエージェントを用意できます。

ハンドオフは LLM にはツールとして表現されます。Refund Agent というエージェントへハンドオフする場合、ツール名は transfer_to_refund_agent になります。

すべてのエージェントは handoffs オプションを受け取れます。ここには、他の Agent インスタンスや handoff() ヘルパーが返す Handoff オブジェクトを含められます。

Basic handoffs
import { Agent, handoff } from '@openai/agents';
const billingAgent = new Agent({ name: 'Billing agent' });
const refundAgent = new Agent({ name: 'Refund agent' });
// Use Agent.create method to ensure the finalOutput type considers handoffs
const triageAgent = Agent.create({
name: 'Triage agent',
handoffs: [billingAgent, handoff(refundAgent)],
});

handoff() によるハンドオフのカスタマイズ

Section titled “handoff() によるハンドオフのカスタマイズ”

handoff() 関数を使うと、生成されるツールを細かく調整できます。

  • agent – ハンドオフ先のエージェント
  • toolNameOverride – 既定の transfer_to_<agent_name> ツール名を上書き
  • toolDescriptionOverride – 既定のツール説明を上書き
  • onHandoff – ハンドオフ発生時に呼び出されるコールバック。RunContext と、オプションで解析済み入力を受け取る
  • inputType – ハンドオフ時に期待される入力スキーマ
  • inputFilter – 次のエージェントに渡す履歴をフィルタリング
Customized handoffs
import { Agent, handoff, RunContext } from '@openai/agents';
function onHandoff(ctx: RunContext) {
console.log('Handoff called');
}
const agent = new Agent({ name: 'My agent' });
const handoffObj = handoff(agent, {
onHandoff,
toolNameOverride: 'custom_handoff_tool',
toolDescriptionOverride: 'Custom description',
});

ハンドオフを呼び出す際に LLM にデータを渡してほしい場合があります。その場合は入力スキーマを定義し、handoff() で指定します。

Handoff inputs
import { z } from 'zod';
import { Agent, handoff, RunContext } from '@openai/agents';
const EscalationData = z.object({ reason: z.string() });
type EscalationData = z.infer<typeof EscalationData>;
async function onHandoff(
ctx: RunContext<EscalationData>,
input: EscalationData | undefined,
) {
console.log(`Escalation agent called with reason: ${input?.reason}`);
}
const agent = new Agent<EscalationData>({ name: 'Escalation agent' });
const handoffObj = handoff(agent, {
onHandoff,
inputType: EscalationData,
});

デフォルトでは、ハンドオフ先は会話履歴全体を受け取ります。次のエージェントに渡す内容を変更したい場合は inputFilter を提供します。共通のヘルパーは @openai/agents-core/extensions に含まれています。

Input filters
import { Agent, handoff } from '@openai/agents';
import { removeAllTools } from '@openai/agents-core/extensions';
const agent = new Agent({ name: 'FAQ agent' });
const handoffObj = handoff(agent, {
inputFilter: removeAllTools,
});

プロンプトにハンドオフを明示すると、LLM の応答が安定します。SDK では RECOMMENDED_PROMPT_PREFIX として推奨のプレフィックスを提供しています。

Recommended prompts
import { Agent } from '@openai/agents';
import { RECOMMENDED_PROMPT_PREFIX } from '@openai/agents-core/extensions';
const billingAgent = new Agent({
name: 'Billing agent',
instructions: `${RECOMMENDED_PROMPT_PREFIX}
Fill in the rest of your prompt here.`,
});