コンテンツにスキップ

人間の介入(HITL)

このガイドでは、SDK に組み込まれている Human in the loop (人間の介入) サポートを利用し、ユーザーの介入に応じてエージェントの実行を一時停止・再開する方法を説明します。

現在の主なユースケースは、機密性の高いツール実行に対して承認を求めることです。

needsApproval オプションを true に設定するか、真偽値を返す非同期関数を指定すると、承認が必要なツールを定義できます。

ツール承認の定義
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
},
});
  1. エージェントがツール(複数可)を呼び出そうとすると、まず needsApproval を評価してそのツールに承認が必要か確認します。
  2. 承認が必要な場合、エージェントはすでに承認済みか拒否済みかを確認します。
    • 承認も拒否もされていない場合、ツールは「実行できない」という固定メッセージをエージェントへ返します。
    • 承認/拒否が未決定の場合、ツール承認リクエストを発行します。
  3. エージェントはすべてのツール承認リクエストを収集し、実行を中断します。
  4. 中断がある場合、エージェントの実行結果 には保留中のステップを示す interruptions 配列が含まれます。ツール呼び出しに確認が必要なときは、type: "tool_approval_item" を持つ ToolApprovalItem が挿入されます。
  5. result.state.approve(interruption) または result.state.reject(interruption) を呼び出してツール呼び出しを承認または拒否できます。
  6. すべての中断を処理したら、result.staterunner.run(agent, state) に渡して実行を再開します。ここで agent は元のエージェントです。
  7. 以上のフローがステップ 1 から再開されます。

以下は、ターミナルで承認を求め、状態を一時的にファイルへ保存する Human in the loop フローのより完全な例です。

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 フローは、サーバーを常時稼働させなくても長時間中断できるよう設計されています。リクエストを一旦終了し、後で続行する必要がある場合は、状態をシリアライズしてから再開できます。

JSON.stringify(result.state) で状態をシリアライズし、後で RunState.fromString(agent, serializedState) にシリアライズ済み状態を渡して再開します。ここで agent は元のエージェントのインスタンスです。

この方法で、シリアライズした状態をデータベースやリクエストと一緒に保存できます。

保留中タスクのバージョン管理

Section titled “保留中タスクのバージョン管理”

承認に時間がかかり、エージェント定義を意味のある形でバージョン管理したい、または Agents SDK のバージョンを上げたい場合は、パッケージエイリアスを使って Agents SDK を 2 つ並行インストールし、独自のブランチロジックを実装することを推奨します。

実際には、独自のコードにバージョン番号を割り当て、それをシリアライズした状態と共に保存し、デシリアライズ時に正しいコードバージョンへ誘導する形になります。