Update endpoints.py
Browse files- endpoints.py +35 -15
endpoints.py
CHANGED
|
@@ -22,7 +22,7 @@ class ChatRequest(BaseModel):
|
|
| 22 |
format: Optional[str] = "clean"
|
| 23 |
temperature: Optional[float] = 0.7
|
| 24 |
max_new_tokens: Optional[int] = 512
|
| 25 |
-
patient_id: Optional[str] = None
|
| 26 |
|
| 27 |
class VoiceOutputRequest(BaseModel):
|
| 28 |
text: str
|
|
@@ -35,7 +35,7 @@ class RiskLevel(BaseModel):
|
|
| 35 |
score: float
|
| 36 |
factors: Optional[List[str]] = None
|
| 37 |
|
| 38 |
-
def create_router(agent, logger, patients_collection, analysis_collection, users_collection):
|
| 39 |
router = APIRouter()
|
| 40 |
|
| 41 |
@router.get("/status")
|
|
@@ -110,10 +110,10 @@ def create_router(agent, logger, patients_collection, analysis_collection, users
|
|
| 110 |
cleaned_text = clean_text_response(text)
|
| 111 |
full_response = ""
|
| 112 |
|
| 113 |
-
# Store chat session in
|
| 114 |
chat_entry = {
|
| 115 |
"user_id": current_user["email"],
|
| 116 |
-
"patient_id": request.patient_id,
|
| 117 |
"message": request.message,
|
| 118 |
"response": cleaned_text,
|
| 119 |
"chat_type": "chat",
|
|
@@ -121,8 +121,15 @@ def create_router(agent, logger, patients_collection, analysis_collection, users
|
|
| 121 |
"temperature": request.temperature,
|
| 122 |
"max_new_tokens": request.max_new_tokens
|
| 123 |
}
|
| 124 |
-
|
| 125 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 126 |
|
| 127 |
for chunk in cleaned_text.split():
|
| 128 |
full_response += chunk + " "
|
|
@@ -130,10 +137,15 @@ def create_router(agent, logger, patients_collection, analysis_collection, users
|
|
| 130 |
await asyncio.sleep(0.05)
|
| 131 |
|
| 132 |
# Update chat entry with full response
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 137 |
|
| 138 |
except Exception as e:
|
| 139 |
logger.error(f"Streaming error: {e}")
|
|
@@ -147,11 +159,12 @@ def create_router(agent, logger, patients_collection, analysis_collection, users
|
|
| 147 |
):
|
| 148 |
logger.info(f"Fetching chats for {current_user['email']}")
|
| 149 |
try:
|
| 150 |
-
chats = await
|
|
|
|
| 151 |
return [
|
| 152 |
{
|
| 153 |
"id": str(chat["_id"]),
|
| 154 |
-
"title": chat.get("message", "Untitled Chat")[:30],
|
| 155 |
"timestamp": chat["timestamp"].isoformat(),
|
| 156 |
"message": chat["message"],
|
| 157 |
"response": chat["response"]
|
|
@@ -229,7 +242,7 @@ def create_router(agent, logger, patients_collection, analysis_collection, users
|
|
| 229 |
|
| 230 |
audio_data = text_to_speech(chat_response, language.split('-')[0])
|
| 231 |
|
| 232 |
-
# Store voice chat in
|
| 233 |
chat_entry = {
|
| 234 |
"user_id": current_user["email"],
|
| 235 |
"patient_id": None,
|
|
@@ -240,8 +253,14 @@ def create_router(agent, logger, patients_collection, analysis_collection, users
|
|
| 240 |
"temperature": temperature,
|
| 241 |
"max_new_tokens": max_new_tokens
|
| 242 |
}
|
| 243 |
-
|
| 244 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 245 |
|
| 246 |
return StreamingResponse(
|
| 247 |
io.BytesIO(audio_data),
|
|
@@ -344,6 +363,7 @@ def create_router(agent, logger, patients_collection, analysis_collection, users
|
|
| 344 |
|
| 345 |
# Delete all analyses and chats associated with this patient
|
| 346 |
await analysis_collection.delete_many({"patient_id": patient_id})
|
|
|
|
| 347 |
logger.info(f"Deleted analyses and chats for patient {patient_id}")
|
| 348 |
|
| 349 |
# Delete the patient
|
|
|
|
| 22 |
format: Optional[str] = "clean"
|
| 23 |
temperature: Optional[float] = 0.7
|
| 24 |
max_new_tokens: Optional[int] = 512
|
| 25 |
+
patient_id: Optional[str] = None
|
| 26 |
|
| 27 |
class VoiceOutputRequest(BaseModel):
|
| 28 |
text: str
|
|
|
|
| 35 |
score: float
|
| 36 |
factors: Optional[List[str]] = None
|
| 37 |
|
| 38 |
+
def create_router(agent, logger, patients_collection, analysis_collection, users_collection, chats_collection):
|
| 39 |
router = APIRouter()
|
| 40 |
|
| 41 |
@router.get("/status")
|
|
|
|
| 110 |
cleaned_text = clean_text_response(text)
|
| 111 |
full_response = ""
|
| 112 |
|
| 113 |
+
# Store chat session in the chats_collection
|
| 114 |
chat_entry = {
|
| 115 |
"user_id": current_user["email"],
|
| 116 |
+
"patient_id": request.patient_id,
|
| 117 |
"message": request.message,
|
| 118 |
"response": cleaned_text,
|
| 119 |
"chat_type": "chat",
|
|
|
|
| 121 |
"temperature": request.temperature,
|
| 122 |
"max_new_tokens": request.max_new_tokens
|
| 123 |
}
|
| 124 |
+
logger.info(f"Attempting to insert chat entry into chats_collection: {chat_entry}")
|
| 125 |
+
try:
|
| 126 |
+
result = await chats_collection.insert_one(chat_entry)
|
| 127 |
+
chat_entry["_id"] = str(result.inserted_id)
|
| 128 |
+
logger.info(f"Successfully inserted chat entry with ID: {chat_entry['_id']}")
|
| 129 |
+
except Exception as db_error:
|
| 130 |
+
logger.error(f"Failed to insert chat entry into chats_collection: {str(db_error)}")
|
| 131 |
+
yield f"⚠️ Error: Failed to store chat in database: {str(db_error)}"
|
| 132 |
+
return
|
| 133 |
|
| 134 |
for chunk in cleaned_text.split():
|
| 135 |
full_response += chunk + " "
|
|
|
|
| 137 |
await asyncio.sleep(0.05)
|
| 138 |
|
| 139 |
# Update chat entry with full response
|
| 140 |
+
try:
|
| 141 |
+
update_result = await chats_collection.update_one(
|
| 142 |
+
{"_id": result.inserted_id},
|
| 143 |
+
{"$set": {"response": full_response.strip()}}
|
| 144 |
+
)
|
| 145 |
+
logger.info(f"Updated chat entry {chat_entry['_id']}: matched {update_result.matched_count}, modified {update_result.modified_count}")
|
| 146 |
+
except Exception as update_error:
|
| 147 |
+
logger.error(f"Failed to update chat entry {chat_entry['_id']}: {str(update_error)}")
|
| 148 |
+
yield f"⚠️ Warning: Chat streamed successfully, but failed to update in database: {str(update_error)}"
|
| 149 |
|
| 150 |
except Exception as e:
|
| 151 |
logger.error(f"Streaming error: {e}")
|
|
|
|
| 159 |
):
|
| 160 |
logger.info(f"Fetching chats for {current_user['email']}")
|
| 161 |
try:
|
| 162 |
+
chats = await chats_collection.find({"user_id": current_user["email"], "chat_type": "chat"}).sort("timestamp", -1).to_list(length=100)
|
| 163 |
+
logger.info(f"Retrieved {len(chats)} chats for {current_user['email']}")
|
| 164 |
return [
|
| 165 |
{
|
| 166 |
"id": str(chat["_id"]),
|
| 167 |
+
"title": chat.get("message", "Untitled Chat")[:30],
|
| 168 |
"timestamp": chat["timestamp"].isoformat(),
|
| 169 |
"message": chat["message"],
|
| 170 |
"response": chat["response"]
|
|
|
|
| 242 |
|
| 243 |
audio_data = text_to_speech(chat_response, language.split('-')[0])
|
| 244 |
|
| 245 |
+
# Store voice chat in the chats_collection
|
| 246 |
chat_entry = {
|
| 247 |
"user_id": current_user["email"],
|
| 248 |
"patient_id": None,
|
|
|
|
| 253 |
"temperature": temperature,
|
| 254 |
"max_new_tokens": max_new_tokens
|
| 255 |
}
|
| 256 |
+
logger.info(f"Attempting to insert voice chat entry into chats_collection: {chat_entry}")
|
| 257 |
+
try:
|
| 258 |
+
result = await chats_collection.insert_one(chat_entry)
|
| 259 |
+
chat_entry["_id"] = str(result.inserted_id)
|
| 260 |
+
logger.info(f"Successfully inserted voice chat entry with ID: {chat_entry['_id']}")
|
| 261 |
+
except Exception as db_error:
|
| 262 |
+
logger.error(f"Failed to insert voice chat entry into chats_collection: {str(db_error)}")
|
| 263 |
+
raise HTTPException(status_code=500, detail=f"Failed to store voice chat: {str(db_error)}")
|
| 264 |
|
| 265 |
return StreamingResponse(
|
| 266 |
io.BytesIO(audio_data),
|
|
|
|
| 363 |
|
| 364 |
# Delete all analyses and chats associated with this patient
|
| 365 |
await analysis_collection.delete_many({"patient_id": patient_id})
|
| 366 |
+
await chats_collection.delete_many({"patient_id": patient_id})
|
| 367 |
logger.info(f"Deleted analyses and chats for patient {patient_id}")
|
| 368 |
|
| 369 |
# Delete the patient
|