首页
/ Multi-Agent Orchestrator工具定义中的JSON Schema类型错误解析

Multi-Agent Orchestrator工具定义中的JSON Schema类型错误解析

2025-06-11 00:13:29作者:齐冠琰

在Multi-Agent Orchestrator项目开发过程中,定义Agent工具时可能会遇到JSON Schema验证错误的问题。本文将通过一个典型案例,深入分析错误原因并提供解决方案。

问题现象

开发者在定义天气查询工具时,按照如下方式声明了工具参数:

weather_tool = AgentTool(
    name="weather_tool",
    description="天气查询工具",
    properties = {
        "day": {
            "type": "string",
            "description": "星期几"
        },
        "hour": {
            "type": "int",  # 这里使用了int类型
            "description": "小时数[0-24]",
        }
    },
    func=get_forecast
)

当Agent首次被调用时,系统返回了JSON Schema验证错误,提示输入模式无效。从调试信息可以看到,工具配置最终被序列化为:

{
  "tools": [{
    "toolSpec": {
      "name": "weather_tool",
      "description": "天气查询工具",
      "inputSchema": {
        "json": {
          "type": "object",
          "properties": {
            "day": {"type": "string", "description": "星期几"},
            "hour": {"type": "int", "description": "小时数[0-24]"}
          },
          "required": ["day", "hour"]
        }
      }
    }
  }]
}

根本原因分析

问题出在参数类型的定义上。JSON Schema规范中,数字类型应该使用"number"而不是"int"。虽然"int"在编程语言中很常见,但在JSON Schema标准中,只有以下几种基本类型:

  1. string - 字符串类型
  2. number - 数字类型(包括整数和浮点数)
  3. integer - 整数类型(JSON Schema draft-07及以后版本支持)
  4. boolean - 布尔类型
  5. object - 对象类型
  6. array - 数组类型
  7. null - 空值类型

解决方案

将工具定义中的"int"改为"number"即可解决问题:

weather_tool = AgentTool(
    name="weather_tool",
    description="天气查询工具",
    properties = {
        "day": {
            "type": "string",
            "description": "星期几"
        },
        "hour": {
            "type": "number",  # 修正为number类型
            "description": "小时数[0-24]",
        }
    },
    func=get_forecast
)

最佳实践建议

  1. 类型选择:在定义工具参数时,始终使用JSON Schema标准类型
  2. 参数验证:对于整数参数,可以结合"type": "number"和"multipleOf": 1来确保接收整数
  3. 范围限制:对于有范围限制的参数,应添加minimum和maximum约束
  4. 枚举值:对于固定选项的参数,使用enum列出所有可能值

修正后的完整示例如下:

weather_tool = AgentTool(
    name="weather_tool",
    description="天气查询工具",
    properties = {
        "day": {
            "type": "string",
            "enum": ["周一","周二","周三","周四","周五","周六","周日"],
            "description": "星期几"
        },
        "hour": {
            "type": "number",
            "minimum": 0,
            "maximum": 24,
            "multipleOf": 1,
            "description": "小时数[0-24]",
        }
    },
    func=get_forecast
)

通过遵循这些规范,可以确保工具定义与JSON Schema标准完全兼容,避免出现验证错误。

登录后查看全文
热门项目推荐
相关项目推荐