从"一把锤子"到"瑞士军刀"——函数调用的进阶玩法
Function Calling(函数调用)让LLM从"说话"进化到"动手"。基础用法是"问答→选工具→调用",高级用法则是复杂的编排模式。
| 层级 | 模式 | 复杂度 |
|---|---|---|
| L1 | 单工具调用 | ★☆☆☆☆ |
| L2 | 多工具并行 | ★★☆☆☆ |
| L3 | 顺序依赖调用 | ★★★☆☆ |
| L4 | 条件分支调用 | ★★★★☆ |
| L5 | 循环迭代调用 | ★★★★★ |
一次调用多个独立工具,然后汇总结果。适合信息收集类任务。
// 并行获取多个城市天气
const tools = [
{ name: "get_weather", params: { city: "北京" } },
{ name: "get_weather", params: { city: "上海" } },
{ name: "get_weather", params: { city: "深圳" } }
];
// 同时发起3个调用
const results = await Promise.all(
tools.map(t => callFunction(t.name, t.params))
);
// 汇总:"北京25°C,上海28°C,深圳31°C"
后一个调用依赖前一个的结果,形成调用链。
// 链式调用:查询→分析→执行
async function chainCalling() {
// Step 1: 查询用户信息
const user = await callFunction("get_user", { id: "123" });
// Step 2: 基于用户偏好推荐产品
const recommendations = await callFunction("recommend", {
preference: user.preference
});
// Step 3: 创建订单
const order = await callFunction("create_order", {
user_id: user.id,
items: recommendations.map(r => r.id)
});
return order;
}
根据中间结果决定下一步调用哪个工具。
// 条件调用:根据意图选择不同工具
async function conditionalCalling(userInput) {
const intent = await classifyIntent(userInput);
switch (intent.type) {
case "search":
return await callFunction("web_search", { query: intent.query });
case "calculate":
return await callFunction("calculator", { expr: intent.expr });
case "schedule":
return await callFunction("calendar", { event: intent.event });
default:
return await generateDirectResponse(userInput);
}
}
循环调用直到满足条件,适合处理分页数据或逐步优化。
// 迭代调用:分页获取所有数据
async function iterativeCalling(apiEndpoint) {
let allData = [];
let page = 1;
let hasMore = true;
while (hasMore && page <= 10) {
const result = await callFunction("fetch_page", {
endpoint: apiEndpoint,
page: page,
limit: 100
});
allData = [...allData, ...result.items];
hasMore = result.has_more;
page++;
}
return allData;
}
工具A的结果作为工具B的参数,B的结果再传给C。
// 嵌套调用:复杂数据处理流水线
async function nestedCalling(rawText) {
const result = await callFunction("summarize", {
text: await callFunction("translate", {
text: await callFunction("extract", {
html: rawText,
selector: "article"
}),
target_lang: "zh"
})
});
return result;
}
// 等效于: summarize(translate(extract(html)))
// OpenClaw自动工具选择流程
1. 用户输入: "搜索OpenClaw最新新闻并生成报告"
↓
2. LLM分析意图,决定调用哪些工具
↓
3. 自动调用 web_search: { query: "OpenClaw最新新闻" }
↓
4. 获取结果后,自动调用 write: 生成报告文件
↓
5. 返回完成结果给用户
// 复杂任务自动编排
async function analyzeSalesData() {
// OpenClaw自动执行以下调用链:
// 1. 从数据库查询数据
const dbResult = await exec({
command: "psql -c 'SELECT * FROM sales'"
});
// 2. 分析数据(spawn子Agent)
const analysis = await sessions_spawn({
task: `分析以下销售数据,找出趋势:${dbResult.output}`,
runtime: "subagent"
});
// 3. 生成可视化图表
await write({
file: "/tmp/chart_data.json",
content: JSON.stringify(analysis.charts)
});
// 4. 生成报告
await write({
file: "/var/www/miaoquai/reports/sales.html",
content: generateReportHTML(analysis)
});
// 5. 发送通知
await message({
action: "send",
content: "销售分析报告已生成!"
});
}