AI怎么使用本地工具

  在实际调用大模型的过程中,我们本地化的一些函数方法,可以有针对性的喂给AI,让AI知道可以通过它获取需要的信息

  举个例子,我们咨询一下AI今天的天气

public static async Task Ask()
{
    IChatClient client = new ChatClient("qwen3-vl-plus",
        new ApiKeyCredential(apiKey),
        new OpenAI.OpenAIClientOptions() { Endpoint = new Uri(url) }
    ).AsIChatClient();

    while (true)
    {
        Console.Write(">>>>>>");
        var question = Console.ReadLine();
        if (question == null)
            continue;
        try
        {
            var res = await client.GetResponseAsync(question);
            if (res.FinishReason == ChatFinishReason.Stop)
            {
                Console.WriteLine(res.Text);
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"发生异常: {ex.Message}");
        }
    }
}

  结果: 

>>>>>>今天深圳天气怎么样
你好!我无法实时获取当前天气数据,但你可以通过以下方式快速查询深圳今日天气:

? 推荐方式:
- 打开手机自带的天气App(如苹果天气、华为天气等)
- 使用微信搜索“深圳天气”或进入“深圳天气”公众号
- 访问中国天气网:[http://www.weather.com.cn](http://www.weather.com.cn) → 搜索“深圳”
- 或直接在百度/谷歌搜索“深圳今天天气”

?? 小提示:
深圳近期(5月下旬至6月)已进入**龙舟水**季节,多雷雨、短时强降水,气温普遍在 **25°C~32°C** 之间,湿度大,体感闷热。建议出门带伞、注意防滑和防雷。

需要我帮你解读天气预报内容(比如你查到的数据),欢迎随时发给我 ??

  因为qwen3-vl-plus大模型不具备联网查询功能,所以它并不能知道今天的天气

  如果,我们给他封装一个调用天气的API呢?

    public record WeatherInfo(string City, string Temperature, string Condition, string UpdateTime);
    public static class WeatherHelper
    {
        // Demo 数据源
        private static readonly Dictionary<string, WeatherInfo> DemoData = new(StringComparer.OrdinalIgnoreCase)
        {
            { "北京", new WeatherInfo("北京", "28°C", "", DateTime.Now.ToString("yyyy-MM-dd HH:mm")) },
            { "上海", new WeatherInfo("上海", "32°C", "多云", DateTime.Now.ToString("yyyy-MM-dd HH:mm")) },
            { "深圳", new WeatherInfo("深圳", "30°C", "阵雨", DateTime.Now.ToString("yyyy-MM-dd HH:mm")) },
            { "广州", new WeatherInfo("广州", "33°C", "", DateTime.Now.ToString("yyyy-MM-dd HH:mm")) },
            { "杭州", new WeatherInfo("杭州", "26°C", "小雨", DateTime.Now.ToString("yyyy-MM-dd HH:mm")) }
        };

        /// <summary>
        /// 根据城市名称获取当前时间的天气信息(Demo版本)
        /// </summary>
        /// <param name="cityName">城市名称,支持模糊匹配</param>
        /// <returns>匹配的天气信息列表,未找到时返回空列表</returns>
        [Description("根据城市名称获取当前时间的天气信息")]
        public static WeatherInfo GetWeather(string cityName)
        {
            return DemoData[cityName];
        }
    }

  然后,执行以下代码

using HttpMataki.NET.Auto;
using Microsoft.Extensions.AI;
using NaturalLanguageToSQL;
using OpenAI;
using OpenAI.Chat;
using System.ClientModel;
using ChatMessage = Microsoft.Extensions.AI.ChatMessage;

//HttpClientAutoInterceptor.StartInterception();

// 1. 配置千问的 OpenAI 兼容环境
string apiKey = "";
var url = "";//专属
IChatClient client = new ChatClient("qwen3-vl-plus",
    new ApiKeyCredential(apiKey),
    new OpenAI.OpenAIClientOptions() { Endpoint = new Uri(url) }
).AsIChatClient();

IChatClient functionCallingChatClient = new ChatClientBuilder(client)
            .UseFunctionInvocation() // ✨ 核心:这一步让框架自动处理 Tool 逻辑,业务代码完全不用管中间过程
            .Build();

var chatOptions = new ChatOptions
{
    Tools = [
        AIFunctionFactory.Create(WeatherHelper.GetWeather),
    ] // 绑定工具
};


while (true)
{
    Console.Write("用户提问 > ");
    string userInput = Console.ReadLine();

    if (string.IsNullOrWhiteSpace(userInput) || userInput.ToLower() == "exit")
        break;

    // 5. 组装对话历史
    var chatHistory = new List<ChatMessage>
    {
        new ChatMessage(ChatRole.System, @"
你是一个企业通用助手,会根据自己的判断调用Tools。
1、若是不调用Tools,无需提醒Tools并不涉及提问的问题
"),
        new ChatMessage(ChatRole.User, userInput)
    };

    try
    {
        // 6. 调用千问大模型
        var response = await functionCallingChatClient.GetResponseAsync(chatHistory, chatOptions);
        Console.ForegroundColor = ConsoleColor.Green;
        Console.WriteLine(response.Text);
        Console.ResetColor();
        var AIMessages = response.Messages.Where(m => m.Role == ChatRole.Assistant);//筛选出AI回复的消息
        if (AIMessages.Any(m => m.Contents.OfType<FunctionCallContent>().Any(f => f.Name == nameof(WeatherHelper.GetWeather))))
        {
            Console.WriteLine("调用了WeatherHelper.GetWeather");
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine($"\n发生错误: {ex.Message}");
    }
}

  返回结果

用户提问 > 今天深圳天气怎么样
今天深圳天气为阵雨,气温30°C,更新时间为2026-07-17 10:34。
调用了WeatherHelper.GetWeather

  输出天气信息和模拟的信息是一致的,可见调用了本地的工具

  本质上是大模型告诉本地程序,调用这个工具,本地调用工具后,把信息一起发给大模型

  我们来看看通讯过程

[HttpMataki.NET.Auto] HttpClient automatic interception started
用户提问 > 今天深圳天气怎么样
2026-07-17 10:39:33 - Request:  //本地第一次请求

Method: POST

URL: https://ws-i70rvm4btlzu3tr0.cn-beijing.maas.aliyuncs.com/compatible-mode/v1/chat/completions

Headers:

Body: {"messages":[{"role":"system","content":"\r\n你是一个企业通用助手,会根据自己的判断调用Tools。\r\n1、若是不调用Tools,无需提醒Tools并不涉及提问的问题\r\n"}
,{"role":"user","content":"今天深圳天气怎么样"}],"model":"qwen3-vl-plus",
"tools":[{"type":"function","function":{"description":"根据城市名称获取当前时间的天气信息","name":"GetWeather","parameters":{ "type": "object", "required": [ "cityName" ], "properties": { "cityName": { "type": "string" } }, "additionalProperties": false }}}],"tool_choice":"auto"} 2026-07-17 10:39:36 - Response: //大模型回复,在Body告诉本地,需要调用工具GetWeather,参数=深圳 Status Code: 200 OK Headers: Body: {"id":"chatcmpl-9e83d38e-e6a4-9caa-8fe4-ccd2d63e3588","object":"chat.completion","created":1784255974,"model":"qwen3-vl-plus",

"choices":[{"index":0,"message":{"role":"assistant","reasoning_content":"","content":"",

"tool_calls":[{"id":"call_d573a4da9e484656ad73fa64","type":"function","function":{"name":"GetWeather","arguments":"{\"cityName\": \"深圳\"}"},"index":0}]},

"finish_reason":"tool_calls","logprobs":null}],"usage":{"prompt_tokens":300,"total_tokens":324,"completion_tokens":24,"prompt_tokens_details":{"text_tokens":300}}} ************************************************** 2026-07-17 10:39:36 - Request: //本地发起第二次请求,请求带上了天气信息 Method: POST URL: https://ws-i70rvm4btlzu3tr0.cn-beijing.maas.aliyuncs.com/compatible-mode/v1/chat/completions Headers: Body: {"messages":[{"role":"system","content":"\r\n你是一个企业通用助手,会根据自己的判断调用Tools。\r\n1、若是不调用Tools,无需提醒Tools并不涉及提问的问题\r\n"},
{"role":"user","content":"今天深圳天气怎么样"},
{"role":"assistant","content":"","tool_calls":[{"id":"call_d573a4da9e484656ad73fa64","type":"function",
"function":{"name":"GetWeather","arguments":"{\r\n \"cityName\": \"深圳\"\r\n}"}}]},
{"role":"tool","tool_call_id":"call_d573a4da9e484656ad73fa64",
"content":"{\r\n \"city\": \"深圳\",\r\n \"temperature\": \"30°C\",\r\n \"condition\": \"阵雨\",\r\n \"updateTime\": \"2026-07-17 10:39\"\r\n}"}],
"model":"qwen3-vl-plus","tools":[{"type":"function","function":{"description":"根据城市名称获取当前时间的天气信息","name":"GetWeather","parameters":{ "type": "object", "required": [ "cityName" ], "properties": { "cityName": { "type": "string" } }, "additionalProperties": false }}}],"tool_choice":"auto"} 2026-07-17 10:39:38 - Response://大模型第二次回复 Status Code: 200 OK Headers: Body: {"id":"chatcmpl-3da8e2e0-ae31-907d-b4df-ed1c2e36decf","object":"chat.completion","created":1784255976,"model":"qwen3-vl-plus",
"choices":[{"index":0,"message":{"role":"assistant","reasoning_content":"",
"content":"今天深圳的天气是阵雨,气温为30°C,数据更新时间为2026年7月17日10:39。建议外出时携带雨具,并注意防暑降温。"},
"finish_reason":"stop","logprobs":null}],
"usage":{"prompt_tokens":386,"total_tokens":432,"completion_tokens":46,"prompt_tokens_details":{"text_tokens":386}}} ************************************************** 今天深圳的天气是阵雨,气温为30°C,数据更新时间为2026年7月17日10:39。建议外出时携带雨具,并注意防暑降温。 调用了WeatherHelper.GetWeather

  至此!!!

 

  

 

posted @ 2026-07-17 11:16  wskxy  阅读(12)  评论(0)    收藏  举报