Skip to content

Commit 9a28516

Browse files
Add requests import and clean up whitespace in test_azure_credential_utils.py
1 parent d469f6b commit 9a28516

File tree

2 files changed

+35
-29
lines changed

2 files changed

+35
-29
lines changed

src/app.py

Lines changed: 27 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
import logging
55
import os
66
import re
7+
import requests
78
import uuid
89
from typing import Dict, Any, AsyncGenerator
910

@@ -164,26 +165,26 @@ async def send_chat_request(request_body, request_headers) -> AsyncGenerator[Dic
164165
"original_count": len(messages),
165166
"filtered_count": len(filtered_messages)
166167
})
167-
168+
168169
# Convert messages to simple prompt format for ChatAgent
169170
conversation_prompt = "\n\n".join([
170-
f"{msg['role']}: {msg['content']}"
171-
for msg in filtered_messages
171+
f"{msg['role']}: {msg['content']}"
172+
for msg in filtered_messages
172173
if msg.get('content')
173174
])
174-
175+
175176
try:
176177
track_event_if_configured("Foundry_sdk_for_response", {"status": "success"})
177178
answer: Dict[str, Any] = {"answer": "", "citations": []}
178179
doc_mapping = {}
179-
180+
180181
# Browse
181182
if request_body["chat_type"] == "browse":
182183
# Get browse agent name and create AzureAIClient
183184
browse_agent_name = app_settings.azure_ai.agent_name_browse
184185
if not browse_agent_name:
185186
raise ValueError("Browse agent name not configured in settings")
186-
187+
187188
async with (
188189
await get_azure_credential_async(client_id=app_settings.base_settings.azure_client_id) as credential,
189190
AIProjectClient(endpoint=app_settings.azure_ai.agent_endpoint, credential=credential) as project_client,
@@ -200,15 +201,15 @@ async def send_chat_request(request_body, request_headers) -> AsyncGenerator[Dic
200201
tool_choice="auto", # Let agent decide when to use Azure AI Search
201202
) as chat_agent:
202203
thread = chat_agent.get_new_thread()
203-
204+
204205
if app_settings.azure_openai.stream:
205206
# Stream response
206207
async for chunk in chat_agent.run_stream(messages=conversation_prompt, thread=thread):
207208
# Extract text from chunk
208209
if hasattr(chunk, 'text') and chunk.text:
209210
delta_text = chunk.text
210211
answer["answer"] += delta_text
211-
212+
212213
# Check if citation markers are present
213214
has_citation_markers = bool(re.search(r'【(\d+:\d+)†source】', delta_text))
214215
if has_citation_markers:
@@ -220,7 +221,7 @@ async def send_chat_request(request_body, request_headers) -> AsyncGenerator[Dic
220221
yield {
221222
"answer": delta_text
222223
}
223-
224+
224225
# # Collect citations from annotations
225226
# if hasattr(chunk, 'contents') and chunk.contents:
226227
# for content in chunk.contents:
@@ -232,7 +233,7 @@ async def send_chat_request(request_body, request_headers) -> AsyncGenerator[Dic
232233
# "title": annotation.title,
233234
# "url": annotation.url
234235
# })
235-
236+
236237
# Final citation update if needed
237238
has_final_citation_markers = bool(re.search(r'【(\d+:\d+)†source】', answer["answer"]))
238239
if has_final_citation_markers:
@@ -242,15 +243,15 @@ async def send_chat_request(request_body, request_headers) -> AsyncGenerator[Dic
242243
else:
243244
# Non-streaming response
244245
result = await chat_agent.run(messages=conversation_prompt, thread=thread)
245-
246+
246247
# Extract text from result
247248
if hasattr(result, 'text'):
248249
response_text = result.text
249250
else:
250251
response_text = str(result) if result is not None else ""
251-
252+
252253
answer["answer"] = response_text
253-
254+
254255
# # Collect citations from annotations
255256
# if hasattr(result, 'contents') and result.contents:
256257
# for content in result.contents:
@@ -262,7 +263,7 @@ async def send_chat_request(request_body, request_headers) -> AsyncGenerator[Dic
262263
# "title": annotation.title,
263264
# "url": annotation.url
264265
# })
265-
266+
266267
# Check if citation markers are present
267268
has_citation_markers = bool(re.search(r'【(\d+:\d+)†source】', response_text))
268269
if has_citation_markers:
@@ -282,7 +283,7 @@ async def send_chat_request(request_body, request_headers) -> AsyncGenerator[Dic
282283
template_agent_name = app_settings.azure_ai.agent_name_template
283284
if not template_agent_name:
284285
raise ValueError("Template agent name not configured in settings")
285-
286+
286287
async with (
287288
await get_azure_credential_async(client_id=app_settings.base_settings.azure_client_id) as credential,
288289
AIProjectClient(endpoint=app_settings.azure_ai.agent_endpoint, credential=credential) as project_client,
@@ -300,17 +301,17 @@ async def send_chat_request(request_body, request_headers) -> AsyncGenerator[Dic
300301
) as chat_agent:
301302
thread = chat_agent.get_new_thread()
302303
result = await chat_agent.run(messages=conversation_prompt, thread=thread)
303-
304+
304305
# Extract text from result
305306
if hasattr(result, 'text'):
306307
response_text = result.text
307308
else:
308309
response_text = str(result) if result is not None else ""
309-
310+
310311
# Remove citation markers from template
311312
response_text = re.sub(r'【(\d+:\d+)†source】', '', response_text)
312313
answer["answer"] = convert_citation_markers(response_text, doc_mapping)
313-
314+
314315
# # Collect citations from annotations (if any)
315316
# if hasattr(result, 'contents') and result.contents:
316317
# for content in result.contents:
@@ -322,7 +323,7 @@ async def send_chat_request(request_body, request_headers) -> AsyncGenerator[Dic
322323
# "title": annotation.title,
323324
# "url": annotation.url
324325
# })
325-
326+
326327
yield {
327328
"answer": answer["answer"],
328329
"citations": json.dumps(answer["citations"])
@@ -1097,10 +1098,10 @@ def fetch_content(fetch_url):
10971098
async def generate_title(conversation_messages):
10981099
"""
10991100
Generate a conversation title using the Title Agent.
1100-
1101+
11011102
Args:
11021103
conversation_messages: List of conversation messages
1103-
1104+
11041105
Returns:
11051106
str: Generated title or fallback content
11061107
"""
@@ -1152,11 +1153,11 @@ async def generate_title(conversation_messages):
11521153
async def get_section_content(request_body, request_headers):
11531154
"""
11541155
Generate section content using the Section Agent.
1155-
1156+
11561157
Args:
11571158
request_body: Request body containing sectionTitle and sectionDescription
11581159
request_headers: Request headers
1159-
1160+
11601161
Returns:
11611162
str: Generated section content
11621163
"""
@@ -1191,14 +1192,14 @@ async def get_section_content(request_body, request_headers):
11911192
thread = chat_agent.get_new_thread()
11921193
result = await chat_agent.run(messages=user_prompt, thread=thread)
11931194
response_text = str(result) if result is not None else ""
1194-
1195+
11951196
# Remove citation markers from section content
11961197
response_text = re.sub(r'【(\d+:\d+)†source】', '', response_text)
1197-
1198+
11981199
track_event_if_configured("SectionContentGenerated", {
11991200
"sectionTitle": request_body["sectionTitle"]
12001201
})
1201-
1202+
12021203
return response_text
12031204

12041205
except Exception as e:

src/tests/unit_tests/helpers/test_azure_credential_utils.py

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,17 @@
1-
import pytest
2-
import sys
31
import os
2+
import sys
43
from unittest.mock import patch, MagicMock
54

5+
import pytest
6+
67
# Ensure src/backend is on the Python path for imports
78
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "../../../")))
89

910
import backend.helpers.azure_credential_utils as azure_credential_utils
1011

1112
# Synchronous tests
1213

14+
1315
@patch("backend.helpers.azure_credential_utils.os.getenv")
1416
@patch("backend.helpers.azure_credential_utils.DefaultAzureCredential")
1517
@patch("backend.helpers.azure_credential_utils.ManagedIdentityCredential")
@@ -26,6 +28,7 @@ def test_get_azure_credential_dev_env(mock_managed_identity_credential, mock_def
2628
mock_managed_identity_credential.assert_not_called()
2729
assert credential == mock_default_credential
2830

31+
2932
@patch("backend.helpers.azure_credential_utils.os.getenv")
3033
@patch("backend.helpers.azure_credential_utils.DefaultAzureCredential")
3134
@patch("backend.helpers.azure_credential_utils.ManagedIdentityCredential")
@@ -43,6 +46,7 @@ def test_get_azure_credential_non_dev_env(mock_managed_identity_credential, mock
4346

4447
# Asynchronous tests
4548

49+
4650
@pytest.mark.asyncio
4751
@patch("backend.helpers.azure_credential_utils.os.getenv")
4852
@patch("backend.helpers.azure_credential_utils.AioDefaultAzureCredential")
@@ -60,6 +64,7 @@ async def test_get_azure_credential_async_dev_env(mock_aio_managed_identity_cred
6064
mock_aio_managed_identity_credential.assert_not_called()
6165
assert credential == mock_aio_default_credential
6266

67+
6368
@pytest.mark.asyncio
6469
@patch("backend.helpers.azure_credential_utils.os.getenv")
6570
@patch("backend.helpers.azure_credential_utils.AioDefaultAzureCredential")
@@ -75,4 +80,4 @@ async def test_get_azure_credential_async_non_dev_env(mock_aio_managed_identity_
7580
mock_getenv.assert_called_once_with("APP_ENV", "prod")
7681
mock_aio_managed_identity_credential.assert_called_once_with(client_id="test-client-id")
7782
mock_aio_default_azure_credential.assert_not_called()
78-
assert credential == mock_aio_managed_credential
83+
assert credential == mock_aio_managed_credential

0 commit comments

Comments
 (0)