Thanks to visit codestin.com
Credit goes to openai.github.io

コンテンツにスキップ

ハンドオフ

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

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

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

基本的なハンドオフ
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 – 次のエージェントに渡す履歴のフィルター
カスタマイズしたハンドオフ
import { z } from 'zod';
import { Agent, handoff, RunContext } from '@openai/agents';
const FooSchema = z.object({ foo: z.string() });
function onHandoff(ctx: RunContext, input?: { foo: string }) {
console.log('Handoff called with:', input?.foo);
}
const agent = new Agent({ name: 'My agent' });
const handoffObj = handoff(agent, {
onHandoff,
inputType: FooSchema,
toolNameOverride: 'custom_handoff_tool',
toolDescriptionOverride: 'Custom description',
});

ハンドオフを呼び出す際に LLM にデータを提供させたい場合があります。入力スキーマを定義し、handoff() で使用します。

ハンドオフ入力
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 にあります。

入力フィルター
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 を通じて推奨のプレフィックスを提供します。

推奨プロンプト
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.`,
});