ガードレール
ガードレールは、エージェントと並行して実行することも、完了まで実行をブロックすることもでき、ユーザー入力やエージェント出力に対するチェックやバリデーションを行えます。たとえば、高価なモデルを呼び出す前に軽量モデルをガードレールとして実行できます。ガードレールが悪意ある利用を検知した場合、エラーを発生させて高コストなモデルの実行を停止できます。
ガードレールには 2 種類あります:
- 入力ガードレール は最初のユーザー入力に対して実行されます
- 出力ガードレール は最終的なエージェント出力に対して実行されます
入力ガードレール
Section titled “入力ガードレール”入力ガードレールは次の 3 つのステップで実行されます:
- ガードレールはエージェントに渡されたものと同じ入力を受け取ります
- ガードレール関数が実行され、
InputGuardrailResultにラップされたGuardrailFunctionOutputを返します tripwireTriggeredがtrueの場合、InputGuardrailTripwireTriggeredエラーがスローされます
Note 入力ガードレールはユーザー入力を対象としているため、ワークフローでエージェントが最初のエージェントの場合にのみ実行されます。ガードレールはエージェント自体に設定します。これは、エージェントごとに必要なガードレールが異なることが多いためです
runInParallel: true(デフォルト)は、ガードレールを LLM/ツール呼び出しと並行して開始します。レイテンシーを最小化しますが、後からガードレールが作動した場合でも、モデルはすでにトークンを消費したりツールを実行している可能性がありますrunInParallel: falseはモデル呼び出しの前にガードレールを実行し、ガードレールがリクエストをブロックする際にトークン消費やツール実行を防ぎます。安全性やコストをレイテンシーより優先する場合に使用します
出力ガードレール
Section titled “出力ガードレール”出力ガードレールは次の 3 つのステップで実行されます:
- ガードレールはエージェントによって生成された出力を受け取ります
- ガードレール関数が実行され、
OutputGuardrailResultにラップされたGuardrailFunctionOutputを返します tripwireTriggeredがtrueの場合、OutputGuardrailTripwireTriggeredエラーがスローされます
Note 出力ガードレールは、ワークフローでエージェントが最後のエージェントである場合にのみ実行されます。リアルタイムの音声インタラクションについては音声エージェントの構築を参照してください
ツールガードレール
Section titled “ツールガードレール”ツールガードレールは 関数ツール をラップし、実行の前後でツール呼び出しを検証またはブロックできます。ツール自体(tool() のオプション)に設定され、ツールの呼び出しごとに実行されます。
- 入力ツールガードレール はツールの実行前に動作し、メッセージ付きで呼び出しを拒否したり、トリップワイヤーをスローできます
- 出力ツールガードレール はツールの実行後に動作し、拒否メッセージで出力を置き換えたり、トリップワイヤーをスローできます
ツールガードレールは behavior を返します:
allow— 次のガードレールまたはツール実行に進むrejectContent— メッセージでショートサーキットする(ツール呼び出しをスキップ、または出力を置き換える)throwException— 直ちにトリップワイヤーエラーをスローする
ツールガードレールは tool() で作成した関数ツールに適用されます。組み込みツール(Hosted)やローカルのビルトインツール(computerTool、shellTool、applyPatchTool)はこのガードレールパイプラインを使用しません。
トリップワイヤー
Section titled “トリップワイヤー”ガードレールが失敗すると、トリップワイヤーによってその旨が通知されます。トリップワイヤーが作動するとすぐに、ランナーは対応するエラーをスローして実行を停止します。
ガードレールの実装
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],});
void agent;guardrailAgentはガードレール関数内で使用されます- ガードレール関数はエージェントの入力または出力を受け取り、結果を返します
- ガードレール結果には追加情報を含めることができます
agentはガードレールが適用される実際のワークフローを定義します