Lesson 4 of 11 · Graphs
Your First Graph
Build a LangGraph graph step by step: a model writes, code checks facts, a model reviews with structured output and conditional edges loop back for revisions.
- 6 min read
- Advanced
- Reviewed
- Design a graph's state, nodes and edges for a real task
- Combine model nodes with plain-code nodes
- Use structured output inside a node
- Loop for revisions with limits, and hand over when stuck
- Watch a graph run step by step with stream_mode="updates"
The task
A shop wants short product descriptions written from a list of facts. Each description must:
- Include every fact exactly (name, range, price), and nothing invented.
- Be good enough by a reviewer's standards.
- Never loop forever: after three attempts, a person takes over.
That's a natural graph: write, check the facts (code), review (model), and loop back with feedback when either check fails.
Designing it first
Before writing code, decide the three ingredients:
| Ingredient | Design |
|---|---|
| State | facts, draft, fact_problems, score, comments, revisions |
| Nodes | write (model), check_facts (code), review (model with structured output), human (hand-over) |
| Edges | start → write → check_facts; facts wrong → write again (or human after 3); facts right → review; score 8+ → end; lower → write again (or human after 3) |
Notice which checks are code and which are models. Whether the price appears in the text is a fact that code can check exactly and cheaply. Whether the description is appealing needs judgement, so a model reviews it.
The graph
from typing import Literal, TypedDict
from pydantic import BaseModel, Field
from langchain.chat_models import init_chat_model
from langgraph.graph import END, START, StateGraph
model = init_chat_model("anthropic:MODEL_NAME", temperature=0.7)
class Review(BaseModel):
score: int = Field(description="Quality from 1 to 10")
comments: str = Field(description="What to improve, in one sentence")
reviewer = model.with_structured_output(Review)
class State(TypedDict):
facts: dict
draft: str
score: int
comments: str
fact_problems: list[str]
revisions: int
def write(state: State) -> dict:
prompt = (f"Write a product description of at most 30 words using only these facts: {state['facts']}.\n"
f"Reviewer comments: {state.get('comments') or 'none'}")
return {"draft": model.invoke(prompt).content, "revisions": state.get("revisions", 0) + 1}
def check_facts(state: State) -> dict: # plain code: every fact must appear exactly
missing = [f"{k}={v}" for k, v in state["facts"].items() if str(v) not in state["draft"]]
if missing:
return {"fact_problems": missing, "comments": f"Mention these facts exactly: {', '.join(missing)}"}
return {"fact_problems": []}
def review(state: State) -> dict:
r = reviewer.invoke(f"Review this product description for clarity and appeal:\n{state['draft']}")
return {"score": r.score, "comments": r.comments}
def after_check(state: State) -> Literal["review", "write", "human"]:
if state["fact_problems"]: # wrong or missing facts: rewrite first
return "write" if state["revisions"] < 3 else "human"
return "review"
def after_review(state: State) -> Literal["write", "human", "__end__"]:
if state["score"] >= 8:
return END
return "write" if state["revisions"] < 3 else "human"
builder = StateGraph(State)
builder.add_node("write", write)
builder.add_node("check_facts", check_facts)
builder.add_node("review", review)
builder.add_node("human", lambda s: {"comments": "sent to the marketing team"})
builder.add_edge(START, "write")
builder.add_edge("write", "check_facts")
builder.add_conditional_edges("check_facts", after_check)
builder.add_conditional_edges("review", after_review)
builder.add_edge("human", END)
graph = builder.compile()
facts = {"name": "Volta City 3", "range_km": 70, "price_eur": 2190}
for step in graph.stream({"facts": facts}, stream_mode="updates"):
for node, update in step.items():
print(f"{node}: {update}")write: {'draft': 'Meet the Volta City 3: a light, stylish city e-bike with a 70 km range for your daily commute.', 'revisions': 1}
check_facts: {'fact_problems': ['price_eur=2190'], 'comments': 'Mention these facts exactly: price_eur=2190'}
write: {'draft': 'Meet the Volta City 3: a light city e-bike with a 70 km range, made for daily commutes, for 2190 EUR.', 'revisions': 2}
check_facts: {'fact_problems': []}
review: {'score': 6, 'comments': 'Lead with a benefit and cut the filler words.'}
write: {'draft': 'The Volta City 3 glides through traffic: 70 km range, light frame, 2190 EUR. Your commute, upgraded.', 'revisions': 3}
check_facts: {'fact_problems': []}
review: {'score': 9, 'comments': 'Clear and appealing.'}Reading the run
graph.stream(..., stream_mode="updates") yields each node's update as it finishes, which makes the run easy to follow:
- The first draft forgot the price.
check_factscaught it without spending a model call, and its comment went back to the writer. - The second draft had all the facts, but the reviewer scored it 6 and asked for a stronger opening.
- The third draft scored 9, so the graph ended.
Each node's comments flow through the state into the next write prompt. That's the feedback loop from the Agent Workflows course's evaluator-optimiser pattern, now with explicit state and limits.
Making the fact check stricter
The graph's check_facts only checks that facts appear. Models also invent details, like a warranty nobody mentioned. Here's a stricter check in plain Python that also flags numbers not found in the facts:
import re
# The graph's check_facts node, made stricter: every fact must appear, and the draft
# must not contain numbers that aren't in the facts (models sometimes invent them).
facts = {"name": "Volta City 3", "range_km": 70, "price_eur": 2190}
def check_facts(draft):
numbers_in_draft = {n.replace(",", "") for n in re.findall(r"\d[\d,]*", draft)}
allowed = {str(v) for v in facts.values()} | set(re.findall(r"\d+", facts["name"]))
missing = [k for k, v in facts.items() if str(v) not in draft.replace(",", "")]
invented = sorted(numbers_in_draft - allowed)
return missing, invented
drafts = [
"Meet the Volta City 3: a light city e-bike with a 70 km range.",
"The Volta City 3: 70 km range, 2,190 EUR, and a 5-year warranty.",
"The Volta City 3 glides through traffic: 70 km range, 2190 EUR.",
]
for d in drafts:
missing, invented = check_facts(d)
verdict = "OK" if not missing and not invented else f"missing={missing} invented={invented}"
print(f"{verdict:<38} | {d}")The second draft looks fine to a reader, but it invented a 5-year warranty. A check like this belongs in code, where it is exact, instant and free.
Common mistakes
Catch invented numbers: a model writing a product description must not add figures that aren't in the facts.
import re
facts = {"range_km": 70, "price_eur": 2190, "weight_kg": 19}
draft = "Only 19 kg, a 75 km range and yours for 2190 EUR, with 2 free services."
# Find every whole number in the draft (re.findall(r"\d+", draft)) that is NOT one of the
# fact values, and print them as a sorted list of integers.
Why is check_facts a plain-code node rather than a model call?
Summary
- Design state, nodes and edges before coding.
- Mix model nodes (writing, judging) with code nodes (exact checks).
- Use structured output inside nodes to get scores and comments as data.
- Loop with feedback in the state and attempt limits, handing over to a person when stuck.
stream_mode="updates"shows each node's update as the graph runs.
Next: a tool-calling agent as a graph.
Finished reading? Tick it off to track your progress.