LangGraph Example: Building Multi-Step AI Workflows

By upGrad

Updated on Jan 30, 2026 | 8 min read | 1.7K+ views

Share:

LangGraph creates stateful, multi-actor applications by modeling agent workflows as graphs with nodes that represent functions or tools and edges that define control flow. 

For example, a question-answering assistant can start with a user's query, generate an answer, route it to a review node, and loop back for improvement if the response is weak. The workflow only exits when quality checks pass, ensuring reliable and consistent outputs across steps. 

In this blog, you will see a clear LangGraph example, understand how nodes, edges, and state work together, and learn how to design simple multi-step AI workflows using practical patterns. 

Build practical skills for designing multi-step AI systems with upGrad’s Generative AI and Agentic AI courses. Learn how to structure agent workflows, manage state, and apply graph-based reasoning to build reliable AI applications used in real-world scenarios. 

Basic LangGraph Example with Agent and Tool Interaction 

Below is a simplified LangGraph example that shows how an AI agent can decide when to use a tool, act on the result, and loop back until it produces a final answer. The structure is similar to real-world agent workflows but kept easy to follow. 

Get ready for real-world Agentic AI roles with the Executive Post Graduate Programme in Generative AI and Agentic AI by IIT Kharagpur and build hands-on experience. 

What this example does 

  • Accepts a user question 
  • Let's an agent decide whether it needs a tool 
  • Calls the tool if required 
  • Loops back to the agent with updated context 
  • Stops when no further action is needed 

Simplified LangGraph Example Code 

from langgraph.graph import StateGraph, END 
from typing import TypedDict, Annotated, List 
import operator 
 
from langchain_core.messages import BaseMessage, HumanMessage 
from langchain_openai import ChatOpenAI 
from langgraph.prebuilt import ToolNode 
 
# Define shared state 
class GraphState(TypedDict): 
    messages: Annotated[List[BaseMessage], operator.add] 
 
# Define a simple tool 
def lookup_weather(city: str): 
    return f"The weather in {city} is sunny." 
 
tools = [lookup_weather] 
tool_node = ToolNode(tools) 
 
# Initialize model with tool support 
llm = ChatOpenAI(model="gpt-4o-mini").bind_tools(tools) 
 
# Agent node logic 
def agent_step(state: GraphState): 
    response = llm.invoke(state["messages"]) 
    return {"messages": [response]} 
 
# Decide next step 
def route_decision(state: GraphState): 
    last_msg = state["messages"][-1] 
    if last_msg.tool_calls: 
        return "tool" 
    return END 
 
# Build the graph 
graph = StateGraph(GraphState) 
graph.add_node("agent", agent_step) 
graph.add_node("tool", tool_node) 
 
graph.set_entry_point("agent") 
graph.add_conditional_edges("agent", route_decision) 
graph.add_edge("tool", "agent") 
 
app = graph.compile() 
 
# Run the workflow 
result = app.invoke( 
    {"messages": [HumanMessage(content="What is the weather in London?")]} 
) 
 
print(result["messages"][-1].content) 
 

This LangGraph example clearly shows how reasoning, tool usage, and control flow come together to create reliable, multi-step AI behavior. 

Also Read: What Is Agentic AI? The Simple Guide to Self-Driving Software 

Understanding the Workflow Logic in This LangGraph Example 

This LangGraph example follows a clear, step-by-step workflow where each part has a defined role. The graph controls how the AI moves from one step to the next based on decisions made during execution. 

How the workflow starts 

  • A user question enters the graph 
  • The message is stored in shared state under messages 
  • This state is accessible to every node in the workflow 

What the agent node does 

  • Reads the current messages from state 
  • Sends them to the language model 
  • Decides whether it can answer directly or needs a tool 
  • Appends its response back to the state 

Also Read: 10+ Real Agentic AI Examples Across Industries (2026 Guide) 

How routing decisions are made 

  • The graph checks the last agent response 
  • If a tool call is requested, execution moves to the tool node 
  • If no tool is needed, the workflow stops 

What the tool node handles 

  • Runs the external function, such as weather lookup 
  • Adds the tool output to the shared state 
  • Routes execution back to the agent node 

Also Read: Types of Agents in AI: A Complete Guide to How Intelligent Agents Work 

When the workflow ends 

  • The agent produces a final response 
  • No tool call is present in the last message 
  • The graph reaches the end state and exits 

Overall flow 

  • User input → Agent reasoning 
  • Conditional decision → Tool execution if required 
  • Updated context → Agent refinement 
  • Final answer → Workflow completion 

This structure keeps the logic easy to follow while allowing the AI to reason, act, and improve its response in a controlled loop. 

Also Read: Agentic AI vs Generative AI: What Sets Them Apart 

Designing Clear Multi-Step AI Workflows in LangGraph 

This LangGraph example builds a two-step reasoning workflow: 

  • The model generates an answer 
  • The answer is validated 
  • If validation fails, the model retries 
  • The workflow exits only when validation passes 

Step 1: Define the shared state 

The state tracks the question and the generated answer. 

from typing import TypedDict 
from langgraph.graph import StateGraph, END 
 
class QAState(TypedDict): 
    question: str 
    answer: str 
 

Why this state works 

  • Keeps data minimal 
  • Easy to inspect 
  • Clear responsibility 

Also Read: What Is the BERT Model? 

Step 2: Create the answer generation node 

This node produces an answer to the question. 

from langchain_openai import ChatOpenAI 
 
llm = ChatOpenAI(model="gpt-4o-mini") 
 
def generate_answer(state: QAState): 
    response = llm.invoke(state["question"]) 
    return {"answer": response.content} 

Step 3: Create the validation node 

This node checks if the answer meets a simple condition. 

def validate_answer(state: QAState): 
    if len(state["answer"]) < 50: 
        return "retry" 
    return END 

Validation rule 

  • Too short → retry 
  • Long enough → finish 

Also Read: Hugging Face Model: Beginner Guide to Using Pretrained AI Models 

Step 4: Build the graph 

Connect nodes using conditional logic. 
graph = StateGraph(QAState) 
 
graph.add_node("generate", generate_answer) 
graph.set_entry_point("generate") 
 
graph.add_conditional_edges( 
    "generate", 
    validate_answer, 
    { 
        "retry": "generate", 
        END: END 
    } 
) 
 
app = graph.compile() 

Step 5: Run the workflow 

result = app.invoke( 
    {"question": "Explain LangGraph in simple terms."} 
) 
 
print(result["answer"]) 

How This Workflow Runs 

  • Question enters the graph 
  • Answer is generated 
  • Length is checked 
  • If weak, the model retries 
  • Workflow exits only when valid 

Also Read: Top 15 Agentic AI Books for Beginners to Advanced Learners 

Why This LangGraph Example Is Useful 

  • Shows looping without tools 
  • Demonstrates conditional exit logic 
  • Easy to extend with scoring, rules, or reviewers 
  • Perfect for beginners learning control flow 

This LangGraph example highlights how LangGraph helps you design clear, self-correcting, multi-step AI workflows without relying on complex agent setups. 

Also Read: Top Agentic AI Tools in 2026 for Automated Workflows 

Conclusion 

LangGraph makes it easier to build AI systems that think in steps instead of responding in a single pass. By modeling workflows as graphs, it gives you clear control over execution, state, and decision paths. 

Through practical LangGraph examples, you can see how agents reason, retry, and improve outputs in a structured way. Learning to design these multi-step workflows helps you build more reliable, maintainable, and real-world–ready AI applications. 

Take the next step in your Generative AI journey by booking a free counseling session. Get personalized guidance from our experts and learn how to build practical skills for real-world AI roles.

Frequently Asked Questions (FAQs)

1. What is a LangGraph example used for?

It is used to show how AI workflows can be designed as graphs instead of linear steps. The example helps explain how reasoning, decision-making, retries, and state management work together in structured, multi-step AI systems. 

2. How does a LangGraph example help beginners understand AI workflows?

It breaks complex reasoning into clear steps. By showing nodes, edges, and execution flow, beginners can see how decisions are made, how data moves between steps, and why structured control improves reliability over single prompt approaches. 

3. What is a LangGraph example in Python?

A Python-based example demonstrates how to define state, nodes, and control flow using code. It helps developers understand how multi-step reasoning can be implemented programmatically while keeping execution predictable and easy to debug. 

4. What is a LangGraph example agent?

It shows how an agent operates inside a graph-based workflow. The agent reads shared state, produces outputs, and decides what to do next. This makes agent behavior more controlled compared to free-form prompt-driven execution. 

5. What is a LangGraph multi agent example?

A multi-agent example demonstrates how different agents collaborate within the same workflow. Each agent handles a specific role, such as generating or reviewing responses, while the graph coordinates execution and manages shared state between them. 

6. How does control flow work in a LangGraph example?

Control flow is managed through edges that connect nodes. These edges can be conditional, allowing the workflow to branch, loop, or exit based on intermediate results rather than following a fixed sequence. 

7. Why are loops important in LangGraph workflows?

Loops allow workflows to retry steps, refine outputs, or validate results before continuing. This makes AI systems more robust by ensuring that weak or incomplete responses are improved instead of being returned immediately. 

8. How is state handled across steps in LangGraph?

State acts as shared memory for the workflow. Each node can read and update it, allowing decisions to be based on previous outputs. This persistence is essential for multi-step reasoning and controlled execution. 

9. When should you use LangGraph instead of simple chains?

You should use it when tasks require decisions, retries, or validation. Simple chains work straightforward flows, but graphs are better suited for workflows that need branching logic and predictable control over execution. 

10. Can LangGraph workflows scale to real-world applications?

Yes. The structured design makes it easier to maintain and extend. As workflows grow, clear nodes and explicit control paths help manage complexity without turning logic into hard-to-debug prompt chains. 

11. Is learning LangGraph useful for building AI agents?

Yes. It teaches how to design agents that behave consistently across steps. Understanding graph-based workflows helps developers build AI systems for that reason, act, and self-correct in a controlled and reliable manner. 

upGrad

620 articles published

We are an online education platform providing industry-relevant programs for professionals, designed and delivered in collaboration with world-class faculty and businesses. Merging the latest technolo...

Get Free Consultation

+91

By submitting, I accept the T&C and
Privacy Policy