虽然python后台可以设置agent并调用工具,但是后台和前端交互速度不如直接在前端JavaScript调用快,在内网调用时确实可以改善使用体验。
下面以硅基流动的API为例子,让AI调用本地tools工具。
<html>
<head>
<title>test ai tools</title>
</head>
<body>
<button onclick="test()">Click Me!</button>
<script>
alert("Hello World!");
function test() {
const options = {
method: 'POST',
headers: {
Authorization: 'Bearer sk-******************************************',
'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.choices[0]);
res = response.choices[0].message;
console.log(res);
if ('tool_calls' in res){
console.log('存在方法调用');
function_name = res.tool_calls[0].function.name;
console.log('存在方法调用:'+function_name);
if (function_name == 'multiplication'){
//参数获取
arguments = res.tool_calls[0].function.arguments;
let jsonObj = JSON.parse(arguments);
console.log(jsonObj);
let num1 = jsonObj.number1
let num2 = jsonObj.number2
//返回结果
return_obj = multiplication(num1,num2)
console.log('计算结果:'+return_obj);
}
if (function_name == 'weather'){
//返回结果
return_obj = weather()
console.log('天气查询:'+return_obj);
}
}
console.log(response.choices[0].message.content);
console.log('*******************');
})
.catch(err => console.error(err));
}
function multiplication(num1,num2){
return num1*num2;
}
function weather(){
//此处可调用第三方天气API获取天气信息
return '今天天气很好万里无云。';
}
</script>
</body>
</html>
根据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即可。