使用ZodSchema时OpenAI Agent的outputType功能异常报错
OpenAI Agents自定义ZodSchema作为outputType报错解决方法
问题情况
使用OpenAI Agents时,将自定义ZodSchema赋值给outputType参数后触发报错,错误信息如下:
error: { message: "Invalid value: 'object'. Supported values are: 'json_object', 'text', and 'json_schema'.", type: "invalid_request_error", param: "text.format.type", code: "invalid_value", }
错误原因
当前OpenAI Agents SDK在自动处理ZodSchema类型的outputType时存在识别异常,错误地将格式类型设为了平台不接受的object,而平台仅支持json_object、text、json_schema三种格式类型。
解决方案
需要显式指定输出格式为json_schema,以下两种方法均可解决问题:
方法一:用OutputFormat.jsonSchema()包装ZodSchema
使用SDK提供的工具方法包装自定义ZodSchema,明确告知平台使用json_schema格式:
import { Agent, OutputFormat } from "@langchain/openai"; import z from "zod"; import { readFileSync } from "fs"; import path from "path"; const messageContentSchema = z.object({ type: z.enum([ "text", "image", "add-routine", "add-meal", "log-meal", "log-routine", "log-workout", ]), summary: z.string().optional(), data: z .object({ id: z.string().uuid(), name: z.string() }) .or( z.object({ id: z.string().uuid(), name: z.string(), brandName: z.string().optional(), }), ) .or(z.string()), }); const agent = new Agent({ outputType: OutputFormat.jsonSchema(messageContentSchema), instructions: readFileSync( path.resolve(__srcdir, "src/mcp/prompt.txt"), "utf-8", ).replace("%userId%", "f1434e18-3d52-4c01-8a85-202b58a7adf6"), });
方法二:手动构造outputType配置对象
直接构造符合平台要求的配置对象,明确指定type为json_schema:
const agent = new Agent({ outputType: { type: "json_schema", json_schema: { schema: messageContentSchema, name: "MessageContent", // 可选,给Schema命名便于识别 strict: true // 可选,启用严格模式确保输出完全匹配Schema } }, instructions: readFileSync( path.resolve(__srcdir, "src/mcp/prompt.txt"), "utf-8", ).replace("%userId%", "f1434e18-3d52-4c01-8a85-202b58a7adf6"), });
额外建议
如果上述方法无效,尝试升级OpenAI Agents SDK到最新版本,可能是旧版本SDK存在ZodSchema自动转换的bug。
内容的提问来源于stack exchange,提问作者Oasis Inc
相关产品推荐
相关产品推荐

