在构建大语言模型(LLM)可调用的工具时,我们通常会定义工具的参数结构(parameters),使模型能够根据用户输入自动选择工具并构造合法的参数调用。对于多功能工具,一个关键问题是:
不同动作(action)需要不同的参数,该如何让模型明白?
本文将进一步探讨:如何使用 JSON Schema
中的 dependencies
机制,优雅地约束不同 action
所需的参数,确保 LLM 生成合法的调用请求。
问题背景:工具支持多种动作,但参数不同
考虑一个通用浏览器控制工具 browser_use
,它支持多种操作:
go_to_url
:需要url
click_element
:需要index
input_text
:需要index
和text
web_search
:需要query
如果不做任何约束,模型可能会在 click_element
中错误地填入 text
,导致调用失败或行为异常。
解决方案:使用 JSON Schema 的 dependencies
我们可以为工具定义如下参数结构:
{
"type": "object",
"properties": {
"action": {
"type": "string",
"enum": ["go_to_url", "click_element", "input_text", "web_search"]
},
"url": { "type": "string" },
"index": { "type": "integer" },
"text": { "type": "string" },
"query": { "type": "string" }
},
"required": ["action"],
"dependencies": {
"go_to_url": ["url"],
"click_element": ["index"],
"input_text": ["index", "text"],
"web_search": ["query"]
}
}
其中:
required
: 所有调用必须至少指定action
dependencies
: 定义每个动作对应必须提供的参数
如果模型选择了
action = "click_element"
,它就必须同时提供index
模型如何理解 dependencies
?
以用户问题为例:
“点击第二个按钮”
模型经过推理,会生成:
{
"action": "click_element",
"index": 2
}
这背后正是因为模型读懂了 schema 中的:
"click_element": ["index"]
从而避免生成无效调用:
{
"action": "click_element",
"text": "提交"
}
使用场景与兼容性
应用框架 | 是否支持 dependencies |
说明 |
---|---|---|
OpenAI Function Calling | ✅ | 模型遵循 JSON Schema 结构 |
Qwen Tool Use | ✅ | 完全兼容 dependencies 字段 |
LangChain Tool | ✅ | 可通过 args_schema 显式定义 |
自定义代理系统 | ✅ | 可手动解析 schema 实现验证逻辑 |
实践建议
- 当一个工具支持多个
action
时,强烈建议使用dependencies
来约束参数组合。 - 避免写成统一大 schema 而不做依赖区分,会导致模型乱填字段。
- 建议搭配
description
字段,为每个参数添加清晰提示,有助于 LLM 理解和生成。
完整示例
{
"name": "browser_use",
"description": "A tool for browser automation and web page interaction.",
"parameters": {
"type": "object",
"properties": {
"action": {
"type": "string",
"enum": ["click_element", "go_to_url", "input_text", "web_search"]
},
"url": { "type": "string", "description": "URL to navigate to" },
"index": { "type": "integer", "description": "Index of element" },
"text": { "type": "string", "description": "Text input" },
"query": { "type": "string", "description": "Search query" }
},
"required": ["action"],
"dependencies": {
"go_to_url": ["url"],
"click_element": ["index"],
"input_text": ["index", "text"],
"web_search": ["query"]
}
}
}
总结
使用 JSON Schema
的 dependencies
字段,是实现 LLM 工具调用参数依赖管理的最佳实践之一:
- ✅ 约束参数组合合法性
- ✅ 避免模型生成错误字段
- ✅ 简洁清晰,模型易于理解
- ✅ 与主流 LLM 平台兼容性强
未来,在构建多功能 AI 工具时,合理使用 dependencies
,可以极大提高系统健壮性和模型调用成功率。