project-8f76630a

byNiru Singh

You are acting as a senior Python backend engineer building a portfolio-grade Retrieval-Augmented-Generation (RAG) API called LegalMind. Project Summary LegalMind lets authenticated users upload legal documents (contracts, court filings, agreements) and ask natural language questions about them. Every answer must include source citations pointing to the exact page/clause the information came from. This is API only — no frontend/UI . Tech Stack - FastAPI (async, Pydantic v2 models) - ChromaDB (vector store, one physical collection per user) - OpenAI API (embeddings + chat completion for answer synthesis) - SQLAlchemy (async) for relational metadata (users, documents, query logs) - Document parsing: PyMuPDF for PDFs, python-docx for Word files - Text chunking: LangChain text splitters or tiktoken-based custom chunker, chunk size ~500-800 tokens with overlap, must preserve page/clause metadata Multi-Tenancy & Security Requirements - Every request is authenticated via JWT; extract `user_id` from the token. - Each user gets their own physical ChromaDB collection (e.g. `collection_{user_id}`) — never a shared collection with a metadata filter. This is a hard isolation boundary, not a soft one. - All document metadata rows in the relational DB are scoped by `user_id` with row-level checks on every query — never trust a client-supplied user_id in the payload; always derive it from the verified JWT. - Write at least one test that proves user A cannot retrieve user B's data even with a crafted request. Core API Endpoints to Design 1. `POST /auth/token` — issue JWT (stub or real auth, your choice, but must embed `user_id` and `role` claims) 2. `POST /documents/upload` — accept PDF/DOCX, extract text with page numbers, chunk it, embed it, upsert into the user's Chroma collection, store document metadata (filename, upload date, page count) in the relational DB 3. `GET /documents` — list the current user's uploaded documents 4. `DELETE /documents/{document_id}` — remove a document and its vectors 5. `POST /query` — accept a natural-language question + optional `document_id` filter, retrieve top-k relevant chunks from the user's collection, call the LLM to synthesize an answer, and return the answer with a `citations` array (document name, page number, and the source text snippet for each cited chunk) RAG Pipeline Details - On upload: extract text page-by-page (never lose the page boundary), chunk with metadata `{document_id, page_number, chunk_index}`, embed with OpenAI `text-embedding-3-small` (or similar), upsert to Chroma with that metadata attached to every vector. - On query: embed the question, run similarity search (top_k configurable, default 5) against the user's collection only, pass retrieved chunks + question into a structured prompt that forces the LLM to cite which chunk each claim came from, and parse the response into `{answer: str, citations: [{document, page, snippet}]}`. - Include a basic guard against hallucinated citations: validate that every cited page/document actually exists in the retrieved chunk set before returning the response. Deliverables - Clean FastAPI project structure (routers/services/schemas/db separated) - `.env.example` with all required config keys - Dockerfile + docker-compose (API + Chroma persistent volume) - README with setup, architecture diagram description, and example curl requests for each endpoint - Basic pytest suite covering auth, upload, query, and the tenant-isolation test above Constraints - Keep this POC-scoped: no Kubernetes, no complex orchestration frameworks (no LangGraph/Autogen needed here — this is intentionally simpler than a multi-agent system). - Favor clarity and correctness over cleverness; this is a portfolio piece meant to demonstrate solid RAG + multi-tenant API design to interviewers. Start by proposing the folder structure and the SQLAlchemy models, then wait for confirmation before writing endpoint code.

LandingLoginAuth
Landing

Comments (0)

No comments yet. Be the first!

System Requirements

System Requirement Document
Page 1 of 6

System Requirements Document for project-8f76630a

1. Introduction

This document outlines the system requirements for project-8f76630a, a Retrieval-Augmented-Generation (RAG) API named LegalMind. The API allows authenticated users to upload legal documents and query them using natural language, with responses that include source citations.

2. System Overview

LegalMind is designed to handle legal document uploads and queries, providing users with answers that are directly linked to the source material. The system is API-only, with no frontend/UI, and is built using FastAPI. It ensures multi-tenancy and security by isolating user data and verifying access through JWT authentication.

Tech Stack

  • Backend: FastAPI (async, Pydantic v2 models)
  • Vector Store: ChromaDB (one physical collection per user)
  • AI Integration: OpenAI API (embeddings + chat completion)
  • Database: SQLAlchemy (async) for relational metadata
  • Document Parsing: PyMuPDF for PDFs, python-docx for Word files
  • Text Chunking: LangChain text splitters or tiktoken-based custom chunker
Page 2 of 6

Multi-Tenancy & Security

  • JWT authentication with user_id extraction
  • User-specific ChromaDB collections
  • Row-level security checks in the relational database

Core API Endpoints

  1. POST /auth/token
  2. POST /documents/upload
  3. GET /documents
  4. DELETE /documents/{document_id}
  5. POST /query
Page 3 of 6

3. Functional Requirements as Story Points

  • As a Developer, I should be able to bootstrap a FastAPI project with a structured folder layout, logging infrastructure, and environment handling.

    • Deliverables: FastAPI project structure, logging setup, .env handling.
    • Acceptance Criteria: Project initializes without errors, logging captures startup events, environment variables load correctly.
  • As a Developer, I should be able to create a core directory for security, logging, and configuration details.

    • Deliverables: Core directory with security, logging, and config files.
    • Acceptance Criteria: Core services initialize correctly, logs capture security events.
  • As a Developer, I should be able to create a separate repositories folder for database operations.

    • Deliverables: Repositories folder with database operation functions.
    • Acceptance Criteria: Database operations execute correctly, logs capture database queries.
  • As a Developer, I should be able to create a separate folder for models, distinct from the database.

    • Deliverables: Models folder with data models.
    • Acceptance Criteria: Models are correctly defined and used in the application.
  • As a Developer, I should be able to implement JWT authentication for user requests.

    • Deliverables: JWT authentication mechanism.
    • Acceptance Criteria: Authentication works as expected, logs capture authentication attempts.
  • As a Developer, I should be able to implement document upload functionality with text extraction and embedding.

    • Deliverables: Document upload endpoint, text extraction, and embedding logic.
    • Acceptance Criteria: Documents upload successfully, text is extracted and embedded, logs capture upload events.
  • As a Developer, I should be able to implement a query endpoint that retrieves and synthesizes answers with citations.

    • Deliverables: Query endpoint with answer synthesis.
    • Acceptance Criteria: Queries return correct answers with citations, logs capture query processing.
Page 4 of 6

4. User Personas

  • Developer: Responsible for implementing and maintaining the API.
  • Authenticated User: Uploads documents and queries them for information.

5. Core User Flows

  • Developer sets up the project -> Initializes FastAPI -> Configures logging and environment -> Implements core functionalities.
  • Authenticated User uploads a document -> System extracts and embeds text -> User queries the document -> System retrieves and synthesizes an answer with citations.

6. Visuals Colors and Theme

[Default — not specified by user]

  • primary: #1E3A8A (Deep Blue)
  • primary_light: #3B82F6 (Light Blue)
  • secondary: #F59E0B (Amber)
  • accent: #EF4444 (Red)
  • highlight: #FBBF24 (Yellow)
  • bg: #F3F4F6 (Light Gray)
  • surface: rgba(255, 255, 255, 0.8)
  • text: #111827 (Dark Gray)
  • text_muted: #6B7280 (Muted Gray)
  • border: rgba(209, 213, 219, 0.2)
Page 5 of 6

7. Signature Design Concept

[Default — not specified by user]

Interactive Legal Document Flow: The landing page features an interactive flow of legal documents. As users scroll, documents appear to be uploaded into a virtual filing cabinet. Each document flips open, revealing highlighted clauses and sections. Users can click on sections to see detailed information and citations. This concept uses motion/react for smooth animations and transitions.

Landing Hero Motion Brief: The hero animation shows a stack of documents being scanned and transformed into digital data streams. As the streams flow, they form a cohesive answer to a legal query, showcasing the transformation from physical to digital. The animation loops every 10 seconds, with interactive elements allowing users to pause and explore specific document sections.

8. Interaction Model & Motion Direction

  • Intended Interaction Model: Animated
  • Description: Moderate scroll-triggered reveals, hover transitions, and spring physics on interactive elements. Suitable for showcasing the API's capabilities in transforming legal documents into actionable insights.

9. Non-Functional Requirements

  • Performance: The API should handle up to 100 concurrent requests with minimal latency.
  • Security: Ensure JWT authentication and data isolation for each user.
  • Scalability: Design for easy scaling of document processing and query handling.
Page 6 of 6

10. Tech Stack

  • Frontend: None (API-only)
  • Backend: FastAPI
  • Database: SQLAlchemy with ChromaDB
  • AI Models: OpenAI API for embeddings and chat completion

11. Assumptions and Constraints

  • The system is API-only with no frontend.
  • Each user has isolated data storage.
  • The project is a proof-of-concept and should not include complex orchestration frameworks.

12. Glossary

  • RAG: Retrieval-Augmented-Generation
  • JWT: JSON Web Token
  • API: Application Programming Interface
  • LLM: Large Language Model
Landing design preview
Landing: View Info
Login: Sign In
Documents: Upload Document
Documents: View List
Query: Ask Question
Query: View Answer
Query: Review Citations
Documents: Delete Document
Landing design preview
Landing: View Info
Login: Sign In
Documents: Upload Document
Documents: View List
Query: Ask Question
Query: View Answer
Query: Review Citations
Documents: Delete Document