# aardio 范例: AI 调用本地函数（function calling ）



```aardio
// AI 调用本地函数（function calling ）
//调用 AI （function calling ）： https://www.aardio.com/zh-cn/docs/library-guide/std/web/rest/aiChat.html#function-calling 

import console.int;  
import web.rest.aiChat;

/*
web.rest.aiChat 支持 OpenAI/Anthropic/Google 兼容接口的 function calling 功能。

如果服务端报错缺少 content 字段，
这是因为接口不支持 function calling，只能处理包含 content 的普通消息。
不支持 function calling 接口可能会不停地重复调用本地函数，而非直接出错。
*/
 
var aiClient = web.rest.aiChat( 
	key =   '\0\1\96';
	url = "https://ai.aardio.com/api/v1/";//接口地址
	model = "test-model-id";
	toolChoice = "required"; //设置为必须调用工具，不指定则默认由 AI 自动决定是否调用工具
	temperature = 0.5,
	tools = { //关键在于增加 tools 字段声明可以调用的本地函数，细节请参考 API 文档。
        {
            "type": "function",
            "function": {
                "name": "getWeather",
                "description": "获取给定地点的天气",
                "parameters": {
                    "type": "object",//为避免不必要的麻烦，参数务必指定为 "object" 类型！！！
                    "properties": {
                        "location": {
                            "type": "string",
                            "description": "地点的位置信息，比如北京"
                        },
                        "unit": {
                            "type": "string",
                            "enum": {
                                "摄氏度",
                                "华氏度"
                            }
                        }
                    },
                    "required": {
                        "location"
                    }
                }
            }
        }
    }
)

//导出允许 AI 调用的函数，与前面的 tools 里声明的函数名称与原型说明要匹配。
aiClient.external = {
	getWeather = function(args){ 
		/*
        要特别注意修改 args 会写入工具调用历史，AI 可以看到你的改动。
        如果对 args 的修改会让 AI 困惑，则应使用 args = table.clone(args) 复制副本然后仅修改副本。
        */
        
		console.log("正在调用函数，参数：",args.location,args.unit)
		
		// 用自然语言描述清楚
		// return  args.location + "天气晴，24~30 度"
		
		// 也可以返回对象/数组/其数据类型
	    return {
            result =args.location + "天气晴，24~30 度";
            succeeded = true;
            //error = err;
        }
	} 
}

//单独 创建 AI 会话消息队列以保存聊天上下文。
var chatMsg = web.rest.aiChat.messages();

//添加用户提示词
chatMsg.prompt("杭州天气如何？" );

console.showLoading(" Thinking "); 

/*
调用聊天接口。
如果参数 2 指定回调函数，则启用流式输出，并将 AI 逐步回复的增量文本作为回调参数。
可选用参数 3 指定一个表，表中可指定要添加的其他请求参数。
*/
var ok,err = aiClient.messages(chatMsg,
	function(deltaText,reasoning){ 
		
		if(reasoning) return console.writeColorText(reasoning,0xA); 
		 
		console.writeText(deltaText) 
	}
);

console.log(err)
```

