← [ BACK_TO_NOTES ]

Function Schema

Function Schema 是用 JSON Schema 定义工具的参数格式,让 LLM 知道该传什么参数、参数类型是什么、哪些是必填。

#concept #evergreen #ai

[!info] related notes

Function Schema

一句话定义

Function Schema 是用 JSON Schema 格式定义工具参数的规范。它告诉 LLM:这个工具接受什么参数、参数类型是什么、哪些是必填、参数值的范围是什么。

核心原理

JSON Schema 结构

{
  "type": "object",
  "properties": {
    "query": {
      "type": "string",
      "description": "搜索关键词"
    },
    "limit": {
      "type": "integer",
      "description": "返回结果数量",
      "default": 10,
      "minimum": 1,
      "maximum": 100
    },
    "filters": {
      "type": "object",
      "properties": {
        "category": {"type": "string"},
        "date_range": {"type": "string"}
      }
    }
  },
  "required": ["query"]
}

工具定义的接口封装(示例)

tool_definition = {
    "type": "function",
    "function": {
        "name": "search_knowledge",
        "description": "搜索知识库中的相关信息",
        "parameters": {
            "type": "object",
            "properties": {
                "query": {
                    "type": "string",
                    "description": "搜索关键词"
                },
                "top_k": {
                    "type": "integer",
                    "description": "返回结果数量",
                    "default": 5
                }
            },
            "required": ["query"]
        }
    }
}

该 function 封装不是所有模型接口的通用格式。JSON Schema 描述参数结构;外层工具定义、支持的关键字和严格输出模式需按实际接口适配。

Pydantic 转 JSON Schema(v2)

from pydantic import BaseModel, ConfigDict, Field

class SearchParams(BaseModel):
    model_config = ConfigDict(extra="forbid", strict=True)

    query: str = Field(description="搜索关键词")
    top_k: int = Field(default=5, description="返回结果数量", ge=1, le=100)

schema = SearchParams.model_json_schema()

声明与执行的边界

  • JSON Schema 的 default 是注解,普通校验不会自动填值;Pydantic model_validate 会按模型定义应用默认值。
  • 只声明 properties 不会拒绝额外字段;需要 additionalProperties: false,嵌套对象也分别设置。
  • format 通常需要显式检查器;description 中的日期格式说明不是校验器。
  • Pydantic 导出 schema 不等于校验输入,服务端仍需 model_validate;示例 strict=True 拒绝把字符串数字当整数。
  • 结构合法不代表资源存在、当前主体有权操作或业务条件成立。

常见坑

  1. description 太模糊: “参数”比”搜索关键词”差很多
  2. 不定义 required: LLM 不知道哪些参数必填
  3. 类型不准确: 应该是 integer 写成 number
  4. 不做参数验证: LLM 传了非法参数直接崩溃

参考资料

创建于 2026/6/30 更新于 2026/10/7
Digital Biome
Access

键盘导航

j / k / ↑ / ↓
选择对象
Enter / o
打开选择
/ 或 Ctrl+K
全站搜索
i / f / 1–4
筛选当前列表
g → h / l / p / t / a
首页 / 笔记 / 项目 / 工具 / About
r → 1–9
打开所选对象的关联
u
返回上一页
Esc
关闭浮层 / 取消命令;输入框内清空文本