UseFunctionInvocation()ChatOptions.ToolMode = Auto
// 方式 A:课程辅助类(推荐)
var chatClient = AIClientHelper.GetDefaultChatClient();
// 方式 B:自行创建(示意)
// var chatClient = new OpenAIChatClient(apiKey: "...", model: "gpt-4o-...");using Microsoft.Extensions.AI;
// 最小示例:无入参,返回字符串
string GetCurrentWeather() => Random.Shared.NextDouble() > 0.5 ? "It's sunny" : "It's raining";
var tools = AIFunctionFactory.Create(GetCurrentWeather, name: "GetCurrentWeather", description: "查询当前天气");稍复杂(带描述/类型)
using System.ComponentModel;
public record WeatherReport(string City, int TemperatureCelsius, bool WillRain);
public class TravelToolset
{
[Description("查询指定城市的实时天气")]
public WeatherReport QueryWeather(string city)
=> new(city, 25, willRain: false);
}
var travelTools = AIFunctionFactory.CreateFromMethods(new TravelToolset());var client = chatClient.AsBuilder()
.UseFunctionInvocation() // 🔧 关键:启用自动函数调用
.Build();var messages = new List<ChatMessage>
{
new(ChatRole.System, "你是出行助手,善于调用工具给出穿搭建议。"),
new(ChatRole.User, "帮我查看今天北京的天气,要不要带伞?")
};
var options = new ChatOptions
{
ToolMode = ChatToolMode.Auto,
Tools = [ tools ] // 或 travelTools
};
var response = await client.GetResponseAsync(messages, options);
Console.WriteLine(response.Text);依赖:Microsoft.Extensions.AI(以及选用的提供方实现,如 Microsoft.Extensions.AI.OpenAI 或 Azure.AI.OpenAI)
using System;
using System.Collections.Generic;
using Microsoft.Extensions.AI;
class Program
{
static async System.Threading.Tasks.Task Main()
{
// 1) 获取 ChatClient
var chatClient = AIClientHelper.GetDefaultChatClient();
// 2) 注册工具
string GetCurrentWeather() => Random.Shared.NextDouble() > 0.5 ? "It's sunny" : "It's raining";
var tools = AIFunctionFactory.Create(GetCurrentWeather, name: "GetCurrentWeather", description: "查询当前天气");
// 3) 启用函数调用
var client = chatClient.AsBuilder().UseFunctionInvocation().Build();
// 4) 配置与对话
var messages = new List<ChatMessage>
{
new(ChatRole.System, "你是出行助手,善于调用工具给出穿搭建议。"),
new(ChatRole.User, "帮我查看今天北京的天气,要不要带伞?")
};
var options = new ChatOptions { ToolMode = ChatToolMode.Auto, Tools = [ tools ] };
var result = await client.GetResponseAsync(messages, options);
Console.WriteLine(result.Text);
}
}
模式 | 含义 | 适用场景 |
|---|---|---|
None | 禁用工具调用 | 只对话,不走工具 |
Auto | 模型自行决定是否调用 | 通用推荐,灵活强 |
RequireAny | 必须调用任意一个工具 | 强制走工具流程 |
RequireSpecific("name") | 必须调用指定工具 | 固定关键步骤 |
ToolMode 是否为 Auto/Require*RequireSpecific 强制关键工具UseFunctionInvocation 叠加中间件:日志/缓存/限流AdditionalTools,场景内复用MEAI 的函数调用把“模型 + 你的业务能力”无缝拼起来:声明工具、打开开关、开始对话,剩下的交给中间件自动编排。