
Agent Graph Engineering
For most of 2025, the default mental model for AI agents was the loop: plan, act, observe, repeat. Andrej Karpathy popularised the term; every major framework built around it. Loops work — but they break at the seams when you need multiple specialised agents working in parallel, each maintaining independent context while still sharing knowledge with the others. That is the flaw. Graph engineering is the fix.
What is a Graph, exactly?
In this context, a graph is not a chart or a knowledge base. It is a formal way of describing how work flows through a system of agents. Every graph has three primitives:
The key distinction from a simple loop: a loop is sequential. A graph can be parallel, branching, and persistent. When you have five specialised agents — researcher, coder, critic, tester, summariser — a loop forces them to take turns. A graph lets them run concurrently and share findings through a common state layer.
The Flaw Graph Engineering Fixes
Every Claude agent starts with a blank context window. When it finishes its task, that context disappears. In a multi-agent graph this means Agent A's discovered facts are invisible to Agent B unless you explicitly pass them. The naive fix — dump everything into a shared prompt — runs straight into token limits and cost explosion.
Anthropic's approach replaces the "bloated shared prompt" with a shared knowledge graph: a structured store of entities and relationships extracted from each agent's work, which any downstream agent can query without reading the full raw output. The memory is persistent; the context passed to each agent stays lean.
Anthropic's Four-Stage Pipeline
The reference implementation runs four stages, each using the cheapest model capable of the task:
Stage overviewExtract (Haiku) → Pull entities + relations from raw output Resolve (Sonnet) → Merge aliases: "NASA" == "Nat. Aeronautics..." Assemble (Sonnet) → Build node summaries for high-degree entities Query (Sonnet) → Serialize k-hop neighborhood → feed to next agent
The storage layer is a NetworkX MultiDiGraph in Python. Each node is an entity; each edge is a typed, directed relation with provenance metadata pointing back to the source document or agent turn that produced it. A healthy graph has an edge-to-node ratio above 1.3 — anything lower means your agents are producing isolated facts rather than connected knowledge.
Code Examples
1. Defining a subagent in Claude Code
Anthropic baked graph nodes directly into Claude Code. Each subagent lives in .claude/agents/ as a markdown file with YAML frontmatter declaring its tools and scope.
--- name: researcher description: > Searches the web and internal docs for facts on a given topic. Produces structured output: a list of entities and relations. tools: - web_search - read_file - write_file model: claude-haiku-4-5 --- You are a focused research agent. Given a query, return: - A bullet list of key entities (name + one-sentence description) - A bullet list of relations in the form: Entity A → [predicate] → Entity B Stay within scope. Do not summarise — extract raw structured facts only..claude/agents/critic.md
---
name: critic
description: >
Reviews the researcher's output for gaps, contradictions,
or low-confidence claims. Returns a structured critique.
tools:
- read_file
model: claude-opus-4-6
---
You are a rigorous critic. Read the researcher's structured output.
Flag: missing evidence, circular reasoning, unresolved aliases,
and any claim that cannot be traced to a primary source.
Return a JSON array of { claim, issue, severity } objects.2. Building the knowledge graph
The extraction stage uses structured outputs to force schema-compliant entity/relation extraction.
graph_builder.pyimport anthropic
import networkx as nx
from pydantic import BaseModel
class Entity(BaseModel):
name: str
type: str # person | org | concept | event
description: str # one sentence, for alias resolution later
class Relation(BaseModel):
source: str # entity name
predicate: str # short verb phrase
target: str # entity name
provenance: str # which agent run / document produced this
class ExtractedGraph(BaseModel):
entities: list[Entity]
relations: list[Relation]
client = anthropic.Anthropic()
def extract(text: str) -> ExtractedGraph:
"""Stage 1 — Haiku extracts entities and relations."""
return client.messages.parse(
model="claude-haiku-4-5-20251001",
max_tokens=2048,
messages=[{
"role": "user",
"content": (
"Extract entities and relations from the text below.\n"
"Rules:\n"
"- Extract only entities central to the document.\n"
"- Descriptions must disambiguate (include dates, roles).\n"
"- Predicates: short verb phrases (e.g. 'founded', 'acquired').\n"
"- Every relation must connect two extracted entities.\n\n"
f"{text}"
),
}],
output_format=ExtractedGraph,
)
def resolve(graph: ExtractedGraph) -> dict[str, str]:
"""Stage 2 — Sonnet merges surface-form aliases."""
prompt = (
"Given these entities, identify groups that refer to "
"the same real-world thing. Return a JSON object mapping "
"each alias to its canonical name.\n\n"
+ "\n".join(
f"- {e.name} ({e.type}): {e.description}"
for e in graph.entities
)
)
response = client.messages.create(
model="claude-sonnet-4-6",
max_tokens=1024,
messages=[{"role": "user", "content": prompt}],
)
import json
return json.loads(response.content[0].text)
def assemble(extracted: ExtractedGraph, aliases: dict[str, str]) -> nx.MultiDiGraph:
"""Stage 3 — Build the graph with resolved canonical names."""
G = nx.MultiDiGraph()
for e in extracted.entities:
canonical = aliases.get(e.name, e.name)
G.add_node(canonical, type=e.type, description=e.description)
for r in extracted.relations:
src = aliases.get(r.source, r.source)
tgt = aliases.get(r.target, r.target)
G.add_edge(src, tgt, predicate=r.predicate, provenance=r.provenance)
return G
def query(G: nx.MultiDiGraph, entity: str, k: int = 2) -> str:
"""Stage 4 — Serialize a k-hop neighborhood as triples."""
nodes = nx.single_source_shortest_path_length(G, entity, cutoff=k)
triples = []
for u, v, data in G.edges(data=True):
if u in nodes or v in nodes:
triples.append(f"({u}) --[{data['predicate']}]--> ({v})")
return "\n".join(triples)3. Orchestrator-Workers pattern
The orchestrator dispatches to specialist workers, collects their extracted graphs, merges them, and feeds the resolved knowledge back to a synthesis agent — all without any single agent holding the full context.
orchestrator.pyimport anthropic, asyncio, networkx as nx
from graph_builder import extract, resolve, assemble, query
client = anthropic.Anthropic()
WORKERS = [
{"name": "market-researcher", "query": "market size and competitors"},
{"name": "tech-researcher", "query": "technical architecture options"},
{"name": "risk-analyst", "query": "regulatory and operational risks"},
]
async def run_worker(topic: str, sub_query: str) -> nx.MultiDiGraph:
"""Each worker researches one slice and returns a subgraph."""
response = client.messages.create(
model="claude-haiku-4-5-20251001",
max_tokens=2048,
messages=[{
"role": "user",
"content": f"Research the following aspect of '{topic}': {sub_query}. "
"Return a detailed factual report."
}],
)
raw_text = response.content[0].text
extracted = extract(raw_text)
aliases = resolve(extracted)
return assemble(extracted, aliases)
async def run_graph(topic: str) -> str:
# Fan-out: all workers run in parallel
subgraphs = await asyncio.gather(*[
run_worker(topic, w["query"]) for w in WORKERS
])
# Join: merge all subgraphs into one shared knowledge graph
G = nx.MultiDiGraph()
for sg in subgraphs:
G = nx.compose(G, sg)
# Query: pull the 2-hop neighborhood of the main topic entity
context = query(G, topic, k=2)
# Synthesis agent gets only the lean graph context, not raw reports
synthesis = client.messages.create(
model="claude-opus-4-6",
max_tokens=4096,
messages=[{
"role": "user",
"content": (
f"Using only the verified knowledge graph below, "
f"write a strategic briefing on '{topic}'.\n\n"
f"{context}"
),
}],
)
return synthesis.content[0].text
# Run
if __name__ == "__main__":
result = asyncio.run(run_graph("autonomous vehicle regulation"))
print(result)4. Verification with the Second Opinion pattern
The video's main practical contribution: launch a fresh Claude session for review, so it carries no inherited context bias from the producing agent. Cheap for verification; expensive for the judge — so pick your reviewer model deliberately.
second_opinion.pydef second_opinion(original_output: str, criteria: str) -> dict:
"""
Launch an isolated session to review output.
'The node that does the judging is the one place
where saving tokens costs you everything.'
— Anthropic workshop, 2026
"""
reviewer = anthropic.Anthropic() # fresh client = clean context
response = reviewer.messages.create(
model="claude-opus-4-6", # do NOT downgrade the judge
max_tokens=1024,
system=(
"You are a strict independent reviewer. "
"You have no prior context. Evaluate only what is shown."
),
messages=[{
"role": "user",
"content": (
f"Criteria:\n{criteria}\n\n"
f"Output to review:\n{original_output}\n\n"
"Return JSON: {{ pass: bool, issues: [str], confidence: float }}"
),
}],
)
import json
return json.loads(response.content[0].text)When to use a Graph vs a Loop
Not every agent needs a graph. A loop is simpler, cheaper, and easier to debug. Reach for a graph when your workflow genuinely has:
- Parallel branches that can run independently
- Multiple specialised agents that each need only a slice of the full context
- Facts that must persist and be verified across agent boundaries
- Human approval or external gating steps in the middle of a workflow
- Recovery paths — the ability to retry a single failed node without re-running the whole run
The critical constraint: every node must be a loop that reliably ships on its own before you wire it into a graph. Composing unreliable agents multiplies failures rather than fixing them, while multiplying token costs at the same time.
The Practical Takeaway
Graph engineering is not a new framework to install. It is a design discipline: stop thinking in sequential agent conversations and start thinking in bounded, parallelisable work units connected by explicit routing logic and a shared, lean state layer. Anthropic's native tooling — Claude Code subagents, the Agent SDK, and structured output extraction — gives you everything you need to prototype this without pulling in a third-party orchestration library. Start with a single loop. When it reliably ships, wrap it in a node. Wire two nodes together. Build the graph from proven parts.
New articles, tools and experiments — no noise.