11from fastapi import APIRouter , HTTPException , Request
22from fastapi .responses import StreamingResponse
33from schemas import ChatRequest
4- from routes .connection import get_user_db , get_db_pool , get_schema_filter_for , get_db_type
4+ from routes .connection import get_user_db , get_db_pool , get_schema_filter_for , get_db_type , get_connection_details
55from utils .deepseek_client import deepseek_client
66from utils .schema_queries import get_count_query
7+ from utils .activity import log_activity , ActivityType
8+ from utils .cache_db import get_cached_chat_response , store_chat_response
79import logging
810import json
911from typing import Optional
@@ -26,6 +28,30 @@ async def chat_with_schema_streaming(request: ChatStreamRequest):
2628 try :
2729 db = get_db_pool (request .connection_id ) if request .connection_id else get_user_db ()
2830
31+ # Check cache first
32+ conn_details = get_connection_details (request .connection_id )
33+ if conn_details :
34+ cached = await get_cached_chat_response (
35+ host = conn_details ["host" ],
36+ port = conn_details ["port" ],
37+ database = conn_details ["database" ],
38+ schema_filter = conn_details ["schema_filter" ],
39+ user = conn_details ["user" ],
40+ question = request .question ,
41+ )
42+ if cached :
43+ log_activity (
44+ ActivityType .CHAT_QUERY ,
45+ "Chat query (cached)" ,
46+ f"Asked: { request .question [:80 ]} { '...' if len (request .question ) > 80 else '' } " ,
47+ {"question" : request .question [:200 ], "cached" : True }
48+ )
49+ async def cached_response ():
50+ yield json .dumps ({"type" : "status" , "message" : "⚡ Found cached response..." }) + "\n "
51+ yield json .dumps ({"type" : "content" , "data" : cached }) + "\n "
52+ yield json .dumps ({"type" : "done" }) + "\n "
53+ return StreamingResponse (cached_response (), media_type = "application/x-ndjson" )
54+
2955 # Build comprehensive context from all tables
3056 async with db .acquire () as conn :
3157 tables_query = """
@@ -40,7 +66,6 @@ async def chat_with_schema_streaming(request: ChatStreamRequest):
4066 context = "DATABASE SCHEMA:\n "
4167 db_type = get_db_type (request .connection_id )
4268 for table_name in table_names :
43- # Get row count
4469 count_query = get_count_query (table_name , db_type )
4570 count_result = await conn .fetchval (count_query )
4671
@@ -54,30 +79,49 @@ async def chat_with_schema_streaming(request: ChatStreamRequest):
5479
5580 async def stream_response ():
5681 """Generator that streams response chunks"""
57- # Send initial status that appears in blue box
82+ log_activity (
83+ ActivityType .CHAT_QUERY ,
84+ "Chat query (streaming)" ,
85+ f"Asked: { request .question [:80 ]} { '...' if len (request .question ) > 80 else '' } " ,
86+ {"question" : request .question [:200 ]}
87+ )
5888 yield json .dumps ({"type" : "status" , "message" : "🤖 Connecting to AI..." }) + "\n "
5989 yield json .dumps ({"type" : "status" , "message" : "📊 Analyzing your database..." }) + "\n "
6090 yield json .dumps ({"type" : "status" , "message" : "🔍 Processing your question..." }) + "\n "
6191 yield json .dumps ({"type" : "status" , "message" : "⚡ Generating response..." }) + "\n "
6292
6393 try :
64- # Stream the actual response content (without progress messages)
94+ full_response = ""
6595 async for chunk in deepseek_client .stream_chat_about_schema (
6696 question = request .question ,
6797 context = context
6898 ):
69- # Send content chunks directly (no status messages mixed in)
99+ full_response += chunk
70100 yield json .dumps ({"type" : "content" , "data" : chunk }) + "\n "
71101
72- # Completion signal
102+ # Store in cache for future requests
103+ if conn_details and full_response :
104+ try :
105+ await store_chat_response (
106+ host = conn_details ["host" ],
107+ port = conn_details ["port" ],
108+ database = conn_details ["database" ],
109+ schema_filter = conn_details ["schema_filter" ],
110+ user = conn_details ["user" ],
111+ question = request .question ,
112+ response = full_response ,
113+ )
114+ except Exception as cache_err :
115+ logger .warning (f"Failed to cache chat response: { cache_err } " )
116+
73117 yield json .dumps ({"type" : "done" }) + "\n "
74118 except Exception as e :
75119 logger .error (f"Streaming error: { e } " )
76120 yield json .dumps ({"type" : "error" , "message" : f"Error: { str (e )} " }) + "\n "
77121
78122 return StreamingResponse (
79123 stream_response (),
80- media_type = "application/x-ndjson" # Newline-delimited JSON
124+ media_type = "application/x-ndjson"
81125 )
82126
83127 except HTTPException :
0 commit comments