Skip to content

Commit caf9cd0

Browse files
Copilotmrm9084
andcommitted
Convert Flask web app to console app
Co-authored-by: mrm9084 <1054559+mrm9084@users.noreply.github.com>
1 parent 0c6960e commit caf9cd0

File tree

6 files changed

+35
-231
lines changed

6 files changed

+35
-231
lines changed

examples/Python/ChatApp/README.md

Lines changed: 5 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,13 @@
11
# Azure App Configuration - Python ChatApp Sample
22

3-
This sample demonstrates using Azure App Configuration to configure Azure OpenAI settings for a chat application built with Python and Flask.
3+
This sample demonstrates using Azure App Configuration to configure Azure OpenAI settings for a chat application built with Python.
44

55
## Features
66

7-
- Built with Python and Flask
7+
- Built with Python
88
- Uses azure-appconfiguration-provider for configuration management
99
- Integrates with Azure OpenAI for chat completions
1010
- Dynamically refreshes configuration from Azure App Configuration
11-
- Supports both web interface and console-like views
1211

1312
## Prerequisites
1413

@@ -49,18 +48,13 @@ This sample demonstrates using Azure App Configuration to configure Azure OpenAI
4948

5049
## Running the Application
5150

52-
Start the Flask application:
51+
Start the console application:
5352
```bash
5453
python app.py
5554
```
5655

57-
The application will be available at http://localhost:5000/
58-
59-
## Views
60-
61-
- **Chat Interface** (/) - A web interface for chatting with the AI
62-
- **Console Mode** (/console) - A view that mimics the .NET Core console application experience
56+
The application will display the configured messages and the AI's response. Press Enter to continue and refresh the configuration from Azure App Configuration.
6357

6458
## Configuration Refresh
6559

66-
The application refreshes the configuration on each request, so any changes made in Azure App Configuration will be reflected immediately in the app.
60+
The application refreshes the configuration on each loop iteration, so any changes made in Azure App Configuration will be reflected in the next response after you press Enter.

examples/Python/ChatApp/app.py

Lines changed: 30 additions & 84 deletions
Original file line numberDiff line numberDiff line change
@@ -3,15 +3,11 @@
33
#
44
import os
55
import time
6-
from flask import Flask, render_template, request
76
from azure.identity import DefaultAzureCredential
87
from azure.appconfiguration.provider import load, SettingSelector
98
from openai import AzureOpenAI
109
from models import ModelConfiguration
1110

12-
# Initialize Flask app
13-
app = Flask(__name__)
14-
1511
# Get Azure App Configuration endpoint from environment variable
1612
ENDPOINT = os.environ.get("AZURE_APPCONFIG_ENDPOINT")
1713
if not ENDPOINT:
@@ -26,25 +22,21 @@
2622
# Load configuration from Azure App Configuration
2723
def callback():
2824
"""Callback function for configuration refresh"""
29-
app.config.update(azure_app_config)
3025
print("Configuration refreshed successfully")
3126

32-
global azure_app_config
33-
azure_app_config = load(
27+
global config
28+
config = load(
3429
endpoint=ENDPOINT,
3530
selects=[chat_app_selector],
3631
credential=credential,
3732
keyvault_credential=credential,
3833
on_refresh_success=callback,
3934
)
4035

41-
# Update Flask app config with Azure App Configuration
42-
app.config.update(azure_app_config)
43-
4436
# Get OpenAI configuration
4537
def get_openai_client():
4638
"""Create and return an Azure OpenAI client"""
47-
endpoint = app.config.get("ChatApp:AzureOpenAI:Endpoint")
39+
endpoint = config.get("ChatApp:AzureOpenAI:Endpoint")
4840
api_key = os.environ.get("AZURE_OPENAI_API_KEY") # Using environment variable for API key
4941

5042
# For DefaultAzureCredential auth
@@ -63,32 +55,32 @@ def get_openai_client():
6355
)
6456

6557
def get_model_configuration():
66-
"""Get model configuration from app config"""
58+
"""Get model configuration from config"""
6759
model_config = {}
6860

69-
# Extract model configuration from app.config
61+
# Extract model configuration from config
7062
prefix = "ChatApp:Model:"
71-
for key in app.config:
63+
for key in config:
7264
if key.startswith(prefix):
7365
# Get the part of the key after the prefix
7466
config_key = key[len(prefix):].lower()
75-
model_config[config_key] = app.config[key]
67+
model_config[config_key] = config[key]
7668

7769
# Handle messages specially (they're nested)
7870
messages = []
7971
messages_prefix = "ChatApp:Model:messages:"
8072

8173
# Group message configs by index
8274
message_configs = {}
83-
for key in app.config:
75+
for key in config:
8476
if key.startswith(messages_prefix):
8577
# Extract the index and property (e.g., "0:role" -> ("0", "role"))
8678
parts = key[len(messages_prefix):].split(':')
8779
if len(parts) == 2:
8880
index, prop = parts
8981
if index not in message_configs:
9082
message_configs[index] = {}
91-
message_configs[index][prop.lower()] = app.config[key]
83+
message_configs[index][prop.lower()] = config[key]
9284

9385
# Create message list in the right order
9486
for index in sorted(message_configs.keys()):
@@ -102,34 +94,27 @@ def get_chat_messages(model_config):
10294
"""Convert from model configuration messages to OpenAI messages format"""
10395
return [{"role": msg.role, "content": msg.content} for msg in model_config.messages]
10496

105-
@app.route('/')
106-
def index():
107-
"""Main route to display and handle chat"""
108-
# Refresh configuration from Azure App Configuration
109-
azure_app_config.refresh()
110-
111-
# Get model configuration
112-
model_config = get_model_configuration()
113-
97+
def main():
98+
"""Main entry point for the console app"""
11499
# Get OpenAI client
115100
client = get_openai_client()
116101

117102
# Get deployment name
118-
deployment_name = app.config.get("ChatApp:AzureOpenAI:DeploymentName")
119-
120-
# Get chat history from model config for display
121-
chat_history = [{"role": msg.role, "content": msg.content} for msg in model_config.messages]
103+
deployment_name = config.get("ChatApp:AzureOpenAI:DeploymentName")
122104

123-
# Check if a new message was submitted
124-
if request.args.get('message'):
125-
user_message = request.args.get('message')
105+
while True:
106+
# Refresh configuration from Azure App Configuration
107+
config.refresh()
126108

127-
# Add user message to chat messages
128-
messages = get_chat_messages(model_config)
129-
messages.append({"role": "user", "content": user_message})
109+
# Get model configuration
110+
model_config = get_model_configuration()
130111

131-
# Add user message to chat history
132-
chat_history.append({"role": "user", "content": user_message})
112+
# Display messages from configuration
113+
for msg in model_config.messages:
114+
print(f"{msg.role}: {msg.content}")
115+
116+
# Get chat messages for the API
117+
messages = get_chat_messages(model_config)
133118

134119
# Get response from OpenAI
135120
response = client.chat.completions.create(
@@ -143,51 +128,12 @@ def index():
143128
# Extract assistant message
144129
assistant_message = response.choices[0].message.content
145130

146-
# Add assistant message to chat history
147-
chat_history.append({"role": "assistant", "content": assistant_message})
148-
149-
return render_template('index.html',
150-
chat_history=chat_history,
151-
model_config=model_config)
152-
153-
@app.route('/console')
154-
def console():
155-
"""Console mode similar to the .NET Core example"""
156-
# Refresh configuration from Azure App Configuration
157-
azure_app_config.refresh()
158-
159-
# Get model configuration
160-
model_config = get_model_configuration()
161-
162-
# Get OpenAI client
163-
client = get_openai_client()
164-
165-
# Get deployment name
166-
deployment_name = app.config.get("ChatApp:AzureOpenAI:DeploymentName")
167-
168-
# Display messages from configuration
169-
messages_display = ""
170-
for msg in model_config.messages:
171-
messages_display += f"{msg.role}: {msg.content}\n"
172-
173-
# Get chat messages for the API
174-
messages = get_chat_messages(model_config)
175-
176-
# Get response from OpenAI
177-
response = client.chat.completions.create(
178-
model=deployment_name,
179-
messages=messages,
180-
max_tokens=model_config.max_tokens,
181-
temperature=model_config.temperature,
182-
top_p=model_config.top_p
183-
)
184-
185-
# Extract assistant message
186-
assistant_message = response.choices[0].message.content
187-
188-
return render_template('console.html',
189-
messages=messages_display,
190-
response=assistant_message)
131+
# Display the response
132+
print(f"AI response: {assistant_message}")
133+
134+
# Wait for user to continue
135+
print("Press Enter to continue...")
136+
input()
191137

192138
if __name__ == '__main__':
193-
app.run(debug=True)
139+
main()
Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
Flask==2.3.3
21
azure-identity==1.16.1
32
azure-appconfiguration-provider==1.3.0
43
openai==1.6.1

examples/Python/ChatApp/templates/base.html

Lines changed: 0 additions & 55 deletions
This file was deleted.

examples/Python/ChatApp/templates/console.html

Lines changed: 0 additions & 23 deletions
This file was deleted.

examples/Python/ChatApp/templates/index.html

Lines changed: 0 additions & 57 deletions
This file was deleted.

0 commit comments

Comments
 (0)