-第9天实战-实现计算器工具)
1. 目标让AI能计算数学表达式通过Function Calling调用计算器工具。2. 实现代码在昨天的基础上增加上一节学习地址https://blog.csdn.net/weixin_42800530/article/details/161726697?spm1011.2124.3001.6209publicobjectGetCalculatorTool(){returnnew{typefunction,functionnew{namecalculator,description计算数学表达式的结果。支持加减乘除、括号等基本运算。用户问数学计算时必须调用此函数。,parametersnew{typeobject,propertiesnew{expressionnew{typestring,description数学表达式例如1024*256、200500、1520*2}},requirednew[]{expression}}}};}3. 实现计算功能代码如果需要支持高级函数使用 NCalc 库功能更强大安装NuGet包dotnet add package NCalcusingSystem;usingSystem.Collections.Generic;usingSystem.Data;usingSystem.Linq;usingSystem.Text;usingSystem.Text.Json;usingSystem.Threading.Tasks;usingNCalc;namespaceConsoleApp1.Common{publicclassCommonHelper{/// summary/// 执行本地工具/// /summarypublicstringExecuteTool(stringtoolName,stringarguments){switch(toolName){caseget_current_time:returnDateTime.Now.ToString(yyyy-MM-dd HH:mm:ss);casecalculator://计算器returnCalculateExpression(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};}}}}4. 调用代码publicstaticasyncTaskDay(){try{Console.WriteLine($-------------计算器工具测试-------------\r\n);CommonClasscommonClassnewCommonClass();commonClass.SetSystemPrompt(当用户询问数学计算问题时必须调用 calculator 函数来计算不要自己计算。计算完成后用自然语言告诉用户结果。);vartoolsnewobject[]{commonClass.GetCalculatorTool()};// 测试1乘法Console.WriteLine(用户1024 * 256 等于多少);varreply1awaitcommonClass.CallAPIWithTools(1024 * 256 等于多少,tools);Console.WriteLine($AI回答{reply1}\n);// 测试2复杂表达式Console.WriteLine(用户(100 50) * 2 ÷ 3 等于多少);varreply2awaitcommonClass.CallAPIWithTools((100 50) * 2 ÷ 3 等于多少,tools);Console.WriteLine($AI回答{reply2}\n);// 测试3减法Console.WriteLine(用户1000 - 357 等于多少);varreply3awaitcommonClass.CallAPIWithTools(1000 - 357 等于多少,tools);Console.WriteLine($AI回答{reply3}\n);// 测试4除法小数Console.WriteLine(用户10 ÷ 3 等于多少);varreply4awaitcommonClass.CallAPIWithTools(10 ÷ 3 等于多少,tools);Console.WriteLine($AI回答{reply4}\n);// 测试5混合运算Console.WriteLine(用户(2 3) × 4 - 5 ÷ 2 等于多少);varreply5awaitcommonClass.CallAPIWithTools((2 3) × 4 - 5 ÷ 2 等于多少,tools);Console.WriteLine($AI回答{reply5}\n);}catch(Exceptionex){Console.WriteLine($异常{ex.Message});}}5. 输出6. 常见问题Q1 问题需要支持更复杂的数学函数sin、cos、sqrt解决使用 NCalc 库支持更多函数usingNCalc;varexprnewExpression(sqrt(16) sin(30));expr.Evaluate();// 支持数学函数Q2 问题计算错误表达式包含不支持的字符原因用户输入了中文符号×、÷或其他特殊字符解决在计算前替换expressionexpression.Replace(×,*).Replace(÷,/);以上计算器工具实现完成