How We Built a Contract Review Agent (Without a PhD in AI)

6 min read
ai-agentslanggraphraghuman-in-the-loopfastapiopen-source

Reading time: about 4–5 minutes
Who this is for: developers curious about “AI agents” who have shipped a web app before but have not wired up LangChain, graphs, or vector search.

If you have ever pasted a 40-page PDF into a chat box and hoped for the best, you already know the problem: the model might sound confident, but it is hard to trust, hard to cite, and impossible to put through a real approval process. The contract-review-agent repository is our answer—a small product-shaped stack that turns a PDF into a structured risk report, compares clauses to precedent, and pauses for a human before anything is treated as final.

This is decision support, not legal advice. The architecture is the interesting part: you can copy the pattern for onboarding docs, policy checks, or any workflow where “read → reason → show your work → get sign-off” matters.


The idea in one sentence

An agent here is not a mystical autonomous being. It is a workflow: each step is a plain Python function, state is a typed dictionary, and the large language model (LLM) is called only where judgment is needed—classification, extraction, scoring, summarization.

Think of it like a factory line with checkpoints, not a single prompt.


What happens when someone uploads a contract

From the reviewer’s perspective:

  1. Sign in with an API key (the Next.js UI calls FastAPI over HTTP).
  2. Upload a PDF.
  3. Watch milestone steps: reading the document, identifying the contract, extracting clauses, checking precedents, scoring risk.
  4. Review findings beside the PDF, then Approve, Reject, or request Re-analysis.
  5. Open a summary export when the run finishes.

Under the hood, PDF parsing and chunking run before the main graph starts (so the graph works on chunks already in Postgres). The graph itself focuses on reasoning, retrieval, human gate, and persistence.

flowchart LR subgraph Browser UI[Next.js UI] end subgraph API HTTP[FastAPI] Ingest[Ingest PDF chunks] Runner[Product runner] end subgraph Brain Graph[LangGraph product graph] LLM[LiteLLM → Bedrock / OpenAI / etc.] RAG[(pgvector precedents)] end subgraph Human HITL[Approve / Reject / Re-analyse] end UI -->|X-API-Key| HTTP HTTP --> Ingest HTTP --> Runner Runner --> Graph Graph --> LLM Graph --> RAG Graph -.->|interrupt| HITL HITL -.->|resume| Graph

You do not need to memorize every box. The lesson is separable: UI talks HTTP, API owns persistence and scheduling, graph owns the reasoning pipeline, humans own the last mile.


The agent flow (the graph)

LangGraph compiles our steps into a directed graph. Nodes are functions; edges are “what happens next,” including branches for errors and document type.

Here is a simplified view of the product path (contracts). The full diagram is generated from code in docs/graph.md.

flowchart TD Start([Upload complete]) --> Load[Mark review running] Load --> Classify[Classify document] Classify -->|contract| Plan[Plan extraction batches] Plan --> Extract[Extract clauses in parallel] Extract --> Merge[Merge and dedupe clauses] Merge --> Retrieve[Retrieve similar precedents] Retrieve --> Score[Score risk rules + LLM] Score --> Gate{Risk gate} Gate -->|needs human| Review[Human review interrupt] Gate -->|low risk| Summary[Summarize] Review --> Decide[Apply decision] Decide -->|approve| Summary Decide -->|re-analyse| Score Decide -->|reject| Reject[Finalize rejected] Summary --> Save[Persist to Postgres] Reject --> Save Save --> End([Done])

Three design choices worth stealing:

ChoiceWhy it matters for beginners
Typed state (ReviewState)Every node reads and writes the same shape—debuggable, testable, no hidden globals.
Map-reduce extractionLong contracts are split into batches; multiple extract_clauses runs fan out, then merge_clauses combines.
Human-in-the-loop (interrupt)The graph stops until a person decides. Resume uses the same thread_id as the review id.

A little code: wiring the graph

Building the graph is mostly declarative—register nodes, wire edges, compile with a checkpointer so runs can survive restarts:

# src/cra/graph/builder.py (excerpt)
builder.add_edge("retrieve_precedent", "score_risk")
builder.add_conditional_edges(
    "risk_gate",
    needs_review,
    {"review": "human_review", "auto": "summarize"},
)
builder.add_edge("human_review", "apply_review")

Parallel extraction uses LangGraph’s Send API—one node returns many downstream jobs:

def fanout_extract(state: ReviewState) -> list[Send]:
    return [
        Send("extract_clauses", {"batch_index": index, "chunk_ids": batch, ...})
        for index, batch in enumerate(state.get("batches") or [])
    ]

That pattern is how you scale to 60-page NDAs without one giant prompt.


Where the “AI” actually shows up

Not every step calls a model. Rough division:

Models are routed through LiteLLM so you can point at Bedrock, OpenAI, Anthropic, or others via config—not a pile of provider-specific SDK calls in every node.

The human gate is deliberately tiny and explicit:

# src/cra/graph/hitl.py (excerpt)
async def human_review(state: ReviewState) -> dict[str, object]:
    payload = {
        "findings": [...],
        "allowed_decisions": ["approve", "approve_with_edits", "request_reanalysis", "reject"],
    }
    raw = interrupt(payload)
    return {"decision": ReviewDecision.model_validate(raw)}

interrupt is the LangGraph primitive that says: stop the run, surface this payload to the API/UI, wait. When the reviewer clicks Approve, the API resumes with Command(resume=...) on the same thread. No fake “the AI approved itself.”


Try it in one coffee break

You do not need cloud GPUs to explore the shape of the system:

git clone https://github.com/thisIsAditya/contract-review-agent.git
cd contract-review-agent
cp .env.example .env   # set API_KEY to something you will type in the UI
docker compose up -d --build

Open http://localhost:3000, sign in with API_KEY, upload a PDF. For offline graph behaviour without live providers, make demo and the default test suite use fake models and embedders.

Optional: make seed-precedents loads fixture precedent rows so “Checking precedents” returns real matches.


What you could build next with the same skeleton

Swap the domain, keep the spine:

  1. Ingest documents into chunks + embeddings.
  2. Graph with classify → extract → enrich (retrieval / rules) → score.
  3. Interrupt for the role that must sign off.
  4. Persist artifacts people can audit later.

Start with five nodes, not twenty. Add parallel extraction when prompts get too long. Add RAG when “what did we agree last time?” matters. Add policy YAML when legal or compliance wants transparent rules alongside model judgment.

The repo is meant to be read: docs/README.md is the map; docs/ai-assisted-development.md shows how we iterated with agents and tests.


Further reading in this repo

TopicDoc
Full generated graphdocs/graph.md
Graph module detaildocs/modules/graph.md
LLM provider setupdocs/llm-providers.md
Local runbookdocs/runbook.md

Reminder: outputs are for review workflows only. Always involve qualified counsel for legal decisions.

All posts