ガードレール
ガードレールはエージェントと並行して実行することも、完了するまで実行をブロックすることもでき、ユーザー入力やエージェント出力に対するチェックと検証を実行できます。たとえば、高コストなモデルを呼び出す前に、軽量なモデルをガードレールとして実行できます。ガードレールが悪意のある使用を検出した場合、エラーを発生させ、高コストなモデルの実行を停止できます。
ガードレールには、次の 2 種類があります。
- 入力ガードレール は、最初のユーザー入力に対して実行されます。
- 出力ガードレール は、最終的なエージェント出力に対して実行されます。
ワークフローの境界
Section titled “ワークフローの境界”ガードレールはエージェントに設定されますが、ワークフロー内のすべてのエージェントで実行されるとは限りません。
- 入力ガードレール は、チェーン内の最初のエージェントに対してのみ実行されます。
- 出力ガードレール は、最終出力を生成するエージェントに対してのみ実行されます。
- ツールガードレール は、関数ツールの呼び出しごとに実行されます。入力ガードレールは実行前に、出力ガードレールは実行後に実行されます。
マネージャーやハンドオフを含むワークフローで、カスタム関数ツールの各呼び出しをチェックする必要がある場合は、エージェントレベルの入出力ガードレールではなく、 ツールガードレール を使用してください。
入力ガードレール
Section titled “入力ガードレール”入力ガードレールは、次の 3 段階で実行されます。
- ガードレールは、エージェントに渡されたものと同じ入力を受け取ります。
- ガードレール関数が実行され、
InputGuardrailResult内にラップされたGuardrailFunctionOutputを返します。 tripwireTriggeredがtrueの場合、InputGuardrailTripwireTriggeredエラーがスローされます。
注記 入力ガードレールはユーザー入力を対象としているため、エージェントがワークフロー内の 最初の エージェントである場合にのみ実行されます。エージェントごとに必要なガードレールが異なることが多いため、ガードレールはエージェント自体に設定されます。
runInParallel: true(デフォルト)では、ガードレールが LLM やツールの呼び出しと並行して開始されます。これによりレイテンシーは最小限になりますが、後からガードレールが作動した場合、その時点ですでにモデルがトークンを消費していたり、ツールが実行されていたりする可能性があります。runInParallel: falseでは、モデルを呼び出す 前に ガードレールを実行し、ガードレールがリクエストをブロックした場合のトークン消費とツール実行を防ぎます。レイテンシーよりも安全性とコストを優先する場合に使用してください。
出力ガードレール
Section titled “出力ガードレール”出力ガードレールは、次の 3 段階で実行されます。
- ガードレールは、エージェントが生成した出力を受け取ります。
- ガードレール関数が実行され、
OutputGuardrailResult内にラップされたGuardrailFunctionOutputを返します。 tripwireTriggeredがtrueの場合、OutputGuardrailTripwireTriggeredエラーがスローされます。
注記 出力ガードレールは、エージェントがワークフロー内の 最後の エージェントである場合にのみ実行されます。リアルタイムの音声インタラクションについては、リアルタイムエージェントの構築を参照してください。
出力ガードレール関数は、基になる modelResponse と、そのターンで生成された出力項目を含む、オプションの details オブジェクトも受け取ります。最終出力だけではレスポンスを許可すべきか判断できない場合に使用します。たとえば、ガードレールを作動させる前に、生成された項目の完全なリストやプロバイダーのレスポンスメタデータを調べる場合です。
ツールガードレール
Section titled “ツールガードレール”ツールガードレールは 関数ツール をラップし、実行前後のツール呼び出しを検証またはブロックできます。ツール自体に(tool() のオプションを介して)設定され、そのツールが呼び出されるたびに実行されます。
実際には、tool({...}) に inputGuardrails や outputGuardrails を設定したカスタム関数ツールが対象です。
- 入力ツールガードレール は、ツールの実行前に実行され、メッセージ付きで呼び出しを拒否するか、トリップワイヤーを発生させることができます。
- 出力ツールガードレール は、ツールの実行後に実行され、出力を拒否メッセージに置き換えるか、トリップワイヤーを発生させることができます。
ローカル関数ツールで人間による承認も必要な場合、入力ツールガードレールは通常、承認後、実行直前に実行されます。保留中の承認リクエストより前にも入力ガードレールを実行するには、run() または Runner で toolExecution: { preApprovalInputGuardrails: true } を設定します。ガードレールは承認後、ツールの実行前にも再度実行されます。
ツールガードレールは behavior を返します。
allow— 次のガードレールまたはツールの実行に進みます。rejectContent— メッセージを返して処理を打ち切ります(ツール呼び出しはスキップされるか、出力が置き換えられます)。throwException— トリップワイヤーエラーを直ちにスローします。
ツールガードレールは、tool() で定義した関数ツールに適用されます。ハンドオフは関数のようなツールとしてモデルに提示されますが、通常の関数ツールのパイプラインではなく、SDK のハンドオフ経路を通じて実行されるため、ツールガードレールはハンドオフ呼び出し自体には適用されません。組み込みツール(Hosted)と組み込み実行ツール(computerTool、shellTool、applyPatchTool)も、このガードレールパイプラインを使用しません。また、agent.asTool() では現在、ツールガードレールのオプションを直接公開していません。
トリップワイヤー
Section titled “トリップワイヤー”ガードレールが失敗すると、トリップワイヤーを通じて通知されます。トリップワイヤーが作動すると、Runner は直ちに対応するエラーをスローし、実行を停止します。
ガードレールの実装
Section titled “ガードレールの実装”ガードレールは、単に GuardrailFunctionOutput を返す関数です。以下は、内部で別のエージェントを実行し、ユーザーが数学の宿題について助けを求めているかどうかを確認する最小限の例です。
import { Agent, run, InputGuardrailTripwireTriggered, InputGuardrail,} from '@openai/agents';import { z } from 'zod';
const guardrailAgent = new Agent({ name: 'Guardrail check', instructions: 'Check if the user is asking you to do their math homework.', outputType: z.object({ isMathHomework: z.boolean(), reasoning: z.string(), }),});
const mathGuardrail: InputGuardrail = { name: 'Math Homework Guardrail', // Set runInParallel to false to block the model until the guardrail completes. runInParallel: false, execute: async ({ input, context }) => { const result = await run(guardrailAgent, input, { context }); return { outputInfo: result.finalOutput, tripwireTriggered: result.finalOutput?.isMathHomework ?? false, }; },};
const agent = new Agent({ name: 'Customer support agent', instructions: 'You are a customer support agent. You help customers with their questions.', inputGuardrails: [mathGuardrail],});
async function main() { try { await run(agent, 'Hello, can you help me solve for x: 2x + 3 = 11?'); throw new Error('Expected the math homework guardrail to trip.'); } catch (e) { if (e instanceof InputGuardrailTripwireTriggered) { console.log('Math homework guardrail tripped'); return; } throw e; }}
main().catch((error) => { console.error(error); process.exit(1);});出力ガードレールも同様に機能します。
import { Agent, run, OutputGuardrailTripwireTriggered, OutputGuardrail,} from '@openai/agents';import { z } from 'zod';
// The output by the main agentconst MessageOutput = z.object({ response: z.string() });type MessageOutput = z.infer<typeof MessageOutput>;
// The output by the math guardrail agentconst MathOutput = z.object({ reasoning: z.string(), isMath: z.boolean() });
// The guardrail agentconst guardrailAgent = new Agent({ name: 'Guardrail check', instructions: 'Check if the output includes any math.', outputType: MathOutput,});
// An output guardrail using an agent internallyconst mathGuardrail: OutputGuardrail<typeof MessageOutput> = { name: 'Math Guardrail', async execute({ agentOutput, context }) { const result = await run(guardrailAgent, agentOutput.response, { context, }); return { outputInfo: result.finalOutput, tripwireTriggered: result.finalOutput?.isMath ?? false, }; },};
const agent = new Agent({ name: 'Support agent', instructions: 'You are a user support agent. You help users with their questions.', outputGuardrails: [mathGuardrail], outputType: MessageOutput,});
async function main() { try { const input = 'Hello, can you help me solve for x: 2x + 3 = 11?'; await run(agent, input); throw new Error('Expected the math output guardrail to trip.'); } catch (e) { if (e instanceof OutputGuardrailTripwireTriggered) { console.log('Math output guardrail tripped'); return; } throw e; }}
main().catch((error) => { console.error(error); process.exit(1);});ツールの入出力ガードレールは次のようになります。
import { Agent, ToolGuardrailFunctionOutputFactory, defineToolInputGuardrail, defineToolOutputGuardrail, tool,} from '@openai/agents';import { z } from 'zod';
const blockSecrets = defineToolInputGuardrail({ name: 'block_secrets', run: async ({ toolCall }) => { const args = JSON.parse(toolCall.arguments) as { text?: string }; if (args.text?.includes('sk-')) { return ToolGuardrailFunctionOutputFactory.rejectContent( 'Remove secrets before calling this tool.', ); } return ToolGuardrailFunctionOutputFactory.allow(); },});
const redactOutput = defineToolOutputGuardrail({ name: 'redact_output', run: async ({ output }) => { const text = String(output ?? ''); if (text.includes('sk-')) { return ToolGuardrailFunctionOutputFactory.rejectContent( 'Output contained sensitive data.', ); } return ToolGuardrailFunctionOutputFactory.allow(); },});
const classifyTool = tool({ name: 'classify_text', description: 'Classify text for internal routing.', parameters: z.object({ text: z.string(), }), inputGuardrails: [blockSecrets], outputGuardrails: [redactOutput], execute: ({ text }) => `length:${text.length}`,});
const agent = new Agent({ name: 'Classifier', instructions: 'Classify incoming text.', tools: [classifyTool],});guardrailAgentは、ガードレール関数内で使用されます。- ガードレール関数はエージェントの入力または出力を受け取り、実行結果を返します。
- ガードレールの実行結果には追加情報を含めることができます。
agentは、ガードレールが適用される実際のワークフローを定義します。