工具调用
工具调用(Function Calling / Tool Use)允许大模型调用自定义函数,扩展模型能力,适用于信息检索、数据库操作、外部 API 调用等场景。
工作原理
CloudBase AI SDK 自动处理上述流程,开发者只需定义工具并注册即可。
使用步骤
1. 定义工具
const getWeatherTool = {
name: "get_weather",
description: "查询指定城市的天气信息",
fn: async ({ city }) => {
// 实际场景中调用天气 API
return `${city}:26°C,晴`;
},
parameters: {
type: "object",
properties: {
city: {
type: "string",
description: "城市名称"
}
},
required: ["city"]
}
};
2. 注册工具
ai.registerFunctionTool(getWeatherTool);
3. 调用模型
const model = ai.createModel("hunyuan-exp");
const result = await model.generateText({
model: "hunyuan-turbos-latest",
tools: [getWeatherTool],
messages: [{ role: "user", content: "北京天气怎么样?" }]
});
console.log(result.text);
// 输出:北京今天 26°C,晴天,适宜外出活动。
工具定义
FunctionTool 类型
interface FunctionTool {
name: string; // 工具名称,唯一标识
description: string; // 工具描述,帮助模型理解用途
fn: Function; // 执行函数
parameters: object; // 参数定义(JSON Schema 格式)
}