使用 AI 模型调用 .NET 函数

在本快速入门中,你将创建一个 .NET 控制台 AI 聊天应用,以连接到启用了本地函数调用的 AI 模型。 应用使用 Microsoft.Extensions.AI 库,因此可以使用 AI 抽象而不是特定 SDK 编写代码。 借助 AI 抽象,你可以通过最少的代码更改来更改基础 AI 模型。

先决条件

先决条件

注释

你还可以使用语义内核完成本文中的任务。 语义内核是一种轻型开源 SDK,可用于生成 AI 代理并将最新的 AI 模型集成到 .NET 应用中。

创建应用

完成以下步骤,创建 .NET 控制台应用以连接到 AI 模型。

  1. 在计算机上的空目录中,使用 dotnet new 命令创建新的控制台应用:

    dotnet new console -o FunctionCallingAI
    
  2. 将目录更改为应用文件夹:

    cd FunctionCallingAI
    
  3. 安装所需的包:

    dotnet add package Azure.Identity
    dotnet add package Azure.AI.OpenAI
    dotnet add package Microsoft.Extensions.AI
    dotnet add package Microsoft.Extensions.AI.OpenAI --prerelease
    dotnet add package Microsoft.Extensions.Configuration
    dotnet add package Microsoft.Extensions.Configuration.UserSecrets
    
    dotnet add package Microsoft.Extensions.AI
    dotnet add package Microsoft.Extensions.AI.OpenAI --prerelease
    dotnet add package Microsoft.Extensions.Configuration
    dotnet add package Microsoft.Extensions.Configuration.UserSecrets
    
  4. 在 Visual Studio Code 或所选编辑器中打开应用

    code .
    

创建 AI 服务

  1. 若要预配 Azure OpenAI 服务和模型,请完成 创建和部署 Azure OpenAI 服务资源 文章中的步骤。

  2. 在终端或命令提示符下,导航到项目目录的根目录。

  3. 运行以下命令为示例应用配置 Azure OpenAI 终结点和模型名称:

    dotnet user-secrets init
    dotnet user-secrets set AZURE_OPENAI_ENDPOINT <your-Azure-OpenAI-endpoint>
    dotnet user-secrets set AZURE_OPENAI_GPT_NAME <your-Azure-OpenAI-model-name>
    

配置应用

  1. 从终端或命令提示符导航到 .NET 项目的根目录。

  2. 运行以下命令,将 OpenAI API 密钥配置为示例应用的机密:

    dotnet user-secrets init
    dotnet user-secrets set OpenAIKey <your-OpenAI-key>
    dotnet user-secrets set ModelName <your-OpenAI-model-name>
    

添加应用代码

应用使用该 Microsoft.Extensions.AI 包向 AI 模型发送和接收请求。

  1. Program.cs 文件中,添加以下代码以连接到 AI 模型并进行身份验证。 它还 ChatClient 配置为使用函数调用,从而使 AI 模型能够在你的代码中调用 .NET 函数。

    using Microsoft.Extensions.Configuration;
    using Microsoft.Extensions.AI;
    using Azure.AI.OpenAI;
    using Azure.Identity;
    
    var config = new ConfigurationBuilder().AddUserSecrets<Program>().Build();
    string endpoint = config["AZURE_OPENAI_ENDPOINT"];
    string deployment = config["AZURE_OPENAI_GPT_NAME"];
    
    IChatClient client =
        new ChatClientBuilder(
            new AzureOpenAIClient(new Uri(endpoint), new DefaultAzureCredential())
            .GetChatClient(deployment).AsIChatClient())
        .UseFunctionInvocation()
        .Build();
    

    注释

    DefaultAzureCredential 从本地工具中搜寻身份验证凭据。 如果不使用 azd 模板来预配 Azure OpenAI 资源,则需要将 Azure AI Developer 角色分配给用于登录到 Visual Studio 或 Azure CLI 的帐户。 有关详细信息,请参阅使用 .NET 向 Azure AI 服务进行身份验证

    using Microsoft.Extensions.AI;
    using Microsoft.Extensions.Configuration;
    using OpenAI;
    
    IConfigurationRoot config = new ConfigurationBuilder().AddUserSecrets<Program>().Build();
    string? model = config["ModelName"];
    string? key = config["OpenAIKey"];
    
    IChatClient client =
        new ChatClientBuilder(new OpenAIClient(key).GetChatClient(model ?? "gpt-4o").AsIChatClient())
        .UseFunctionInvocation()
        .Build();
    
  2. 创建包含 AI 模型可以调用以获取当前天气的内联函数的新 ChatOptions 对象。 函数声明包括运行逻辑的委托,以及用于将函数用途描述为 AI 模型的名称和说明参数。

    // Add a new plugin with a local .NET function
    // that should be available to the AI model.
    var chatOptions = new ChatOptions
    {
        Tools = [AIFunctionFactory.Create((string ___location, string unit) =>
        {
            // Here you would call a weather API
            // to get the weather for the ___location.
            return "Periods of rain or drizzle, 15 C";
        },
        "get_current_weather",
        "Get the current weather in a given ___location")]
    };
    
  3. 向模型添加系统提示 chatHistory 以提供上下文和说明。 发送带有问题的用户提示,要求 AI 模型调用注册函数来正确回答问题。

    // System prompt to provide context.
    List<ChatMessage> chatHistory = [new(ChatRole.System, """
        You are a hiking enthusiast who helps people discover fun hikes in their area. You are upbeat and friendly.
        """)];
    
    // Weather conversation relevant to the registered function.
    chatHistory.Add(new ChatMessage(ChatRole.User,
        "I live in Montreal and I'm looking for a moderate intensity hike. What's the current weather like?"));
    Console.WriteLine($"{chatHistory.Last().Role} >>> {chatHistory.Last()}");
    
    ChatResponse response = await client.GetResponseAsync(chatHistory, chatOptions);
    Console.WriteLine($"Assistant >>> {response.Text}");
    
  4. 使用 dotnet run 命令运行应用:

    dotnet run
    

    应用打印来自 AI 模型的完成响应,其中包括 .NET 函数提供的数据。 AI 模型理解已注册的函数可用,并自动调用它以生成适当的响应。

清理资源

如果不再需要它们,请删除 Azure OpenAI 资源和 GPT-4 模型部署。

  1. Azure 门户中,导航到 Azure OpenAI 资源。
  2. 选择 Azure OpenAI 资源,然后选择 删除

后续步骤