Notatka
Dostęp do tej strony wymaga autoryzacji. Może spróbować zalogować się lub zmienić katalogi.
Dostęp do tej strony wymaga autoryzacji. Możesz spróbować zmienić katalogi.
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 Azure App Configuration GitHub.
Wymagania wstępne
- Ukończ samouczek, aby utworzyć konfigurację uzupełniania czatu.
- Python 3.10 lub nowszy — aby uzyskać informacje na temat konfigurowania Python na Windows, zobacz dokumentację Python dotyczącą Windows.
Tworzenie aplikacji konsolowej
Utwórz nowy katalog dla projektu i przejdź do niego:
mkdir chatapp-quickstart cd chatapp-quickstartZainstaluj wymagane pakiety języka Python:
pip install azure-appconfiguration-provider pip install azure-identity pip install azure-ai-inferenceUtwórz plik o nazwie
app.pyi dodaj następujące instrukcje importowania:import os from azure.appconfiguration.provider import load, SettingSelector, WatchKey from azure.identity import DefaultAzureCredential from azure.ai.inference import ChatCompletionsClientUtwó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
DefaultAzureCredentialdo uwierzytelniania w sklepie App Configuration. Postępuj zgodnie z tymi instrukcjami, aby przypisać rolę Czytelnik danych konfiguracji aplikacji do tożsamości reprezentowanej przezDefaultAzureCredential. Przed uruchomieniem aplikacji należy dać wystarczająco czasu na propagację uprawnień.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 configUtwórz funkcję, aby uzyskać odpowiedzi sztucznej inteligencji z klienta czatu:
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.contentUtwórz funkcję główną, która konfiguruje klienta czatu i uruchamia pętlę czatu.
Utwórz wystąpienie obiektu ,
ChatCompletionsClientaby nawiązać połączenie z Azure AI Foundry. UżyjDefaultAzureCredential, aby uwierzytelnić i przypisać rolę Cognitive Services OpenAI User tożsamości reprezentowanej przezDefaultAzureCredential. Aby uzyskać szczegółowe instrukcje, zapoznaj się z przewodnikiem Kontrola dostępu oparta na rolach dla usługi Azure OpenAI . Przed uruchomieniem aplikacji należy dać wystarczająco czasu na propagację uprawnień.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()Po wykonaniu poprzednich kroków twój plik
app.pypowinien teraz zawierać pełną implementację, jak pokazano poniżej: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()
Kompilowanie i uruchamianie aplikacji
Ustaw zmienną środowiskową o nazwie AZURE_APPCONFIGURATION_ENDPOINT na punkt końcowy Twojego sklepu App Configuration, który znajdziesz w sekcji Overview w portalu Azure.
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>'Po poprawnym ustawieniu zmiennej środowiskowej uruchom następujące polecenie, aby uruchomić aplikację:
python app.pyWpisz 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?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".
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?