Most AI agent tutorials start with a chatbot that answers questions.
That's a good starting point, but real-world AI applications need to do much more than generate text. They need to make decisions, interact with external systems, follow business rules, handle failures, and sometimes know when NOT to act without human approval.
Let's build something closer to a real production use case.
In this project, we'll build an AI-powered customer support refund agent using Python and LangGraph.
The agent will understand customer refund requests, retrieve order information, check refund eligibility, and process eligible refunds automatically.
But there's one important rule:
- Refunds below $100 can be processed automatically if they meet the business rules.
- Refunds above $100 must be reviewed and approved by a human before execution.
- Invalid or ineligible requests are escalated to the support team.
This is where LangGraph becomes particularly useful.
Instead of building one large AI prompt and hoping the model makes the right decisions, we'll design an explicit workflow where every step has a responsibility.
Let's build it.
1. What Are We Building?
Imagine a customer sends the following message:
Hi, I recently purchased a product from your store, but it doesn't work as expected. I'd like to request a refund. My order ID is ORD-1002.
Normally, a support representative would need to:
- Understand the customer's request.
- Identify whether it's a refund request.
- Retrieve the order information.
- Check whether the order is eligible for a refund.
- Determine whether approval is required.
- Process the refund or send it for manual review.
- Update the customer support ticket.
We can automate much of this workflow with an AI agent.
Here's the architecture we'll implement:
Customer Request
|
v
Classify Request
|
v
Is it a refund?
/ \
No Yes
| |
v v
Manual Support Fetch Order
|
v
Check Eligibility
|
v
Check Refund Value
/ \
Under $100 Above $100
| |
v v
Process Refund Human Approval
| |
| /-----------\
| Approve Reject
| | |
| v v
| Process Refund Stop
| |
v v
Update Ticket
|
v
END
The important part is that the LLM doesn't get unrestricted access to the payment system.
It helps us understand the customer's request, while application code and business rules determine whether a refund can proceed.
2. Why LangGraph?
We could technically implement this workflow using regular Python functions, but LangGraph gives us a structured way to manage more complex agent execution.
A few concepts are particularly useful here:
State
A shared object containing the information collected and updated throughout the workflow.
Nodes
Individual functions responsible for specific tasks, such as classifying a ticket, retrieving an order, or processing a refund.
Edges
Define which node should execute next.
Conditional Edges
Allow the workflow to take different paths depending on the current state.
Checkpointer
Persists graph state so that an execution can be resumed later.
Human-in-the-Loop
Allows us to pause execution, request approval from a human, and continue from the same point.
Think of LangGraph as a way to turn an AI workflow into an explicit, stateful application rather than a collection of disconnected LLM calls.
3. Project Setup
Let's create a new Python project.
mkdir langgraph-refund-agent
cd langgraph-refund-agent
python -m venv .venv
source .venv/bin/activate
Install the dependencies:
pip install langgraph langchain-openai typing-extensions
We'll use OpenAI's chat model for ticket classification and LangGraph for workflow orchestration.
Set your API key:
export OPENAI_API_KEY="your-openai-api-key"
Our project will initially have a simple structure:
langgraph-refund-agent/
│
├── .venv/
├── support_agent.py
└── requirements.txt
Create a requirements.txt file:
langgraph
langchain-openai
typing-extensions
For this demonstration, we'll use an in-memory order repository and a simulated payment function. Later, these can be replaced with PostgreSQL and an actual payment gateway.
4. Define the Agent State
Before creating nodes, we need to decide what information the agent needs throughout the workflow.
This is one of the most important design decisions in LangGraph.
Our agent needs to remember:
- The original customer message.
- The order ID.
- The detected ticket intent.
- The order amount.
- Whether the order is eligible for a refund.
- The human approval decision.
- The final refund status.
Let's define our state.
from typing import Any, Literal
from typing_extensions import TypedDict
class RefundState(TypedDict, total=False):
customer_message: str
order_id: str
ticket_intent: Literal[
"refund",
"order_status",
"product_question",
"other"
]
summary: str
order_found: bool
order_total: float
refund_eligible: bool
approval: dict[str, Any]
refund_status: str
refund_id: str
message: str
Every node will receive the current state and return the fields it wants to update.
For example, our classification node might return:
{
"ticket_intent": "refund",
"summary": "Customer wants a refund for a defective product."
}
The next node can access this information without making another LLM call.
One useful design principle: keep the state focused on application data. Avoid storing unnecessary prompt templates or repeatedly formatted strings in it.
5. Build the Ticket Classification Node
Our first node will understand the customer's message.
We'll use an LLM with structured output so that the classification result follows a predictable schema.
from pydantic import BaseModel
from langchain_openai import ChatOpenAI
class TicketAnalysis(BaseModel):
intent: Literal[
"refund",
"order_status",
"product_question",
"other"
]
summary: str
classifier = ChatOpenAI(
model="gpt-4o-mini",
temperature=0
).with_structured_output(TicketAnalysis)
Now let's create the LangGraph node.
def classify_ticket(state: RefundState):
result = classifier.invoke([
(
"system",
"""
You are a customer support ticket classification assistant.
Identify the customer's primary intent.
Available intents:
- refund
- order_status
- product_question
- other
Do not make financial decisions.
Only classify the request and summarize it.
"""
),
(
"human",
state["customer_message"]
)
])
return {
"ticket_intent": result.intent,
"summary": result.summary
}
Notice something important.
The LLM is responsible for understanding the request, not authorizing a payment transaction.
We should never rely solely on an LLM to determine whether a financial transaction is permitted.
That's a decision for our application logic.
6. Retrieve Order Information
Now let's create a node that retrieves the order details.
For this tutorial, we'll use a mock order repository.
In a real application, this function would query PostgreSQL or an order management API.
ORDERS = {
"ORD-1001": {
"total": 75.0,
"status": "delivered",
"already_refunded": False
},
"ORD-1002": {
"total": 250.0,
"status": "delivered",
"already_refunded": False
},
"ORD-1003": {
"total": 150.0,
"status": "pending",
"already_refunded": False
}
}
Here's our node:
def load_order(state: RefundState):
order = ORDERS.get(state["order_id"])
if not order:
return {
"order_found": False,
"refund_eligible": False
}
eligible = (
order["status"] == "delivered"
and not order["already_refunded"]
)
return {
"order_found": True,
"order_total": order["total"],
"refund_eligible": eligible
}
This node does not need an LLM.
It's a regular Python function performing a deterministic operation.
That's another important lesson when building AI agents: not every step needs artificial intelligence.
Use an LLM for language understanding and regular application code for predictable business logic.
7. Implement Conditional Routing
Now comes the interesting part.
Based on the order details, our graph needs to decide what should happen next.
We'll define a refund threshold:
AUTO_REFUND_LIMIT = 100.0
Our routing function:
def route_after_classification(state: RefundState):
if state["ticket_intent"] == "refund":
return "load_order"
return "manual_queue"
Next, we'll decide what happens after retrieving the order.
def route_after_order(state: RefundState):
if not state.get("order_found"):
return "manual_queue"
if not state.get("refund_eligible"):
return "manual_queue"
if state["order_total"] > AUTO_REFUND_LIMIT:
return "human_approval"
return "execute_refund"
This gives us three possible outcomes:
Scenario 1: Invalid order
The request goes to the support team.
Scenario 2: Eligible order below $100
The refund is processed automatically.
Scenario 3: Eligible order above $100
The workflow pauses and requests human approval.
Notice how we're using conditional routing to make these decisions.
This is exactly where LangGraph becomes useful. We can explicitly define how the application should behave instead of hiding the entire workflow inside a single prompt.
8. Implement Human-in-the-Loop Approval
This is the most interesting part of the project.
Let's assume a customer requests a $250 refund.
Our application has already verified that the order exists and is eligible.
However, because the amount exceeds our automatic refund threshold, the agent must not process it immediately.
Instead, it should wait for a human decision.
LangGraph provides the interrupt() function for this.
from langgraph.types import interrupt
def human_approval(state: RefundState):
decision = interrupt({
"type": "refund_approval",
"order_id": state["order_id"],
"refund_amount": state["order_total"],
"customer_message": state["customer_message"],
"message": "Human approval is required before processing this refund."
})
return {
"approval": decision
}
What happens here?
When this node executes, LangGraph pauses the workflow and exposes the approval request to the calling application.
Our support dashboard could display something like:
{
"type": "refund_approval",
"order_id": "ORD-1002",
"refund_amount": 250.0,
"message": "Human approval is required before processing this refund."
}
A support representative can now review the request.
They can either approve or reject it.
The important thing is that the graph doesn't need to restart from the beginning after the human responds.
It can resume from the interrupted execution.
Let's define our next routing function:
def route_after_approval(state: RefundState):
approval = state.get("approval", {})
if approval.get("approved") is True:
return "execute_refund"
return "refund_rejected"
And our rejection node:
def refund_rejected(state: RefundState):
return {
"refund_status": "rejected",
"message": "Refund request was rejected by the support team."
}
One important implementation detail: keep side effects out of the approval node before calling interrupt().
LangGraph re-executes the interrupted node from its beginning when resuming. That means anything before the interrupt can run again.
Our approval node only prepares an approval request, so it is safe to resume.
9. Execute the Refund
Now let's create the final execution node.
For this demonstration, we'll simulate a payment gateway response.
def issue_refund(order_id: str, amount: float, idempotency_key: str):
print(f"Processing refund for {order_id}")
print(f"Refund amount: ${amount}")
# Simulated payment gateway response.
# Replace this with your payment provider integration.
# Use the idempotency key to prevent duplicate refunds.
return f"demo-refund-{order_id}"
Our LangGraph node:
def execute_refund(state: RefundState):
refund_id = issue_refund(
order_id=state["order_id"],
amount=state["order_total"],
idempotency_key=f"refund:{state['order_id']}"
)
return {
"refund_status": "processed",
"refund_id": refund_id,
"message": "Refund processed successfully."
}
In production, the payment gateway should enforce idempotency using the refund request identifier.
You should also update your order database transactionally, maintain an audit trail, and ensure that concurrent requests cannot issue duplicate refunds.
For a financial workflow, these safeguards matter just as much as the AI logic.
10. Connect Everything Using StateGraph
We now have all our individual nodes.
Let's connect them.
from langgraph.graph import StateGraph, START, END
from langgraph.checkpoint.memory import InMemorySaver
def manual_queue(state: RefundState):
return {
"refund_status": "manual_review",
"message": "This request requires manual support review."
}
def build_graph():
builder = StateGraph(RefundState)
# Register nodes
builder.add_node("classify_ticket", classify_ticket)
builder.add_node("load_order", load_order)
builder.add_node("manual_queue", manual_queue)
builder.add_node("human_approval", human_approval)
builder.add_node("execute_refund", execute_refund)
builder.add_node("refund_rejected", refund_rejected)
# Entry point
builder.add_edge(START, "classify_ticket")
# Route after classification
builder.add_conditional_edges(
"classify_ticket",
route_after_classification,
{
"load_order": "load_order",
"manual_queue": "manual_queue"
}
)
# Route after order lookup
builder.add_conditional_edges(
"load_order",
route_after_order,
{
"manual_queue": "manual_queue",
"human_approval": "human_approval",
"execute_refund": "execute_refund"
}
)
# Route after human approval
builder.add_conditional_edges(
"human_approval",
route_after_approval,
{
"execute_refund": "execute_refund",
"refund_rejected": "refund_rejected"
}
)
# End nodes
builder.add_edge("manual_queue", END)
builder.add_edge("execute_refund", END)
builder.add_edge("refund_rejected", END)
# Add persistence
checkpointer = InMemorySaver()
return builder.compile(
checkpointer=checkpointer
)
We've now connected the entire workflow.
The graph consists of:
- One LLM-based classification node.
- One order lookup node.
- Conditional routing logic.
- One human approval node.
- One refund execution node.
- One manual support escalation node.
The graph is explicit, modular, and easier to test than a single large agent function.
11. Run the Agent
Let's test it with a high-value refund request.
from langgraph.types import Command
app = build_graph()
config = {
"configurable": {
"thread_id": "refund-ticket-2002"
}
}
initial_state = {
"customer_message": """
Hi, I recently purchased a product, but it is defective.
I would like to request a refund.
""",
"order_id": "ORD-1002"
}
# First execution
result = app.invoke(
initial_state,
config=config
)
# The graph should be paused for human approval
pending_approval = result["__interrupt__"][0]
print("Approval required:")
print(pending_approval.value)
At this point, the graph has completed the classification and order lookup steps.
It has also verified that the order is eligible.
But it has not processed the refund.
Instead, it is waiting for human input.
Let's say the support representative reviews the request and approves it.
We can resume the graph:
final_result = app.invoke(
Command(
resume={
"approved": True,
"note": "Reviewed and approved by support manager."
}
),
config=config
)
print(final_result["refund_status"])
print(final_result["refund_id"])
The same thread_id is used when resuming the workflow.
This is important because LangGraph uses that identifier to retrieve the saved execution state.
We don't need to repeat the original customer message, classification, or order lookup.
We simply provide the human decision, and execution continues.
12. What About Small Refunds?
Let's test our other scenario.
A customer requests a refund for order ORD-1001, which has a value of $75.
Since the order is eligible and its value is below our $100 threshold, the graph will automatically route it to the execution node.
small_refund_config = {
"configurable": {
"thread_id": "refund-ticket-1001"
}
}
result = app.invoke(
{
"customer_message": "I would like a refund for my defective product.",
"order_id": "ORD-1001"
},
config=small_refund_config
)
print(result["refund_status"])
print(result["refund_id"])
Expected output:
Processing refund for ORD-1001
Refund amount: $75.0
processed
demo-refund-ORD-1001
No human approval was required.
That's the workflow we wanted.
We have built an agent that can understand requests, make deterministic routing decisions, perform actions, and pause when human intervention is necessary.
13. What Makes This Useful in a Real Application?
The example above uses a mock order repository and a simulated payment gateway, but the architecture can be extended into a real customer support platform.
Here are some natural improvements.
Replace the Mock Order Repository
Connect the load_order node to PostgreSQL or an existing order management API.
Retrieve:
- Order amount.
- Payment status.
- Delivery status.
- Refund history.
- Customer information.
- Return eligibility.
The refund amount should always come from a trusted backend, never from the customer's message or an LLM-generated response.
Integrate a Real Payment Gateway
Replace the simulated issue_refund() function with a payment provider API.
Implement:
- Idempotency keys.
- Duplicate refund protection.
- Transaction records.
- Retry handling.
- Payment status verification.
Build a Support Dashboard
Create a React application where support representatives can:
- View pending refund approvals.
- Inspect customer messages.
- Review order information.
- Approve or reject refunds.
- Add internal notes.
- View execution history.
The frontend can communicate with a FastAPI backend that manages LangGraph execution and resumes interrupted workflows.
Use Persistent Checkpointing
Our example uses InMemorySaver.
This is convenient for local development, but it stores checkpoints in RAM. Checkpoints are lost when the process restarts.
For a real application, use a persistent checkpointer such as PostgreSQL-backed PostgresSaver.
This is especially important when human approval might take minutes, hours, or days.
Add Observability
Once the workflow becomes more complex, debugging individual agent steps becomes important.
Integrate LangSmith to inspect:
- LLM inputs and outputs.
- Node execution.
- Workflow transitions.
- Errors and retries.
- Execution latency.
- Token usage.
This makes it much easier to understand what happened when an agent produces an unexpected result.
14. What Did We Actually Learn?
The interesting part of this project isn't the refund function itself.
It's how we designed the entire execution flow.
We used LangGraph to solve several real application problems:
State Management
All nodes share a common state, allowing us to maintain context throughout the workflow.
Conditional Execution
We used conditional edges to decide which path should execute based on business rules.
Human-in-the-Loop
We used interrupt() to pause an agent before executing a sensitive financial operation.
Persistence
We used a checkpointer and thread_id to preserve execution state and resume the workflow.
Separation of Responsibilities
We kept LLM reasoning separate from deterministic operations such as order verification and payment execution.
These are the kinds of design patterns that make agentic applications much more useful than simple conversational chatbots.
Conclusion
AI agents become interesting when they start interacting with real applications and business processes.
A customer support refund agent is a small example, but the same architectural approach can be applied to invoice approvals, payment processing, insurance claims, expense management, subscription cancellations, and many other workflows.
The bigger lesson is this:
Don't give an LLM unrestricted control over your application. Build a workflow around it, define clear boundaries, validate important decisions, and introduce human approval wherever necessary.
That's where LangGraph really shines.
Want to Build More LangGraph Projects?
I have also created a practical, hands-on Udemy course where we build an AI-powered customer support agent using LangGraph, Python, and Human-in-the-Loop (HITL).
Instead of only discussing concepts, the course walks through building an actual agentic workflow.
You can check it out here:
Build AI Agents with LangGraph: Customer Support & Human-in-the-Loop
If you're learning LangGraph and want to move beyond basic chatbot examples, this is a good project to explore.
Top comments (0)