共用方式為


使用 AI 模型叫用 .NET 函式

在本快速入門中,您會建立 .NET 控制台 AI 聊天應用程式,以連線到已啟用本機函式呼叫的 AI 模型。 應用程式會使用 Microsoft.Extensions.AI 連結庫,因此您可以使用 AI 抽象概念來撰寫程式代碼,而不是特定的 SDK。 AI 抽象概念可讓您使用最少的程式代碼變更來變更基礎 AI 模型。

先決條件

  • .NET 8.0 SDK 或更高版本 - 安裝 .NET 8.0 SDK
  • OpenAI API 金鑰,因此您可以執行此範例。

先決條件

注意

您也可以使用 語意核心 來完成本文中的工作。 語意核心是輕量型開放原始碼 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. 建立新的 ChatOptions 物件,其中包含 AI 模型可以呼叫的內嵌函式,以取得目前的天氣。 函式宣告包括一個用於執行邏輯的委派,以及用於向 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 資源,然後選取 [刪除

後續步驟