ガードレール
ガードレールはエージェントと並行して実行することも、完了するまで実行をブロックすることもでき、ユーザー入力やエージェント出力に対するチェックや検証を行えます。たとえば、高コストなモデルを呼び出す前に、軽量なモデルをガードレールとして実行できます。ガードレールが悪意のある利用を検出した場合、エラーを発生させて高コストなモデルの実行を停止できます。
ガードレールには 2 種類あります:
- 入力ガードレール は最初のユーザー入力に対して実行されます。
- 出力ガードレール は最終的なエージェント出力に対して実行されます。
ワークフローの境界
Section titled “ワークフローの境界”ガードレールはエージェントに関連付けられますが、ワークフロー内のすべてのエージェントで必ず実行されるわけではありません:
- 入力ガードレール はチェーン内の最初のエージェントに対してのみ実行されます
- 出力ガードレール は最終出力を生成するエージェントに対してのみ実行されます
- ツールガードレール はすべての関数ツール呼び出しで実行され、入力ガードレールは実行前、出力ガードレールは実行後に動作します
マネージャーやハンドオフを含むワークフローで、個々のカスタム関数ツール呼び出しごとにチェックが必要な場合は、エージェントレベルの入力 / 出力ガードレールではなく ツールガードレール を使用してください。
入力ガードレール
Section titled “入力ガードレール”入力ガードレールは 3 つのステップで実行されます:
- ガードレールは、エージェントに渡されたものと同じ入力を受け取ります。
- ガードレール関数が実行され、
GuardrailFunctionOutputをInputGuardrailResultでラップして返します。 tripwireTriggeredがtrueの場合、InputGuardrailTripwireTriggeredエラーがスローされます。
Note 入力ガードレールはユーザー入力向けであるため、ワークフロー内でそのエージェントが 最初の エージェントである場合にのみ実行されます。ガードレールはエージェント自体に設定されます。これは、エージェントごとに必要なガードレールが異なることが多いためです。
runInParallel: true(デフォルト)は、LLM / ツール呼び出しと並行してガードレールを開始します。これによりレイテンシは最小化されますが、後からガードレールが発火した場合には、モデルがすでにトークンを消費したりツールを実行したりしている可能性があります。runInParallel: falseは、モデルを呼び出す 前 にガードレールを実行し、ガードレールがリクエストをブロックした場合のトークン消費やツール実行を防ぎます。レイテンシよりも安全性とコストを優先したい場合に使用してください。
出力ガードレール
Section titled “出力ガードレール”出力ガードレールは 3 つのステップで実行されます:
- ガードレールは、エージェントが生成した出力を受け取ります。
- ガードレール関数が実行され、
GuardrailFunctionOutputをOutputGuardrailResultでラップして返します。 tripwireTriggeredがtrueの場合、OutputGuardrailTripwireTriggeredエラーがスローされます。
Note 出力ガードレールは、ワークフロー内でそのエージェントが 最後の エージェントである場合にのみ実行されます。リアルタイム音声インタラクションについては、音声エージェントの構築 を参照してください。
出力ガードレール関数は、基盤となる modelResponse と、そのターンで生成された出力アイテムを含む任意の details オブジェクトも受け取ります。これは、応答を通過させるべきかどうかを最終出力だけでは判断できない場合に使用します。たとえば、ガードレールを発火させる前に、生成されたアイテム一覧全体やプロバイダー応答のメタデータを確認したい場合です。
ツールガードレール
Section titled “ツールガードレール”ツールガードレールは 関数ツール をラップし、実行前後でツール呼び出しを検証またはブロックできるようにします。これらはツール自体(tool() のオプション経由)に設定され、そのツールの呼び出しごとに実行されます。
実際には、tool({...}) に inputGuardrails および / または outputGuardrails を設定するカスタム関数ツールを意味します。
- 入力ツールガードレール はツールの実行前に動作し、メッセージ付きで呼び出しを拒否したり、tripwire をスローしたりできます
- 出力ツールガードレール はツールの実行後に動作し、出力を拒否メッセージに置き換えたり、tripwire をスローしたりできます
ツールガードレールは behavior を返します:
allow— 次のガードレールまたはツール実行に進みますrejectContent— メッセージ付きで短絡終了します(ツール呼び出しはスキップされるか、出力が置き換えられます)throwException— ただちに tripwire エラーをスローします
ツールガードレールは、tool() で定義した関数ツールに適用されます。ハンドオフは関数に似たツールとしてモデルに提示されますが、通常の関数ツールパイプラインではなく SDK のハンドオフ経路を通って実行されるため、ツールガードレールはハンドオフ呼び出し自体には適用されません。組み込みツール(Hosted)や組み込み実行ツール(computerTool、shellTool、applyPatchTool)もこのガードレールパイプラインを使用せず、agent.asTool() も現時点ではツールガードレールのオプションを直接公開していません。
トリップワイヤ
Section titled “トリップワイヤ”ガードレールが失敗すると、tripwire を通じてそのことを通知します。tripwire が発火するとすぐに、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?'); console.log("Guardrail didn't trip - this is unexpected"); } catch (e) { if (e instanceof InputGuardrailTripwireTriggered) { console.log('Math homework guardrail tripped'); } }}
main().catch(console.error);出力ガードレールも同様に動作します。
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); console.log("Guardrail didn't trip - this is unexpected"); } catch (e) { if (e instanceof OutputGuardrailTripwireTriggered) { console.log('Math output guardrail tripped'); } }}
main().catch(console.error);ツール入力 / 出力ガードレールは次のようになります:
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は、ガードレールが適用される実際のワークフローを定義します。