Korzystanie z konfiguracji uzupełniania czatu w aplikacji konsolowej języka Go

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.

Pełny przykładowy kod źródłowy jest dostępny w repozytorium GitHub usługi Azure App Configuration.

Wymagania wstępne

Tworzenie aplikacji konsolowej

  1. Utwórz nowy katalog dla projektu i przejdź do niego:

    mkdir chatapp-quickstart
    cd chatapp-quickstart
    
  2. Zainicjuj nowy moduł języka Go:

    go mod init chatapp-quickstart
    
  3. Zainstaluj wymagane pakiety Języka Go:

    go get github.com/Azure/AppConfiguration-GoProvider/azureappconfiguration
    go get github.com/Azure/azure-sdk-for-go/sdk/azidentity
    go get github.com/openai/openai-go
    
  4. Utwórz plik o nazwie main.go i dodaj następujące instrukcje importowania:

    package main
    
    import (
        "bufio"
        "context"
        "fmt"
        "log"
        "os"
    
        "github.com/Azure/AppConfiguration-GoProvider/azureappconfiguration"
        "github.com/Azure/azure-sdk-for-go/sdk/azidentity"
        openai "github.com/openai/openai-go"
        "github.com/openai/openai-go/azure"
    )
    
  5. Zdefiniuj struktury konfiguracji i utwórz globalną zmienną poświadczeń:

    type AIConfig struct {
        ChatCompletion ChatCompletion
        AzureOpenAI    AzureOpenAI
    }
    
    type ChatCompletion struct {
        Model       string    `json:"model"`
        Messages    []Message `json:"messages"`
        MaxTokens   int64     `json:"max_tokens"`
        Temperature float64   `json:"temperature"`
        TopP        float64   `json:"top_p"`
    }
    
    type AzureOpenAI struct {
        Endpoint   string
        APIVersion string
        APIKey     string
    }
    
    type Message struct {
        Role    string `json:"role"`
        Content string `json:"content"`
    }
    
    var aiConfig AIConfig
    var tokenCredential, _ = azidentity.NewDefaultAzureCredential(nil)
    
  6. Utwórz funkcję do załadowania konfiguracji z usługi Azure App Configuration.

    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 wraz z DefaultAzureCredential do uwierzytelniania w 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ń.

    // Load configuration from Azure App Configuration
    func loadAzureAppConfiguration(ctx context.Context) (*azureappconfiguration.AzureAppConfiguration, error) {
        endpoint := os.Getenv("AZURE_APPCONFIGURATION_ENDPOINT")
        if endpoint == "" {
            return nil, fmt.Errorf("AZURE_APPCONFIGURATION_ENDPOINT environment variable is not set")
        }
    
        authOptions := azureappconfiguration.AuthenticationOptions{
            Endpoint:   endpoint,
            Credential: tokenCredential,
        }
    
        options := &azureappconfiguration.Options{
            Selectors: []azureappconfiguration.Selector{
                // Load all keys that start with "ChatApp:" and have no label
                {
                    KeyFilter: "ChatApp:*",
                },
            },
            TrimKeyPrefixes: []string{"ChatApp:"},
            // Reload configuration if any selected key-values have changed.
            // Use the default refresh interval of 30 seconds. It can be overridden via RefreshOptions.Interval
            RefreshOptions: azureappconfiguration.KeyValueRefreshOptions{
                Enabled:  true,
            },
            KeyVaultOptions: azureappconfiguration.KeyVaultOptions{
                Credential: tokenCredential,
            },
        }
    
        return azureappconfiguration.Load(ctx, authOptions, options)
    }
    
  7. Utwórz funkcję główną, która konfiguruje uzupełnianie czatów przy użyciu konfiguracji sztucznej inteligencji i rejestruje wywołanie zwrotne w celu odświeżenia konfiguracji sztucznej inteligencji w przypadku zmian.

    func main() {
        configProvider, err := loadAzureAppConfiguration(context.Background())
        if err != nil {
            log.Fatal("Error loading Azure App Configuration:", err)
        }
    
        // Configure chat completion with AI configuration
        configProvider.Unmarshal(&aiConfig, &azureappconfiguration.ConstructionOptions{Separator: ":"})
    
        // Register a callback to refresh AI configuration on changes
        configProvider.OnRefreshSuccess(func() {
            configProvider.Unmarshal(&aiConfig, &azureappconfiguration.ConstructionOptions{Separator: ":"})
        })
    }
    
  8. 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ń.

    openAIClient := openai.NewClient(azure.WithEndpoint(aiConfig.AzureOpenAI.Endpoint, aiConfig.AzureOpenAI.APIVersion), azure.WithTokenCredential(tokenCredential))
    

    Aby uzyskać dostęp do zasobu usługi Azure OpenAI przy użyciu klucza interfejsu API, dodaj następujący kod. Jeśli klucz ChatApp:AzureOpenAI:ApiKey jest odwołaniem usługi Key Vault w usłudze App Configuration, upewnij się, że aplikacja ma dostęp do usługi Key Vault.

    openAIClient := openai.NewClient(azure.WithAPIKey(aiConfig.AzureOpenAI.APIKey), azure.WithEndpoint(aiConfig.AzureOpenAI.Endpoint, aiConfig.AzureOpenAI.APIVersion))
    
  9. Utwórz funkcję, aby uzyskać odpowiedzi sztucznej inteligencji z klienta OpenAI:

    func getAIResponse(openAIClient openai.Client, chatConversation []openai.ChatCompletionMessageParamUnion) (string, error) {
        var completionMessages []openai.ChatCompletionMessageParamUnion
    
        for _, msg := range aiConfig.ChatCompletion.Messages {
            switch msg.Role {
            case "system":
                completionMessages = append(completionMessages, openai.SystemMessage(msg.Content))
            case "user":
                completionMessages = append(completionMessages, openai.UserMessage(msg.Content))
            case "assistant":
                completionMessages = append(completionMessages, openai.AssistantMessage(msg.Content))
            }
        }
    
        // Add the chat conversation history
        completionMessages = append(completionMessages, chatConversation...)
    
        // Create chat completion parameters
        params := openai.ChatCompletionNewParams{
            Messages:    completionMessages,
            Model:       aiConfig.ChatCompletion.Model,
            MaxTokens:   openai.Int(aiConfig.ChatCompletion.MaxTokens),
            Temperature: openai.Float(aiConfig.ChatCompletion.Temperature),
            TopP:        openai.Float(aiConfig.ChatCompletion.TopP),
        }
    
        if completion, err := openAIClient.Chat.Completions.New(context.Background(), params); err != nil {
            return "", err
        } else {
            return completion.Choices[0].Message.Content, nil
        }
    }
    
  10. Następnie zaktualizuj funkcję main, aby dodać pętlę czatu:

    func main() {
        // ...Existing code...
    
        // Initialize chat conversation
        var chatConversation []openai.ChatCompletionMessageParamUnion
        fmt.Println("Chat started! What's on your mind?")
        reader := bufio.NewReader(os.Stdin)
    
        for {
            // Refresh the configuration from Azure App Configuration
            configProvider.Refresh(context.Background())
    
            // Get user input
            fmt.Print("You: ")
            userInput, _ := reader.ReadString('\n')
    
            // Exit if user input is empty
            if userInput == "" {
                fmt.Println("Exiting Chat. Goodbye!")
                break
            }
    
            // Add user message to chat conversation
            chatConversation = append(chatConversation, openai.UserMessage(userInput))
    
            // Get AI response and add it to chat conversation
            response, _ := getAIResponse(openAIClient, chatConversation)
            fmt.Printf("AI: %s\n", response)
            chatConversation = append(chatConversation, openai.AssistantMessage(response))
    
            fmt.Println()
        }
    }
    
  11. Po wykonaniu poprzednich kroków twój plik main.go powinien teraz zawierać pełną implementację, jak pokazano poniżej:

    package main
    
    import (
        "bufio"
        "context"
        "fmt"
        "log"
        "os"
    
        "github.com/Azure/AppConfiguration-GoProvider/azureappconfiguration"
        "github.com/Azure/azure-sdk-for-go/sdk/azidentity"
        openai "github.com/openai/openai-go"
        "github.com/openai/openai-go/azure"
    )
    
    type AIConfig struct {
        ChatCompletion ChatCompletion
        AzureOpenAI    AzureOpenAI
    }
    
    type ChatCompletion struct {
        Model       string    `json:"model"`
        Messages    []Message `json:"messages"`
        MaxTokens   int64     `json:"max_tokens"`
        Temperature float64   `json:"temperature"`
        TopP        float64   `json:"top_p"`
    }
    
    type AzureOpenAI struct {
        Endpoint   string
        APIVersion string
        APIKey     string
    }
    
    type Message struct {
        Role    string `json:"role"`
        Content string `json:"content"`
    }
    
    var aiConfig AIConfig
    var tokenCredential, _ = azidentity.NewDefaultAzureCredential(nil)
    
    func main() {
        configProvider, err := loadAzureAppConfiguration(context.Background())
        if err != nil {
            log.Fatal("Error loading Azure App Configuration:", err)
        }
    
        // Configure chat completion with AI configuration
        configProvider.Unmarshal(&aiConfig, &azureappconfiguration.ConstructionOptions{Separator: ":"})
    
        // Register a callback to refresh AI configuration on changes
        configProvider.OnRefreshSuccess(func() {
            configProvider.Unmarshal(&aiConfig, &azureappconfiguration.ConstructionOptions{Separator: ":"})
        })
    
        // Create a chat client using API key if available, otherwise use the DefaultAzureCredential
        var openAIClient openai.Client
        if aiConfig.AzureOpenAI.APIKey != "" {
            openAIClient = openai.NewClient(azure.WithAPIKey(aiConfig.AzureOpenAI.APIKey), azure.WithEndpoint(aiConfig.AzureOpenAI.Endpoint, aiConfig.AzureOpenAI.APIVersion))
        } else {
            openAIClient = openai.NewClient(azure.WithEndpoint(aiConfig.AzureOpenAI.Endpoint, aiConfig.AzureOpenAI.APIVersion), azure.WithTokenCredential(tokenCredential))
        }
    
        // Initialize chat conversation
        var chatConversation []openai.ChatCompletionMessageParamUnion
        fmt.Println("Chat started! What's on your mind?")
        reader := bufio.NewReader(os.Stdin)
    
        for {
            // Refresh the configuration from Azure App Configuration
            configProvider.Refresh(context.Background())
    
            // Get user input
            fmt.Print("You: ")
            userInput, _ := reader.ReadString('\n')
    
            // Exit if user input is empty
            if userInput == "" {
                fmt.Println("Exiting Chat. Goodbye!")
                break
            }
    
            // Add user message to chat conversation
            chatConversation = append(chatConversation, openai.UserMessage(userInput))
    
            // Get AI response and add it to chat conversation
            response, _ := getAIResponse(openAIClient, chatConversation)
            fmt.Printf("AI: %s\n", response)
            chatConversation = append(chatConversation, openai.AssistantMessage(response))
    
            fmt.Println()
        }
    }
    
    // Load configuration from Azure App Configuration
    func loadAzureAppConfiguration(ctx context.Context) (*azureappconfiguration.AzureAppConfiguration, error) {
        endpoint := os.Getenv("AZURE_APPCONFIGURATION_ENDPOINT")
        if endpoint == "" {
            return nil, fmt.Errorf("AZURE_APPCONFIGURATION_ENDPOINT environment variable is not set")
        }
    
        authOptions := azureappconfiguration.AuthenticationOptions{
            Endpoint:   endpoint,
            Credential: tokenCredential,
        }
    
        options := &azureappconfiguration.Options{
            Selectors: []azureappconfiguration.Selector{
                // Load all keys that start with "ChatApp:" and have no label
                {
                    KeyFilter: "ChatApp:*",
                },
            },
            TrimKeyPrefixes: []string{"ChatApp:"},
            // Reload configuration if any selected key-values have changed.
            // Use the default refresh interval of 30 seconds. It can be overridden via RefreshOptions.Interval
            RefreshOptions: azureappconfiguration.KeyValueRefreshOptions{
                Enabled:  true,
            },
            KeyVaultOptions: azureappconfiguration.KeyVaultOptions{
                Credential: tokenCredential,
            },
        }
    
        return azureappconfiguration.Load(ctx, authOptions, options)
    }
    
    func getAIResponse(openAIClient openai.Client, chatConversation []openai.ChatCompletionMessageParamUnion) (string, error) {
        var completionMessages []openai.ChatCompletionMessageParamUnion
    
        for _, msg := range aiConfig.ChatCompletion.Messages {
            switch msg.Role {
            case "system":
                completionMessages = append(completionMessages, openai.SystemMessage(msg.Content))
            case "user":
                completionMessages = append(completionMessages, openai.UserMessage(msg.Content))
            case "assistant":
                completionMessages = append(completionMessages, openai.AssistantMessage(msg.Content))
            }
        }
    
        // Add the chat conversation history
        completionMessages = append(completionMessages, chatConversation...)
    
        // Create chat completion parameters
        params := openai.ChatCompletionNewParams{
            Messages:    completionMessages,
            Model:       aiConfig.ChatCompletion.Model,
            MaxTokens:   openai.Int(aiConfig.ChatCompletion.MaxTokens),
            Temperature: openai.Float(aiConfig.ChatCompletion.Temperature),
            TopP:        openai.Float(aiConfig.ChatCompletion.TopP),
        }
    
        if completion, err := openAIClient.Chat.Completions.New(context.Background(), params); err != nil {
            return "", err
        } else {
            return completion.Choices[0].Message.Content, nil
        }
    }
    

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 "<AppConfigurationEndpoint>"
    

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

    $Env:AZURE_APPCONFIGURATION_ENDPOINT = "<AppConfigurationEndpoint>"
    

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

    export AZURE_APPCONFIGURATION_ENDPOINT='<AppConfigurationEndpoint>'
    
  2. Po poprawnym ustawieniu zmiennej środowiskowej uruchom następujące polecenia, aby skompilować i uruchomić aplikację:

    go mod tidy
    go run main.go
    
  3. Wpisz komunikat "Jaka jest Twoja nazwa?" po wyświetleniu monitu z komunikatem "You:", a następnie naciśnij Enter.

    Chat started! What's on your mind?
    You: What is your name?
    AI: I'm your helpful assistant! I don't have a personal name, but you can call me whatever you'd like. 
    😊 Do you have a name in mind?
    
  4. W witrynie Azure Portal wybierz utworzone wystąpienie sklepu App Configuration. W menu Operacje wybierz pozycję Eksplorator konfiguracji i wybierz klucz ChatApp:ChatCompletion . Zaktualizuj wartość właściwości Messages:

    • Rola: system
    • Zawartość: "Jesteś piratem, a Twoje imię to Eddy".
  5. Wpisz ten sam komunikat po wyświetleniu monitu z komunikatem "You:". Pamiętaj, aby poczekać kilka 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.

    Chat started! What's on your mind?
    You: What is your name?
    AI: I'm your helpful assistant! I don't have a personal name, but you can call me whatever you'd like. 
    😊 Do you have a name in mind?
    
    You: What is your name?
    AI: Arrr, matey! Me name be Eddy, the most fearsome pirate to ever sail the seven seas!
    What be yer name, landlubber?