Utilizzare la configurazione di completamento della chat in un'applicazione console Go

In questa guida si compila un'applicazione di chat di intelligenza artificiale e si esegue l'iterazione al prompt usando la configurazione di completamento della chat caricata dinamicamente da Configurazione app di Azure.

Il codice sorgente di esempio completo è disponibile nel repository GitHub di Azure App Configuration.

Prerequisiti

Creare un'app console

  1. Crea una nuova directory per il tuo progetto e naviga al suo interno.

    mkdir chatapp-quickstart
    cd chatapp-quickstart
    
  2. Inizializzare un nuovo modulo Go:

    go mod init chatapp-quickstart
    
  3. Installare i pacchetti Go necessari:

    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. Creare un file denominato main.go e aggiungere le istruzioni import seguenti:

    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. Definire le strutture di configurazione e creare una variabile di credenziali globale:

    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. Creare una funzione per caricare la configurazione da Configurazione app di Azure.

    È possibile connettersi a App Configuration usando Microsoft Entra ID (scelta consigliata) o una stringa di connessione. In questo esempio si usa Microsoft Entra ID con DefaultAzureCredential per eseguire l'autenticazione all'archivio di Configurazione app. Seguire queste istruzioni per assegnare il ruolo Lettore dati di Configurazione app all'identità rappresentata da DefaultAzureCredential. Assicurarsi di consentire tempo sufficiente per la propagazione dell'autorizzazione prima di eseguire l'applicazione.

    // 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. Creare la funzione principale che configura il completamento della chat con la configurazione di intelligenza artificiale e registra un callback per aggiornare la configurazione di intelligenza artificiale in caso di modifiche.

    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. Creare un'istanza AzureOpenAIClient di per connettersi alla risorsa OpenAI di Azure. È possibile usare Microsoft Entra ID o chiave API per l'autenticazione.

    Per accedere alla risorsa OpenAI di Azure con Microsoft Entra ID, usare DefaultAzureCredential. Assegnare il ruolo Utente dei Servizi cognitivi OpenAI all'identità rappresentata da DefaultAzureCredential. Per i passaggi dettagliati, vedere la guida al controllo degli accessi in base al ruolo per il servizio Azure OpenAI . Assicurarsi di consentire tempo sufficiente per la propagazione dell'autorizzazione prima di eseguire l'applicazione.

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

    Per accedere alla risorsa OpenAI di Azure con una chiave API, aggiungere il codice seguente. Se la chiave ChatApp:AzureOpenAI:ApiKey è un riferimento a Key Vault in Configurazione app, assicurati di concedere all'app accesso a Key Vault.

    openAIClient := openai.NewClient(azure.WithAPIKey(aiConfig.AzureOpenAI.APIKey), azure.WithEndpoint(aiConfig.AzureOpenAI.Endpoint, aiConfig.AzureOpenAI.APIVersion))
    
  9. Creare una funzione per ottenere risposte di intelligenza artificiale dal client 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. Aggiornare quindi la funzione main per aggiungere il ciclo di chat:

    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. Dopo aver completato i passaggi precedenti, il main.go file dovrebbe ora contenere l'implementazione completa, come illustrato di seguito:

    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
        }
    }
    

Compilare ed eseguire l'app

  1. Impostare la variabile di ambiente denominata AZURE_APPCONFIGURATION_ENDPOINT sull'endpoint del tuo App Configuration trovato nella sezione Panoramica del tuo store nel portale di Azure.

    Se si usa il prompt dei comandi di Windows, eseguire il comando seguente e riavviare il prompt per rendere effettiva la modifica:

    setx AZURE_APPCONFIGURATION_ENDPOINT "<AppConfigurationEndpoint>"
    

    Se si usa PowerShell, eseguire il comando seguente:

    $Env:AZURE_APPCONFIGURATION_ENDPOINT = "<AppConfigurationEndpoint>"
    

    Se si usa macOS o Linux, eseguire il comando seguente:

    export AZURE_APPCONFIGURATION_ENDPOINT='<AppConfigurationEndpoint>'
    
  2. Dopo aver impostato correttamente la variabile di ambiente, eseguire i comandi seguenti per compilare ed eseguire l'app:

    go mod tidy
    go run main.go
    
  3. Digitare il messaggio "Qual è il nome?" quando viene richiesto "You:" e quindi premere INVIO.

    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. Nel portale di Azure, seleziona l'istanza dell'archivio di configurazione dell'app che hai creato. Dal menu Operazioni selezionare Esplora configurazione e selezionare la chiave ChatApp:ChatCompletion . Aggiornare il valore della proprietà Messages:

    • Ruolo: sistema
    • Contenuto: "Sei un pirata e il tuo nome è Eddy".
  5. Digitare lo stesso messaggio quando viene visualizzato il prompt "You:". Assicurarsi di attendere alcuni istanti prima che l'intervallo di aggiornamento sia trascorso e quindi premere INVIO per visualizzare la risposta di intelligenza artificiale aggiornata nell'output.

    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?