Skip to content

Commit 06f91c1

Browse files
added stream plus wss provision for rhl_fastapi_deploy
1 parent 24c0863 commit 06f91c1

File tree

4 files changed

+143
-14
lines changed

4 files changed

+143
-14
lines changed
Binary file not shown.

FASTAPI-DEPLOYMENT/rhl_fastapi_deploy.py

Lines changed: 143 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
import re
66
from pathlib import Path
77
from dotenv import load_dotenv
8-
from fastapi import FastAPI, HTTPException, Query, BackgroundTasks
8+
from fastapi import FastAPI, HTTPException, Query, BackgroundTasks, WebSocket, WebSocketDisconnect
99
from fastapi.responses import StreamingResponse
1010
import aiosqlite
1111
from typing import List, Tuple, Dict, Any
@@ -754,23 +754,30 @@ async def _background_update_and_save(user_id: str, user_message: str, bot_reply
754754
- STOP adding points once the query is fully answered
755755
756756
757-
STEP 4 - FOLLOW-UP QUESTION (MANDATORY IF context_followup PROVIDED):
758-
- If <context_followup> is non-empty, you MUST include a follow-up question
757+
STEP 4 - FOLLOW-UP QUESTION (CONDITIONAL - ONLY IF CLOSELY RELATED):
758+
- Follow-up questions should ONLY be provided if there is VERY CLOSE RESEMBLANCE between the answer topic and the follow-up context topic
759+
- CRITICAL RULE: Before generating a follow-up, analyze if the <context_followup> topic is an EXTENSION or CLOSELY RELATED aspect of the answer topic
760+
* ✅ INCLUDE follow-up if: The follow-up context discusses the SAME medical condition/topic as your answer (e.g., answer about jaundice → follow-up about complications of jaundice, treatment of jaundice, prevention of jaundice)
761+
* ❌ EXCLUDE follow-up if: The follow-up context discusses a DIFFERENT medical condition/topic (e.g., answer about jaundice → follow-up about blood pressure, diabetes, or any unrelated topic)
759762
- Format: "Would you like to know about <topic from context_followup>?" (without bullet points, at the end of answer)
760763
- Follow-up should be about a medical topic (not general/document titles like "Clinical Reference Manual for Advanced Neonatal Care in Ethiopia" ❌)
761764
- Follow-up should NOT overlap with information already in the answer
762765
- The follow-up must be STRICTLY from context_followup
763766
764767
CRITICAL FOR FOLLOW-UP GENERATION:
765-
- Read the ENTIRE context_followup content carefully
766-
- Extract the MAIN MEDICAL TOPIC or KEY TERM from context_followup
768+
- FIRST: Identify the MAIN TOPIC of your answer (e.g., "jaundice", "pre-eclampsia", "newborn feeding")
769+
- SECOND: Read the ENTIRE context_followup content carefully
770+
- THIRD: Extract the MAIN MEDICAL TOPIC or KEY TERM from context_followup
771+
- FOURTH: Compare the topics - Are they the SAME medical condition/topic or closely related aspects?
772+
* If YES (same topic, different aspect) → Generate follow-up question
773+
* If NO (different topic entirely) → DO NOT generate follow-up question
767774
- Look for medical conditions, treatments, symptoms, complications, or procedures mentioned
768775
- Generate a question that will match relevant medical documents when searched
769776
- Use specific medical terminology that appears in medical documents
770777
- Avoid generic phrases - use precise medical terms (e.g., "treatment for jaundice" not "more information")
771778
- Ensure the question format matches how medical documents are indexed (e.g., "What are the complications of X?", "How to manage Y?", "What are the symptoms of Z?")
772779
- The question should be searchable and will retrieve relevant chunks from the document database
773-
- If context_followup contains multiple topics, pick the most relevant/interesting one that doesn't overlap with your answer
780+
- If context_followup contains multiple topics, pick the one that is MOST CLOSELY RELATED to your answer topic
774781
775782
EXAMPLES:
776783
@@ -885,7 +892,7 @@ async def _background_update_and_save(user_id: str, user_message: str, bot_reply
885892
886893
---
887894
888-
Example 5 - Follow-up Question Generation:
895+
Example 5 - Follow-up Question Generation (CLOSELY RELATED - INCLUDE):
889896
Query: "What causes jaundice?"
890897
Context:
891898
From [jaundice_guide.pdf]:
@@ -895,6 +902,7 @@ async def _background_update_and_save(user_id: str, user_message: str, bot_reply
895902
From [complications_guide.pdf]:
896903
Complications of jaundice include liver damage, kernicterus in newborns, and chronic liver disease.
897904
905+
Analysis: Answer topic = "jaundice", Follow-up topic = "complications of jaundice" → SAME topic (jaundice), different aspect (complications) → ✅ CLOSELY RELATED → INCLUDE follow-up
898906
Answer:
899907
According to jaundice_guide:
900908
• Jaundice is caused by bilirubin buildup in the blood
@@ -903,7 +911,49 @@ async def _background_update_and_save(user_id: str, user_message: str, bot_reply
903911
904912
Would you like to know about complications of jaundice?
905913
906-
Note: The follow-up question extracted the main medical topic "complications of jaundice" from the followup_context, which is a specific, searchable medical term that will match documents.
914+
Note: The follow-up question extracted the main medical topic "complications of jaundice" from the followup_context, which is a specific, searchable medical term that will match documents. This is included because it's an extension of the same topic (jaundice).
915+
916+
---
917+
918+
Example 5b - Follow-up Question Generation (DIFFERENT TOPIC - EXCLUDE):
919+
Query: "What causes jaundice?"
920+
Context:
921+
From [jaundice_guide.pdf]:
922+
Jaundice is caused by bilirubin buildup...
923+
924+
Followup Context:
925+
From [blood_pressure_guide.pdf]:
926+
Blood pressure management involves monitoring systolic and diastolic readings. High blood pressure can lead to cardiovascular complications.
927+
928+
Analysis: Answer topic = "jaundice", Follow-up topic = "blood pressure" → DIFFERENT topics entirely → ❌ NOT CLOSELY RELATED → EXCLUDE follow-up
929+
Answer:
930+
According to jaundice_guide:
931+
• Jaundice is caused by bilirubin buildup in the blood
932+
• Common causes include liver diseases and hemolytic anemia
933+
• Newborn jaundice is common due to immature liver function
934+
935+
Note: No follow-up question is included because the follow-up context discusses "blood pressure", which is a completely different medical topic from "jaundice" (the answer topic). Follow-ups should only be provided when they are extensions or closely related aspects of the same topic.
936+
937+
---
938+
939+
Example 5c - Follow-up Question Generation (SAME TOPIC, DIFFERENT ASPECT - INCLUDE):
940+
Query: "What are the symptoms of jaundice?"
941+
Context:
942+
From [symptom_guide.pdf]:
943+
Jaundice symptoms include yellowing of skin, yellowing of eyes, dark urine.
944+
945+
Followup Context:
946+
From [treatment_guide.pdf]:
947+
Treatment of jaundice involves phototherapy for newborns, addressing underlying liver conditions, and in severe cases, exchange transfusion.
948+
949+
Analysis: Answer topic = "jaundice" (symptoms), Follow-up topic = "treatment of jaundice" → SAME topic (jaundice), different aspect (treatment) → ✅ CLOSELY RELATED → INCLUDE follow-up
950+
Answer:
951+
According to symptom_guide:
952+
• Yellowing of skin and eyes (sclera) is the primary visible symptom
953+
• Dark urine indicates bile pigment changes
954+
• Pale stools may occur in some cases
955+
956+
Would you like to know about treatment of jaundice?
907957
908958
---
909959
@@ -1203,13 +1253,17 @@ async def _background_update_and_save(user_id: str, user_message: str, bot_reply
12031253
5. Assess confidence: Only answer if you can logically explain how chunks support your answer
12041254
6. Synthesize information from multiple sources (use format: "According to A, B, C" when multiple sources contribute)
12051255
7. Generate answer following all rules above - be confident if reasoning is clear, be honest if it fails
1206-
8. MANDATORY: If <followup_context> is provided and non-empty, you MUST include a follow-up question at the end
1207-
- Read the entire <followup_context> content
1208-
- Extract the MAIN MEDICAL TOPIC or KEY TERM from <followup_context>
1209-
- Generate: "Would you like to know about [specific medical topic]?"
1256+
8. CONDITIONAL: If <followup_context> is provided and non-empty, evaluate if follow-up should be included:
1257+
- FIRST: Identify the MAIN TOPIC of your answer (e.g., "jaundice", "pre-eclampsia", "newborn feeding")
1258+
- SECOND: Read the entire <followup_context> content
1259+
- THIRD: Extract the MAIN MEDICAL TOPIC or KEY TERM from <followup_context>
1260+
- FOURTH: Compare topics - Are they the SAME medical condition/topic or closely related aspects?
1261+
* ✅ INCLUDE follow-up if: Same topic, different aspect (e.g., answer about jaundice → follow-up about complications/treatment/prevention of jaundice)
1262+
* ❌ EXCLUDE follow-up if: Different topic entirely (e.g., answer about jaundice → follow-up about blood pressure, diabetes, or any unrelated topic)
1263+
- If INCLUDING: Generate "Would you like to know about [specific medical topic]?" (without bullet points, at the end of answer)
12101264
- Use precise medical terminology that will match document searches
12111265
- Example: "Would you like to know about jaundice treatment?" (not "Would you like more information?")
1212-
- The follow-up question should be the LAST line of your response
1266+
- The follow-up question should be the LAST line of your response (only if included)
12131267
12141268
CRITICAL REASONING PRINCIPLES:
12151269
- Think step-by-step: What does each chunk tell you? How can you connect them to answer the query?
@@ -1221,7 +1275,7 @@ async def _background_update_and_save(user_id: str, user_message: str, bot_reply
12211275
- If you cannot reason a confident answer → Respond with: "I couldn't find sufficient information in the provided documents to answer this question accurately."
12221276
- NEVER use external knowledge - only reason within provided chunks
12231277
1224-
REMINDER: If <followup_context> is provided, you MUST generate a follow-up question. Do not skip this step.
1278+
REMINDER: If <followup_context> is provided, evaluate if the follow-up topic is closely related to your answer topic. Only include a follow-up question if there is very close resemblance (same medical condition/topic, different aspect). If the follow-up context discusses a different medical topic entirely, DO NOT include a follow-up question.
12251279
12261280
Write the final answer now.
12271281
"""
@@ -3352,6 +3406,81 @@ async def generate():
33523406

33533407
return StreamingResponse(generate(), media_type="text/event-stream")
33543408

3409+
@app.websocket("/chat-ws")
3410+
async def chat_websocket_endpoint(websocket: WebSocket):
3411+
"""
3412+
WebSocket endpoint for streaming chat responses.
3413+
Client sends: {"user_id": "...", "message": "..."}
3414+
Server sends: {"type": "token|metadata|error", "content": "..."} or {"type": "metadata", ...}
3415+
"""
3416+
await websocket.accept()
3417+
print(f"[WEBSOCKET] Client connected: {websocket.client}")
3418+
3419+
try:
3420+
# Receive initial message with user_id and message
3421+
data = await websocket.receive_json()
3422+
user_id = data.get("user_id", "default_user")
3423+
user_message = data.get("message", "")
3424+
3425+
print(f"[WEBSOCKET] Received: user_id={user_id}, message={user_message[:50]}...")
3426+
3427+
# Create background tasks container
3428+
class BackgroundTasksContainer:
3429+
def __init__(self):
3430+
self.tasks = []
3431+
def add_task(self, func, *args, **kwargs):
3432+
self.tasks.append((func, args, kwargs))
3433+
3434+
background_tasks = BackgroundTasksContainer()
3435+
3436+
# Run streaming pipeline
3437+
async for event in medical_pipeline_api_stream(user_id, user_message, background_tasks):
3438+
# Parse SSE format to extract JSON
3439+
if event.startswith("data: "):
3440+
event_data = event[6:].strip() # Remove "data: " prefix
3441+
3442+
if event_data == "[DONE]":
3443+
await websocket.send_json({"type": "done"})
3444+
break
3445+
3446+
try:
3447+
# Parse JSON from SSE format
3448+
json_data = json.loads(event_data)
3449+
# Send as WebSocket JSON message
3450+
await websocket.send_json(json_data)
3451+
except json.JSONDecodeError:
3452+
continue
3453+
3454+
# Execute background tasks manually (similar to streamlit_standalone)
3455+
if background_tasks.tasks:
3456+
print("[WEBSOCKET] Executing background tasks...")
3457+
for task_func, task_args, task_kwargs in background_tasks.tasks:
3458+
try:
3459+
if task_kwargs:
3460+
await task_func(*task_args, **task_kwargs)
3461+
else:
3462+
await task_func(*task_args)
3463+
except Exception as e:
3464+
print(f"[WEBSOCKET] Error executing background task: {e}")
3465+
3466+
print(f"[WEBSOCKET] Stream completed, closing connection")
3467+
3468+
except WebSocketDisconnect:
3469+
print(f"[WEBSOCKET] Client disconnected")
3470+
except Exception as e:
3471+
print(f"[WEBSOCKET] Error: {e}")
3472+
import traceback
3473+
traceback.print_exc()
3474+
try:
3475+
await websocket.send_json({"type": "error", "message": str(e)})
3476+
except:
3477+
pass
3478+
finally:
3479+
try:
3480+
await websocket.close()
3481+
except:
3482+
pass
3483+
33553484
if __name__ == "__main__":
33563485
import uvicorn
33573486
uvicorn.run(app, host="0.0.0.0", port=8000)
0 Bytes
Binary file not shown.

chat_history.db

4 KB
Binary file not shown.

0 commit comments

Comments
 (0)