Spaces:
Sleeping
Sleeping
| import ast | |
| import json | |
| import logging | |
| from fastapi import APIRouter | |
| from fastapi.responses import StreamingResponse | |
| from api.stored_data import stored_data | |
| from src.genai.context_analysis_agent.agent import IntroductionChatbot | |
| from api.schemas.context_analysis import UserMessage | |
| app_logger = logging.getLogger("app_logger") | |
| error_logger = logging.getLogger("error_logger") | |
| router = APIRouter() | |
| context_analysis_graph = IntroductionChatbot() | |
| def context_analysis(msg: UserMessage): | |
| def event_generator(): | |
| try: | |
| accumulated_response = "" | |
| for chunk in context_analysis_graph.chat(msg.message): | |
| accumulated_response += chunk | |
| payload = { | |
| "streamed_response": chunk, | |
| } | |
| yield json.dumps(payload) + "\n" | |
| app_logger.info('Executed context analysis agent') | |
| last_response = context_analysis_graph.messages[-1]["content"] | |
| print('Last-Response:', last_response) | |
| if context_analysis_graph.is_complete(last_response) == 'complete': | |
| app_logger.info('Context analysis completed.') | |
| try: | |
| details = context_analysis_graph.extract_details() | |
| app_logger.info('Details extracted after context analysis.') | |
| except Exception as e: | |
| error_logger.error(f'Unable to extract details: {e}') | |
| if type(details) != dict:details = details.model_dump() | |
| if isinstance(details, str):details = ast.literal_eval(details) | |
| stored_data["business_details"] = details | |
| try: | |
| context_analysis_graph.reset() | |
| app_logger.info('Context analysis memory reset after details extraction.') | |
| except Exception as e: | |
| error_logger.error('Unable to reset memory:', e) | |
| final_payload = { | |
| "response": accumulated_response, | |
| "complete": True, | |
| "business_details": details | |
| } | |
| else: | |
| final_payload = { | |
| "response": accumulated_response, | |
| "complete": False | |
| } | |
| yield json.dumps(final_payload) + "\n" | |
| except Exception as e: | |
| error_logger.error('Unable to run context analysis agent:', e) | |
| return StreamingResponse(event_generator(), media_type="text/event-stream") | |