Korzystanie z konfiguracji uzupełniania czatu w aplikacji konsolowej platformy .NET

W tym przewodniku utworzysz aplikację do czatu sztucznej inteligencji i wykonasz iterację po wyświetleniu monitu przy użyciu konfiguracji uzupełniania czatu dynamicznie ładowanej z usługi Azure App Configuration.

Wymagania wstępne

Tworzenie aplikacji konsolowej

  1. Utwórz nowy folder dla projektu. W nowym folderze uruchom następujące polecenie, aby utworzyć nowy projekt aplikacji konsolowej platformy .NET:

    dotnet new console
    
  2. Zainstaluj następujące pakiety NuGet w projekcie:

    dotnet add package Microsoft.Extensions.Configuration.AzureAppConfiguration
    dotnet add package Microsoft.Extensions.Configuration.Binder
    dotnet add package Azure.Identity
    dotnet add package Azure.AI.OpenAI
    
  3. Otwórz plik Program.cs i dodaj następujące przestrzenie nazw w górnej części pliku:

    using Microsoft.Extensions.Configuration;
    using Microsoft.Extensions.Configuration.AzureAppConfiguration;
    using Azure.Identity;
    using Azure.AI.OpenAI;
    using OpenAI.Chat;
    
  4. Połącz się z magazynem App Configuration, wywołując metodę AddAzureAppConfiguration w pliku Program.cs.

    Możesz nawiązać połączenie z usługą App Configuration przy użyciu Microsoft Entra ID (zalecane) lub ciągu połączenia. W tym przykładzie używasz Microsoft Entra ID z DefaultAzureCredential do uwierzytelniania się w Twoim sklepie App Configuration. Postępuj zgodnie z tymi instrukcjami, aby przypisać rolę Czytelnik danych konfiguracji aplikacji do tożsamości reprezentowanej przez DefaultAzureCredential. Upewnij się, że przed uruchomieniem aplikacji pozwolisz na wystarczający czas na propagację uprawnień.

    TokenCredential credential = new DefaultAzureCredential();
    IConfigurationRefresher refresher = null;
    
    // Load configuration from Azure App Configuration
    IConfiguration configuration = new ConfigurationBuilder()
        .AddAzureAppConfiguration(options =>
        {
            Uri endpoint = new(Environment.GetEnvironmentVariable("AZURE_APPCONFIGURATION_ENDPOINT") ??
                throw new InvalidOperationException("The environment variable 'AZURE_APPCONFIGURATION_ENDPOINT' is not set or is empty."));
            options.Connect(endpoint, credential)
                // Load all keys that start with "ChatApp:" and have no label.
                .Select("ChatApp:*")
                // Reload configuration if any selected key-values have changed.
                // Use the default refresh interval of 30 seconds. It can be overridden via refreshOptions.SetRefreshInterval.
                .ConfigureRefresh(refreshOptions =>
                {
                    refreshOptions.RegisterAll();
                });
    
            refresher = options.GetRefresher();
        })
        .Build();
    
  5. Utwórz wystąpienie obiektu AzureOpenAIClient , aby nawiązać połączenie z zasobem usługi Azure OpenAI. Do uwierzytelniania można użyć identyfikatora Entra firmy Microsoft lub klucza interfejsu API.

    Aby uzyskać dostęp do zasobu usługi Azure OpenAI za pomocą identyfikatora Entra firmy Microsoft, użyj polecenia DefaultAzureCredential. Przypisz rolę użytkownika OpenAI usług Cognitive Services do tożsamości reprezentowanej przez DefaultAzureCredential. Aby uzyskać szczegółowe instrukcje, zapoznaj się z przewodnikiem Kontrola dostępu oparta na rolach dla usługi Azure OpenAI . Upewnij się, że przed uruchomieniem aplikacji pozwolisz na wystarczający czas na propagację uprawnień.

    // Retrieve the OpenAI connection information from the configuration
    Uri openaiEndpoint = new(configuration["ChatApp:AzureOpenAI:Endpoint"]);
    string deploymentName = configuration["ChatApp:AzureOpenAI:DeploymentName"];
    
    // Initialize the AzureOpenAIClient
    AzureOpenAIClient azureClient = new(openaiEndpoint, credential);
    // Create a chat client
    ChatClient chatClient = azureClient.GetChatClient(deploymentName);
    

    Aby uzyskać dostęp do zasobu usługi Azure OpenAI przy użyciu klucza interfejsu API, dodaj następujący kod:

    // Initialize the AzureOpenAIClient
    var apiKey = configuration["ChatApp:AzureOpenAI:ApiKey"];
    AzureOpenAIClient client = new(openAIEndpoint, new AzureKeyCredential(apiKey));
    

    Jeśli klucz ChatApp:AzureOpenAI:ApiKey jest odwołaniem do usługi Key Vault w usłudze App Configuration, dodaj następujący fragment kodu do AddAzureAppConfiguration wywołania i przyznaj aplikacji dostęp do usługi Key Vault.

    options.ConfigureKeyVault(keyVaultOptions =>
    {
        keyVaultOptions.SetCredential(credential);
    });
    
  6. Zdefiniuj klasę ModelConfiguration w pliku Program.cs :

    internal class ModelConfiguration
    {
        [ConfigurationKeyName("model")]
        public string? Model { get; set; }
    
        [ConfigurationKeyName("messages")]
        public List<Message>? Messages { get; set; }
    
        [ConfigurationKeyName("max_tokens")]
        public int MaxTokens { get; set; }
    
        [ConfigurationKeyName("temperature")]
        public float Temperature { get; set; }
    
        [ConfigurationKeyName("top_p")]
        public float TopP { get; set; }
    }
    
    internal class Message
    {
        [ConfigurationKeyName("role")]
        public required string Role { get; set; }
    
        [ConfigurationKeyName("content")]
        public string? Content { get; set; }
    }
    
  7. Zaktualizuj plik Program.cs , aby dodać metodę GetChatMessages pomocnika do przetwarzania wiadomości czatu:

    // Helper method to convert configuration messages to chat API format
    static IEnumerable<ChatMessage> GetChatMessages(ModelConfiguration modelConfiguration)
    {
        return modelConfiguration.Messages.Select<Message, ChatMessage>(message => message.Role switch
        {
            "system" => ChatMessage.CreateSystemMessage(message.Content),
            "user" => ChatMessage.CreateUserMessage(message.Content),
            "assistant" => ChatMessage.CreateAssistantMessage(message.Content),
            _ => throw new ArgumentException($"Unknown role: {message.Role}", nameof(message.Role))
        });
    }
    
  8. Następnie zaktualizuj istniejący kod w pliku Program.cs , aby odświeżyć konfigurację z usługi Azure App Configuration, zastosować najnowsze wartości konfiguracji sztucznej inteligencji do ustawień uzupełniania czatu i pobrać odpowiedź z modelu AI.

    while (true)
    {
        // Refresh the configuration from Azure App Configuration
        await refresher.RefreshAsync();
    
        // Configure chat completion with AI configuration
        var modelConfiguration = configuration.GetSection("ChatApp:Model").Get<ModelConfiguration>();
        var requestOptions = new ChatCompletionOptions()
        {
            MaxOutputTokenCount = modelConfiguration.MaxTokens,
            Temperature = modelConfiguration.Temperature,
            TopP = modelConfiguration.TopP
        };
    
        foreach (var message in modelConfiguration.Messages)
        {
            Console.WriteLine($"{message.Role}: {message.Content}");
        }
    
        // Get chat response from AI
        var response = await chatClient.CompleteChatAsync(GetChatMessages(modelConfiguration), requestOptions);
        Console.WriteLine($"AI response: {response.Value.Content[0].Text}");
    
        Console.WriteLine("Press Enter to continue...");
        Console.ReadLine();
    }
    
  9. Po wykonaniu poprzednich kroków plik Program.cs powinien teraz zawierać pełną implementację, jak pokazano poniżej:

    using Azure.AI.OpenAI;
    using Azure.Identity;
    using Azure.Core;
    using Microsoft.Extensions.Configuration;
    using Microsoft.Extensions.Configuration.AzureAppConfiguration;
    using OpenAI.Chat;
    
    TokenCredential credential = new DefaultAzureCredential();
    IConfigurationRefresher refresher = null;
    
    // Load configuration from Azure App Configuration
    IConfiguration configuration = new ConfigurationBuilder()
        .AddAzureAppConfiguration(options =>
        {
            Uri endpoint = new(Environment.GetEnvironmentVariable("AZURE_APPCONFIGURATION_ENDPOINT") ??
                throw new InvalidOperationException("The environment variable 'AZURE_APPCONFIGURATION_ENDPOINT' is not set or is empty."));
            options.Connect(endpoint, credential)
                // Load all keys that start with "ChatApp:" and have no label.
                .Select("ChatApp:*")
                // Reload configuration if any selected key-values have changed.
                // Use the default refresh interval of 30 seconds. It can be overridden via refreshOptions.SetRefreshInterval.
                .ConfigureRefresh(refreshOptions =>
                {
                    refreshOptions.RegisterAll();
                });
    
            refresher = options.GetRefresher();
        })
        .Build();
    
    // Retrieve the OpenAI connection information from the configuration
    Uri openaiEndpoint = new(configuration["ChatApp:AzureOpenAI:Endpoint"]);
    string deploymentName = configuration["ChatApp:AzureOpenAI:DeploymentName"];
    
    // Create a chat client
    AzureOpenAIClient azureClient = new(openaiEndpoint, credential);
    ChatClient chatClient = azureClient.GetChatClient(deploymentName);
    
    while (true)
    {
        // Refresh the configuration from Azure App Configuration
        await refresher.RefreshAsync();
    
        // Configure chat completion with AI configuration
        var modelConfiguration = configuration.GetSection("ChatApp:Model").Get<ModelConfiguration>();
        var requestOptions = new ChatCompletionOptions()
        {
            MaxOutputTokenCount = modelConfiguration.MaxTokens,
            Temperature = modelConfiguration.Temperature,
            TopP = modelConfiguration.TopP
        };
    
        foreach (var message in modelConfiguration.Messages)
        {
            Console.WriteLine($"{message.Role}: {message.Content}");
        }
    
        // Get chat response from AI
        var response = await chatClient.CompleteChatAsync(GetChatMessages(modelConfiguration), requestOptions);
        Console.WriteLine($"AI response: {response.Value.Content[0].Text}");
    
        Console.WriteLine("Press Enter to continue...");
        Console.ReadLine();
    
    }
    
    static IEnumerable<ChatMessage> GetChatMessages(ModelConfiguration modelConfiguration)
    {
        return modelConfiguration.Messages.Select<Message, ChatMessage>(message => message.Role switch
        {
            "system" => ChatMessage.CreateSystemMessage(message.Content),
            "user" => ChatMessage.CreateUserMessage(message.Content),
            "assistant" => ChatMessage.CreateAssistantMessage(message.Content),
            _ => throw new ArgumentException($"Unknown role: {message.Role}", nameof(message.Role))
        });
    }
    
    internal class ModelConfiguration
    {
        [ConfigurationKeyName("model")]
        public string? Model { get; set; }
    
        [ConfigurationKeyName("messages")]
        public List<Message>? Messages { get; set; }
    
        [ConfigurationKeyName("max_tokens")]
        public int MaxTokens { get; set; }
    
        [ConfigurationKeyName("temperature")]
        public float Temperature { get; set; }
    
        [ConfigurationKeyName("top_p")]
        public float TopP { get; set; }
    }
    
    internal class Message
    {
        [ConfigurationKeyName("role")]
        public required string Role { get; set; }
    
        [ConfigurationKeyName("content")]
        public string? Content { get; set; }
    }
    

Kompilowanie i uruchamianie aplikacji

  1. Ustaw zmienną środowiskową o nazwie AZURE_APPCONFIGURATION_ENDPOINT na punkt końcowy sklepu App Configuration znajdującego się w obszarze Przegląd sklepu w witrynie Azure Portal.

    Jeśli używasz wiersza polecenia systemu Windows, uruchom następujące polecenie i uruchom ponownie wiersz polecenia, aby zezwolić na wprowadzenie zmian:

    setx AZURE_APPCONFIGURATION_ENDPOINT "<endpoint-of-your-app-configuration-store>"
    

    Jeśli używasz programu PowerShell, uruchom następujące polecenie:

    $Env:AZURE_APPCONFIGURATION_ENDPOINT = "<endpoint-of-your-app-configuration-store>"
    

    Jeśli używasz systemu macOS lub Linux, uruchom następujące polecenie:

    export AZURE_APPCONFIGURATION_ENDPOINT ='<endpoint-of-your-app-configuration-store>'
    
  2. Po prawidłowym ustawieniu zmiennej środowiskowej uruchom następujące polecenie, aby skompilować i uruchomić aplikację.

    dotnet run
    

    Powinny zostać wyświetlone następujące dane wyjściowe:

    system: You are a helpful assistant.
    user: What is the capital of France ?
    AI response: The capital of France is **Paris**.
    Press Enter to continue...
    
    
  3. W portalu Azure wybierz utworzone wystąpienie sklepu App Configuration. W menu Operacje wybierz pozycję Eksplorator konfiguracji i wybierz klucz ChatApp:Model . Zaktualizuj wartość właściwości Messages:

    • Rola: system
    • Zawartość: "Jesteś wesołym przewodnikiem".
  4. Poczekaj chwilę na upłynięcie interwału odświeżania, a następnie naciśnij Enter, aby zobaczyć zaktualizowaną odpowiedź sztucznej inteligencji w danych wyjściowych.

    system: You are a cheerful tour guide
    user: What is the capital of France ?
    AI response: Oh là là! The capital of France is the magnificent **Paris**!
    Known as the "City of Light" (*La Ville Lumière*), it's famous for its romantic ambiance,
    iconic landmarks like the Eiffel Tower, the Louvre Museum, and Notre-Dame Cathedral,
    as well as its delicious pastries and charming cafés.
    Have you ever been, or is it on your travel bucket list? 😊✨
    Press Enter to continue...