Not
Bu sayfaya erişim yetkilendirme gerektiriyor. Oturum açmayı veya dizinleri değiştirmeyi deneyebilirsiniz.
Bu sayfaya erişim yetkilendirme gerektiriyor. Dizinleri değiştirmeyi deneyebilirsiniz.
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
- Sohbet tamamlama yapılandırması oluşturma öğreticisini tamamlayın.
- Python 3.10 veya üzeri - Windows Python ayarlama hakkında bilgi için Windows Python belgelerine bakın.
Konsol uygulaması oluşturma
Projeniz için yeni bir dizin oluşturun ve bu dizine gidin:
mkdir chatapp-quickstart cd chatapp-quickstartGerekli Python paketlerini yükleyin:
pip install azure-appconfiguration-provider pip install azure-identity pip install azure-ai-inferenceadlı
app.pybir 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 ChatCompletionsClientAzure 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
DefaultAzureCredentialile 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 buDefaultAzureCredentializleyin. 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 configSohbet 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.contentSohbet 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.DefaultAzureCredentialkimlik doğrulaması yapmak veDefaultAzureCredentialtarafı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()Önceki adımları tamamladıktan sonra dosyanız
app.pyartı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
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>'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"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?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."
"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?