Browse by type
Tenant-aware, human-in-the-loop legal contract analysis on LangGraph. Saul ingests messy real-world contracts into canonical, versioned chunks, retrieves evidence under server-derived authorization, and produces grounded findings — every claim carried by a verified evidence handle, every terminal state typed, nothing answered from memory.
📚 Documentation: Mintlify site in apps/docs/ — cd apps/docs and run npx mintlify dev locally.
Legal work has a strange cruelty to it: the most expensive human judgment sits behind a wall of repetitive reading, clause sorting, calendar math, template comparison, and anxious second-guessing. The people who need clarity most are usually the least able to buy it continuously — founders signing vendor terms, families reading settlement papers, policyholders facing claim language, small businesses trying not to discover a liability clause after the damage is done.
Agent Saul exists to reduce that information asymmetry. Not by pretending to be a lawyer, and not by turning legal judgment into autocomplete, but by making the repetitive surface area small enough that humans spend their attention on the parts that actually require judgment.
The pain in India is specific: small startups rarely have strong legal teams on call; individuals are intimidated by fine print and legal notices; much of the work is high-volume, low-judgment grunt work; and most contract-AI products carry US/UK assumptions, not Indian statutes, procedures, and enforcement realities. The high-volume surface worth automating: clause tagging, risk flagging (one-sided indemnity, unlimited liability), deadline tracking, template comparison, stamp-duty and jurisdiction sanity checks, "is this clause enforceable in India?"
Time is a symptom. Risk and uncertainty are the disease. The same principle governs how we build this project: agents should remove avoidable strain and the quiet dread of "what if I chose wrong" — lifting invisible weight off people, not adding a new layer of it.
contract_index,
page_no, document_version, pipeline_version. Terminal states are truthful:
completed, completed_with_warnings, or failed — never a silent partial.allowed_doc_ids and contract_index scoping, with Graphiti as an optional
relationship backend and coverage signal.read_evidence_by_id re-authorizes on every call (run, thread, checkpoint,
document version). Identity and scope never come from the model.The static console in apps/console/ uses Bun 1.4.4. Install and verify it with the
checked-in lockfile before changing frontend dependencies:
cd apps/console
bun install --frozen-lockfile
bun check --threads 4
bun run lint
bun fmt --check
bun run build
The Bun version is pinned in apps/console/.bun-version and apps/console/package.json; CI uses
the same version and bun ci. Bun 1.4.4 provides the built-in TypeScript
checker and formatter. Its pinned CLI does not provide the newer native lint
command, so this project retains ESLint for linting. Python tooling continues
to use uv.
CI caches Bun's package cache against apps/console/bun.lock. For an offline or
prewarmed install, run bun pm fetch before bun ci; to move the exact cache
entries for this lockfile, use bun pm cache pack <archive> and
bun pm cache unpack <archive>.
Saul is a stateful, resumable, memory-aware reasoning pipeline: a distributed, resumable, schema-driven cognitive workflow engine with controlled reasoning surfaces, built on three layers:
The mental model underneath:
LegalAgentState and its projections).The deepest design constraint: if your system cannot deterministically replay a run, you do not control your agent. Hence the shape:
Plan -> deterministic execution -> validated output -> persisted state
Not:
LLM -> decide -> act -> hope it works
The orchestration maps one-to-one onto the requirements. The orchestrator plans, then
delegates to specialist sub-agents (risk, compliance, deep research) that loop over
their tool surfaces until the plan step is done; the orchestrator reviews specialist
output, handles failures, and replans when needed. Both plan approval and final report
review are LangGraph interrupts — humans sit inside the loop, not on top of it.
State lives in LegalAgentState; specialists read and write through controlled
surfaces, and every resume re-resolves server-derived authorization before any
evidence handle is honored.
Do not initialize models or compile agents inside graph nodes. That is the fast path to slow requests, memory churn, noisy traces, and production pain.
# Wrong: rebuilds the runtime on every call
def research_node(state):
model = init_chat_model("<provider:model>")
agent = create_agent(model, tools)
return agent.invoke(state)
# Right: compile once, execute many
research_agent = create_agent(
init_chat_model("<provider:model>"),
tools=[search_caselaw],
)
def research_node(state):
return research_agent.invoke(state)
Model initialization can spend 100–500 ms fetching config and metadata; agent construction adds tens of milliseconds more. Ten nodes across ten concurrent requests become hundreds of avoidable constructions per second — and traces stop being comparable because the runtime shape keeps being rebuilt.
The convention in this repo: models, tools, and graphs are compiled once at startup
(FastAPI lifespan), held on app.state, and passed into graph.add_node(...) as ready
callables. Checkpointers are wired per-workflow where isolation matters, dynamic model
selection goes through explicit lookup tables, and heavy resources are never built
inside node bodies. The graph behaves like infrastructure, not improvisation.
| Orchestration — LangGraph with HITL interrupts, server-owned authorization, TTL evidence handles, mandatory grounding. | Topology — Caddy → FastAPI → role-separated Celery pools → Timescale/Postgres, RabbitMQ, Redis, Neo4j, MongoDB, R2. |
| Query path — deterministic scoping → hybrid fusion → optional Graphiti enrichment → answers that disclose their evidence policy. | Memory — durable workflow state (checkpointer, handle store) vs advisory memory (Graphiti, cognee), surfaced through a coverage signal. |
| Documents system — bounded upload → canonical ingestion → versioned persistence → evaluation as a first-class subsystem. |
What is real today: the ingestion pipeline with truthful terminal states and bounded validation; the evidence-handle service; the Saul orchestration graph with HITL and a grounding gate; the evaluation corpus and its CI gates (64 release-tier cases; 41 await human SME adjudication — the corpus is designated candidate, not gold, until adjudication completes). What is pending: SME adjudication of judgment-dependent labels (typed relationship edges landed with the retired plan's Phase D — the archived plan carries the completion audit), retrieval unification (mount-retrieval-graph) and the portfolio tool layer (see PLAN-agent-tools.md).
Agent Saul also has a default-off AG-UI run API at
POST /api/v2/agent-saul/agui/runs, with owner-scoped session and transcript
reads at GET /api/v2/agent-saul/sessions and
GET /api/v2/agent-saul/sessions/{session_id}/transcript. The same-origin
/console client remains behind AGENT_CONSOLE_ENABLED. Locally, FastAPI can
serve apps/console/dist when the bundle is present; production Compose serves
the independently tagged console image behind Caddy. Its Agent Saul
RunProvider uses the AG-UI HttpAgent directly; no Copilot Runtime service
is deployed. Each human interrupt terminates one run, and the client resumes by posting a new
run for the same threadId. The console is served only when the corresponding
feature flag is on. Its SPA document uses a restrictive same-origin CSP and
revalidation; hashed assets are cached immutably. The production
bundle still needs its build-under-CSP acceptance. The GCP Cloud Run request
timeout is 2,100 seconds above the 1,800-second run budget. Other deployment
proxies must disable buffering and allow a read timeout longer than the run;
Uvicorn trusts forwarded scheme/client headers only from the configured
UVICORN_FORWARDED_ALLOW_IPS peers (loopback by default). The Cloud Run
Terraform service explicitly sets * because managed ingress is the only path
to its container. Caddy deployments must set the setting to the exact Caddy
peer address or a tightly scoped proxy subnet; never use * on a host or
container deployment. The existing WebSocket interface remains compatible and
is deprecated for new clients.
ToolRuntimeContext/AuthorizationContext
(user, tenant, role, allowed_doc_ids) is constructed from authenticated claims on
every request and WebSocket resume — client-supplied identity is never trusted.The evals/ subsystem is CI-gated, offline and provenance-first:
# validate a gold set (provenance, checksums, adjudication state)
uv run python -m app.ai.evaluation.validate evals/golden/legal_retrieval_v2.jsonl
# run the deterministic experiment harness (console script: legal-eval)
uv run python -m app.ai.evaluation.experiment evals/experiments/legal_retrieval_smoke.json
The v2 corpus (evals/golden/legal_retrieval_v2.jsonl, 105 cases) ships with a
per-artifact provenance manifest (source URLs, licences, SHA-256, permission and
redistribution status), dual blind annotations, and an
adjudication runbook. CI fails on unknown provenance,
missing checksums, unadjudicated release-quality cases, multi-contract cases without
contract_index, and raw binaries whose terms disallow redistribution.
Prerequisites: Python 3.12, uv, Docker (for local infrastructure).
```bash git clone https://github.com/Harmeet10000/AgentNexus-LangChain-FastAPI.git cd AgentNexus-LangChain-FastAPI cp .env.example .env.development # fill
browse all types & interfaces →
$ claude mcp add AgentNexus-LangChain-FastAPI \
-- python -m otcore.mcp_server <graph>