How We Built a Contract Review Agent (Without a PhD in AI)
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:
- Sign in with an API key (the Next.js UI calls FastAPI over HTTP).
- Upload a PDF.
- Watch milestone steps: reading the document, identifying the contract, extracting clauses, checking precedents, scoring risk.
- Review findings beside the PDF, then Approve, Reject, or request Re-analysis.
- 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.
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.
Three design choices worth stealing:
| Choice | Why it matters for beginners |
|---|---|
Typed state (ReviewState) | Every node reads and writes the same shape—debuggable, testable, no hidden globals. |
| Map-reduce extraction | Long 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:
- Deterministic: ingest PDF, plan batches, fuzzy quote location, YAML policy rules, persist rows.
- LLM: classify subtype, extract clauses per batch, merge key terms, score nuanced risk, write the executive summary.
- Retrieval: embed clause text, search pgvector for precedent snippets (after
make seed-precedentsin local dev).
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:
- Ingest documents into chunks + embeddings.
- Graph with classify → extract → enrich (retrieval / rules) → score.
- Interrupt for the role that must sign off.
- 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
| Topic | Doc |
|---|---|
| Full generated graph | docs/graph.md |
| Graph module detail | docs/modules/graph.md |
| LLM provider setup | docs/llm-providers.md |
| Local runbook | docs/runbook.md |
Reminder: outputs are for review workflows only. Always involve qualified counsel for legal decisions.
All posts