1+ import logging
12from quart import current_app
23from semantic_kernel .agents import AzureAIAgent , AzureAIAgentThread
34from semantic_kernel .contents .chat_message_content import ChatMessageContent
45from semantic_kernel .contents .utils .author_role import AuthorRole
56
7+ from backend .agents .agent_factory import AgentFactory
68from backend .common .config import config
79from backend .services .sqldb_service import get_client_name_from_db
810
11+ async def ensure_agents (app ):
12+ """Ensure both agents are initialized on demand."""
13+ if not hasattr (app , "wealth_advisor_agent" ) or app .wealth_advisor_agent is None :
14+ app .wealth_advisor_agent = await AgentFactory .get_wealth_advisor_agent ()
15+ logging .info ("Wealth Advisor Agent initialized on demand" )
16+ if not hasattr (app , "search_agent" ) or app .search_agent is None :
17+ app .search_agent = await AgentFactory .get_search_agent ()
18+ logging .info ("Search Agent initialized on demand" )
19+
20+ async def delete_agents (app ):
21+ """Delete both agents after use."""
22+ await AgentFactory .delete_all_agent_instance ()
23+ app .wealth_advisor_agent = None
24+ app .search_agent = None
925
1026async def stream_response_from_wealth_assistant (query : str , client_id : str ):
1127 """
1228 Streams real-time chat response from the Wealth Assistant.
1329 Uses Semantic Kernel agent with SQL and Azure Cognitive Search based on the client ID.
1430 """
31+ thread = None
1532 try :
1633 # Dynamically get the name from the database
17- selected_client_name = get_client_name_from_db (
18- client_id
19- ) # Optionally fetch from DB
34+ selected_client_name = get_client_name_from_db (client_id )
2035
2136 # Prepare fallback instructions with the single-line prompt
2237 additional_instructions = config .STREAM_TEXT_SYSTEM_PROMPT
@@ -37,28 +52,35 @@ async def stream_response_from_wealth_assistant(query: str, client_id: str):
3752 "{client_id}" , client_id
3853 )
3954
55+ # Lazy agent initialization
56+ await ensure_agents (current_app )
4057 agent : AzureAIAgent = current_app .wealth_advisor_agent
4158
42- thread : AzureAIAgentThread = None
4359 message = ChatMessageContent (role = AuthorRole .USER , content = query )
4460 sk_response = agent .invoke_stream (
4561 messages = [message ],
46- thread = thread ,
62+ thread = None ,
4763 additional_instructions = additional_instructions ,
4864 )
4965
5066 async def generate ():
67+ nonlocal thread
5168 try :
5269 # yields deltaText strings one-by-one
5370 async for chunk in sk_response :
5471 if not chunk or not chunk .content :
5572 continue
73+ thread = chunk .thread if hasattr (chunk , "thread" ) else None
5674 yield chunk .content # just the deltaText
5775 finally :
58- thread = chunk .thread if chunk else None
59- await thread .delete () if thread else None
76+ if thread :
77+ await thread .delete ()
78+ # Delete agents after operation
79+ await delete_agents (current_app )
6080
6181 return generate
6282 except Exception as e :
63- await thread .delete () if thread else None
64- raise e
83+ if thread :
84+ await thread .delete ()
85+ await delete_agents (current_app )
86+ raise e
0 commit comments