Spaces:
Sleeping
Sleeping
| import ast | |
| import os | |
| import json | |
| import hashlib | |
| import logging | |
| from fastapi import APIRouter | |
| from redis import Redis | |
| from fastapi.responses import StreamingResponse | |
| from api.stored_data import stored_data | |
| from src.genai.analytics_chatbot.agent import ChatbotAgent | |
| from src.genai.analytics_chatbot.utils.utils import process_query | |
| from api.schemas.analytics_chatbot import UserMessage | |
| from config.redis_config import redis_client | |
| app_logger = logging.getLogger("app_logger") | |
| error_logger = logging.getLogger("error_logger") | |
| router = APIRouter() | |
| agent=ChatbotAgent() | |
| graph = agent.chatbot_graph() | |
| def get_analytics(msg:str): | |
| # user_query=process_query(msg) | |
| cache_key = f"analytics:{hashlib.md5(msg.encode()).hexdigest()}" | |
| cached_response = redis_client.get(cache_key) | |
| if cached_response: | |
| print("Cache hit") | |
| return json.loads(cached_response) | |
| config={"configurable": {"thread_id": "analytics-chatbot-thread"},"run_name":"analytics-chatbot"} | |
| result=graph.invoke({'messages':msg},config=config) | |
| print('Final Result:', result) | |
| response_to_cache = {} | |
| if result.get('backup_data') is not None: | |
| response_to_cache = {'backup_response': result['backup_data']} | |
| else: | |
| response_to_cache = { | |
| 'response': result['response'], | |
| 'endpoint': result['endpoint'] | |
| } | |
| # Save to Redis with TTL (e.g., 1 hour) | |
| redis_client.set(cache_key, json.dumps(response_to_cache), ex=1) # ex=seconds | |
| return response_to_cache | |