LangGraph in Python: Building a Support Agent Step by Step
By · · 10 min read · AI Development
#python #langgraph #langchain #openai #ai-agents
A hands-on walk through LangGraph: state, nodes and edges, then a customer support agent, a small multi-agent pipeline, and the checkpointing features that make it worth using.
On this page
Most agent demos are a while loop around an LLM call. That works until you need the agent to pause for approval, remember a conversation from yesterday, or take a different path depending on what the user said. Then the loop grows flags and if statements, and nobody wants to touch it.
LangGraph is LangChain’s answer to that. You describe your agent as a graph: steps are nodes, and the paths between them are edges. It sounds like more ceremony than a loop, and for a toy it is. For anything with branching or long-running state, it’s a lot easier to reason about.
In this post we’ll build two things: a customer support agent that can look things up and hand off to a human, and a small research pipeline with three agents in a row. Then we’ll look at checkpointing, which is the feature that makes LangGraph more than a nice way to draw boxes.
The three ideas you need
State. A typed dictionary that travels through the graph. Every node reads it and returns the keys it wants to update.
Nodes. Plain Python functions. They take the state and return a partial update. A node can call an LLM, hit an API, or do nothing clever at all.
Edges. They decide what runs next. A normal edge always goes from A to B. A conditional edge calls a function and uses the return value to pick the next node.
That’s it. Everything else (streaming, persistence, human approval) is built on these.
Setup
pip install langgraph langchain-openai python-dotenv
echo "OPENAI_API_KEY=your_openai_api_key_here" > .envA customer support agent
Here’s the behaviour we want:
- If the user is clearly upset or asks for a person, hand off to a human.
- Otherwise, look up what we can (order status or the knowledge base), then let the model write the reply.
State and tools
import operator
from typing import Annotated, TypedDict
from dotenv import load_dotenv
from langchain_core.messages import AIMessage, HumanMessage, SystemMessage
from langchain_core.tools import tool
from langchain_openai import ChatOpenAI
from langgraph.graph import END, StateGraph
load_dotenv()
class AgentState(TypedDict):
# operator.add means "append to the list" instead of "replace it"
messages: Annotated[list, operator.add]
lookup_result: str
escalation_needed: bool
llm = ChatOpenAI(model="gpt-4o-mini", temperature=0.1)
@tool
def search_knowledge_base(query: str) -> str:
"""Search the company knowledge base for information."""
# Stand-in for a real search
knowledge_base = {
"refund": "Refunds are processed within 5-7 business days. Please provide your order number.",
"shipping": "Standard shipping takes 3-5 business days. Express shipping is 1-2 business days.",
"password": "To reset your password, click 'Forgot Password' on the login page.",
"warranty": "Our products come with a 1-year warranty. Contact support for warranty claims.",
}
for key, value in knowledge_base.items():
if key in query.lower():
return value
return "No matching article found."
@tool
def get_order_status(order_number: str) -> str:
"""Get the status of a customer order."""
# Stand-in for a real order lookup
orders = {
"ORD123": "Shipped - Expected delivery: Tomorrow",
"ORD456": "Processing - Will ship within 24 hours",
"ORD789": "Delivered - Delivered yesterday at 2:30 PM",
}
return orders.get(order_number, "Order not found. Please check the order number.")The Annotated[list, operator.add] line deserves a second look. By default, when a node returns a key, it overwrites the old value. The annotation tells LangGraph how to merge instead. For messages you almost always want append.
Nodes
ESCALATION_TRIGGERS = [
"speak to manager", "speak to a manager", "human agent",
"not satisfied", "complaint", "cancel subscription",
]
def route_request(state: AgentState) -> str:
"""Decide where a new user message goes first."""
last_message = state["messages"][-1].content.lower()
if any(trigger in last_message for trigger in ESCALATION_TRIGGERS):
return "escalate"
return "lookup"
def lookup_node(state: AgentState):
"""Fetch whatever facts we can before the model answers."""
text = state["messages"][-1].content
order_numbers = [w.strip(".,!?") for w in text.split() if w.upper().startswith("ORD")]
if order_numbers:
result = get_order_status.invoke({"order_number": order_numbers[0].upper()})
else:
result = search_knowledge_base.invoke({"query": text})
return {"lookup_result": result}
def agent_node(state: AgentState):
"""Write the reply, using the lookup result as context."""
system_prompt = f"""You are a friendly, professional customer support agent.
Answer using this information from our systems:
{state.get("lookup_result", "Nothing found.")}
If the information does not answer the question, say so honestly and
offer to connect the customer with a human agent."""
response = llm.invoke([SystemMessage(content=system_prompt)] + state["messages"])
return {"messages": [response]}
def escalation_node(state: AgentState):
"""Hand the conversation to a person."""
message = AIMessage(
content="I'm connecting you with a human agent who can help with this. "
"Please hold for a moment while I transfer the conversation."
)
return {"messages": [message], "escalation_needed": True}Notice that none of these functions know about each other. lookup_node doesn’t call agent_node. Each one does its job and returns. The wiring lives in one place, which is the next block.
Wiring the graph
workflow = StateGraph(AgentState)
workflow.add_node("lookup", lookup_node)
workflow.add_node("agent", agent_node)
workflow.add_node("escalate", escalation_node)
# The first hop depends on what the user said
workflow.set_conditional_entry_point(
route_request,
{"lookup": "lookup", "escalate": "escalate"},
)
workflow.add_edge("lookup", "agent")
workflow.add_edge("agent", END)
workflow.add_edge("escalate", END)
app = workflow.compile()Read those six lines and you know the whole control flow. A request either goes lookup → agent → END or escalate → END. Compare that with digging through a 200-line loop to work out when the escalation branch fires.
One thing to watch for: every path must reach END. If you add an edge from agent back to lookup with no exit condition, the graph will spin until it hits the recursion limit and throws. It’s an easy mistake to make when you start adding loops.
Running it
def run_customer_support():
print("Customer support agent started. Type 'quit' to exit.\n")
state = {"messages": [], "lookup_result": "", "escalation_needed": False}
while True:
user_input = input("You: ")
if user_input.lower() == "quit":
break
state["messages"].append(HumanMessage(content=user_input))
state = app.invoke(state)
print(f"Agent: {state['messages'][-1].content}\n")
if state.get("escalation_needed"):
print("Conversation has been escalated to a human agent.")
break
if __name__ == "__main__":
run_customer_support()Try “Where is ORD123?” and then “I want to speak to a manager”. You’ll see the two paths.
A note on honesty: the routing here is keyword matching, which is fine for a tutorial and not fine for real customers. The usual next step is to bind the tools to the model with llm.bind_tools(...) and let it decide which one to call, using LangGraph’s prebuilt ToolNode to execute the calls. The graph shape stays almost the same.
A small multi-agent pipeline
“Multi-agent” sounds grand. Often it just means several nodes, each with its own prompt, passing work along. Here’s a researcher, an analyst and a writer:
from typing import List
class ResearchState(TypedDict):
query: str
research_results: List[str]
analysis: str
final_report: str
def researcher_agent(state: ResearchState):
prompt = f"""Research the topic: {state["query"]}
Give 3-5 key findings. Stick to facts and recent developments."""
response = llm.invoke([HumanMessage(content=prompt)])
return {"research_results": [response.content]}
def analyst_agent(state: ResearchState):
research = "\n".join(state["research_results"])
prompt = f"""Analyse these research findings:
{research}
Cover:
1. Key insights and patterns
2. Likely implications
3. What still needs investigating"""
response = llm.invoke([HumanMessage(content=prompt)])
return {"analysis": response.content}
def report_writer_agent(state: ResearchState):
research = "\n".join(state["research_results"])
prompt = f"""Write a short report based on:
Research findings:
{research}
Analysis:
{state["analysis"]}
Sections: Summary, Key Findings, Analysis, Recommendations."""
response = llm.invoke([HumanMessage(content=prompt)])
return {"final_report": response.content}
def create_research_workflow():
workflow = StateGraph(ResearchState)
workflow.add_node("researcher", researcher_agent)
workflow.add_node("analyst", analyst_agent)
workflow.add_node("report_writer", report_writer_agent)
workflow.set_entry_point("researcher")
workflow.add_edge("researcher", "analyst")
workflow.add_edge("analyst", "report_writer")
workflow.add_edge("report_writer", END)
return workflow.compile()
research_app = create_research_workflow()
result = research_app.invoke({"query": "How AI coding assistants are changing code review"})
print(result["final_report"])The “researcher” here only asks the model what it already knows. To make it real, give that node a search tool. The point of the example is the shape: each agent writes to its own key in the state, and the next one reads it. When the report comes out bad, you can check research_results and analysis separately and see which stage let you down.
Checkpointing: the part that matters
So far a plain script could do all of this. Checkpointing is where the graph model starts paying rent.
A checkpointer saves the state after every step, keyed by a thread ID. From that one feature you get memory, pause and resume, and the ability to rewind.
Memory across turns
from langgraph.checkpoint.memory import MemorySaver
app = workflow.compile(checkpointer=MemorySaver())
config = {"configurable": {"thread_id": "customer-42"}}
app.invoke({"messages": [HumanMessage(content="Where is ORD456?")]}, config)
app.invoke({"messages": [HumanMessage(content="And how long does shipping take?")]}, config)The second call only passes the new message. LangGraph loads the earlier state for customer-42 and appends to it. No more carrying the state dict around by hand like we did in the first example.
MemorySaver keeps everything in process memory, so it’s for development only. For production there are SQLite and Postgres checkpointers with the same interface.
Human in the loop
Say a supervisor should confirm every handoff before it happens. You tell the graph to stop before a given node:
app = workflow.compile(
checkpointer=MemorySaver(),
interrupt_before=["escalate"],
)
config = {"configurable": {"thread_id": "customer-43"}}
app.invoke({"messages": [HumanMessage(content="I have a complaint")]}, config)
# The graph is now paused. Check what it's about to do:
snapshot = app.get_state(config)
print(snapshot.next) # ('escalate',)
# A human reviews, then resumes by passing None as the input
app.invoke(None, config)Because the state is checkpointed, the pause can last a second or a week. The process can even restart in between, if you use a persistent checkpointer. Try doing that with a while loop.
Looking back in time
Every step is saved, so you can list them:
for snapshot in app.get_state_history(config):
print(snapshot.next, len(snapshot.values.get("messages", [])))Each snapshot has its own config, and you can invoke the graph from any of them to replay or branch from that point. This is brilliant for debugging. When an agent goes wrong at step six, you rerun from step five with a fix instead of starting the whole conversation over.
Things I’d do on a real project
Start with the smallest graph that works. Two or three nodes. Add branches when you have a concrete case for them, not because the diagram looks thin.
Keep nodes boring. One job each. If a node calls an LLM, parses the result, hits a database and decides the next step, split it up.
Handle LLM failures inside the node. Timeouts and rate limits will happen. Catch them, and return a state update that routes to a fallback or to escalation, so the user gets a sensible message.
Test nodes as plain functions. They’re just functions that take a dict and return a dict. You can test the routing logic and the lookup node without any LLM call at all, which keeps the test suite fast and free.
Turn on tracing early. Once a graph has loops, reading print output is miserable. LangSmith shows each node as a step, with inputs and outputs. I wrote about it here.
Wrapping up
LangGraph isn’t magic, and for a single prompt-and-response it’s overkill. Where it helps is when your agent has real control flow: branches, loops, pauses, long-lived conversations. Writing that flow down as a graph makes it visible, and checkpointing gives you memory and human approval without building them yourself.
The official LangGraph docs have good tutorials on tool calling and streaming, which are the natural next steps after this post.