护栏
护栏可以与智能体并行运行,也可以阻止执行直至检查完成,从而对用户输入或智能体输出执行检查和验证。例如,您可以先运行一个轻量级模型作为护栏,再调用成本较高的模型。如果护栏检测到恶意使用行为,它可以触发错误并阻止高成本模型运行。
护栏分为两类:
- 输入护栏针对初始用户输入运行。
- 输出护栏针对智能体的最终输出运行。
护栏附加到智能体上,但不一定会针对工作流中的每个智能体运行:
- 输入护栏仅针对链中的第一个智能体运行。
- 输出护栏仅针对生成最终输出的智能体运行。
- 工具护栏会在每次调用函数工具时运行,其中输入护栏在执行前运行,输出护栏在执行后运行。
如果您需要检查包含管理器或交接的工作流中的每次自定义函数工具调用,请使用工具护栏,而不是智能体级别的输入/输出护栏。
输入护栏分三个步骤运行:
- 护栏接收传递给智能体的同一份输入。
- 护栏函数执行并返回一个封装在
InputGuardrailResult中的GuardrailFunctionOutput。 - 如果
tripwireTriggered为true,则会抛出InputGuardrailTripwireTriggered错误。
注意 输入护栏用于处理用户输入,因此仅当该智能体是工作流中的第一个智能体时才会运行。护栏配置在智能体本身,因为不同的智能体通常需要不同的护栏。
runInParallel: true(默认值)会让护栏与 LLM/工具调用并行启动。这可以最大限度降低延迟,但如果护栏随后被触发,模型可能已经消耗了 token 或运行了工具。runInParallel: false会在调用模型之前运行护栏。当护栏阻止请求时,这可以避免消耗 token 和执行工具。如果您更重视安全性和成本,而不是延迟,请使用此模式。
输出护栏分 3 个步骤运行:
- 护栏接收智能体生成的输出。
- 护栏函数执行并返回一个封装在
OutputGuardrailResult中的GuardrailFunctionOutput。 - 如果
tripwireTriggered为true,则会抛出OutputGuardrailTripwireTriggered错误。
注意 输出护栏仅当该智能体是工作流中的最后一个智能体时才会运行。有关实时语音交互,请参阅实时智能体指南。
输出护栏函数还会接收一个可选的 details 对象,其中包含底层 modelResponse 和本轮生成的输出项。当仅凭最终输出不足以判断响应是否应当通过时,可以使用此对象。例如,您可以先检查完整的生成项列表或提供方响应元数据,再决定是否触发护栏。
工具护栏封装函数工具,让您可以在执行前后验证或阻止工具调用。它们配置在工具本身(通过 tool() 选项),并在每次调用该工具时运行。
在实际使用中,这指的是您在 tool({...}) 上设置了 inputGuardrails 和/或 outputGuardrails 的自定义函数工具。
- 输入工具护栏在工具执行前运行,可以通过消息拒绝调用或抛出触发器。
- 输出工具护栏在工具执行后运行,可以用拒绝消息替换输出或抛出触发器。
如果本地函数工具还需要人工批准,输入工具护栏通常会在批准后、执行前立即运行。如果还需要在生成待批准请求之前运行这些输入护栏,请在 run() 或 Runner 上设置 toolExecution: { preApprovalInputGuardrails: true }。批准后、工具执行前,这些护栏仍会再次运行。
工具护栏会返回一个 behavior:
allow——继续运行下一个护栏或执行工具。rejectContent——使用一条消息提前终止(跳过工具调用或替换输出)。throwException——立即抛出触发器错误。
工具护栏适用于使用 tool() 定义的函数工具。交接会以类似函数工具的形式呈现给模型,但它们通过 SDK 的交接路径运行,而不是通过常规函数工具管线,因此工具护栏不适用于交接调用本身。托管工具和内置执行工具(computerTool、shellTool、applyPatchTool)也不使用此护栏管线,并且 agent.asTool() 目前无法直接公开工具护栏选项。
当护栏检查失败时,它会通过触发器发出信号。一旦触发器被触发,运行器就会抛出相应错误并停止执行。
护栏本质上只是一个返回 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定义实际应用护栏的工作流。