Python konsol uygulamasında sohbet tamamlama yapılandırmasını kullanma

Bu kılavuzda bir yapay zeka sohbet uygulaması oluşturup Azure Uygulama Yapılandırması'ndan dinamik olarak yüklenen sohbet tamamlama yapılandırmasını kullanarak istem üzerinde yineleme yaparsınız.

Örnek kaynak kodunun tamamı Azure Uygulama Yapılandırması GitHub deposunda bulunur.

Önkoşullar

Konsol uygulaması oluşturma

  1. Projeniz için yeni bir dizin oluşturun ve bu dizine gidin:

    mkdir chatapp-quickstart
    cd chatapp-quickstart
    
  2. Gerekli Python paketlerini yükleyin:

    pip install azure-appconfiguration-provider
    pip install azure-identity
    pip install azure-ai-inference
    
  3. adlı app.py bir dosya oluşturun ve aşağıdaki içeri aktarma deyimlerini ekleyin:

    import os
    from azure.appconfiguration.provider import load, SettingSelector, WatchKey
    from azure.identity import DefaultAzureCredential
    from azure.ai.inference import ChatCompletionsClient
    
  4. Azure Uygulama Yapılandırması'ndan yapılandırmayı yüklemek için bir işlev oluşturun.

    Microsoft Entra ID (önerilen) veya bir bağlantı dizesi kullanarak Uygulama Yapılandırmasına bağlanabilirsiniz. Bu örnekte, Uygulama Yapılandırma deposuna kimlik doğrulaması yapmak için DefaultAzureCredential ile Microsoft Entra ID'yi kullanırsınız. Tarafından temsil edilen kimliğe Uygulama Yapılandırma Veri Okuyucusu rolünü atamak için bu DefaultAzureCredential izleyin. Uygulamanızı çalıştırmadan önce iznin yayılması için yeterli süreye izin verdiğinden emin olun.

    credential = DefaultAzureCredential()
    
    def load_azure_app_configuration():
        endpoint = os.environ.get("AZURE_APPCONFIGURATION_ENDPOINT")
        if not endpoint:
            raise ValueError("AZURE_APPCONFIGURATION_ENDPOINT environment variable is not set")
    
        config = load(
            endpoint=endpoint,
            credential=credential,
            # Load all keys that start with "ChatApp:" and have no label
            selectors=[SettingSelector(key_filter="ChatApp:*")],
            trim_prefixes=["ChatApp:"],
            # Reload configuration if the ChatCompletion key has changed.
            # Use the default refresh interval of 30 seconds. It can be overridden via refresh_interval.
            refresh_on=[WatchKey("ChatApp:ChatCompletion")],
        )
        return config
    
  5. Sohbet istemcisinden yapay zeka yanıtları almak için bir işlev oluşturun:

    def get_ai_response(client, config, chat_conversation):
        chat_completion_config = config["ChatCompletion"]
        messages = []
    
        # Add configured messages (system, user, assistant)
        if not chat_completion_config.get("messages"):
            chat_completion_config["messages"] = []
    
        for msg in chat_completion_config["messages"]:
            messages.append({"role": msg["role"], "content": msg["content"]})
    
        # Add the chat conversation history
        messages.extend(chat_conversation)
    
        # Create chat completion
        response = client.complete(
            model=chat_completion_config["model"],
            messages=messages,
        )
        return response.choices[0].message.content
    
  6. Sohbet istemcisini yapılandıran ve sohbet döngüsünü çalıştıran ana işlevi oluşturun.

    Azure Yapay Zeka Atölyesi'ye bağlanmak için ChatCompletionsClient öğesinin bir örneğini oluşturun. DefaultAzureCredential kimlik doğrulaması yapmak ve DefaultAzureCredential tarafından temsil edilen kimliğe Cognitive Services OpenAI User rolünü atamak için kullanın. Ayrıntılı adımlar için Azure OpenAI hizmeti için rol tabanlı erişim denetimi kılavuzuna bakın. Uygulamanızı çalıştırmadan önce iznin yayılması için yeterli süreye izin verdiğinden emin olun.

    def main():
        config = load_azure_app_configuration()
    
        # Create a chat completions client using Microsoft Entra ID
        client = ChatCompletionsClient(
            endpoint=config["AzureAIFoundry:Endpoint"],
            credential=credential,
            credential_scopes=["https://cognitiveservices.azure.com/.default"],
        )
    
        # Initialize chat conversation
        chat_conversation = []
        print("Chat started! What's on your mind?")
    
        while True:
            # Refresh the configuration from Azure App Configuration
            config.refresh()
    
            # Get user input
            user_input = input("You: ")
    
            # Exit if user input is empty
            if not user_input:
                print("Exiting Chat. Goodbye!")
                break
    
            # Add user message to chat conversation
            chat_conversation.append({"role": "user", "content": user_input})
    
            # Get AI response and add it to chat conversation
            response = get_ai_response(client, config, chat_conversation)
            print(f"AI: {response}\n")
            chat_conversation.append({"role": "assistant", "content": response})
    
    if __name__ == "__main__":
        main()
    
  7. Önceki adımları tamamladıktan sonra dosyanız app.py artık aşağıda gösterildiği gibi tam uygulamayı içermelidir:

    import os
    from azure.appconfiguration.provider import load, SettingSelector, WatchKey
    from azure.identity import DefaultAzureCredential
    from azure.ai.inference import ChatCompletionsClient
    
    credential = DefaultAzureCredential()
    
    
    def load_azure_app_configuration():
        endpoint = os.environ.get("AZURE_APPCONFIGURATION_ENDPOINT")
        if not endpoint:
            raise ValueError("AZURE_APPCONFIGURATION_ENDPOINT environment variable is not set")
    
        config = load(
            endpoint=endpoint,
            credential=credential,
            # Load all keys that start with "ChatApp:" and have no label
            selectors=[SettingSelector(key_filter="ChatApp:*")],
            trim_prefixes=["ChatApp:"],
            # Reload configuration if the ChatCompletion key has changed.
            # Use the default refresh interval of 30 seconds. It can be overridden via refresh_interval.
            refresh_on=[WatchKey("ChatApp:ChatCompletion")],
        )
        return config
    
    
    def get_ai_response(client, config, chat_conversation):
        chat_completion_config = config["ChatCompletion"]
        messages = []
    
        # Add configured messages (system, user, assistant)
        if not chat_completion_config.get("messages"):
            chat_completion_config["messages"] = []
    
        for msg in chat_completion_config["messages"]:
            messages.append({"role": msg["role"], "content": msg["content"]})
    
        # Add the chat conversation history
        messages.extend(chat_conversation)
    
        # Create chat completion
        response = client.complete(
            model=chat_completion_config["model"],
            messages=messages,
        )
        return response.choices[0].message.content
    
    
    def main():
        config = load_azure_app_configuration()
    
        # Create a chat completions client using Microsoft Entra ID
        client = ChatCompletionsClient(
            endpoint=config["AzureAIFoundry:Endpoint"],
            credential=credential,
            credential_scopes=["https://cognitiveservices.azure.com/.default"],
        )
    
        # Initialize chat conversation
        chat_conversation = []
        print("Chat started! What's on your mind?")
    
        while True:
            # Refresh the configuration from Azure App Configuration
            config.refresh()
    
            # Get user input
            user_input = input("You: ")
    
            # Exit if user input is empty
            if not user_input:
                print("Exiting Chat. Goodbye!")
                break
    
            # Add user message to chat conversation
            chat_conversation.append({"role": "user", "content": user_input})
    
            # Get AI response and add it to chat conversation
            response = get_ai_response(client, config, chat_conversation)
            print(f"AI: {response}\n")
            chat_conversation.append({"role": "assistant", "content": response})
    
        if __name__ == "__main__":
            main()
    

Uygulamayı derleyin ve çalıştırın

  1. AZURE_APPCONFIGURATION_ENDPOINT adlı ortam değişkenini Azure portalındaki mağazanızın Overview altında bulunan Uygulama Yapılandırma deponuzun uç noktasına ayarlayın.

    Windows komut istemini kullanıyorsanız, aşağıdaki komutu çalıştırın ve değişikliğin etkili olması için komut istemini yeniden başlatın:

    setx AZURE_APPCONFIGURATION_ENDPOINT "<AppConfigurationEndpoint>"
    

    PowerShell kullanıyorsanız aşağıdaki komutu çalıştırın:

    $Env:AZURE_APPCONFIGURATION_ENDPOINT = "<AppConfigurationEndpoint>"
    

    macOS veya Linux kullanıyorsanız aşağıdaki komutu çalıştırın:

    export AZURE_APPCONFIGURATION_ENDPOINT='<AppConfigurationEndpoint>'
    
  2. Ortam değişkeni düzgün şekilde ayarlandıktan sonra uygulamanızı çalıştırmak için aşağıdaki komutu çalıştırın:

    python app.py
    
  3. "Siz: " sorulduğunda "Adınız nedir?" iletisini yazın ve Enter tuşuna basın.

    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. Azure portalında, oluşturduğunuz Uygulama Yapılandırma deposu örneğini seçin. İşlemler menüsünde Yapılandırma gezgini'ni ve ardından ChatApp:ChatCompletion anahtarını seçin. İletiler özelliğinin değerini güncelleştirin:

    • Rol: sistem
    • İçerik: "Sen bir korsansın ve adınız Eddy."
  5. "Siz:" ile sorulduğunda aynı iletiyi yazın. Yenileme aralığının geçmesi için birkaç dakika beklediğinizden emin olun ve ardından çıktıda güncelleştirilmiş yapay zeka yanıtını görmek için Enter tuşuna basın.

    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?