Skip to content

Commit 18fbda0

Browse files
committed
Update app.py
1 parent b8e8a55 commit 18fbda0

1 file changed

Lines changed: 53 additions & 76 deletions

File tree

examples/Python/ChatApp/app.py

Lines changed: 53 additions & 76 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
"""
1111

1212
import os
13-
from typing import List, Dict, Any
13+
from typing import Dict, Any
1414
from azure.core.credentials import TokenCredential
1515
from azure.identity import DefaultAzureCredential, get_bearer_token_provider
1616
from azure.appconfiguration.provider import load, SettingSelector, WatchKey
@@ -19,6 +19,7 @@
1919

2020

2121
def main():
22+
global appconfig, azure_openai_config, chat_completion_config, azure_client, chat_messages, chat_conversation, credential
2223
# Create a credential using DefaultAzureCredential
2324
credential = DefaultAzureCredential()
2425

@@ -29,84 +30,79 @@ def main():
2930
"The environment variable 'AZURE_APPCONFIGURATION_ENDPOINT' is not set or is empty."
3031
)
3132

32-
try:
33-
azure_openai_config = None
34-
azure_client = None
35-
36-
def on_refresh_success():
37-
azure_openai_config, azure_client = _create_ai_client(appconfig)
38-
39-
global appconfig
40-
# Create the configuration provider with refresh settings
41-
appconfig = load(
42-
endpoint=app_config_endpoint,
43-
selects=[SettingSelector(key_filter="ChatApp:*")],
44-
credential=credential,
45-
keyvault_credential=credential, # Use the same credential for Key Vault references
46-
trim_prefixes=["ChatApp:"],
47-
refresh_on=[WatchKey(key="ChatApp:ChatCompletion:Messages")],
48-
on_refresh_success=on_refresh_success,
49-
)
50-
51-
azure_openai_config, azure_client = _create_ai_client(appconfig, credential)
33+
# Initialize chat conversation
34+
chat_messages = []
35+
chat_conversation = []
5236

53-
# Initialize chat conversation
54-
chat_conversation = []
55-
print("Chat started! What's on your mind?")
37+
def configure_app():
38+
global appconfig, azure_openai_config, chat_completion_config, azure_client, chat_messages, credential
39+
azure_openai_config = _extract_openai_config(appconfig)
40+
azure_client = _create_ai_client(azure_openai_config, credential)
5641

57-
while True:
58-
# Refresh the configuration from Azure App Configuration
59-
appconfig.refresh()
42+
# Configure chat completion with AI configuration
43+
chat_completion_config = ChatCompletionConfiguration(
44+
**appconfig["ChatCompletion"]
45+
)
46+
chat_messages = chat_completion_config.messages
47+
48+
# Create the configuration provider with refresh settings
49+
appconfig = load(
50+
endpoint=app_config_endpoint,
51+
selects=[SettingSelector(key_filter="ChatApp:*")],
52+
credential=credential,
53+
keyvault_credential=credential, # Use the same credential for Key Vault references
54+
trim_prefixes=["ChatApp:"],
55+
refresh_on=[WatchKey(key="ChatApp:ChatCompletion")],
56+
on_refresh_success=configure_app,
57+
)
58+
configure_app()
6059

61-
# Configure chat completion with AI configuration
62-
chat_completion_config = ChatCompletionConfiguration(**appconfig["ChatCompletion"])
60+
print("Chat started! What's on your mind?")
6361

64-
# Get user input
65-
user_input = input("You: ")
62+
while True:
63+
# Refresh the configuration from Azure App Configuration
64+
appconfig.refresh()
6665

67-
# Exit if user input is empty
68-
if not user_input.strip():
69-
print("Exiting chat. Goodbye!")
70-
break
66+
# Get user input
67+
user_input = input("You: ")
7168

72-
# Add user message to chat conversation
73-
chat_conversation.append({"role": "user", "content": user_input})
69+
# Exit if user input is empty
70+
if not user_input.strip():
71+
print("Exiting chat. Goodbye!")
72+
break
7473

75-
# Get latest system message from AI configuration
76-
chat_messages = _get_chat_messages(chat_completion_config)
77-
chat_messages.extend(chat_conversation)
74+
# Add user message to chat conversation
75+
chat_conversation.append({"role": "user", "content": user_input})
7876

79-
# Get AI response and add it to chat conversation
80-
response = azure_client.chat.completions.create(
81-
model=azure_openai_config.deployment_name,
82-
messages=chat_messages,
83-
max_tokens=chat_completion_config.max_tokens,
84-
temperature=chat_completion_config.temperature,
85-
top_p=chat_completion_config.top_p,
86-
)
77+
# Get latest system message from AI configuration
78+
chat_messages.extend(chat_conversation)
8779

88-
ai_response = response.choices[0].message.content
89-
chat_conversation.append({"role": "assistant", "content": ai_response})
90-
print(f"AI: {ai_response}")
80+
# Get AI response and add it to chat conversation
81+
response = azure_client.chat.completions.create(
82+
model=azure_openai_config.deployment_name,
83+
messages=chat_messages,
84+
max_tokens=chat_completion_config.max_tokens,
85+
temperature=chat_completion_config.temperature,
86+
top_p=chat_completion_config.top_p,
87+
)
9188

92-
except Exception as e:
93-
print(f"Error: {e}")
89+
ai_response = response.choices[0].message.content
90+
chat_conversation.append({"role": "assistant", "content": ai_response})
91+
print(f"AI: {ai_response}")
9492

9593

9694
def _create_ai_client(
9795
azure_openai_config: AzureOpenAIConfiguration, credential: TokenCredential = None
9896
) -> AzureOpenAI:
99-
# Extract Azure OpenAI configuration
100-
azure_openai_config = _extract_openai_config(appconfig)
10197
# Create an Azure OpenAI client
10298
if azure_openai_config.api_key:
103-
return azure_openai_config, AzureOpenAI(
99+
return AzureOpenAI(
104100
azure_endpoint=azure_openai_config.endpoint,
105101
api_key=azure_openai_config.api_key,
106102
api_version=azure_openai_config.api_version,
107103
)
108104
else:
109-
return azure_openai_config, AzureOpenAI(
105+
return AzureOpenAI(
110106
azure_endpoint=azure_openai_config.endpoint,
111107
azure_ad_token_provider=get_bearer_token_provider(
112108
credential or DefaultAzureCredential(),
@@ -131,25 +127,6 @@ def _extract_openai_config(config_data: Dict[str, Any]) -> AzureOpenAIConfigurat
131127
api_version=config_data.get(f"{prefix}ApiVersion", "2023-05-15"),
132128
)
133129

134-
def _get_chat_messages(
135-
chat_completion_config: ChatCompletionConfiguration,
136-
) -> List[Dict[str, str]]:
137-
"""
138-
Convert configuration messages to chat message dictionaries.
139-
140-
:param chat_completion_config: The chat completion configuration
141-
:return: A list of chat message dictionaries
142-
"""
143-
chat_messages = []
144-
145-
for message in chat_completion_config.messages:
146-
if message["role"] in ["system", "user", "assistant"]:
147-
chat_messages.append({"role": message["role"], "content": message["content"]})
148-
else:
149-
raise ValueError(f"Unknown role: {message.role}")
150-
151-
return chat_messages
152-
153130

154131
if __name__ == "__main__":
155132
main()

0 commit comments

Comments
 (0)