Project: The Graph
Wiring it up.
Now we connect the pieces. Triage first. Then a conditional edge sends each message to the node named after its category. The specialists, the refund node, and a simple other node.

- Connect the pieces
- Triage first
- Route by category
desk.py
We import every piece. Other is a tiny node with a holding reply. A loop adds all five nodes. Start goes to triage. The conditional edge reads the category, which is also a node name. And we compile with a checkpointer, for memory, and for refund approvals.
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.graph import StateGraph, START
from state import DeskState
from triage import triage
from policy_agent import policy
from orders_agent import orders
from refund import refund
def other(s):
return {"messages": [("ai", "Thanks! A member of our team will reply by email soon.")]}
b = StateGraph(DeskState)
for name, node in [("triage", triage), ("policy", policy), ("orders", orders),
("refund", refund), ("other", other)]:
b.add_node(name, node)
b.add_edge(START, "triage")
b.add_conditional_edges("triage", lambda s: s["category"])
desk = b.compile(checkpointer=InMemorySaver())Trying the desk
Let's send three different messages, each on its own thread. We print the category triage chose, and the final reply. Run it. A policy question goes to the policy agent. A stock question goes to the orders agent. And a joke request gets the holding reply.
from desk import desk
for i, text in enumerate(["How much is express delivery?", "Is The Hobbit in stock?",
"Can you tell me a joke?"]):
out = desk.invoke({"messages": [{"role": "user", "content": text}]},
{"configurable": {"thread_id": f"t{i}"}})
print(f"[{out['category']}] {text}\n {out['messages'][-1].text.strip()[:90]}")[policy] How much is express delivery? Express delivery costs £5.99 and arrives the next working day if ordered before 2 pm. [orders] Is The Hobbit in stock? Yes, there are 7 copies of The Hobbit in stock. [other] Can you tell me a joke? Thanks! A member of our team will reply by email soon.
Also uses kb/shipping.md
# Shipping
Standard delivery in the UK takes 3 to 5 working days and costs £2.99.
Delivery is free on orders over £25.
Express delivery arrives the next working day if you order before 2pm, and costs £5.99.
We ship to Ireland and France in 5 to 8 working days for £7.50.
Every order gets a tracking link by email once it leaves our warehouse.Also uses kb/returns.md
# Returns and refunds
You can return any book within 30 days of delivery for a full refund.
Books must be unread and in the condition you received them.
Damaged or faulty books can be returned at any time, and we pay the return postage.
Refunds go back to the original payment method within 5 working days of us receiving the book.
To start a return, reply to your order confirmation email.Also uses kb/gift_cards.md
# Gift cards
Riverside Books gift cards come in values from £10 to £100.
Gift cards never expire and can be used online or in our shop.
A gift card can be used across several orders until the balance is spent.
Gift cards cannot be exchanged for cash.Also uses kb/loyalty.md
# Riverside Readers loyalty club
Joining the Riverside Readers club is free.
Members earn one point for every pound they spend.
100 points can be swapped for a £5 voucher.
Members get early access to signed editions and a birthday discount of 10 percent.Also uses kb/shop.md
# About the shop
Riverside Books has one physical shop, at 12 Mill Lane, Bath.
The shop is open from 9am to 6pm Monday to Saturday, and 11am to 4pm on Sunday.
We sell new and second-hand books, and run a children's story time every Saturday at 10am.
You can contact us at hello@riverside-books.example or on 01225 000 000.Also uses shop_kb.py
from pathlib import Path
from langchain_core.documents import Document
from langchain_core.vectorstores import InMemoryVectorStore
from langchain_google_genai import GoogleGenerativeAIEmbeddings
from langchain_text_splitters import RecursiveCharacterTextSplitter
def load_docs(folder="kb"):
return [Document(p.read_text(), metadata={"source": p.name})
for p in sorted(Path(folder).glob("*.md"))]
def build_store(folder="kb"):
splitter = RecursiveCharacterTextSplitter(chunk_size=300, chunk_overlap=40)
chunks = splitter.split_documents(load_docs(folder))
embeddings = GoogleGenerativeAIEmbeddings(model="gemini-embedding-001")
return InMemoryVectorStore.from_documents(chunks, embeddings)Also uses shop_tools.py
from langchain.tools import tool
BOOKS = {
"The Hobbit": {"stock": 7, "price": 8.99, "author": "J.R.R. Tolkien"},
"Dune": {"stock": 3, "price": 9.99, "author": "Frank Herbert"},
"Circe": {"stock": 0, "price": 10.99, "author": "Madeline Miller"},
}
@tool
def check_stock(title: str) -> int:
"""Copies of a book in stock at Riverside Books."""
return BOOKS.get(title, {}).get("stock", 0)
@tool
def get_price(title: str) -> float:
"""Price of a book in pounds."""
return BOOKS.get(title, {}).get("price", 0.0)
@tool
def get_author(title: str) -> str:
"""Author of a book."""
return BOOKS.get(title, {}).get("author", "unknown")Also uses state.py
from typing import get_type_hints
from langgraph.graph import MessagesState
class DeskState(MessagesState):
category: str # policy, orders, refund or other
refund_amount: float # filled in by triage for refund requests
refund_status: str # approved or declined
if __name__ == "__main__":
for key, kind in get_type_hints(DeskState).items():
print(f"{key:<14} {getattr(kind, '__name__', kind)}")Also uses triage.py
from typing import Literal
from pydantic import BaseModel
from langchain.chat_models import init_chat_model
from langchain.messages import HumanMessage
class Triage(BaseModel):
category: Literal["policy", "orders", "refund", "other"]
refund_amount: float = 0.0
judge = init_chat_model("google_genai:gemini-flash-lite-latest", temperature=0).with_structured_output(Triage)
RULES = ("Classify this Riverside Books message. policy: delivery, returns, gift cards, loyalty, "
"opening hours. orders: stock, prices, order status. refund: wants money back now "
"(give the amount). other: anything else.")
def triage(s):
t = judge.invoke([("system", RULES), s["messages"][-1]])
return {"category": t.category, "refund_amount": t.refund_amount}
if __name__ == "__main__":
for text in ["Do you deliver to France?", "Is Dune in stock?", "Refund my £45 order please", "Tell me a joke"]:
print(f"{text:<28} -> {triage({'messages': [HumanMessage(text)]})}")Also uses policy_agent.py
from langchain.agents import create_agent
from langchain.tools import tool
from shop_kb import build_store
store = build_store()
@tool
def search_policies(query: str) -> str:
"""Search Riverside Books' policies: delivery, returns, gift cards, loyalty, the shop."""
return "\n".join(d.page_content for d in store.similarity_search(query, k=2))
policy = create_agent("google_genai:gemini-flash-lite-latest", tools=[search_policies], name="policy",
system_prompt="Answer policy questions for Riverside Books in one or two "
"sentences, only from search_policies. If it isn't there, say so.")
if __name__ == "__main__":
out = policy.invoke({"messages": [{"role": "user", "content": "Do gift cards expire?"}]})
print(out["messages"][-1].text)Also uses orders_agent.py
from langchain.agents import create_agent
from langchain.tools import tool
from shop_tools import check_stock, get_price
@tool
def order_status(order_id: str) -> str:
"""Status of an order. Order ids look like RB-1234."""
orders = {"RB-1234": "shipped, arriving Thursday", "RB-5678": "being packed"}
return orders.get(order_id.strip().upper(), "No such order. Ask the customer to check it.")
orders = create_agent("google_genai:gemini-flash-lite-latest", name="orders",
tools=[check_stock, get_price, order_status],
system_prompt="You handle stock, prices and orders at Riverside Books. Be brief.")
if __name__ == "__main__":
out = orders.invoke({"messages": [{"role": "user", "content": "Has RB-5678 shipped? Is Circe in stock?"}]})
print(out["messages"][-1].text)Also uses refund.py
from langgraph.types import interrupt
def refund(s):
amount = s["refund_amount"]
if amount > 20:
decision = interrupt({"refund": amount, "question": "Approve this refund?"})
if decision != "approve":
return {"refund_status": "declined",
"messages": [("ai", "Sorry, we couldn't approve this refund. We'll email you.")]}
return {"refund_status": "approved",
"messages": [("ai", f"Your refund of £{amount:.2f} is approved. Expect it within 5 working days.")]}Also uses desk.py
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.graph import StateGraph, START
from state import DeskState
from triage import triage
from policy_agent import policy
from orders_agent import orders
from refund import refund
def other(s):
return {"messages": [("ai", "Thanks! A member of our team will reply by email soon.")]}
b = StateGraph(DeskState)
for name, node in [("triage", triage), ("policy", policy), ("orders", orders),
("refund", refund), ("other", other)]:
b.add_node(name, node)
b.add_edge(START, "triage")
b.add_conditional_edges("triage", lambda s: s["category"])
desk = b.compile(checkpointer=InMemorySaver())Also uses judge.py
from pydantic import BaseModel, Field
from langchain.chat_models import init_chat_model
class Grade(BaseModel):
correct: bool = Field(description="Does the answer agree with the reference?")
reason: str = Field(description="One short sentence.")
judge = init_chat_model("google_genai:gemini-flash-lite-latest", temperature=0).with_structured_output(Grade)
def grade(question, answer, reference):
g = judge.invoke(f"Question: {question}\nReference: {reference}\nAnswer: {answer}\nGrade the answer.")
return g.correctSummary
Desk dot p y wires triage, specialists, refunds, and other into one graph, with a checkpointer. Next, approving big refunds.
Key takeaways- Five nodes
- Route by category
- Checkpointer