虽然python后台可以设置agent并调用工具,但是后台和前端交互速度不如直接在前端JavaScript调用快,在内网调用时确实可以改善使用体验。
下面以硅基流动的API为例子,让AI调用本地tools工具。
const options = {method: 'POST',headers: {Authorization: 'Bearer sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxx','Content-Type': 'application/json'},body: JSON.stringify({tools: [{type: "function",function: {name: "multiplication",description: "Calculate the multiplication of two numbers",parameters: {number1:"数字1",number2:"数字2"}},strict: false},{type: "function",function: {name: "weather",description: "获取天气预报数据",},strict: false}],model: "deepseek-ai/DeepSeek-V2.5",stream: false,messages: [{role: "user",content: "今天天气怎么样"}]})};fetch('https://api.siliconflow.cn/v1/chat/completions', options).then(response => response.json()).then(response => console.log(response)).catch(err => console.error(err));
创建了一个数字相乘和获取天气的接口
当用户问道数字相乘时会返回
[{"index": 0,"message": {"role": "assistant","content": "","tool_calls": [{"id": "01955b43e609018a7ff2b475594c4fe5","type": "function","function": {"name": "multiplication","arguments": "{\"number1\":256,\"number2\":789}"}}]},"finish_reason": "tool_calls"}
]
根据arguments参数和function_name:multiplication可以调用计算相关的function
当用户问道天气相关的数据时会返回
[{"index": 0,"message": {"role": "assistant","content": "","tool_calls": [{"id": "01955b44a36f329401e0578374922cb1","type": "function","function": {"name": "weather","arguments": "{}"}}]},"finish_reason": "tool_calls"}
]
此时调用weather方法,在方法内调用天气查询的api即可。