Update routes.py
Browse files
routes.py
CHANGED
@@ -1,5 +1,7 @@
|
|
1 |
# routes.py
|
2 |
|
|
|
|
|
3 |
from fastapi import APIRouter, Body, HTTPException
|
4 |
from models import (
|
5 |
PageSpeedURLRequest,
|
@@ -15,6 +17,9 @@ from gemini_report import generate_report_with_gemini
|
|
15 |
from chatbot import create_new_chat, get_chain_for_user, summarize_messages
|
16 |
from langchain_mongodb.chat_message_histories import MongoDBChatMessageHistory
|
17 |
|
|
|
|
|
|
|
18 |
router = APIRouter()
|
19 |
|
20 |
|
@@ -25,10 +30,13 @@ async def ingest_user_report(request: ReportIngestRequest):
|
|
25 |
"""
|
26 |
Ingests a user’s PageSpeed report text into the FAISS vectorstore.
|
27 |
"""
|
|
|
28 |
try:
|
29 |
vectorstore, retriever = ingest_report(request.user_id, request.report_text)
|
|
|
30 |
return {"status": "success", "message": f"Report ingested for user {request.user_id}"}
|
31 |
except Exception as e:
|
|
|
32 |
raise HTTPException(status_code=500, detail=str(e))
|
33 |
|
34 |
|
@@ -37,8 +45,14 @@ async def generate_report(data: dict = Body(...)):
|
|
37 |
"""
|
38 |
Generates a report using Gemini given arbitrary data in the request body.
|
39 |
"""
|
40 |
-
report =
|
41 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
42 |
|
43 |
|
44 |
@router.post("/fetch-pagespeed-data")
|
@@ -46,10 +60,13 @@ async def fetch_pagespeed_data(request: PageSpeedURLRequest):
|
|
46 |
"""
|
47 |
Fetches PageSpeed Insights data for the provided target URL.
|
48 |
"""
|
|
|
49 |
try:
|
50 |
data = get_pagespeed_data(request.target_url, PAGESPEED_API_KEY)
|
|
|
51 |
return {"status": "success", "data": data}
|
52 |
except Exception as e:
|
|
|
53 |
raise HTTPException(status_code=500, detail=str(e))
|
54 |
|
55 |
|
@@ -58,6 +75,7 @@ async def home():
|
|
58 |
"""
|
59 |
Simple health check endpoint.
|
60 |
"""
|
|
|
61 |
return {"API is UP and running"}
|
62 |
|
63 |
|
@@ -69,10 +87,13 @@ async def new_chat(request: NewChatRequest):
|
|
69 |
Creates a new chat session for the given user_id and returns a chat_id.
|
70 |
Expected JSON body: {"user_id": "<string>"}
|
71 |
"""
|
|
|
72 |
try:
|
73 |
chat_id = create_new_chat(request.user_id)
|
|
|
74 |
return {"status": "success", "chat_id": chat_id}
|
75 |
except Exception as e:
|
|
|
76 |
raise HTTPException(status_code=500, detail=str(e))
|
77 |
|
78 |
|
@@ -87,16 +108,19 @@ async def chat_query(request: ChatQueryRequest):
|
|
87 |
"query": "<string>"
|
88 |
}
|
89 |
"""
|
|
|
90 |
try:
|
91 |
# Reconstruct the ConversationalRetrievalChain for this user & chat_id
|
92 |
chain = get_chain_for_user(request.user_id, request.chat_id)
|
93 |
chat_history: MongoDBChatMessageHistory = chain.memory # type: ignore
|
94 |
|
95 |
# Optionally summarize if the history is too long
|
96 |
-
summarize_messages(chat_history)
|
|
|
97 |
|
98 |
# Add the user’s message to history
|
99 |
chat_history.add_user_message(request.query)
|
|
|
100 |
|
101 |
# Run the chain synchronously (non-streaming)
|
102 |
result = chain({
|
@@ -105,15 +129,22 @@ async def chat_query(request: ChatQueryRequest):
|
|
105 |
})
|
106 |
|
107 |
answer = result.get("answer", "").strip()
|
|
|
108 |
|
109 |
# Persist the AI’s message
|
110 |
if answer:
|
111 |
chat_history.add_ai_message(answer)
|
|
|
112 |
|
113 |
-
return {
|
|
|
|
|
|
|
|
|
114 |
|
115 |
except ValueError as ve:
|
116 |
-
|
117 |
raise HTTPException(status_code=404, detail=str(ve))
|
118 |
except Exception as e:
|
|
|
119 |
raise HTTPException(status_code=500, detail=str(e))
|
|
|
1 |
# routes.py
|
2 |
|
3 |
+
import logging
|
4 |
+
|
5 |
from fastapi import APIRouter, Body, HTTPException
|
6 |
from models import (
|
7 |
PageSpeedURLRequest,
|
|
|
17 |
from chatbot import create_new_chat, get_chain_for_user, summarize_messages
|
18 |
from langchain_mongodb.chat_message_histories import MongoDBChatMessageHistory
|
19 |
|
20 |
+
# Configure logger to integrate with Uvicorn’s logging
|
21 |
+
logger = logging.getLogger("uvicorn.error")
|
22 |
+
|
23 |
router = APIRouter()
|
24 |
|
25 |
|
|
|
30 |
"""
|
31 |
Ingests a user’s PageSpeed report text into the FAISS vectorstore.
|
32 |
"""
|
33 |
+
logger.info(f"[ingest-report] Received ingest request for user_id={request.user_id}")
|
34 |
try:
|
35 |
vectorstore, retriever = ingest_report(request.user_id, request.report_text)
|
36 |
+
logger.info(f"[ingest-report] Successfully ingested report for user_id={request.user_id}")
|
37 |
return {"status": "success", "message": f"Report ingested for user {request.user_id}"}
|
38 |
except Exception as e:
|
39 |
+
logger.error(f"[ingest-report] Error ingesting report for user_id={request.user_id}: {e}")
|
40 |
raise HTTPException(status_code=500, detail=str(e))
|
41 |
|
42 |
|
|
|
45 |
"""
|
46 |
Generates a report using Gemini given arbitrary data in the request body.
|
47 |
"""
|
48 |
+
logger.info(f"[generate-report] Received data for Gemini report generation: keys={list(data.keys())}")
|
49 |
+
try:
|
50 |
+
report = generate_report_with_gemini(data, GEMINI_API_KEY)
|
51 |
+
logger.info(f"[generate-report] Successfully generated report")
|
52 |
+
return {"report": report}
|
53 |
+
except Exception as e:
|
54 |
+
logger.error(f"[generate-report] Error generating report: {e}")
|
55 |
+
raise HTTPException(status_code=500, detail=str(e))
|
56 |
|
57 |
|
58 |
@router.post("/fetch-pagespeed-data")
|
|
|
60 |
"""
|
61 |
Fetches PageSpeed Insights data for the provided target URL.
|
62 |
"""
|
63 |
+
logger.info(f"[fetch-pagespeed-data] Fetching PageSpeed for URL={request.target_url}")
|
64 |
try:
|
65 |
data = get_pagespeed_data(request.target_url, PAGESPEED_API_KEY)
|
66 |
+
logger.info(f"[fetch-pagespeed-data] Successfully fetched PageSpeed data for URL={request.target_url}")
|
67 |
return {"status": "success", "data": data}
|
68 |
except Exception as e:
|
69 |
+
logger.error(f"[fetch-pagespeed-data] Error fetching PageSpeed data for URL={request.target_url}: {e}")
|
70 |
raise HTTPException(status_code=500, detail=str(e))
|
71 |
|
72 |
|
|
|
75 |
"""
|
76 |
Simple health check endpoint.
|
77 |
"""
|
78 |
+
logger.info("[home] Health check endpoint called")
|
79 |
return {"API is UP and running"}
|
80 |
|
81 |
|
|
|
87 |
Creates a new chat session for the given user_id and returns a chat_id.
|
88 |
Expected JSON body: {"user_id": "<string>"}
|
89 |
"""
|
90 |
+
logger.info(f"[new-chat] Creating new chat session for user_id={request.user_id}")
|
91 |
try:
|
92 |
chat_id = create_new_chat(request.user_id)
|
93 |
+
logger.info(f"[new-chat] Created chat_id={chat_id} for user_id={request.user_id}")
|
94 |
return {"status": "success", "chat_id": chat_id}
|
95 |
except Exception as e:
|
96 |
+
logger.error(f"[new-chat] Error creating chat session for user_id={request.user_id}: {e}")
|
97 |
raise HTTPException(status_code=500, detail=str(e))
|
98 |
|
99 |
|
|
|
108 |
"query": "<string>"
|
109 |
}
|
110 |
"""
|
111 |
+
logger.info(f"[chat] Received query for user_id={request.user_id}, chat_id={request.chat_id}")
|
112 |
try:
|
113 |
# Reconstruct the ConversationalRetrievalChain for this user & chat_id
|
114 |
chain = get_chain_for_user(request.user_id, request.chat_id)
|
115 |
chat_history: MongoDBChatMessageHistory = chain.memory # type: ignore
|
116 |
|
117 |
# Optionally summarize if the history is too long
|
118 |
+
if summarize_messages(chat_history):
|
119 |
+
logger.info(f"[chat] Summarized chat history for chat_id={request.chat_id}")
|
120 |
|
121 |
# Add the user’s message to history
|
122 |
chat_history.add_user_message(request.query)
|
123 |
+
logger.info(f"[chat] Added user message to history: \"{request.query}\"")
|
124 |
|
125 |
# Run the chain synchronously (non-streaming)
|
126 |
result = chain({
|
|
|
129 |
})
|
130 |
|
131 |
answer = result.get("answer", "").strip()
|
132 |
+
logger.info(f"[chat] LLM returned answer=\"{answer}\" for user_id={request.user_id}")
|
133 |
|
134 |
# Persist the AI’s message
|
135 |
if answer:
|
136 |
chat_history.add_ai_message(answer)
|
137 |
+
logger.info(f"[chat] Persisted AI message to history for chat_id={request.chat_id}")
|
138 |
|
139 |
+
return {
|
140 |
+
"status": "success",
|
141 |
+
"answer": answer,
|
142 |
+
"source_documents": result.get("source_documents", []),
|
143 |
+
}
|
144 |
|
145 |
except ValueError as ve:
|
146 |
+
logger.warning(f"[chat] No vectorstore for user_id={request.user_id}: {ve}")
|
147 |
raise HTTPException(status_code=404, detail=str(ve))
|
148 |
except Exception as e:
|
149 |
+
logger.error(f"[chat] Error processing chat request for user_id={request.user_id}, chat_id={request.chat_id}: {e}")
|
150 |
raise HTTPException(status_code=500, detail=str(e))
|