跳转到主要内容
🧠

函数Schema

📂 LLM ⏱ 1 min 160 words

函数Schema概述

函数Schema(Function Schema)是使用JSON Schema格式定义函数接口的规范。在LLM函数调用中,Schema定义了函数的名称、描述、参数结构和约束,是模型理解如何调用函数的关键。

Schema结构

基本框架

{
  "name": "get_weather",
  "description": "获取指定城市的天气信息",
  "parameters": {
    "type": "object",
    "properties": {
      "city": {
        "type": "string",
        "description": "城市名称"
      },
      "unit": {
        "type": "string",
        "enum": ["celsius", "fahrenheit"],
        "description": "温度单位"
      }
    },
    "required": ["city"]
  }
}

字段说明

  • name:函数名称,模型用于引用
  • description:函数功能描述
  • parameters:JSON Schema格式的参数定义
  • required:必填参数列表

类型系统

基本类型

  • string:字符串类型
  • number:数字类型(整数和浮点数)
  • integer:整数类型
  • boolean:布尔类型

复合类型

  • object:对象类型,定义属性
  • array:数组类型,定义元素类型
  • enum:枚举类型,限定取值范围

约束属性

  • minimum/maximum:数值范围
  • minLength/maxLength:字符串长度
  • pattern:正则表达式匹配
  • default:默认值

设计原则

描述清晰

  • 用简洁的语言描述函数功能
  • 每个参数都有明确的描述
  • 避免歧义和模糊表述

参数最小化

  • 只定义必要的参数
  • 使用默认值减少必填参数
  • 避免过度约束

向前兼容

  • 新增可选参数不影响旧调用
  • 参数值使用枚举而非自由文本
  • 版本化命名

嵌套Schema

支持复杂的参数结构:

{
  "parameters": {
    "type": "object",
    "properties": {
      "filters": {
        "type": "object",
        "properties": {
          "date_range": {
            "type": "object",
            "properties": {
              "start": {"type": "string", "format": "date"},
              "end": {"type": "string", "format": "date"}
            }
          },
          "category": {"type": "string", "enum": ["all", "news", "sports"]}
        }
      }
    }
  }
}

多函数Schema

定义多个可用函数:

{
  "functions": [
    {"name": "search", "description": "搜索信息", ...},
    {"name": "calculate", "description": "执行计算", ...},
    {"name": "translate", "description": "翻译文本", ...}
  ]
}

模型根据用户意图选择合适的函数。

验证与测试

  • 使用JSON Schema验证工具
  • 测试边界条件和异常输入
  • 验证模型生成的参数是否正确
  • 收集线上调用数据持续优化Schema设计

最佳实践

  1. 函数命名遵循一致的命名规范
  2. description应包含使用场景和约束
  3. 使用enum限制可选值
  4. 为复杂参数提供示例
  5. 定期审查和更新Schema设计

良好的函数Schema设计是实现可靠LLM工具调用的基础。