MCPcopy Create free account
hub / github.com/Harmeet10000/AgentNexus-LangChain-FastAPI

github.com/Harmeet10000/AgentNexus-LangChain-FastAPI @main

Chat with this repo
repository ↗ · DeepWiki ↗ · + Follow
1,965 symbols 8,690 edges 348 files ⚖ MIT 739 documented · 38% ● updated 3d ago★ 521 open issues

Browse by type

⨍ Functions 1,424◇ Types & classes 479↳ Endpoints 62
What it actually does AI analysis from the code graph — generated when you open this
loading…
README

Agent Saul

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.

CI Greptile: The War on Bugs

Why this exists

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.

What it does

  • Bulletproof ingestion — bounded uploads (size + extension checked before buffering) → queued Celery pipeline → canonical chunks carrying contract_index, page_no, document_version, pipeline_version. Terminal states are truthful: completed, completed_with_warnings, or failed — never a silent partial.
  • Scoped hybrid retrieval — BM25/pg_trgm + pgvector fusion under allowed_doc_ids and contract_index scoping, with Graphiti as an optional relationship backend and coverage signal.
  • Evidence-handle security — search returns server-issued, TTL-scoped handles; read_evidence_by_id re-authorizes on every call (run, thread, checkpoint, document version). Identity and scope never come from the model.
  • Grounded specialist analysis — risk, compliance and deep-research sub-agents behind a ≤7-tool projection, mandatory grounding gate (handle membership → quoted-text substring check → entailment), typed findings, then human review.
  • Human-in-the-loop by construction — plan approval and report review are LangGraph interrupts; resumes re-resolve authorization because a checkpoint can outlive a role change.
  • An evaluated system — a provenance-gated evaluation corpus (105 cases, 23 categories, dual-annotated, Cohen's κ 0.815) runs in CI with checksum, licensing and adjudication gates.

How Saul reasons

Frontend toolchain

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:

  1. Memory shaping — filters, trimming, bounded context.
  2. Runtime control — specialist sub-agents, routing, orchestration.
  3. Execution durability — pause, resume, retry, replay.

The mental model underneath:

  • The LLM is a stateless reasoning engine.
  • State is the source of truth (LegalAgentState and its projections).
  • Memory is indexed projections of state — advisory surfaces, never the record.

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.

LangGraph performance rules

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.

Architecture

Agent Saul full architecture Deployment topology
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.
Hybrid query pipeline Memory stack
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.
Search system overview
Documents system — bounded upload → canonical ingestion → versioned persistence → evaluation as a first-class subsystem.

Honest status

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.

Security model

  • Server-derived authorization. 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.
  • Capability-shaped evidence. Handles are short-lived, run- and version-bound, and mechanically invalid outside their provenance context.
  • Untrusted documents. Document text is data, never instructions; injection fixtures are part of the evaluation corpus and CI.
  • Bounded inputs. Upload size and extension are enforced before buffering; per-document cost/latency budgets are part of the hardening track.

Evaluation

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.

Quickstart

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

Extension points exported contracts — how you extend this code

browse all types & interfaces →

Core symbols most depended-on inside this repo

browse all functions →

Shape

Function 895
Method 529
Class 450
Route 62
Struct 25
Interface 3
TypeAlias 1

Languages

Python96%
Go4%

Modules by API surface

src/app/shared/services/storage.py76 symbols
src/app/shared/langgraph_layer/agent_saul/nodes.py45 symbols
src/app/shared/langgraph_layer/ingestion_kb/nodes.py41 symbols
src/app/utils/cache/redis_func.py38 symbols
src/app/shared/rag/document_processing/models.py29 symbols
src/app/shared/langgraph_layer/agent_saul/state.py29 symbols
src/app/features/auth/router.py28 symbols
src/app/features/documents/service.py27 symbols
tests/integration/test_auth.py26 symbols
src/app/utils/exceptions.py26 symbols
src/app/examples/redis_examples.py24 symbols
src/app/features/auth/websocket_security.py23 symbols

Datastores touched

token_audit_logsCollection · 1 repos
usersCollection · 1 repos
(mongodb)Database · 1 repos
langchain_appDatabase · 1 repos
langchain_dbDatabase · 1 repos
dbDatabase · 1 repos

For agents

$ claude mcp add AgentNexus-LangChain-FastAPI \
  -- python -m otcore.mcp_server <graph>

⬇ download graph artifact

Ask about this repo answers extend the page