跳转到内容

模式验证

SDK 使用模式向模型描述结构化数据,并验证应用程序中的数据。请根据是否需要本地验证和类型推断来选择模式形式。

模式形式本地验证和转换TypeScript 类型推断支持的接口
Zod 对象是是函数工具和智能体工具的 parameters、函数工具的 outputSchema、智能体的 outputType,以及交接的 inputType
支持 Standard JSON Schema 转换的 Standard Schema是,同步执行是,根据验证输出类型推断函数工具和智能体工具的 parameters、智能体的 outputType,以及交接的 inputType
原始 JSON Schema否;SDK 仅解析 JSON否;值的类型为 unknown函数工具和智能体工具的 parameters、函数工具的 outputSchema、智能体的 outputType,以及交接的 inputType

如果 Zod 已经适合您的应用程序,就使用 Zod。如果您希望通过其他兼容的验证库获得相同的 SDK 验证能力和输出类型推断,请使用 Standard Schema。如果您已有传输层模式,并且会在其他地方验证值,请使用原始 JSON Schema。

兼容的值必须实现 Standard Schema V1 验证和 Standard JSON Schema 转换。有些库直接提供这两种能力,其他库则提供适配器。本示例使用 Valibot,以及 @valibot/to-json-schema 中的 toStandardJsonSchema()。

在已使用 @openai/agents 的应用程序中,运行 npm install valibot @valibot/to-json-schema 安装示例依赖项。

用于工具、智能体输出和交接的 Valibot 模式
import { Agent, handoff, tool } from '@openai/agents';
import { toStandardJsonSchema } from '@valibot/to-json-schema';
import * as v from 'valibot';
const LookupOrderParameters = toStandardJsonSchema(
v.object({
orderId: v.pipe(v.string(), v.minLength(1)),
includeHistory: v.optional(v.boolean(), false),
}),
);
const lookupOrder = tool({
name: 'lookup_order',
description: 'Look up an order by ID.',
parameters: LookupOrderParameters,
// The argument type is inferred after Valibot validation and defaults run.
execute: async ({ orderId, includeHistory }) => ({
orderId,
status: 'shipped',
history: includeHistory ? ['placed', 'shipped'] : undefined,
}),
});
const Resolution = toStandardJsonSchema(
v.object({
orderId: v.string(),
message: v.string(),
}),
);
const supportAgent = new Agent({
name: 'Order support',
instructions: 'Resolve order questions and return a structured summary.',
tools: [lookupOrder],
// The final output is converted to JSON Schema, then validated by Valibot.
outputType: Resolution,
});
const supportAgentTool = supportAgent.asTool({
toolName: 'resolve_order',
toolDescription: 'Resolve an order question with the support specialist.',
parameters: LookupOrderParameters,
// inputBuilder receives the same validated and inferred parameter type.
inputBuilder: ({ params }) =>
`Resolve order ${params.orderId}. Include history: ${params.includeHistory}.`,
});
const EscalationDetails = toStandardJsonSchema(
v.object({
reason: v.pipe(v.string(), v.minLength(1)),
priority: v.optional(v.picklist(['normal', 'urgent']), 'normal'),
}),
);
const billingAgent = new Agent({
name: 'Billing specialist',
instructions: 'Resolve billing questions.',
});
const billingHandoff = handoff(billingAgent, {
inputType: EscalationDetails,
// The callback receives the validated value, including Valibot defaults.
onHandoff: async (_context, details) => {
if (details) {
await recordEscalation(details.reason, details.priority);
}
},
});
async function recordEscalation(_reason: string, _priority: string) {}
export { billingHandoff, supportAgent, supportAgentTool };

同一模式约定在不同接口中承担不同的角色:

  • tool({ parameters }) 将模式转换为供模型使用的形式,在本地验证每次工具调用,应用库提供的转换或默认值,并将推断出类型的验证输出传递给 execute。
  • agent.asTool({ parameters }) 应用相同的验证,并在嵌套智能体运行之前,将推断出类型的验证输出传递给 inputBuilder。
  • new Agent({ outputType }) 请求结构化模型输出,在本地验证解析后的值,并通过 result.finalOutput 提供推断出类型的验证输出。
  • handoff(..., { inputType }) 验证交接工具调用的参数,并将推断出类型的验证输出传递给 onHandoff。

Standard Schema 支持有意采用了范围有限的约定:

  • 该值必须提供同步的 ~standard.validate 行为,以及 ~standard.jsonSchema.input() 和 ~standard.jsonSchema.output()。不支持仅提供验证能力的 Standard Schema 值。
  • 这些 SDK 接口使用的输入 JSON Schema 必须在根级别设置 type: "object"。请将标量值或数组值包装在对象模式中。
  • Standard Schema 函数工具参数要求启用严格模式。使用此类参数时,请勿设置 strict: false。
  • 不支持异步 Standard Schema 验证。如果验证器返回 Promise,操作将失败,而不会运行工具回退逻辑或无效最终输出处理程序。
  • 生成的 JSON Schema 必须使用 SDK 严格模式规范化所支持的构造。不支持的构造会在创建工具、交接或智能体时导致失败,此时尚未向模型发送请求。
  • 函数工具的 outputSchema 目前不接受 Standard Schema。请使用 Zod 模式、原始 JSON Schema,或在应用程序代码中验证工具结果。

如果您正在编写自己的适配器,请从 @openai/agents 导入 StandardSchemaWithJSON<Input, Output> 类型,以检查适配器是否提供所需的验证和转换方法。如果有库维护的适配器,请优先使用。