Repository navigation
Expand file tree
/
Copy pathmain.py
More file actions
475 lines (394 loc) · 16.1 KB
/
Copy pathmain.py
File metadata and controls
475 lines (394 loc) · 16.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
"""
ClinIQ FastAPI Backend
Replaces the Streamlit app.py with a proper REST API that serves the
HTML/CSS/JS frontend from the public/ directory. Handles auth, conversations,
and CRAG pipeline invocation.
"""
from __future__ import annotations
import os
os.environ["TRANSFORMERS_VERBOSITY"] = "error"
os.environ["TRANSFORMERS_NO_ADVISORY_WARNINGS"] = "1"
import json
import secrets
from typing import Any, Dict, List, Optional
from fastapi import Depends, FastAPI, HTTPException, Request, Response, status
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from pydantic import BaseModel
from langchain_core.documents import Document
import jwt
import urllib.request
from jwt.algorithms import RSAAlgorithm
from src.auth import authenticate_user, register_user
from src.config import CHROMA_PERSIST_DIR, HISTORY_WINDOW_TURNS
from src.corrective_rag import run_corrective_rag
from src.db import (
add_assistant_message,
add_user_message,
create_conversation,
delete_conversation,
get_messages,
init_db,
list_conversations,
rename_conversation,
touch_conversation,
create_user,
get_user_by_username,
)
from src.embeddings import get_embedding_model
from src.llm import get_llm
from src.vectorstore import load_vector_store
# ---------------------------------------------------------------------------
# App init
# ---------------------------------------------------------------------------
app = FastAPI(title="ClinIQ CRAG API", version="2.0.0")
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# ---------------------------------------------------------------------------
# In-memory session store (simple cookie-based sessions)
# ---------------------------------------------------------------------------
_sessions: Dict[str, Dict[str, Any]] = {} # session_token -> {user_id, username}
def _create_session(user_id: int, username: str) -> str:
token = secrets.token_hex(32)
_sessions[token] = {"user_id": user_id, "username": username}
return token
def require_session(request: Request) -> Dict[str, Any]:
token = request.cookies.get("medsage_session")
if not token or token not in _sessions:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Not authenticated")
return _sessions[token]
# ---------------------------------------------------------------------------
# Lazy-loaded ML resources (loaded once on first ask, not on boot)
# ---------------------------------------------------------------------------
_vectordb = None
_llm = None
def _get_pipeline():
global _vectordb, _llm
if _vectordb is None:
try:
embedding_model = get_embedding_model()
_vectordb = load_vector_store(
embedding_model=embedding_model,
persist_directory=CHROMA_PERSIST_DIR,
)
except FileNotFoundError:
raise RuntimeError(
"The vector store hasn't been built yet. "
"Run: python -m src.build_index\n"
"This takes 5-20 minutes on first run (one-time only)."
)
if _llm is None:
_llm = get_llm()
return _vectordb, _llm
# ---------------------------------------------------------------------------
# Startup
# ---------------------------------------------------------------------------
@app.on_event("startup")
async def startup():
init_db()
# ---------------------------------------------------------------------------
# Pydantic schemas
# ---------------------------------------------------------------------------
class AuthRequest(BaseModel):
username: str
password: str
class ClerkLoginRequest(BaseModel):
token: str
username: Optional[str] = None
class AskRequest(BaseModel):
question: str
class RenameRequest(BaseModel):
title: str
# ---------------------------------------------------------------------------
# Clerk JWKS & verification helper
# ---------------------------------------------------------------------------
CLERK_JWKS_URL = os.environ.get(
"CLERK_JWKS_URL",
"https://wondrous-mole-4807.clerk.accounts.dev/.well-known/jwks.json"
)
_jwks_cache = None
def get_jwks():
global _jwks_cache
if _jwks_cache is None:
try:
req = urllib.request.Request(
CLERK_JWKS_URL,
headers={"User-Agent": "Mozilla/5.0"}
)
with urllib.request.urlopen(req) as response:
_jwks_cache = json.loads(response.read().decode())
except Exception as e:
print("Error loading Clerk JWKS:", e)
return _jwks_cache
def verify_clerk_token(token: str) -> dict:
jwks = get_jwks()
if not jwks:
raise HTTPException(status_code=500, detail="Failed to load Clerk identity keys")
try:
unverified_header = jwt.get_unverified_header(token)
except Exception as e:
raise HTTPException(status_code=400, detail=f"Invalid token format: {e}")
kid = unverified_header.get("kid")
rsa_key = {}
for key in jwks.get("keys", []):
if key.get("kid") == kid:
rsa_key = {
"kty": key.get("kty"),
"kid": key.get("kid"),
"use": key.get("use"),
"n": key.get("n"),
"e": key.get("e")
}
break
if not rsa_key:
raise HTTPException(status_code=401, detail="Invalid token signing key")
try:
public_key = RSAAlgorithm.from_jwk(rsa_key)
payload = jwt.decode(
token,
public_key,
algorithms=["RS256"],
options={"verify_aud": False}
)
return payload
except jwt.ExpiredSignatureError:
raise HTTPException(status_code=401, detail="Clerk session has expired")
except Exception as e:
raise HTTPException(status_code=401, detail=f"Token verification failed: {e}")
# ---------------------------------------------------------------------------
# Auth endpoints
# ---------------------------------------------------------------------------
@app.post("/api/auth/clerk-login")
async def api_clerk_login(body: ClerkLoginRequest, response: Response):
payload = verify_clerk_token(body.token)
clerk_id = payload.get("sub")
if not clerk_id:
raise HTTPException(status_code=400, detail="Missing subject claim in token")
user = get_user_by_username(clerk_id)
if user is None:
user = create_user(username=clerk_id, password_hash="")
display_name = body.username or clerk_id
token = _create_session(user.id, display_name)
response.set_cookie(
"medsage_session", token, httponly=True, samesite="lax", max_age=60 * 60 * 24 * 7
)
return {"username": display_name, "user_id": user.id}
@app.post("/api/auth/register")
async def api_register(body: AuthRequest, response: Response):
user, error = register_user(body.username, body.password)
if error:
raise HTTPException(status_code=400, detail=error)
token = _create_session(user.id, user.username)
response.set_cookie(
"medsage_session", token, httponly=True, samesite="lax", max_age=60 * 60 * 24 * 7
)
return {"username": user.username, "user_id": user.id}
@app.post("/api/auth/login")
async def api_login(body: AuthRequest, response: Response):
user, error = authenticate_user(body.username, body.password)
if error:
raise HTTPException(status_code=401, detail=error)
token = _create_session(user.id, user.username)
response.set_cookie(
"medsage_session", token, httponly=True, samesite="lax", max_age=60 * 60 * 24 * 7
)
return {"username": user.username, "user_id": user.id}
@app.post("/api/auth/logout")
async def api_logout(request: Request, response: Response):
token = request.cookies.get("medsage_session")
if token and token in _sessions:
del _sessions[token]
response.delete_cookie("medsage_session")
return {"ok": True}
@app.get("/api/auth/me")
async def api_me(session: Dict = Depends(require_session)):
return {"username": session["username"], "user_id": session["user_id"]}
# ---------------------------------------------------------------------------
# Conversation endpoints
# ---------------------------------------------------------------------------
@app.get("/api/conversations")
async def api_list_conversations(session: Dict = Depends(require_session)):
convos = list_conversations(session["user_id"])
return [
{
"id": c.id,
"title": c.title,
"created_at": c.created_at.isoformat(),
"updated_at": c.updated_at.isoformat(),
}
for c in convos
]
@app.post("/api/conversations", status_code=201)
async def api_create_conversation(session: Dict = Depends(require_session)):
convo = create_conversation(session["user_id"])
return {"id": convo.id, "title": convo.title}
@app.delete("/api/conversations/{conversation_id}")
async def api_delete_conversation(
conversation_id: int, session: Dict = Depends(require_session)
):
convos = list_conversations(session["user_id"])
if not any(c.id == conversation_id for c in convos):
raise HTTPException(status_code=404, detail="Conversation not found")
delete_conversation(conversation_id)
return {"ok": True}
@app.patch("/api/conversations/{conversation_id}")
async def api_rename_conversation(
conversation_id: int, body: RenameRequest, session: Dict = Depends(require_session)
):
convos = list_conversations(session["user_id"])
if not any(c.id == conversation_id for c in convos):
raise HTTPException(status_code=404, detail="Conversation not found")
rename_conversation(conversation_id, body.title)
return {"ok": True}
@app.get("/api/conversations/{conversation_id}/messages")
async def api_get_messages(
conversation_id: int, session: Dict = Depends(require_session)
):
convos = list_conversations(session["user_id"])
if not any(c.id == conversation_id for c in convos):
raise HTTPException(status_code=404, detail="Conversation not found")
messages = get_messages(conversation_id)
result = []
for m in messages:
entry = dict(m)
if "local_sources" in entry:
entry["local_sources"] = [
{"content": doc.page_content, "metadata": doc.metadata}
for doc in entry["local_sources"]
]
result.append(entry)
return result
@app.post("/api/conversations/{conversation_id}/ask")
async def api_ask(
conversation_id: int, body: AskRequest, session: Dict = Depends(require_session)
):
convos = list_conversations(session["user_id"])
if not any(c.id == conversation_id for c in convos):
raise HTTPException(status_code=404, detail="Conversation not found")
question = body.question.strip()
if not question:
raise HTTPException(status_code=400, detail="Question cannot be empty")
# Build recent chat history for condensation
messages = get_messages(conversation_id)
chat_history = [
{"role": m["role"], "content": m["content"]}
for m in messages[-(HISTORY_WINDOW_TURNS * 2):]
]
# Persist user message
add_user_message(conversation_id, question)
# Auto-title conversation on first message
if len(messages) == 0:
title = question[:80] + ("..." if len(question) > 80 else "")
rename_conversation(conversation_id, title)
# Run CRAG pipeline
try:
vectordb, llm = _get_pipeline()
result = run_corrective_rag(
vectordb=vectordb,
llm=llm,
question=question,
chat_history=chat_history,
)
except RuntimeError as exc:
# Setup error (e.g. vector store not built yet) — surface clearly
raise HTTPException(status_code=503, detail=str(exc))
except Exception as exc:
raise HTTPException(status_code=500, detail=f"Pipeline error: {exc}")
# Persist assistant message
add_assistant_message(
conversation_id=conversation_id,
summary=result["summary"],
key_points=result.get("key_points", []),
caveat=result.get("caveat"),
source_type=result.get("source_type"),
local_sources=result.get("local_sources", []),
web_sources=result.get("web_sources", []),
)
touch_conversation(conversation_id)
local_sources_out = [
{"content": doc.page_content, "metadata": doc.metadata}
for doc in result.get("local_sources", [])
]
return {
"summary": result["summary"],
"key_points": result.get("key_points", []),
"caveat": result.get("caveat"),
"source_type": result.get("source_type"),
"local_sources": local_sources_out,
"web_sources": result.get("web_sources", []),
"standalone_question": result.get("standalone_question"),
}
from sse_starlette.sse import EventSourceResponse
from src.streaming_pipeline import run_corrective_rag_stream
@app.get("/api/conversations/{conversation_id}/ask/stream")
async def api_ask_stream(
conversation_id: int, question: str, session: Dict = Depends(require_session)
):
convos = list_conversations(session["user_id"])
if not any(c.id == conversation_id for c in convos):
raise HTTPException(status_code=404, detail="Conversation not found")
question = question.strip()
if not question:
raise HTTPException(status_code=400, detail="Question cannot be empty")
messages = get_messages(conversation_id)
chat_history = [
{"role": m["role"], "content": m["content"]}
for m in messages[-(HISTORY_WINDOW_TURNS * 2):]
]
# Persist user message
add_user_message(conversation_id, question)
# Auto-title conversation on first message
if len(messages) == 0:
title = question[:80] + ("..." if len(question) > 80 else "")
rename_conversation(conversation_id, title)
async def event_generator():
try:
vectordb, llm = _get_pipeline()
except RuntimeError as exc:
yield {"event": "error", "data": str(exc)}
return
except Exception as exc:
yield {"event": "error", "data": f"Pipeline error: {exc}"}
return
# Generator runs stream and yields chunks
pipeline_generator = run_corrective_rag_stream(
vectordb=vectordb,
llm=llm,
question=question,
chat_history=chat_history,
)
for event_raw in pipeline_generator:
event_data = json.loads(event_raw)
evt_type = event_data.get("type")
evt_payload = event_data.get("data")
# Yield individual events
yield {"event": evt_type, "data": json.dumps(evt_payload)}
# When execution finishes, persist the assistant response to the DB
if evt_type == "result":
# Convert list of dicts to langchain Document-like objects for DB serialization
loc_docs = [
Document(page_content=d["content"], metadata=d.get("metadata", {}))
for d in evt_payload.get("local_sources", [])
]
add_assistant_message(
conversation_id=conversation_id,
summary=evt_payload["summary"],
key_points=evt_payload.get("key_points", []),
caveat=evt_payload.get("caveat"),
source_type=evt_payload.get("source_type"),
local_sources=loc_docs,
web_sources=evt_payload.get("web_sources", []),
)
touch_conversation(conversation_id)
return EventSourceResponse(event_generator())
# ---------------------------------------------------------------------------
# Static frontend (API routes must be declared BEFORE this mount)
# ---------------------------------------------------------------------------
PUBLIC_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "public")
if os.path.isdir(PUBLIC_DIR):
app.mount("/", StaticFiles(directory=PUBLIC_DIR, html=True), name="frontend")