Skip to content

The langgraph-agent template

An AI assistant built with LangGraph: agents that call models and tools, answers drawn from the company's documents (RAG), a person's approval before anything acts, and an API in front. LangGraph itself imposes no structure; this template brings one and checks it, with the agent rules (AGT*).

archvow init assistant -t langgraph-agent -a architects=@my-team

It shares with the other templates everything that is not about the stack - the init answers (language, platform, CI, AI assistants, Sonar, internal sources), the Git hook, the code owners, the CI files - through the common base, python-base. The questions, the safety analysis and their tests work the same way.

init answers

All the answers of the pyspark-pipeline template except the Spark ones, plus:

Answer Default Meaning
langgraph_version 1 the LangGraph line the project pins (langgraph==1.*)
python_version 3.12 minimum Python: 3.11 to 3.13

A model provider, a vector store or an MCP library is approved like any package, by an architect: -a dependencies=langchain_anthropic,langchain_postgres. Until one is approved, the project runs on the fake models of the models foundation.

Layers

Layer Holds May import Never
p0_common settings, the models, logging, the access scope, documents, the memory - business rules
p1_domain the state, structured outputs (schemas), prompts, chunkers p0_common a model call, I/O
p2_tools tools, retrievers, MCP clients, clients of other services p0_common, p1_domain an agent
p3_agents routers, nodes, agents: one step of thinking each p0_common, p1_domain, p2_tools data except through a tool or a retriever
p4_app the graphs, the API, the MCP server, the indexing jobs every layer below business rules

Starting components

init creates six foundations; they hold what must exist in one place only:

Foundation Public API What it decides
settings Settings, get_settings() every setting and key, from the environment
models chat(role), embeddings(), fake(messages) the roles (fast, reasoner...) and the model of each, pinned and approved; the gateway; timeouts, retries, fallbacks, cost limits; the fake models of the tests
logging_setup setup_logging(level) one line per event with the request and conversation ids; traces of model calls (personal data)
access AccessScope who asks: the user, their groups, the tenant - built by the API, never by a model
documents Document, Passage the one shape of the company's data (below)
memory get_checkpointer() where conversations are kept, how long, how one user's history is erased

The agents never name a model: they ask models.chat("reasoner"). Changing a model is one line in one file, reviewed by the architects.

Component types

Type File Public API Test Questions
state p1_domain/<name>_state.py class <Name>State (TypedDict) unit 3: fields and how each is updated, saved conversations when it changes, personal data
schema p1_domain/<name>_schema.py class <Name> (Pydantic) unit 3: fields, an output that does not fit, citations and "written by an AI"
prompt p1_domain/<name>_prompt.py build_<name>_prompt(...) unit 3: what the model may do, where untrusted text goes, the language
chunker p1_domain/<name>_chunker.py chunk_<name>(document) unit 3: by structure or size, chunk size and overlap, what each chunk keeps
utility p0_common/<name>.py (verb_noun) <name>(...) unit 2: what it takes and returns, invalid input
tool p2_tools/<name>_tool.py <name> (@tool) integration 5: untrusted content, private data, acts, approval and repeats, text to SQL
retriever p2_tools/<name>_retriever.py retrieve_<name>(query, scope) integration 4: access rights, keywords or meaning, how many and a threshold, which store and index
mcp_client p2_tools/<name>_mcp.py load_<name>_tools() integration 3: which server (pinned, approved by whom), which of its tools and which act, the server down
client p2_tools/<name>_client.py class <Name>Client integration 3: timeout, retries, the other service down
router p3_agents/<name>_router.py route_<name>(state) unit 3: the routes and their model roles, how it classifies, when unsure
node p3_agents/<name>_node.py <name>_node(state) unit 3: what it reads and writes, which model role, a failing call
agent p3_agents/<name>_agent.py build_<name>_agent() unit 4: its tools, its step limit, its model role, what it returns
graph p4_app/<name>_graph.py build_<name>_graph() integration 3: the steps, where a person approves, the step limit
api p4_app/<name>_api.py router: APIRouter, create_app() and its routes integration 4: sign-in and scope, telling users it is an AI, limits per user, streaming
mcp_server p4_app/<name>_mcp_server.py create_<name>_server() integration 2: which tools to which clients and how they sign in, the user's rights checked on each call
index_job p4_app/<name>_index_job.py index_<name>() integration 4: which source and why copy it, what one run copies, deletions and removed rights, a new embedding model

The tool questions are the Rule of Two: a tool that reads untrusted content, one that reads private data and one that acts may not all be in reach of one agent unless a person approves before it acts (AGT005).

Business examples (archvow example add) are the evaluations: a question in, what the answer must hold out (the cited passages, "I don't know"), checked by properties, never word for word. A chunker takes them too: a document in, its chunks out.

Company data: Documents

A Document is one piece of content from any source, in one shape (the documents foundation): source_id, source_kind, text, url, modified_at and allowed - the groups that may read it, copied from the source. A Passage is a piece of a Document that is indexed, found and cited.

Source One Document is Copy or ask live
files, SharePoint, Drive one file (or one page of a site) copy: stable, searched by meaning
e-mails one e-mail with its thread's subject ask live (the mailbox's search API, as the user) unless an archive is approved
a database one row or one record, described in words ask live (a tool with a read-only account), unless the text columns are searched by meaning
dashboards one dashboard's description and its figures' definitions copy the descriptions; ask the figures live
tickets, a wiki one ticket, one page copy, with the access rights of each

The flow of what is copied is always the same: source -> Documents -> passages (a chunker) -> embeddings (the models foundation) -> the index (an index_job) -> search (a retriever, filtered by the user's access scope) -> the answer, which cites its passages. What is asked live makes no Documents: a tool answers directly, as the user.

What the questions make each project decide:

  • Access rights travel with the data. The allowed groups of each Document are copied on every chunk; the retriever filters by the user's groups before the model sees anything (AGT007: only a retriever searches the index).
  • Stable ids. An index job writes with ids built from the source id, the chunk number and a content hash: a re-run changes nothing (AGT008), a changed document replaces its chunks, a deleted one leaves the index.
  • One embedding model, pinned in the models foundation: the same one indexes and searches. A new model means a new index, named with the model's version.

Rules

On top of archvow's generic rules (ARCH*, STY*) and the FastAPI rules (FAPI*) of the API, the template switches on the agent rules:

Code Fails when
AGT001 a model provider is imported, or a model created, outside the models foundation
AGT002 a model is named by its id in the code ("gpt-4o", "claude-...")
AGT003 a graph is compiled without the memory's checkpointer
AGT004 a graph has no step limit (recursion_limit)
AGT005 an agent can read untrusted content, read private data and act, with no person's approval (interrupt())
AGT006 a model's text is parsed by hand (json.loads) in p3_agents instead of a structured output
AGT007 the index is searched outside a retriever
AGT008 the index is written without ids
AGT009 a tool has no docstring, or an argument without a type
AGT010 a tool argument names the user (user_id, email...) and is filled by the model, not injected from the access scope
AGT011 an MCP server is connected outside an mcp_client component
AGT012 a prompt is pulled from a hub at run time

A company template says which of its component types play which part, under agent_roles (Packs). See Rules.

What must never happen

Guide word Typical hazard Example invariant
leak an answer shows another team's document "a passage is returned only when the user's groups may read its document" (property test)
injection a document's text makes the model call a tool "text the model reads is data; acting needs a person's approval"
acts a booking made without the user's yes "nothing is booked until the person it acts for approves" (property test)
runaway an agent loops on its tools "at most 8 tool calls per request, then it stops and says so"
wrong a made-up citation "every citation is the id of a passage the model was given"
stale a deleted policy still answers "a deleted file leaves the index at the next run"
repeated a retried call books twice "a booking key stops the same booking twice"
exposed a question written to a log "logs never hold a prompt, an answer or personal data"
missing the index is down "nothing found: the answer says it does not know"
partial an index half written "a run writes a new index, then replaces the old one"

Tests

  • Unit (states, schemas, prompts, chunkers, routers, nodes, agents): fake models from the models foundation - models.fake([...]) answers the messages it is given, in turn, tool calls included - and fake embeddings; no network.
  • Integration (tools, retrievers, graphs, the API, indexing jobs): a whole graph with an in-memory checkpointer, an in-memory index, FastAPI's TestClient; @pytest.mark.integration. An approval is tested through the graph: it stops at interrupt(), then resumes with Command(resume=...).

Real models are judged apart, on the business examples, by properties.

Logging

logging_setup is the only place that configures logging (ARCH059); every module takes its own logger, logging.getLogger(__name__). One line per event with the request id and the conversation (thread) id - never a prompt, an answer's text, a secret or personal data. The tests put the logging back after each test (a shared fixture of tests/conftest.py).

A company-wide assistant

What the template asks before an assistant serves the whole company:

  • Models through the company's gateway, by role, with a cost limit per request and the region prompts may go to (the models questions).
  • Sign-in and scope from the company's identity provider, never from the request body; a conversation belongs to its user (the api questions).
  • Users told they talk to an AI (EU AI Act, article 50), and every answer marked ai_generated.
  • Retention and erasure of conversations (GDPR article 17, the memory questions), and traces kept inside the company.
  • MCP servers approved one by one (AGT011), and the company's own tools served over MCP by an mcp_server component, with the same access scope.

Running

make run                       # uvicorn with reload, the API of the `chat` component (API=<name>)
make test                      # every test, with coverage

What init writes

Like the fastapi-service template: README.md (with the walkthrough from the empty project to a running assistant), AGENTS.md and the assistants' files, pyproject.toml (LangGraph, langchain-core, FastAPI, pydantic-settings, uvicorn, and the test settings), requirements.txt, Makefile, ruff.toml (with LOG, FAST and ASYNC), the Git hook, the code owners, the CI, .gitignore (with .env) and .archvow/.

The finished example

The archvow repository holds an assistant finished, its spec and its code: examples/langgraph-agent (airport_assistant). It answers employees' questions from the travel policies - only those their groups may read - and books flights once they approve. Every check passes: archvow check --complete (the agent rules included), ruff and the tests, with the invariants proven by Hypothesis property tests (a user only finds what their groups may read; nothing is booked without the user's approval, and never twice; a conversation belongs to its user).

cd examples/langgraph-agent
python3 -m pip install -r requirements.txt
archvow check --complete && make test
PYTHONPATH=src python3 -c "from airport_assistant.p4_app.policies_index_job import index_policies as i; print(i())"   # the index: 6 chunks
make run                                     # then, in another terminal:
curl -X POST localhost:8000/chat -H "X-User: ann" -H "X-Groups: employees" \
     -H "Content-Type: application/json" -d '{"thread_id": "t1", "message": "hotel night in Paris"}'

It runs on fake models (ASSISTANT_MODELS=fake): the answer is a placeholder, the passages found are real. To see a rule fail, create a model in answer_node.py (init_chat_model("gpt-4o")), or compile the graph without its checkpointer, and run archvow check.