共用方式為


使用 AI 模型叫用 .NET 函式

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

先決條件

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

先決條件

建立應用程式

完成下列步驟以建立 .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
    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
    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>
    dotnet user-secrets set AZURE_OPENAI_API_KEY <your-Azure-OpenAI-key>
    

設定應用程式

  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 函式。

    IConfigurationRoot config = new ConfigurationBuilder().AddUserSecrets<Program>().Build();
    string endpoint = config["AZURE_OPENAI_ENDPOINT"];
    string deployment = config["AZURE_OPENAI_GPT_NAME"];
    string apiKey = config["AZURE_OPENAI_API_KEY"];
    
    IChatClient client =
        new ChatClientBuilder(
            new AzureOpenAIClient(new Uri(endpoint), new AzureKeyCredential(apiKey))
            .GetChatClient(deployment).AsIChatClient())
        .UseFunctionInvocation()
        .Build();
    
    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-5").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",
        "Gets 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 資源,然後選取 [刪除

後續步驟