File size: 10,202 Bytes
c49440d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55320cc
 
 
 
 
13de702
55320cc
 
 
 
 
 
 
 
c49440d
 
 
 
 
 
 
 
 
 
55320cc
 
 
 
 
13de702
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55320cc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c49440d
3950291
 
 
 
 
 
 
89096eb
 
 
 
 
 
 
 
 
3950291
c49440d
 
 
 
13de702
 
3950291
c49440d
 
13de702
c49440d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13de702
 
55320cc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c49440d
55320cc
 
c49440d
 
 
 
 
 
55320cc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c49440d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
from typing import Optional, List, Dict, Any
from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from fastapi.responses import FileResponse
from pydantic import BaseModel
from dotenv import load_dotenv

from src.retriever import HybridLegalRetriever
from src.rag_engine import LegalRAGEngine, CLOUDFLARE_MODELS
from src.downloader import ICAI_MANIFEST

load_dotenv()

app = FastAPI(title="ICAI Legal RAG Core", version="2.1.0")

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# Singleton retriever and engine
print("Initializing persistent RAG retriever and engine...")
retriever = HybridLegalRetriever(persist_dir="data/index")
engine = LegalRAGEngine(retriever)

import src.db as db

class UserAuthRequest(BaseModel):
    username: str
    name: Optional[str] = None
    mode: Optional[str] = "create"  # "create" | "login"

class CreateSessionRequest(BaseModel):
    session_id: Optional[str] = None
    username: Optional[str] = None
    title: Optional[str] = "New Chat"
    model: Optional[str] = None
    chapter_filter: Optional[str] = "All"

class ChatMessage(BaseModel):
    role: str
    content: str

class QueryRequest(BaseModel):
    query: str
    history: Optional[List[ChatMessage]] = []
    model: Optional[str] = None
    chapter_filter: Optional[str] = "All"
    top_k: Optional[int] = 5
    session_id: Optional[str] = None
    username: Optional[str] = None

@app.post("/api/auth")
def auth_endpoint(req: UserAuthRequest):
    uname = req.username.strip()
    if not uname:
        raise HTTPException(status_code=400, detail="Username cannot be empty.")
    
    # Mode 1: Login / Sign In (Existing user)
    if req.mode == "login":
        user = db.get_user(uname)
        if not user:
            raise HTTPException(status_code=404, detail=f"User '@{uname}' not found. Please create a profile.")
        return user

    # Mode 2: Create / Register (Unique check)
    try:
        user = db.create_user(uname, req.name.strip() if req.name else None)
        return user
    except ValueError as e:
        raise HTTPException(status_code=409, detail=str(e))
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@app.get("/api/sessions")
def list_sessions_endpoint(username: Optional[str] = None):
    sessions = db.list_sessions(username=username, limit=50)
    return {"sessions": sessions}

@app.get("/api/sessions/{session_id}")
def get_session_endpoint(session_id: str):
    session = db.get_session(session_id)
    if not session:
        raise HTTPException(status_code=404, detail="Session not found")
    return session

@app.post("/api/sessions")
def create_session_endpoint(req: CreateSessionRequest):
    sid = db.create_session(
        session_id=req.session_id,
        username=req.username,
        title=req.title or "New Chat",
        model=req.model,
        chapter_filter=req.chapter_filter or "All"
    )
    return {"session_id": sid}

@app.delete("/api/sessions/{session_id}")
def delete_session_endpoint(session_id: str):
    ok = db.delete_session(session_id)
    if not ok:
        raise HTTPException(status_code=404, detail="Session not found or could not be deleted")
    return {"deleted": True}

@app.post("/api/sessions/{session_id}/compact")
def compact_session_endpoint(session_id: str):
    ok = db.compact_session_messages(session_id, keep_last=2)
    if not ok:
        raise HTTPException(status_code=500, detail="Could not compact session")
    session = db.get_session(session_id)
    return {"compacted": True, "session": session}



@app.get("/api/info")
def get_info():
    chapters = ["All"] + sorted(list(set(item["chapter"] for item in ICAI_MANIFEST)))
    groq_keys = engine.get_groq_keys()
    default_m = os.getenv("CLOUDFLARE_MODEL")
    if not default_m or default_m == "@cf/deepseek-ai/deepseek-r1-distill-qwen-32b":
        default_m = "groq:qwen/qwen3.8-27b"
    return {
        "models": CLOUDFLARE_MODELS,
        "default_model": default_m,
        "chapters": chapters,
        "total_chunks": len(retriever.indexed_chunks),
        "groq_keys_count": len(groq_keys)
    }

from fastapi.responses import FileResponse, StreamingResponse, Response
import requests

class TTSRequest(BaseModel):
    text: str
    speaker: Optional[str] = "luna"

@app.post("/api/tts")
def tts_endpoint(req: TTSRequest):
    if not req.text.strip():
        raise HTTPException(status_code=400, detail="Text cannot be empty")
        
    cf_token = os.getenv("CLOUDFLARE_API_TOKEN")
    cf_acc_id = os.getenv("CLOUDFLARE_ACCOUNT_ID")
    
    url = f"https://api.cloudflare.com/client/v4/accounts/{cf_acc_id}/ai/run/@cf/deepgram/aura-2-en"
    headers = {
        "Authorization": f"Bearer {cf_token}",
        "Content-Type": "application/json"
    }
    
    # Strip excessive markdown formatting/links for clean audio
    cleaned_text = req.text.replace("#", "").replace("*", "").replace("`", "")[:2000]
    
    payload = {
        "text": cleaned_text,
        "speaker": req.speaker or "luna"
    }
    
    try:
        resp = requests.post(url, headers=headers, json=payload, timeout=30)
        if resp.status_code != 200:
            raise HTTPException(status_code=resp.status_code, detail=f"TTS API Error: {resp.text}")
        return Response(content=resp.content, media_type="audio/mpeg")
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@app.post("/api/chat")
def chat_endpoint(req: QueryRequest):
    if not req.query.strip():
        raise HTTPException(status_code=400, detail="Query cannot be empty")
    if not req.username or not req.username.strip():
        raise HTTPException(status_code=401, detail="Profile creation is compulsory. Please provide your username.")

    session_id = req.session_id
    if not session_id:
        session_id = db.create_session(
            username=req.username,
            title=req.query[:60].strip(),
            model=req.model,
            chapter_filter=req.chapter_filter
        )
    else:
        db.create_session(
            session_id=session_id,
            username=req.username,
            title=req.query[:60].strip(),
            model=req.model,
            chapter_filter=req.chapter_filter
        )
        db.update_session_title_if_default(session_id, req.query[:60].strip())

    # Save user message to database
    db.save_message(session_id=session_id, role="user", content=req.query)

    history_dicts = [{"role": m.role, "content": m.content} for m in req.history] if req.history else []

    raw_generator = engine.stream_answer_query(
        query=req.query,
        history=history_dicts,
        top_k=req.top_k or 5,
        chapter_filter=req.chapter_filter if req.chapter_filter != "All" else None,
        model_name=req.model
    )

    def event_stream_with_persistence():
        import json
        accumulated_answer = ""
        accumulated_thinking = ""
        findings_data = None
        citations_data = None
        usage_data = None

        # Emit session_id event first so client knows which session is active
        yield f"event: session\ndata: {json.dumps({'session_id': session_id})}\n\n"

        for chunk in raw_generator:
            yield chunk
            # Parse chunk to collect for DB saving
            lines = chunk.strip().split("\n")
            event_type = ""
            data_val = ""
            for line in lines:
                if line.startsWith if hasattr(line, "startsWith") else line.startswith("event: "):
                    event_type = line[7:].strip()
                elif line.startswith("data: "):
                    data_val = line[6:].strip()
            
            if event_type == "token" and data_val:
                try:
                    obj = json.loads(data_val)
                    accumulated_answer += obj.get("text", "")
                except Exception:
                    pass
            elif event_type == "thinking" and data_val:
                try:
                    obj = json.loads(data_val)
                    accumulated_thinking += obj.get("text", "")
                except Exception:
                    pass
            elif event_type == "findings" and data_val:
                try:
                    findings_data = json.loads(data_val)
                except Exception:
                    pass
            elif event_type == "citations" and data_val:
                try:
                    citations_data = json.loads(data_val)
                except Exception:
                    pass
            elif event_type == "usage" and data_val:
                try:
                    usage_data = json.loads(data_val)
                except Exception:
                    pass

        # Save assistant message to DB after stream finishes
        if accumulated_answer or accumulated_thinking:
            try:
                db.save_message(
                    session_id=session_id,
                    role="assistant",
                    content=accumulated_answer,
                    thinking=accumulated_thinking if accumulated_thinking else None,
                    findings=findings_data,
                    citations=citations_data,
                    usage=usage_data
                )
            except Exception as e:
                print(f"Error saving assistant message to DB: {e}")

    return StreamingResponse(event_stream_with_persistence(), media_type="text/event-stream")

# Mount official @assistant-ui/react production bundle
if os.path.exists("web/dist"):
    app.mount("/assets", StaticFiles(directory="web/dist/assets"), name="assets")
    @app.get("/")
    def serve_index():
        return FileResponse("web/dist/index.html")
else:
    app.mount("/static", StaticFiles(directory="frontend"), name="static")
    @app.get("/")
    def serve_index():
        return FileResponse("frontend/index.html")

if __name__ == "__main__":
    import uvicorn
    port = int(os.getenv("PORT", 7860))
    uvicorn.run(app, host="0.0.0.0", port=port)