By Abhijith N M · Reviewed 24 October 2026 · Editorial standards
Turn part 1 into Harbor Support Graph proper: a checkpointed support graph that pauses for a human before any refund, answers policy questions from retrieved documents with their source, keeps a per-ticket thread, and tests all of it without an API key. The live model is deliberately optional — the plan node stays deterministic so the graph's behaviour can be tested before prompt quality is in play.
InMemorySaver(); pass one thread_id per ticket in the config. Note where a SQLite or Postgres saver would go for production.approve_refund node that calls interrupt() with the exact action and arguments; the run resumes with Command(resume=...).execute_refund only when approved is true; otherwise route to draft_reply with an explanation. Nothing writes before the decision.search_docs(query) tool backed by an in-memory vector store; answers cite the passage source or say the docs do not cover the question.from typing import Annotated, Literal, TypedDict
from langchain_core.documents import Document
from langchain_core.embeddings import DeterministicFakeEmbedding
from langchain_core.messages import AIMessage, ToolCall
from langchain_core.tools import tool
from langchain_core.vectorstores import InMemoryVectorStore
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.graph import END, START, StateGraph
from langgraph.graph.message import add_messages
from langgraph.prebuilt import ToolNode
from langgraph.types import interrupt
ORDERS = {"4521": {"status": "delivered", "items": ["ceramic mug"]}}
POLICY = [
Document(
page_content=(
"Damaged items are refunded or replaced within 30 days of delivery. "
"Keep the original packaging."
),
metadata={"source": "refund-policy"},
),
]
store = InMemoryVectorStore(embedding=DeterministicFakeEmbedding(size=64))
store.add_documents(POLICY)
@tool
def lookup_order(order_id: str) -> str:
"""Read-only: return an order's status and items."""
order = ORDERS.get(order_id)
if order is None:
raise ValueError(f"Unknown order: {order_id}")
return f"{order_id}: {order['status']}, {', '.join(order['items'])}"
@tool
def search_docs(query: str) -> str:
"""Read-only: retrieve policy passages with their source."""
hits = store.similarity_search(query, k=1)
return " | ".join(
f"{hit.metadata['source']}: {hit.page_content}" for hit in hits
)
class SupportState(TypedDict):
messages: Annotated[list, add_messages]
order_id: str | None
intent: str | None
approved: bool | None
attempts: int
def intake(state: SupportState) -> dict:
"""Extract the order id, then the intent, from the latest message."""
text = state["messages"][-1].text.lower()
order_id = next(
(
word.strip(".,!?#")
for word in text.split()
if word.strip(".,!?#").isdigit()
),
None,
)
intent = "refund" if "refund" in text else "order_status"
return {"order_id": order_id, "intent": intent}
def plan(state: SupportState) -> dict:
"""Deterministic stand-in for the model: one read-only tool call."""
if state["intent"] == "refund":
return {}
if state["order_id"]:
call = ToolCall(
name="lookup_order",
args={"order_id": state["order_id"]},
id="call_lookup",
)
else:
call = ToolCall(
name="search_docs",
args={"query": state["messages"][-1].text},
id="call_search",
)
return {"messages": [AIMessage(content="", tool_calls=[call])]}
def route_after_plan(state: SupportState) -> Literal["approve_refund", "tools"]:
return "approve_refund" if state["intent"] == "refund" else "tools"
def approve_refund(state: SupportState) -> dict:
"""Pause with the exact proposed action; resume with the decision."""
decision = interrupt(
{
"action": "issue_refund",
"order_id": state["order_id"],
"question": "Approve this refund?",
}
)
approved = decision == "approved"
return {
"approved": approved,
"messages": [
AIMessage(
content=f"Refund {decision} for order {state['order_id']}."
)
],
}
def route_after_approval(
state: SupportState,
) -> Literal["execute_refund", "draft_reply"]:
return "execute_refund" if state["approved"] else "draft_reply"
def execute_refund(state: SupportState) -> dict:
"""The only node that performs the write; idempotent in production."""
return {
"messages": [
AIMessage(content=f"Refund queued for order {state['order_id']}.")
]
}
def draft_reply(state: SupportState) -> dict:
"""Answer from the last tool result or the approval decision."""
last_result = state["messages"][-1].text
return {"messages": [AIMessage(content=f"Update: {last_result}")]}
builder = StateGraph(SupportState)
builder.add_node("intake", intake)
builder.add_node("plan", plan)
builder.add_node("tools", ToolNode([lookup_order, search_docs]))
builder.add_node("approve_refund", approve_refund)
builder.add_node("execute_refund", execute_refund)
builder.add_node("draft_reply", draft_reply)
builder.add_edge(START, "intake")
builder.add_edge("intake", "plan")
builder.add_conditional_edges(
"plan",
route_after_plan,
{"approve_refund": "approve_refund", "tools": "tools"},
)
builder.add_conditional_edges(
"approve_refund",
route_after_approval,
{"execute_refund": "execute_refund", "draft_reply": "draft_reply"},
)
builder.add_edge("tools", "draft_reply")
builder.add_edge("execute_refund", "draft_reply")
builder.add_edge("draft_reply", END)
graph = builder.compile(checkpointer=InMemorySaver())from langgraph.types import Command
from support_graph import graph
BASE = {
"order_id": None,
"intent": None,
"approved": None,
"attempts": 0,
}
def test_refund_pauses_then_resumes_with_approval():
config = {"configurable": {"thread_id": "refund-4521"}}
paused = graph.invoke(
{
**BASE,
"messages": [
{"role": "user", "content": "Please refund order 4521"}
],
},
config,
)
assert "__interrupt__" in paused
assert graph.get_state(config).next == ("approve_refund",)
resumed = graph.invoke(Command(resume="approved"), config)
assert resumed["approved"] is True
assert "queued" in resumed["messages"][-1].text
def test_rejection_never_reaches_the_write():
config = {"configurable": {"thread_id": "refund-4522"}}
graph.invoke(
{
**BASE,
"messages": [
{"role": "user", "content": "Please refund order 4522"}
],
},
config,
)
rejected = graph.invoke(Command(resume="rejected"), config)
assert rejected["approved"] is False
assert "queued" not in rejected["messages"][-1].text
def test_policy_question_is_grounded_in_a_source():
result = graph.invoke(
{
**BASE,
"messages": [
{
"role": "user",
"content": "How long do I have to return a damaged item?",
}
],
},
{"configurable": {"thread_id": "policy-1"}},
)
tool_messages = [
message for message in result["messages"] if message.type == "tool"
]
assert "refund-policy" in tool_messages[0].text
assert "refund-policy" in result["messages"][-1].text
def test_same_thread_keeps_the_conversation():
config = {"configurable": {"thread_id": "memory-1"}}
first = graph.invoke(
{
**BASE,
"messages": [{"role": "user", "content": "Where is order 4521?"}],
},
config,
)
second = graph.invoke(
{
**BASE,
"messages": [{"role": "user", "content": "Where is order 4521?"}],
},
config,
)
assert len(second["messages"]) > len(first["messages"])InMemorySaver in development, one thread_id per ticket, a database saver noted for production.search_docs returns passages with source metadata; the final answer cites the source or says the docs do not cover it.pytest -q passes without an API key, including the part 1 tests.__interrupt__; nothing writes until Command(resume=...) supplies an approval, and a rejection reaches no write path.ToolMessage that names a retrieved source, and the final answer carries that source.InMemorySaver for the SQLite saver and kill the process between the pause and the resume.plan node with a live model and compare the trace; keep the keyless tests as the fast suite.Key takeaways
A support graph is a schema plus named nodes plus routing, with a checkpointer for threads and an interrupt for writes.
The interrupt payload carries the exact proposed action; the execution node is reachable only through an approval edge.
Retrieval grounds policy answers and must cite a source; fake embeddings keep the tests deterministic.
Acceptance is behavioural: keyless tests, pause/resume, no pre-approval write, cited answers and per-ticket memory.
Written and edited by the nexGenCoders team. Spotted a mistake? Tell us and we will fix it.
Don't lose this lesson
Create a free account to save your progress, keep your streak, and work toward a shareable certificate.