Function Schema
Function Schema 是用 JSON Schema 定义工具的参数格式,让 LLM 知道该传什么参数、参数类型是什么、哪些是必填。
#type / concept
#status / evergreen
#tech / 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"]
}
}
}
Pydantic 转 JSON Schema
from pydantic import BaseModel, Field
class SearchParams(BaseModel):
query: str = Field(description="搜索关键词")
top_k: int = Field(default=5, description="返回结果数量", ge=1, le=100)
schema = SearchParams.model_json_schema()
常见坑
- description 太模糊: “参数”比”搜索关键词”差很多
- 不定义 required: LLM 不知道哪些参数必填
- 类型不准确: 应该是 integer 写成 number
- 不做参数验证: LLM 传了非法参数直接崩溃