import os import glob import json import shutil import tempfile import time import uuid from typing import List, Optional from pathlib import Path from fastapi import FastAPI, HTTPException, UploadFile, File, Form from fastapi.middleware.cors import CORSMiddleware from pydantic import BaseModel, Field from dotenv import load_dotenv # langchain / loaders / chroma / embeddings / llm from langchain_community.document_loaders import PyMuPDFLoader from langchain_text_splitters import CharacterTextSplitter from langchain_huggingface import HuggingFaceEmbeddings from langchain_chroma import Chroma from langchain_groq import ChatGroq from langchain.chains import RetrievalQA from langchain.prompts import PromptTemplate from langchain.schema import Document from langchain.schema.retriever import BaseRetriever load_dotenv() os.environ["TOKENIZERS_PARALLELISM"] = "false" # ------------------------------------------------------------------ # Configuration # ------------------------------------------------------------------ BASE_DIR = Path.cwd() CHATS_DIR = BASE_DIR / "chats" GLOBAL_DATA_DIR = BASE_DIR / "data" # keep global PDFs here GLOBAL_CHROMA_DIR = BASE_DIR / "chroma_global" # global vectorstore CHATS_INDEX = CHATS_DIR / "index.json" # Ensure folders exist CHATS_DIR.mkdir(parents=True, exist_ok=True) GLOBAL_DATA_DIR.mkdir(parents=True, exist_ok=True) GLOBAL_CHROMA_DIR.mkdir(parents=True, exist_ok=True) # Embedding & chunking config CHUNK_SIZE = 2000 CHUNK_OVERLAP = 500 # LLM config from env GROQ_API_KEY = os.getenv("GROQ_API_KEY") # ------------------------------------------------------------------ # FastAPI # ------------------------------------------------------------------ app = FastAPI(title="Justitia - Multi-Chat RAG Prototype", version="0.9") app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"], ) # ------------------------------------------------------------------ # Utilities: filesystem-safe JSON write (atomic) # ------------------------------------------------------------------ def atomic_write_json(path: Path, data): tmp_fd, tmp_path = tempfile.mkstemp(dir=str(path.parent)) try: with os.fdopen(tmp_fd, "w", encoding="utf-8") as f: json.dump(data, f, ensure_ascii=False, indent=2) os.replace(tmp_path, str(path)) except Exception: try: os.remove(tmp_path) except Exception: pass raise def read_json(path): if not os.path.exists(path): return [] if os.path.getsize(path) == 0: with open(path, "w") as f: json.dump([], f) return [] try: with open(path, "r") as f: return json.load(f) except json.JSONDecodeError: with open(path, "w") as f: json.dump([], f) return [] # ------------------------------------------------------------------ # Chat index management # ------------------------------------------------------------------ def ensure_index(): if not CHATS_INDEX.exists(): atomic_write_json(CHATS_INDEX, []) def add_chat_to_index(chat_id: str, metadata: dict): ensure_index() idx = read_json(CHATS_INDEX) or [] for entry in idx: if entry.get("chat_id") == chat_id: entry.update(metadata) atomic_write_json(CHATS_INDEX, idx) return idx.append({"chat_id": chat_id, **metadata}) atomic_write_json(CHATS_INDEX, idx) def list_chats(): ensure_index() return read_json(CHATS_INDEX) or [] # ------------------------------------------------------------------ # Document ingestion helpers # ------------------------------------------------------------------ def load_pdfs_from_folder(folder: Path): docs = [] for file_path in sorted(folder.glob("*.pdf")): loader = PyMuPDFLoader(str(file_path)) docs.extend(loader.load()) return docs def split_documents(documents): splitter = CharacterTextSplitter(chunk_size=CHUNK_SIZE, chunk_overlap=CHUNK_OVERLAP) return splitter.split_documents(documents) # ------------------------------------------------------------------ # Global vectorstore: load or create # ------------------------------------------------------------------ EMBEDDING = HuggingFaceEmbeddings() def build_global_vectorstore_if_needed(): if any(GLOBAL_CHROMA_DIR.iterdir()): return print("Building global vectorstore from data/*.pdf ...") docs = load_pdfs_from_folder(GLOBAL_DATA_DIR) if not docs: print("No global PDFs found in data/. Skipping global indexing.") return chunks = split_documents(docs) Chroma.from_documents( documents=chunks, embedding=EMBEDDING, persist_directory=str(GLOBAL_CHROMA_DIR) ) print("Global vectorstore created.") def get_global_retriever(k: int = 5): vs = Chroma(persist_directory=str(GLOBAL_CHROMA_DIR), embedding_function=EMBEDDING) return vs.as_retriever(search_kwargs={"k": k}) # ------------------------------------------------------------------ # Per-chat vectorstore management # ------------------------------------------------------------------ def chat_paths(chat_id: str): base = CHATS_DIR / f"chat_{chat_id}" return { "base": base, "files": base / "files", "vectorstore": base / "vectorstore", "messages": base / "messages.json", "summary": base / "summary.txt", } def ensure_chat_dirs(chat_id: str): p = chat_paths(chat_id) p["base"].mkdir(parents=True, exist_ok=True) p["files"].mkdir(parents=True, exist_ok=True) p["vectorstore"].mkdir(parents=True, exist_ok=True) if not p["messages"].exists(): atomic_write_json(p["messages"], []) # ensure summary exists if not p["summary"].exists(): p["summary"].write_text("") def build_chat_vectorstore(chat_id: str) -> bool: p = chat_paths(chat_id) files_dir = p["files"] if not files_dir.exists(): return False pdfs = list(files_dir.glob("*.pdf")) if not pdfs: return False docs = [] for pdf in pdfs: loader = PyMuPDFLoader(str(pdf)) docs.extend(loader.load()) if not docs: return False chunks = split_documents(docs) Chroma.from_documents( documents=chunks, embedding = EMBEDDING, persist_directory=str(p["vectorstore"]) ) return True def get_chat_retriever(chat_id: str, k: int = 5): p = chat_paths(chat_id) if not p["vectorstore"].exists(): built = build_chat_vectorstore(chat_id) if not built: return None vs = Chroma(persist_directory=str(p["vectorstore"]), embedding_function=EMBEDDING) return vs.as_retriever(search_kwargs={"k": k}) # ------------------------------------------------------------------ # LLMs & Chains # ------------------------------------------------------------------ if not GROQ_API_KEY: print("WARNING: GROQ_API_KEY not found in environment. LLM calls will fail until you set it.") QA_LLM = ChatGroq(model="llama-3.1-8b-instant", temperature=0.2, groq_api_key=GROQ_API_KEY) REFINE_LLM = ChatGroq(model="llama-3.3-70b-versatile", temperature=0, groq_api_key=GROQ_API_KEY) QA_PROMPT = PromptTemplate.from_template(""" You are Justitia, an expert assistant specializing in Indian law. Use the following legal documents to answer the question accurately: Context: {context} Question: {question} Instructions: - Answer in simple, clear English - Be precise and cite relevant sections/articles if mentioned in context - If the context doesn't contain enough information, say "I don't have sufficient information" - Stay neutral and factual Answer: """) REFINE_PROMPT = PromptTemplate.from_template(""" You are an expert legal assistant specializing in Indian law. Refine the following answer to make it: - Accurate, concise, and well-structured - Written in simple English - Neutral and factually grounded Raw Answer: {raw_answer} Refined Answer: """) def load_summary(chat_id: str) -> str: p = chat_paths(chat_id) if p["summary"].exists(): try: return p["summary"].read_text() except Exception: return "" return "" def save_summary(chat_id: str, summary: str): p = chat_paths(chat_id) try: p["summary"].write_text(summary) except Exception: # fallback to atomic write for safety tmp_fd, tmp_path = tempfile.mkstemp(dir=str(p["base"])) with os.fdopen(tmp_fd, "w", encoding="utf-8") as f: f.write(summary) os.replace(tmp_path, str(p["summary"])) def update_chat_summary(chat_id: str, new_user_msg: str, new_ai_msg: str): """ Compresses conversation into a short summary and saves it. Also prunes messages to keep only last few turns to limit prompt growth. """ p = chat_paths(chat_id) old_summary = load_summary(chat_id) prompt = f""" Summarize the following conversation so far into a short, concise, factual memory (1-3 sentences) that preserves important context and facts but removes any fluff. Previous summary: {old_summary} New interaction: USER: {new_user_msg} ASSISTANT: {new_ai_msg} Provide the updated summary only. """ try: resp = QA_LLM.invoke(prompt) new_summary = resp.content.strip() if hasattr(resp, "content") else str(resp).strip() if not new_summary: # keep old summary if model returned nothing new_summary = old_summary except Exception as e: # on failure, fallback to appending a tiny note new_summary = old_summary if new_user_msg: snippet = new_user_msg if len(new_user_msg) < 200 else new_user_msg[:197] + "..." new_summary = (old_summary + " " + snippet).strip() if old_summary else snippet save_summary(chat_id, new_summary) # prune messages to keep only the last few (so history doesn't grow unbounded) try: messages = read_json(p["messages"]) if p["messages"].exists() else [] # keep last 6 entries (3 turns) pruned = messages[-6:] atomic_write_json(p["messages"], pruned) except Exception: pass def invoke_qa_with_retriever(retriever, question: str, chat_id: Optional[str] = None, max_context_tokens: int = 2500): docs = retriever.get_relevant_documents(question) if retriever else [] context = "\n\n".join([d.page_content for d in docs]) # hard cap context to avoid huge dumps context = context[:4000] # Load compact summary if available (preferred over full history) summary_text = "" if chat_id: summary_text = load_summary(chat_id) hybrid_prompt = PromptTemplate.from_template(""" You are Justitia, an expert assistant specializing in Indian law. Conversation summary: {summary} Retrieved Legal Context: {context} Current Question: {question} Instructions: - Use the conversation summary to maintain continuity. - Use retrieved context only if relevant. - If the context is empty, answer using general knowledge. - Do not answer anything other than law, legal, policy, or government-related questions. - If user asks anything outside law, legal, policy, or government domains, respond with: "I am made only for legal use and government questions only." - Keep all answers simple, neutral, and factual. Answer: """) formatted_prompt = hybrid_prompt.format( summary=summary_text or "No prior summary available.", context=context or "No relevant documents found.", question=question ) # Emergency fallback trim to keep request small (character-based safety net) # Groq TPM errors come from token load; trimming characters helps avoid that. MAX_PROMPT_CHARS = 18000 if len(formatted_prompt) > MAX_PROMPT_CHARS: # keep the last part where the question and recent context live formatted_prompt = formatted_prompt[-MAX_PROMPT_CHARS:] llm_out = QA_LLM.invoke(formatted_prompt) return { "result": llm_out.content if hasattr(llm_out, "content") else str(llm_out), "source_documents": docs } def refine_text(raw_answer: str): out = REFINE_PROMPT | REFINE_LLM result = out.invoke({"raw_answer": raw_answer}) return result.content if hasattr(result, "content") else str(result) # ------------------------------------------------------------------ # API Models # ------------------------------------------------------------------ class QueryRequest(BaseModel): chat_id: Optional[str] = None question: str class CreateChatRequest(BaseModel): title: Optional[str] = None # user only provides title # ------------------------------------------------------------------ # API Endpoints # ------------------------------------------------------------------ @app.on_event("startup") def startup_tasks(): build_global_vectorstore_if_needed() ensure_index() @app.get("/") def root(): return {"message": "Justitia RAG multi-chat prototype", "status": "ok"} @app.get("/health") def health(): return {"status": "ok", "time": int(time.time())} @app.post("/create_chat") def create_chat(payload: CreateChatRequest): # Generate UUID automatically chat_id = str(uuid.uuid4()) ensure_chat_dirs(chat_id) meta = { "title": payload.title or f"Chat {chat_id}", "created_at": int(time.time()), "last_used": int(time.time()) } add_chat_to_index(chat_id, meta) return {"chat_id": chat_id, "meta": meta} @app.get("/list_chats") def api_list_chats(): return {"chats": list_chats()} @app.post("/upload/{chat_id}") async def upload_pdf(chat_id: str, file: UploadFile = File(...)): if not file.filename.lower().endswith(".pdf"): raise HTTPException(status_code=400, detail="Only PDF uploads allowed.") ensure_chat_dirs(chat_id) p = chat_paths(chat_id) save_path = p["files"] / file.filename with open(save_path, "wb") as f: shutil.copyfileobj(file.file, f) built = build_chat_vectorstore(chat_id) add_chat_to_index(chat_id, {"last_used": int(time.time())}) return {"uploaded": file.filename, "vectorstore_built": bool(built)} @app.get("/get_messages/{chat_id}") def get_messages(chat_id: str): p = chat_paths(chat_id) if not p["messages"].exists(): raise HTTPException(status_code=404, detail="Chat not found") return read_json(p["messages"]) @app.post("/append_message/{chat_id}") def append_message(chat_id: str, role: str = Form(...), text: str = Form(...)): ensure_chat_dirs(chat_id) p = chat_paths(chat_id) messages = read_json(p["messages"]) or [] entry = {"role": role, "text": text, "ts": int(time.time())} messages.append(entry) atomic_write_json(p["messages"], messages) add_chat_to_index(chat_id, {"last_used": int(time.time())}) return {"ok": True, "message": entry} class CombinedRetriever(BaseRetriever): global_retriever: Optional[BaseRetriever] = Field(default=None) chat_retriever: Optional[BaseRetriever] = Field(default=None) k: int = Field(default=5) def get_relevant_documents(self, query: str) -> List[Document]: docs = [] if self.chat_retriever: try: docs.extend(self.chat_retriever.get_relevant_documents(query)) except Exception as e: print(f"[WARN] Chat retriever failed: {e}") if self.global_retriever: try: docs.extend(self.global_retriever.get_relevant_documents(query)) except Exception as e: print(f"[WARN] Global retriever failed: {e}") return docs async def aget_relevant_documents(self, query: str) -> List[Document]: return self.get_relevant_documents(query) def load_chat_history(chat_id: str, max_messages: int = 5): """Load last N messages as a conversational context block (kept for compatibility).""" p = chat_paths(chat_id) messages = read_json(p["messages"]) if p["messages"].exists() else [] # Keep last N messages so history doesn't blow up prompt size messages = messages[-max_messages:] history_blocks = [] for msg in messages: role = msg.get("role", "") text = msg.get("text", "") # truncate long messages to avoid blowups if len(text) > 600: text = text[:600] + "...(truncated)" history_blocks.append(f"{role.upper()}: {text}") return "\n".join(history_blocks) @app.post("/query") def query_endpoint(req: QueryRequest): query = req.question.strip() if not query: raise HTTPException(status_code=400, detail="Empty query") chat_id = req.chat_id global_retriever = get_global_retriever(k=5) chat_retriever = get_chat_retriever(chat_id, k=5) if chat_id else None combined_retriever = CombinedRetriever( global_retriever=global_retriever, chat_retriever=chat_retriever ) qa_result = invoke_qa_with_retriever(combined_retriever, query, chat_id=chat_id) raw_answer = qa_result.get("result") if isinstance(qa_result, dict) else str(qa_result) refined_answer = refine_text(raw_answer) all_docs = combined_retriever.get_relevant_documents(query) sources = [] for doc in all_docs: meta = getattr(doc, "metadata", {}) src = meta.get("source", "Unknown") sources.append(src) sources = list(dict.fromkeys(sources)) if chat_id: append_message(chat_id, role="user", text=query) append_message(chat_id, role="assistant", text=refined_answer) # update compact summary and prune messages to keep history small try: update_chat_summary(chat_id, query, refined_answer) except Exception: # don't fail the endpoint if summary update fails pass add_chat_to_index(chat_id, {"last_used": int(time.time())}) return { "query": query, "used_rag": True, "raw_answer": raw_answer, "refined_answer": refined_answer, "sources": sources }