C#调用 AI学习从0开始-第2阶段(Function Calling+工具调用智能体)-第11天实战-实现天气工具+混合调用
1. 目标让AI能查询天气通过Function Calling调用天气工具。在昨天的基础上学习2.实现逻辑提示词写清晰commonClass.SetSystemPrompt(查询指定城市的天气信息。用户询问天气时必须调用此函数获取准确数据);天气工具publicstaticobjectGetWeatherTool(){returnnew{typefunction,functionnew{nameget_weather,description查询指定城市的天气信息。用户询问天气时必须调用此函数获取准确数据。,parametersnew{typeobject,propertiesnew{citynew{typestring,description城市名称例如北京、上海、广州、深圳}},requirednew[]{city}}}};}主要实现代码usingSystem;usingSystem.Collections.Generic;usingSystem.Data;usingSystem.Linq;usingSystem.Net.Http;usingSystem.Text;usingSystem.Text.Json;usingSystem.Threading.Tasks;usingNCalc;namespaceConsoleApp1.Common{publicclassCommonHelper{privatereadonlyHttpClient_httpClientnewHttpClient();privateconststringAMAP_KEY这里写你的天气 高德 天气应用Key;/// summary/// 执行本地工具/// /summarypublicasyncTaskstringExecuteTool(stringtoolName,stringarguments){switch(toolName){caseget_current_time:returnDateTime.Now.ToString(yyyy-MM-dd HH:mm:ss);casecalculator://计算器returnCalculateExpression(arguments);caseget_weather://天气returnawaitGetWeather(arguments);// 未来可以添加更多工具default:return$未知工具:{toolName};}}privatestringCalculateExpression(stringarguments){try{// 解析参数vardocJsonDocument.Parse(arguments);stringexpressiondoc.RootElement.GetProperty(expression).GetString();// 替换中文符号和空格expressionexpression.Replace(×,*).Replace(÷,/).Replace( ,);// 使用DataTable计算vartablenewDataTable();varresulttable.Compute(expression,);returnresult.ToString();}catch(Exceptionex){return$计算错误:{ex.Message};}}privateasyncTaskstringGetWeather(stringcity){try{// 1. 地理编码城市名 → adcodestringgeoUrl$https://restapi.amap.com/v3/geocode/geo?address{city}key{AMAP_KEY};vargeoResponseawait_httpClient.GetStringAsync(geoUrl);vargeoDocJsonDocument.Parse(geoResponse);varadcodegeoDoc.RootElement.GetProperty(geocodes)[0].GetProperty(adcode).GetString();// 2. 查询天气stringweatherUrl$https://restapi.amap.com/v3/weather/weatherInfo?city{adcode}key{AMAP_KEY};varweatherResponseawait_httpClient.GetStringAsync(weatherUrl);varweatherDocJsonDocument.Parse(weatherResponse);varliveweatherDoc.RootElement.GetProperty(lives)[0];stringweatherlive.GetProperty(weather).GetString();stringtemperaturelive.GetProperty(temperature).GetString();stringwindlive.GetProperty(windpower).GetString();return${city}{weather}{temperature}°C风力{wind}级;}catch(Exceptionex){return$获取真实天气失败:{ex.Message};}}}}混合调用publicstaticasyncTaskDay(){try{Console.WriteLine($-------------天气工具测试-------------\r\n);CommonClasscommonClassnewCommonClass();//commonClass.SetSystemPrompt(查询指定城市的天气信息。用户询问天气时必须调用此函数获取准确数据);// 设置系统提示commonClass.SetSystemPrompt(你是一个智能助手。 - 当用户询问时间时调用 get_current_time - 当用户询问数学计算时调用 calculator - 当用户询问天气时调用 get_weather - 如果是闲聊直接回答不需要调用工具);// 定义工具天气 时间 计算器多工具协同//var tools new object[] { CommonClass.GetCurrentTimeTool(), CommonClass.GetCalculatorTool(), CommonClass.GetWeatherTool() }; //object[]toolscommonClass.GetAllTools();//获取所有工具统一注册Console.WriteLine(用户现在几点了);varreplyawaitcommonClass.CallAPIWithTools(现在几点了,tools);Console.WriteLine($AI{reply}\n);// 测试1查询北京天气//Console.WriteLine(用户西安今天天气怎么样);//var reply1 await commonClass.CallAPIWithTools(西安今天天气怎么样, tools);//Console.WriteLine($AI回答{reply1}\n);// 测试5混合意图 Console.WriteLine(【测试混合意图】);Console.WriteLine(用户北京天气怎么样现在几点了);varreply5awaitcommonClass.CallAPIWithTools(北京天气怎么样现在几点了,tools);Console.WriteLine($AI{reply5}\n);Console.WriteLine(用户西安美食推荐);varreply1awaitcommonClass.CallAPIWithTools(西安美食推荐,tools);Console.WriteLine($AI回答{reply1}\n);}catch(Exceptionex){Console.WriteLine($异常{ex.Message});}}主要设置请求体的tool_choice设置auto//请求体 第1次请求带tools参数varrequestBodynew{modelqwen-turbo,messages_history,//MessagesIntoolstools,tool_choiceauto,//让AI自动决定是否调用工具streamfalse};注册高德天气应用步骤调用高德天气需注册高德应用天气申请Key。申请步骤详解【1】注册/登录高德开放平台访问高德开放平台官网如果没有账号先点击“注册”完成开发者注册已有账号则直接登录。【2】进入控制台创建应用登录后进入“控制台”在左侧菜单找到“应用管理” - “我的应用”。点击右上角的“创建新应用”给你的应用起个名字比如“我的AI助手”选择好应用类型然后提交。【3】添加Key并选择“Web服务”进入刚创建的应用点击“添加Key”。在弹出的对话框里最关键的步骤是服务平台一定要选择“Web服务”不是Web端JS API。之后填好Key名称勾选同意条款提交就可以了。【4】获取你的Key添加成功后你就能在应用详情里看到生成的Key字符串了复制保存好就行。⚠️ 避坑小贴士别选错平台申请时服务平台务必选“Web服务”。选错了类型比如选成iOS/Android SDK调用天气接口时就会报“INVALID_USER_KEY”这个错。注意每日调用限额个人认证的开发者账号天气接口每日免费调用限额是5,000次。学习和个人项目完全够用注意别超限就行。