Skip to content

Commit bc3f454

Browse files
committed
Python Chat Completion
1 parent 671dae0 commit bc3f454

3 files changed

Lines changed: 289 additions & 1 deletion

File tree

articles/azure-app-configuration/TOC.yml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -192,6 +192,8 @@
192192
href: howto-chat-completion-config.md
193193
- name: .NET
194194
href: quickstart-chat-completion-dotnet.md
195+
- name: Python
196+
href: quickstart-chat-completion-python.md
195197
- name: Go
196198
href: quickstart-chat-completion-go.md
197199
- name: Agent framework

articles/azure-app-configuration/howto-chat-completion-config.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -63,4 +63,5 @@ You successfully added your chat completion configuration named **ChatApp:ChatCo
6363
1. Continue to the following instructions to implement the chat completion configuration into your application for the language or platform you're using.
6464

6565
- [.NET](./quickstart-chat-completion-dotnet.md)
66-
- [.Go](./quickstart-chat-completion-go.md)
66+
- [Go](./quickstart-chat-completion-go.md)
67+
- [Python](./quickstart-chat-completion-python.md)
Lines changed: 285 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,285 @@
1+
---
2+
title: Quickstart for using chat completion configuration in a Python app
3+
titleSuffix: Azure App Configuration
4+
description: Learn to implement chat completion configuration in your Python application using Azure App Configuration.
5+
services: azure-app-configuration
6+
author: mrm9084
7+
ms.service: azure-app-configuration
8+
ms.devlang: python
9+
ms.custom: devx-track-python, mode-other
10+
ms.topic: quickstart
11+
ms.tgt_pltfrm: Python
12+
ms.date: 02/27/2026
13+
ms.update-cycle: 180-days
14+
ms.author: mametcal
15+
ms.collection: ce-skilling-ai-copilot
16+
---
17+
18+
# Use chat completion configuration in a Python console app
19+
20+
In this guide, you build an AI chat application and iterate on the prompt using chat completion configuration dynamically loaded from Azure App Configuration.
21+
22+
The full sample source code is available in the [Azure App Configuration GitHub repository](https://github.com/Azure/AppConfiguration/tree/main/examples/Python/ChatApp).
23+
24+
## Prerequisites
25+
26+
- Complete the tutorial to [Create a chat completion configuration](./howto-chat-completion-config.md#create-a-chat-completion-configuration).
27+
- Python 3.9 or later - for information on setting up Python on Windows, see the [Python on Windows documentation](/windows/python/).
28+
29+
## Create a console app
30+
31+
1. Create a new directory for your project and navigate to it:
32+
33+
```bash
34+
mkdir chatapp-quickstart
35+
cd chatapp-quickstart
36+
```
37+
38+
1. Install the required Python packages:
39+
40+
```console
41+
pip install azure-appconfiguration-provider
42+
pip install azure-identity
43+
pip install azure-ai-inference
44+
```
45+
46+
1. Create a file named `app.py` and add the following import statements:
47+
48+
```python
49+
import os
50+
from azure.appconfiguration.provider import load, SettingSelector, WatchKey
51+
from azure.identity import DefaultAzureCredential
52+
from azure.ai.inference import ChatCompletionsClient
53+
```
54+
55+
1. Create a function to load configuration from Azure App Configuration.
56+
57+
You can connect to App Configuration using either Microsoft Entra ID (recommended) or a connection string. In this example, you use Microsoft Entra ID with `DefaultAzureCredential` to authenticate to your App Configuration store. Follow these [instructions](./concept-enable-rbac.md#authentication-with-token-credentials) to assign the **App Configuration Data Reader** role to the identity represented by `DefaultAzureCredential`. Be sure to allow sufficient time for the permission to propagate before running your application.
58+
59+
```python
60+
credential = DefaultAzureCredential()
61+
62+
def load_azure_app_configuration():
63+
endpoint = os.environ.get("AZURE_APPCONFIGURATION_ENDPOINT")
64+
if not endpoint:
65+
raise ValueError("AZURE_APPCONFIGURATION_ENDPOINT environment variable is not set")
66+
67+
config = load(
68+
endpoint=endpoint,
69+
credential=credential,
70+
# Load all keys that start with "ChatApp:" and have no label
71+
selectors=[SettingSelector(key_filter="ChatApp:*")],
72+
trim_prefixes=["ChatApp:"],
73+
# Reload configuration if the ChatCompletion key has changed.
74+
# Use the default refresh interval of 30 seconds. It can be overridden via refresh_interval.
75+
refresh_on=[WatchKey("ChatApp:ChatCompletion")],
76+
)
77+
return config
78+
```
79+
80+
1. Create a function to get AI responses from the chat client:
81+
82+
```python
83+
def get_ai_response(client, config, chat_conversation):
84+
chat_completion_config = config["ChatCompletion"]
85+
messages = []
86+
87+
# Add configured messages (system, user, assistant)
88+
for msg in chat_completion_config["messages"]:
89+
messages.append({"role": msg["role"], "content": msg["content"]})
90+
91+
# Add the chat conversation history
92+
messages.extend(chat_conversation)
93+
94+
# Create chat completion
95+
response = client.complete(
96+
model=chat_completion_config["model"],
97+
messages=messages,
98+
)
99+
return response.choices[0].message.content
100+
```
101+
102+
1. Create the main function that configures the chat client and runs the chat loop.
103+
104+
Create an instance of the `ChatCompletionsClient` to connect to your Azure AI Foundry project. You use `DefaultAzureCredential` to authenticate. Assign the **Cognitive Services OpenAI User** role to the identity represented by `DefaultAzureCredential`. For detailed steps, refer to the [Role-based access control for Azure OpenAI service](/azure/ai-services/openai/how-to/role-based-access-control) guide. Be sure to allow sufficient time for the permission to propagate before running your application.
105+
106+
```python
107+
def main():
108+
config = load_azure_app_configuration()
109+
110+
# Create a chat client using Microsoft Entra ID
111+
client = ChatCompletionsClient(
112+
endpoint=config["AzureAIFoundry:Endpoint"],
113+
credential=credential,
114+
credential_scopes=["https://cognitiveservices.azure.com/.default"],
115+
)
116+
117+
# Initialize chat conversation
118+
chat_conversation = []
119+
print("Chat started! What's on your mind?")
120+
121+
while True:
122+
# Refresh the configuration from Azure App Configuration
123+
config.refresh()
124+
125+
# Get user input
126+
user_input = input("You: ")
127+
128+
# Exit if user input is empty
129+
if not user_input:
130+
print("Exiting Chat. Goodbye!")
131+
break
132+
133+
# Add user message to chat conversation
134+
chat_conversation.append({"role": "user", "content": user_input})
135+
136+
# Get AI response and add it to chat conversation
137+
response = get_ai_response(client, config, chat_conversation)
138+
print(f"AI: {response}")
139+
chat_conversation.append({"role": "assistant", "content": response})
140+
141+
print()
142+
143+
if __name__ == "__main__":
144+
main()
145+
```
146+
147+
1. After completing the previous steps, your `app.py` file should now contain the complete implementation as shown below:
148+
149+
```python
150+
import os
151+
from azure.appconfiguration.provider import load, SettingSelector, WatchKey
152+
from azure.identity import DefaultAzureCredential
153+
from azure.ai.inference import ChatCompletionsClient
154+
155+
credential = DefaultAzureCredential()
156+
157+
158+
def load_azure_app_configuration():
159+
endpoint = os.environ.get("AZURE_APPCONFIGURATION_ENDPOINT")
160+
if not endpoint:
161+
raise ValueError("AZURE_APPCONFIGURATION_ENDPOINT environment variable is not set")
162+
163+
config = load(
164+
endpoint=endpoint,
165+
credential=credential,
166+
# Load all keys that start with "ChatApp:" and have no label
167+
selectors=[SettingSelector(key_filter="ChatApp:*")],
168+
trim_prefixes=["ChatApp:"],
169+
# Reload configuration if the ChatCompletion key has changed.
170+
# Use the default refresh interval of 30 seconds. It can be overridden via refresh_interval.
171+
refresh_on=[WatchKey("ChatApp:ChatCompletion")],
172+
)
173+
return config
174+
175+
176+
def get_ai_response(client, config, chat_conversation):
177+
chat_completion_config = config["ChatCompletion"]
178+
messages = []
179+
180+
# Add configured messages (system, user, assistant)
181+
for msg in chat_completion_config["messages"]:
182+
messages.append({"role": msg["role"], "content": msg["content"]})
183+
184+
# Add the chat conversation history
185+
messages.extend(chat_conversation)
186+
187+
# Create chat completion
188+
response = client.complete(
189+
model=chat_completion_config["model"],
190+
messages=messages,
191+
)
192+
return response.choices[0].message.content
193+
194+
195+
def main():
196+
config = load_azure_app_configuration()
197+
198+
# Create a chat client using Microsoft Entra ID
199+
client = ChatCompletionsClient(
200+
endpoint=config["AzureAIFoundry:Endpoint"],
201+
credential=credential,
202+
credential_scopes=["https://cognitiveservices.azure.com/.default"],
203+
)
204+
205+
# Initialize chat conversation
206+
chat_conversation = []
207+
print("Chat started! What's on your mind?")
208+
209+
while True:
210+
# Refresh the configuration from Azure App Configuration
211+
config.refresh()
212+
213+
# Get user input
214+
user_input = input("You: ")
215+
216+
# Exit if user input is empty
217+
if not user_input:
218+
print("Exiting Chat. Goodbye!")
219+
break
220+
221+
# Add user message to chat conversation
222+
chat_conversation.append({"role": "user", "content": user_input})
223+
224+
# Get AI response and add it to chat conversation
225+
response = get_ai_response(client, config, chat_conversation)
226+
print(f"AI: {response}")
227+
chat_conversation.append({"role": "assistant", "content": response})
228+
229+
print()
230+
231+
232+
if __name__ == "__main__":
233+
main()
234+
```
235+
236+
## Build and run the app
237+
238+
1. Set the environment variable named **AZURE_APPCONFIGURATION_ENDPOINT** to the endpoint of your App Configuration store found under the *Overview* of your store in the Azure portal.
239+
240+
If you use the Windows command prompt, run the following command and restart the command prompt to allow the change to take effect:
241+
242+
```cmd
243+
setx AZURE_APPCONFIGURATION_ENDPOINT "<endpoint-of-your-app-configuration-store>"
244+
```
245+
246+
If you use PowerShell, run the following command:
247+
```powershell
248+
$Env:AZURE_APPCONFIGURATION_ENDPOINT = "<endpoint-of-your-app-configuration-store>"
249+
```
250+
251+
If you use macOS or Linux, run the following command:
252+
```bash
253+
export AZURE_APPCONFIGURATION_ENDPOINT='<endpoint-of-your-app-configuration-store>'
254+
```
255+
256+
1. After the environment variable is properly set, run the following command to run your app:
257+
```console
258+
python app.py
259+
```
260+
261+
1. Type the message "What is your name?" when prompted with "You:" and then press the Enter key.
262+
263+
```Output
264+
Chat started! What's on your mind?
265+
You: What is your name?
266+
AI: I'm your helpful assistant! I don't have a personal name, but you can call me whatever you'd like.
267+
😊 Do you have a name in mind?
268+
```
269+
270+
1. In Azure portal, select the App Configuration store instance that you created. From the **Operations** menu, select **Configuration explorer** and select the **ChatApp:ChatCompletion** key. Update the value of the Messages property:
271+
- Role: **system**
272+
- Content: "You are a pirate and your name is Eddy."
273+
274+
1. Type the same message when prompted with "You:". Be sure to wait a few moments for the refresh interval to elapse, and then press the Enter key to see the updated AI response in the output.
275+
276+
```Output
277+
Chat started! What's on your mind?
278+
You: What is your name?
279+
AI: I'm your helpful assistant! I don't have a personal name, but you can call me whatever you'd like.
280+
😊 Do you have a name in mind?
281+
282+
You: What is your name?
283+
AI: Arrr, matey! Me name be Eddy, the most fearsome pirate to ever sail the seven seas!
284+
What be yer name, landlubber?
285+
```

0 commit comments

Comments
 (0)