MEAI.AICallFunc_暂时

decade
9
2025-12-27

using System.ClientModel;
using System.ComponentModel;
using System.Reflection;
using Microsoft.Extensions.AI;
using OpenAI;


namespace MyNlog;

class Program
{
    static async Task Main(string[] args)
    {
        string baseUrl = "https://openrouter.ai/api/v1";
        string apiKey = "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";
        string model = "openai/gpt-5-nano";

        
        #region 创建基础客户端

        OpenAIClientOptions clientOptions = new()
        {
            Endpoint = new Uri(baseUrl)
        };
        
        OpenAIClient aiClient = new(new ApiKeyCredential(apiKey), clientOptions);
        var chatClient = aiClient.GetChatClient(model);
        var CanUseChatClient = chatClient.AsIChatClient();

        #endregion

        #region 反射添加函数
        var travelTools = new FunctionTools();

        IList<AITool> batchRegisteredTools =
            //使用位或来进行参数配置
            //Instance成员方法 Public公共方法 DeclaredOnly当前声明 不查找父类
            typeof(FunctionTools)
                .GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly)
                .Select(method => AIFunctionFactory.Create(
                    method,
                    travelTools,
                    name: method.Name.ToLowerInvariant(),
                    description: method.GetCustomAttribute<DescriptionAttribute>()?.Description))
                .Cast<AITool>()
                .ToList();

        #endregion
        
        #region 注册函数
        string GetCurrentWeather() => Random.Shared.NextDouble() > 0.5 ? "地球毁灭了" : "地球还活着";

        var tools = AIFunctionFactory.Create(GetCurrentWeather,"check","检查当天如何");
        batchRegisteredTools.Add(tools);
        #endregion

        #region 对话配置
        var messages = new[]
        {
            new ChatMessage(ChatRole.System, aiPrompt),
            new ChatMessage(ChatRole.User, "赵博奕在干嘛呢?")
        };

        var options = new ChatOptions
        {
            ToolMode = ChatToolMode.Auto, // 自动决定是否调用工具,默认值为 Auto
            AllowMultipleToolCalls = true, // 允许模型一次调用多个工具,默认 false
            Tools = batchRegisteredTools
        };
        #endregion

        #region 转换客户端

        var client = CanUseChatClient.AsBuilder()
            .UseFunctionInvocation()
            .Build();
        var result = await client.GetResponseAsync(
            messages,
            options
        );

        #endregion

        Console.WriteLine(result.Text);
     
        
       
    }
    

}

class FunctionTools
{
    [Description("检查团队状态")]
    public string DoSomething()
    {
        Console.WriteLine("调用检查团队状态");
        return "大家都很死了呢";
    }
    [Description("获取赵博奕当前状态")]
    public string CheckBoYi()
    {
        Console.WriteLine("调用CheckBoYi");
        return "和它的动物朋友小鹿一起玩耍";
    }
}