Skip to content

Latest commit

Β 

History

5 Commits

Folders and files

NameName
Last commit message
Last commit date
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

βš–οΈ WhatLawSays

Source-Grounded Multi-Agent Legal Reasoning & System Architecture Engine

Python FastAPI Streamlit LangGraph Qdrant Groq Redis PostgreSQL Docker

A production-grade, source-grounded legal reasoning platform engineered to map citizen scenarios to Indian Criminal Statutes (BNS 2023, BNSS 2023, BSS 2023) and the Constitution of India while eliminating factual contamination and hallucinated charges.


🌟 Architectural Highlights

Unlike basic RAG chatbots that perform naive similarity searches and generate unchecked responses, WhatLawSays implements a strict, multi-agent deductive reasoning pipeline:

  • 🧠 Immutable Fact Contracts (established_facts vs user_allegations vs unknown_facts):
    • Strictly separates objective, undisputed facts from subjective user allegations and indeterminate unknowns.
    • Enforces the core legal reasoning rule: $\text{UNKNOWN} \neq \text{FALSE}$ and $\text{UNKNOWN} \neq \text{TRUE}$.
  • 🎯 Fact-Clean Legal Query Generator:
    • Generates retrieval queries strictly using explicit scenario terms without injecting premature section numbers or assumptions.
  • πŸ” Expanded Hybrid Retrieval (Dense + Sparse BM25):
    • Executes parallel Dense Cosine (bge-small-en-v1.5) and Sparse BM25 (Qdrant/bm25) vector search over Qdrant, merged via Reciprocal Rank Fusion (RRF).
    • Unfiltered retrieval recall across full statutory corpus prevents premature category classification failures.
  • βš–οΈ Element-Based Verification & Statutory Exception Evaluation:
    • Verification Agent acts as a two-part logic judge: audits factual alignment first, then audits statutory accuracy.
    • Evaluates section-specific statutory exceptions (e.g. Grave & Sudden Provocation) and general legal defences (e.g. Right of Private Defence BNS Sec 38–44).
    • Automatically exonerates accused parties if statutory elements are CONTRADICTED_BY_FACT (e.g. valid invitation negates criminal trespass).
  • πŸ“‹ Procedural Classification & Evidentiary Mapping (BNSS & BSS):
    • Automatically classifies offenses by Cognizability, Bailability, and Punishment Severity (CAPITAL_LIFE, SERIOUS, MINOR).
    • Maps procedural provisions under BNSS 2023 (e.g. Sec 173 e-FIR, Sec 185 search rules) and evidentiary standards under BSS 2023 (Sec 63 electronic records certificate).
  • 🚨 Actionable Citizen Guidance & Statutory Reporting Duties:
    • Generates prioritized immediate action steps (emergency helpline 112, filing e-FIR, medical audit, digital evidence preservation).
    • Highlights statutory duties required of citizens under Indian criminal procedure (e.g. BNSS Section 33 obligation to report certain offenses).
  • πŸ›‘οΈ System UNDETERMINED State:
    • Returns a grounded legal explanation when facts are insufficient to establish an offense instead of making false claims.

πŸ“‚ Project Structure

β”œβ”€β”€ frontend/
β”‚   β”œβ”€β”€ app.py                   # Streamlit Interactive Web Application
β”‚   β”œβ”€β”€ components.py            # Streamlit UI Components, Styling & Cards
β”‚   └── sample_scenarios.py      # Predefined Legal Test Scenarios
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ main.py                  # FastAPI Application Gateway & Middleware
β”‚   β”œβ”€β”€ config.py                # Pydantic Settings & Environment Configurations
β”‚   β”œβ”€β”€ agents/
β”‚   β”‚   β”œβ”€β”€ graph.py             # LangGraph Multi-Agent Workflow Definition
β”‚   β”‚   β”œβ”€β”€ state.py             # TypedDict GraphState Engine Representation
β”‚   β”‚   └── nodes/
β”‚   β”‚       β”œβ”€β”€ extractor.py     # Agent 1: Established & Allegation Fact Extractor
β”‚   β”‚       β”œβ”€β”€ query_builder.py # Agent 2: Fact-Clean Query Generator
β”‚   β”‚       β”œβ”€β”€ retriever.py     # Hybrid Qdrant Vector Retriever Node
β”‚   β”‚       β”œβ”€β”€ reranker_node.py # Step 3: Legal Reranker Node
β”‚   β”‚       β”œβ”€β”€ analyst.py       # Agent 3: Deductive Analyst, Exceptions & Action Mapper
β”‚   β”‚       β”œβ”€β”€ verifier.py      # Agent 4: Claim-Evidence & Exception Verification Judge
β”‚   β”‚       └── compiler.py      # Step 5: Response Compiler & Calibrated Confidence
β”‚   β”œβ”€β”€ core/
β”‚   β”‚   β”œβ”€β”€ vector_store.py      # Qdrant Client Hybrid Dense + BM25 Integration
β”‚   β”‚   β”œβ”€β”€ reranker.py          # Reranking Engine & Fallback Manager
β”‚   β”‚   β”œβ”€β”€ task_queue.py        # Redis Async Task Queue Producer/Consumer
β”‚   β”‚   β”œβ”€β”€ database.py          # SQLAlchemy PostgreSQL Async Models & Operations
β”‚   β”‚   └── logger.py            # Colorized Pipeline Stage Logging Engine
β”‚   └── schemas/
β”‚       β”œβ”€β”€ legal.py             # Pydantic Schemas for Requests, Offenses, Actions & Duties
β”‚       └── corpus.py            # Legal Section Data Schemas
β”œβ”€β”€ scripts/
β”‚   β”œβ”€β”€ ingest_legal_corpus.py   # Seed Data Ingestion Script (Batch & Async Setup)
β”‚   β”œβ”€β”€ test_pipeline.py         # End-to-End Pipeline Integration Test
β”‚   β”œβ”€β”€ test_hybrid_search.py   # Hybrid Vector Search Verification Script
β”‚   └── test_president_invitation.py # Test Script for Undetermined Scenario
β”œβ”€β”€ tests/
β”‚   └── test_agents.py           # Pytest Suite for Agents & Workflows
β”œβ”€β”€ docker-compose.yml           # Multi-Container Deployment (FastAPI, Redis, Qdrant)
β”œβ”€β”€ pyproject.toml               # Dependencies & UV Project Configuration
└── README.md                    # System Documentation

⚑ Quick Start & Installation

Prerequisites

  • Python 3.13+
  • Docker & Docker Compose (for Qdrant & Redis)
  • uv package manager (pip install uv)

1. Clone Repository & Install Dependencies

git clone https://github.com/your-username/whatLawSays.git
cd whatLawSays
uv sync

2. Environment Configuration

Create a .env file in the root directory:

PROJECT_NAME="WhatLawSays Backend"
API_V1_STR="/api/v1"
GROQ_API_KEY="gsk_your_groq_api_key_here"
GROQ_MODEL="openai/gpt-oss-120b"
QDRANT_URL="http://localhost:6333"
REDIS_URL="redis://localhost:6379/0"
DATABASE_URL="postgresql+asyncpg://postgres:postgres@localhost:5432/whatlawsays"

3. Launch Services with Docker Compose

docker-compose up -d

4. Seed Legal Corpus into Qdrant

uv run python -m scripts.ingest_legal_corpus

5. Run FastAPI Application Server

uv run uvicorn src.main:app --reload --port 8000

Interactive API Documentation will be available at: http://localhost:8000/docs

6. Run Interactive Streamlit Frontend UI

uv run streamlit run frontend/app.py

Interactive Web Workbench will open at: http://localhost:8501


πŸ§ͺ Testing & Verification

Run the automated agent pytest suite:

uv run pytest tests/

Run the hybrid search verification script:

uv run python -m scripts.test_hybrid_search

Run the President's Residence Invitation integration test:

uv run python -m scripts.test_president_invitation

πŸ“‘ API Usage Example

Request

POST /api/v1/analyze

{
  "scenario_text": "A person was going to enter the President's residence with an invitation to attend a party.",
  "jurisdiction": "India"
}

Response (UNDETERMINED State Example)

{
  "status": "UNDETERMINED",
  "scenario_domain": "POTENTIAL_CRIMINAL",
  "offense_status": "UNDETERMINED",
  "confidence_score": 0.35,
  "reason": "The supplied facts do not establish the elements of an offence.",
  "extracted_facts": {
    "explicit_facts": [
      "A person was going to enter the President's residence",
      "The person had an invitation to attend a party"
    ],
    "established_facts": [
      "The person possessed an invitation to attend a party at the President's residence"
    ],
    "user_allegations": [],
    "unknown_facts": [
      "Whether the person actually entered the residence",
      "Whether the invitation was valid or authorized"
    ],
    "actor": "person",
    "action": "enter",
    "scenario_domain": "POTENTIAL_CRIMINAL",
    "offense_status": "UNDETERMINED"
  },
  "identified_offenses": [],
  "applied_defences": [],
  "procedural_provisions": [
    "BNSS 2023 Section 173 - Procedure for recording information regarding cognizable offences"
  ],
  "immediate_action_steps": [
    {
      "step_number": 1,
      "title": "Verify Authorization",
      "action_details": "Confirm invitation authenticity with the event organizers or venue security prior to entry.",
      "statutory_duty_reference": null,
      "urgency": "MEDIUM"
    }
  ],
  "citizen_duties": [],
  "clarification_questions": [
    "Whether the person actually entered the residence",
    "Whether the invitation was valid or authorized"
  ],
  "disclaimer": "This platform provides legal information based on BNS/BNSS/BSS, not formal legal advice."
}

πŸ“œ License

Distributed under the MIT License. See LICENSE for more information.

About

Source-grounded multi-agent legal reasoning engine for Indian Criminal Statutes (BNS, BNSS, BSS 2023) using LangGraph, Qdrant Hybrid RAG & FastAPI.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages