Skip to content
Veror245Public

About

Adaptive GraphRAG Legal Reasoning Engine

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

⚖️ LexGraph – Adaptive GraphRAG Legal Reasoning Engine

Python 3.10+ FastAPI Neo4j Streamlit

LexGraph is a hybrid legal reasoning system that combines semantic retrieval (vector search) with graph‑based relational retrieval to improve legal query understanding and contextual reasoning.

Unlike traditional RAG systems that rely entirely on vector similarity, LexGraph uses a confidence‑aware adaptive pipeline that dynamically escalates to graph traversal when semantic confidence is insufficient. It is built specifically for legal domains where:

  • clauses reference other clauses,
  • exceptions override rules,
  • precedents influence interpretation,
  • relationships between entities matter as much as the text itself.

✨ Key Features

  • Adaptive Retrieval Routing — High‑confidence semantic results go straight to the LLM; low‑confidence triggers a Neo4j graph expansion.
  • Hybrid Candidate Retrieval — BM25 keyword search + Chroma vector store, then a cross‑encoder reranker selects the best chunks.
  • Legal Knowledge Graph — Ingested PDFs become a rich graph with entities (Law, Clause, Case, Obligation, Penalty, Exception, LegalConcept) and relationships (REFERENCES, EXCEPTION_TO, APPLIES_TO, REQUIRES, OVERRIDES).
  • Explainable Retrieval — Every step is logged: extracted entities, traversed relationships, confidence scores, and source chunks.
  • Interactive Graph Visualisation — Real‑time Pyvis/Vis.js graph showing the legal relationships found.
  • Streaming Frontend — Streamlit UI with live progress, token‑by‑token answer streaming, and final chunk/confidence display.
  • Parallel Entity Processing — Multi‑hop graph expansion runs in parallel with a cap of 5 entities to control latency.
  • Robust Fallbacks — If LLM entity extraction fails, the system matches semantic chunks to entities via text‑hash lookup as a fallback.

🧰 Tech Stack

Component Technology
Backend Framework FastAPI
Frontend Streamlit + custom HTML/JS (SSE, Marked.js)
Vector Store Chroma
Keyword Search BM25 (rank‑bm25)
Graph Database Neo4j 5.x
Embeddings Ollama / local embedding model
Reranker Cross‑encoder (Qwen3‑Reranker or similar)
Answer Generation Gemma (via Ollama) or configurable LLM
PDF Ingestion PyMuPDF + Chonkie
Graph Visualization Pyvis / Vis.js

🚀 Installation & Setup (uv only)

This project uses uv to manage a disposable virtual environment and developer tasks.

  1. Clone the repository
git clone https://github.com/Veror245/LexGraph
cd LexGraph
  1. Provision the environment with uv
# Install dependencies into a disposable venv as defined by pyproject.toml
uv sync

# Optional: enter a shell inside the project environment
uv shell
  1. Create a .env file at the project root (example values)
OLLAMA_API_KEY=ollama
PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True
LEXGRAPH_GRAPH_DIR=LexGraph/graph_dir
  1. Start Neo4j (Docker example)
docker run -d --name lexgraph-neo4j \
	-p 7474:7474 -p 7687:7687 \
	-e NEO4J_AUTH=neo4j/12345678 \
	neo4j:5
  1. Prepare local stores
  • Ensure the chroma_db/ directory exists.
  • Put any prebuilt indexes or graph exports under chroma_db/ or graph_dir/.
  1. Ingest documents and build indices (run inside uv environment)
# Run ingestion inside uv's environment
uv run python -m backend.services.ingest

# Build and save BM25 index
uv run python -c "from backend.services.retrieve import RetrieveService; RetrieveService().build_and_save_bm25()"
  1. Start services (API + frontend)
# Run the backend
uv run fastapi run backend/api/main.py

# Run the frontend
uv run streamlit run frontend/app.py

Open the dashboard at http://localhost:8501 and the API at http://localhost:8000.


API

  • GET /answer/stream?query=... — server‑sent events stream returning ordered retrieval steps, token stream for the generated answer, and a final metadata event with confidence and source chunks.

Example (streaming):

curl "http://localhost:8000/answer/stream?query=What%20are%20obligations%20under%20Section%2032%3F"

Screenshots

Architecture Diagram

Architecture Diagram

Dashboard

Dashboard

Answer Example

Answer Example

Retrieval Sequence

Retrieval Sequence

Interactive Graph Visualization

Graph Visualization


Project Layout

  • backend/ — FastAPI application, retrieval and ingestion services, Neo4j integration
  • frontend/ — Streamlit UI and static visualization assets

Troubleshooting

  • If uv sync fails: verify Python 3.10+ is on your PATH and that uv is installed.
  • Neo4j connection errors: confirm Docker container is running and NEO4J_AUTH matches .env.
  • Reranker OOM errors: lower LEXGRAPH_RERANKER_BATCH_SIZE or set LEXGRAPH_RERANKER_DEVICE=cpu.

About

Adaptive GraphRAG Legal Reasoning Engine

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages