Spaces:
Sleeping
Sleeping
Download server.py from veltrixcode/businesslawrag: direct link, hf CLI and curl.
- Browser
- Download file 10.2 kB
-
https://huggingface.co/spaces/veltrixcode/businesslawrag/resolve/main/server.py
- Command line
-
hf download hf://spaces/veltrixcode/businesslawrag/server.py
-
curl -L -o server.py https://huggingface.co/spaces/veltrixcode/businesslawrag/resolve/main/server.py
10.2 kB
| 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 | |
| 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)) | |
| def list_sessions_endpoint(username: Optional[str] = None): | |
| sessions = db.list_sessions(username=username, limit=50) | |
| return {"sessions": sessions} | |
| 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 | |
| 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} | |
| 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} | |
| 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} | |
| 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" | |
| 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)) | |
| 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") | |
| def serve_index(): | |
| return FileResponse("web/dist/index.html") | |
| else: | |
| app.mount("/static", StaticFiles(directory="frontend"), name="static") | |
| 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) | |