Skip to content

Commit 433030d

Browse files
committed
Updated to use black formating
1 parent 00136bd commit 433030d

2 files changed

Lines changed: 59 additions & 50 deletions

File tree

examples/Python/ChatApp/app.py

Lines changed: 37 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,9 @@
1111
# Get Azure App Configuration endpoint from environment variable
1212
ENDPOINT = os.environ.get("AZURE_APPCONFIG_ENDPOINT")
1313
if not ENDPOINT:
14-
raise ValueError("The environment variable 'AZURE_APPCONFIG_ENDPOINT' is not set or is empty.")
14+
raise ValueError(
15+
"The environment variable 'AZURE_APPCONFIG_ENDPOINT' is not set or is empty."
16+
)
1517

1618
# Initialize Azure credentials
1719
credential = DefaultAzureCredential()
@@ -29,99 +31,105 @@
2931
trim_prefixes=["ChatApp:"],
3032
)
3133

32-
T = TypeVar('T')
34+
T = TypeVar("T")
35+
3336

3437
# Get OpenAI configuration
3538
def get_openai_client():
3639
"""Create and return an Azure OpenAI client"""
3740
endpoint = config.get("AzureOpenAI:Endpoint")
3841
# Get API key from App Configuration or fall back to environment variable
3942
api_key = config.get("AzureOpenAI:ApiKey", os.environ.get("AZURE_OPENAI_API_KEY"))
40-
api_version = config.get("AzureOpenAI:ApiVersion", "2023-05-15") # Read API version from config or use default
41-
43+
api_version = config.get(
44+
"AzureOpenAI:ApiVersion", "2023-05-15"
45+
) # Read API version from config or use default
46+
4247
# For DefaultAzureCredential auth if no API key is available
4348
if not api_key:
4449
token_provider = get_bearer_token_provider(
4550
DefaultAzureCredential(), "https://cognitiveservices.azure.com/.default"
4651
)
4752
return AzureOpenAI(
48-
azure_endpoint=endpoint,
53+
azure_endpoint=endpoint,
4954
api_version=api_version,
50-
azure_ad_token_provider=token_provider
55+
azure_ad_token_provider=token_provider,
5156
)
52-
57+
5358
# For API key auth
5459
return AzureOpenAI(
55-
azure_endpoint=endpoint,
56-
api_key=api_key,
57-
api_version=api_version
60+
azure_endpoint=endpoint, api_key=api_key, api_version=api_version
5861
)
5962

63+
6064
def get_chat_messages(messages: List[Message]):
6165
"""Convert from model Message objects to OpenAI messages format"""
6266
return [{"role": msg.role, "content": msg.content} for msg in messages]
6367

68+
6469
def main():
6570
"""Main entry point for the console app"""
6671
# Get OpenAI client
6772
client = get_openai_client()
68-
73+
6974
# Get deployment name
7075
deployment_name = config.get("AzureOpenAI:DeploymentName")
71-
76+
7277
# Initialize conversation history with the configuration messages
7378
conversation_history = []
7479
first_run = True
75-
80+
7681
print("Chat Application - type 'exit' to quit\n")
77-
82+
7883
while True:
7984
# Refresh configuration from Azure App Configuration
8085
config.refresh()
81-
86+
8287
# Get model configuration using data binding
8388
model_config = ModelConfiguration.from_dict(config.get("Model"))
84-
89+
8590
# On first run, initialize conversation history with configuration messages
8691
# and display the initial messages
8792
if first_run:
8893
conversation_history = model_config.messages.copy()
8994
for msg in conversation_history:
9095
print(f"{msg.role}: {msg.content}")
9196
first_run = False
92-
97+
9398
# Get chat messages for the API
9499
messages = get_chat_messages(conversation_history)
95-
100+
96101
# Get response from OpenAI
97102
response = client.chat.completions.create(
98103
model=deployment_name,
99104
messages=messages,
100105
max_tokens=model_config.max_tokens,
101106
temperature=model_config.temperature,
102-
top_p=model_config.top_p
107+
top_p=model_config.top_p,
103108
)
104-
109+
105110
# Extract assistant message
106111
assistant_message = response.choices[0].message.content
107-
112+
108113
# Display the response
109114
print(f"assistant: {assistant_message}")
110-
115+
111116
# Add assistant response to conversation history
112-
conversation_history.append(Message(role="assistant", content=assistant_message))
113-
117+
conversation_history.append(
118+
Message(role="assistant", content=assistant_message)
119+
)
120+
114121
# Get user input for the next message
115122
print("\nuser: ", end="")
116123
user_input = input().strip()
117-
124+
118125
# Check if user wants to exit
119-
if user_input.lower() == 'exit':
126+
if user_input.lower() == "exit":
120127
print("Exiting application...")
121128
break
122-
129+
123130
# Add user input to conversation history
124131
conversation_history.append(Message(role="user", content=user_input))
125132

126-
if __name__ == '__main__':
127-
main()
133+
134+
if __name__ == "__main__":
135+
main()

examples/Python/ChatApp/models.py

Lines changed: 22 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -9,45 +9,46 @@ class Message:
99
Represents a chat message with a role and content.
1010
Maps to configuration values with keys 'role' and 'content'.
1111
"""
12+
1213
def __init__(self, role: Optional[str] = None, content: Optional[str] = None):
1314
self.role = role
1415
self.content = content
15-
16+
1617
@classmethod
17-
def from_dict(cls, data: Dict[str, Any]) -> 'Message':
18+
def from_dict(cls, data: Dict[str, Any]) -> "Message":
1819
"""Create a Message instance from a dictionary."""
19-
return cls(
20-
role=data.get('role'),
21-
content=data.get('content')
22-
)
20+
return cls(role=data.get("role"), content=data.get("content"))
2321

2422

2523
class ModelConfiguration:
2624
"""
2725
Represents the configuration for an AI model including messages and parameters.
2826
Maps to configuration values with keys 'model', 'messages', 'max_tokens', 'temperature', and 'top_p'.
2927
"""
30-
def __init__(self,
31-
model: Optional[str] = None,
32-
messages: Optional[List[Message]] = None,
33-
max_tokens: int = 1024,
34-
temperature: float = 0.7,
35-
top_p: float = 0.95):
28+
29+
def __init__(
30+
self,
31+
model: Optional[str] = None,
32+
messages: Optional[List[Message]] = None,
33+
max_tokens: int = 1024,
34+
temperature: float = 0.7,
35+
top_p: float = 0.95,
36+
):
3637
self.model = model
3738
self.messages = messages or []
3839
self.max_tokens = int(max_tokens) if max_tokens is not None else 1024
3940
self.temperature = float(temperature) if temperature is not None else 0.7
4041
self.top_p = float(top_p) if top_p is not None else 0.95
41-
42+
4243
@classmethod
43-
def from_dict(cls, data: Dict[str, Any]) -> 'ModelConfiguration':
44+
def from_dict(cls, data: Dict[str, Any]) -> "ModelConfiguration":
4445
"""Create a ModelConfiguration instance from a dictionary."""
45-
messages = [Message.from_dict(msg) for msg in data.get('messages', [])]
46-
46+
messages = [Message.from_dict(msg) for msg in data.get("messages", [])]
47+
4748
return cls(
48-
model=data.get('model'),
49+
model=data.get("model"),
4950
messages=messages,
50-
max_tokens=data.get('max_tokens', 1024),
51-
temperature=data.get('temperature', 0.7),
52-
top_p=data.get('top_p', 0.95)
53-
)
51+
max_tokens=data.get("max_tokens", 1024),
52+
temperature=data.get("temperature", 0.7),
53+
top_p=data.get("top_p", 0.95),
54+
)

0 commit comments

Comments
 (0)