44import logging
55import os
66import re
7+ import requests
78import uuid
89from 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):
10971098async 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):
11521153async 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 :
0 commit comments