人間の介入(HITL)
このガイドでは、エージェントの実行を人間の介入で一時停止・再開できる、組み込みの Human-in-the-loop 機能の使い方を説明します。
主なユースケースは、機密度の高いツール呼び出しに対する承認の取得です。
承認リクエスト
Section titled “承認リクエスト”needsApproval
オプションを true
、または boolean を返す非同期関数に設定すると、承認が必要なツールを定義できます。
import { tool } from '@openai/agents';import z from 'zod';
const sensitiveTool = tool({ name: 'cancelOrder', description: 'Cancel order', parameters: z.object({ orderId: z.number(), }), // always requires approval needsApproval: true, execute: async ({ orderId }, args) => { // prepare order return },});
const sendEmail = tool({ name: 'sendEmail', description: 'Send an email', parameters: z.object({ to: z.string(), subject: z.string(), body: z.string(), }), needsApproval: async (_context, { subject }) => { // check if the email is spam return subject.includes('spam'); }, execute: async ({ to, subject, body }, args) => { // send email },});
- エージェントがツール(複数可)を呼び出そうとすると、
needsApproval
を評価してそのツールが承認を必要とするか確認します - 承認が必要な場合、エージェントは承認がすでに許可・拒否されているかを確認します
- まだ許可・拒否されていない場合、ツールは「ツール呼び出しを実行できない」という固定メッセージをエージェントに返します
- 許可 / 拒否が未決の場合、ツール承認リクエストをトリガーします
- エージェントはすべてのツール承認リクエストを集め、実行を中断します
- 中断がある場合、実行結果 には保留中のステップを示す
interruptions
配列が含まれます。ツール呼び出しに確認が必要なときはtype: "tool_approval_item"
のToolApprovalItem
が現れます result.state.approve(interruption)
またはresult.state.reject(interruption)
を呼び出してツール呼び出しを許可・拒否できます- すべての中断を処理したら、
result.state
をrunner.run(agent, state)
に渡して実行を再開します。ここでagent
は最初に実行を開始させたエージェントです - フローは 1 に戻ります
以下は、ターミナルで承認を促し、一時的に state をファイルへ保存する Human-in-the-loop フローの、より完全な例です。
import { z } from 'zod';import readline from 'node:readline/promises';import fs from 'node:fs/promises';import { Agent, run, tool, RunState, RunResult } from '@openai/agents';
const getWeatherTool = tool({ name: 'get_weather', description: 'Get the weather for a given city', parameters: z.object({ location: z.string(), }), needsApproval: async (_context, { location }) => { // forces approval to look up the weather in San Francisco return location === 'San Francisco'; }, execute: async ({ location }) => { return `The weather in ${location} is sunny`; },});
const dataAgentTwo = new Agent({ name: 'Data agent', instructions: 'You are a data agent', handoffDescription: 'You know everything about the weather', tools: [getWeatherTool],});
const agent = new Agent({ name: 'Basic test agent', instructions: 'You are a basic agent', handoffs: [dataAgentTwo],});
async function confirm(question: string) { const rl = readline.createInterface({ input: process.stdin, output: process.stdout, });
const answer = await rl.question(`${question} (y/n): `); const normalizedAnswer = answer.toLowerCase(); rl.close(); return normalizedAnswer === 'y' || normalizedAnswer === 'yes';}
async function main() { let result: RunResult<unknown, Agent<unknown, any>> = await run( agent, 'What is the weather in Oakland and San Francisco?', ); let hasInterruptions = result.interruptions?.length > 0; while (hasInterruptions) { // storing await fs.writeFile( 'result.json', JSON.stringify(result.state, null, 2), 'utf-8', );
// from here on you could run things on a different thread/process
// reading later on const storedState = await fs.readFile('result.json', 'utf-8'); const state = await RunState.fromString(agent, storedState);
for (const interruption of result.interruptions) { const confirmed = await confirm( `Agent ${interruption.agent.name} would like to use the tool ${interruption.rawItem.name} with "${interruption.rawItem.arguments}". Do you approve?`, );
if (confirmed) { state.approve(interruption); } else { state.reject(interruption); } }
// resume execution of the current state result = await run(agent, state); hasInterruptions = result.interruptions?.length > 0; }
console.log(result.finalOutput);}
main().catch((error) => { console.dir(error, { depth: null });});
動作するエンドツーエンド版は 完全なスクリプト を参照してください。
長時間の承認待ちへの対応
Section titled “長時間の承認待ちへの対応”Human-in-the-loop フローは、サーバーを起動し続けなくても長時間一時停止できるよう設計されています。リクエストを終了して後で続行したい場合、state をシリアライズして後で再開できます。
JSON.stringify(result.state)
で state をシリアライズし、後で RunState.fromString(agent, serializedState)
にシリアライズ済みの state を渡して再開します。ここで agent
は実行を開始させたエージェントのインスタンスです。
この方法で、シリアライズした state をデータベースやリクエストと一緒に保存できます。
保留タスクのバージョニング
Section titled “保留タスクのバージョニング”承認に時間がかかり、エージェント定義を意味のある形でバージョン管理したい、または Agents SDK のバージョンを上げたい場合、現時点では package alias を使って 2 つの Agents SDK を並行インストールし、独自にブランチロジックを実装することを推奨します。
実際には、独自にコードのバージョン番号を割り当て、それをシリアライズした state と一緒に保存し、デシリアライズ時に正しいコードバージョンへ誘導する形になります。