<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Shubham Nagar on Medium]]></title>
        <description><![CDATA[Stories by Shubham Nagar on Medium]]></description>
        <link>https://medium.com/@shubhamnagar234?source=rss-10b51a93c3a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*G0jc4Q2X6eAoQQSMAfb1ag.jpeg</url>
            <title>Stories by Shubham Nagar on Medium</title>
            <link>https://medium.com/@shubhamnagar234?source=rss-10b51a93c3a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 14:58:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@shubhamnagar234/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Streaming in LangGraph: Building Real-Time AI Chatbots with Streamlit — Part 12]]></title>
            <link>https://medium.com/@shubhamnagar234/streaming-in-langgraph-building-real-time-ai-chatbots-with-streamlit-part-12-915a7e590c3b?source=rss-10b51a93c3a------2</link>
            <guid isPermaLink="false">https://medium.com/p/915a7e590c3b</guid>
            <category><![CDATA[chatbots]]></category>
            <category><![CDATA[streamlit]]></category>
            <category><![CDATA[streaming]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[langgraph]]></category>
            <dc:creator><![CDATA[Shubham Nagar]]></dc:creator>
            <pubDate>Sun, 29 Nov 2026 16:34:47 GMT</pubDate>
            <atom:updated>2026-11-29T16:35:09.578Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Learn how to implement token-by-token streaming in LangGraph and Streamlit to build faster, more responsive, and interactive AI chatbots.</blockquote><p>In the previous part, we built a context-aware chatbot using <strong>LangGraph and Streamlit</strong>. We connected our LangGraph backend with a Streamlit frontend, managed conversation history using st.session_state, and used a checkpointer to maintain conversational context.</p><p>However, there’s one important user experience problem we haven’t addressed yet.</p><blockquote><strong>Our chatbot waits for the entire AI response to be generated before displaying anything on the screen.</strong></blockquote><p>Imagine asking your chatbot to write a 500-word blog post about cricket in India. The screen stays blank for several seconds while the LLM generates the complete response. Once generation finishes, the entire answer appears at once.</p><p>This waiting experience can make an application feel slow or unresponsive, especially when generating long responses.</p><p>What if we could display the response as soon as the model starts generating it, showing the text gradually, just like someone typing?</p><blockquote>That’s where <strong>Streaming</strong> comes in!</blockquote><p>In this part, we’ll learn how streaming works in LangGraph and upgrade our existing Streamlit chatbot to display AI responses in real time using LangGraph’s .stream() method and Streamlit&#39;s st.write_stream() function.</p><p>By the end of this tutorial, our chatbot will generate responses with a smooth, typewriter-like effect while maintaining its conversation history.</p><h3>Overview</h3><ul><li><strong>What is Streaming?</strong></li><li><strong>Why Streaming?</strong></li><li><strong>Chat Interface in Streamlit (with Streaming)</strong></li><li><strong>Project Architecture</strong></li><li><strong>Step-by-Step Guide</strong></li><li><strong>1. Building the Backend (</strong><strong>langgraph_backend.py)</strong></li><li><strong>2. Building the Frontend (</strong><strong>streamlit_frontend_streaming.py)</strong></li><li><strong><em>Final Thoughts</em></strong></li><li><strong><em>Key Takeaways</em></strong></li><li><strong><em>Conclusion</em></strong></li><li><strong><em>What’s Next?</em></strong></li></ul><h3>What is Streaming?</h3><p>In Large Language Models (LLMs), <strong>streaming</strong> means the model starts sending its response in small chunks as soon as they are generated, instead of waiting for the entire response to be completed before returning it.</p><p>Normally, when we send a prompt to an LLM, it processes the input, generates the complete response, and then returns it all at once.</p><p>With streaming, the model sends the generated output progressively. This means users don’t have to wait for the entire response to be ready.</p><p>Instead of seeing a blank screen for several seconds, users see a real-time, typewriter-like effect where the response appears gradually, word by word (or token by token).</p><p><strong>In simple terms:</strong></p><ul><li><strong>Without Streaming:</strong> The LLM generates the complete response first and displays it all at once.</li><li><strong>With Streaming:</strong> The LLM sends the response in chunks as it generates them, allowing the UI to display the content progressively.</li></ul><p>This makes AI applications feel faster, more responsive, and more interactive, especially when generating long responses.</p><h3>Why Streaming?</h3><p>Streaming is crucial for building responsive and user-friendly LLM-based applications. It significantly improves the user experience by making conversations feel more natural and preventing the application from appearing frozen during long generation times.</p><p>Let’s understand this with an example.</p><p>Imagine asking our chatbot to write a 500-word blog post about cricket in India.</p><p>There are two ways the chatbot can handle this request:</p><h4>1. Standard Response (The Problem)</h4><p>Without streaming, the chatbot waits for the LLM to generate the entire response before displaying anything on the screen.</p><p>For example:</p><ol><li>The user sends a prompt.</li><li>The LLM starts generating the response.</li><li>The screen remains blank for several seconds.</li><li>Once the entire response is ready, it appears all at once.</li></ol><p>This creates a poor user experience because the user has to wait without receiving any feedback. It can also be difficult to read a large block of text that appears all at once.</p><h4>2. Streaming Response (The Solution)</h4><p>With streaming enabled, the chatbot starts displaying the response as soon as the LLM begins generating it.</p><p>For example:</p><ol><li>The user sends a prompt.</li><li>The LLM starts generating the response.</li><li>The chatbot displays the generated text progressively, token by token.</li><li>The response continues appearing in real time until generation is complete.</li></ol><p>This creates a smooth, typewriter-like effect. The user can start reading the response immediately instead of waiting for the entire output.</p><h4>Key Benefits of Streaming</h4><p>Let’s look at the major benefits:</p><ul><li><strong>Faster Perceived Response Time:</strong> Users don’t have to wait for the complete answer. The response starts appearing as soon as the model begins generating it.</li><li><strong>Human-Like Conversation:</strong> Streaming makes interactions feel more natural, alive, and engaging, similar to having a real-time conversation.</li><li><strong>Better UX for Long Outputs:</strong> When generating long content, such as 500-word essays or code, streaming keeps users engaged and makes the response easier to follow as it appears.</li><li><strong>Cost &amp; Control:</strong> If users change their minds or notice that the response is going in the wrong direction, they can stop generation midway, potentially saving tokens and time.</li></ul><h4>Understanding Generators in Python</h4><p>Before implementing streaming in our LangGraph chatbot, there’s one important Python concept we should understand: <strong>Generators</strong>.</p><p>In Python, a generator is a special type of iterator that allows us to generate values on the fly, one at a time, using the yield keyword instead of return.</p><p>Generators are useful when working with streaming because they allow us to process and consume data incrementally rather than waiting for all the values to be generated first.</p><p>We’ll use this concept when extracting response chunks from LangGraph and passing them to Streamlit for real-time display.</p><h3>Chat Interface in Streamlit (with Streaming)</h3><p>Now that we understand what streaming is and why it matters, let’s see how we can implement it in our Streamlit chatbot.</p><blockquote>Streamlit provides a built-in function called <strong>st.write_stream()</strong>, which makes displaying streaming responses incredibly simple.</blockquote><h4>Chat Write (st.write_stream())</h4><p>The st.write_stream() function takes a stream or generator as input and automatically displays the generated content with a typewriter-like effect.</p><p>Instead of waiting for the complete AI response, it renders the incoming text chunks progressively as they arrive.</p><p>In our chatbot, we’ll use st.write_stream() to display the AI&#39;s response in real time.</p><figure><img alt="A Streamlit chat interface showing an AI assistant response appearing gradually with a typewriter-like effect." src="https://cdn-images-1.medium.com/max/1024/1*hZNhxUrex6Xi5c3caiQQ4A.png" /><figcaption><em>Streamlit chatbot interface displaying an AI-generated response progressively using the streaming feature.</em></figcaption></figure><p>We’ll integrate this function with LangGraph’s .stream() method in the upcoming implementation, allowing our chatbot to generate and display responses in real time.</p><h3>Project Architecture</h3><p>Before implementing streaming, let’s understand how the existing chatbot architecture will change. The good news is that <strong>we don’t need to redesign the backend</strong>. LangGraph already supports streaming, so most of our changes will happen in the frontend.</p><h4>Plan of Action</h4><p>We will make changes in two main parts:</p><p><strong>1. Back-End (</strong><strong>langgraph_backend.py)</strong></p><p>The backend will remain largely the same. It will continue to define:</p><ul><li>The chatbot state.</li><li>The LLM node responsible for generating responses.</li><li>The LangGraph workflow and its execution flow.</li></ul><p>LangGraph natively supports streaming, so we don’t need to make structural changes to our existing graph. We will simply use its .stream() method when we want to receive the response in chunks.</p><p><strong>2. Front-End (</strong><strong>streamlit_frontend_streaming.py)</strong></p><p>The main changes will happen in the Streamlit frontend.</p><p>Instead of using the backend’s .invoke() method, which waits for the complete response, we will switch to .stream() to receive response chunks as they are generated.</p><p>We will also use Streamlit’s st.write_stream() method to display those chunks in the chat interface with a typewriter effect.</p><figure><img alt="Architecture diagram showing the LangGraph backend remaining largely unchanged while the Streamlit frontend uses .stream() and st.write_stream() to display AI responses in real time." src="https://cdn-images-1.medium.com/max/1024/1*OSeHO_GQF4Ja84Lyu5dgAw.png" /><figcaption><em>Project architecture and plan of action for implementing streaming in LangGraph and Streamlit.</em></figcaption></figure><h4>Execution Steps</h4><p>We will follow these steps to implement streaming:</p><ol><li><strong>Understand the Change:</strong> Learn how chatbot.stream() differs from chatbot.invoke() and how it delivers response chunks.</li><li><strong>Implement Generator:</strong> Create a generator that extracts text tokens from the LangGraph stream and yields them one by one.</li><li><strong>UI Rendering:</strong> Use Streamlit’s st.write_stream() to render the generated text progressively with a typewriter effect.</li><li><strong>Maintain Memory:</strong> After streaming completes, save the fully assembled AI response to st.session_state so it remains available in the chat history.</li></ol><p>With this approach, we can introduce real-time streaming while keeping our existing chatbot architecture simple and familiar.</p><h3>Step-by-Step Guide</h3><p>Let’s now implement streaming in our existing LangGraph and Streamlit chatbot. We will keep the backend structure almost identical to the previous part and focus on how to stream the LLM response to the frontend.</p><h3>1. Building the Backend (langgraph_backend.py)</h3><p>In this section, we’ll build the backend of our chatbot using <strong>LangGraph, Gemini 2.5 Flash, and InMemorySaver</strong>.</p><p>The backend will handle all the core conversational logic and provide an executable chatbot workflow that our Streamlit frontend can interact with.</p><h4>What We’re Building</h4><p>We’re building a stateful chatbot backend using:</p><ul><li><strong>Large Language Model (LLM):</strong> Gemini 2.5 Flash to understand user messages and generate AI responses.</li><li><strong>LangGraph:</strong> To organize and execute the conversational workflow.</li><li><strong>InMemorySaver:</strong> To enable persistence (checkpointing) and maintain conversation history.</li></ul><p>This backend will:</p><ul><li>Take a <strong>user message</strong> as input and append it to the chat history.</li><li>Pass the conversation context to the LLM to generate an <strong>AI response</strong>.</li><li>Save the entire conversation as persistent state under a thread_id.</li><li>Serve as the brain for our Streamlit frontend to power a real-time chat interface.</li></ul><figure><img alt="Workflow illustration showing the LangGraph chatbot backend receiving user messages, processing conversation history through an LLM, and returning AI responses with persistence enabled." src="https://cdn-images-1.medium.com/max/1024/1*8mxgmJ46wW3KOpRo182Y0g.png" /><figcaption><em>Code workflow for building a streaming chatbot using LangGraph and Streamlit.</em></figcaption></figure><h4>Understanding the Workflow: A Visual Breakdown</h4><p>Before writing the code, let’s understand how the backend workflow operates.</p><p><strong>START</strong></p><ul><li>The workflow begins here — this is the entry point where the user’s message history is received.</li></ul><p><strong>chat_node</strong></p><ul><li>Extracts the current list of messages from the state.</li><li>Passes the messages to the LLM to generate a response.</li><li>Returns the updated list containing the new AI response, which is appended to the state.</li></ul><p><strong>END</strong></p><ul><li>This is where the workflow ends. At this point, the final response is generated and returned to the frontend.</li></ul><p>The workflow follows a simple sequential execution pattern:</p><blockquote><strong><em>START</em> → </strong><strong><em>chat_node</em> → </strong><strong><em>END</em></strong></blockquote><p>Now, let’s implement each part of the backend step by step.</p><h4>1. Import &amp; Setup</h4><p>First, let’s import all the necessary modules and components required to build our LangGraph chatbot.</p><pre># If using ChatOpenAI<br># from langchain_openai import ChatOpenAI<br><br># If using ChatGoogleGenerativeAI<br>from langchain_google_genai import ChatGoogleGenerativeAI<br><br>from langgraph.graph import StateGraph, START, END<br>from typing import TypedDict, Annotated<br>from langchain_core.messages import BaseMessage<br>from langgraph.checkpoint.memory import InMemorySaver<br>from langgraph.graph.message import add_messages<br>from dotenv import load_dotenv</pre><p>Let’s understand the purpose of these imports:</p><ul><li><strong>Essential Imports:</strong> We import the necessary modules from LangGraph, LangChain, and Python’s typing module to define our chatbot&#39;s state and structure the workflow.</li><li><strong>LLM Integration:</strong> We import ChatGoogleGenerativeAI to connect our chatbot with Google&#39;s Gemini models. If you prefer OpenAI, you can use ChatOpenAI instead.</li><li><strong>Core LangGraph Components:</strong> We import StateGraph, START, and END to create and define the execution flow of our chatbot.</li><li><strong>State Definition:</strong> We use TypedDict and Annotated to define the chatbot&#39;s state, while BaseMessage represents the messages stored in the conversation.</li><li><strong>Message Management:</strong> We import add_messages, which will help us append new messages to the existing conversation history.</li><li><strong>Persistence:</strong> We import InMemorySaver from langgraph.checkpoint.memory. It acts as a checkpointer that saves workflow state in memory (RAM), allowing the chatbot to maintain conversation context for a thread during execution.</li><li><strong>Environment Configuration:</strong> We import load_dotenv to load environment variables from a .env file.</li></ul><p>These imports provide the foundation for defining our chatbot’s state, connecting the LLM, building the LangGraph workflow, and enabling in-memory persistence.</p><h4>2. Configure Environment Variables</h4><p>Next, we need to configure the environment variables required to connect our chatbot to the LLM provider.</p><p>First, call load_dotenv() to load the environment variables defined in the .env file.</p><pre>load_dotenv()</pre><p>Let’s understand what’s happening:</p><ul><li><strong>API Keys:</strong> We define our API keys in a .env file. For this project, we can use GEMINI_API_KEY for Google Gemini or OPENAI_API_KEY if we&#39;re using OpenAI.</li><li><strong>Environment Setup:</strong> The load_dotenv() function loads the variables from the .env file into the application&#39;s environment so the LLM integration can access the required credentials.</li><li><strong>Authentication:</strong> These API keys allow our application to authenticate with the selected LLM provider when making API requests.</li></ul><p>Make sure your .env file is configured with the appropriate API key before running the application. Keep this file private and never commit it to a public Git repository.</p><h4>3. Initialize the LLM</h4><p>Now, let’s initialize the Large Language Model (LLM) that will power our chatbot.</p><p>We’ll use Google’s Gemini 2.5 Flash model for this project.</p><pre># If using ChatOpenAI<br># Initialize ChatOpenAI<br># llm = ChatOpenAI(model=&quot;gpt-4o-mini&quot;)<br><br># If using ChatGoogleGenerativeAI<br># Initialize ChatGoogleGenerativeAI<br>llm = ChatGoogleGenerativeAI(model=&quot;gemini-2.5-flash&quot;)</pre><p>Let’s understand what’s happening:</p><ul><li><strong>Model Initialization:</strong> We initialize ChatGoogleGenerativeAI with the gemini-2.5-flash model. This model acts as the brain of our chatbot, processing conversation messages and generating responses.</li><li><strong>Flexibility:</strong> The commented-out ChatOpenAI implementation provides an alternative if you want to use OpenAI instead. You can switch providers by uncommenting the relevant code and configuring the corresponding API key.</li></ul><p>The llm object is now ready to be used inside our LangGraph node, where it will process the conversation history and generate the chatbot&#39;s response.</p><h4>4. Define the State (ChatState)</h4><p>Now, let’s define the state schema that will store our chatbot’s conversation history.</p><pre># Define the state class<br>class ChatState(TypedDict):<br>    messages: Annotated[list[BaseMessage], add_messages]</pre><p>Let’s understand what’s happening:</p><ul><li><strong>State Schema:</strong> We define ChatState using TypedDict. It contains a messages field, which stores a list of BaseMessage objects representing the conversation.</li><li><strong>Message Management:</strong> The Annotated type associates the message list with the add_messages reducer. This ensures that new messages are appended to the existing conversation history rather than simply replacing it.</li><li><strong>Shared Memory:</strong> The state is shared across the nodes in the workflow. Each node can read the current state and return updates, which LangGraph applies to the shared state as the workflow executes.</li></ul><p>This state definition allows our chatbot to maintain a growing conversation history, giving the LLM access to previous messages when generating responses.</p><h4>5. Build the Graph</h4><p>Now that we’ve defined our chatbot’s state, let’s initialize the LangGraph workflow.</p><pre># Initialize the graph with the ChatState schema<br>graph = StateGraph(ChatState)</pre><p>Let’s understand what’s happening:</p><ul><li><strong>Graph Initialization:</strong> We create a StateGraph object and pass ChatState as its state schema.</li><li><strong>State Structure:</strong> By associating the graph with ChatState, we tell LangGraph what information the workflow will manage. In our case, it is the conversation history stored in the messages field.</li></ul><p>At this point, we’ve created the graph structure, but it doesn’t contain any nodes or edges yet. We’ll add those in the upcoming steps.</p><h4>6. Define Your Workflow Nodes (Functions)</h4><p>Now, let’s define the node that handles the chatbot’s core logic: receiving conversation messages, sending them to the LLM, and returning the generated response.</p><h4>chat_node</h4><pre># Define the chatbot node<br>def chat_node(state: ChatState) -&gt; ChatState:<br>    messages = state[&#39;messages&#39;]<br>    response = llm.invoke(messages)<br>    return {&quot;messages&quot;: [response]}</pre><p>Let’s understand what’s happening:</p><ul><li><strong>Node Function:</strong> We define chat_node, which accepts the current workflow state (ChatState) as input.</li><li><strong>Extract Messages:</strong> state[&#39;messages&#39;] retrieves the conversation history, including the latest user message and any previous messages in the thread.</li><li><strong>LLM Invocation:</strong> llm.invoke(messages) sends the conversation history to the configured LLM and waits for its response.</li><li><strong>Return Updated State:</strong> The node returns the LLM response inside a messages list. Because we configured add_messages as the reducer in ChatState, this response is appended to the existing conversation history.</li></ul><p><strong>Seamless Processing:</strong> This node is the core of our chatbot. It connects the conversation state with the LLM, allowing the AI to generate context-aware responses using the available message history.</p><h4>7. Build and Compile the Graph</h4><p>We’ve defined our chatbot node. Now, let’s connect it to the graph, configure the checkpointer, and compile the workflow.</p><pre># Initialize the checkpointer<br>checkpointer = InMemorySaver()<br><br># Initialize the graph<br>graph = StateGraph(ChatState)<br><br># Add the chatbot node<br>graph.add_node(&quot;chat_node&quot;, chat_node)<br><br># Define the workflow edges<br>graph.add_edge(START, &quot;chat_node&quot;)<br>graph.add_edge(&quot;chat_node&quot;, END)<br><br># Compile the graph with the checkpointer<br>chatbot = graph.compile(checkpointer=checkpointer)</pre><p>Let’s understand what’s happening:</p><ul><li><strong>Checkpointer:</strong> We initialize InMemorySaver() as our checkpointer. It saves workflow checkpoints in memory (RAM), allowing the chatbot to retain conversation state across interactions when the same thread is used.</li><li><strong>Add Node:</strong> We register chat_node with the graph. This is the function responsible for processing the conversation and generating the LLM response. We have one node in this workflow.</li><li><strong>Define Edges:</strong> We connect the workflow components to establish the execution sequence:</li><li>START → chat_node</li><li>chat_node → END</li><li><strong>Compilation:</strong> Finally, graph.compile(checkpointer=checkpointer) compiles the graph into a runnable object named chatbot.</li></ul><p>The compiled chatbot object is now ready to be imported and invoked by our Streamlit frontend.</p><p><strong>Note:</strong> InMemorySaver stores checkpoints in memory, so they are not durable across application or process restarts.</p><h4>8. Workflow Graph</h4><p>Now that we’ve built and compiled our LangGraph workflow, let’s visualize its structure.</p><p>We can use get_graph() to retrieve the graph representation and draw_mermaid_png() to generate a PNG image of the workflow.</p><pre>from IPython.display import Image, display<br><br># Generate and display the workflow graph<br>Image(chatbot.get_graph().draw_mermaid_png())</pre><p>The workflow follows a simple sequence:</p><ul><li><strong>START:</strong> The workflow begins when the chatbot receives the conversation state.</li><li><strong>chat_node:</strong> The node sends the conversation messages to the LLM and returns the generated response.</li><li><strong>END:</strong> The workflow finishes after the chatbot node completes execution.</li></ul><figure><img alt="A LangGraph workflow diagram with three connected elements: START, the chat_node processing node, and END." src="https://cdn-images-1.medium.com/max/121/1*8AxwksZXCMpfqReme_EF6Q.png" /><figcaption>LangGraph workflow graph showing the execution flow from START to chat_node and then END.</figcaption></figure><h4>9. Complete Backend Code (langgraph_backend.py)</h4><p>We’ve now completed all the steps required to build our LangGraph chatbot backend.</p><p>Let’s combine everything into a single Python file named langgraph_backend.py. This file contains the LLM configuration, conversation state, chatbot node, and compiled workflow.</p><pre># If using ChatOpenAI<br># from langchain_openai import ChatOpenAI<br><br># If using ChatGoogleGenerativeAI<br>from langchain_google_genai import ChatGoogleGenerativeAI<br><br>from langgraph.graph import StateGraph, START, END<br>from typing import TypedDict, Annotated<br>from langchain_core.messages import BaseMessage<br>from langgraph.checkpoint.memory import InMemorySaver<br>from langgraph.graph.message import add_messages<br>from dotenv import load_dotenv<br><br># Load environment variables<br>load_dotenv()<br><br># If using ChatOpenAI<br># Initialize ChatOpenAI<br># llm = ChatOpenAI(model=&quot;gpt-4o-mini&quot;)<br><br># If using ChatGoogleGenerativeAI<br># Initialize ChatGoogleGenerativeAI<br>llm = ChatGoogleGenerativeAI(model=&quot;gemini-2.5-flash&quot;)<br><br># Define the chatbot state<br>class ChatState(TypedDict):<br>    messages: Annotated[list[BaseMessage], add_messages]<br><br># Define the chatbot node<br>def chat_node(state: ChatState) -&gt; ChatState:<br>    messages = state[&#39;messages&#39;]<br>    response = llm.invoke(messages)<br>    return {&quot;messages&quot;: [response]}<br><br># Initialize the checkpointer<br>checkpointer = InMemorySaver()<br><br># Build the graph<br>graph = StateGraph(ChatState)<br>graph.add_node(&quot;chat_node&quot;, chat_node)<br>graph.add_edge(START, &quot;chat_node&quot;)<br>graph.add_edge(&quot;chat_node&quot;, END)<br><br># Compile the chatbot workflow<br>chatbot = graph.compile(checkpointer=checkpointer)</pre><p><strong>Understanding the complete backend:</strong></p><ul><li><strong>Imports and Environment:</strong> We import the required libraries and load API credentials from the .env file.</li><li><strong>LLM Initialization:</strong> We configure Gemini 2.5 Flash to generate chatbot responses.</li><li><strong>State Management:</strong> ChatState defines the conversation history, while add_messages appends new messages to the existing state.</li><li><strong>Chatbot Node:</strong> chat_node sends the conversation history to the LLM and returns its response.</li><li><strong>Checkpointer:</strong> InMemorySaver stores workflow checkpoints in memory.</li><li><strong>Graph Compilation:</strong> We connect START, chat_node, and END, then compile the graph into the chatbot object.</li></ul><p><strong>Important:</strong> The backend is now ready to be imported into our Streamlit frontend. To maintain conversation context between separate invocations, the frontend must pass the same thread_id in its configuration. Since we&#39;re using InMemorySaver, the checkpoints are held in memory and are not durable across process restarts.</p><p>Our backend is complete! In the next section, we’ll start building the frontend in streamlit_frontend_streaming.py and connect it to our LangGraph chatbot.</p><h3>2. Building the Frontend (streamlit_frontend_streaming.py)</h3><p>Now, let’s move to the frontend, where we will implement the streaming functionality.</p><p>Unlike the backend, which remains largely unchanged from Part 11, the frontend requires a few important updates. We will replace chatbot.invoke() with chatbot.stream() and use Streamlit&#39;s st.write_stream() to display the AI response as it is generated.</p><p>Let’s implement it step by step.</p><h4>1. Importing Required Libraries</h4><p>First, import the required libraries and the compiled chatbot workflow from our backend.</p><pre>import streamlit as st<br>from langgraph_backend import chatbot<br>from langchain_core.messages import HumanMessage<br><br># Configuration for thread memory<br>CONFIG = {&#39;configurable&#39;: {&#39;thread_id&#39;: &#39;thread-1&#39;}}</pre><ul><li><strong>Streamlit:</strong> Imports the Streamlit library, which we use to build the chat interface.</li><li><strong>Backend:</strong> Imports the compiled chatbot workflow from langgraph_backend.py.</li><li><strong>HumanMessage:</strong> Represents the user’s input as a LangChain message.</li><li><strong>CONFIG:</strong> Specifies the thread ID used by LangGraph to maintain conversation state.</li></ul><h4>2. Creating a Place to Store Messages (Session State)</h4><p>Next, we initialize Streamlit’s session state to maintain the frontend chat history.</p><pre>if &#39;message_history&#39; not in st.session_state:<br>    st.session_state[&#39;message_history&#39;] = []</pre><ul><li><strong>Session State:</strong> st.session_state works like temporary memory for the frontend.</li><li><strong>Initialization:</strong> If message_history doesn&#39;t exist, we create an empty list to store chat messages.</li></ul><p>This allows us to retain and display the chat history across Streamlit script reruns within the same session.</p><h4>3. Displaying Previous Messages</h4><p>Now, let’s display all previously saved messages whenever the Streamlit app reruns.</p><pre># Loading the conversation history<br>for message in st.session_state[&#39;message_history&#39;]:<br>    with st.chat_message(message[&#39;role&#39;]):<br>        st.text(message[&#39;content&#39;])</pre><ul><li><strong>Iteration:</strong> We loop through all saved messages in message_history.</li><li><strong>Rendering:</strong> st.chat_message() creates the appropriate chat bubble based on the message role, such as user or assistant.</li><li><strong>Content:</strong> st.text() displays the message inside the chat bubble.</li></ul><h4>4. Getting User Input</h4><p>Next, we create the chat input box where users can type their messages.</p><pre>user_input = st.chat_input(&#39;Type here&#39;)</pre><ul><li><strong>Chat Input Box:</strong> st.chat_input() creates the message input field at the bottom of the chat interface.</li></ul><h4>5. If User Sends a Message → Show It + Save It</h4><p>When the user submits a message, we first save it to the frontend history and immediately display it in the chat interface.</p><pre>if user_input:<br>    # First add the message to message_history<br>    st.session_state[&#39;message_history&#39;].append({<br>        &#39;role&#39;: &#39;user&#39;,<br>        &#39;content&#39;: user_input<br>    })<br><br>    with st.chat_message(&#39;user&#39;):<br>        st.text(user_input)</pre><ul><li><strong>Save to History:</strong> We append the user’s message to message_history.</li><li><strong>Instant Display:</strong> We immediately create a user chat bubble and display the submitted text.</li></ul><h4>6. Streaming the AI Response</h4><p>This is the most important change in Part 12.</p><p>In Part 11, we used chatbot.invoke() to wait for the complete response. Now, we will use chatbot.stream() to receive message chunks as they are generated and pass them to Streamlit&#39;s st.write_stream().</p><pre>with st.chat_message(&#39;assistant&#39;):<br>    ai_message = st.write_stream(<br>        message_chunk.content for message_chunk, metadata in chatbot.stream(<br>            {&#39;messages&#39;: [HumanMessage(content=user_input)]},<br>            config=CONFIG,<br>            stream_mode=&#39;messages&#39;<br>        )<br>    )</pre><p>Let’s understand the important parts:</p><ul><li><strong>chatbot.stream():</strong> Requests a stream of outputs from the LangGraph workflow instead of waiting for the complete response.</li><li><strong>stream_mode=&#39;messages&#39;:</strong> Enables message-level streaming, providing message chunks along with metadata.</li><li><strong>Generator Expression:</strong> message_chunk.content for message_chunk, metadata in chatbot.stream(...) extracts the text content from each message chunk and yields it to the next component.</li><li><strong>st.write_stream():</strong> Consumes the generator and progressively displays the text in the Streamlit interface, creating a typewriter effect.</li></ul><p>As a result, users can see the AI response appearing progressively instead of waiting for the entire answer to be generated.</p><h4>7. Saving the Assembled Assistant Reply</h4><p>Once streaming finishes, we need to save the complete AI response to our frontend chat history.</p><pre>st.session_state[&#39;message_history&#39;].append({<br>    &#39;role&#39;: &#39;assistant&#39;,<br>    &#39;content&#39;: ai_message<br>})</pre><ul><li><strong>Final Value:</strong> st.write_stream() returns the assembled response after the generator finishes. We capture that value in ai_message.</li><li><strong>Save to History:</strong> We append the complete assistant response to message_history.</li></ul><p>This ensures that the complete response is available in st.session_state and can be displayed again when the Streamlit app reruns.</p><p><strong>Chat Interface in Streamlit (with Streaming)</strong></p><figure><img alt="Streamlit chatbot interface showing an AI-generated response appearing progressively through token-by-token streaming." src="https://cdn-images-1.medium.com/max/1024/1*hZNhxUrex6Xi5c3caiQQ4A.png" /><figcaption><em>Streaming chatbot interface in Streamlit, displaying the AI response progressively as it is generated.</em></figcaption></figure><h4>8. Complete Frontend Code (streamlit_frontend_streaming.py)</h4><p>We have now implemented all the individual frontend components. Let’s combine them into one complete file.</p><p>Create a file named streamlit_frontend_streaming.py and add the following code:</p><pre>import streamlit as st<br>from langgraph_backend import chatbot<br>from langchain_core.messages import HumanMessage<br><br># Configuration for thread memory<br>CONFIG = {&#39;configurable&#39;: {&#39;thread_id&#39;: &#39;thread-1&#39;}}<br><br># Initialize message history<br>if &#39;message_history&#39; not in st.session_state:<br>    st.session_state[&#39;message_history&#39;] = []<br><br># Load the conversation history<br>for message in st.session_state[&#39;message_history&#39;]:<br>    with st.chat_message(message[&#39;role&#39;]):<br>        st.text(message[&#39;content&#39;])<br><br># Get user input<br>user_input = st.chat_input(&#39;Type here&#39;)<br><br>if user_input:<br><br>    # Save and display the user message<br>    st.session_state[&#39;message_history&#39;].append({<br>        &#39;role&#39;: &#39;user&#39;,<br>        &#39;content&#39;: user_input<br>    })<br><br>    with st.chat_message(&#39;user&#39;):<br>        st.text(user_input)<br><br>    # Stream and display the assistant response<br>    with st.chat_message(&#39;assistant&#39;):<br>        ai_message = st.write_stream(<br>            message_chunk.content for message_chunk, metadata in chatbot.stream(<br>                {&#39;messages&#39;: [HumanMessage(content=user_input)]},<br>                config=CONFIG,<br>                stream_mode=&#39;messages&#39;<br>            )<br>        )<br><br>    # Save the complete assistant response<br>    st.session_state[&#39;message_history&#39;].append({<br>        &#39;role&#39;: &#39;assistant&#39;,<br>        &#39;content&#39;: ai_message<br>    })</pre><h4>What’s Happening Here?</h4><ul><li><strong>User Input:</strong> The user submits a message through st.chat_input().</li><li><strong>Message History:</strong> The user’s message is saved and displayed immediately.</li><li><strong>LangGraph Streaming:</strong> chatbot.stream() generates message chunks from the workflow.</li><li><strong>Streamlit Rendering:</strong> st.write_stream() progressively displays the generated text.</li><li><strong>Response Storage:</strong> Once streaming completes, the complete response is saved to st.session_state[&#39;message_history&#39;].</li></ul><p>That’s it! We have successfully upgraded our existing LangGraph chatbot to support real-time response streaming without changing the backend graph structure.</p><h3>Final Thoughts</h3><p>In this tutorial, we significantly improved the user experience of our LangGraph chatbot by introducing <strong>streaming</strong>.</p><p>Streaming makes interactions more engaging and conversational by displaying the AI-generated response token by token, reducing the perceived wait time and avoiding the experience of a frozen screen.</p><p>The best part is that we didn’t need to make any structural changes to our backend. LangGraph natively supports streaming through its .stream() method.</p><p>On the frontend, Streamlit makes implementation simple with the st.write_stream() function, which works seamlessly with LangGraph&#39;s streaming capabilities.</p><p>With just a few frontend changes, we transformed our existing chatbot into a more responsive, real-time conversational application.</p><h3>Key Takeaways</h3><p>Let’s quickly recap what we learned in this tutorial:</p><ul><li><strong>What is Streaming?</strong> Streaming allows an LLM to send its response in chunks as it is generated instead of waiting for the complete response.</li><li><strong>Better User Experience:</strong> It creates a more responsive and conversational experience by displaying the AI response progressively.</li><li><strong>LangGraph Streaming:</strong> LangGraph supports streaming natively through the .stream() method.</li><li><strong>stream_mode=&#39;messages&#39;:</strong> Allows us to receive LLM message chunks along with their metadata.</li><li><strong>Generator Expression:</strong> We use a generator expression to extract the text content from each message chunk.</li><li><strong>Streamlit </strong><strong>st.write_stream():</strong> Displays the generated text progressively with a typewriter effect.</li><li><strong>Maintaining Chat History:</strong> st.write_stream() returns the assembled response, which we save to st.session_state for future display.</li><li><strong>Minimal Backend Changes:</strong> We can introduce streaming without changing the structure of our existing LangGraph backend.</li></ul><p>The key idea is simple: <strong>LangGraph generates the stream, and Streamlit displays it in real time.</strong></p><h3>Conclusion</h3><p>In this tutorial, we upgraded our LangGraph chatbot by introducing real-time streaming with Streamlit.</p><p>Instead of waiting for the complete AI response, users can now see the generated text appear chunk by chunk, creating a more engaging and conversational experience.</p><p>The best part is that we didn’t need to make major changes to our existing backend. LangGraph already supports streaming through its .stream() method, while Streamlit&#39;s st.write_stream() makes displaying those streamed responses simple.</p><p>By combining these two features, we can build AI chat applications that feel faster, more responsive, and more interactive.</p><p><strong>That’s it for Part 12!</strong> We have successfully added real-time streaming to our LangGraph chatbot while maintaining its conversation history.</p><p>In the next part, we’ll explore another important concept in LangGraph and continue building our understanding of agentic AI workflows.</p><h3>What’s Next?</h3><p>In the next part, we’ll take our LangGraph chatbot one step further by building a <strong>Resume Chat Feature Like ChatGPT</strong>.</p><p>So far, our chatbot can stream AI responses and maintain conversation history within a chat session. But what if users want to start a new conversation, switch between previous conversations, or return to an old chat without losing its context?</p><p>That’s exactly what we’ll build in <strong>Part 13</strong>!</p><p>We’ll upgrade our Streamlit interface with a sidebar, allowing users to:</p><ul><li><strong>Start New Chats:</strong> Create separate conversations without losing previous ones.</li><li><strong>Manage Multiple Conversations:</strong> Maintain a list of historical chat threads.</li><li><strong>Resume Previous Chats:</strong> Select an old conversation and continue from where they left off.</li><li><strong>Generate Unique Thread IDs:</strong> Use Python’s uuid module to assign a unique ID to every conversation.</li><li><strong>Restore Conversation State:</strong> Use LangGraph’s InMemorySaver and get_state() to retrieve previous conversation messages.</li></ul><blockquote><strong>Next Part:</strong> Agentic AI using LangGraph — Part 13: <strong>How to Build a Resume Chat Feature Like ChatGPT</strong></blockquote><p>By combining LangGraph’s checkpointing capabilities with Streamlit’s session state, we’ll build a multi-conversation chatbot experience similar to ChatGPT’s sidebar.</p><blockquote><strong>Series:</strong> Agentic AI using LangGraph — Part 12 of 27</blockquote><h3>Connect with me</h3><p><strong><em>Connect with me on </em></strong><a href="https://www.linkedin.com/in/shubhamnagar234/"><strong><em>LinkedIn</em></strong></a><strong><em>, </em></strong><a href="https://github.com/shubhamnagar234"><strong><em>GitHub</em></strong></a><strong><em>, </em></strong><a href="https://x.com/nagarshubham234"><strong><em>X (Twitter)</em></strong></a><strong><em>, or explore my </em></strong><a href="https://shubhamnagar234.vercel.app/"><strong><em>Portfolio</em></strong></a><strong><em>.</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=915a7e590c3b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Chatbot with UI in LangGraph and Streamlit — Part 11]]></title>
            <link>https://medium.com/@shubhamnagar234/building-a-chatbot-with-ui-in-langgraph-and-streamlit-part-11-4280aaeb2156?source=rss-10b51a93c3a------2</link>
            <guid isPermaLink="false">https://medium.com/p/4280aaeb2156</guid>
            <category><![CDATA[streamlit]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[chatbots]]></category>
            <category><![CDATA[langgraph]]></category>
            <category><![CDATA[ai-agent]]></category>
            <dc:creator><![CDATA[Shubham Nagar]]></dc:creator>
            <pubDate>Sat, 28 Nov 2026 17:32:57 GMT</pubDate>
            <atom:updated>2026-11-28T17:33:23.726Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Learn How to Build a Context-Aware AI Chatbot Using LangGraph and Streamlit, Create an Interactive Chat Interface, Manage Conversation History, and Integrate Backend Persistence with Frontend Session State.</blockquote><p>So far, we’ve explored how to build AI workflows and manage their execution using LangGraph. We’ve learned about sequential, parallel, and conditional workflows, along with persistence, memory, and fault tolerance.</p><p>But there’s one important step remaining: <strong>How do we turn a LangGraph chatbot into an application that users can interact with through a proper web interface?</strong></p><p>A Jupyter Notebook or terminal is useful during development, but it isn’t the most convenient way for regular users to interact with an AI chatbot.</p><blockquote>This is where <strong>Streamlit</strong> comes into the picture.</blockquote><p>Streamlit allows us to build an interactive web interface using Python. By combining it with LangGraph, we can create a chatbot that not only generates AI responses but also provides a visual chat experience with conversation history.</p><p>In this tutorial, we’ll build a chatbot by separating the application into two main components:</p><ul><li><strong>Backend (LangGraph):</strong> Handles the chatbot’s logic, processes user messages, communicates with the LLM, and maintains conversation state using InMemorySaver.</li><li><strong>Frontend (Streamlit):</strong> Provides the chat interface, displays user and AI messages, accepts new input, and manages conversation history using st.session_state.</li></ul><p>We’ll then connect both components so that the frontend can send user messages to the LangGraph backend and display context-aware AI responses.</p><p>By the end of this tutorial, we’ll have a working chatbot with an interactive Streamlit interface and conversation memory powered by LangGraph.</p><p>Let’s get started!</p><h3>Overview</h3><ul><li><strong><em>Chat Interface in Streamlit</em></strong></li><li><strong><em>Chat Interface in Streamlit (Components)</em></strong></li><li><strong><em>Project Architecture</em></strong></li><li><strong><em>Step-by-Step Guide</em></strong></li><li><strong><em>1. Building the Backend (</em></strong><strong><em>langgraph_backend.py)</em></strong></li><li><strong><em>2. Building the Frontend (</em></strong><strong><em>streamlit_frontend.py)</em></strong></li><li><strong><em>Final Thoughts</em></strong></li><li><strong><em>Key Takeaways</em></strong></li><li><strong><em>Conclusion</em></strong></li><li><strong><em>What’s Next?</em></strong></li></ul><h3>Chat Interface in Streamlit</h3><p>When building an AI chatbot, the user experience is just as important as the backend workflow.</p><p>Although we can interact with a LangGraph chatbot through a Jupyter Notebook or terminal, these interfaces are not ideal for regular users. A proper chat interface makes the application more accessible, interactive, and easier to use.</p><blockquote><strong>Streamlit</strong> provides a simple way to build a chat-based UI for our LangGraph application.</blockquote><p>Let’s understand why a chat interface is important.</p><ul><li><strong>End-User Experience:</strong> A Jupyter Notebook or terminal is not suitable for regular users. A UI makes the chatbot accessible and easy to use.</li><li><strong>Conversation Continuity:</strong> A proper chat interface visually represents the conversation history, distinguishing between User and AI responses. This makes it easier for users to follow the conversation.</li><li><strong>State Management:</strong> It provides a practical way to manage short-term memory using Streamlit’s session state on the client side, complementing the backend checkpointer.</li></ul><figure><img alt="Screenshot of a Streamlit chatbot interface showing a conversation between a user and an AI assistant, with separate message displays and a chat input field." src="https://cdn-images-1.medium.com/max/1024/1*sTWWi8az2gNrFdHD4Xc7dQ.png" /><figcaption>Chat Interface in Streamlit — a user-friendly interface for interacting with a LangGraph-powered chatbot.</figcaption></figure><h3>Chat Interface in Streamlit (Components)</h3><p>Building a chat interface in Streamlit involves two primary components: <strong>st.chat_message</strong> and <strong>st.chat_input</strong>.</p><p>Let’s understand how each component works.</p><h4>1. Chat Message (st.chat_message)</h4><p>The st.chat_message component acts as a container for displaying messages from the user or the assistant.</p><p>It automatically formats the chat interface with appropriate icons based on the role, making it easy to distinguish between user and AI messages.</p><h4>2. Chat Input (st.chat_input)</h4><p>The st.chat_input component creates the input field at the bottom of the chat interface.</p><p>Users can type their messages into this field and submit them to interact with the chatbot.</p><figure><img alt="Diagram highlighting the chat message container and chat input field in a Streamlit interface." src="https://cdn-images-1.medium.com/max/1024/1*043N9hr9YG6I2WzVBlWRRQ.png" /><figcaption>Chat Interface in Streamlit (Components) — understanding how st.chat_message and st.chat_input are used to display and receive messages.</figcaption></figure><h4>Key Implementation Logic</h4><p>Apart from displaying messages and accepting user input, we also need to manage the conversation history.</p><p>Streamlit reruns the entire script whenever a user interacts with the application. Therefore, we need to use <strong>st.session_state</strong> to preserve the conversation between reruns.</p><p>Here are the key implementation steps:</p><ul><li><strong>Managing State:</strong> Use st.session_state to store the message history. This prevents previous conversation turns from disappearing whenever the user presses Enter.</li><li><strong>Displaying History:</strong> Before processing new input, loop through the messages stored in st.session_state and render the complete conversation on the screen.</li><li><strong>Updating History:</strong> After receiving user input and generating an AI response, append both messages to the session state list. This ensures that the conversation remains visible across subsequent reruns.</li></ul><p>Together, these two chat components and session state provide the foundation for building an interactive chatbot interface in Streamlit.</p><h3>Project Architecture</h3><h4>Plan of Action</h4><p>To build a user interface for our LangGraph chatbot, we’ll divide the project into two main components: <strong>Back-End</strong> and <strong>Front-End</strong>.</p><p>Let’s understand the responsibility of each component and how they work together.</p><h4>1. Back-End (langgraph_backend.py)</h4><p>The backend contains the LangGraph workflow logic. It is responsible for:</p><ul><li>Defining the chatbot’s state.</li><li>Initializing the Large Language Model (LLM).</li><li>Creating the chatbot node.</li><li>Building and compiling the LangGraph workflow.</li><li>Using an in-memory checkpointer to maintain the conversation flow.</li></ul><h4>2. Front-End (streamlit_frontend.py)</h4><p>The frontend contains the Streamlit user interface code. It is responsible for:</p><ul><li>Displaying the chatbot interface.</li><li>Accepting user messages.</li><li>Showing user and AI messages.</li><li>Managing conversation history using Streamlit’s session_state.</li><li>Communicating with the backend to process user inputs.</li></ul><h4>3. Integration</h4><p>The frontend communicates with the backend by calling its invoke() method and passing the user&#39;s message.</p><p>It also passes a unique thread_id to ensure that LangGraph can identify the conversation and retrieve its previously saved context.</p><figure><img alt="Architecture diagram showing the user interacting with a Streamlit frontend, which sends user queries to the LangGraph backend and receives AI-generated responses." src="https://cdn-images-1.medium.com/max/1024/1*dHqF69BcF4Euu_u7atBPbw.png" /><figcaption>Project Architecture (Plan of Action) — illustrating how the user, Streamlit frontend, and LangGraph backend communicate with each other.</figcaption></figure><h4>Execution Steps</h4><p>We’ll follow these steps to build and integrate our chatbot:</p><ol><li><strong>Learn Streamlit Basics:</strong> Understand how to build chat interfaces in Streamlit before connecting them to the chatbot.</li><li><strong>Setup Code:</strong> Organize the project into two separate files: one for the backend logic and another for the frontend UI.</li><li><strong>Interface Components:</strong> Implement the core UI elements, specifically the chat message box and the user input box.</li><li><strong>Handle State:</strong> Use Streamlit’s session state to manage conversation history effectively without losing data during script re-executions.</li><li><strong>Final Integration:</strong> Connect the LangGraph backend’s invoke() function to the frontend to enable intelligent, context-aware responses.</li></ol><p>By separating the backend and frontend, we can keep the workflow logic independent of the user interface while making both components easier to understand and maintain.</p><h3>Step-by-Step Guide</h3><h3>1. Building the Backend (langgraph_backend.py)</h3><p>In this section, we’ll build the backend of our chatbot using <strong>LangGraph, Gemini 2.5 Flash, and InMemorySaver</strong>.</p><p>The backend will handle all the core conversational logic and provide an executable chatbot workflow that our Streamlit frontend can interact with.</p><h4>What We’re Building</h4><p>We’re building a stateful chatbot backend using:</p><ul><li><strong>Large Language Model (LLM):</strong> Gemini 2.5 Flash to understand user messages and generate AI responses.</li><li><strong>LangGraph:</strong> To organize and execute the conversational workflow.</li><li><strong>InMemorySaver:</strong> To enable persistence (checkpointing) and maintain conversation history.</li></ul><p>This backend will:</p><ul><li>Take a <strong>user message</strong> as input and append it to the chat history.</li><li>Pass the conversation context to the LLM to generate an <strong>AI response</strong>.</li><li>Save the entire conversation as persistent state under a thread_id.</li><li>Serve as the brain for our Streamlit frontend to power a real-time chat interface.</li></ul><figure><img alt="Workflow illustration showing the LangGraph chatbot backend receiving user messages, processing conversation history through an LLM, and returning AI responses with persistence enabled." src="https://cdn-images-1.medium.com/max/1024/1*8mxgmJ46wW3KOpRo182Y0g.png" /><figcaption>Building a Chatbot with UI in LangGraph and Streamlit — backend code workflow.</figcaption></figure><h4>Understanding the Workflow: A Visual Breakdown</h4><p>Before writing the code, let’s understand how the backend workflow operates.</p><p><strong>START</strong></p><ul><li>The workflow begins here — this is the entry point where the user’s message history is received.</li></ul><p><strong>chat_node</strong></p><ul><li>Extracts the current list of messages from the state.</li><li>Passes the messages to the LLM to generate a response.</li><li>Returns the updated list containing the new AI response, which is appended to the state.</li></ul><p><strong>END</strong></p><ul><li>This is where the workflow ends. At this point, the final response is generated and returned to the frontend.</li></ul><p>The workflow follows a simple sequential execution pattern:</p><blockquote><strong>START → </strong><strong>chat_node → </strong><strong>END</strong></blockquote><p>Now, let’s implement each part of the backend step by step.</p><h4>1. Import &amp; Setup</h4><p>First, let’s import all the necessary modules and components required to build our LangGraph chatbot.</p><pre># If using ChatOpenAI<br># from langchain_openai import ChatOpenAI<br><br># If using ChatGoogleGenerativeAI<br>from langchain_google_genai import ChatGoogleGenerativeAI<br><br>from langgraph.graph import StateGraph, START, END<br>from typing import TypedDict, Annotated<br>from langchain_core.messages import BaseMessage<br>from langgraph.checkpoint.memory import InMemorySaver<br>from langgraph.graph.message import add_messages<br>from dotenv import load_dotenv</pre><p>Let’s understand the purpose of these imports:</p><ul><li><strong>Essential Imports:</strong> We import the necessary modules from LangGraph, LangChain, and Python’s typing module to define our chatbot&#39;s state and structure the workflow.</li><li><strong>LLM Integration:</strong> We import ChatGoogleGenerativeAI to connect our chatbot with Google&#39;s Gemini models. If you prefer OpenAI, you can use ChatOpenAI instead.</li><li><strong>Core LangGraph Components:</strong> We import StateGraph, START, and END to create and define the execution flow of our chatbot.</li><li><strong>State Definition:</strong> We use TypedDict and Annotated to define the chatbot&#39;s state, while BaseMessage represents the messages stored in the conversation.</li><li><strong>Message Management:</strong> We import add_messages, which will help us append new messages to the existing conversation history.</li><li><strong>Persistence:</strong> We import InMemorySaver from langgraph.checkpoint.memory. It acts as a checkpointer that saves workflow state in memory (RAM), allowing the chatbot to maintain conversation context for a thread during execution.</li><li><strong>Environment Configuration:</strong> We import load_dotenv to load environment variables from a .env file.</li></ul><p>These imports provide the foundation for defining our chatbot’s state, connecting the LLM, building the LangGraph workflow, and enabling in-memory persistence.</p><h4>2. Configure Environment Variables</h4><p>Next, we need to configure the environment variables required to connect our chatbot to the LLM provider.</p><p>First, call load_dotenv() to load the environment variables defined in the .env file.</p><pre>load_dotenv()</pre><p>Let’s understand what’s happening:</p><ul><li><strong>API Keys:</strong> We define our API keys in a .env file. For this project, we can use GEMINI_API_KEY for Google Gemini or OPENAI_API_KEY if we&#39;re using OpenAI.</li><li><strong>Environment Setup:</strong> The load_dotenv() function loads the variables from the .env file into the application&#39;s environment so the LLM integration can access the required credentials.</li><li><strong>Authentication:</strong> These API keys allow our application to authenticate with the selected LLM provider when making API requests.</li></ul><p>Make sure your .env file is configured with the appropriate API key before running the application. Keep this file private and never commit it to a public Git repository.</p><h4>3. Initialize the LLM</h4><p>Now, let’s initialize the Large Language Model (LLM) that will power our chatbot.</p><p>We’ll use Google’s Gemini 2.5 Flash model for this project.</p><pre># If using ChatOpenAI<br># Initialize ChatOpenAI<br># llm = ChatOpenAI(model=&quot;gpt-4o-mini&quot;)<br><br># If using ChatGoogleGenerativeAI<br># Initialize ChatGoogleGenerativeAI<br>llm = ChatGoogleGenerativeAI(model=&quot;gemini-2.5-flash&quot;)</pre><p>Let’s understand what’s happening:</p><ul><li><strong>Model Initialization:</strong> We initialize ChatGoogleGenerativeAI with the gemini-2.5-flash model. This model acts as the brain of our chatbot, processing conversation messages and generating responses.</li><li><strong>Flexibility:</strong> The commented-out ChatOpenAI implementation provides an alternative if you want to use OpenAI instead. You can switch providers by uncommenting the relevant code and configuring the corresponding API key.</li></ul><p>The llm object is now ready to be used inside our LangGraph node, where it will process the conversation history and generate the chatbot&#39;s response.</p><h4>4. Define the State (ChatState)</h4><p>Now, let’s define the state schema that will store our chatbot’s conversation history.</p><pre># Define the state class<br>class ChatState(TypedDict):<br>    messages: Annotated[list[BaseMessage], add_messages]</pre><p>Let’s understand what’s happening:</p><ul><li><strong>State Schema:</strong> We define ChatState using TypedDict. It contains a messages field, which stores a list of BaseMessage objects representing the conversation.</li><li><strong>Message Management:</strong> The Annotated type associates the message list with the add_messages reducer. This ensures that new messages are appended to the existing conversation history rather than simply replacing it.</li><li><strong>Shared Memory:</strong> The state is shared across the nodes in the workflow. Each node can read the current state and return updates, which LangGraph applies to the shared state as the workflow executes.</li></ul><p>This state definition allows our chatbot to maintain a growing conversation history, giving the LLM access to previous messages when generating responses.</p><h4>5. Build the Graph</h4><p>Now that we’ve defined our chatbot’s state, let’s initialize the LangGraph workflow.</p><pre># Initialize the graph with the ChatState schema<br>graph = StateGraph(ChatState)</pre><p>Let’s understand what’s happening:</p><ul><li><strong>Graph Initialization:</strong> We create a StateGraph object and pass ChatState as its state schema.</li><li><strong>State Structure:</strong> By associating the graph with ChatState, we tell LangGraph what information the workflow will manage. In our case, it is the conversation history stored in the messages field.</li></ul><p>At this point, we’ve created the graph structure, but it doesn’t contain any nodes or edges yet. We’ll add those in the upcoming steps.</p><h4>6. Define Your Workflow Nodes (Functions)</h4><p>Now, let’s define the node that handles the chatbot’s core logic: receiving conversation messages, sending them to the LLM, and returning the generated response.</p><h4>chat_node</h4><pre># Define the chatbot node<br>def chat_node(state: ChatState) -&gt; ChatState:<br>    messages = state[&#39;messages&#39;]<br>    response = llm.invoke(messages)<br>    return {&quot;messages&quot;: [response]}</pre><p>Let’s understand what’s happening:</p><ul><li><strong>Node Function:</strong> We define chat_node, which accepts the current workflow state (ChatState) as input.</li><li><strong>Extract Messages:</strong> state[&#39;messages&#39;] retrieves the conversation history, including the latest user message and any previous messages in the thread.</li><li><strong>LLM Invocation:</strong> llm.invoke(messages) sends the conversation history to the configured LLM and waits for its response.</li><li><strong>Return Updated State:</strong> The node returns the LLM response inside a messages list. Because we configured add_messages as the reducer in ChatState, this response is appended to the existing conversation history.</li></ul><p><strong>Seamless Processing:</strong> This node is the core of our chatbot. It connects the conversation state with the LLM, allowing the AI to generate context-aware responses using the available message history.</p><h4>7. Build and Compile the Graph</h4><p>We’ve defined our chatbot node. Now, let’s connect it to the graph, configure the checkpointer, and compile the workflow.</p><pre># Initialize the checkpointer<br>checkpointer = InMemorySaver()<br><br># Initialize the graph<br>graph = StateGraph(ChatState)<br><br># Add the chatbot node<br>graph.add_node(&quot;chat_node&quot;, chat_node)<br><br># Define the workflow edges<br>graph.add_edge(START, &quot;chat_node&quot;)<br>graph.add_edge(&quot;chat_node&quot;, END)<br><br># Compile the graph with the checkpointer<br>chatbot = graph.compile(checkpointer=checkpointer)</pre><p>Let’s understand what’s happening:</p><ul><li><strong>Checkpointer:</strong> We initialize InMemorySaver() as our checkpointer. It saves workflow checkpoints in memory (RAM), allowing the chatbot to retain conversation state across interactions when the same thread is used.</li><li><strong>Add Node:</strong> We register chat_node with the graph. This is the function responsible for processing the conversation and generating the LLM response. We have one node in this workflow.</li><li><strong>Define Edges:</strong> We connect the workflow components to establish the execution sequence:</li><li>START → chat_node</li><li>chat_node → END</li><li><strong>Compilation:</strong> Finally, graph.compile(checkpointer=checkpointer) compiles the graph into a runnable object named chatbot.</li></ul><p>The compiled chatbot object is now ready to be imported and invoked by our Streamlit frontend.</p><p><strong>Note:</strong> InMemorySaver stores checkpoints in memory, so they are not durable across application or process restarts.</p><h4>8. Workflow Graph</h4><p>Now that we’ve built and compiled our LangGraph workflow, let’s visualize its structure.</p><p>We can use get_graph() to retrieve the graph representation and draw_mermaid_png() to generate a PNG image of the workflow.</p><pre>from IPython.display import Image, display<br><br># Generate and display the workflow graph<br>Image(chatbot.get_graph().draw_mermaid_png())</pre><p>The workflow follows a simple sequence:</p><ul><li><strong>START:</strong> The workflow begins when the chatbot receives the conversation state.</li><li><strong>chat_node:</strong> The node sends the conversation messages to the LLM and returns the generated response.</li><li><strong>END:</strong> The workflow finishes after the chatbot node completes execution.</li></ul><figure><img alt="A LangGraph workflow diagram with three connected elements: START, the chat_node processing node, and END." src="https://cdn-images-1.medium.com/max/121/1*8AxwksZXCMpfqReme_EF6Q.png" /><figcaption>LangGraph workflow graph showing the execution flow from START to chat_node and then END.</figcaption></figure><h4>9. Complete Backend Code (langgraph_backend.py)</h4><p>We’ve now completed all the steps required to build our LangGraph chatbot backend.</p><p>Let’s combine everything into a single Python file named langgraph_backend.py. This file contains the LLM configuration, conversation state, chatbot node, and compiled workflow.</p><pre># If using ChatOpenAI<br># from langchain_openai import ChatOpenAI<br><br># If using ChatGoogleGenerativeAI<br>from langchain_google_genai import ChatGoogleGenerativeAI<br><br>from langgraph.graph import StateGraph, START, END<br>from typing import TypedDict, Annotated<br>from langchain_core.messages import BaseMessage<br>from langgraph.checkpoint.memory import InMemorySaver<br>from langgraph.graph.message import add_messages<br>from dotenv import load_dotenv<br><br># Load environment variables<br>load_dotenv()<br><br># If using ChatOpenAI<br># Initialize ChatOpenAI<br># llm = ChatOpenAI(model=&quot;gpt-4o-mini&quot;)<br><br># If using ChatGoogleGenerativeAI<br># Initialize ChatGoogleGenerativeAI<br>llm = ChatGoogleGenerativeAI(model=&quot;gemini-2.5-flash&quot;)<br><br># Define the chatbot state<br>class ChatState(TypedDict):<br>    messages: Annotated[list[BaseMessage], add_messages]<br><br># Define the chatbot node<br>def chat_node(state: ChatState) -&gt; ChatState:<br>    messages = state[&#39;messages&#39;]<br>    response = llm.invoke(messages)<br>    return {&quot;messages&quot;: [response]}<br><br># Initialize the checkpointer<br>checkpointer = InMemorySaver()<br><br># Build the graph<br>graph = StateGraph(ChatState)<br>graph.add_node(&quot;chat_node&quot;, chat_node)<br>graph.add_edge(START, &quot;chat_node&quot;)<br>graph.add_edge(&quot;chat_node&quot;, END)<br><br># Compile the chatbot workflow<br>chatbot = graph.compile(checkpointer=checkpointer)</pre><p><strong>Understanding the complete backend:</strong></p><ul><li><strong>Imports and Environment:</strong> We import the required libraries and load API credentials from the .env file.</li><li><strong>LLM Initialization:</strong> We configure Gemini 2.5 Flash to generate chatbot responses.</li><li><strong>State Management:</strong> ChatState defines the conversation history, while add_messages appends new messages to the existing state.</li><li><strong>Chatbot Node:</strong> chat_node sends the conversation history to the LLM and returns its response.</li><li><strong>Checkpointer:</strong> InMemorySaver stores workflow checkpoints in memory.</li><li><strong>Graph Compilation:</strong> We connect START, chat_node, and END, then compile the graph into the chatbot object.</li></ul><p><strong>Important:</strong> The backend is now ready to be imported into our Streamlit frontend. To maintain conversation context between separate invocations, the frontend must pass the same thread_id in its configuration. Since we&#39;re using InMemorySaver, the checkpoints are held in memory and are not durable across process restarts.</p><p>Our backend is complete! In the next section, we’ll start building the frontend in streamlit_frontend.py and connect it to our LangGraph chatbot.</p><h3>2. Building the Frontend (streamlit_frontend.py)</h3><p>Now that our LangGraph backend is ready, let’s start building the frontend using Streamlit.</p><p>The frontend will provide a chat interface where users can enter messages, view previous conversations, and receive AI-generated responses.</p><h4>1. Importing Required Libraries</h4><p>First, let’s create a new Python file named streamlit_frontend.py and import the required libraries.</p><pre>import streamlit as st<br>from langgraph_backend import chatbot<br>from langchain_core.messages import HumanMessage<br><br># Configuration for thread memory<br>CONFIG = {&#39;configurable&#39;: {&#39;thread_id&#39;: &#39;thread-1&#39;}}</pre><p>Let’s understand what’s happening:</p><ul><li><strong>Streamlit:</strong> We import the streamlit library, which provides the components needed to build our chatbot&#39;s user interface.</li><li><strong>Backend Integration:</strong> We import the compiled chatbot workflow from langgraph_backend.py. This allows our frontend to communicate directly with the LangGraph backend.</li><li><strong>HumanMessage:</strong> We import HumanMessage to represent the user&#39;s input in the message format expected by LangChain and LangGraph.</li><li><strong>Thread Configuration:</strong> We define a CONFIG dictionary containing thread_id=&#39;thread-1&#39;. This identifier allows LangGraph&#39;s checkpointer to associate multiple interactions with the same conversation thread and maintain its context.</li></ul><p><strong>Why is </strong><strong>thread_id important?</strong></p><p>Whenever we invoke the chatbot, we pass this configuration along with the user’s message. By using the same thread_id for each interaction, LangGraph can retrieve the previous checkpoint and continue the conversation with its existing context.</p><p>Our frontend is now connected to the backend, and we’re ready to manage the conversation history using Streamlit’s session state.</p><h4>2. Creating a Place to Store Messages (Session State)</h4><p>Now that we’ve connected our frontend to the LangGraph backend, let’s create a place to store the conversation history.</p><p>For this, we’ll use Streamlit’s st.session_state, which allows us to maintain data across script reruns within the same user session.</p><pre># Initialize message history<br>if &#39;message_history&#39; not in st.session_state:<br>    st.session_state[&#39;message_history&#39;] = []</pre><p>Let’s understand what’s happening:</p><ul><li><strong>Session State:</strong> st.session_state works like temporary memory for the frontend. It allows us to preserve data when Streamlit reruns the script after user interactions.</li><li><strong>Initialization:</strong> We check whether message_history already exists in the session state. If it doesn&#39;t, we initialize it as an empty list.</li><li><strong>Memory Retention:</strong> This list will store all chat messages from both the user and the AI assistant. We can use it to rebuild the conversation interface whenever the script reruns.</li></ul><p><strong>Why do we need this?</strong></p><p>Streamlit reruns the application script when a user interacts with the interface. Without session state, previously displayed messages would not be available to rebuild the conversation.</p><p>By storing messages in st.session_state[&#39;message_history&#39;], we can maintain the frontend conversation history throughout the Streamlit session.</p><h4>3. Displaying Previous Messages</h4><p>Now, let’s display the conversation history stored in st.session_state[&#39;message_history&#39;].</p><p>Since Streamlit reruns the script after every interaction, we need to render all previously saved messages whenever the application runs.</p><pre># Load and display the conversation history<br>for message in st.session_state[&#39;message_history&#39;]:<br>    with st.chat_message(message[&#39;role&#39;]):<br>        st.text(message[&#39;content&#39;])</pre><p>Let’s understand what’s happening:</p><ul><li><strong>Iteration:</strong> We loop through all the messages stored in st.session_state[&#39;message_history&#39;]. This allows us to rebuild the conversation whenever the Streamlit script reruns.</li><li><strong>Roles and Chat Bubbles:</strong> Each message contains a role, such as user or assistant. We pass this role to st.chat_message() to display the appropriate chat bubble.</li><li><strong>Rendering Message Content:</strong> Inside the chat message container, st.text(message[&#39;content&#39;]) displays the actual message content.</li></ul><p><strong>Why is this important?</strong></p><p>Without this step, previously saved messages would not be displayed when Streamlit reruns the application. By iterating through the message history, we can maintain a continuous chat experience and show both user and assistant messages in their correct order.</p><h4>4. Getting User Input</h4><p>Now, let’s add an input box to our chatbot interface where users can type their messages.</p><p>Streamlit provides a built-in component called st.chat_input() specifically designed for chat applications.</p><pre># Get user input<br>user_input = st.chat_input(&#39;Type here&#39;)</pre><p>Let’s understand what’s happening:</p><ul><li><strong>Chat Input Box:</strong> st.chat_input() creates a message input field at the bottom of the chat interface where users can type their messages.</li><li><strong>Capture User Input:</strong> When the user enters a message and presses Enter, the submitted text is returned and stored in the user_input variable.</li></ul><p>We can now use the user_input variable to access the user&#39;s message and process it in our LangGraph backend.</p><p><strong>What’s next?</strong></p><p>In the next step, we’ll check whether the user has submitted a message, save it to st.session_state[&#39;message_history&#39;], and immediately display it in the chat interface.</p><h4>5. If User Sends a Message → Show It + Save It</h4><p>Now that we’ve created the chat input box, let’s handle the user’s submitted message.</p><p>Whenever a user enters a message and presses Enter, we need to save it in our conversation history and display it in the chat interface.</p><pre>if user_input:<br>    # First add the message to message_history<br>    st.session_state[&#39;message_history&#39;].append({<br>        &#39;role&#39;: &#39;user&#39;,<br>        &#39;content&#39;: user_input<br>    })<br><br>    with st.chat_message(&#39;user&#39;):<br>        st.text(user_input)</pre><p>Let’s understand what’s happening:</p><ul><li><strong>Check User Input:</strong> We use if user_input: to check whether the user has submitted a message. The following operations execute only when input is available.</li><li><strong>Save to History:</strong> We append the user’s message to st.session_state[&#39;message_history&#39;] as a dictionary containing two fields:</li><li>role: Identifies the sender as user.</li><li>content: Stores the actual message entered by the user.</li><li><strong>Instant Display:</strong> We use st.chat_message(&#39;user&#39;) to create a user chat bubble and st.text(user_input) to display the submitted message.</li></ul><p><strong>Why do we save the message before invoking the backend?</strong></p><p>This ensures that the frontend records the user’s message immediately. We can then send the same message to our LangGraph backend for processing and generate an AI response.</p><p>Our frontend can now capture, store, and display user messages. The next step is to send the user’s message to the LangGraph backend using chatbot.invoke().</p><h4>6. Sending the User Message to LangGraph Backend</h4><p>Now that we’ve saved and displayed the user’s message in the frontend, let’s send it to our LangGraph backend for processing.</p><p>We’ll use the chatbot.invoke() method to execute our compiled LangGraph workflow.</p><pre># Invoke the backend<br>response = chatbot.invoke(<br>    {&#39;messages&#39;: [HumanMessage(content=user_input)]},<br>    config=CONFIG<br>)</pre><p>Let’s understand what’s happening:</p><ul><li><strong>Backend Invocation:</strong> We call chatbot.invoke() to execute the compiled LangGraph workflow. We pass the user&#39;s input inside a messages list.</li><li><strong>HumanMessage:</strong> We use HumanMessage(content=user_input) to convert the user&#39;s text into a message object that LangGraph can process.</li><li><strong>Persistence Configuration:</strong> We pass CONFIG as the second argument. It contains thread_id=&#39;thread-1&#39;, which identifies the conversation thread for the checkpointer.</li><li><strong>Conversation Context:</strong> Because we use the same thread_id for each interaction, LangGraph can retrieve the previous checkpoint and include the existing conversation history when processing the new message.</li></ul><p>The backend processes the conversation through chat_node, sends the messages to the LLM, and returns the updated state containing the conversation history and the newly generated AI response.</p><p>We store this result in the response variable, which we&#39;ll use in the next step to extract the assistant&#39;s latest message.</p><h4>7. Extracting the AI’s Last Message</h4><p>After invoking the LangGraph backend, we receive the updated conversation state containing the complete message history.</p><p>Now, we need to extract the latest AI-generated response so that we can display it in our Streamlit interface.</p><pre># Extract the AI&#39;s latest response<br>ai_message = response[&#39;messages&#39;][-1].content</pre><p>Let’s understand what’s happening:</p><ul><li><strong>Message List:</strong> The backend returns the updated state, including the existing conversation messages and the newly generated AI response.</li><li><strong>Extracting the Reply:</strong> We use response[&#39;messages&#39;] to access the message list.</li><li><strong>Getting the Last Message:</strong> The [-1] index retrieves the last message in the list, which contains the AI&#39;s latest response.</li><li><strong>Accessing Content:</strong> We use .content to extract the actual text from the AI message object.</li></ul><p>The extracted response is now stored in the ai_message variable, ready to be saved in our frontend conversation history and displayed to the user.</p><h4>8. Saving and Showing the Assistant Reply</h4><p>Once we receive the AI’s response from the LangGraph backend, we need to save it in our frontend chat history and display it in the Streamlit interface.</p><p><strong>Code:</strong></p><pre># Add the AI response to message_history<br>st.session_state[&#39;message_history&#39;].append({<br>    &#39;role&#39;: &#39;assistant&#39;,<br>    &#39;content&#39;: ai_message<br>})<br><br>with st.chat_message(&#39;assistant&#39;):<br>    st.text(ai_message)</pre><p><strong>How It Works:</strong></p><ul><li><strong>Save AI Reply:</strong> We append the AI’s response to message_history in st.session_state. We use the assistant role to identify it as an AI-generated message.</li><li><strong>Display:</strong> We use st.chat_message(&#39;assistant&#39;) to create an assistant message bubble and st.text(ai_message) to display the response inside it.</li></ul><p>This completes the basic frontend conversation flow: the user’s message is displayed, sent to the LangGraph backend, and the assistant’s reply is saved and displayed in the chat interface.</p><p><strong>Chat Interface in Streamlit (with Memory)</strong></p><figure><img alt="A Streamlit chatbot interface showing a conversation between a user and an AI assistant, with previous messages retained in the chat history." src="https://cdn-images-1.medium.com/max/1024/1*Kf_QHOb_LSU9xSbJNJtU8w.png" /><figcaption><em>The Streamlit chatbot interface displaying the conversation history, including both user messages and assistant responses.</em></figcaption></figure><h4>9. Complete Frontend Code (streamlit_frontend.py)</h4><p>We’ve now covered all the individual steps required to build the frontend of our chatbot. Let’s bring them together into a single Python file.</p><p>This frontend connects our Streamlit interface with the LangGraph backend, manages the conversation history, accepts user messages, and displays AI responses.</p><p><strong>Complete Code:</strong></p><pre>import streamlit as st<br>from langgraph_backend import chatbot<br>from langchain_core.messages import HumanMessage<br><br># Configuration for thread memory<br>CONFIG = {&#39;configurable&#39;: {&#39;thread_id&#39;: &#39;thread-1&#39;}}<br><br># Initialize message history<br>if &#39;message_history&#39; not in st.session_state:<br>    st.session_state[&#39;message_history&#39;] = []<br><br># Display previous conversation messages<br>for message in st.session_state[&#39;message_history&#39;]:<br>    with st.chat_message(message[&#39;role&#39;]):<br>        st.text(message[&#39;content&#39;])<br><br># Get user input<br>user_input = st.chat_input(&#39;Type here&#39;)<br><br>if user_input:<br>    # Save and display the user&#39;s message<br>    st.session_state[&#39;message_history&#39;].append({<br>        &#39;role&#39;: &#39;user&#39;,<br>        &#39;content&#39;: user_input<br>    })<br><br>    with st.chat_message(&#39;user&#39;):<br>        st.text(user_input)<br><br>    # Invoke the LangGraph backend<br>    response = chatbot.invoke(<br>        {&#39;messages&#39;: [HumanMessage(content=user_input)]},<br>        config=CONFIG<br>    )<br><br>    # Extract the AI&#39;s latest response<br>    ai_message = response[&#39;messages&#39;][-1].content<br><br>    # Save and display the assistant&#39;s response<br>    st.session_state[&#39;message_history&#39;].append({<br>        &#39;role&#39;: &#39;assistant&#39;,<br>        &#39;content&#39;: ai_message<br>    })<br><br>    with st.chat_message(&#39;assistant&#39;):<br>        st.text(ai_message)</pre><h4>Understanding the Complete Flow</h4><p>Let’s summarize what happens when a user sends a message:</p><ol><li><strong>Initialize Session State:</strong> Streamlit creates an empty message_history list if one doesn&#39;t already exist.</li><li><strong>Display Previous Messages:</strong> The frontend renders the messages stored in the session history.</li><li><strong>Receive User Input:</strong> st.chat_input() captures the user&#39;s message.</li><li><strong>Save and Display User Message:</strong> The message is appended to message_history and displayed in the chat interface.</li><li><strong>Invoke LangGraph:</strong> The frontend sends the user’s message to the compiled chatbot workflow using .invoke().</li><li><strong>Retrieve AI Response:</strong> The latest message is extracted from the backend response.</li><li><strong>Save and Display AI Response:</strong> The assistant’s reply is stored in session state and displayed in the interface.</li></ol><h4>How Memory Works in This Project</h4><p>There are two separate memory mechanisms working together:</p><ul><li><strong>Streamlit Session State:</strong> Stores the messages displayed in the frontend through st.session_state[&#39;message_history&#39;].</li><li><strong>LangGraph Checkpointer:</strong> Stores the backend conversation state using InMemorySaver, associated with the thread_id provided through CONFIG.</li></ul><p>The frontend uses message_history to rebuild the visible chat interface, while LangGraph uses its checkpointer to retain conversational context when processing subsequent messages.</p><p><strong>Important:</strong> Both mechanisms used in this project are temporary. Streamlit session state is associated with the active session, and InMemorySaver stores checkpoints in process memory. They are not a substitute for durable database-backed storage.</p><h3>Final Thoughts</h3><p>In this tutorial, we successfully bridged the gap between backend AI logic and frontend user experience by building a chatbot with <strong>LangGraph and Streamlit</strong>.</p><p>We separated the application into two parts: the LangGraph backend, which handles the conversational workflow and LLM interactions, and the Streamlit frontend, which provides an interactive chat interface.</p><p>Along the way, we learned how to:</p><ul><li>Use Streamlit’s st.chat_message and st.chat_input components to build a user-friendly chat interface.</li><li>Manage frontend conversation history using st.session_state.</li><li>Connect the Streamlit frontend to the LangGraph backend using the invoke() method.</li><li>Use LangGraph’s checkpointer and thread_id to maintain conversational context across interactions.</li></ul><p>The most important takeaway is that <strong>a chatbot needs more than an LLM to deliver a good user experience</strong>. By combining LangGraph’s workflow and state management capabilities with Streamlit’s interactive interface, we can build a context-aware chatbot that users can interact with naturally.</p><p>This project also gives us a foundation for building more advanced AI applications with persistent conversations, richer interfaces, and additional capabilities.</p><h3>Key Takeaways</h3><p>Let’s recap the important concepts we learned in this tutorial:</p><ul><li><strong>Backend and Frontend Separation:</strong> Keep LangGraph workflow logic in langgraph_backend.py and Streamlit UI code in streamlit_frontend.py to maintain a clean project structure.</li><li><strong>Streamlit Chat Components:</strong> Use st.chat_message() to display user and assistant messages and st.chat_input() to receive user input.</li><li><strong>Session State:</strong> Use st.session_state to maintain frontend conversation history across Streamlit script reruns.</li><li><strong>LangGraph Integration:</strong> Use the compiled chatbot’s invoke() method to send user messages from Streamlit to the LangGraph backend.</li><li><strong>Checkpointer and Thread ID:</strong> Use InMemorySaver as the backend checkpointer and pass a thread_id through the configuration to maintain conversation context.</li><li><strong>Context-Aware Responses:</strong> By combining frontend message history with LangGraph’s checkpointed state, the chatbot can use previous conversation messages when generating responses.</li></ul><p><strong>Remember:</strong> Streamlit’s session state manages the messages displayed in the UI, while LangGraph’s checkpointer manages the backend workflow state. Both play different but complementary roles in building a conversational chatbot.</p><h3>Conclusion</h3><p>Congratulations! 🎉 We’ve successfully built a context-aware chatbot with a user-friendly interface using <strong>LangGraph and Streamlit</strong>.</p><p>In this part, we learned how to separate backend AI logic from frontend UI code, manage conversation history using Streamlit’s session state, and connect everything with LangGraph’s workflow and checkpointer.</p><p>We also saw how thread_id helps LangGraph maintain conversational context across multiple interactions, allowing the chatbot to remember previous messages and generate more relevant responses.</p><p>With this foundation, you can now build more interactive AI applications by combining LangGraph’s powerful workflow capabilities with Streamlit’s simple and intuitive interface.</p><p><strong>That’s a wrap for Part 11!</strong> Keep experimenting, keep building, and I’ll see you in the next part of the LangGraph series.</p><h3>What’s Next?</h3><p>In the next part of this LangGraph series, <strong>Part 12: Streaming in LangGraph</strong>, we’ll take our chatbot one step further by introducing real-time response streaming.</p><p>So far, our chatbot waits for the LLM to generate the complete response before displaying it on the screen. But what happens when a user asks it to write a 500-word blog post or generate a long piece of code? The user has to wait until the entire response is ready.</p><p>We’ll solve this problem by implementing <strong>streaming</strong>, allowing the chatbot to display the AI’s response as it is generated, creating a smooth, typewriter-like experience.</p><p>In Part 12, we’ll explore:</p><ul><li><strong>What is Streaming?</strong> Understand how LLMs generate and deliver responses token by token.</li><li><strong>Why Streaming?</strong> Learn how streaming improves perceived response time and creates a more interactive user experience.</li><li><strong>LangGraph Streaming:</strong> Use LangGraph’s .stream() method to receive response chunks in real time.</li><li><strong>Streamlit Integration:</strong> Use st.write_stream() to display the generated text with a typewriter effect.</li><li><strong>Maintaining Conversation Memory:</strong> Save the fully assembled AI response in st.session_state after streaming completes.</li></ul><p>We’ll also upgrade our existing Streamlit chatbot without making structural changes to the LangGraph backend.</p><blockquote><strong><em>Next Part:</em></strong><em> Agentic AI using LangGraph — Part 12: </em><strong>Streaming in LangGraph</strong></blockquote><p><strong>Stay tuned for Part 12, where we’ll make our chatbot feel faster, more responsive, and more natural to interact with!</strong></p><blockquote><strong><em>Series:</em></strong><em> Agentic AI using LangGraph — Part 11 of 27</em></blockquote><h3>Connect with me</h3><p><strong><em>Connect with me on </em></strong><a href="https://www.linkedin.com/in/shubhamnagar234/"><strong><em>LinkedIn</em></strong></a><strong><em>, </em></strong><a href="https://github.com/shubhamnagar234"><strong><em>GitHub</em></strong></a><strong><em>, </em></strong><a href="https://x.com/nagarshubham234"><strong><em>X (Twitter)</em></strong></a><strong><em>, or explore my </em></strong><a href="https://shubhamnagar234.vercel.app/"><strong><em>Portfolio</em></strong></a><strong><em>.</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4280aaeb2156" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Persistence in LangGraph: Saving, Restoring, and Managing Workflow State — Part 10]]></title>
            <link>https://medium.com/@shubhamnagar234/persistence-in-langgraph-saving-restoring-and-managing-workflow-state-part-10-d786cbc8351e?source=rss-10b51a93c3a------2</link>
            <guid isPermaLink="false">https://medium.com/p/d786cbc8351e</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[persistence]]></category>
            <category><![CDATA[langgraph]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <dc:creator><![CDATA[Shubham Nagar]]></dc:creator>
            <pubDate>Thu, 26 Nov 2026 06:16:59 GMT</pubDate>
            <atom:updated>2026-11-26T06:17:27.842Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Learn How Persistence Works in LangGraph, Explore Checkpointers and Threads, and Build Stateful AI Workflows with Short-Term Memory, Fault Tolerance, Human-in-the-Loop, and Time Travel.</blockquote><p>Imagine building an AI chatbot that can remember previous conversations, even after a user closes the application and returns later.</p><p>Or consider an AI workflow that performs several steps. What happens if the application crashes halfway through? Do we have to execute every step again from the beginning?</p><p>These are important challenges when building real-world AI applications. A workflow needs more than the ability to execute tasks — it also needs a way to <strong>save its progress, remember previous interactions, and recover when something goes wrong.</strong></p><blockquote>This is where <strong>Persistence in LangGraph</strong> comes into the picture.</blockquote><p>Persistence allows LangGraph to save and restore the state of a workflow over time. Instead of keeping state only during execution, LangGraph can store intermediate and final state values at different checkpoints, making them available for future use.</p><p>With persistence, we can build applications that support:</p><ul><li><strong>Short-Term Memory:</strong> Maintain conversation history and resume previous interactions.</li><li><strong>Fault Tolerance:</strong> Recover interrupted workflows from their last successful checkpoint.</li><li><strong>Human-in-the-Loop (HITL):</strong> Pause workflows for human feedback or approval and resume them later.</li><li><strong>Time Travel:</strong> Revisit previous checkpoints, modify state, and execute workflows again from a selected point.</li></ul><p>In this part of the series, we’ll understand how persistence works internally, explore important concepts such as checkpointers and threads, and implement practical examples using LangGraph.</p><p>Let’s get started!</p><h3>Overview</h3><ul><li><strong><em>What is Persistence in LangGraph?</em></strong></li><li><strong><em>Why Persistence?</em></strong></li><li><strong><em>Speciality of Persistence</em></strong></li><li><strong><em>Key Concepts: Checkpointers and Threads</em></strong></li><li><strong><em>Building Chatbots with Persistence</em></strong></li><li><strong><em>Example of Checkpointer in Persistence</em></strong></li><li><strong><em>Benefits of Persistence</em></strong></li><li>Short-Term Memory</li><li>Fault Tolerance</li><li>Human-in-the-Loop (HITL)</li><li>Time Travel</li><li><strong><em>Example 1: Building a Joke Generator Using LangGraph (with LLM)</em></strong></li><li><strong><em>Example 2: Fault Tolerance — Simulating a Crash and Recovering</em></strong></li><li><strong><em>Final Thoughts</em></strong></li><li><strong><em>Key Takeaways</em></strong></li><li><strong><em>Conclusion</em></strong></li><li><strong><em>What’s Next?</em></strong></li></ul><h3>What is Persistence in LangGraph?</h3><p><strong>Persistence</strong> in LangGraph refers to the ability to <strong>save and restore the state of a workflow over time</strong>.</p><p>Normally, when a LangGraph workflow finishes executing using .invoke(), the state maintained during that execution remains in memory (RAM). Once the execution ends, that state is not automatically available for future executions.</p><p>Persistence solves this problem by saving workflow state — including intermediate values and the final output — so it can be retrieved later.</p><p>This allows us to:</p><ul><li><strong>Save Workflow State:</strong> Store intermediate values and final results instead of losing them after execution.</li><li><strong>Resume Interrupted Workflows:</strong> Continue execution from a previously saved checkpoint rather than starting from the beginning.</li><li><strong>Travel Back in Execution:</strong> Revisit previous checkpoints and inspect or modify the workflow state.</li></ul><p>This capability is especially useful when building:</p><ul><li><strong>Chatbots:</strong> Maintain conversation history across multiple interactions.</li><li><strong>Fault-Tolerant Pipelines:</strong> Recover workflows after interruptions or failures.</li><li><strong>Human-in-the-Loop Systems:</strong> Pause workflows for human input and resume them later.</li><li><strong>Long-Running Workflows:</strong> Preserve progress across multiple stages of execution.</li></ul><figure><img alt="Diagram illustrating how LangGraph persistence saves workflow state, including intermediate values and final output, so the workflow can retrieve its state and resume execution later." src="https://cdn-images-1.medium.com/max/1024/1*h6OuZRuHGEba2dV3kdRrSA.png" /><figcaption>Persistence in LangGraph — saving and restoring workflow state across execution checkpoints.</figcaption></figure><h3>Why Persistence?</h3><p>Persistence gives LangGraph workflows the ability to <strong>remember what happened during previous executions</strong> instead of losing their state when execution finishes or gets interrupted.</p><p>Think of persistence as a <strong>save point in a video game</strong>. If something goes wrong, you don’t have to start from the beginning. You can resume from the last saved checkpoint and continue where you left off.</p><p>In LangGraph, persistence stores intermediate state values at every <strong>superstep</strong> of the graph’s execution. This makes it possible to preserve workflow progress and retrieve it when needed.</p><p>Here are some important capabilities that persistence provides:</p><ul><li><strong>Fault Tolerance:</strong> If a workflow is interrupted or encounters an error, it can resume from its last saved checkpoint instead of executing everything again.</li><li><strong>Chatbot Memory:</strong> Chatbots can retain conversation history and allow users to resume previous conversations using a unique thread_id.</li><li><strong>Human-in-the-Loop (HITL):</strong> Workflows can pause and wait for human input or approval without losing their saved state. Once the input is provided, execution can continue.</li><li><strong>Time Travel:</strong> Developers can revisit previous checkpoints, inspect or update the saved state, and re-run the workflow from a selected point.</li></ul><p>With these capabilities, persistence makes workflows <strong>fault-tolerant, memory-enabled, and capable of continuing from previously saved progress</strong>.</p><p>It is an important foundation for building reliable AI applications that need to maintain state across multiple interactions and execution stages.</p><h3>Speciality of Persistence</h3><p>The unique power of <strong>Persistence in LangGraph</strong> is that it doesn’t just save the final output of a workflow. Instead, it captures and stores <strong>all intermediate state values at every superstep</strong> of the graph’s execution.</p><p>This means that even while a workflow is running, its progress is continuously saved through checkpoints. These saved states make it possible to inspect previous execution stages, recover from interruptions, and continue workflows without starting from scratch.</p><p>This capability unlocks four major features:</p><ul><li><strong>Short-Term Memory:</strong> Store conversation history and build chatbots that can remember and resume previous conversations.</li><li><strong>Fault Tolerance:</strong> Recover interrupted workflows from their last successful checkpoint instead of restarting the entire workflow.</li><li><strong>Human-in-the-Loop (HITL):</strong> Pause workflow execution and wait for human feedback or approval while preserving the current state.</li><li><strong>Time Travel:</strong> Navigate back to specific checkpoints to inspect, modify, debug, or replay workflow execution.</li></ul><p>These capabilities make persistence much more than a mechanism for saving results. It provides the foundation for building stateful, recoverable, and interactive AI workflows.</p><h3>Key Concepts: Checkpointers and Threads</h3><p>To understand how persistence works in LangGraph, we need to become familiar with two important concepts: <strong>Checkpointers</strong> and <strong>Threads</strong>.</p><h4>1. Checkpointers</h4><p>A <strong>Checkpointer</strong> is a core component of LangGraph persistence that saves the workflow’s state at every superstep of graph execution.</p><p>Instead of storing only the final output, a checkpointer creates checkpoints containing the state at different stages of execution. These checkpoints can later be retrieved to inspect previous states or resume a workflow.</p><p>To implement persistence, we define a checkpointer and pass it when compiling the graph.</p><p>For example, LangGraph provides InMemorySaver, which is useful for local development and testing.</p><pre>from langgraph.checkpoint.memory import InMemorySaver<br><br>checkpointer = InMemorySaver()<br><br>workflow = graph.compile(checkpointer=checkpointer)</pre><p>Here:</p><ul><li>InMemorySaver() creates an in-memory checkpointer.</li><li>graph.compile(checkpointer=checkpointer) enables checkpointing for the workflow.</li><li>The workflow’s state is saved at each superstep.</li></ul><p>For production applications, persistent database-backed options such as <strong>PostgreSQL</strong> or <strong>Redis</strong> can be used so that saved checkpoints remain available beyond the lifetime of the application process.</p><figure><img alt="Diagram illustrating how a LangGraph checkpointer saves the workflow state at each superstep, creating checkpoints that can be retrieved later." src="https://cdn-images-1.medium.com/max/1024/1*NtNnvD2XvQS6_lJQXDMzWw.png" /><figcaption>Checkpointers in LangGraph — saving workflow state at different execution checkpoints.</figcaption></figure><figure><img alt="Detailed diagram showing the relationship between graph execution, supersteps, and saved state checkpoints in LangGraph." src="https://cdn-images-1.medium.com/max/1024/1*C-akesB5Jr36kVmPJwmKSw.png" /><figcaption>Checkpointers in Persistence — a detailed view of how workflow state is saved across checkpoints.</figcaption></figure><h4>2. Threads</h4><p><strong>Threads</strong> allow LangGraph to maintain separate workflow executions using unique thread_id values.</p><p>A thread_id acts as an identifier for a particular workflow execution or conversation. It tells the checkpointer which saved state belongs to which thread.</p><p>For example:</p><pre>config1 = {<br>    &quot;configurable&quot;: {<br>        &quot;thread_id&quot;: &quot;user_01&quot;<br>    }<br>}<br><br>config2 = {<br>    &quot;configurable&quot;: {<br>        &quot;thread_id&quot;: &quot;user_02&quot;<br>    }<br>}</pre><p>In this example:</p><ul><li>user_01 stores the state associated with User 1&#39;s conversation.</li><li>user_02 stores the state associated with User 2&#39;s conversation.</li><li>Each thread maintains its own separate workflow state.</li></ul><p>This separation is particularly important when building chatbots that serve multiple users. Each user can continue their previous conversation without interfering with another user’s conversation.</p><figure><img alt="Diagram showing multiple users with separate thread IDs, where each thread stores and retrieves its own conversation state independently." src="https://cdn-images-1.medium.com/max/1024/1*LWARMSLnO7Rk_vhutnCifw.png" /><figcaption>Threads in LangGraph — maintaining separate workflow states for different users through unique thread IDs.</figcaption></figure><p>Together, <strong>Checkpointers and Threads</strong> form the foundation of persistence in LangGraph. Checkpointers save workflow states, while threads organize those saved states into separate execution histories.</p><h3>Building Chatbots with Persistence</h3><p>Building chatbots in LangGraph heavily relies on <strong>Persistence</strong> to manage conversation history and maintain continuity across multiple interactions.</p><p>Unlike standard workflows, where state is not automatically available after execution finishes, persistence allows a chatbot to save its conversation state and retrieve it whenever needed.</p><p>Let’s understand how this works.</p><h4>1. Memory and Continuity</h4><p>Persistence allows a chatbot to store the entire interaction history in a database instead of losing it after execution.</p><p>This makes it possible to:</p><ul><li>Maintain previous conversations.</li><li>Retrieve earlier messages.</li><li>Resume past conversations when a user returns.</li></ul><p>As a result, users can continue interacting with the chatbot without having to start a new conversation every time.</p><h4>2. The Role of Threads</h4><p>LangGraph uses <strong>threads</strong> to manage separate conversations or sessions.</p><p>Each conversation is assigned a unique thread_id. When a user wants to continue a previous conversation, the chatbot uses that thread ID to retrieve the associated messages and saved state.</p><p>For example:</p><ul><li>User 1’s conversation can be stored under thread_id = &quot;user_01&quot;.</li><li>User 2’s conversation can be stored under thread_id = &quot;user_02&quot;.</li></ul><p>This keeps conversations separate and allows each user to resume their own chat.</p><h4>3. State Management</h4><p>A chatbot’s state contains the exchange of messages between the human and the AI.</p><p>With persistence enabled, this state is saved at every checkpoint during graph execution. The saved conversation context can then be loaded again when the same thread is used.</p><p>This allows the chatbot to maintain continuity across multiple interactions.</p><figure><img alt="Diagram illustrating how LangGraph persistence saves chatbot messages in separate threads, allowing each conversation’s state to be retrieved and resumed later." src="https://cdn-images-1.medium.com/max/1024/1*MMXZ5Rg9PhxE6e7G_RGquw.png" /><figcaption>Building Chatbots with Persistence — managing conversation history and maintaining context using checkpoints and threads.</figcaption></figure><p>In short, <strong>persistence provides the memory foundation for stateful chatbots</strong>, while threads ensure that each conversation maintains its own history and context.</p><h3>Example of Checkpointer in Persistence</h3><p>Let’s look at a simple practical example of how to enable persistence in a LangGraph workflow using the <strong>InMemorySaver</strong> class.</p><p>InMemorySaver is a checkpointer primarily used for local development, testing, and demonstration purposes.</p><p>We can enable it in three simple steps.</p><h4>1. Import InMemorySaver</h4><p>First, import InMemorySaver from the langgraph.checkpoint.memory module.</p><pre>from langgraph.checkpoint.memory import InMemorySaver</pre><h4>2. Create a Checkpointer Instance</h4><p>Next, create an instance of the checkpointer.</p><pre>checkpointer = InMemorySaver()</pre><p>This creates an in-memory checkpointer that LangGraph can use to save workflow state.</p><h4>3. Compile the Graph with the Checkpointer</h4><p>Finally, pass the checkpointer to the graph’s compile() method.</p><pre>workflow = graph.compile(checkpointer=checkpointer)</pre><h3>Complete Code</h3><p>Combining all three steps:</p><pre>from langgraph.checkpoint.memory import InMemorySaver<br><br># Create a checkpointer<br>checkpointer = InMemorySaver()<br><br># Compile the graph with persistence enabled<br>workflow = graph.compile(checkpointer=checkpointer)</pre><p>That’s it! With this simple setup, LangGraph automatically saves intermediate and final workflow state values in memory at every superstep.</p><p><strong>Important:</strong> InMemorySaver is suitable for local development and testing. Since it stores checkpoints in memory, the saved data does not survive when the program stops. For production applications, use persistent database-backed checkpointers such as <strong>PostgreSQL</strong> or <strong>Redis</strong>.</p><figure><img alt="Code illustration showing how to import InMemorySaver, create a checkpointer instance, and pass it to the LangGraph compile() method to enable persistence." src="https://cdn-images-1.medium.com/max/1024/1*y2ehb6HVB3f5WZQu9qdBVg.png" /><figcaption>Example of Checkpointer in Persistence — enabling workflow state checkpointing using InMemorySaver.</figcaption></figure><h3>Benefits of Persistence</h3><p>Persistence in LangGraph provides four primary benefits that significantly enhance the capabilities of LLM-based workflows.</p><p>By saving workflow state at every superstep, LangGraph makes it possible to maintain conversation context, recover interrupted executions, involve humans in automated processes, and revisit previous execution states.</p><p>Let’s explore these four benefits in detail.</p><figure><img alt="Diagram illustrating the four primary benefits of LangGraph persistence: Short-Term Memory, Fault Tolerance, Human-in-the-Loop, and Time Travel." src="https://cdn-images-1.medium.com/max/1024/1*VtfUa1bpBOdCo1dCEaKEkg.png" /><figcaption>Benefits of Persistence in LangGraph — four major capabilities enabled by saving workflow state.</figcaption></figure><p>1. Short-Term Memory</p><p>2. Fault Tolerance</p><p>3. Human-in-the-Loop (HITL)</p><p>4. Time Travel</p><p>Each of these capabilities plays an important role in building reliable and stateful AI applications. Let’s understand them one by one.</p><h3>1. Short-Term Memory</h3><p>In LangGraph, <strong>Short-Term Memory</strong> refers to the system’s ability to maintain context during interactions by storing conversation history in a database.</p><p>It allows a chatbot to remember previous messages, maintain conversational context, and continue an interaction even after a user pauses or returns later.</p><p>Let’s understand how persistence makes this possible.</p><ul><li><strong>Persistence as the Foundation:</strong> Short-term memory relies on the persistence feature. Without storing interaction data, a chatbot cannot retrieve past messages or maintain conversation context across separate executions.</li><li><strong>Resuming Conversations:</strong> By leveraging persistent state, users can pause an interaction and resume their previous conversation from where they left off. This is an important requirement for building high-quality conversational AI applications.</li><li><strong>Practical Implementation:</strong> LangGraph saves and retrieves workflow states using different threads. Each thread maintains its own conversation history, ensuring that the model can access the relevant context throughout that conversation.</li></ul><figure><img alt="Diagram illustrating how LangGraph stores conversation history in persistent state and retrieves it using a thread, allowing a chatbot to resume previous interactions with their context intact." src="https://cdn-images-1.medium.com/max/1024/1*yQ3vN8A-L0n2ZfjKHHYH3g.png" /><figcaption>Short-Term Memory in LangGraph — maintaining conversation history through persistent state.</figcaption></figure><p>In short, <strong>Short-Term Memory allows LangGraph chatbots to maintain conversational continuity</strong> by saving and retrieving previous interactions through persistence.</p><h3>2. Fault Tolerance</h3><p><strong>Fault Tolerance</strong> ensures that if a workflow crashes — due to server downtime or API failures — you do not lose progress or need to restart the entire workflow from the beginning.</p><p>LangGraph achieves this through its checkpointing mechanism, which saves the workflow’s state at every intermediate superstep.</p><p>Let’s understand how it works.</p><ul><li><strong>Checkpointing Mechanism:</strong> By saving the state at every intermediate superstep, LangGraph maintains a record of the workflow’s progress up to the point of failure.</li><li><strong>Resumption:</strong> When a workflow is interrupted, invoking it again with the same thread_id allows LangGraph to retrieve the last successful checkpoint and continue execution from the saved state.</li><li><strong>Reliability:</strong> This capability is particularly useful for long-running or complex LLM-based workflows, providing a way to handle unexpected interruptions without unnecessarily repeating completed steps.</li></ul><figure><img alt="Diagram illustrating how LangGraph uses checkpointing to preserve workflow progress and resume execution from the last successful checkpoint after an interruption." src="https://cdn-images-1.medium.com/max/1024/1*Brip2EErAfxhvDYhuI0SLg.png" /><figcaption>Fault Tolerance in LangGraph — recovering interrupted workflows from their last saved checkpoint.</figcaption></figure><p>In short, <strong>Fault Tolerance helps LangGraph workflows recover from interruptions</strong> by preserving completed progress and allowing execution to continue from a saved checkpoint.</p><h3>3. Human-in-the-Loop (HITL)</h3><p><strong>Human-in-the-Loop (HITL)</strong> is a workflow pattern that allows human intervention or approval at specific stages of an automated process.</p><p>Instead of allowing a workflow to execute every step automatically, HITL introduces checkpoints where a human can review the results, provide input, or approve an action before execution continues.</p><p>Let’s understand how persistence makes this possible.</p><ul><li><strong>Mechanism:</strong> When a workflow reaches a point requiring human input — for example, approving a social media post before publishing — LangGraph interrupts and suspends execution.</li><li><strong>The Role of Persistence:</strong> Because the workflow state is saved at checkpoints, the workflow can remain paused without losing its state information. Once the human provides input, LangGraph retrieves the saved state and resumes execution from where it was interrupted.</li><li><strong>Use Cases:</strong> HITL is useful in automated agents, business approval workflows, content moderation, and multi-step pipelines where human review is required before proceeding.</li></ul><figure><img alt="Diagram illustrating a LangGraph workflow that pauses at a human review stage, preserves its state through persistence, and resumes execution after receiving human input." src="https://cdn-images-1.medium.com/max/1024/1*O7COyiMuGShjkkoCGf8Nsw.png" /><figcaption>Human-in-the-Loop in LangGraph — pausing workflow execution for human review and resuming after approval or input.</figcaption></figure><p>In short, <strong>Human-in-the-Loop allows humans to remain part of automated workflows</strong> while persistence ensures that the workflow can pause and resume without losing its saved state.</p><h3>4. Time Travel</h3><p><strong>Time Travel</strong> is a powerful debugging and development feature in LangGraph that allows you to revisit or replay previous states of a workflow execution.</p><p>Since persistence stores intermediate state values at specific checkpoints, developers can navigate through the workflow’s execution history and continue execution from a selected point.</p><p>Let’s understand how it works.</p><ul><li><strong>Mechanism:</strong> Because persistence stores intermediate states at different checkpoints, you can use a checkpoint_id to identify and revisit a specific point in the workflow&#39;s execution history.</li><li><strong>Re-execution:</strong> You can use get_state() to inspect the saved state associated with a checkpoint. By invoking the workflow from that checkpoint, you can re-run the remaining nodes from that point forward.</li><li><strong>State Modification:</strong> You can use update_state() to modify the state at a specific checkpoint. This creates a new branch in the execution history, allowing you to experiment with alternative inputs or scenarios without changing the original execution history.</li></ul><figure><img alt="Diagram illustrating how LangGraph time travel allows developers to navigate to previous checkpoints, inspect or update saved state, and re-execute the workflow from a selected point." src="https://cdn-images-1.medium.com/max/1024/1*4V2ceeAkzoswSN-wqc4YDw.png" /><figcaption>Time Travel in LangGraph — revisiting previous checkpoints, modifying workflow state, and replaying execution.</figcaption></figure><p>In short, <strong>Time Travel makes workflow execution easier to inspect, debug, and experiment with</strong> by allowing developers to revisit and branch from previously saved states.</p><h3>Example 1: Building a Joke Generator Using LangGraph: A Step-by-Step Guide (with LLM)</h3><h4>What We’re Building</h4><p>In this example, we’ll build a simple <strong>Joke Generator and Explainer</strong> using:</p><ul><li><strong>Large Language Model (LLM):</strong> To generate jokes and explain their meaning.</li><li><strong>LangGraph:</strong> To organize the workflow into sequential steps.</li><li><strong>InMemorySaver:</strong> To enable persistence through checkpointing.</li></ul><p>Our application will:</p><ol><li>Take a topic as input.</li><li>Generate a joke about that topic.</li><li>Generate an explanation of the joke.</li><li>Save the workflow state under a unique thread_id.</li><li>Allow us to inspect the complete state history.</li><li>Demonstrate <strong>Time Travel</strong> by revisiting a previous checkpoint and modifying the workflow state.</li></ol><h4>Understanding the Workflow: A Visual Breakdown</h4><p>Our joke generator consists of two sequential nodes:</p><figure><img alt="LangGraph workflow showing the START node, followed by generate_joke and generate_explanation nodes, and finally the END node." src="https://cdn-images-1.medium.com/max/921/1*2eyMcj3SHG2BZTVf-WZlrw.png" /><figcaption>Joke Generator Workflow — an overview of the sequential execution flow with persistence.</figcaption></figure><p>Let’s understand each component.</p><p><strong>START</strong></p><p>The workflow begins here. We provide the input topic that will be used to generate a joke.</p><p><strong>generate_joke</strong></p><ul><li>The LLM generates a joke based on the given topic.</li><li>The generated joke is stored in the joke field of the workflow state.</li></ul><p><strong>generate_explanation</strong></p><ul><li>The LLM reads the generated joke from the state.</li><li>It creates an explanation of the joke.</li><li>The explanation is stored in the explanation field.</li></ul><p><strong>END</strong></p><p>The workflow finishes execution. Its final state contains the topic, joke, and explanation fields, and the checkpointer saves the state under the specified thread_id.</p><figure><img alt="Example of the LangGraph joke generator processing a topic through joke generation and explanation nodes before producing the final state." src="https://cdn-images-1.medium.com/max/1024/1*Ovnr2flDAWHxtZJf7Xp4Hg.png" /><figcaption>Joke Generator Workflow with Example — a visual representation of the workflow using a sample input topic.</figcaption></figure><h4>1. Import &amp; Setup</h4><p>First, let’s import the required libraries and components.</p><pre># If using ChatOpenAI<br># from langchain_openai import ChatOpenAI<br><br># If using ChatGoogleGenerativeAI<br>from langchain_google_genai import ChatGoogleGenerativeAI<br>from langgraph.graph import StateGraph, START, END<br>from langgraph.checkpoint.memory import InMemorySaver<br>from typing import TypedDict<br>from dotenv import load_dotenv</pre><p><strong>Understanding the Imports:</strong></p><ul><li><strong>LLM Integration:</strong> We import ChatGoogleGenerativeAI to power our joke generator and explainer.</li><li><strong>Core Tools:</strong> We import StateGraph, START, and END to structure the workflow.</li><li><strong>Persistence:</strong> We import InMemorySaver from langgraph.checkpoint.memory. This checkpointer saves workflow state in RAM.</li><li><strong>State Definition:</strong> We use TypedDict to define the structure of our workflow state.</li><li><strong>Environment Configuration:</strong> We use load_dotenv() to load API credentials from a .env file.</li></ul><h4>2. Configure Environment Variables</h4><p>Next, let’s load our environment variables.</p><pre>load_dotenv()</pre><p><strong>Understanding the Configuration:</strong></p><ul><li><strong>API Keys:</strong> Store your API credentials in a .env file, such as GEMINI_API_KEY or OPENAI_API_KEY, depending on the provider you use.</li><li><strong>Loading:</strong> The load_dotenv() function loads these credentials into the application&#39;s environment so that the LLM integration can access them.</li></ul><h4>3. Initialize the LLM</h4><p>Now, let’s initialize the language model that will generate our jokes and explanations.</p><pre># If using ChatOpenAI<br># Initialize ChatOpenAI<br># llm = ChatOpenAI(model=&quot;gpt-4o-mini&quot;)<br><br># If using ChatGoogleGenerativeAI<br># Initialize ChatGoogleGenerativeAI<br>llm = ChatGoogleGenerativeAI(model=&quot;gemini-2.5-flash&quot;)</pre><p><strong>Understanding the Model Initialization:</strong></p><ul><li><strong>Model Selection:</strong> We initialize Google’s Gemini 2.5 Flash model using ChatGoogleGenerativeAI.</li><li><strong>Flexibility:</strong> The commented-out ChatOpenAI alternative shows how you can switch to an OpenAI model if required.</li></ul><p>The llm object will be used inside our workflow nodes to generate the joke and its explanation.</p><h4>4. Define the State (JokeState)</h4><p>Before creating our workflow nodes, we need to define the structure of the state that will be shared across the graph.</p><pre># Define the state<br>class JokeState(TypedDict):<br><br>    topic: str<br>    joke: str<br>    explanation: str</pre><p><strong>Understanding the State:</strong></p><p>Our JokeState contains three fields:</p><ul><li><strong>topic:</strong> Stores the input topic provided by the user.</li><li><strong>joke:</strong> Stores the joke generated by the LLM.</li><li><strong>explanation:</strong> Stores the explanation of the generated joke.</li></ul><p>Every node in the workflow can read the available state values and return updates to the state.</p><p>For example, the generate_joke node reads topic and updates joke. The next node reads joke and updates explanation.</p><p>This shared state allows information to flow automatically between the nodes.</p><h4>5. Build the Graph</h4><p>Now, let’s initialize our LangGraph workflow using the StateGraph class.</p><pre>graph = StateGraph(JokeState)</pre><p>Here:</p><ul><li>StateGraph creates the graph structure.</li><li>JokeState defines the schema of the state that will be shared across the workflow.</li></ul><p>We will register our functions as nodes and connect them using edges in the next steps.</p><h4>6. Define Your Workflow Nodes (Functions)</h4><p>Our workflow requires two nodes:</p><ol><li>generate_joke</li><li>generate_explanation</li></ol><p>Each node performs a specific task using the LLM.</p><p><strong>Node 1: generate_joke</strong></p><p>This node takes the input topic from the state and asks the LLM to generate a joke.</p><pre># Define generate_joke<br>def generate_joke(state: JokeState) -&gt; JokeState:<br><br>    prompt = f&#39;generate a joke on the topic {state[&quot;topic&quot;]}&#39;<br>    response = llm.invoke(prompt).content<br>    return {&#39;joke&#39;: response}</pre><p><strong>Understanding the Function:</strong></p><ul><li><strong>Input:</strong> The function receives the current workflow state.</li><li><strong>Prompt:</strong> It extracts the topic from the state and constructs a prompt for the LLM.</li><li><strong>LLM Invocation:</strong> llm.invoke(prompt) sends the prompt to the language model.</li><li><strong>State Update:</strong> The generated response is returned in the joke field.</li></ul><p>Notice that the function returns only {&#39;joke&#39;: response} instead of the entire state. LangGraph merges this partial update into the existing workflow state.</p><h4>Node 2: generate_explanation</h4><p>The second node reads the generated joke and asks the LLM to explain it.</p><pre># Define generate_explanation<br>def generate_explanation(state: JokeState) -&gt; JokeState:<br><br>    prompt = f&#39;write an explanation for the joke - {state[&quot;joke&quot;]}&#39;<br>    response = llm.invoke(prompt).content<br>    return {&#39;explanation&#39;: response}</pre><p><strong>Understanding the Function:</strong></p><ul><li><strong>Input:</strong> The function receives the updated workflow state.</li><li><strong>Prompt:</strong> It extracts the generated joke from the joke field.</li><li><strong>LLM Invocation:</strong> The LLM generates an explanation of the joke.</li><li><strong>State Update:</strong> The function returns the explanation in the explanation field.</li></ul><p>Just like the previous node, LangGraph merges this partial update into the existing state.</p><h4>7. Build the LangGraph Workflow</h4><p>Now that we have defined our nodes, let’s connect them to create the complete workflow.</p><pre># Add nodes to the graph<br>graph.add_node(&#39;generate_joke&#39;, generate_joke)<br>graph.add_node(&#39;generate_explanation&#39;, generate_explanation)<br><br># Define the workflow edges<br>graph.add_edge(START, &#39;generate_joke&#39;)<br>graph.add_edge(&#39;generate_joke&#39;, &#39;generate_explanation&#39;)<br>graph.add_edge(&#39;generate_explanation&#39;, END)<br><br># Create a checkpointer<br>checkpointer = InMemorySaver()<br><br># Compile the workflow with persistence<br>workflow = graph.compile(checkpointer=checkpointer)</pre><p><strong>Understanding the Workflow:</strong></p><p><strong>1. Register Nodes</strong></p><pre>graph.add_node(&#39;generate_joke&#39;, generate_joke)<br>graph.add_node(&#39;generate_explanation&#39;, generate_explanation)</pre><p>We register both functions as nodes in the graph.</p><p><strong>2. Define Edges</strong></p><pre>graph.add_edge(START, &#39;generate_joke&#39;)<br>graph.add_edge(&#39;generate_joke&#39;, &#39;generate_explanation&#39;)<br>graph.add_edge(&#39;generate_explanation&#39;, END)</pre><p>These edges define the sequential execution flow:</p><p>START → generate_joke → generate_explanation → END</p><p><strong>3. Enable Persistence</strong></p><pre>checkpointer = InMemorySaver()</pre><p>We create an instance of InMemorySaver, which acts as our checkpointer.</p><p><strong>4. Compile the Workflow</strong></p><pre>workflow = graph.compile(checkpointer=checkpointer)</pre><p>By passing the checkpointer to compile(), we enable persistence for our workflow.</p><p>LangGraph can now save the workflow state at different checkpoints during execution.</p><h4>8. Workflow Graph</h4><p>Let’s visualize our completed workflow using Mermaid.</p><pre>from IPython.display import Image, display<br><br>display(Image(workflow.get_graph().draw_mermaid_png()))</pre><p>This generates a visual representation of the graph, showing the nodes and edges we defined.</p><figure><img alt="LangGraph visualization showing the START node connected to generate_joke, followed by generate_explanation, and ending at END." src="https://cdn-images-1.medium.com/max/200/1*DaKtZINaPxm6k8P18AP7WA.png" /><figcaption>Building a Joke Generator Using LangGraph — the complete workflow graph with sequential execution and persistence.</figcaption></figure><h4>9. Execute the Workflow (Thread 1)</h4><p>Now, let’s execute our workflow with a sample topic.</p><p>First, we define a configuration containing a unique thread_id.</p><pre>config1 = {<br>    &quot;configurable&quot;: {<br>        &quot;thread_id&quot;: &quot;1&quot;<br>    }<br>}</pre><p>Next, invoke the workflow:</p><pre>workflow.invoke(<br>    {&#39;topic&#39;: &#39;pizza&#39;},<br>    config=config1<br>)</pre><p><strong>Understanding the Execution:</strong></p><ul><li><strong>Configuration:</strong> We define thread_id = &quot;1&quot; to uniquely identify this workflow execution&#39;s saved state.</li><li><strong>Input:</strong> We pass pizza as the input topic.</li><li><strong>Invocation:</strong> The workflow executes both nodes sequentially.</li><li><strong>Persistence:</strong> The checkpointer saves the workflow state under thread_id = &quot;1&quot;.</li></ul><p>The final state contains:</p><ul><li>topic: pizza</li><li>joke: The joke generated by the LLM.</li><li>explanation: The explanation generated by the LLM.</li></ul><p>The actual joke and explanation will depend on the model’s response.</p><h4>10. Inspect the Saved State</h4><p>One of the biggest advantages of persistence is that we can inspect the saved state even after the workflow has finished executing.</p><p>LangGraph provides two useful methods for this.</p><p><strong>1. Get the Current State</strong></p><pre>workflow.get_state(config1)</pre><p>The get_state() method retrieves the latest saved state associated with the specified thread.</p><p>It allows us to inspect the values of topic, joke, and explanation, along with checkpoint metadata.</p><p><strong>2. Get the Complete State History</strong></p><pre>list(workflow.get_state_history(config1))</pre><p>The get_state_history() method retrieves the checkpoint history for the specified thread.</p><p>It allows us to inspect the intermediate states created during workflow execution.</p><p>For example, we can examine:</p><ul><li>The initial state containing the input topic.</li><li>The state after the generate_joke node executes.</li><li>The state after the generate_explanation node executes.</li></ul><p>This history is particularly important because it forms the foundation of <strong>Time Travel</strong> and <strong>Fault Tolerance</strong> in LangGraph.</p><h4>11. Run a Second Thread (Thread 2)</h4><p>Now, let’s execute the same workflow with another topic using a different thread_id.</p><pre>config2 = {<br>    &quot;configurable&quot;: {<br>        &quot;thread_id&quot;: &quot;2&quot;<br>    }<br>}<br><br>workflow.invoke(<br>    {&#39;topic&#39;: &#39;pasta&#39;},<br>    config=config2<br>)</pre><p>Next, inspect the saved state and its history:</p><pre>workflow.get_state(config2)<br><br>list(workflow.get_state_history(config2))</pre><p><strong>Understanding Threads:</strong></p><ul><li><strong>Thread 1:</strong> Stores the workflow state for the pizza topic.</li><li><strong>Thread 2:</strong> Stores the workflow state for the pasta topic.</li><li><strong>Isolation:</strong> Both threads maintain independent execution histories.</li></ul><p>Even though both executions use the same compiled workflow, their saved states remain separate because they use different thread_id values.</p><p>This is exactly how we can manage multiple conversations in a chatbot application: each user or conversation can have its own thread ID.</p><h4>12. Time Travel — Jump to a Previous Checkpoint</h4><p>Now comes one of the most interesting features of LangGraph persistence: <strong>Time Travel</strong>.</p><p>Time Travel allows us to revisit a previous checkpoint, inspect its state, modify it, and execute the workflow again from that point.</p><p>For this demonstration, we’ll revisit the checkpoint where the input topic is available but the joke has not yet been generated.</p><p><strong>Important Note:</strong> In the LangGraph 1.2.x example using InMemorySaver, checkpoint IDs exist in memory during the current session. Therefore, never hardcode checkpoint IDs. Always retrieve them dynamically from the workflow&#39;s state history.</p><p><strong>Step 1: Inspect a Previous Checkpoint Dynamically</strong></p><p>First, retrieve the complete checkpoint history.</p><pre># Get all checkpoints saved so far<br>history = list(workflow.get_state_history(config1))<br><br># Find the checkpoint where topic exists but joke has not been generated<br>target_snapshot = [<br>    s for s in history<br>    if s.values.get(&#39;topic&#39;) and not s.values.get(&#39;joke&#39;)<br>][-1]<br># Extract the checkpoint ID dynamically<br>target_checkpoint_id = (<br>    target_snapshot.config[&#39;configurable&#39;][&#39;checkpoint_id&#39;]<br>)<br><br>print(&#39;Target checkpoint_id:&#39;, target_checkpoint_id)<br>print(&#39;State at that point:&#39;, target_snapshot.values)</pre><p><strong>Understanding the Code:</strong></p><ul><li><strong>State History:</strong> get_state_history() retrieves all saved checkpoints for Thread 1.</li><li><strong>Checkpoint Selection:</strong> We filter the history to find a checkpoint where topic exists but joke has not yet been generated.</li><li><strong>Dynamic Lookup:</strong> We extract the checkpoint_id from the selected snapshot instead of hardcoding it.</li><li><strong>State Inspection:</strong> We print the state stored at that checkpoint.</li></ul><p>At this point, the workflow has the input topic, but the generate_joke node has not yet completed.</p><p><strong>Step 2: Fork the Previous Checkpoint Using update_state()</strong></p><p>Now, let’s modify the state at that checkpoint.</p><p>Instead of generating a joke about pizza, we&#39;ll change the topic to samosa.</p><pre># Fork the previous checkpoint using update_state()<br>new_config = workflow.update_state(<br>    {<br>        &quot;configurable&quot;: {<br>            &quot;thread_id&quot;: &quot;1&quot;,<br>            &quot;checkpoint_id&quot;: target_checkpoint_id,<br>            &quot;checkpoint_ns&quot;: &quot;&quot;<br>        }<br>    },<br>    {&#39;topic&#39;: &#39;samosa&#39;}<br>)<br><br>print(<br>    &#39;New checkpoint_id after fork:&#39;,<br>    new_config[&#39;configurable&#39;][&#39;checkpoint_id&#39;]<br>)</pre><p><strong>Understanding the Code:</strong></p><ul><li><strong>update_state():</strong> Updates the state associated with the selected checkpoint.</li><li><strong>Thread ID:</strong> We specify thread_id = &quot;1&quot; to identify the original execution.</li><li><strong>Checkpoint ID:</strong> We select the checkpoint we want to branch from.</li><li><strong>State Modification:</strong> We change the topic from pizza to samosa.</li></ul><p>The important point here is that update_state() creates a new checkpoint based on the selected previous state.</p><p>This gives us a separate branch in the execution history, allowing us to experiment with a different input without replacing the original execution.</p><p><strong>Step 3: Resume from the Forked Checkpoint</strong></p><p>Now that we have created a new checkpoint, let’s resume the workflow from it.</p><pre># Resume from the newly created checkpoint<br>result = workflow.invoke(<br>    None,<br>    {<br>        &quot;configurable&quot;: {<br>            &quot;thread_id&quot;: &quot;1&quot;,<br>            &quot;checkpoint_id&quot;: new_config[&#39;configurable&#39;][&#39;checkpoint_id&#39;]<br>        }<br>    }<br>)<br><br>print(&#39;Topic:&#39;, result[&#39;topic&#39;])<br>print(&#39;Joke:&#39;, result[&#39;joke&#39;])</pre><p><strong>Understanding the Code:</strong></p><ul><li><strong>invoke(None, ...):</strong> We pass None because the input state is already available in the newly created checkpoint.</li><li><strong>Checkpoint ID:</strong> We use the checkpoint ID returned by update_state().</li><li><strong>Resumption:</strong> LangGraph resumes execution from the forked checkpoint and continues with the remaining workflow nodes.</li></ul><p>Since we changed the topic to samosa, the generate_joke node generates a new joke about samosa, followed by the explanation node.</p><p><strong>Why Is This Useful?</strong></p><p>This technique is useful for:</p><ul><li>Debugging workflows.</li><li>Testing alternative inputs.</li><li>Running what-if experiments.</li><li>Re-executing specific stages without restarting the entire workflow.</li></ul><figure><img alt="Diagram illustrating LangGraph time travel. The workflow starts with the topic pizza, saves checkpoints during joke generation and explanation, and allows developers to travel back to a previous checkpoint, inspect and debug the state, change the topic to samosa, and resume execution through a new branch." src="https://cdn-images-1.medium.com/max/1024/1*4V2ceeAkzoswSN-wqc4YDw.png" /><figcaption>Time Travel in LangGraph — revisiting previous checkpoints, inspecting workflow state, debugging execution, and creating a new branch with a modified topic.</figcaption></figure><h4>13. Update State at a Checkpoint</h4><p>We have already seen how to use update_state() to create a new branch from a previous checkpoint.</p><p>Let’s look at the same capability from another perspective: modifying a past checkpoint and inspecting how the execution history changes.</p><pre># Update a past checkpoint to create a new branch<br># Reuse target_checkpoint_id from the Time Travel section<br><br>branch_config = workflow.update_state(<br>    {<br>        &quot;configurable&quot;: {<br>            &quot;thread_id&quot;: &quot;1&quot;,<br>            &quot;checkpoint_id&quot;: target_checkpoint_id,<br>            &quot;checkpoint_ns&quot;: &quot;&quot;<br>        }<br>    },<br>    {&#39;topic&#39;: &#39;samosa&#39;}<br>)<br><br>print(branch_config)</pre><p>Here, update_state() creates a new checkpoint based on the selected historical state and updates the topic field.</p><p>Let’s inspect the updated execution history:</p><pre>list(workflow.get_state_history(config1))</pre><p>Now, invoke the workflow from the newly created branch.</p><pre># Invoke from the branched checkpoint<br>result = workflow.invoke(<br>    None,<br>    {<br>        &quot;configurable&quot;: {<br>            &quot;thread_id&quot;: &quot;1&quot;,<br>            &quot;checkpoint_id&quot;: branch_config[&#39;configurable&#39;][&#39;checkpoint_id&#39;]<br>        }<br>    }<br>)<br><br>print(&#39;Topic:&#39;, result[&#39;topic&#39;])<br>print(&#39;Joke:&#39;, result[&#39;joke&#39;])</pre><p>Finally, inspect the state history again:</p><pre>list(workflow.get_state_history(config1))</pre><p><strong>Understanding State Modification:</strong></p><ul><li><strong>State Modification:</strong> update_state() allows us to modify state values at a specific historical checkpoint.</li><li><strong>Branch Creation:</strong> The modified state creates a new checkpoint and execution branch.</li><li><strong>Dynamic Checkpoint IDs:</strong> We use branch_config[&#39;configurable&#39;][&#39;checkpoint_id&#39;] to retrieve the new checkpoint ID generated in the current session.</li><li><strong>Workflow Execution:</strong> We invoke the workflow from the newly created branch to generate a joke using the modified topic.</li></ul><p>This allows us to experiment with alternative scenarios without restarting the entire workflow or losing the original execution history.</p><h4>14. Complete Code</h4><p>Now that we’ve implemented every component of our Joke Generator, let’s combine everything into a single Python script.</p><p>This complete implementation includes:</p><ul><li>LLM initialization using Gemini 2.5 Flash.</li><li>State definition and workflow node creation.</li><li>Graph construction and compilation with InMemorySaver.</li><li>Workflow execution using multiple threads.</li><li>State inspection and checkpoint history retrieval.</li><li>Time Travel using dynamically retrieved checkpoint IDs.</li><li>State modification and branching using update_state().</li></ul><p>Before running the code, make sure your .env file contains your Gemini API key.</p><pre><br># ==========================================<br># 1. Import &amp; Setup<br># ==========================================<br><br># If using ChatOpenAI<br># from langchain_openai import ChatOpenAI<br># If using ChatGoogleGenerativeAIs<br>from langchain_google_genai import ChatGoogleGenerativeAI<br>from langgraph.graph import StateGraph, START, END<br>from langgraph.checkpoint.memory import InMemorySaver<br>from typing import TypedDict<br>from dotenv import load_dotenv<br><br><br># ==========================================<br># 2. Configure Environment Variables<br># ==========================================<br><br>load_dotenv()<br><br><br># ==========================================<br># 3. Initialize the LLM<br># ==========================================<br><br># If using ChatOpenAI<br># Initialize ChatOpenAI<br># llm = ChatOpenAI(model=&quot;gpt-4o-mini&quot;)<br><br># If using ChatGoogleGenerativeAI<br># Initialize ChatGoogleGenerativeAI<br>llm = ChatGoogleGenerativeAI(model=&quot;gemini-2.5-flash&quot;)<br><br><br># ==========================================<br># 4. Define the State<br># ==========================================<br><br>class JokeState(TypedDict):<br>    topic: str<br>    joke: str<br>    explanation: str<br><br><br># ==========================================<br># 5. Build the Graph<br># ==========================================<br><br>graph = StateGraph(JokeState)<br><br><br># ==========================================<br># 6. Define Workflow Nodes<br># ==========================================<br><br>def generate_joke(state: JokeState) -&gt; JokeState:<br><br>    prompt = f&#39;generate a joke on the topic {state[&quot;topic&quot;]}&#39;<br>    response = llm.invoke(prompt).content<br><br>    return {&quot;joke&quot;: response}<br><br><br>def generate_explanation(state: JokeState) -&gt; JokeState:<br><br>    prompt = f&#39;write an explanation for the joke - {state[&quot;joke&quot;]}&#39;<br>    response = llm.invoke(prompt).content<br><br>    return {&quot;explanation&quot;: response}<br><br><br># ==========================================<br># 7. Build the LangGraph Workflow<br># ==========================================<br><br>graph.add_node(&quot;generate_joke&quot;, generate_joke)<br>graph.add_node(&quot;generate_explanation&quot;, generate_explanation)<br><br>graph.add_edge(START, &quot;generate_joke&quot;)<br>graph.add_edge(&quot;generate_joke&quot;, &quot;generate_explanation&quot;)<br>graph.add_edge(&quot;generate_explanation&quot;, END)<br><br># Enable Persistence<br>checkpointer = InMemorySaver()<br><br>workflow = graph.compile(checkpointer=checkpointer)<br><br><br># ==========================================<br># 8. Visualize the Workflow Graph<br># ==========================================<br><br>from IPython.display import Image, display<br><br>display(Image(workflow.get_graph().draw_mermaid_png()))<br><br><br># ==========================================<br># 9. Execute the Workflow (Thread 1)<br># ==========================================<br><br>config1 = {<br>    &quot;configurable&quot;: {<br>        &quot;thread_id&quot;: &quot;1&quot;<br>    }<br>}<br><br>result1 = workflow.invoke(<br>    {&quot;topic&quot;: &quot;pizza&quot;},<br>    config=config1<br>)<br><br>print(&quot;Thread 1 Result:&quot;)<br>print(result1)<br><br><br># ==========================================<br># 10. Inspect the Saved State<br># ==========================================<br><br>print(&quot;\nCurrent State:&quot;)<br>print(workflow.get_state(config1))<br><br>print(&quot;\nState History:&quot;)<br>history = list(workflow.get_state_history(config1))<br><br>for snapshot in history:<br>    print(snapshot.values)<br><br><br># ==========================================<br># 11. Run a Second Thread (Thread 2)<br># ==========================================<br><br>config2 = {<br>    &quot;configurable&quot;: {<br>        &quot;thread_id&quot;: &quot;2&quot;<br>    }<br>}<br><br>result2 = workflow.invoke(<br>    {&quot;topic&quot;: &quot;pasta&quot;},<br>    config=config2<br>)<br><br>print(&quot;\nThread 2 Result:&quot;)<br>print(result2)<br><br>print(&quot;\nThread 2 State:&quot;)<br>print(workflow.get_state(config2))<br><br>print(&quot;\nThread 2 History:&quot;)<br>print(list(workflow.get_state_history(config2)))<br><br><br># ==========================================<br># 12. Time Travel - Jump to a Previous Checkpoint<br># ==========================================<br><br># Step 1: Retrieve checkpoint history dynamically<br><br>history = list(workflow.get_state_history(config1))<br><br># Find the checkpoint where topic exists<br># but joke has not been generated yet<br><br>target_snapshot = [<br>    snapshot<br>    for snapshot in history<br>    if snapshot.values.get(&quot;topic&quot;)<br>    and not snapshot.values.get(&quot;joke&quot;)<br>][-1]<br><br>target_checkpoint_id = (<br>    target_snapshot.config[&quot;configurable&quot;][&quot;checkpoint_id&quot;]<br>)<br><br>print(&quot;\nTarget Checkpoint ID:&quot;)<br>print(target_checkpoint_id)<br><br>print(&quot;\nState at Target Checkpoint:&quot;)<br>print(target_snapshot.values)<br><br><br># Step 2: Fork the previous checkpoint using update_state()<br><br>new_config = workflow.update_state(<br>    {<br>        &quot;configurable&quot;: {<br>            &quot;thread_id&quot;: &quot;1&quot;,<br>            &quot;checkpoint_id&quot;: target_checkpoint_id,<br>            &quot;checkpoint_ns&quot;: &quot;&quot;<br>        }<br>    },<br>    {&quot;topic&quot;: &quot;samosa&quot;}<br>)<br><br>print(&quot;\nNew Checkpoint ID:&quot;)<br>print(new_config[&quot;configurable&quot;][&quot;checkpoint_id&quot;])<br><br><br># Step 3: Resume from the forked checkpoint<br><br>result = workflow.invoke(<br>    None,<br>    {<br>        &quot;configurable&quot;: {<br>            &quot;thread_id&quot;: &quot;1&quot;,<br>            &quot;checkpoint_id&quot;: new_config[&quot;configurable&quot;][&quot;checkpoint_id&quot;]<br>        }<br>    }<br>)<br><br>print(&quot;\nTime Travel Result:&quot;)<br>print(&quot;Topic:&quot;, result[&quot;topic&quot;])<br>print(&quot;Joke:&quot;, result[&quot;joke&quot;])<br>print(&quot;Explanation:&quot;, result[&quot;explanation&quot;])<br><br><br># ==========================================<br># 13. Update State at a Checkpoint<br># ==========================================<br><br># Create another branch from the original checkpoint<br><br>branch_config = workflow.update_state(<br>    {<br>        &quot;configurable&quot;: {<br>            &quot;thread_id&quot;: &quot;1&quot;,<br>            &quot;checkpoint_id&quot;: target_checkpoint_id,<br>            &quot;checkpoint_ns&quot;: &quot;&quot;<br>        }<br>    },<br>    {&quot;topic&quot;: &quot;samosa&quot;}<br>)<br><br>print(&quot;\nBranch Configuration:&quot;)<br>print(branch_config)<br><br><br># Inspect the updated state history<br><br>print(&quot;\nUpdated State History:&quot;)<br>print(list(workflow.get_state_history(config1)))<br><br><br># Invoke the workflow from the branched checkpoint<br><br>branch_result = workflow.invoke(<br>    None,<br>    {<br>        &quot;configurable&quot;: {<br>            &quot;thread_id&quot;: &quot;1&quot;,<br>            &quot;checkpoint_id&quot;: branch_config[&quot;configurable&quot;][&quot;checkpoint_id&quot;]<br>        }<br>    }<br>)<br><br>print(&quot;\nBranch Execution Result:&quot;)<br>print(&quot;Topic:&quot;, branch_result[&quot;topic&quot;])<br>print(&quot;Joke:&quot;, branch_result[&quot;joke&quot;])<br>print(&quot;Explanation:&quot;, branch_result[&quot;explanation&quot;])<br><br><br># Inspect the final execution history<br><br>print(&quot;\nFinal State History:&quot;)<br>print(list(workflow.get_state_history(config1)))</pre><h4>Important Notes</h4><ol><li><strong>Environment Variables:</strong> Make sure your .env file contains a valid GEMINI_API_KEY.</li><li><strong>In-Memory Persistence:</strong> InMemorySaver stores checkpoints in RAM. They are available during the current process/session but are not durable across application restarts.</li><li><strong>Thread Isolation:</strong> Thread 1 and Thread 2 maintain separate workflow states.</li><li><strong>Dynamic Checkpoint IDs:</strong> Always retrieve checkpoint IDs from the state history rather than hardcoding them.</li><li><strong>Time Travel:</strong> update_state() creates a new checkpoint based on a previous state, allowing you to create a separate execution branch.</li></ol><p><strong>Note:</strong> The code is designed to run in a Python environment with the required LangChain, LangGraph, Gemini integration, and dotenv packages installed. The visualization snippet uses IPython/Jupyter display functionality.</p><p>With this complete implementation, you can experiment with persistence, inspect execution history, and explore how LangGraph supports time travel and state branching in a practical application.</p><h3>Example 2: Fault Tolerance — Simulating a Crash and Recovering: A Step-by-Step Guide</h3><h4>What We’re Building</h4><p>In this example, we’ll demonstrate <strong>Fault Tolerance in LangGraph</strong> by creating a simple three-step workflow and deliberately interrupting its execution.</p><p>We’ll use:</p><ul><li><strong>LangGraph:</strong> To organize our workflow into sequential steps.</li><li><strong>InMemorySaver:</strong> To enable persistence through checkpointing.</li><li><strong>Python </strong><strong>time module:</strong> To simulate a long-running operation that we can interrupt manually.</li></ul><p>Our application will:</p><ol><li>Execute a three-step workflow (step_1 → step_2 → step_3).</li><li>Save workflow state after each successfully completed step.</li><li>Simulate an interruption during step_2.</li><li>Resume execution from the last saved checkpoint.</li><li>Verify the final state and inspect the complete checkpoint history.</li></ol><p>The goal is to understand how LangGraph preserves completed progress and recovers an interrupted workflow.</p><h4>Understanding the Workflow: A Visual Breakdown</h4><figure><img alt="LangGraph fault tolerance workflow showing three sequential steps. Step 1 completes and saves a checkpoint, step 2 simulates a long-running operation that is manually interrupted, and step 3 executes after the workflow resumes." src="https://cdn-images-1.medium.com/max/1024/1*Brip2EErAfxhvDYhuI0SLg.png" /><figcaption>Fault Tolerance Workflow — simulating an interruption during execution and recovering from the last saved checkpoint.</figcaption></figure><p>Let’s understand each component.</p><p><strong>START</strong></p><p>The workflow begins here and passes the initial input to step_1.</p><p><strong>step_1</strong></p><ul><li>Executes successfully.</li><li>Saves step1 = &quot;done&quot; in the workflow state.</li><li>LangGraph saves a checkpoint after the node completes.</li></ul><p><strong>step_2 — Crash Zone</strong></p><ul><li>Prints a message indicating that execution is hanging.</li><li>Sleeps for 1000 seconds to simulate a long-running operation or network request.</li><li>We manually interrupt execution using the Stop Kernel button in the notebook.</li></ul><p>At this point, the checkpoint from step_1 has already been saved.</p><p><strong>step_3</strong></p><ul><li>Executes after step_2 completes.</li><li>Saves step3 = &quot;done&quot; in the workflow state.</li><li>In our initial interrupted execution, this node does not run.</li></ul><p><strong>END</strong></p><p>The workflow finishes with all three steps completed after successful recovery.</p><h4>1. Import &amp; Setup</h4><p>First, let’s import the required libraries and components.</p><pre># If using ChatOpenAI<br># from langchain_openai import ChatOpenAI<br><br># If using ChatGoogleGenerativeAI<br>from langchain_google_genai import ChatGoogleGenerativeAI<br>from langgraph.graph import StateGraph, START, END<br>from langgraph.checkpoint.memory import InMemorySaver<br>from typing import TypedDict<br>from dotenv import load_dotenv<br>import time</pre><p><strong>Understanding the Imports:</strong></p><ul><li><strong>Core Tools:</strong> We import StateGraph, START, and END to create and organize our LangGraph workflow.</li><li><strong>InMemorySaver:</strong> We use this checkpointer to save intermediate workflow states.</li><li><strong>TypedDict:</strong> We use it to define the structure of our workflow state.</li><li><strong>Environment Configuration:</strong> We import load_dotenv() to load environment variables.</li><li><strong>Time Module:</strong> We use time.sleep() to simulate a long-running operation that can be manually interrupted.</li></ul><h4>2. Configure Environment Variables</h4><p>Next, let’s load our environment variables.</p><pre>load_dotenv()</pre><p><strong>Understanding the Configuration:</strong></p><ul><li><strong>API Keys:</strong> We can define our API credentials in a .env file, such as GEMINI_API_KEY or OPENAI_API_KEY.</li><li><strong>Loading:</strong> The load_dotenv() function loads these credentials into the application&#39;s environment.</li></ul><h4>3. Initialize the LLM</h4><p>Now, let’s initialize the language model.</p><pre># If using ChatOpenAI<br># Initialize ChatOpenAI<br># llm = ChatOpenAI(model=&quot;gpt-4o-mini&quot;)<br><br># If using ChatGoogleGenerativeAI<br># Initialize ChatGoogleGenerativeAI<br>llm = ChatGoogleGenerativeAI(model=&quot;gemini-2.5-flash&quot;)</pre><p><strong>Understanding the Model Initialization:</strong></p><ul><li><strong>Model Selection:</strong> We initialize Google’s Gemini 2.5 Flash model using ChatGoogleGenerativeAI.</li><li><strong>Flexibility:</strong> We can switch to OpenAI by uncommenting the alternative initialization.</li></ul><p><strong>Note:</strong> The LLM is initialized in this example, following the source implementation, but the three workflow nodes do not actually call it. The fault tolerance demonstration uses simple Python functions instead.</p><h4>4. Define the State (CrashState)</h4><p>Before creating our workflow nodes, let’s define the structure of the state.</p><pre># Define the state<br>class CrashState(TypedDict):<br><br>    input: str<br>    step1: str<br>    step2: str<br>    step3: str</pre><p><strong>Understanding the State:</strong></p><p>Our CrashState contains four fields:</p><ul><li><strong>input:</strong> Stores the initial input provided to the workflow.</li><li><strong>step1:</strong> Tracks the completion status of the first step.</li><li><strong>step2:</strong> Tracks the completion status of the second step.</li><li><strong>step3:</strong> Tracks the completion status of the third step.</li></ul><p>Each node updates its corresponding field, allowing us to track the workflow’s progress through the shared state.</p><h4>5. Build the Graph</h4><p>Now, let’s initialize our LangGraph workflow using the StateGraph class.</p><pre>graph = StateGraph(CrashState)</pre><p>Here, StateGraph creates the graph structure using CrashState as its state schema.</p><p>We will register our three workflow functions as nodes and connect them sequentially.</p><h4>6. Define Your Workflow Nodes (Functions)</h4><p>Our workflow consists of three nodes:</p><ol><li>step_1</li><li>step_2</li><li>step_3</li></ol><p>Each node represents one stage of execution.</p><p><strong>Node 1: step_1</strong></p><p>The first node executes normally and updates the state.</p><pre># Define step_1<br>def step_1(state: CrashState) -&gt; CrashState:<br><br>    print(&quot;✅ Step 1 executed&quot;)<br><br>    return {<br>        &quot;step1&quot;: &quot;done&quot;,<br>        &quot;input&quot;: state[&quot;input&quot;]<br>    }</pre><p><strong>Understanding the Function:</strong></p><ul><li><strong>Execution:</strong> Prints a message confirming that Step 1 has executed.</li><li><strong>State Update:</strong> Returns step1 = &quot;done&quot; to indicate successful completion.</li><li><strong>Input Preservation:</strong> Keeps the original input in the workflow state.</li></ul><p>Once this node completes successfully, LangGraph saves a checkpoint containing the updated state.</p><p><strong>Node 2: step_2 — Crash Zone</strong></p><p>The second node simulates a long-running operation.</p><pre># Define step_2<br>def step_2(state: CrashState) -&gt; CrashState:<br><br>    print(<br>        &quot;⏳ Step 2 hanging... &quot;<br>        &quot;now manually interrupt from the notebook toolbar (STOP button)&quot;<br>    )<br><br>    for _ in range(1000):<br>        time.sleep(1)<br><br>    return {<br>        &quot;step2&quot;: &quot;done&quot;<br>    }</pre><p><strong>Understanding the Function:</strong></p><ul><li><strong>Simulation:</strong> We use time.sleep(1) inside a loop to simulate a long-running operation.</li><li><strong>Delay:</strong> The loop runs 1000 times, resulting in a total delay of approximately 1000 seconds if uninterrupted.</li><li><strong>Manual Interruption:</strong> While this function is running, we manually interrupt execution using the Stop Kernel button.</li><li><strong>State Update:</strong> If the function completes normally, it returns step2 = &quot;done&quot;.</li></ul><p>The important point is that the checkpoint from step_1 was already saved before this node started.</p><p>Therefore, when the workflow is interrupted, we can recover from the last saved checkpoint.</p><p><strong>Node 3: step_3</strong></p><p>The final node executes after step_2 completes.</p><pre># Define step_3<br>def step_3(state: CrashState) -&gt; CrashState:<br><br>    print(&quot;✅ Step 3 executed&quot;)<br><br>    return {<br>        &quot;step3&quot;: &quot;done&quot;<br>    }</pre><p><strong>Understanding the Function:</strong></p><ul><li><strong>Execution:</strong> Prints a message confirming that Step 3 has executed.</li><li><strong>State Update:</strong> Returns step3 = &quot;done&quot; to indicate successful completion.</li></ul><p>This node runs only after step_2 completes successfully.</p><h4>7. Build the LangGraph Workflow</h4><p>Now, let’s register all three nodes and connect them to create our sequential workflow.</p><pre># Add nodes to the graph<br>graph.add_node(&quot;step_1&quot;, step_1)<br>graph.add_node(&quot;step_2&quot;, step_2)<br>graph.add_node(&quot;step_3&quot;, step_3)<br><br># Define sequential edges<br>graph.add_edge(START, &quot;step_1&quot;)<br>graph.add_edge(&quot;step_1&quot;, &quot;step_2&quot;)<br>graph.add_edge(&quot;step_2&quot;, &quot;step_3&quot;)<br>graph.add_edge(&quot;step_3&quot;, END)<br><br># Create a checkpointer<br>checkpointer = InMemorySaver()<br><br># Compile the workflow with persistence<br>workflow = graph.compile(checkpointer=checkpointer)</pre><p><strong>Understanding the Workflow:</strong></p><p><strong>1. Register Nodes</strong></p><pre>graph.add_node(&quot;step_1&quot;, step_1)<br>graph.add_node(&quot;step_2&quot;, step_2)<br>graph.add_node(&quot;step_3&quot;, step_3)</pre><p>We register our three functions as nodes in the graph.</p><p><strong>2. Define Edges</strong></p><pre>graph.add_edge(START, &quot;step_1&quot;)<br>graph.add_edge(&quot;step_1&quot;, &quot;step_2&quot;)<br>graph.add_edge(&quot;step_2&quot;, &quot;step_3&quot;)<br>graph.add_edge(&quot;step_3&quot;, END)</pre><p>These edges define the sequential execution flow:</p><blockquote><strong>START → step_1 → step_2 → step_3 → END</strong></blockquote><p><strong>3. Enable Persistence</strong></p><pre>checkpointer = InMemorySaver()</pre><p>We create an instance of InMemorySaver to save workflow state at different checkpoints.</p><p><strong>4. Compile the Workflow</strong></p><pre>workflow = graph.compile(checkpointer=checkpointer)</pre><p>By passing the checkpointer to compile(), we enable persistence for our workflow.</p><p>LangGraph can now save the state after each successfully completed node.</p><h4>8. Workflow Graph</h4><p>Let’s visualize our completed workflow using Mermaid.</p><pre>from IPython.display import Image, display<br><br>display(Image(workflow.get_graph().draw_mermaid_png()))</pre><p>This generates a visual representation of our graph, showing the three sequential nodes and their connections.</p><figure><img alt="Graph visualization showing the sequential LangGraph workflow from START to step_1, step_2, and step_3, followed by END." src="https://cdn-images-1.medium.com/max/106/1*tPiV71PJsLTXdmC15qiB_w.png" /><figcaption>Fault Tolerance — Simulating a Crash and Recovering: the complete LangGraph workflow graph.</figcaption></figure><h4>9. Run the Workflow (and Crash It)</h4><p>Now comes the interesting part. Let’s execute the workflow and deliberately interrupt it during step_2.</p><pre># Run and simulate a crash<br>try:<br>    print(<br>        &quot;▶️ Running graph: &quot;<br>        &quot;Please manually interrupt during Step 2...&quot;<br>    )<br><br>    workflow.invoke(<br>        {&quot;input&quot;: &quot;start&quot;},<br>        config={<br>            &quot;configurable&quot;: {<br>                &quot;thread_id&quot;: &quot;thread-1&quot;<br>            }<br>        }<br>    )<br><br>except KeyboardInterrupt:<br>    print(&quot;❌ Kernel manually interrupted (crash simulated).&quot;)</pre><p><strong>Understanding the Execution:</strong></p><ul><li><strong>Run:</strong> We invoke the workflow with the initial input start.</li><li><strong>Thread Configuration:</strong> We assign thread_id = &quot;thread-1&quot; so LangGraph can associate saved checkpoints with this execution.</li><li><strong>Step 1:</strong> The first node executes successfully and saves its updated state.</li><li><strong>Step 2:</strong> The second node begins its simulated delay.</li></ul><p><strong>Now, follow these steps:</strong></p><ol><li>Execute the code cell.</li><li>Wait until you see ✅ Step 1 executed.</li><li>Wait until you see ⏳ Step 2 hanging....</li><li>Click the Stop Kernel button in your notebook toolbar to interrupt execution.</li></ol><p>At this point, the workflow has been interrupted during step_2.</p><p>However, the checkpoint created after step_1 has already been saved.</p><p><strong>This is Fault Tolerance in action:</strong> completed progress is preserved even when a later step is interrupted.</p><h4>10. Resume After Crash</h4><p>Now, let’s try to resume the workflow from its last saved checkpoint.</p><pre># Re-run to demonstrate fault tolerance<br>print(&quot;\n🔁 Re-running the graph to demonstrate fault tolerance...&quot;)<br><br>try:<br>    final_state = workflow.invoke(<br>        None,<br>        config={<br>            &quot;configurable&quot;: {<br>                &quot;thread_id&quot;: &quot;thread-1&quot;<br>            }<br>        }<br>    )<br><br>    print(&quot;\n✅ Final State:&quot;, final_state)<br><br>except KeyboardInterrupt:<br>    print(&quot;❌ Interrupted again during resume.&quot;)</pre><p><strong>Understanding the Recovery:</strong></p><ul><li><strong>Resume:</strong> We invoke the workflow again using the same thread_id.</li><li><strong>Input:</strong> We pass None because we want LangGraph to continue using the saved workflow state rather than provide new input.</li><li><strong>Checkpoint Retrieval:</strong> LangGraph retrieves the saved state associated with thread_id = &quot;thread-1&quot;.</li><li><strong>Execution:</strong> The unfinished step_2 node is executed again, followed by step_3.</li></ul><p>If the resumed execution completes successfully, the final state will contain all three completed steps.</p><p><strong>Important:</strong> Recovery does not continue from the exact line where Python was interrupted inside step_2. The unfinished node is executed again from its beginning. The previously completed step_1 does not need to be repeated.</p><h4>11. Verify the Final State</h4><p>After the workflow resumes successfully, let’s verify its final saved state.</p><pre>workflow.get_state(<br>    {<br>        &quot;configurable&quot;: {<br>            &quot;thread_id&quot;: &quot;thread-1&quot;<br>        }<br>    }<br>)</pre><p>The final state should contain:</p><pre>{<br>    &quot;input&quot;: &quot;start&quot;,<br>    &quot;step1&quot;: &quot;done&quot;,<br>    &quot;step2&quot;: &quot;done&quot;,<br>    &quot;step3&quot;: &quot;done&quot;<br>}</pre><p><strong>Understanding the Result:</strong></p><ul><li>step1: &quot;done&quot; — The first step completed before the interruption.</li><li>step2: &quot;done&quot; — The second step completed after recovery.</li><li>step3: &quot;done&quot; — The third step completed after the second step.</li></ul><p>Even though the workflow was interrupted during execution, the completed work from step_1 was preserved.</p><p>This demonstrates how LangGraph persistence supports recovery from interrupted workflows.</p><h4>12. View Full State History</h4><p>Finally, let’s inspect the complete checkpoint history for our workflow.</p><pre>list(<br>    workflow.get_state_history(<br>        {<br>            &quot;configurable&quot;: {<br>                &quot;thread_id&quot;: &quot;thread-1&quot;<br>            }<br>        }<br>    )<br>)</pre><p><strong>Understanding the State History:</strong></p><p>The get_state_history() method retrieves the saved checkpoints associated with the specified thread.</p><p>It allows us to inspect:</p><ul><li>The initial workflow state.</li><li>The state after step_1 completed.</li><li>The execution history around the interruption.</li><li>The state after the workflow successfully resumed.</li><li>The final state after all three steps completed.</li></ul><p>This provides a complete view of how the workflow progressed before and after the interruption.</p><p><strong>Full Trace:</strong> We can inspect the saved checkpoints to understand what happened during execution and how the workflow recovered.</p><h4>13. Complete Code</h4><p>Now let’s combine all the implementation steps into a single Python script.</p><p>This complete implementation demonstrates:</p><ul><li>Creating a three-step sequential workflow.</li><li>Enabling persistence with InMemorySaver.</li><li>Simulating an interruption during step_2.</li><li>Resuming execution from the last saved checkpoint.</li><li>Verifying the final workflow state.</li><li>Inspecting the complete checkpoint history.</li></ul><pre># ==========================================<br># 1. Import &amp; Setup<br># ==========================================<br><br>from langgraph.graph import StateGraph, START, END<br>from langgraph.checkpoint.memory import InMemorySaver<br><br>from typing import TypedDict<br>from dotenv import load_dotenv<br><br>import time<br><br><br># ==========================================<br># 2. Configure Environment Variables<br># ==========================================<br><br>load_dotenv()<br><br><br># ==========================================<br># 3. Define the State<br># ==========================================<br><br>class CrashState(TypedDict):<br>    input: str<br>    step1: str<br>    step2: str<br>    step3: str<br><br><br># ==========================================<br># 4. Build the Graph<br># ==========================================<br><br>graph = StateGraph(CrashState)<br><br><br># ==========================================<br># 5. Define Workflow Nodes<br># ==========================================<br><br>def step_1(state: CrashState) -&gt; CrashState:<br><br>    print(&quot;✅ Step 1 executed&quot;)<br><br>    return {<br>        &quot;step1&quot;: &quot;done&quot;,<br>        &quot;input&quot;: state[&quot;input&quot;]<br>    }<br><br><br>def step_2(state: CrashState) -&gt; CrashState:<br><br>    print(<br>        &quot;⏳ Step 2 hanging... &quot;<br>        &quot;manually interrupt using the notebook STOP button&quot;<br>    )<br><br>    for _ in range(1000):<br>        time.sleep(1)<br><br>    return {<br>        &quot;step2&quot;: &quot;done&quot;<br>    }<br><br><br>def step_3(state: CrashState) -&gt; CrashState:<br><br>    print(&quot;✅ Step 3 executed&quot;)<br><br>    return {<br>        &quot;step3&quot;: &quot;done&quot;<br>    }<br><br><br># ==========================================<br># 6. Build the LangGraph Workflow<br># ==========================================<br><br>graph.add_node(&quot;step_1&quot;, step_1)<br>graph.add_node(&quot;step_2&quot;, step_2)<br>graph.add_node(&quot;step_3&quot;, step_3)<br><br>graph.add_edge(START, &quot;step_1&quot;)<br>graph.add_edge(&quot;step_1&quot;, &quot;step_2&quot;)<br>graph.add_edge(&quot;step_2&quot;, &quot;step_3&quot;)<br>graph.add_edge(&quot;step_3&quot;, END)<br><br><br># ==========================================<br># 7. Enable Persistence<br># ==========================================<br><br>checkpointer = InMemorySaver()<br><br>workflow = graph.compile(<br>    checkpointer=checkpointer<br>)<br><br><br># ==========================================<br># 8. Visualize the Workflow Graph<br># ==========================================<br><br>from IPython.display import Image, display<br><br>display(<br>    Image(workflow.get_graph().draw_mermaid_png())<br>)<br><br><br># ==========================================<br># 9. Run the Workflow and Simulate a Crash<br># ==========================================<br><br>config = {<br>    &quot;configurable&quot;: {<br>        &quot;thread_id&quot;: &quot;thread-1&quot;<br>    }<br>}<br><br>try:<br><br>    print(&quot;▶️ Running graph...&quot;)<br><br>    workflow.invoke(<br>        {&quot;input&quot;: &quot;start&quot;},<br>        config=config<br>    )<br><br>except KeyboardInterrupt:<br><br>    print(&quot;❌ Workflow manually interrupted.&quot;)<br><br><br># ==========================================<br># 10. Resume After Interruption<br># ==========================================<br><br>print(&quot;\n🔁 Resuming the workflow...&quot;)<br><br>try:<br><br>    final_state = workflow.invoke(<br>        None,<br>        config=config<br>    )<br><br>    print(&quot;\n✅ Final State:&quot;)<br>    print(final_state)<br><br>except KeyboardInterrupt:<br><br>    print(&quot;❌ Workflow interrupted again.&quot;)<br><br><br># ==========================================<br># 11. Verify the Final State<br># ==========================================<br><br>print(&quot;\n📌 Saved Workflow State:&quot;)<br><br>print(<br>    workflow.get_state(config)<br>)<br><br><br># ==========================================<br># 12. View Full State History<br># ==========================================<br><br>print(&quot;\n📜 Complete State History:&quot;)<br><br>history = list(<br>    workflow.get_state_history(config)<br>)<br><br>for snapshot in history:<br><br>    print(&quot;\nCheckpoint:&quot;)<br>    print(snapshot.config[&quot;configurable&quot;][&quot;checkpoint_id&quot;])<br><br>    print(&quot;State:&quot;)<br>    print(snapshot.values)</pre><h4>Important Notes</h4><ol><li><strong>Manual Interruption:</strong> Interrupt execution while step_2 is sleeping. Do not restart the kernel.</li><li><strong>Checkpointing:</strong> step_1 has completed before the interruption, so its checkpoint is available.</li><li><strong>Recovery:</strong> Invoke the workflow again using the same thread_id and None input.</li><li><strong>Node Re-execution:</strong> The unfinished step_2 runs again from its beginning; Python does not resume at the interrupted line.</li><li><strong>In-Memory Persistence:</strong> Checkpoints remain available only while the same Python process and checkpointer remain alive. Use a database-backed checkpointer for durable recovery across restarts.</li></ol><p>With this implementation, you can reproduce the interruption and recovery process and inspect how LangGraph manages workflow state.</p><h3>Final Thoughts</h3><p>In this part of the series, we explored <strong>Persistence in LangGraph</strong> through two practical examples: a Joke Generator with Time Travel and a Fault-Tolerant Workflow.</p><p>In the first example, we built an LLM-powered Joke Generator and Explainer using Gemini 2.5 Flash, LangGraph, and InMemorySaver. We explored how persistence allows us to save workflow states, manage multiple threads, inspect execution history, and revisit previous checkpoints.</p><p>In the second example, we built a three-step workflow and deliberately interrupted its execution to understand how LangGraph recovers from failures using saved checkpoints.</p><p>Through these examples, we learned how to:</p><ul><li><strong>Enable Persistence:</strong> Configure InMemorySaver to save workflow state at every superstep.</li><li><strong>Manage Threads:</strong> Maintain independent workflow states using unique thread_id values.</li><li><strong>Inspect State:</strong> Retrieve saved workflow states using get_state().</li><li><strong>Explore Execution History:</strong> Retrieve previous checkpoints using get_state_history().</li><li><strong>Implement Time Travel:</strong> Revisit previous checkpoints and resume execution from a selected point.</li><li><strong>Modify Workflow State:</strong> Use update_state() to create alternative execution branches.</li><li><strong>Handle Interruptions:</strong> Recover unfinished workflows from their last successful checkpoint without repeating previously completed nodes.</li></ul><p>The key takeaway is that <strong>Persistence makes LangGraph workflows stateful, recoverable, and easier to inspect and control.</strong></p><p>Whether we’re building conversational AI applications, long-running agents, or complex multi-step LLM pipelines, persistence provides the foundation for managing workflow execution reliably.</p><p><strong>Important Note:</strong> Our examples use InMemorySaver, which stores checkpoints in memory. These checkpoints are not durable across application or kernel restarts. For production applications that require persistent recovery, use database-backed checkpointers such as PostgreSQL or Redis.</p><h3>Key Takeaways</h3><p>Let’s summarize the important concepts and lessons from <strong>Persistence in LangGraph</strong>:</p><ul><li><strong>Persistence in LangGraph:</strong> Allows us to save and restore workflow state over time instead of losing it after execution.</li><li><strong>Checkpointers:</strong> Save intermediate workflow states at every superstep, allowing us to inspect previous states and recover execution.</li><li><strong>Threads:</strong> Use unique thread_id values to maintain separate workflow executions and conversation histories.</li><li><strong>Short-Term Memory:</strong> Enables chatbots to maintain conversation history and resume previous interactions using persistent state.</li><li><strong>Fault Tolerance:</strong> Allows interrupted workflows to resume from their last successful checkpoint without repeating previously completed nodes.</li><li><strong>Human-in-the-Loop (HITL):</strong> Enables workflows to pause for human input or approval and resume later using saved state.</li><li><strong>Time Travel:</strong> Allows developers to revisit previous checkpoints, inspect workflow states, and replay execution from a selected point.</li><li><strong>State Modification:</strong> The update_state() method allows us to modify saved state and create alternative execution branches.</li><li><strong>InMemorySaver:</strong> Provides a simple way to enable persistence for local development and testing, while production applications should use database-backed checkpointers such as PostgreSQL or Redis.</li><li><strong>Practical Implementation:</strong> We built a Joke Generator with Time Travel and a Fault-Tolerant Workflow to understand how persistence works in real LangGraph applications.</li></ul><p><strong>Remember:</strong> Persistence is not just about saving workflow results. It is about maintaining execution history, recovering progress, and controlling how workflows evolve over time.</p><h3>Conclusion</h3><p>In this tutorial, we explored <strong>Persistence in LangGraph</strong> and understood how it transforms workflows by allowing them to save, restore, and manage state over time.</p><p>We started by understanding the concepts of checkpointers and threads, then implemented two practical examples to see persistence in action.</p><p>Here’s what we accomplished:</p><ul><li><strong>Joke Generator:</strong> Built an LLM-powered joke generator and explainer using LangGraph and InMemorySaver, demonstrating how workflow state is saved and retrieved through checkpoints.</li><li><strong>Threads:</strong> Learned how unique thread_id values maintain independent workflow executions, making it possible to manage multiple conversations and users.</li><li><strong>Time Travel:</strong> Explored how to revisit previous checkpoints using checkpoint_id, inspect historical states, re-execute workflows, and create alternative execution branches using update_state().</li><li><strong>Fault Tolerance:</strong> Simulated an interruption during step_2 and successfully resumed the workflow from its last saved checkpoint without repeating previously completed steps.</li><li><strong>Four Major Benefits:</strong> Understood how Short-Term Memory, Fault Tolerance, Human-in-the-Loop, and Time Travel make workflows more flexible and reliable.</li></ul><p>Together, these capabilities make <strong>LangGraph Persistence an essential feature for building stateful, reliable, and interactive AI applications.</strong></p><p>Whether you’re developing conversational chatbots, autonomous AI agents, or complex multi-step workflows, persistence gives you the ability to maintain context, recover progress, and control workflow execution.</p><h3>What’s Next?</h3><p>So far, we’ve explored how <strong>Persistence in LangGraph</strong> allows us to save workflow states, maintain conversation history, recover interrupted executions, and revisit previous checkpoints using Time Travel.</p><p>But understanding persistence is only one part of building a complete AI application. The next step is to bring our LangGraph chatbot to life with a user-friendly interface.</p><p>In the next part of this series, we’ll explore <strong>Building a Chatbot with UI in LangGraph and Streamlit</strong>.</p><p>In <strong>Part 11: Building a Chatbot with UI in LangGraph and Streamlit</strong>, we’ll learn how to:</p><ul><li><strong>Build a Chatbot Backend:</strong> Connect a LangGraph chatbot workflow with a Streamlit frontend.</li><li><strong>Create a Chat Interface:</strong> Use Streamlit components such as st.chat_message() and st.chat_input() to build an interactive chat experience.</li><li><strong>Manage Conversation History:</strong> Use st.session_state to maintain and display messages throughout user interactions.</li><li><strong>Connect Frontend and Backend:</strong> Send user messages from Streamlit to the LangGraph chatbot and display AI-generated responses.</li><li><strong>Integrate Persistence:</strong> Use thread configuration with thread_id to manage conversation state across chatbot interactions.</li></ul><p>We’ll also build a practical chatbot application that brings together LangGraph, persistence, and Streamlit to create an interactive conversational experience.</p><blockquote><strong>Next Part:</strong> Agentic AI using LangGraph — Part 11: <strong>Building a Chatbot with UI in LangGraph and Streamlit</strong></blockquote><p>By the end, you’ll understand how to move beyond backend workflows and build a complete chatbot application with a working user interface.</p><blockquote><strong>Series:</strong> Agentic AI using LangGraph — Part 10 of 27</blockquote><h3>Connect with me</h3><p><strong><em>Connect with me on </em></strong><a href="https://www.linkedin.com/in/shubhamnagar234/"><strong><em>LinkedIn</em></strong></a><strong><em>, </em></strong><a href="https://github.com/shubhamnagar234"><strong><em>GitHub</em></strong></a><strong><em>, </em></strong><a href="https://x.com/nagarshubham234"><strong><em>X (Twitter)</em></strong></a><strong><em>, or explore my </em></strong><a href="https://shubhamnagar234.vercel.app/"><strong><em>Portfolio</em></strong></a><strong><em>.</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d786cbc8351e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Build a Chatbot Using LangGraph: Adding Memory to AI Conversations — Part 9]]></title>
            <link>https://medium.com/@shubhamnagar234/how-to-build-a-chatbot-using-langgraph-adding-memory-to-ai-conversations-part-9-1536c5208670?source=rss-10b51a93c3a------2</link>
            <guid isPermaLink="false">https://medium.com/p/1536c5208670</guid>
            <category><![CDATA[chatbots]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[langgraph]]></category>
            <dc:creator><![CDATA[Shubham Nagar]]></dc:creator>
            <pubDate>Tue, 17 Nov 2026 11:03:17 GMT</pubDate>
            <atom:updated>2026-11-17T11:03:55.195Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><strong>Learn How to Build a Question-Answering Chatbot Using LangGraph, Gemini, and MemorySaver() to Maintain Conversation History Across Multiple Turns.</strong></blockquote><p>In the previous articles of our <strong>Agentic AI Using LangGraph</strong> series, we explored different workflow patterns, including Sequential, Parallel, Conditional, and Iterative Workflows.</p><p>Now, it’s time to build something practical: a <strong>Question-Answering Chatbot with Memory</strong>.</p><p>Imagine having a conversation with an AI chatbot. You ask a question, receive an answer, and then ask another question related to the previous one.</p><p>For example:</p><ul><li><strong>You:</strong> What is the capital of India?</li><li><strong>AI:</strong> The capital of India is New Delhi.</li><li><strong>You:</strong> What is its currency?</li><li><strong>AI:</strong> The currency of India is the Indian Rupee (₹).</li></ul><p>To answer the second question correctly, the chatbot needs to remember the previous conversation.</p><p>But without memory, every time the workflow runs, the chatbot may lose the context of earlier messages. It won’t automatically remember what you discussed in previous interactions.</p><blockquote>This is where <strong>LangGraph Memory</strong> comes in.</blockquote><p>In this article, we’ll build a simple question-answering chatbot using LangGraph and Gemini. We’ll also integrate MemorySaver() to maintain conversation history across multiple turns.</p><p>We’ll use a thread_id to identify a conversation and add_messages to append new messages to the existing conversation history.</p><p>Let’s get started!</p><h3>Overview</h3><ul><li><strong><em>Question-Answering Chatbot With Memory</em></strong></li><li><strong><em>1. Import &amp; Setup</em></strong></li><li><strong><em>2. Define the State (</em></strong><strong><em>ChatState)</em></strong></li><li><strong><em>3. Initialize LLM and Define Chat Node</em></strong></li><li><strong><em>4. Build and Compile the Graph</em></strong></li><li><strong><em>5. Execute the Workflow</em></strong></li><li><strong><em>6. Running the Chatbot Loop</em></strong></li><li><strong><em>7. Complete Code</em></strong></li><li><strong><em>8. Workflow Graph</em></strong></li><li><strong><em>Final Thoughts</em></strong></li><li><strong><em>Key Takeaways</em></strong></li><li><strong><em>Conclusion</em></strong></li><li><strong><em>What’s Next?</em></strong></li></ul><h3>Example: Question-Answering Chatbot With Memory</h3><p>In this example, we’ll build a simple <strong>Question-Answering Chatbot using LangGraph</strong> and add memory so it can remember previous messages across multiple conversation turns.</p><p>Without memory, every time the workflow runs, the chatbot may lose the context of the previous conversation. As a result, it won’t be able to understand follow-up questions that depend on earlier messages.</p><p>To solve this problem, we’ll integrate memory into our LangGraph chatbot so it can maintain conversation history and generate context-aware responses.</p><p>Let’s understand the architecture before implementing it.</p><figure><img alt="Diagram illustrating a LangGraph question-answering chatbot with a chat node connected to conversation memory. The memory stores previous user and AI messages and provides conversation context for future responses." src="https://cdn-images-1.medium.com/max/1024/1*tJqNIpuXvY6meBO1W7pBVA.png" /><figcaption><em>Architecture of a Question-Answering Chatbot with Memory using LangGraph, showing how the chat node interacts with conversation history to generate context-aware responses.</em></figcaption></figure><h3>1. Import &amp; Setup</h3><p>First, let’s import all the required libraries and components for building our question-answering chatbot with memory.</p><pre># If using ChatOpenAI<br># from langchain_openai import ChatOpenAI<br><br># If using ChatGoogleGenerativeAI<br>from langchain_google_genai import ChatGoogleGenerativeAI<br>from langgraph.graph import StateGraph, START, END<br>from typing import TypedDict, Annotated<br>from langchain_core.messages import BaseMessage, HumanMessage<br>from langgraph.checkpoint.memory import MemorySaver<br>from langgraph.graph.message import add_messages</pre><p><strong>Understanding the imports:</strong></p><ul><li><strong>LLM Integration:</strong> We import ChatOpenAI or ChatGoogleGenerativeAI to power our chatbot interactions.</li><li><strong>Core Tools:</strong> We import LangGraph components such as StateGraph, START, and END to define the chatbot&#39;s workflow.</li><li><strong>State Management:</strong> We use TypedDict and Annotated to define the structure of our shared conversation state.</li><li><strong>Message Handling:</strong> We import BaseMessage and HumanMessage to represent conversation messages.</li><li><strong>Memory Tools:</strong> We import MemorySaver and add_messages to manage conversation history and maintain state across multiple interactions.</li></ul><p>These imports provide everything we need to create the chatbot, process messages, and preserve conversation history using LangGraph’s memory functionality.</p><h3>2. Define the State (ChatState)</h3><p>Next, we need to define the shared state that will maintain the conversation history throughout our chatbot workflow.</p><p>For this, we’ll create a ChatState using Python&#39;s TypedDict.</p><pre>class ChatState(TypedDict):<br><br>    messages: Annotated[list[BaseMessage], add_messages]</pre><p><strong>Understanding the state:</strong></p><ul><li><strong>State Definition:</strong> We define ChatState, which expects a list of BaseMessage objects in its messages field.</li><li><strong>Message Appending:</strong> Annotated[..., add_messages] is a LangGraph-specific pattern that tells the workflow to append new messages to the existing message list rather than simply overwriting it.</li><li><strong>Memory Foundation:</strong> This messages field holds the conversation history, including both user messages and AI responses.</li></ul><p><strong>Why do we use </strong><strong>add_messages?</strong></p><p>In a chatbot, we need to maintain the history of previous messages so the LLM can understand the context of the conversation.</p><p>The add_messages reducer handles this by appending new messages to the existing message list whenever a node returns additional messages.</p><p>For example:</p><ul><li>When a user sends a message, it is added to the conversation history.</li><li>When the chatbot generates a response, that response is also added to the history.</li><li>During the next interaction, the chatbot can access the accumulated conversation history.</li></ul><p>This makes ChatState the foundation of our chatbot&#39;s conversation memory.</p><h3>3. Initialize LLM and Define Chat Node</h3><p>Now, let’s initialize our LLM and create the chat_node function that will handle user messages and generate responses.</p><p><strong>A. Initialize the LLM</strong></p><p>First, we’ll initialize the Gemini 2.5 Flash model using ChatGoogleGenerativeAI.</p><pre># If using ChatOpenAI<br># from langchain_openai import ChatOpenAI<br># llm = ChatOpenAI(model=&quot;gpt-4o-mini&quot;)<br><br># If using ChatGoogleGenerativeAI<br>from langchain_google_genai import ChatGoogleGenerativeAI<br>llm = ChatGoogleGenerativeAI(model=&quot;gemini-2.5-flash&quot;)</pre><p>Here, we initialize the LLM that will power our chatbot. You can use either OpenAI or Google Gemini, depending on your preference.</p><p><strong>B. Define the Chat Node</strong></p><p>Next, we’ll define the chat_node function.</p><pre>def chat_node(state: ChatState):<br><br>    # Take user query from state<br>    messages = state[&#39;messages&#39;]<br><br>    # Send messages to LLM<br>    response = llm.invoke(messages)<br><br>    # Store response in state<br>    return {&#39;messages&#39;: [response]}</pre><p><strong>Understanding the function:</strong></p><ul><li><strong>Model Input:</strong> The function retrieves the complete conversation history from state[&#39;messages&#39;].</li><li><strong>LLM Invocation:</strong> It sends the message history to the LLM using llm.invoke(messages).</li><li><strong>State Update:</strong> It returns the LLM’s response as a new message in the messages list.</li></ul><p><strong>How does the conversation history get updated?</strong></p><p>Remember the add_messages reducer we defined in ChatState?</p><p>Because we used Annotated[list[BaseMessage], add_messages], LangGraph appends the returned AI response to the existing conversation history instead of replacing the entire list.</p><p>This means the chatbot can access previous user messages and AI responses when processing future questions.</p><p>The chat_node doesn&#39;t need to manage the conversation history manually. LangGraph handles the message updates through the reducer.</p><h3>4. Build and Compile the Graph (With Memory)</h3><p>Now that we’ve defined our state and chat node, let’s build the LangGraph workflow and integrate memory using MemorySaver().</p><p><strong>A. Create the StateGraph and Add the Node</strong></p><p>First, we’ll initialize the graph using our ChatState and register the chat_node.</p><pre>graph = StateGraph(ChatState)<br><br># Add node<br>graph.add_node(&#39;chat_node&#39;, chat_node)</pre><p><strong>B. Define the Workflow Edges</strong></p><p>Next, we’ll connect the nodes to define the execution flow.</p><pre>graph.add_edge(START, &#39;chat_node&#39;)<br>graph.add_edge(&#39;chat_node&#39;, END)</pre><p>Our workflow follows a simple structure:</p><blockquote><strong>START → </strong><strong>chat_node → </strong><strong>END</strong></blockquote><p>Whenever a user sends a message, the chat_node processes the conversation history and generates a response.</p><p><strong>C. Configure Memory Using MemorySaver()</strong></p><p>Now comes the important part: integrating memory into our chatbot.</p><pre>checkpointer = MemorySaver()</pre><p>Here, we create an instance of MemorySaver(), which stores graph state snapshots in memory.</p><p><strong>D. Compile the Graph with Memory</strong></p><p>Finally, we’ll compile our graph and pass the checkpointer.</p><pre>chatbot = graph.compile(checkpointer=checkpointer)</pre><p>By passing checkpointer=checkpointer, we enable LangGraph&#39;s checkpointing functionality.</p><p>This allows the chatbot to save and retrieve conversation state across multiple interactions when the same conversation thread is used.</p><p><strong>Understanding the complete setup:</strong></p><ul><li><strong>Graph Initialization:</strong> We create a StateGraph using ChatState to define the structure of our chatbot.</li><li><strong>Node Registration:</strong> We add chat_node, which processes the conversation messages and generates an AI response.</li><li><strong>Workflow Edges:</strong> We define the execution path as START → chat_node → END.</li><li><strong>Memory Checkpointer:</strong> We initialize MemorySaver() to store conversation state snapshots in memory.</li><li><strong>Compilation:</strong> We compile the graph with checkpointer=checkpointer, enabling conversation state to be saved and retrieved across interactions.</li></ul><p>Now our chatbot workflow is ready. The next step is to execute it and see how thread_id allows us to maintain separate conversations.</p><h3>5. Execute the Workflow (Initial Test)</h3><p>Now that our chatbot workflow is compiled with memory, let’s execute it by sending our first question.</p><p>We’ll ask the chatbot a simple question: <strong>“What is the capital of India?”</strong></p><p><strong>A. Define the Initial State</strong></p><p>First, let’s create the initial state containing the user’s question.</p><pre>initial_state = {<br>    &#39;messages&#39;: [<br>        HumanMessage(content=&#39;What is the capital of India?&#39;)<br>    ]<br>}</pre><p>Here, we pass the user’s question as a HumanMessage inside the messages list.</p><p><strong>B. Configure the Thread ID</strong></p><p>Next, we’ll define a configuration dictionary containing a unique thread_id.</p><pre>config = {<br>    &#39;configurable&#39;: {<br>        &#39;thread_id&#39;: &#39;1&#39;<br>    }<br>}</pre><p>The thread_id is important because it tells LangGraph which conversation&#39;s state to retrieve and update.</p><p>In this example, we’re using &#39;1&#39; as the thread ID. All interactions using this same ID will belong to the same conversation.</p><p><strong>C. Invoke the Chatbot</strong></p><p>Finally, let’s invoke our chatbot with the initial state and configuration.</p><pre>chatbot.invoke(initial_state, config=config)[&#39;messages&#39;][-1].content</pre><p>Here:</p><ul><li>chatbot.invoke() executes our compiled LangGraph workflow.</li><li>initial_state provides the user&#39;s question.</li><li>config=config passes the thread ID to the checkpointer.</li><li>[&#39;messages&#39;][-1].content retrieves the content of the latest message, which is the chatbot&#39;s response.</li></ul><p><strong>Expected Output:</strong></p><pre>The capital of India is New Delhi.</pre><p><em>Note: The exact response may vary depending on the LLM.</em></p><p><strong>Understanding What Happened</strong></p><p>When we executed the workflow:</p><ol><li>LangGraph received the user’s question.</li><li>The chat_node retrieved the messages from the state and sent them to Gemini.</li><li>Gemini generated a response.</li><li>The add_messages reducer appended the AI response to the existing message history.</li><li>The MemorySaver() checkpointer saved the updated conversation state under thread_id: &#39;1&#39;.</li></ol><p>Now, our chatbot has stored both the user’s question and the AI’s response.</p><p>We can continue the conversation using the same thread_id and the chatbot will be able to access the previous messages.</p><h3>6. Running the Chatbot Loop</h3><p>So far, we’ve tested our chatbot with a single question. Now, let’s make it interactive by creating a continuous conversation loop.</p><p>We’ll use a Python while loop to accept user input, send each message to the chatbot, and display its response.</p><pre>thread_id = &#39;1&#39;<br><br>while True:<br>    user_message = input(&quot;Type here: &quot;)<br>    print(&quot;User: &quot;, user_message)<br>    if user_message.strip().lower() in [&#39;exit&#39;, &#39;quit&#39;, &#39;bye&#39;]:<br>        break<br><br>    config = {<br>        &#39;configurable&#39;: {<br>            &#39;thread_id&#39;: thread_id<br>        }<br>    }<br><br>    response = chatbot.invoke(<br>        {&#39;messages&#39;: [HumanMessage(content=user_message)]},<br>        config=config<br>    )<br><br>    print(&#39;AI: &#39;, response[&#39;messages&#39;][-1].content)</pre><p><strong>Understanding the code:</strong></p><ul><li><strong>Continuous Conversation:</strong> We use a while True loop to continuously accept messages from the user through the terminal.</li><li><strong>Exit Condition:</strong> The loop stops when the user enters exit, quit, or bye.</li><li><strong>Consistent Thread:</strong> We keep the same thread_id = &#39;1&#39; for every interaction. This ensures that all messages belong to the same conversation.</li><li><strong>Chatbot Invocation:</strong> For each new message, we call chatbot.invoke() with the user&#39;s message and the thread configuration.</li><li><strong>Intelligent Memory:</strong> Because the same thread is reused, LangGraph retrieves the previous conversation state and makes the accumulated message history available to the chat node.</li></ul><p><strong>Example Conversation:</strong></p><pre>Type here: What is the capital of India?<br>User: What is the capital of India?<br>AI: The capital of India is New Delhi.</pre><pre>Type here: What is its currency?<br>User: What is its currency?<br>AI: The currency of India is the Indian Rupee (₹).<br>Type here: bye<br>User: bye</pre><p>As you can see, the chatbot can answer the second question using the context of the first question.</p><p><strong>Why does this work?</strong></p><p>Two important components make this possible:</p><ol><li><strong>MemorySaver()</strong> stores conversation state for each thread.</li><li><strong>thread_id</strong> identifies which conversation history should be retrieved and updated.</li></ol><p>Whenever we invoke the chatbot with the same thread_id, LangGraph loads the previous state, processes the new message, and saves the updated conversation.</p><p>This allows our chatbot to maintain context across multiple turns without manually passing the entire conversation history every time.</p><h3>7. Complete Code</h3><p>Now, let’s put everything together into a single Python script.</p><p>This implementation uses <strong>Gemini 2.5 Flash</strong>, <strong>LangGraph</strong>, and MemorySaver() to build a chatbot that remembers previous messages across multiple conversation turns.</p><p><strong>Complete Python Code:</strong></p><pre><br># If using ChatOpenAI<br># from langchain_openai import ChatOpenAI<br><br># If using ChatGoogleGenerativeAI<br>from langchain_google_genai import ChatGoogleGenerativeAI<br>from langgraph.graph import StateGraph, START, END<br>from typing import TypedDict, Annotated<br>from langchain_core.messages import BaseMessage, HumanMessage<br>from langgraph.checkpoint.memory import MemorySaver<br>from langgraph.graph.message import add_messages<br><br><br># 1. Initialize LLM<br># If using ChatOpenAI<br># Initialize ChatOpenAI<br># llm = ChatOpenAI(model=&quot;gpt-4o-mini&quot;)<br><br># If using ChatGoogleGenerativeAI<br># Initialize ChatGoogleGenerativeAI<br>llm = ChatGoogleGenerativeAI(model=&quot;gemini-2.5-flash&quot;)<br><br><br># 2. Define Chat State<br>class ChatState(TypedDict):<br>    messages: Annotated[list[BaseMessage], add_messages]<br><br><br># 3. Define Chat Node<br>def chat_node(state: ChatState):<br><br>    # Take conversation history from state<br>    messages = state[&#39;messages&#39;]<br><br>    # Send messages to LLM<br>    response = llm.invoke(messages)<br><br>    # Return AI response<br>    return {&#39;messages&#39;: [response]}<br><br><br># 4. Build the Graph<br>graph = StateGraph(ChatState)<br><br># Add node<br>graph.add_node(&#39;chat_node&#39;, chat_node)<br><br># Define edges<br>graph.add_edge(START, &#39;chat_node&#39;)<br>graph.add_edge(&#39;chat_node&#39;, END)<br><br><br># 5. Configure Memory<br>checkpointer = MemorySaver()<br><br># Compile graph with memory<br>chatbot = graph.compile(checkpointer=checkpointer)<br><br><br># 6. Initial Test<br>initial_state = {<br>    &#39;messages&#39;: [<br>        HumanMessage(content=&#39;What is the capital of India?&#39;)<br>    ]<br>}<br><br>config = {<br>    &#39;configurable&#39;: {<br>        &#39;thread_id&#39;: &#39;1&#39;<br>    }<br>}<br><br>response = chatbot.invoke(initial_state, config=config)<br><br>print(&quot;AI:&quot;, response[&#39;messages&#39;][-1].content)<br><br><br># 7. Continuous Chatbot Loop<br>thread_id = &#39;1&#39;<br><br>while True:<br><br>    user_message = input(&quot;Type here: &quot;)<br><br>    print(&quot;User:&quot;, user_message)<br><br>    if user_message.strip().lower() in [&#39;exit&#39;, &#39;quit&#39;, &#39;bye&#39;]:<br>        break<br><br>    config = {<br>        &#39;configurable&#39;: {<br>            &#39;thread_id&#39;: thread_id<br>        }<br>    }<br><br>    response = chatbot.invoke(<br>        {&#39;messages&#39;: [HumanMessage(content=user_message)]},<br>        config=config<br>    )<br><br>    print(&#39;AI:&#39;, response[&#39;messages&#39;][-1].content)<br></pre><p><strong>Understanding the Complete Execution:</strong></p><ol><li><strong>Initialize the LLM:</strong> We initialize Gemini 2.5 Flash to generate responses to user questions.</li><li><strong>Define Chat State:</strong> We create ChatState with a messages field and use add_messages to append new messages to the conversation history.</li><li><strong>Create the Chat Node:</strong> The chat_node retrieves the conversation history, sends it to the LLM, and returns the generated response.</li><li><strong>Build the Graph:</strong> We create a StateGraph, register the chat node, and connect START → chat_node → END.</li><li><strong>Configure Memory:</strong> We initialize MemorySaver() and pass it to graph.compile() as the checkpointer.</li><li><strong>Execute the Initial Test:</strong> We send the first question using thread_id = &#39;1&#39;.</li><li><strong>Start the Chatbot Loop:</strong> We continuously accept user messages and invoke the chatbot using the same thread ID.</li><li><strong>Maintain Conversation Context:</strong> LangGraph retrieves the previous conversation state, processes the new message, and saves the updated state after each interaction.</li></ol><p><strong>Example Output:</strong></p><pre>AI: The capital of India is New Delhi.<br><br>Type here: What is its currency?<br>User: What is its currency?<br>AI: The currency of India is the Indian Rupee (₹).<br><br>Type here: Who is the current Prime Minister?<br>User: Who is the current Prime Minister?<br>AI: As of my latest information, the Prime Minister of India is Narendra Modi.<br><br>Type here: bye<br>User: bye</pre><p><em>Note: The actual responses may vary depending on the LLM. The example output is illustrative.</em></p><p><strong>Important Notes:</strong></p><ul><li>MemorySaver() stores conversation checkpoints in memory. It is suitable for this demonstration, but its state is not durable across application restarts.</li><li>The same thread_id must be used to continue an existing conversation.</li><li>A different thread_id creates a separate conversation.</li><li>The add_messages reducer appends new messages to the existing message history, allowing the LLM to receive the conversation context on subsequent turns.</li></ul><p>With this, we’ve built a complete question-answering chatbot that remembers previous interactions using LangGraph memory.</p><h3>8. Workflow Graph</h3><p>Now that we’ve implemented and executed our chatbot, let’s visualize the complete workflow to understand how it works.</p><figure><img alt="A simple LangGraph workflow consisting of START, a single chat_node, and END, where the chat node processes user messages and generates AI responses." src="https://cdn-images-1.medium.com/max/121/1*8AxwksZXCMpfqReme_EF6Q.png" /><figcaption><em>Workflow graph of a Question-Answering Chatbot using LangGraph, showing the execution flow from START to </em><em>chat_node and then to END.</em></figcaption></figure><p><strong>Understanding the Workflow:</strong></p><p>The graph follows a simple execution path:</p><ol><li><strong>START:</strong> The workflow receives the user’s message as input.</li><li><strong>chat_node:</strong> The chat node retrieves the conversation history from the shared state and sends it to the LLM. The LLM generates a response, which is added to the message history using the add_messages reducer.</li><li><strong>END:</strong> The workflow finishes execution and returns the updated conversation state.</li></ol><p><strong>Where Does Memory Fit In?</strong></p><p>Although the workflow contains only one processing node, memory plays an important role behind the scenes.</p><ul><li>MemorySaver() saves conversation state checkpoints.</li><li>thread_id identifies the conversation whose history should be retrieved and updated.</li><li>add_messages appends new user and AI messages to the existing message history.</li><li>On the next invocation with the same thread_id, LangGraph retrieves the previous conversation state.</li></ul><p>This allows the chatbot to maintain context across multiple interactions without manually passing the entire conversation history every time.</p><p><strong>Final Workflow:</strong></p><blockquote><strong>START → </strong><strong>chat_node → </strong><strong>END</strong></blockquote><p>The graph is simple, but combining it with MemorySaver() and thread_id gives us a chatbot that can remember previous interactions and generate context-aware responses.</p><h3>Final Thoughts</h3><p>In this article, we learned how to build a <strong>Question-Answering Chatbot using LangGraph with Memory</strong>.</p><p>We started with a simple chatbot and then integrated memory so it could remember previous messages and maintain context across multiple conversation turns.</p><p>Here’s what we built:</p><ul><li><strong>LangGraph Chatbot:</strong> Created a simple chatbot that uses an LLM to understand user questions and generate responses.</li><li><strong>Conversation State:</strong> Defined ChatState to maintain the conversation history using a list of BaseMessage objects.</li><li><strong>Message Management:</strong> Used add_messages to append new user and AI messages to the existing conversation history.</li><li><strong>Chat Node:</strong> Created a chat_node that retrieves the conversation messages, sends them to the LLM, and returns its response.</li><li><strong>Memory Integration:</strong> Used MemorySaver() as a checkpointer to save and retrieve conversation state.</li><li><strong>Thread-Based Memory:</strong> Used thread_id to identify and maintain separate conversations.</li><li><strong>Continuous Conversation:</strong> Implemented a while loop that allows users to ask multiple questions without losing the context of previous interactions.</li></ul><p>The most important concept is that <strong>memory allows a chatbot to remember previous interactions instead of treating every message as a completely new conversation.</strong></p><p>Even though our LangGraph workflow is simple, combining MemorySaver(), thread_id, and add_messages makes it capable of maintaining conversation history across multiple turns.</p><p>Here’s the complete workflow in simple terms:</p><blockquote><strong>User Message → </strong><strong>LLM → </strong><strong>AI Response → </strong><strong>Memory Update → </strong><strong>Next Interaction</strong></blockquote><p>With this, we’ve built our first conversational chatbot using LangGraph that can remember previous messages and answer follow-up questions using conversation context.</p><h3>Key Takeaways</h3><p>In this article, we explored how to build a <strong>Question-Answering Chatbot with Memory using LangGraph</strong>.</p><p>Here are the key concepts to remember:</p><ol><li><strong>LangGraph Chatbot:</strong> We can use LangGraph to build a chatbot that processes user questions and generates responses using an LLM.</li><li><strong>ChatState:</strong> We define a shared state using TypedDict to maintain the conversation history through a messages field.</li><li><strong>Message Management with </strong><strong>add_messages:</strong> This reducer appends new user and AI messages to the existing message list instead of overwriting the conversation history.</li><li><strong>Chat Node:</strong> The chat_node retrieves the conversation messages, sends them to the LLM, and returns the generated response.</li><li><strong>MemorySaver():</strong> We use MemorySaver() as a checkpointer to save and retrieve conversation state across multiple interactions.</li><li><strong>Thread-Based Memory:</strong> The thread_id identifies a particular conversation and allows LangGraph to retrieve the corresponding conversation history.</li><li><strong>Continuous Conversation:</strong> A while loop allows users to interact with the chatbot continuously while maintaining the same conversation thread.</li><li><strong>Context-Aware Responses:</strong> By providing the LLM with the accumulated conversation history, the chatbot can understand follow-up questions and generate relevant responses.</li><li><strong>Simple Workflow Architecture:</strong> Our chatbot follows a straightforward execution path: START → chat_node → END.</li><li><strong>Memory and State Persistence:</strong> The combination of MemorySaver(), thread_id, and add_messages allows the chatbot to maintain conversation context across multiple turns. MemorySaver() stores checkpoints in memory for this implementation.</li></ol><p><strong>The key idea:</strong> LangGraph memory enables chatbots to maintain conversation history, understand follow-up questions, and deliver context-aware responses across multiple interactions.</p><h3>Conclusion</h3><p>In this part of our <strong>Agentic AI Using LangGraph</strong> series, we explored how to build a question-answering chatbot that remembers previous conversations using LangGraph.</p><p>We started by creating a simple chatbot powered by Gemini 2.5 Flash and then integrated memory to maintain conversation history across multiple interactions.</p><p>Through this practical implementation, we learned how to:</p><ul><li>Define a shared conversation state using ChatState and TypedDict.</li><li>Use add_messages to append new user and AI messages to the existing conversation history.</li><li>Create a chat_node that sends conversation messages to the LLM and generates responses.</li><li>Build a simple LangGraph workflow using StateGraph, START, and END.</li><li>Integrate MemorySaver() as a checkpointer to save and retrieve conversation state.</li><li>Use thread_id to identify individual conversations and maintain their context.</li><li>Implement a continuous chatbot loop that supports multiple interactions without losing previous conversation history.</li></ul><p>The most important takeaway is that <strong>a chatbot needs more than an LLM to maintain a meaningful conversation. It also needs a way to remember previous interactions and use that context when answering new questions.</strong></p><p>By combining LangGraph’s state management, message reducers, and checkpointing functionality, we can build conversational AI applications that remember previous messages and respond more naturally to follow-up questions.</p><p>This is an important step toward building more advanced conversational agents and AI applications using LangGraph.</p><h3>What’s Next?</h3><p>So far, we’ve explored how to build dynamic LangGraph workflows using sequential, parallel, and conditional execution patterns.</p><p>But there’s one important question: <strong>What happens to a workflow’s state after execution finishes or something goes wrong?</strong></p><p>In the next part of this series, we’ll explore <strong>Persistence in LangGraph</strong> and learn how to save, restore, and manage workflow state over time.</p><p>In <strong>Part 10: Persistence in LangGraph</strong>, we’ll cover:</p><ul><li><strong>Checkpointers:</strong> Learn how LangGraph saves workflow state at every checkpoint.</li><li><strong>Threads:</strong> Understand how thread_id keeps different workflow executions and conversations separate.</li><li><strong>Short-Term Memory:</strong> Build chatbots that can remember and resume previous conversations.</li><li><strong>Fault Tolerance:</strong> Learn how to recover interrupted workflows without starting from scratch.</li><li><strong>Human-in-the-Loop (HITL):</strong> Understand how workflows can pause for human input and resume later.</li><li><strong>Time Travel:</strong> Explore how to revisit previous checkpoints, modify state, and replay workflows.</li></ul><p>We’ll also build two practical examples:</p><ol><li><strong>Joke Generator with Persistence:</strong> Create an LLM-powered joke generator that saves its state, supports multiple threads, and demonstrates time travel.</li><li><strong>Fault Tolerance:</strong> Simulate a workflow interruption and recover from the last saved checkpoint.</li></ol><blockquote><strong>Next Part:</strong> Agentic AI using LangGraph — Part 10: <strong>Persistence in LangGraph</strong></blockquote><p>By the end, you’ll understand how persistence makes LangGraph applications more reliable, stateful, and capable of handling long-running workflows.</p><blockquote><strong>Series:</strong> Agentic AI using LangGraph — Part 9 of 27</blockquote><h3>Connect with me</h3><p><strong><em>Connect with me on </em></strong><a href="https://www.linkedin.com/in/shubhamnagar234/"><strong><em>LinkedIn</em></strong></a><strong><em>, </em></strong><a href="https://github.com/shubhamnagar234"><strong><em>GitHub</em></strong></a><strong><em>, </em></strong><a href="https://x.com/nagarshubham234"><strong><em>X (Twitter)</em></strong></a><strong><em>, or explore my </em></strong><a href="https://shubhamnagar234.vercel.app/"><strong><em>Portfolio</em></strong></a><strong><em>.</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1536c5208670" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Iterative Workflows in LangGraph: Building Self-Improving AI Workflows — Part 8]]></title>
            <link>https://medium.com/@shubhamnagar234/iterative-workflows-in-langgraph-building-self-improving-ai-workflows-part-8-5a03524613e3?source=rss-10b51a93c3a------2</link>
            <guid isPermaLink="false">https://medium.com/p/5a03524613e3</guid>
            <category><![CDATA[workflow]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[langgraph]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Shubham Nagar]]></dc:creator>
            <pubDate>Mon, 16 Nov 2026 10:46:39 GMT</pubDate>
            <atom:updated>2026-11-16T10:47:04.616Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><strong>Learn How to Build Iterative Workflows in LangGraph Using Loops, Conditional Routing, and LLM-Based Evaluation to Generate, Refine, and Improve Outputs.</strong></blockquote><p>In the previous articles of our <strong>Agentic AI Using LangGraph</strong> series, we explored three important workflow patterns:</p><ul><li><strong>Sequential Workflows:</strong> Executing tasks one after another in a predefined order.</li><li><strong>Parallel Workflows:</strong> Running multiple independent tasks simultaneously.</li><li><strong>Conditional Workflows:</strong> Choosing different execution paths based on conditions.</li></ul><p>But there’s another important question:</p><p><strong>What happens when an AI-generated output isn’t good enough on the first attempt?</strong></p><p>For example, imagine building an AI application that generates tweets. The first tweet might be too long, unclear, or simply not engaging enough. Instead of accepting the first result, what if the AI could evaluate its own output, identify what needs improvement, and generate a better version?</p><blockquote>This is where <strong>Iterative Workflows</strong> come in.</blockquote><p>An iterative workflow allows multiple nodes to execute repeatedly in a loop until a specific condition is satisfied. It enables an AI application to generate, evaluate, and refine its output without requiring manual intervention at every step.</p><p>In this article, we’ll understand how iterative workflows work in LangGraph and build a practical LLM-powered example: an <strong>AI Tweet Generator</strong> that generates tweets, evaluates their quality, and improves them based on feedback until they are approved or reach a maximum iteration limit.</p><p>Let’s get started!</p><h3>Overview</h3><ul><li><strong><em>What Is an Iterative Workflow in LangGraph?</em></strong></li><li><strong><em>Why Iterative Workflows?</em></strong></li><li><strong><em>Example: Auto-Generate Tweets Using LangGraph (With LLM)</em></strong></li><li><strong><em>Final Thoughts</em></strong></li><li><strong><em>Key Takeaways</em></strong></li><li><strong><em>Conclusion</em></strong></li><li><strong><em>What’s Next?</em></strong></li></ul><h3>What Is an Iterative Workflow in LangGraph?</h3><p>An <strong>iterative workflow</strong> (also known as a <strong>looping workflow</strong>) in LangGraph is a workflow in which two or more nodes repeatedly execute in a loop until a specific condition becomes true.</p><p>Think of it as a cycle that continues until you achieve the desired result.</p><p>So far, we’ve explored three types of workflows:</p><ul><li><strong>Sequential Workflows:</strong> Tasks execute one after another in a predefined order.</li><li><strong>Parallel Workflows:</strong> Multiple independent tasks execute simultaneously.</li><li><strong>Conditional Workflows:</strong> The workflow follows different execution paths based on specific conditions.</li></ul><p><strong>Iterative workflows add another important capability: repetition.</strong> Instead of executing a step only once, they allow the workflow to repeat certain steps until a defined condition is satisfied.</p><p>This approach is particularly useful when an AI agent needs to continuously refine its output. For example, an AI application can generate content, evaluate its quality, and improve it repeatedly until the output meets a desired quality threshold.</p><figure><img alt="Diagram illustrating an iterative workflow in LangGraph, where execution starts with Node 1, proceeds to Node 2, and either reaches END when approved or follows an optimization step before returning to Node 2 for another evaluation." src="https://cdn-images-1.medium.com/max/1024/1*cydzPIkCJXvycXFwu97gRA.png" /><figcaption><em>An iterative workflow in LangGraph showing how nodes can repeat through an optimization loop until the desired condition is met.</em></figcaption></figure><h3>Why Iterative Workflows?</h3><p>In many AI applications, the first output generated by an LLM isn’t always good enough. It may need additional improvements, corrections, or refinements before it meets the desired quality standards.</p><p>This is where <strong>iterative workflows</strong> become useful. They help us build self-correcting agents that can evaluate their own outputs and improve them through repeated execution.</p><p>Think of it as asking:</p><blockquote><strong>“Is this output good enough? If not, improve it and check again.”</strong></blockquote><p>An iterative workflow runs a set of steps repeatedly in a cycle until a specific criterion or rule is satisfied.</p><p>Here are some important benefits of iterative workflows:</p><ul><li><strong>Self-Correction:</strong> They help AI agents identify weaknesses in their outputs and improve their own work.</li><li><strong>Autonomous Execution:</strong> The workflow can evaluate and refine its outputs without requiring manual intervention at every step.</li><li><strong>Continuous Improvement:</strong> Each iteration uses feedback from the previous attempt to produce a better result.</li><li><strong>Feedback Loops:</strong> They support tasks that require multiple drafts, edits, evaluations, or refinements.</li><li><strong>Handling Complex Tasks:</strong> They are especially useful for content creation, code generation, and complex AI applications where the first attempt is rarely perfect.</li></ul><p>Overall, iterative workflows make it possible to build AI applications that don’t simply generate an output and stop. Instead, they can repeatedly evaluate and improve their work until the desired condition is met.</p><h3>Example 1: Auto-Generate Tweets Using LangGraph (With LLM)</h3><p>To understand iterative workflows more easily, let’s build a practical example.</p><p>Imagine you’re a busy person who doesn’t have enough time to write tweets every day. You want an AI agent that can automatically generate engaging tweets based on a topic you provide.</p><p>However, the first tweet generated by an LLM might not always be good enough. For example:</p><ul><li>It might be too long.</li><li>It might not be clear.</li><li>It might not match the given topic.</li><li>It might need more creativity or improvement.</li></ul><p>Instead of accepting the first output, we can build an AI workflow that generates a tweet, evaluates it, and improves it whenever necessary.</p><p>We’ll create a loop that follows this process:</p><p><strong>User → Tweet Generator → Evaluator → (Approve or Improve) → Tweet Generator → Evaluator … until approved</strong></p><p>The workflow will contain three main nodes:</p><ol><li><strong>Tweet Generator:</strong> Generates a tweet based on the user’s topic.</li><li><strong>Tweet Evaluator:</strong> Evaluates the generated tweet and provides feedback.</li><li><strong>Tweet Optimizer:</strong> Improves the tweet using the evaluator’s feedback.</li></ol><p>If the evaluator approves the tweet, the workflow ends. Otherwise, the optimizer improves it and sends it back for another evaluation.</p><figure><img alt="LangGraph iterative workflow for automatic tweet generation, showing the generator, evaluator, and optimizer nodes, with conditional routing to either END or another optimization cycle." src="https://cdn-images-1.medium.com/max/1024/1*sZCsGzEB6l7ms2tGiTQfvg.png" /><figcaption><em>Auto-Generate Tweets Using LangGraph — An iterative workflow where an LLM generates a tweet, evaluates its quality, and optimizes it until it gets approved.</em></figcaption></figure><h4>How the Workflow Works</h4><p>Let’s understand the workflow step by step.</p><p><strong>1. User Gives a Topic</strong></p><p>First, the user provides a topic for which they want to generate a tweet.</p><p>For example:</p><ul><li>Benefits of AI in education</li><li>Healthy lifestyle tips</li><li>Motivation for students</li></ul><p>The workflow uses this topic as the initial input for the tweet generator.</p><p><strong>2. Tweet Generator Node</strong></p><p>The Tweet Generator node uses an LLM to generate a tweet or social media post based on the topic provided by the user.</p><p>For example, if the topic is about AI in education, the generated tweet might look like this:</p><pre>AI is changing education by making learning faster and smarter.</pre><p><strong>3. Tweet Evaluator Node</strong></p><p>Next, the generated tweet goes to the Tweet Evaluator node.</p><p>This node evaluates the tweet and provides feedback based on several criteria:</p><ul><li><strong>Clarity:</strong> Is the tweet easy to understand?</li><li><strong>Length:</strong> Is it short enough?</li><li><strong>Meaning:</strong> Does it communicate something meaningful?</li><li><strong>Social Media Performance:</strong> Does it have the potential to perform well on social media?</li></ul><p>After evaluating the tweet, the evaluator returns one of two statuses:</p><ul><li>approved — The tweet meets the required criteria.</li><li>needs_improvement — The tweet needs further refinement.</li></ul><p><strong>4. If Status = approved → END</strong></p><p>If the evaluator approves the tweet, the workflow follows the approved path and reaches END.</p><p>The tweet is considered good enough, so no further optimization is required.</p><p><strong>5. If Status = needs_improvement → Optimizer Node</strong></p><p>If the evaluator returns needs_improvement, the workflow moves to the Optimizer node.</p><p>The optimizer takes the original tweet and the evaluator’s feedback, then generates an improved version.</p><p>After optimization, the improved tweet goes back to the Evaluator node for another evaluation.</p><p>This loop continues until the evaluator approves the tweet or the maximum iteration limit is reached.</p><h4>Building the Workflow Step by Step</h4><p>Now that we understand the workflow, let’s implement it using <strong>LangGraph, Python, and Gemini</strong>.</p><h4>1. Import &amp; Setup</h4><p>First, let’s import the required libraries.</p><pre># If using ChatOpenAI<br># from langchain_openai import ChatOpenAI<br><br># If using ChatGoogleGenerativeAI<br>from langchain_google_genai import ChatGoogleGenerativeAI<br><br>from langgraph.graph import StateGraph, START, END<br>from typing import TypedDict, Literal, Annotated<br>from langchain_core.messages import SystemMessage, HumanMessage<br>import operator<br>from dotenv import load_dotenv</pre><p><strong>Understanding the imports:</strong></p><ul><li><strong>LLM Integration:</strong> We import ChatGoogleGenerativeAI to power our tweet generator, evaluator, and optimizer.</li><li><strong>LangGraph Components:</strong> We import StateGraph, START, and END to construct the workflow.</li><li><strong>Python Types:</strong> We use TypedDict, Literal, and Annotated to define and structure the workflow state.</li><li><strong>Messages:</strong> SystemMessage and HumanMessage help us provide instructions and input to the LLM.</li><li><strong>Operator:</strong> We use operator.add to maintain the history of generated tweets and feedback.</li><li><strong>Environment Variables:</strong> We import load_dotenv to load API credentials from a .env file.</li></ul><h4>2. Configure Environment Variables</h4><p>Next, create a .env file in your project directory and add your API keys.</p><p><strong>.env</strong></p><pre>OPENAI_API_KEY=&quot;YOUR_OPENAI_API_KEY&quot;<br>GEMINI_API_KEY=&quot;YOUR_GEMINI_API_KEY&quot;</pre><p>Now, load the environment variables into your application:</p><pre>load_dotenv()</pre><p><strong>Understanding the setup:</strong></p><ul><li><strong>API Keys:</strong> We define the API credentials in the .env file, such as GEMINI_API_KEY.</li><li><strong>Loading:</strong> We use load_dotenv() to load these credentials into the application&#39;s environment so the model integration can access them.</li></ul><h3>3. Initialize LLM</h3><p>We need three LLM instances because our workflow performs three different tasks:</p><ul><li><strong>Generator LLM:</strong> Generates the initial tweet.</li><li><strong>Evaluator LLM:</strong> Evaluates the tweet and provides feedback.</li><li><strong>Optimizer LLM:</strong> Improves the tweet based on the feedback.</li></ul><p>We’ll use Gemini 2.5 Flash for all three tasks.</p><pre># If using ChatOpenAI<br># Initialize ChatOpenAI<br># generator_llm = ChatOpenAI(model=&#39;gpt-4o-mini&#39;)<br># evaluator_llm = ChatOpenAI(model=&#39;gpt-4o-mini&#39;)<br># optimizer_llm = ChatOpenAI(model=&#39;gpt-4o-mini&#39;)<br><br># If using ChatGoogleGenerativeAI<br># Initialize ChatGoogleGenerativeAI<br>generator_llm = ChatGoogleGenerativeAI(model=&quot;gemini-2.5-flash&quot;)<br>evaluator_llm = ChatGoogleGenerativeAI(model=&quot;gemini-2.5-flash&quot;)<br>optimizer_llm = ChatGoogleGenerativeAI(model=&quot;gemini-2.5-flash&quot;)</pre><p><strong>Understanding the setup:</strong></p><ul><li><strong>Model Selection:</strong> We initialize three instances of Gemini 2.5 Flash for generation, evaluation, and optimization.</li><li><strong>Modularity:</strong> Separating these instances allows us to configure or replace the model used for each task independently.</li></ul><h4>4. Define Schemas and Structured Output</h4><p>The evaluator needs to return a consistent result so that our workflow can decide what to do next.</p><p>For this, we’ll use Pydantic to define a schema.</p><pre>from pydantic import BaseModel, Field<br><br>class TweetEvaluation(BaseModel):<br>    evaluation: Literal[&quot;approved&quot;, &quot;needs_improvement&quot;] = Field(<br>        ...,<br>        description=&quot;Final evaluation result.&quot;<br>    )<br>    feedback: str = Field(<br>        ...,<br>        description=&quot;feedback for the tweet.&quot;<br>    )</pre><p>Now, let’s configure the evaluator LLM to use this schema:</p><pre>structured_evaluator_llm = evaluator_llm.with_structured_output(TweetEvaluation)</pre><p><strong>Understanding the setup:</strong></p><ul><li><strong>Pydantic Model:</strong> TweetEvaluation defines the two fields the evaluator should return: evaluation and feedback.</li><li><strong>Evaluation Status:</strong> The Literal type restricts the evaluation value to either approved or needs_improvement.</li><li><strong>Structured Output:</strong> with_structured_output() configures the evaluator to return data following the TweetEvaluation schema instead of relying on unrestricted free-text responses.</li></ul><p>This structured result makes it easier for our workflow to read the evaluation status and determine the next execution path.</p><h4>5. Define the State (TweetState)</h4><p>Next, we need to define the shared state that will carry information throughout the workflow.</p><pre>class TweetState(TypedDict):<br><br>    topic: str<br>    tweet: str<br>    evaluation: Literal[&quot;approved&quot;, &quot;needs_improvement&quot;]<br>    feedback: str<br>    iteration: int<br>    max_iteration: int<br>    tweet_history: Annotated[list[str], operator.add]<br>    feedback_history: Annotated[list[str], operator.add]</pre><p><strong>Understanding the state:</strong></p><ul><li><strong>topic:</strong> Stores the topic provided by the user.</li><li><strong>tweet:</strong> Stores the current generated or optimized tweet.</li><li><strong>evaluation:</strong> Stores the evaluator’s decision (approved or needs_improvement).</li><li><strong>feedback:</strong> Stores the evaluator’s feedback.</li><li><strong>iteration:</strong> Tracks the current optimization iteration.</li><li><strong>max_iteration:</strong> Defines the maximum number of optimization iterations.</li><li><strong>tweet_history:</strong> Stores all generated and optimized tweet versions.</li><li><strong>feedback_history:</strong> Stores the feedback received during evaluations.</li></ul><p><strong>Why do we use </strong><strong>Annotated[list[str], operator.add]?</strong></p><p>In an iterative workflow, we don’t want to lose previous tweets and feedback when a new iteration runs.</p><p>The operator.add reducer allows new list values returned by nodes to be appended to the existing history instead of simply replacing it.</p><p>This helps us maintain a record of how the tweet changes throughout the optimization process.</p><h4>6. Build the Graph</h4><p>Now, let’s initialize the LangGraph workflow using our TweetState schema.</p><pre>graph = StateGraph(TweetState)</pre><p>Here, we create a StateGraph object associated with TweetState.</p><p>This graph will contain all the nodes and edges required to generate, evaluate, and optimize tweets.</p><h4>7. Define Your Workflow Nodes (Functions)</h4><p>Now comes the most important part: defining the three main nodes of our workflow.</p><p>Each node performs a separate task and updates the shared state.</p><p><strong>A. generate_tweet</strong></p><p>The generate_tweet node uses the generator LLM to create an initial tweet based on the topic provided by the user.</p><pre>def generate_tweet(state: TweetState) -&gt; TweetState:<br><br>    # prompt<br>    messages = [<br>        SystemMessage(content=&quot;You are a funny and clever Twitter/X influencer.&quot;),<br>        HumanMessage(content=f&quot;&quot;&quot;<br>        Write a short, original, and hilarious tweet on the topic: &quot;{state[&#39;topic&#39;]}&quot;.<br>        Rules:<br>        - Do NOT use question-answer format.<br>        - Max 280 characters.<br>        - Use observational humor, irony, sarcasm, or cultural references.<br>        - Think in meme logic, punchlines, or relatable takes.<br>        - Use simple, day to day english<br>        &quot;&quot;&quot;)<br>    ]<br><br>    # send generator_llm<br>    response = generator_llm.invoke(messages).content<br><br>    # return response<br>    return {&#39;tweet&#39;: response, &#39;tweet_history&#39;: [response]}</pre><p><strong>Understanding the function:</strong></p><ul><li><strong>Action:</strong> The generator_llm receives the topic and generates a short, original, and humorous tweet.</li><li><strong>State Update:</strong> The generated tweet is stored in the tweet field.</li><li><strong>History Tracking:</strong> The generated tweet is also added to tweet_history.</li></ul><p><strong>B. evaluate_tweet</strong></p><p>Once the tweet is generated, it needs to be evaluated.</p><p>The evaluate_tweet node uses the structured evaluator LLM to check the tweet based on originality, humor, punchiness, virality potential, and formatting.</p><pre>def evaluate_tweet(state: TweetState) -&gt; TweetState:<br><br>    # prompt<br>    messages = [<br>        SystemMessage(content=&quot;You are a ruthless, no-laugh-given Twitter critic. You evaluate tweets based on humor, originality, virality, and tweet format.&quot;),<br>        HumanMessage(content=f&quot;&quot;&quot;<br>        Evaluate the following tweet:<br>        Tweet: &quot;{state[&#39;tweet&#39;]}&quot;<br>        Use the criteria below to evaluate the tweet:<br>        1. Originality – Is this fresh, or have you seen it a hundred times before?<br>        2. Humor – Did it genuinely make you smile, laugh, or chuckle?<br>        3. Punchiness – Is it short, sharp, and scroll-stopping?<br>        4. Virality Potential – Would people retweet or share it?<br>        5. Format – Is it a well-formed tweet (not a setup-punchline joke, not a Q&amp;A joke, and under 280 characters)?<br>        Auto-reject if:<br>        - It&#39;s written in question-answer format (e.g., &quot;Why did...&quot; or &quot;What happens when...&quot;)<br>        - It exceeds 280 characters<br>        - It reads like a traditional setup-punchline joke<br>        - Dont end with generic, throwaway, or deflating lines that weaken the humor (e.g., &quot;Masterpieces of the auntie-uncle universe&quot; or vague summaries)<br>        ### Respond ONLY in structured format:<br>        - evaluation: &quot;approved&quot; or &quot;needs_improvement&quot;<br>        - feedback: One paragraph explaining the strengths and weaknesses<br>        &quot;&quot;&quot;)<br>            ]<br><br>    response = structured_evaluator_llm.invoke(messages)<br><br>    return {<br>        &#39;evaluation&#39;: response.evaluation,<br>        &#39;feedback&#39;: response.feedback,<br>        &#39;feedback_history&#39;: [response.feedback]<br>    }</pre><p><strong>Understanding the function:</strong></p><ul><li><strong>Action:</strong> The structured_evaluator_llm evaluates the current tweet against the defined criteria and returns a structured result.</li><li><strong>Evaluation:</strong> It determines whether the tweet is approved or needs_improvement.</li><li><strong>Feedback:</strong> It provides a paragraph explaining the tweet’s strengths and weaknesses.</li><li><strong>State Update:</strong> The evaluation status and feedback are stored in the state.</li><li><strong>History Tracking:</strong> The feedback is appended to feedback_history.</li></ul><p><strong>C. optimize_tweet</strong></p><p>If the evaluator decides that the tweet needs improvement, the workflow moves to the optimize_tweet node.</p><p>This node uses the optimizer LLM to rewrite the tweet based on the evaluator’s feedback.</p><pre>def optimize_tweet(state: TweetState) -&gt; TweetState:<br><br>    messages = [<br>        SystemMessage(content=&quot;You punch up tweets for virality and humor based on given feedback.&quot;),<br>        HumanMessage(content=f&quot;&quot;&quot;<br>        Improve the tweet based on this feedback:<br>        &quot;{state[&#39;feedback&#39;]}&quot;<br>        Topic: &quot;{state[&#39;topic&#39;]}&quot;<br>        Original Tweet:<br>        {state[&#39;tweet&#39;]}<br>        Re-write it as a short, viral-worthy tweet. Avoid Q&amp;A style and stay under 280 characters.<br>        &quot;&quot;&quot;)<br>    ]<br><br>    response = optimizer_llm.invoke(messages).content<br>    iteration = state[&#39;iteration&#39;] + 1<br><br>    return {<br>        &#39;tweet&#39;: response,<br>        &#39;iteration&#39;: iteration,<br>        &#39;tweet_history&#39;: [response]<br>    }</pre><p><strong>Understanding the function:</strong></p><ul><li><strong>Action:</strong> The optimizer takes the evaluator’s feedback and rewrites the current tweet to make it funnier and more engaging.</li><li><strong>State Update:</strong> The new tweet replaces the current value in the tweet field.</li><li><strong>Iteration Tracking:</strong> The iteration count increases by one.</li><li><strong>History Tracking:</strong> The improved tweet is appended to tweet_history.</li></ul><p><strong>D. route_evaluation (Conditional Logic)</strong></p><p>Now we need a function that decides whether the workflow should stop or continue with another optimization cycle.</p><p>For this, we’ll create a routing function named route_evaluation.</p><pre>def route_evaluation(state: TweetState) -&gt; Literal[&quot;approved&quot;, &quot;needs_improvement&quot;]:<br><br>    if state[&#39;evaluation&#39;] == &#39;approved&#39; or state[&#39;iteration&#39;] &gt;= state[&#39;max_iteration&#39;]:<br>        return &#39;approved&#39;<br>    else:<br>        return &#39;needs_improvement&#39;</pre><p><strong>Understanding the function:</strong></p><ul><li><strong>Approval Check:</strong> If the evaluator returns approved, the workflow stops.</li><li><strong>Iteration Limit:</strong> If the current iteration reaches or exceeds max_iteration, the workflow also stops.</li><li><strong>Continue Optimization:</strong> Otherwise, the function returns needs_improvement, allowing the workflow to move to the optimizer node.</li></ul><p><strong>Why do we need a maximum iteration limit?</strong></p><p>Without a limit, the workflow could continue looping if the evaluator never approves a tweet.</p><p>The max_iteration condition provides loop protection and ensures that the workflow eventually stops.</p><h4>8. Build the LangGraph Workflow</h4><p>Now that we’ve defined all the nodes and the routing function, let’s connect them to create the iterative workflow.</p><p>First, register the nodes:</p><pre>graph.add_node(&#39;generate&#39;, generate_tweet)<br>graph.add_node(&#39;evaluate&#39;, evaluate_tweet)<br>graph.add_node(&#39;optimize&#39;, optimize_tweet)</pre><p><strong>Understanding the nodes:</strong></p><ul><li>generate creates the initial tweet.</li><li>evaluate checks the tweet and provides feedback.</li><li>optimize improves the tweet using that feedback.</li></ul><p>Next, define the edges:</p><pre>graph.add_edge(START, &#39;generate&#39;)<br>graph.add_edge(&#39;generate&#39;, &#39;evaluate&#39;)<br><br>graph.add_conditional_edges(<br>    &#39;evaluate&#39;,<br>    route_evaluation,<br>    {<br>        &#39;approved&#39;: END,<br>        &#39;needs_improvement&#39;: &#39;optimize&#39;<br>    }<br>)<br>graph.add_edge(&#39;optimize&#39;, &#39;evaluate&#39;)</pre><p><strong>Understanding the edges:</strong></p><ul><li><strong>Initial Flow:</strong> The workflow starts at START, moves to generate, and then proceeds to evaluate.</li><li><strong>Conditional Routing:</strong> After evaluation, route_evaluation determines the next step.</li><li><strong>Approved:</strong> If the tweet is approved or the maximum iteration limit is reached, the workflow moves to END.</li><li><strong>Needs Improvement:</strong> If the tweet needs improvement, the workflow moves to optimize.</li><li><strong>Loop:</strong> After optimization, the workflow returns to evaluate for another review.</li></ul><p>The edge from optimize back to evaluate creates the iterative loop.</p><h4>9. Compile the Workflow</h4><p>Once all nodes and edges are connected, compile the graph.</p><pre>workflow = graph.compile()</pre><p><strong>Understanding the compilation:</strong></p><p>The compile() method prepares the graph for execution using the nodes and edges we&#39;ve defined.</p><h4>10. Execute the Workflow</h4><p>Finally, let’s execute our workflow by providing an initial state.</p><pre>initial_state = {<br>    &quot;topic&quot;: &quot;Working From Home&quot;,<br>    &quot;iteration&quot;: 1,<br>    &quot;max_iteration&quot;: 5<br>}<br><br>result = workflow.invoke(initial_state)</pre><p><strong>Understanding the execution:</strong></p><ul><li><strong>Topic:</strong> We provide Working From Home as the topic for tweet generation.</li><li><strong>Initial Iteration:</strong> We start the iteration counter at 1.</li><li><strong>Maximum Iterations:</strong> We set the maximum iteration limit to 5.</li><li><strong>Invocation:</strong> The workflow.invoke() method starts the graph execution with the initial state.</li></ul><p>The workflow then generates a tweet, evaluates it, and optimizes it whenever necessary.</p><p>It stops when the evaluator approves the tweet or the iteration limit is reached.</p><h4>Complete Code</h4><p>Now, let’s combine everything into one Python script. You can copy this code into a Jupyter Notebook or Python file and execute the complete iterative workflow.</p><pre># If using ChatOpenAI<br># from langchain_openai import ChatOpenAI<br><br># If using ChatGoogleGenerativeAI<br>from langchain_google_genai import ChatGoogleGenerativeAI<br>from langgraph.graph import StateGraph, START, END<br>from langchain_core.messages import SystemMessage, HumanMessage<br>from typing import TypedDict, Literal, Annotated<br>from pydantic import BaseModel, Field<br>from dotenv import load_dotenv<br>import operator<br><br># Load environment variables<br>load_dotenv()<br><br># If using ChatOpenAI<br># Initialize ChatOpenAI<br># generator_llm = ChatOpenAI(model=&#39;gpt-4o-mini&#39;)<br># evaluator_llm = ChatOpenAI(model=&#39;gpt-4o-mini&#39;)<br># optimizer_llm = ChatOpenAI(model=&#39;gpt-4o-mini&#39;)<br><br># If using ChatGoogleGenerativeAI<br># Initialize ChatGoogleGenerativeAI<br>generator_llm = ChatGoogleGenerativeAI(model=&quot;gemini-2.5-flash&quot;)<br>evaluator_llm = ChatGoogleGenerativeAI(model=&quot;gemini-2.5-flash&quot;)<br>optimizer_llm = ChatGoogleGenerativeAI(model=&quot;gemini-2.5-flash&quot;)<br><br># 2. Define Evaluation Schema<br>class TweetEvaluation(BaseModel):<br>    evaluation: Literal[&quot;approved&quot;, &quot;needs_improvement&quot;] = Field(<br>        ...,<br>        description=&quot;Final evaluation result.&quot;<br>    )<br>    feedback: str = Field(<br>        ...,<br>        description=&quot;Feedback for the tweet.&quot;<br>    )<br><br>structured_evaluator_llm = evaluator_llm.with_structured_output(<br>    TweetEvaluation<br>)<br><br># 3. Define Workflow State<br>class TweetState(TypedDict):<br>    topic: str<br>    tweet: str<br>    evaluation: Literal[&quot;approved&quot;, &quot;needs_improvement&quot;]<br>    feedback: str<br>    iteration: int<br>    max_iteration: int<br>    tweet_history: Annotated[list[str], operator.add]<br>    feedback_history: Annotated[list[str], operator.add]<br><br># 4. Create StateGraph<br>graph = StateGraph(TweetState)<br><br># 5. Define Workflow Nodes<br># Generate Tweet<br>def generate_tweet(state: TweetState) -&gt; TweetState:<br>    messages = [<br>        SystemMessage(<br>            content=&quot;You are a funny and clever Twitter/X influencer.&quot;<br>        ),<br>        HumanMessage(content=f&quot;&quot;&quot;<br>        Write a short, original, and hilarious tweet on the topic: &quot;{state[&#39;topic&#39;]}&quot;.<br>        Rules:<br>        - Do NOT use question-answer format.<br>        - Max 280 characters.<br>        - Use observational humor, irony, sarcasm, or cultural references.<br>        - Think in meme logic, punchlines, or relatable takes.<br>        - Use simple, day to day english<br>        &quot;&quot;&quot;)<br>    ]<br><br>    response = generator_llm.invoke(messages).content<br><br>    return {<br>        &quot;tweet&quot;: response,<br>        &quot;tweet_history&quot;: [response]<br>    }<br><br># Evaluate Tweet<br>def evaluate_tweet(state: TweetState) -&gt; TweetState:<br>    messages = [<br>        SystemMessage(<br>            content=&quot;You are a ruthless, no-laugh-given Twitter critic. &quot;<br>                    &quot;You evaluate tweets based on humor, originality, &quot;<br>                    &quot;virality, and tweet format.&quot;<br>        ),<br>        HumanMessage(content=f&quot;&quot;&quot;<br>        Evaluate the following tweet:<br>        Tweet: &quot;{state[&#39;tweet&#39;]}&quot;<br>        Use the criteria below to evaluate the tweet:<br>        1. Originality – Is this fresh, or have you seen it a hundred times before?<br>        2. Humor – Did it genuinely make you smile, laugh, or chuckle?<br>        3. Punchiness – Is it short, sharp, and scroll-stopping?<br>        4. Virality Potential – Would people retweet or share it?<br>        5. Format – Is it a well-formed tweet (not a setup-punchline joke,<br>           not a Q&amp;A joke, and under 280 characters)?<br>        Auto-reject if:<br>        - It&#39;s written in question-answer format (e.g., &quot;Why did...&quot; or &quot;What happens when...&quot;)<br>        - It exceeds 280 characters<br>        - It reads like a traditional setup-punchline joke<br>        - Don&#39;t end with generic, throwaway, or deflating lines that weaken the humor.<br>        ### Respond ONLY in structured format:<br>        - evaluation: &quot;approved&quot; or &quot;needs_improvement&quot;<br>        - feedback: One paragraph explaining the strengths and weaknesses<br>        &quot;&quot;&quot;)<br>    ]<br><br>    response = structured_evaluator_llm.invoke(messages)<br><br>    return {<br>        &quot;evaluation&quot;: response.evaluation,<br>        &quot;feedback&quot;: response.feedback,<br>        &quot;feedback_history&quot;: [response.feedback]<br>    }<br><br># Optimize Tweet<br>def optimize_tweet(state: TweetState) -&gt; TweetState:<br>    messages = [<br>        SystemMessage(<br>            content=&quot;You punch up tweets for virality and humor based on given feedback.&quot;<br>        ),<br>        HumanMessage(content=f&quot;&quot;&quot;<br>        Improve the tweet based on this feedback:<br>        &quot;{state[&#39;feedback&#39;]}&quot;<br>        Topic: &quot;{state[&#39;topic&#39;]}&quot;<br>        Original Tweet:<br>        {state[&#39;tweet&#39;]}<br>        Re-write it as a short, viral-worthy tweet.<br>        Avoid Q&amp;A style and stay under 280 characters.<br>        &quot;&quot;&quot;)<br>    ]<br><br>    response = optimizer_llm.invoke(messages).content<br><br>    iteration = state[&quot;iteration&quot;] + 1<br>    return {<br>        &quot;tweet&quot;: response,<br>        &quot;iteration&quot;: iteration,<br>        &quot;tweet_history&quot;: [response]<br>    }<br><br># 6. Define Conditional Routing<br>def route_evaluation(<br>    state: TweetState<br>) -&gt; Literal[&quot;approved&quot;, &quot;needs_improvement&quot;]:<br>    if (<br>        state[&quot;evaluation&quot;] == &quot;approved&quot;<br>        or state[&quot;iteration&quot;] &gt;= state[&quot;max_iteration&quot;]<br>    ):<br>        return &quot;approved&quot;<br>    else:<br>        return &quot;needs_improvement&quot;<br><br># 7. Register Nodes<br>graph.add_node(&quot;generate&quot;, generate_tweet)<br>graph.add_node(&quot;evaluate&quot;, evaluate_tweet)<br>graph.add_node(&quot;optimize&quot;, optimize_tweet)<br><br># 8. Define Edges<br>graph.add_edge(START, &quot;generate&quot;)<br>graph.add_edge(&quot;generate&quot;, &quot;evaluate&quot;)<br>graph.add_conditional_edges(<br>    &quot;evaluate&quot;,<br>    route_evaluation,<br>    {<br>        &quot;approved&quot;: END,<br>        &quot;needs_improvement&quot;: &quot;optimize&quot;<br>    }<br>)<br>graph.add_edge(&quot;optimize&quot;, &quot;evaluate&quot;)<br><br># 9. Compile Workflow<br>workflow = graph.compile()<br><br># 10. Execute Workflow<br>initial_state = {<br>    &quot;topic&quot;: &quot;Working From Home&quot;,<br>    &quot;iteration&quot;: 1,<br>    &quot;max_iteration&quot;: 5<br>}<br>result = workflow.invoke(initial_state)<br><br># 11. Display Final Result<br>print(&quot;\nFinal Tweet:&quot;)<br>print(result[&quot;tweet&quot;])<br>print(&quot;\nEvaluation:&quot;)<br>print(result[&quot;evaluation&quot;])<br>print(&quot;\nTotal Iteration Count:&quot;)<br>print(result[&quot;iteration&quot;])<br>print(&quot;\nTweet History:&quot;)<br><br>for index, tweet in enumerate(result[&quot;tweet_history&quot;], start=1):<br>    print(f&quot;{index}. {tweet}&quot;)<br>print(&quot;\nFeedback History:&quot;)<br><br>for index, feedback in enumerate(result[&quot;feedback_history&quot;], start=1):<br>    print(f&quot;{index}. {feedback}&quot;)</pre><p><strong>Understanding the complete execution:</strong></p><ol><li>The workflow receives a topic from the user.</li><li>The generator LLM creates the initial tweet.</li><li>The evaluator LLM checks the tweet and returns its evaluation and feedback.</li><li>If approved, the workflow ends.</li><li>If improvement is needed, the optimizer generates a better tweet using the feedback.</li><li>The improved tweet returns to the evaluator for another review.</li><li>The loop continues until approval or the maximum iteration limit is reached.</li><li>Finally, the workflow returns the updated state, including the final tweet and its history.</li></ol><p><strong>Expected result:</strong> The script prints the final tweet, its evaluation status, iteration count, generated tweet history, and feedback history. Since LLM responses are non-deterministic, the actual tweets and number of iterations may vary between executions.</p><h4>Workflow Graph</h4><p>After compiling the workflow, we can visualize its structure using LangGraph’s built-in graph visualization functionality.</p><p>First, import Image from IPython:</p><pre>from IPython.display import Image</pre><p>Now, generate the workflow graph:</p><pre>Image(workflow.get_graph().draw_mermaid_png())</pre><p>This generates a visual representation of our iterative workflow.</p><figure><img alt="LangGraph graph visualization showing START connected to the generate node, followed by evaluate. The approved path leads to END, while the needs_improvement path leads to optimize and loops back to evaluate." src="https://cdn-images-1.medium.com/max/292/1*7jeztQMv7jxrAx85_ncUng.png" /><figcaption><em>LangGraph execution graph for the AI Tweet Generator, showing the generator, evaluator, and optimizer nodes connected through conditional routing and a feedback loop.</em></figcaption></figure><p>As you can see, the workflow doesn’t follow a single fixed execution path. The evaluator determines whether the tweet is ready or needs another optimization cycle.</p><p>This is what makes it an <strong>iterative workflow</strong>: the graph can repeat the evaluation and optimization steps until the desired condition is met.</p><h3>Final Thoughts</h3><p>In this article, we learned how to build an <strong>iterative (or looping) workflow in LangGraph</strong> and understood how it helps AI applications improve their outputs through repeated evaluation and optimization.</p><p>We explored a practical example of an AI-powered Tweet Generator that automatically generates and refines tweets.</p><p>Here’s what we built:</p><ul><li><strong>Tweet Generator:</strong> Generates an initial tweet based on the topic provided by the user.</li><li><strong>Tweet Evaluator:</strong> Evaluates the generated tweet based on originality, humor, punchiness, virality potential, and formatting.</li><li><strong>Tweet Optimizer:</strong> Uses the evaluator’s feedback to improve the tweet whenever it needs further refinement.</li><li><strong>Conditional Routing:</strong> Decides whether the workflow should end or continue with another optimization cycle.</li><li><strong>Iteration Tracking:</strong> Keeps track of the optimization iterations and limits the number of times the workflow can repeat.</li></ul><p>The loop continues until the evaluator approves the tweet or the maximum iteration limit is reached.</p><p>With this example, we now understand how iterative workflows help AI applications refine content step by step, use feedback to improve their outputs, and produce better final results.</p><p><strong>The key idea:</strong> Instead of stopping after the first attempt, an iterative workflow allows an AI agent to generate, evaluate, and improve its work through a continuous feedback loop.</p><h3>Key Takeaways</h3><p>In this article, we explored how to build <strong>iterative workflows in LangGraph</strong> and use looping execution to generate, evaluate, and improve outputs.</p><p>Here are the key concepts to remember:</p><ol><li><strong>Iterative Workflows:</strong> Also known as looping workflows, they allow two or more nodes to execute repeatedly until a specific condition is satisfied.</li><li><strong>Self-Correcting Agents:</strong> Iterative workflows help AI agents evaluate their own outputs and improve them using feedback.</li><li><strong>Generator Node:</strong> Creates the initial output based on the user’s input or topic.</li><li><strong>Evaluator Node:</strong> Checks the generated output against predefined quality criteria and returns an evaluation status along with feedback.</li><li><strong>Optimizer Node:</strong> Uses the evaluator’s feedback to refine and generate an improved version of the output.</li><li><strong>Conditional Routing:</strong> LangGraph uses add_conditional_edges() to decide whether the workflow should end or continue with another optimization cycle.</li><li><strong>State Management:</strong> The shared state maintains information such as the current tweet, evaluation status, feedback, iteration count, and maximum iteration limit.</li><li><strong>History Tracking with Reducers:</strong> Using Annotated[list[str], operator.add] allows the workflow to maintain the history of generated tweets and evaluation feedback across iterations.</li><li><strong>Maximum Iteration Limit:</strong> Setting a maximum iteration count helps prevent the workflow from looping indefinitely.</li><li><strong>Practical Application:</strong> We built an AI-powered Tweet Generator that generates tweets, evaluates their quality, and improves them based on feedback until they are approved or the iteration limit is reached.</li></ol><p><strong>The key idea:</strong> Iterative workflows enable AI applications to go beyond one-time generation by repeatedly evaluating and refining outputs through feedback loops.</p><h3>Conclusion</h3><p>In this part of our <strong>Agentic AI Using LangGraph</strong> series, we explored <strong>iterative workflows</strong> and learned how to build AI applications that can repeatedly generate, evaluate, and improve their outputs.</p><p>We started by understanding how looping workflows work and why they are useful for building self-correcting AI agents.</p><p>Then, we built a practical example: an <strong>AI-powered Tweet Generator</strong> using LangGraph and Gemini.</p><p>Through this example, we learned how to:</p><ul><li>Generate tweets based on a user-provided topic.</li><li>Evaluate generated tweets using an LLM and structured output.</li><li>Provide feedback when a tweet needs improvement.</li><li>Optimize the tweet based on the evaluator’s feedback.</li><li>Use conditional edges to control the loop and decide when the workflow should stop.</li><li>Track iterations, generated tweets, and evaluation feedback using shared state.</li></ul><p>The most important concept is that an AI workflow doesn’t always need to stop after generating its first output. It can evaluate the result, identify areas for improvement, and repeat the process until it meets the required criteria or reaches a predefined iteration limit.</p><p><strong>Iterative workflows are an important building block for creating self-improving AI applications.</strong> They allow us to move beyond one-time LLM responses and build systems that can refine their outputs through continuous feedback loops.</p><p>With this, we’ve explored four important workflow patterns in LangGraph: Sequential, Parallel, Conditional, and Iterative Workflows.</p><h3>What’s Next?</h3><p>In the next part of our <strong>Agentic AI Using LangGraph</strong> series, we’ll move from self-improving workflows to building a conversational AI application with memory.</p><p>So far, we’ve explored different workflow patterns, including sequential, parallel, conditional, and iterative workflows. But there’s another important capability that makes AI applications more useful: <strong>Memory</strong>.</p><p>Imagine having a conversation with a chatbot where you ask a question, receive an answer, and then ask a follow-up question related to your previous message. Without memory, the chatbot may not remember the earlier conversation.</p><p>So, how can we build a chatbot that remembers previous messages across multiple interactions?</p><p>That’s exactly what we’ll explore in <strong>Part 9: How to Build a Chatbot Using LangGraph</strong>.</p><p>In the next article, we’ll build a <strong>Question-Answering Chatbot with Memory</strong> that:</p><ul><li><strong>Answers User Questions:</strong> Uses an LLM to understand user queries and generate relevant responses.</li><li><strong>Maintains Conversation History:</strong> Stores previous user messages and AI responses.</li><li><strong>Uses LangGraph Memory:</strong> Integrates MemorySaver() to maintain conversation state.</li><li><strong>Supports Thread-Based Memory:</strong> Uses a unique thread_id to keep conversations separate.</li><li><strong>Handles Continuous Conversations:</strong> Allows users to ask multiple questions in the same conversation without losing context.</li></ul><p>We’ll also explore how add_messages helps append new messages to the existing conversation history and how LangGraph&#39;s checkpointer enables the chatbot to remember previous interactions.</p><blockquote><strong>Next Part:</strong> Agentic AI using LangGraph — Part 9: <strong>How to Build a Chatbot Using LangGraph</strong></blockquote><p>By the end, you’ll understand how to build a simple conversational chatbot that maintains context across multiple turns using LangGraph.</p><blockquote><strong>Series:</strong> Agentic AI using LangGraph — Part 8 of 27</blockquote><h3>Connect with me</h3><p><strong><em>Connect with me on </em></strong><a href="https://www.linkedin.com/in/shubhamnagar234/"><strong><em>LinkedIn</em></strong></a><strong><em>, </em></strong><a href="https://github.com/shubhamnagar234"><strong><em>GitHub</em></strong></a><strong><em>, </em></strong><a href="https://x.com/nagarshubham234"><strong><em>X (Twitter)</em></strong></a><strong><em>, or explore my </em></strong><a href="https://shubhamnagar234.vercel.app/"><strong><em>Portfolio</em></strong></a><strong><em>.</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5a03524613e3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Conditional Workflows in LangGraph: Building Dynamic AI Workflows with Decision-Based Routing —…]]></title>
            <link>https://medium.com/@shubhamnagar234/conditional-workflows-in-langgraph-building-dynamic-ai-workflows-with-decision-based-routing-7d55424d037a?source=rss-10b51a93c3a------2</link>
            <guid isPermaLink="false">https://medium.com/p/7d55424d037a</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[langgraph]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[workflow]]></category>
            <dc:creator><![CDATA[Shubham Nagar]]></dc:creator>
            <pubDate>Sun, 15 Nov 2026 10:48:50 GMT</pubDate>
            <atom:updated>2026-11-15T10:49:22.060Z</atom:updated>
            <content:encoded><![CDATA[<h3>Conditional Workflows in LangGraph: Building Dynamic AI Workflows with Decision-Based Routing — Part 7</h3><blockquote>Learn How to Build Conditional Workflows in LangGraph Using Conditional Edges, Dynamic Routing, and State-Based Decisions, with Practical Examples With and Without LLMs.</blockquote><p>In the previous articles, we explored two important workflow patterns in LangGraph:</p><ul><li><strong>Sequential Workflows:</strong> Tasks execute one after another in a predefined order.</li><li><strong>Parallel Workflows:</strong> Multiple independent tasks execute simultaneously, and their results are combined.</li></ul><p>But what if a workflow needs to make a decision before deciding what to do next?</p><p>For example, imagine a customer support chatbot that receives a user review. If the review is positive, it should generate a friendly thank-you message. If the review is negative, it should first analyze the issue and then generate an appropriate response.</p><blockquote>This is where <strong>Conditional Workflows</strong> become useful.</blockquote><p>In LangGraph, conditional workflows allow us to dynamically control the execution flow based on the current state. Instead of following a fixed sequence, the workflow evaluates a condition and chooses which node should execute next.</p><p>In this article, we’ll explore how conditional workflows work in LangGraph and build two practical examples to understand how decision-based routing works in real applications.</p><h3>Overview</h3><ul><li><strong><em>What Is a Conditional Workflow in LangGraph?</em></strong></li><li><strong><em>Why Conditional Workflows?</em></strong></li><li><strong><em>Example 1: Solve a Quadratic Equation (Without LLM)</em></strong></li><li><strong><em>Example 2: Customer Review Chatbot (With LLM)</em></strong></li><li><strong><em>Final Thoughts</em></strong></li><li><strong><em>Key Takeaways</em></strong></li><li><strong><em>Conclusion</em></strong></li><li><strong><em>What’s Next?</em></strong></li></ul><h3>What Is a Conditional Workflow in LangGraph?</h3><p>A <strong>conditional workflow</strong> in LangGraph is a workflow where the next step is determined dynamically based on the current State.</p><p>Unlike sequential workflows, where nodes execute in a predefined order, conditional workflows can follow different execution paths depending on the result of a condition.</p><p>LangGraph uses <strong>conditional edges</strong> to evaluate the current state and decide which node should run next.</p><p>For example, imagine a workflow that receives a user request. Based on the request, it can route the execution to different nodes. Similarly, a data validation workflow can choose different processing paths depending on whether the input data is valid or invalid.</p><p>The key characteristics of conditional workflows are:</p><ul><li><strong>Dynamic Decision-Making:</strong> The next step is determined by evaluating the current State.</li><li><strong>Conditional Edges:</strong> These evaluate the current state and decide which node should execute next.</li><li><strong>Multiple Execution Paths:</strong> The workflow can follow different paths depending on the condition’s result.</li><li><strong>Flexible Execution:</strong> The workflow adapts its execution flow based on data, user input, or the result of a previous node.</li></ul><h4>Conditional Workflow in LangGraph: Visual Explanation</h4><figure><img alt="Conditional workflow diagram showing a START node branching into two possible paths: Node 1 for a True condition and Node 2 for a False condition. Both paths eventually connect to the END node." src="https://cdn-images-1.medium.com/max/1024/1*sFS1VyjU0LTQyq-rF6UtIA.png" /><figcaption><em>A visual representation of conditional workflows in LangGraph, showing how execution follows different paths depending on whether a condition evaluates to True or False.</em></figcaption></figure><p>As shown in the diagram, the workflow starts from the START node and evaluates a condition to determine which path to follow.</p><ul><li><strong>Flow 1:</strong> The workflow follows the True path and executes Node 1 before reaching END.</li><li><strong>Flow 2:</strong> The workflow follows the False path and can execute one of the alternative nodes before reaching END.</li></ul><p>This allows a single workflow to handle different scenarios without requiring every node to execute in a fixed sequence.</p><p>In the next sections, we’ll explore why conditional workflows are useful and implement them through practical examples.</p><h3>Why Conditional Workflows?</h3><p>Conditional workflows are useful when an application needs to make decisions based on the data it receives or the results of previous steps.</p><p>Instead of executing every node in a fixed sequence, a conditional workflow evaluates a condition and chooses the appropriate path.</p><p>Think of it as a simple decision:</p><blockquote><strong>“If this happens, do this; otherwise, do that.”</strong></blockquote><p>This makes workflows more flexible because they can react differently to different inputs and situations.</p><p>Here are some key reasons why we use conditional workflows:</p><ul><li><strong>Decision-Making:</strong> They allow workflows to make decisions based on specific conditions or rules.</li><li><strong>Handling Different Inputs:</strong> Different inputs can trigger different execution paths, allowing the workflow to handle each situation appropriately.</li><li><strong>Dynamic Execution:</strong> The workflow can choose which steps to execute instead of following a fixed sequence every time.</li><li><strong>Flexible Applications:</strong> They make workflows more adaptable by allowing them to respond differently depending on the available data.</li></ul><p>Conditional workflows are useful for both simple problems and complex AI applications.</p><p>For example:</p><ul><li><strong>Simple Problems:</strong> A quadratic equation solver can check the discriminant and choose the appropriate path to calculate real roots, repeated roots, or handle cases with no real roots.</li><li><strong>Complex AI Applications:</strong> A customer support chatbot can analyze a review’s sentiment. Positive reviews receive a friendly response, while negative reviews go through an additional diagnosis step before generating a response.</li></ul><p>In short, <strong>conditional workflows make LangGraph applications more dynamic by allowing them to choose what happens next based on the current situation.</strong></p><h3>Example 1: Solve a Quadratic Equation Using LangGraph: A Step-by-Step Guide (Without LLM)</h3><p>Let’s start with a simple mathematical problem to understand how conditional workflows work in LangGraph.</p><p>In this example, we’ll build a <strong>Quadratic Equation Solver</strong> that uses conditional routing to determine which calculation should be performed based on the equation’s discriminant.</p><h4>What We’re Building</h4><p>We’ll create a LangGraph workflow that solves a quadratic equation of the form: <strong>ax² + bx + c = 0</strong></p><p>A quadratic equation can have two distinct real roots, one repeated real root, or no real roots.</p><p>To determine which case applies, we calculate the <strong>discriminant</strong> using the following formula: <strong>D = b² — 4ac</strong></p><p>The value of the discriminant determines which execution path the workflow should follow:</p><ul><li><strong>D &gt; 0:</strong> The equation has two distinct real roots.</li><li><strong>D = 0:</strong> The equation has one repeated real root.</li><li><strong>D &lt; 0:</strong> The equation has no real roots.</li></ul><figure><img alt="LangGraph conditional workflow for solving a quadratic equation. The workflow starts by displaying the equation and calculating the discriminant, then routes to one of three nodes: real_roots, repeated_roots, or no_real_roots." src="https://cdn-images-1.medium.com/max/1024/1*u5jEvjBovEn7qGAMf84_Aw.png" /><figcaption><em>Solving a quadratic equation using a conditional workflow in LangGraph. The workflow calculates the discriminant and dynamically selects the appropriate path to determine the roots.</em></figcaption></figure><h4>What This Diagram Shows (Explained)</h4><p>Let’s understand the different components of this workflow.</p><p><strong>1. START</strong></p><ul><li>The entry point of the workflow.</li><li>Execution begins when we provide the quadratic equation’s coefficients (a, b, and c).</li></ul><p><strong>2. show_equation and calculate_discriminant</strong></p><p>These are the two initial nodes:</p><ul><li><strong>show_equation:</strong> Creates a readable string representing the quadratic equation.</li><li><strong>calculate_discriminant:</strong> Computes the discriminant using (D = b² — 4ac). The calculated value determines which path the workflow should follow.</li></ul><p><strong>3. Conditional Edge (</strong><strong>check_condition)</strong></p><p>After calculating the discriminant, the workflow evaluates it using the check_condition routing function.</p><p>Depending on its value:</p><ul><li>If <strong>D &gt; 0</strong>, the workflow routes to real_roots.</li><li>If <strong>D = 0</strong>, the workflow routes to repeated_roots.</li><li>If <strong>D &lt; 0</strong>, the workflow routes to no_real_roots.</li></ul><p><strong>4. real_roots / repeated_roots / no_real_roots</strong></p><p>These nodes handle the three possible outcomes:</p><ul><li><strong>real_roots:</strong> Calculates two distinct real roots using the quadratic formula.</li><li><strong>repeated_roots:</strong> Calculates the single repeated root.</li><li><strong>no_real_roots:</strong> Returns a message indicating that no real roots exist.</li></ul><p><strong>5. END</strong></p><ul><li>Each of the three possible paths connects to END.</li><li>Once the selected node finishes execution, the workflow ends and returns the final state to the caller.</li></ul><h4>Why Is This Workflow “Conditional”?</h4><p>This workflow is conditional because its execution path is not fixed.</p><p>After calculating the discriminant, LangGraph evaluates the condition and dynamically chooses which node to execute next.</p><p>For example, if the discriminant is zero, the workflow executes repeated_roots. If it is greater than zero, it executes real_roots instead.</p><p>This demonstrates how conditional edges allow a LangGraph workflow to make decisions and follow different execution paths based on the current state.</p><h4>1. Import LangGraph and Define the State</h4><p>First, let’s import the required components from LangGraph and Python’s typing module.</p><pre>from langgraph.graph import StateGraph, START, END<br>from typing import TypedDict, Literal</pre><p>Next, we’ll define the state for our quadratic equation solver.</p><pre># Create a state<br>class QuadraticState(TypedDict):<br>    a: int<br>    b: int<br>    c: int<br><br>    discriminant: float<br>    equation: str<br>    result: str</pre><p><strong>Understanding the code:</strong></p><ul><li><strong>Imports:</strong> We import StateGraph, START, and END from langgraph.graph to structure our workflow. We also import TypedDict and Literal to define the state structure and specify the possible routing outcomes.</li><li><strong>State Definition:</strong> We define QuadraticState to describe the data shared across our workflow.</li></ul><p>It contains:</p><ul><li><strong>Input values:</strong> a, b, and c represent the coefficients of the quadratic equation.</li><li><strong>Intermediate values:</strong> discriminant stores the calculated discriminant, while equation stores the formatted equation.</li><li><strong>Final output:</strong> result stores the calculated roots or the message indicating that no real roots exist.</li></ul><h4>2. Initialize the Graph</h4><p>Now, let’s initialize our LangGraph workflow using the state schema we just defined.</p><pre># Create a graph<br>graph = StateGraph(QuadraticState)</pre><p><strong>Understanding the code:</strong></p><ul><li><strong>Initialization:</strong> We instantiate a StateGraph object and pass QuadraticState as its state schema.</li><li><strong>State Structure:</strong> This defines the structure of the data that our workflow nodes will read and update during execution.</li></ul><h4>3. Define Node Functions</h4><p>In LangGraph, each node represents an individual task. We’ll define separate functions for displaying the equation, calculating the discriminant, and handling the three possible outcomes.</p><p><strong>Show Equation Node</strong></p><pre>def show_equation(state: QuadraticState) -&gt; QuadraticState:<br>    <br>    equation = f&#39;{state[&quot;a&quot;]}x2{state[&quot;b&quot;]}x{state[&quot;c&quot;]}&#39;<br>     <br>    return {&#39;equation&#39;: equation}</pre><p><strong>Understanding the code:</strong></p><ul><li><strong>Functionality:</strong> This node takes the current state and creates a string representing the quadratic equation using the coefficients a, b, and c.</li><li><strong>State Update:</strong> It returns the equation key, which updates the corresponding value in the overall workflow state.</li></ul><p><strong>Calculate Discriminant Node</strong></p><pre>def calculate_discriminant(state: QuadraticState) -&gt; QuadraticState:<br>    <br>    discriminant = state[&quot;b&quot;]**2 - (4 * state[&quot;a&quot;] * state[&quot;c&quot;])<br>    <br>    return {&#39;discriminant&#39;: discriminant}</pre><p><strong>Understanding the code:</strong></p><ul><li><strong>Mathematical Operation:</strong> It calculates the discriminant using the formula:</li><li>D = b² — 4ac</li><li><strong>State Update:</strong> It returns the calculated discriminant, which will be used by the conditional routing function to determine the next execution path.</li></ul><p><strong>Real Roots Node</strong></p><pre>def real_roots(state: QuadraticState) -&gt; QuadraticState:<br><br>    root1 = (-state[&quot;b&quot;] + state[&quot;discriminant&quot;]**0.5) / (2 * state[&quot;a&quot;])<br>    <br>    root2 = (-state[&quot;b&quot;] - state[&quot;discriminant&quot;]**0.5) / (2 * state[&quot;a&quot;])<br>    <br>    result = f&#39;The roots are {root1} and {root2}&#39;<br>    <br>    return {&#39;result&#39;: result}</pre><p><strong>Understanding the code:</strong></p><ul><li><strong>Calculation:</strong> This node uses the quadratic formula to calculate two distinct real roots when the discriminant is greater than zero.</li><li><strong>State Update:</strong> It stores both calculated roots in the result field of the state.</li></ul><p><strong>Repeated Roots Node</strong></p><pre>def repeated_roots(state: QuadraticState) -&gt; QuadraticState:<br><br>    root = (-state[&quot;b&quot;]) / (2 * state[&quot;a&quot;])<br>    <br>    result = f&#39;Only repeating root is {root}&#39;<br>    <br>    return {&#39;result&#39;: result}</pre><p><strong>Understanding the code:</strong></p><ul><li><strong>Calculation:</strong> When the discriminant is exactly zero, this node calculates the single repeated root using:</li><li><strong>x = -b / (2a)</strong></li><li><strong>State Update:</strong> It updates the result field with the calculated repeated root.</li></ul><p><strong>No Real Roots Node</strong></p><pre>def no_real_roots(state: QuadraticState) -&gt; QuadraticState:<br><br>    result = &#39;No real roots&#39;<br>    <br>    return {&#39;result&#39;: result}</pre><p><strong>Understanding the code:</strong></p><ul><li><strong>Handling Negative Discriminants:</strong> When the discriminant is less than zero, this node returns a message indicating that the equation has no real roots.</li><li><strong>State Update:</strong> It stores the message in the result field.</li></ul><p><strong>Conditional Function (</strong><strong>check_condition)</strong></p><p>Now comes the most important part of our workflow: the conditional routing function.</p><pre>def check_condition(state: QuadraticState) -&gt; Literal[&quot;real_roots&quot;, &quot;repeated_roots&quot;, &quot;no_real_roots&quot;]:<br><br>    if state[&#39;discriminant&#39;] &gt; 0:<br>        return &quot;real_roots&quot;<br>    elif state[&#39;discriminant&#39;] == 0:<br>        return &quot;repeated_roots&quot;<br>    else:<br>        return &quot;no_real_roots&quot;</pre><p><strong>Understanding the code:</strong></p><ul><li><strong>Routing Logic:</strong> Unlike the previous functions, check_condition is not a node. It is a routing function that examines the discriminant in the current state and decides which node should execute next.</li><li><strong>Dynamic Execution:</strong> Depending on the discriminant’s value, it returns the name of the next node:</li><li>&quot;real_roots&quot; when the discriminant is greater than zero.</li><li>&quot;repeated_roots&quot; when the discriminant equals zero.</li><li>&quot;no_real_roots&quot; when the discriminant is less than zero.</li></ul><p>The Literal type hint specifies the possible routing destinations.</p><h4>4. Add Nodes to the Graph</h4><p>After defining our functions, we need to register them as nodes in the LangGraph workflow.</p><pre># Add nodes<br>graph.add_node(&#39;show_equation&#39;, show_equation)<br>graph.add_node(&#39;calculate_discriminant&#39;, calculate_discriminant)<br>graph.add_node(&#39;real_roots&#39;, real_roots)<br>graph.add_node(&#39;repeated_roots&#39;, repeated_roots)<br>graph.add_node(&#39;no_real_roots&#39;, no_real_roots)</pre><p><strong>Understanding the code:</strong></p><ul><li><strong>Registration:</strong> We use graph.add_node() to register each Python function as a node in the graph.</li><li><strong>Naming:</strong> The first argument specifies the node’s name, while the second argument references the function that implements its logic.</li></ul><p>These node names are important because our conditional routing function uses them to determine where execution should go next.</p><h4>5. Connect the Nodes (Add Edges)</h4><p>Now, let’s connect the nodes and define how execution should flow through the graph.</p><pre># Add edges<br>graph.add_edge(START, &#39;show_equation&#39;)<br>graph.add_edge(&#39;show_equation&#39;, &#39;calculate_discriminant&#39;)<br><br>graph.add_conditional_edges(&#39;calculate_discriminant&#39;, check_condition)<br><br>graph.add_edge(&#39;real_roots&#39;, END)<br>graph.add_edge(&#39;repeated_roots&#39;, END)<br>graph.add_edge(&#39;no_real_roots&#39;, END)</pre><p><strong>Understanding the code:</strong></p><ul><li><strong>Standard Edges:</strong> We use graph.add_edge() to connect nodes in a fixed sequence. First, execution moves from START to show_equation, then to calculate_discriminant.</li><li><strong>Conditional Edges:</strong> We use graph.add_conditional_edges() to connect calculate_discriminant with the routing function check_condition. Once the discriminant has been calculated, LangGraph calls this function to determine which node should execute next.</li><li><strong>End Edges:</strong> All three possible outcome nodes connect directly to END. This ensures that the workflow finishes after the selected calculation is completed.</li></ul><p>The important difference is that graph.add_edge() defines a fixed transition, while graph.add_conditional_edges() allows the workflow to choose its next node dynamically.</p><h4>6. Compile and Run the Workflow</h4><p>Once all nodes and edges have been defined, we can compile the graph.</p><pre># Compile graph<br>workflow = graph.compile()</pre><p><strong>Understanding the code:</strong></p><ul><li><strong>Compilation:</strong> The graph.compile() method finalizes the graph structure and creates a runnable workflow object.</li></ul><p>We can now provide the initial input and execute the workflow.</p><pre># Execute the graph<br>initial_state = {<br>    &#39;a&#39;: 2,<br>    &#39;b&#39;: 4,<br>    &#39;c&#39;: 2<br>}<br><br>final_state = workflow.invoke(initial_state)<br><br>print(final_state)</pre><p><strong>Understanding the code:</strong></p><ul><li><strong>Execution:</strong> We call workflow.invoke() and pass the initial state containing the coefficients a, b, and c.</li><li><strong>Result:</strong> LangGraph executes the workflow, calculates the discriminant, follows the appropriate conditional path, and returns the updated final state.</li></ul><h4>7. Complete Code</h4><p>Here is the complete implementation of our Solve a Quadratic Equation using LangGraph and Gemini 2.5 Flash.</p><pre>from langgraph.graph import StateGraph, START, END<br>from typing import TypedDict, Literal<br><br><br># Define the shared state of the quadratic equation workflow<br>class QuadraticState(TypedDict):<br><br>    a : int<br>    b : int<br>    c : int<br>    <br>    discriminant: float<br>    equation: str<br>    result : str<br><br><br># Node 1: Display the quadratic equation using the given coefficients<br>def show_equation(state: QuadraticState) -&gt; QuadraticState:<br><br>    equation = f&#39;{state[&quot;a&quot;]}x2{state[&quot;b&quot;]}x{state[&quot;c&quot;]}&#39;<br><br>    return {&#39;equation&#39;:equation}<br><br><br># Node 2: Calculate the discriminant of the quadratic equation<br>def calculate_discriminant(state: QuadraticState) -&gt; QuadraticState:<br><br>    discriminant = state[&quot;b&quot;]**2 - (4*state[&quot;a&quot;]*state[&quot;c&quot;])<br><br>    return {&#39;discriminant&#39;: discriminant}<br><br><br># Node 3: Calculate both real roots when the discriminant is positive<br>def real_roots(state: QuadraticState) -&gt; QuadraticState:<br><br>    root1 = (-state[&quot;b&quot;] + state[&quot;discriminant&quot;]**0.5)/(2*state[&quot;a&quot;])<br>    root2 = (-state[&quot;b&quot;] - state[&quot;discriminant&quot;]**0.5)/(2*state[&quot;a&quot;])<br><br>    result = f&#39;The roots are {root1} and {root2}&#39;<br><br>    return {&#39;result&#39;: result}<br><br><br># Node 4: Calculate the repeated root when the discriminant is zero<br>def repeated_roots(state: QuadraticState) -&gt; QuadraticState:<br><br>    root = (-state[&quot;b&quot;])/(2*state[&quot;a&quot;])<br><br>    result = f&#39;Only repeating root is {root}&#39;<br><br>    return {&#39;result&#39;: result}<br><br><br># Node 5: Return a message when the discriminant is negative<br>def no_real_roots(state: QuadraticState) -&gt; QuadraticState:<br><br>    result = f&#39;No real roots&#39;<br><br>    return {&#39;result&#39;: result}<br><br><br># Conditional Function: Select the next node based on the discriminant<br>def check_condition(state: QuadraticState) -&gt; Literal[&quot;real_roots&quot;, &quot;repeated_roots&quot;, &quot;no_real_roots&quot;]:<br><br>    if state[&#39;discriminant&#39;] &gt; 0:<br>        return &quot;real_roots&quot;<br>    elif state[&#39;discriminant&#39;] == 0:<br>        return &quot;repeated_roots&quot;<br>    else:<br>        return &quot;no_real_roots&quot;<br><br><br># Initialize the LangGraph workflow using the QuadraticState schema<br>graph = StateGraph(QuadraticState)<br><br><br># Register all workflow nodes<br>graph.add_node(&#39;show_equation&#39;, show_equation)<br>graph.add_node(&#39;calculate_discriminant&#39;, calculate_discriminant)<br>graph.add_node(&#39;real_roots&#39;, real_roots)<br>graph.add_node(&#39;repeated_roots&#39;, repeated_roots)<br>graph.add_node(&#39;no_real_roots&#39;, no_real_roots)<br><br><br># Define the workflow execution sequence and conditional routing<br>graph.add_edge(START, &#39;show_equation&#39;)<br>graph.add_edge(&#39;show_equation&#39;, &#39;calculate_discriminant&#39;)<br>graph.add_conditional_edges(&#39;calculate_discriminant&#39;, check_condition)<br><br>graph.add_edge(&#39;real_roots&#39;, END)<br>graph.add_edge(&#39;repeated_roots&#39;, END)<br>graph.add_edge(&#39;no_real_roots&#39;, END)<br><br><br># Compile the graph into an executable workflow<br>workflow = graph.compile()<br><br><br># Provide the initial coefficients of the quadratic equation<br>initial_state = {<br>    &#39;a&#39;: 2,<br>    &#39;b&#39;: 4,<br>    &#39;c&#39;: 2<br>}<br><br><br># Execute the workflow and retrieve the final state<br>final_state = workflow.invoke(initial_state)<br><br><br># Display the final equation, discriminant, and calculated result<br>print(final_state)</pre><h4>Output</h4><pre>{<br>    &#39;a&#39;: 2,<br>    &#39;b&#39;: 4,<br>    &#39;c&#39;: 2,<br>    &#39;discriminant&#39;: 0.0,<br>    &#39;equation&#39;: &#39;2x24x2&#39;,<br>    &#39;result&#39;: &#39;Only repeating root is -1.0&#39;<br>}</pre><p>Let’s understand this output:</p><ul><li><strong>Input:</strong> The coefficients are a = 2, b = 4, and c = 2.</li><li><strong>Discriminant:</strong> The calculated value is 0.0.</li><li><strong>Equation:</strong> The workflow stores the formatted equation in the equation field.</li><li><strong>Result:</strong> Since the discriminant is zero, the conditional function routes execution to repeated_roots, which calculates the repeated root as -1.0.</li></ul><p>This confirms that the workflow successfully selected the correct execution path based on the discriminant.</p><h4>Workflow Graph</h4><p>We can also visualize the compiled workflow using LangGraph’s built-in graph visualization.</p><pre>from IPython.display import Image<br><br>Image(workflow.get_graph().draw_mermaid_png())</pre><figure><img alt="Workflow graph showing START connected to show_equation and calculate_discriminant, followed by conditional branches to real_roots, repeated_roots, and no_real_roots. Each branch connects to END." src="https://cdn-images-1.medium.com/max/483/1*hRv6lTgOvCU972WfvqzcvQ.png" /><figcaption><em>Compiled LangGraph visualization of the quadratic equation solver, showing the initial sequential nodes, conditional routing to three possible outcome nodes, and their connections to END.</em></figcaption></figure><h4>Understanding What We Built</h4><p>In this example, we built a quadratic equation solver using LangGraph without using an LLM.</p><p>The workflow follows these steps:</p><ol><li>Receives the coefficients of a quadratic equation.</li><li>Creates a readable representation of the equation.</li><li>Calculates the discriminant.</li><li>Evaluates the discriminant using the check_condition routing function.</li><li>Dynamically selects one of three nodes:</li></ol><ul><li>real_roots</li><li>repeated_roots</li><li>no_real_roots</li></ul><p>6. Returns the final result.</p><p>The key concept is that <strong>the workflow does not execute every node</strong>. It selects only the appropriate path based on the condition.</p><p>This is the foundation of conditional routing in LangGraph.</p><h3>Example 2: Customer Review Chatbot Using LangGraph: A Step-by-Step Guide (With LLM)</h3><p>In the previous example, we built a quadratic equation solver using conditional workflows without an LLM.</p><p>Now, let’s explore a more practical AI application: an <strong>LLM-powered Customer Review Chatbot</strong>.</p><p>In this example, we’ll use an LLM to analyze customer reviews, identify their sentiment, and dynamically route the workflow to generate an appropriate response.</p><h4>What Are We Building?</h4><p>We’re building a smart customer support system using:</p><ul><li><strong>Large Language Model (LLM):</strong> To analyze customer reviews, identify sentiment, and generate responses.</li><li><strong>LangGraph:</strong> To organize the workflow and manage conditional execution.</li><li><strong>Pydantic:</strong> To define structured output schemas for sentiment classification and review diagnosis.</li></ul><p>Our application will perform the following tasks:</p><ol><li>Take a customer review as input.</li><li>Use an LLM to evaluate the sentiment of the review as either <strong>Positive</strong> or <strong>Negative</strong>.</li><li>Based on the detected sentiment, the workflow follows one of two paths:</li></ol><ul><li><strong>Positive:</strong> Generate a friendly thank-you response.</li><li><strong>Negative:</strong> First diagnose the review to identify the issue type, emotional tone, and urgency. Then generate an empathetic and solution-oriented response based on the diagnosis.</li></ul><figure><img alt="Conditional LangGraph workflow for a customer review chatbot. The workflow starts with sentiment analysis and branches into a positive response path or a negative review diagnosis followed by a negative response." src="https://cdn-images-1.medium.com/max/1024/1*EelNmMK-3n_o7n5Ose_bFQ.png" /><figcaption><em>Customer Review Chatbot using LangGraph and an LLM. The workflow identifies the sentiment of a customer review and dynamically selects the appropriate response-generation path.</em></figcaption></figure><h4>Understanding Conditional Workflows in LangGraph: A Visual Breakdown</h4><p>Let’s understand how each component of this workflow works.</p><p><strong>1. START</strong></p><ul><li>The workflow begins here.</li><li>This is the entry point where we provide the customer review as input.</li></ul><p><strong>2. find_sentiment</strong></p><ul><li>The LLM analyzes the customer review and determines whether its sentiment is positive or negative.</li><li>It returns the sentiment in a structured format using the defined Pydantic schema.</li></ul><p><strong>3. Conditional Edge (</strong><strong>check_sentiment)</strong></p><p>This routing function checks the sentiment value and determines which path the workflow should follow.</p><ul><li>If the sentiment is &quot;positive&quot;, execution routes to the positive_response node.</li><li>If the sentiment is &quot;negative&quot;, execution routes to the run_diagnosis node.</li></ul><p><strong>4. positive_response</strong></p><ul><li>The LLM generates a warm and friendly thank-you message in response to positive customer feedback.</li><li>The generated response is stored in the workflow state.</li></ul><p><strong>5. run_diagnosis</strong></p><ul><li>This node executes only when the review is negative.</li><li>The LLM analyzes the review to identify the issue type, emotional tone, and urgency.</li><li>It returns a structured diagnosis that helps generate an appropriate response.</li></ul><p><strong>6. negative_response</strong></p><ul><li>This node uses the diagnosis generated in the previous step.</li><li>The LLM generates an empathetic and solution-oriented response based on the identified issue, tone, and urgency.</li></ul><p><strong>7. END</strong></p><ul><li>The workflow ends after generating the appropriate response.</li><li>The final state, including the generated response, is returned to the caller.</li></ul><h4>1. Import and Setup</h4><p>First, let’s import the required libraries and components.</p><pre># If using ChatOpenAI<br># from langchain_openai import ChatOpenAI<br><br># If using ChatGoogleGenerativeAI<br>from langchain_google_genai import ChatGoogleGenerativeAI<br><br>from langgraph.graph import StateGraph, START, END<br>from typing import TypedDict, Literal<br>from dotenv import load_dotenv<br>from pydantic import BaseModel, Field</pre><p><strong>Understanding the code:</strong></p><ul><li><strong>LLM Integration:</strong> We import ChatGoogleGenerativeAI to integrate Google&#39;s Gemini model into our chatbot.</li><li><strong>LangGraph Components:</strong> We import StateGraph, START, and END to define and execute the workflow.</li><li><strong>Typing:</strong> We use TypedDict and Literal to define the workflow state and restrict possible values.</li><li><strong>Environment Variables:</strong> We import load_dotenv to load API credentials from a .env file.</li><li><strong>Pydantic:</strong> We import BaseModel and Field to define structured output schemas for the LLM.</li></ul><h4>2. Configure Environment Variables</h4><p>Before initializing the LLM, we need to configure the API credentials.</p><p>Create a .env file in your project directory:</p><pre>OPENAI_API_KEY=&quot;YOUR_OPENAI_API_KEY&quot;<br>GEMINI_API_KEY=&quot;YOUR_GEMINI_API_KEY&quot;</pre><p>Now, load the environment variables:</p><pre>load_dotenv()</pre><p><strong>Understanding the code:</strong></p><ul><li><strong>API Keys:</strong> We define the API credentials in the .env file. Since we&#39;re using Gemini in this example, we need the GEMINI_API_KEY.</li><li><strong>Loading:</strong> We use load_dotenv() to load the environment variables so the application can access the configured credentials.</li></ul><h4>3. Initialize the LLM</h4><p>Next, let’s initialize the language model that will power our customer support chatbot.</p><pre># If using ChatOpenAI<br># Initialize ChatOpenAI<br># model = ChatOpenAI(model=&quot;gpt-4o-mini&quot;)<br><br># If using ChatGoogleGenerativeAI<br># Initialize ChatGoogleGenerativeAI<br>model = ChatGoogleGenerativeAI(model=&quot;gemini-2.5-flash&quot;)</pre><p><strong>Understanding the code:</strong></p><ul><li><strong>Model Selection:</strong> We initialize the Gemini 2.5 Flash model using the ChatGoogleGenerativeAI class.</li><li><strong>Model Instance:</strong> The model instance will be used throughout the workflow for sentiment analysis, review diagnosis, and response generation.</li></ul><p>You can also use the commented-out ChatOpenAI option if you prefer an OpenAI model and have configured the corresponding API credentials.</p><h4>4. Define Schemas and Structured Output</h4><p>Before defining our workflow nodes, let’s create Pydantic schemas to specify the structure of the LLM’s responses.</p><p>We’ll define two schemas:</p><p><strong>SentimentSchema</strong></p><p>This schema ensures that the sentiment classification returns either positive or negative.</p><pre>class SentimentSchema(BaseModel):<br><br>    sentiment: Literal[&quot;positive&quot;, &quot;negative&quot;] = Field(<br>        description=&#39;Sentiment of the review&#39;<br>    )</pre><p><strong>DiagnosisSchema</strong></p><p>This schema defines the information we need when diagnosing a negative customer review.</p><pre>class DiagnosisSchema(BaseModel):<br><br>    issue_type: Literal[&quot;UX&quot;, &quot;Performance&quot;, &quot;Bug&quot;, &quot;Support&quot;, &quot;Other&quot;] = Field(<br>        description=&#39;The category of issue mentioned in the review&#39;<br>    )<br>  <br>    tone: Literal[&quot;angry&quot;, &quot;frustrated&quot;, &quot;disappointed&quot;, &quot;calm&quot;] = Field(<br>        description=&#39;The emotional tone expressed by the user&#39;<br>    )<br><br>    urgency: Literal[&quot;low&quot;, &quot;medium&quot;, &quot;high&quot;] = Field(<br>        description=&#39;How urgent or critical the issue appears to be&#39;<br>    )</pre><p><strong>Understanding the code:</strong></p><ul><li><strong>SentimentSchema:</strong> Defines the sentiment field and restricts its value to either &quot;positive&quot; or &quot;negative&quot;.</li><li><strong>DiagnosisSchema:</strong> Defines three fields:</li><li>issue_type: Identifies the category of the reported issue.</li><li>tone: Identifies the emotional tone expressed by the customer.</li><li>urgency: Indicates how urgent or critical the issue appears to be.</li></ul><p>Now, let’s create structured versions of our LLM:</p><pre>structured_model = model.with_structured_output(SentimentSchema)<br><br>structured_model2 = model.with_structured_output(DiagnosisSchema)</pre><p><strong>Understanding the code:</strong></p><ul><li><strong>structured_model:</strong> Uses SentimentSchema to structure the sentiment classification output.</li><li><strong>structured_model2:</strong> Uses DiagnosisSchema to structure the negative review diagnosis.</li></ul><p>We use .with_structured_output() to guide the model toward returning data that follows the specified Pydantic schema, rather than relying on an unrestricted text response.</p><h4>5. Define the State (ReviewState)</h4><p>Now, let’s define the shared state for our customer review chatbot.</p><pre>class ReviewState(TypedDict):<br><br>    review: str<br>    sentiment: Literal[&quot;positive&quot;, &quot;negative&quot;]<br>    diagnosis: dict<br>    response: str</pre><p><strong>Understanding the code:</strong></p><p>The ReviewState stores all the information required throughout the workflow:</p><ul><li><strong>review:</strong> The original customer review provided as input.</li><li><strong>sentiment:</strong> The sentiment identified by the LLM, either positive or negative.</li><li><strong>diagnosis:</strong> The structured diagnosis generated for a negative review.</li><li><strong>response:</strong> The final customer support response generated by the LLM.</li></ul><p>This shared state allows different nodes to access the information they need and update the workflow as it executes.</p><h4>6. Build the Graph</h4><p>Next, initialize the LangGraph workflow using the ReviewState schema.</p><pre>graph = StateGraph(ReviewState)</pre><p><strong>Understanding the code:</strong></p><ul><li><strong>Initialization:</strong> We create a StateGraph object and pass ReviewState as its state schema.</li><li><strong>State Management:</strong> This defines the structure of the information that our workflow nodes will read and update.</li></ul><h4>7. Define Your Workflow Nodes (Functions)</h4><p>Now, let’s define the individual functions that perform the tasks in our customer support workflow.</p><p><strong>find_sentiment</strong></p><p>This node analyzes the customer review and identifies whether the sentiment is positive or negative.</p><pre>def find_sentiment(state: ReviewState) -&gt; ReviewState:<br><br>    prompt = f&#39;For the following review find out the sentiment \n {state[&quot;review&quot;]}&#39;<br>    <br>    sentiment = structured_model.invoke(prompt).sentiment<br>    <br>    return {&#39;sentiment&#39;: sentiment}</pre><p><strong>Understanding the code:</strong></p><ul><li><strong>Action:</strong> We create a prompt containing the customer review and pass it to structured_model.</li><li><strong>Sentiment Classification:</strong> The LLM analyzes the review and returns a structured sentiment value.</li><li><strong>State Update:</strong> We update the sentiment field in the workflow state.</li></ul><p><strong>check_sentiment (Conditional Logic)</strong></p><p>This is the conditional routing function that determines which node should execute next.</p><pre>def check_sentiment(state: ReviewState) -&gt; Literal[&quot;positive_response&quot;, &quot;run_diagnosis&quot;]:<br><br>    if state[&#39;sentiment&#39;] == &#39;positive&#39;:<br>        return &#39;positive_response&#39;<br>    else:<br>        return &#39;run_diagnosis&#39;</pre><p><strong>Understanding the code:</strong></p><ul><li><strong>Routing Logic:</strong> The function checks the value of state[&#39;sentiment&#39;].</li><li><strong>Dynamic Routing:</strong></li><li>If the sentiment is &#39;positive&#39;, it returns &#39;positive_response&#39;.</li><li>Otherwise, it returns &#39;run_diagnosis&#39;.</li></ul><p>This function does not generate a response itself. Its responsibility is to decide which node should execute next based on the sentiment.</p><p><strong>positive_response</strong></p><p>This node generates a friendly response when the customer submits a positive review.</p><pre>def positive_response(state: ReviewState) -&gt; ReviewState:<br><br>    prompt = f&quot;&quot;&quot;Write a warm thank-you message in response to this review:<br>    <br>    \n\n&quot;{state[&#39;review&#39;]}&quot;\n<br>    <br>    Also, kindly ask the user to leave feedback on our website.&quot;&quot;&quot;<br>    <br>    response = model.invoke(prompt).content<br>     <br>    return {&#39;response&#39;: response}</pre><p><strong>Understanding the code:</strong></p><ul><li><strong>Action:</strong> We create a prompt asking the LLM to generate a warm thank-you message based on the customer’s review.</li><li><strong>Response Generation:</strong> The LLM generates a friendly response and asks the customer to leave feedback on the website.</li><li><strong>State Update:</strong> The generated message is stored in the response field.</li></ul><p><strong>run_diagnosis</strong></p><p>This node is executed only when the customer review has negative sentiment.</p><pre>def run_diagnosis(state: ReviewState) -&gt; ReviewState:<br><br>    prompt = f&quot;&quot;&quot;Diagnose this negative review:<br>    {state[&#39;review&#39;]}<br>    Return issue_type, tone, and urgency.<br>    &quot;&quot;&quot;<br>    <br>    response = structured_model2.invoke(prompt)<br>    <br>    return {&#39;diagnosis&#39;: response.model_dump()}</pre><p><strong>Understanding the code:</strong></p><ul><li><strong>Action:</strong> We pass the negative customer review to structured_model2 for diagnosis.</li><li><strong>Diagnosis:</strong> The LLM identifies the issue type, emotional tone, and urgency using the DiagnosisSchema.</li><li><strong>State Update:</strong> We use .model_dump() to convert the returned Pydantic object into a dictionary and store it in the diagnosis field.</li></ul><p><strong>negative_response</strong></p><p>After diagnosing the negative review, this node generates a customized response using the diagnosis details.</p><pre>def negative_response(state: ReviewState) -&gt; ReviewState:<br><br>    diagnosis = state[&#39;diagnosis&#39;]<br>    <br>    prompt = f&quot;&quot;&quot;You are a support assistant.<br>    The user had a &#39;{diagnosis[&#39;issue_type&#39;]}&#39; issue, sounded &#39;{diagnosis[&#39;tone&#39;]}&#39;, and marked urgency as &#39;{diagnosis[&#39;urgency&#39;]}&#39;.<br>    Write an empathetic, helpful resolution message.<br>    &quot;&quot;&quot;<br>    <br>    response = model.invoke(prompt).content<br>    <br>    return {&#39;response&#39;: response}</pre><p><strong>Understanding the code:</strong></p><ul><li><strong>Action:</strong> We retrieve the diagnosis from the current state.</li><li><strong>Response Generation:</strong> The LLM uses the issue type, emotional tone, and urgency to generate an empathetic and helpful resolution message.</li><li><strong>State Update:</strong> The generated response is stored in the response field.</li></ul><h4>8. Build the LangGraph Workflow</h4><p>Now that we’ve defined all the node functions, let’s register them in our graph.</p><pre># Add nodes<br>graph.add_node(&#39;find_sentiment&#39;, find_sentiment)<br>graph.add_node(&#39;positive_response&#39;, positive_response)<br>graph.add_node(&#39;run_diagnosis&#39;, run_diagnosis)<br>graph.add_node(&#39;negative_response&#39;, negative_response)</pre><p><strong>Understanding the code:</strong></p><ul><li><strong>Node Registration:</strong> We use graph.add_node() to register each Python function as a node in the workflow.</li><li><strong>Node Names:</strong> Each node receives a name that we use when connecting the graph and defining conditional routing.</li></ul><p>Next, let’s connect the nodes using standard and conditional edges.</p><pre># Add edges<br>graph.add_edge(START, &#39;find_sentiment&#39;)<br><br>graph.add_conditional_edges(&#39;find_sentiment&#39;, check_sentiment)<br><br>graph.add_edge(&#39;positive_response&#39;, END)<br>graph.add_edge(&#39;run_diagnosis&#39;, &#39;negative_response&#39;)<br>graph.add_edge(&#39;negative_response&#39;, END)</pre><p><strong>Understanding the code:</strong></p><ul><li><strong>Starting Edge:</strong> START connects to find_sentiment, so every customer review is analyzed first.</li><li><strong>Conditional Edge:</strong> graph.add_conditional_edges() connects find_sentiment to the check_sentiment routing function. Based on the detected sentiment, the workflow chooses either positive_response or run_diagnosis.</li><li><strong>Positive Path:</strong> The positive_response node connects directly to END.</li><li><strong>Negative Path:</strong> The run_diagnosis node connects to negative_response, which then connects to END.</li></ul><p>This creates two different execution paths:</p><ul><li><strong>Positive Review:</strong> START → find_sentiment → positive_response → END</li><li><strong>Negative Review:</strong> START → find_sentiment → run_diagnosis → negative_response → END</li></ul><h4>9. Compile the Workflow</h4><p>Once all the nodes and edges are connected, we can compile the graph.</p><pre># Compile graph<br>workflow = graph.compile()</pre><p><strong>Understanding the code:</strong></p><ul><li><strong>Compilation:</strong> The graph.compile() method prepares the graph for execution and creates a runnable workflow object.</li></ul><h4>10. Execute the Workflow</h4><p>Now, let’s provide a sample negative customer review and execute the workflow.</p><pre>initial_state = {<br>    &#39;review&#39;: &quot;&quot;&quot;I’ve been trying to log in for over an hour now, and the app keeps freezing on the authentication screen. I even tried reinstalling it, but no luck. This kind of bug is unacceptable, especially when it affects basic functionality.&quot;&quot;&quot;<br>}<br><br>final_output = workflow.invoke(initial_state)<br><br>print(final_output)</pre><p><strong>Understanding the code:</strong></p><ul><li><strong>Input:</strong> We pass a negative customer review as the initial state.</li><li><strong>Invocation:</strong> We use workflow.invoke() to execute the compiled LangGraph workflow.</li><li><strong>Conditional Routing:</strong> The LLM first identifies the review sentiment. Since the sample review is negative, the workflow routes through run_diagnosis and then negative_response.</li><li><strong>Result:</strong> The workflow returns the updated state, including the sentiment, diagnosis, and generated customer support response.</li></ul><p>The exact LLM-generated output may vary between executions.</p><h4>11. Complete Code</h4><p>Here is the complete implementation of our Customer Review Chatbot using LangGraph and Gemini 2.5 Flash.</p><pre># If using ChatOpenAI<br># from langchain_openai import ChatOpenAI<br># If using ChatGoogleGenerativeAIs<br>from langchain_google_genai import ChatGoogleGenerativeAI<br>from langgraph.graph import StateGraph, START, END<br>from typing import TypedDict, Literal<br>from dotenv import load_dotenv<br>from pydantic import BaseModel, Field<br><br># Load API keys and other environment variables<br>load_dotenv()<br><br># If using ChatOpenAI<br># Initialize ChatOpenAI<br># model = ChatOpenAI(model=&quot;gpt-4o-mini&quot;)<br><br># If using ChatGoogleGenerativeAI<br># Initialize ChatGoogleGenerativeAI<br>model = ChatGoogleGenerativeAI(model=&quot;gemini-2.5-flash&quot;)<br><br># Define the schema for sentiment classification<br>class SentimentSchema(BaseModel):<br><br>    sentiment: Literal[&quot;positive&quot;, &quot;negative&quot;] = Field(description=&#39;Sentiment of the review&#39;)<br><br># Define the schema for diagnosing negative reviews<br>class DiagnosisSchema(BaseModel):<br>    issue_type: Literal[&quot;UX&quot;, &quot;Performance&quot;, &quot;Bug&quot;, &quot;Support&quot;, &quot;Other&quot;] = Field(description=&#39;The category of issue mentioned in the review&#39;)<br>    tone: Literal[&quot;angry&quot;, &quot;frustrated&quot;, &quot;disappointed&quot;, &quot;calm&quot;] = Field(description=&#39;The emotional tone expressed by the user&#39;)<br>    urgency: Literal[&quot;low&quot;, &quot;medium&quot;, &quot;high&quot;] = Field(description=&#39;How urgent or critical the issue appears to be&#39;)<br><br># Convert the LLM into structured-output models using Pydantic schemas<br>structured_model = model.with_structured_output(SentimentSchema)<br>structured_model2 = model.with_structured_output(DiagnosisSchema)<br><br># Test sentiment classification with a sample review<br>prompt = &#39;What is the sentiment of the following review - The software too good&#39;<br>structured_model.invoke(prompt).sentiment<br><br># Define the shared state of the customer review workflow<br>class ReviewState(TypedDict):<br><br>    review: str<br>    sentiment: Literal[&quot;positive&quot;, &quot;negative&quot;]<br>    diagnosis: dict<br>    response: str<br><br># Node 1: Identify whether the customer review is positive or negative<br>def find_sentiment(state: ReviewState) -&gt; ReviewState:<br><br>    prompt = f&#39;For the following review find out the sentiment \n {state[&quot;review&quot;]}&#39;<br>    sentiment = structured_model.invoke(prompt).sentiment<br><br>    return {&#39;sentiment&#39;: sentiment}<br><br># Conditional function: Decide the next node based on sentiment<br>def check_sentiment(state: ReviewState) -&gt; Literal[&quot;positive_response&quot;, &quot;run_diagnosis&quot;]:<br><br>    if state[&#39;sentiment&#39;] == &#39;positive&#39;:<br>        return &#39;positive_response&#39;<br>    else:<br>        return &#39;run_diagnosis&#39;<br> <br># Node 2: Generate a thank-you response for positive reviews   <br>def positive_response(state: ReviewState) -&gt; ReviewState:<br><br>    prompt = f&quot;&quot;&quot;Write a warm thank-you message in response to this review:<br>    \n\n\&quot;{state[&#39;review&#39;]}\&quot;\n<br>Also, kindly ask the user to leave feedback on our website.&quot;&quot;&quot;<br>    <br>    response = model.invoke(prompt).content<br><br>    return {&#39;response&#39;: response}<br><br># Node 3: Diagnose negative reviews<br>def run_diagnosis(state: ReviewState) -&gt; ReviewState:<br><br>    prompt = f&quot;&quot;&quot;Diagnose this negative review:\n\n{state[&#39;review&#39;]}\n&quot;<br>    &quot;Return issue_type, tone, and urgency.<br>&quot;&quot;&quot;<br>    response = structured_model2.invoke(prompt)<br><br>    return {&#39;diagnosis&#39;: response.model_dump()}<br><br># Node 4: Generate an empathetic response for negative reviews<br>def negative_response(state: ReviewState) -&gt; ReviewState:<br><br>    diagnosis = state[&#39;diagnosis&#39;]<br><br>    prompt = f&quot;&quot;&quot;You are a support assistant.<br>The user had a &#39;{diagnosis[&#39;issue_type&#39;]}&#39; issue, sounded &#39;{diagnosis[&#39;tone&#39;]}&#39;, and marked urgency as &#39;{diagnosis[&#39;urgency&#39;]}&#39;.<br>Write an empathetic, helpful resolution message.<br>&quot;&quot;&quot;<br>    response = model.invoke(prompt).content<br><br>    return {&#39;response&#39;: response}<br><br># Initialize the LangGraph workflow using the ReviewState schema<br>graph = StateGraph(ReviewState)<br><br># Register all workflow nodes<br>graph.add_node(&#39;find_sentiment&#39;, find_sentiment)<br>graph.add_node(&#39;positive_response&#39;, positive_response)<br>graph.add_node(&#39;run_diagnosis&#39;, run_diagnosis)<br>graph.add_node(&#39;negative_response&#39;, negative_response)<br><br># Define the starting point of the workflow<br>graph.add_edge(START, &#39;find_sentiment&#39;)<br><br># Add conditional routing based on the detected sentiment<br>graph.add_conditional_edges(&#39;find_sentiment&#39;, check_sentiment)<br><br># Define the ending paths for both positive and negative reviews<br>graph.add_edge(&#39;positive_response&#39;, END)<br>graph.add_edge(&#39;run_diagnosis&#39;, &#39;negative_response&#39;)<br>graph.add_edge(&#39;negative_response&#39;, END)<br><br># Compile the graph into an executable workflow<br>workflow = graph.compile()<br><br># Define the initial state with a sample negative customer review<br>initial_state={<br>    &#39;review&#39;: &quot;I’ve been trying to log in for over an hour now, and the app keeps freezing on the authentication screen. I even tried reinstalling it, but no luck. This kind of bug is unacceptable, especially when it affects basic functionality.&quot;<br>}<br><br># Execute the workflow with the initial review<br>final_output = workflow.invoke(initial_state)<br><br># Display the final workflow state, including sentiment, diagnosis, and response<br>print(final_output)</pre><h4>Workflow Graph</h4><p>We can visualize the compiled workflow using LangGraph’s graph visualization functionality.</p><pre>from IPython.display import Image<br><br>Image(workflow.get_graph().draw_mermaid_png())</pre><figure><img alt="LangGraph workflow with START connected to find_sentiment. A conditional edge routes positive reviews to positive_response and negative reviews to run_diagnosis, followed by negative_response. Both paths terminate at END." src="https://cdn-images-1.medium.com/max/390/1*w8SrV18zd9IBMqvlsx-o3Q.png" /><figcaption><em>Compiled LangGraph visualization of the customer review chatbot, showing sentiment analysis followed by conditional routing to either a positive response or a negative review diagnosis and response.</em></figcaption></figure><h4>Understanding What We Built</h4><p>In this example, we built an LLM-powered customer support chatbot using LangGraph, Gemini, and Pydantic.</p><p>The workflow follows these steps:</p><ol><li>Receives a customer review as input.</li><li>Uses an LLM to identify whether the review is positive or negative.</li><li>Evaluates the sentiment using the check_sentiment conditional routing function.</li><li>Dynamically selects the appropriate execution path:</li></ol><ul><li><strong>Positive Review:</strong> Generates a friendly thank-you response.</li><li><strong>Negative Review:</strong> Diagnoses the issue type, emotional tone, and urgency before generating an empathetic response.</li></ul><p>5. Returns the final response as part of the workflow state.</p><p>The important concept is that <strong>the workflow does not follow the same path for every customer review</strong>. It makes a decision based on the sentiment and executes only the appropriate nodes.</p><p>This demonstrates how conditional edges can be combined with LLMs and structured outputs to build dynamic customer support applications using LangGraph.</p><h3>Final Thoughts</h3><p>In this tutorial, we explored <strong>conditional workflows in LangGraph</strong> and learned how they allow us to choose different execution paths based on input data or the current state.</p><p>We started with a simple mathematical example and then moved to an LLM-powered customer support application.</p><p>Here’s what we built:</p><ul><li><strong>Quadratic Equation Solver (Without LLM):</strong> We created a workflow that calculates the discriminant and dynamically determines whether the equation has two distinct real roots, one repeated real root, or no real roots.</li><li><strong>Customer Review Chatbot (With LLM):</strong> We built an LLM-powered workflow that analyzes customer reviews and identifies their sentiment.</li><li><strong>Positive Reviews:</strong> The workflow generates friendly, automated thank-you responses.</li><li><strong>Negative Reviews:</strong> The workflow first diagnoses the issue type, emotional tone, and urgency. Based on this diagnosis, it generates empathetic and issue-specific responses.</li></ul><p>These examples demonstrate how conditional edges allow LangGraph workflows to make decisions and handle different scenarios automatically.</p><p>Overall, <strong>conditional workflows make LangGraph applications smarter, more dynamic, and capable of adapting their execution based on different inputs and conditions.</strong></p><p>Whenever the next action depends on a decision, conditional workflows provide a structured way to implement that logic.</p><h3>Key Takeaways</h3><p>In this article, we explored how to build <strong>conditional workflows in LangGraph</strong> and use conditional edges to make dynamic decisions during workflow execution.</p><p>Here are the key concepts to remember:</p><ol><li><strong>Conditional Workflows:</strong> They allow a workflow to choose its next execution step dynamically based on the current state or input data.</li><li><strong>Conditional Edges:</strong> LangGraph uses add_conditional_edges() to connect a node to a routing function that determines which node should execute next.</li><li><strong>Dynamic Routing:</strong> A routing function evaluates a condition and returns the name of the next node, allowing the workflow to follow different execution paths.</li><li><strong>State-Based Decisions:</strong> The workflow can make decisions using information stored in its shared state, such as a calculated value or an LLM-generated sentiment.</li><li><strong>Quadratic Equation Solver (Without LLM):</strong> We used the discriminant to determine whether a quadratic equation has two distinct real roots, one repeated real root, or no real roots.</li><li><strong>Customer Review Chatbot (With LLM):</strong> We used an LLM to classify customer reviews as positive or negative and route them to the appropriate response-generation path.</li><li><strong>Structured Outputs with Pydantic:</strong> We defined SentimentSchema and DiagnosisSchema to structure the LLM&#39;s sentiment classification and negative review diagnosis.</li><li><strong>Flexible AI Applications:</strong> Conditional workflows can handle different inputs and scenarios, making them useful for both simple mathematical problems and complex AI applications.</li></ol><p><strong>The key idea:</strong> Conditional workflows allow LangGraph to make decisions and execute only the appropriate path instead of following the same fixed sequence every time.</p><h3>Conclusion</h3><p>In this part of our LangGraph series, we explored <strong>conditional workflows</strong> and learned how to build dynamic AI workflows using conditional edges and decision-based routing.</p><p>We started with a simple quadratic equation solver, where the discriminant determines which calculation should run. We then moved to an LLM-powered customer review chatbot, where the workflow analyzes sentiment and follows different paths to generate appropriate responses.</p><p>Through these examples, we learned that LangGraph workflows don’t always need to follow a fixed sequence. They can make decisions based on the current state and execute different paths depending on the conditions.</p><p><strong>Conditional workflows are an important building block for developing intelligent and flexible AI applications.</strong> They help us move beyond fixed execution paths and build workflows that can adapt to different inputs and situations.</p><p>As we continue exploring LangGraph, we’ll build on these concepts to understand how more advanced workflows can coordinate multiple steps and make AI applications more capable.</p><h3>What’s Next?</h3><p>In the next part of our <strong>Agentic AI Using LangGraph</strong> series, we’ll explore another important workflow pattern: <strong>Iterative Workflows in LangGraph</strong>.</p><p>So far, we’ve learned how to build sequential workflows, execute tasks in parallel, and make dynamic decisions using conditional workflows. But what happens when an AI-generated output isn’t good enough on the first attempt?</p><blockquote>That’s where iterative workflows come in!</blockquote><p>In <strong>Part 8: Iterative Workflows in LangGraph</strong>, we’ll learn how to build looping workflows that repeatedly generate, evaluate, and improve outputs until they meet a specific quality standard.</p><p>We’ll build a practical example: an <strong>AI-powered Tweet Generator</strong> that:</p><ul><li>Generates a tweet based on a user-provided topic.</li><li>Evaluates the tweet for originality, humor, punchiness, and viral potential.</li><li>Uses evaluator feedback to improve the tweet if it needs further refinement.</li><li>Repeats the evaluation and optimization process until the tweet is approved or the maximum iteration limit is reached.</li></ul><p>We’ll also understand how LangGraph uses conditional edges to create loops and how state tracking helps manage iterations, tweet history, and feedback history.</p><blockquote><strong>Next Part:</strong> Agentic AI using LangGraph — Part 8: <strong>Iterative Workflows in LangGraph</strong></blockquote><p>By the end, you’ll understand how to build <strong>self-improving AI workflows</strong> that can refine their own outputs instead of stopping after the first attempt.</p><blockquote><strong>Series:</strong> Agentic AI using LangGraph — Part 7 of 27</blockquote><h3>Connect with me</h3><p><strong><em>Connect with me on </em></strong><a href="https://www.linkedin.com/in/shubhamnagar234/"><strong><em>LinkedIn</em></strong></a><strong><em>, </em></strong><a href="https://github.com/shubhamnagar234"><strong><em>GitHub</em></strong></a><strong><em>, </em></strong><a href="https://x.com/nagarshubham234"><strong><em>X (Twitter)</em></strong></a><strong><em>, or explore my </em></strong><a href="https://shubhamnagar234.vercel.app/"><strong><em>Portfolio</em></strong></a><strong><em>.</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7d55424d037a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Parallel Workflows in LangGraph: Executing Multiple Tasks Simultaneously — Part 6]]></title>
            <link>https://medium.com/@shubhamnagar234/parallel-workflows-in-langgraph-executing-multiple-tasks-simultaneously-part-6-a269fe673afc?source=rss-10b51a93c3a------2</link>
            <guid isPermaLink="false">https://medium.com/p/a269fe673afc</guid>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[agentic-workflow]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[langgraph]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <dc:creator><![CDATA[Shubham Nagar]]></dc:creator>
            <pubDate>Sat, 14 Nov 2026 10:58:04 GMT</pubDate>
            <atom:updated>2026-11-14T10:58:34.112Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Learn How to Build Parallel Workflows in LangGraph by Executing Multiple Independent Tasks Simultaneously, Managing Shared State, and Combining Results, with Practical Examples With and Without LLMs.</blockquote><p>In the previous part, we explored <strong>Sequential Workflows in LangGraph</strong>, where tasks are executed one after another in a predefined order. We built practical examples such as a BMI calculator, a simple QA chatbot, and a two-stage blog generation workflow using prompt chaining.</p><p>But what happens when multiple tasks are independent and don’t need to wait for one another?</p><p>Running them sequentially can introduce unnecessary waiting time. Instead, we can execute these tasks simultaneously using <strong>Parallel Workflows in LangGraph</strong>.</p><p>A parallel workflow allows multiple nodes to run concurrently from the same starting point. Each node performs an independent task, and their results can be combined before the workflow moves forward.</p><p>In this part, we’ll explore how parallel workflows work in LangGraph, how multiple nodes share and update state, and how their results are brought together.</p><p>We’ll also build two practical examples:</p><ul><li><strong>Batsman Stats Calculator (Without LLM):</strong> Calculate Strike Rate, Balls per Boundary, and Boundary Percentage using independent parallel nodes, then combine the results into a summary.</li><li><strong>Essay Evaluation System (With LLM):</strong> Evaluate an essay simultaneously across language quality, depth of analysis, and clarity of thought, then combine the feedback and calculate an average score.</li></ul><p>By the end of this article, you’ll understand how to build parallel workflows in LangGraph and when to use them to make your AI applications more efficient, modular, and scalable.</p><h3>Overview</h3><ul><li><strong><em>What Is a Parallel Workflow in LangGraph?</em></strong></li><li><strong><em>Why Use Parallel Workflows?</em></strong></li><li><strong><em>How LangGraph Implements Parallel Workflows</em></strong></li><li><strong><em>Real-Life Analogy</em></strong></li><li><strong><em>Example 1: Building a Batsman Stats Calculator Using LangGraph (Without LLM)</em></strong></li><li><strong><em>Example 2: Building an Essay Evaluation System Using LangGraph (With LLM)</em></strong></li><li><strong><em>Key Takeaways</em></strong></li><li><strong><em>Conclusion</em></strong></li><li><strong><em>What’s Next?</em></strong></li></ul><h3>What Is a Parallel Workflow in LangGraph?</h3><p>A <strong>parallel workflow</strong> in LangGraph is a workflow where multiple tasks, represented as nodes, can execute simultaneously from the same starting point.</p><p>It is useful when tasks are independent and do not need to wait for one another. For example, we can analyze data from multiple sources, generate different types of content, or perform multiple LLM calls at the same time.</p><p>Unlike sequential workflows, where nodes execute one after another, parallel workflows allow multiple branches of a graph to execute concurrently. Their results can then be combined or passed to the next step.</p><p>A parallel workflow uses a shared State, allowing multiple nodes to contribute their results to the overall context before the workflow continues.</p><h4><strong>Key characteristics:</strong></h4><ul><li><strong>Concurrent Execution:</strong> Multiple independent nodes can run simultaneously.</li><li><strong>Multiple Branches:</strong> A graph can split into different execution paths and bring them together later.</li><li><strong>Shared State:</strong> Parallel nodes contribute their results to the workflow’s shared state.</li><li><strong>Improved Efficiency:</strong> Independent tasks can execute at the same time, reducing the overall execution time compared with running them one after another.</li></ul><figure><img alt="A LangGraph parallel workflow diagram illustrating multiple independent branches executing concurrently and converging before the workflow continues." src="https://cdn-images-1.medium.com/max/1024/1*BI3s_sLAmIxykPSqr4wdNw.png" /><figcaption><em>Parallel workflow in LangGraph showing multiple branches executing from a common starting point before their results are combined.</em></figcaption></figure><p>In simple terms, a parallel workflow allows us to divide a larger task into smaller independent tasks, execute them simultaneously, and combine their results when they are ready.</p><h3>Why Use Parallel Workflows?</h3><p>Parallel workflows allow multiple independent tasks to execute at the same time instead of waiting for each task to finish one by one. This improves the speed and efficiency of a workflow, especially when multiple operations do not depend on each other.</p><h4>Benefits of Parallel Workflows</h4><ul><li><strong>Faster Execution:</strong> Multiple tasks run simultaneously, reducing the time spent waiting for individual steps to finish sequentially.</li><li><strong>Clean Separation of Concerns:</strong> Each branch handles a specific task, making the workflow easier to understand, manage, and maintain.</li><li><strong>Scalable and Modular:</strong> You can easily add, remove, or modify individual tasks without restructuring the entire workflow.</li></ul><h4>Common Use Cases</h4><ul><li><strong>Running Multiple LLM Tasks at Once:</strong> Perform summarization, translation, and sentiment analysis simultaneously on the same input.</li><li><strong>Performing Parallel Tool Calls:</strong> Call multiple APIs or tools, such as API A and API B, at the same time instead of waiting for one response before requesting another.</li><li><strong>Comparing Outputs Side by Side:</strong> Generate multiple results independently and bring them together to compare their outputs.</li></ul><p>In short, parallel workflows are useful whenever multiple independent tasks can be performed simultaneously. They help build applications that are faster, more modular, and easier to scale.</p><h3>How LangGraph Implements Parallel Workflows?</h3><p>LangGraph supports parallel execution by connecting one node to multiple downstream nodes. These nodes can execute concurrently when they are independent of one another.</p><p>After the parallel branches complete, LangGraph waits for all of them to finish before moving to the next node.</p><p>This allows us to divide a task into multiple independent operations, execute them simultaneously, and combine their results.</p><h4>Here’s the Basic Idea</h4><p>Let’s consider a workflow where we want to summarize and translate some input data at the same time.</p><p>We can create four nodes:</p><ul><li>split: Starts the parallel execution.</li><li>summarize: Generates a summary.</li><li>translate: Translates the input.</li><li>join: Combines the results from both branches.</li></ul><p><strong>Define the graph and nodes:</strong></p><pre>workflow = StateGraph(StateType)<br><br>workflow.add_node(&quot;split&quot;, splitter_fn)<br>workflow.add_node(&quot;summarize&quot;, summarize_fn)<br>workflow.add_node(&quot;translate&quot;, translate_fn)<br>workflow.add_node(&quot;join&quot;, join_fn)</pre><p><strong>Connect the nodes using edges:</strong></p><pre>workflow.add_edge(&quot;split&quot;, &quot;summarize&quot;)<br>workflow.add_edge(&quot;split&quot;, &quot;translate&quot;)<br><br>workflow.add_edge([&quot;summarize&quot;, &quot;translate&quot;], &quot;join&quot;)</pre><p>The execution flow looks like this:</p><ol><li><strong>Split the Work:</strong> The split node initiates the parallel branches.</li><li><strong>Execute in Parallel:</strong> The summarize and translate nodes run independently.</li><li><strong>Wait for Completion:</strong> LangGraph waits until both branches finish.</li><li><strong>Join the Results:</strong> The join node receives the results and combines them.</li></ol><p>In simple terms:</p><blockquote><strong>Split → (Summarize + Translate) → Join</strong></blockquote><p>The key idea is that both branches can execute at the same time rather than waiting for one another to finish.</p><p>Under the hood, LangGraph uses asynchronous execution to handle parallel tasks.</p><h3>Real-Life Analogy</h3><p>Let’s understand parallel workflows with a simple real-life example: <strong>preparing a meal</strong>.</p><p>Imagine you’re preparing a meal with the help of your family:</p><ul><li><strong>You (the Chef):</strong> Read the recipe and decide what needs to be prepared. This represents the input to the workflow.</li><li><strong>Your Friend:</strong> Starts chopping the vegetables.</li><li><strong>You:</strong> Begin boiling water at the same time.</li><li><strong>Your Sibling:</strong> Sets the table.</li></ul><p>All these tasks happen simultaneously. Nobody needs to wait for the other tasks to finish because they are independent.</p><p>Once all the tasks are completed, you can serve the meal.</p><p>This is exactly how a parallel workflow works in LangGraph:</p><ul><li>Each independent task represents a <strong>node</strong>.</li><li>The tasks execute simultaneously through separate <strong>branches</strong>.</li><li>The workflow waits for all branches to complete.</li><li>Once all results are ready, they are combined before moving to the next step.</li></ul><p>Just like preparing a meal, parallel workflows allow us to divide a larger task into smaller independent tasks, execute them simultaneously, and bring everything together at the end.</p><h3>Example 1: Building a Batsman Stats Calculator Using LangGraph (Without LLM)</h3><h4>What We’re Building</h4><p>In cricket, a batsman’s performance can be summarized using several important metrics:</p><ul><li><strong>Strike Rate (SR):</strong> Measures how quickly a batsman scores runs.</li><li><strong>Balls per Boundary (BPB):</strong> Calculates how many balls a batsman faces, on average, before hitting a boundary (four or six).</li><li><strong>Boundary Percentage:</strong> Measures what percentage of the batsman’s total runs came from boundaries.</li><li><strong>Summary:</strong> Combines the calculated metrics into a short, human-readable summary.</li></ul><p>We’ll build a LangGraph workflow that calculates these metrics using separate nodes. The three calculations will execute independently and in parallel. Once all three calculations are complete, their results will be passed to a summary node.</p><p>LangGraph makes it easy to organize these independent operations and manage the shared state between nodes.</p><figure><img alt="A LangGraph workflow where three independent nodes calculate strike rate, balls per boundary, and boundary percentage simultaneously before passing their results to a summary node." src="https://cdn-images-1.medium.com/max/1024/1*dnpHYhqh16jPioPQ2hJXCQ.png" /><figcaption><em>Batsman Stats Calculator using a parallel workflow in LangGraph.</em></figcaption></figure><h4>Understanding the Workflow Diagram</h4><p>Let’s understand how the workflow executes by breaking down its components.</p><p><strong>START</strong></p><ul><li>This is the entry point of the workflow.</li><li>From here, execution branches into three independent tasks.</li></ul><p><strong>Parallel Tasks (Executed Simultaneously)</strong></p><p>Three calculation nodes execute independently:</p><ol><li><strong>calculate_strike_rate</strong></li><li>Calculates the batsman’s strike rate using:</li><li>Strike Rate = (Runs / Balls) × 100</li><li><strong>calculate_balls_per_boundary</strong></li><li>Calculates the average number of balls faced for each boundary:</li><li>BPB = Balls / (Fours + Sixes)</li><li><strong>calculate_boundary_percent</strong></li><li>Calculates the percentage of total runs scored through boundaries:</li><li>Boundary Percentage = ((Fours × 4 + Sixes × 6) / Runs) × 100</li></ol><p>These calculations do not depend on one another. Each node receives the same initial input and calculates its own metric independently.</p><p><strong>Summary Node</strong></p><ul><li>Once all three calculation nodes finish, their results are combined in the shared state.</li><li>The summary node uses these results to create a human-readable summary of the batsman&#39;s performance.</li></ul><p><strong>END</strong></p><ul><li>The workflow finishes after the summary is generated.</li><li>The final state, containing the input data and calculated metrics, is returned to the caller.</li></ul><h4>Why Is This Workflow Parallel?</h4><p>This workflow is parallel because all three metric calculations begin from START and execute independently.</p><p>None of the calculation nodes needs the result of another calculation node. LangGraph allows us to define multiple outgoing edges from START and connect all three branches to a common summary node.</p><p>The summary node runs after all three parallel branches have completed.</p><h4>1. Import LangGraph and Define the State</h4><p>First, import the required components from LangGraph and Python’s typing module.</p><pre>from langgraph.graph import StateGraph, START, END<br>from typing import TypedDict</pre><p>Next, define the state using TypedDict.</p><pre># Create a state<br>class BatsmanState(TypedDict):<br><br>    runs: int<br>    balls: int<br>    fours: int<br>    sixes: int<br>    sr: float<br>    bpb: float<br>    boundary_percent: float<br>    summary: str</pre><p>Here, BatsmanState defines the shared data structure that will be passed between nodes.</p><p>It contains:</p><ul><li><strong>Input fields:</strong> runs, balls, fours, and sixes.</li><li><strong>Calculated fields:</strong> sr, bpb, and boundary_percent.</li><li><strong>Final output:</strong> summary.</li></ul><p>Think of the state as a shared dictionary where each node reads the input values and contributes its calculated result.</p><h4>2. Initialize the Graph</h4><p>Now, create a graph using the BatsmanState schema.</p><pre># Create a graph<br>graph = StateGraph(BatsmanState)</pre><p>This initializes the LangGraph workflow and defines the structure of the state that will be shared between its nodes.</p><h4>3. Define Node Functions</h4><p>Next, we’ll define four node functions.</p><p>The first three nodes perform independent calculations, while the fourth combines their results into a summary.</p><p><strong>Strike Rate Node</strong></p><p>The calculate_strike_rate node calculates the batsman&#39;s strike rate.</p><pre>def calculate_strike_rate(state: BatsmanState) -&gt; BatsmanState:<br><br>    sr = (state[&#39;runs&#39;] / state[&#39;balls&#39;]) * 100<br>    return {&#39;sr&#39;: sr}</pre><p>The formula is:</p><p><strong>Strike Rate = (Runs / Balls) × 100</strong></p><p>For example, if a batsman scores 100 runs in 50 balls, the strike rate is 200.</p><p><strong>Balls per Boundary Node</strong></p><p>The calculate_balls_per_boundary node calculates the average number of balls faced for each boundary.</p><pre>def calculate_balls_per_boundary(state: BatsmanState) -&gt; BatsmanState:<br><br>    bpb = state[&#39;balls&#39;] / (state[&#39;fours&#39;] + state[&#39;sixes&#39;])<br>    return {&#39;bpb&#39;: bpb}</pre><p>It divides the total number of balls faced by the total number of boundaries (fours and sixes).</p><p>For example, if a batsman faces 50 balls and hits 10 boundaries, the result is 5 balls per boundary.</p><p><strong>Boundary Percentage Node</strong></p><p>The calculate_boundary_percent node determines what percentage of the batsman&#39;s total runs came from boundaries.</p><pre>def calculate_boundary_percent(state: BatsmanState) -&gt; BatsmanState:<br><br>    boundary_percent = (<br>        ((state[&#39;fours&#39;] * 4) + (state[&#39;sixes&#39;] * 6))<br>        / state[&#39;runs&#39;]<br>    ) * 100<br>    return {&#39;boundary_percent&#39;: boundary_percent}</pre><p>The calculation first determines the total runs scored through fours and sixes, then divides that value by the total runs and multiplies by 100.</p><p><strong>Summary Node</strong></p><p>Finally, the summary node combines the three calculated metrics into a human-readable string.</p><pre>def summary(state: BatsmanState) -&gt; BatsmanState:<br>  <br>    summary = f&quot;&quot;&quot;<br>        Strike Rate - {state[&#39;sr&#39;]}<br>        Balls per boundary - {state[&#39;bpb&#39;]}<br>        Boundary percent - {state[&#39;boundary_percent&#39;]}<br>    &quot;&quot;&quot;<br>    return {&#39;summary&#39;: summary}</pre><p>Unlike the first three nodes, this node depends on the results of all three calculations.</p><p>It receives the updated state and uses the calculated values to generate the final summary.</p><h4>4. Add Nodes to the Graph</h4><p>After defining the node functions, register them with the graph using add_node().</p><pre># Add nodes<br>graph.add_node(&#39;calculate_strike_rate&#39;, calculate_strike_rate)<br>graph.add_node(&#39;calculate_balls_per_boundary&#39;, calculate_balls_per_boundary)<br>graph.add_node(&#39;calculate_boundary_percent&#39;, calculate_boundary_percent)<br>graph.add_node(&#39;summary&#39;, summary)</pre><p>Each function is now registered as a node in the LangGraph workflow.</p><h4>5. Connect the Nodes (Add Edges)</h4><p>Now comes the most important part: defining the parallel execution flow.</p><p>We connect START to all three calculation nodes. This allows them to execute independently.</p><pre># Add parallel edges from START<br>graph.add_edge(START, &#39;calculate_strike_rate&#39;)<br>graph.add_edge(START, &#39;calculate_balls_per_boundary&#39;)<br>graph.add_edge(START, &#39;calculate_boundary_percent&#39;)</pre><p>Next, connect all three calculation nodes to the common summary node.</p><pre># Connect parallel branches to summary<br>graph.add_edge(&#39;calculate_strike_rate&#39;, &#39;summary&#39;)<br>graph.add_edge(&#39;calculate_balls_per_boundary&#39;, &#39;summary&#39;)<br>graph.add_edge(&#39;calculate_boundary_percent&#39;, &#39;summary&#39;)<br><br># Connect summary to END<br>graph.add_edge(&#39;summary&#39;, END)</pre><p>The complete execution flow is:</p><blockquote><strong>START → (calculate_strike_rate | calculate_balls_per_boundary | calculate_boundary_percent) → summary → END</strong></blockquote><p>Here, the three calculation nodes run in parallel. LangGraph waits for all three branches to finish before executing the summary node.</p><h4>6. Complete Code</h4><p>Now let’s combine everything into one complete implementation.</p><pre>from langgraph.graph import StateGraph, START, END<br>from typing import TypedDict<br><br># Define State<br>class BatsmanState(TypedDict):<br>    runs: int<br>    balls: int<br>    fours: int<br>    sixes: int<br>    sr: float<br>    bpb: float<br>    boundary_percent: float<br>    summary: str<br><br># Node 1: Calculate Strike Rate<br>def calculate_strike_rate(state: BatsmanState) -&gt; BatsmanState:<br>    sr = (state[&#39;runs&#39;] / state[&#39;balls&#39;]) * 100<br>    return {&#39;sr&#39;: sr}<br><br># Node 2: Calculate Balls Per Boundary<br>def calculate_balls_per_boundary(state: BatsmanState) -&gt; BatsmanState:<br>    bpb = state[&#39;balls&#39;] / (state[&#39;fours&#39;] + state[&#39;sixes&#39;])<br>    return {&#39;bpb&#39;: bpb}<br><br># Node 3: Calculate Boundary Percentage<br>def calculate_boundary_percent(state: BatsmanState) -&gt; BatsmanState:<br>    boundary_percent = (<br>        ((state[&#39;fours&#39;] * 4) + (state[&#39;sixes&#39;] * 6))<br>        / state[&#39;runs&#39;]<br>    ) * 100<br>    return {&#39;boundary_percent&#39;: boundary_percent}<br><br># Node 4: Generate Summary<br>def summary(state: BatsmanState) -&gt; BatsmanState:<br>    summary = f&quot;&quot;&quot;<br>        Strike Rate - {state[&#39;sr&#39;]}<br>        Balls per boundary - {state[&#39;bpb&#39;]}<br>        Boundary percent - {state[&#39;boundary_percent&#39;]}<br>    &quot;&quot;&quot;<br>    return {&#39;summary&#39;: summary}<br><br># Create Graph<br>graph = StateGraph(BatsmanState)<br><br># Add Nodes<br>graph.add_node(&#39;calculate_strike_rate&#39;, calculate_strike_rate)<br>graph.add_node(&#39;calculate_balls_per_boundary&#39;, calculate_balls_per_boundary)<br>graph.add_node(&#39;calculate_boundary_percent&#39;, calculate_boundary_percent)<br>graph.add_node(&#39;summary&#39;, summary)<br><br># Add Parallel Edges<br>graph.add_edge(START, &#39;calculate_strike_rate&#39;)<br>graph.add_edge(START, &#39;calculate_balls_per_boundary&#39;)<br>graph.add_edge(START, &#39;calculate_boundary_percent&#39;)<br><br># Join Parallel Branches<br>graph.add_edge(&#39;calculate_strike_rate&#39;, &#39;summary&#39;)<br>graph.add_edge(&#39;calculate_balls_per_boundary&#39;, &#39;summary&#39;)<br>graph.add_edge(&#39;calculate_boundary_percent&#39;, &#39;summary&#39;)<br><br># Connect to END<br>graph.add_edge(&#39;summary&#39;, END)<br><br># Compile Graph<br>workflow = graph.compile()<br><br># Execute Workflow<br>initial_state = {<br>    &#39;runs&#39;: 100,<br>    &#39;balls&#39;: 50,<br>    &#39;fours&#39;: 6,<br>    &#39;sixes&#39;: 4<br>}<br><br>final_state = workflow.invoke(initial_state)<br><br>print(final_state)</pre><h4>7. Compile and Run the Workflow</h4><p>Once the graph is defined, compile it to create an executable workflow.</p><pre>workflow = graph.compile()</pre><p>Next, provide the initial input containing the batsman’s performance data.</p><pre>initial_state = {<br>    &#39;runs&#39;: 100,<br>    &#39;balls&#39;: 50,<br>    &#39;fours&#39;: 6,<br>    &#39;sixes&#39;: 4<br>}<br><br>final_state = workflow.invoke(initial_state)<br><br>print(final_state)</pre><p>When we invoke the workflow, LangGraph executes the three independent calculation nodes in parallel. After all three finish, the summary node receives their results and generates the final summary.</p><h4>Output</h4><p>For the given input:</p><ul><li>Runs: 100</li><li>Balls: 50</li><li>Fours: 6</li><li>Sixes: 4</li></ul><p>The calculated metrics are:</p><ul><li>Strike Rate: 200.0</li><li>Balls per Boundary: 5.0</li><li>Boundary Percentage: 48.0</li></ul><p>The final output will look like this:</p><pre>{<br>    &#39;runs&#39;: 100,<br>    &#39;balls&#39;: 50,<br>    &#39;fours&#39;: 6,<br>    &#39;sixes&#39;: 4,<br>    &#39;sr&#39;: 200.0,<br>    &#39;bpb&#39;: 5.0,<br>    &#39;boundary_percent&#39;: 48.0,<br>    &#39;summary&#39;: &#39;&#39;&#39;<br>        Strike Rate - 200.0<br>        Balls per boundary - 5.0<br>        Boundary percent - 48.0<br>    &#39;&#39;&#39;<br>}</pre><p>Notice that the final state contains both the original input values and the results returned by the four nodes.</p><h4>Workflow Graph</h4><p>We can also visualize the compiled LangGraph workflow using get_graph().draw_mermaid_png().</p><pre>from IPython.display import Image, display<br><br>display(Image(workflow.get_graph().draw_mermaid_png()))</pre><figure><img alt="LangGraph execution diagram showing START branching into strike rate, balls per boundary, and boundary percentage calculations, followed by a shared summary node and END." src="https://cdn-images-1.medium.com/max/766/1*TLm9gvfAAapiJMUpCrCgCA.png" /><figcaption><em>Graph visualization of the Batsman Stats Calculator, showing three parallel calculation branches converging into the summary node.</em></figcaption></figure><h4>Understanding What We Built</h4><p>Let’s recap the execution:</p><ol><li>The workflow receives the batsman’s statistics as its initial state.</li><li>LangGraph starts three independent calculation nodes simultaneously.</li><li>Each node calculates one metric and returns its result.</li><li>LangGraph waits for all three branches to complete.</li><li>The summary node receives the combined results and generates a human-readable summary.</li><li>The workflow reaches END and returns the final state.</li></ol><p>This example demonstrates how we can use parallel workflows in LangGraph to perform multiple independent calculations without using an LLM.</p><h3>Example 2: Building an Essay Evaluation System Using LangGraph (With LLM)</h3><h4>What Are We Building?</h4><p>In this example, we’ll build a smart essay evaluation system using:</p><ul><li><strong>Large Language Model (LLM):</strong> Evaluates the essay and generates feedback.</li><li><strong>LangGraph:</strong> Organizes the workflow and manages parallel execution.</li><li><strong>Scoring System:</strong> Evaluates the essay across multiple dimensions, including language quality, depth of analysis, and clarity of thought.</li><li><strong>Parallel Nodes:</strong> Execute the three evaluations simultaneously.</li></ul><p>The application will:</p><ol><li>Take an essay as input.</li><li>Run three evaluations in parallel:</li></ol><ul><li>Language quality</li><li>Depth of analysis</li><li>Clarity of thought</li></ul><p>3. Combine all three feedback results.</p><p>4. Calculate an average score.</p><p>5. Generate an overall evaluation with summarized feedback.</p><p>Instead of asking the LLM to evaluate everything in one call, we’ll divide the evaluation into three independent tasks and execute them simultaneously.</p><figure><img alt="A LangGraph workflow where an essay is evaluated simultaneously across language quality, depth of analysis, and clarity of thought before the results are combined into a final evaluation." src="https://cdn-images-1.medium.com/max/1024/1*RgZ-FLlLQonGjado6BsOdg.png" /><figcaption><em>Essay Evaluation System using parallel workflows in LangGraph.</em></figcaption></figure><h4>Understanding the Parallel Workflow: A Visual Breakdown</h4><p>Let’s understand how each part of the workflow operates.</p><p><strong>START</strong></p><p>The workflow begins here. This is the entry point where we provide the essay as input.</p><p><strong>What happens here?</strong></p><ul><li>LangGraph receives the essay as a string.</li><li>The shared state contains the essay text and fields for storing evaluation feedback and scores.</li><li>The workflow branches into three independent evaluation tasks.</li></ul><p><strong>Parallel Branches (Executed Simultaneously)</strong></p><p>From the starting point, three evaluation nodes execute in parallel.</p><p><strong>1. </strong><strong>evaluate_language</strong></p><p>This node evaluates the linguistic quality of the essay.</p><p>It checks:</p><ul><li>Grammar and sentence structure.</li><li>Vocabulary richness.</li><li>Fluency and coherence.</li></ul><p><strong>Output:</strong></p><ul><li>Detailed feedback about the essay’s language quality.</li><li>A numerical score out of 10.</li></ul><p><strong>2. </strong><strong>evaluate_analysis</strong></p><p>This node measures the depth and thoughtfulness of the essay.</p><p>It checks:</p><ul><li>Whether the arguments are well-developed.</li><li>Whether supporting evidence is provided.</li><li>Whether the essay has a strong thesis or conclusion.</li></ul><p><strong>Output:</strong></p><ul><li>Feedback on the depth and intellectual quality of the analysis.</li><li>A numerical score out of 10.</li></ul><p><strong>3. </strong><strong>evaluate_thought</strong></p><p>This node evaluates the clarity of the writer’s ideas.</p><p>It checks:</p><ul><li>Logical flow of paragraphs.</li><li>Clarity in structure and expression.</li><li>How easily readers can understand the ideas.</li></ul><p><strong>Output:</strong></p><ul><li>Feedback about the clarity of thought.</li><li>A numerical score out of 10.</li></ul><p>All three branches execute independently. This allows us to evaluate different aspects of the same essay simultaneously.</p><p><strong>final_evaluation</strong></p><p>Once all three evaluation branches finish, their results converge into the final_evaluation node.</p><p><strong>What happens here?</strong></p><ul><li>The three feedback strings are combined into a prompt.</li><li>The LLM generates an overall summary of the feedback.</li><li>The three individual scores are averaged to calculate the overall score.</li><li>The results are returned as the final state.</li></ul><p><strong>Output:</strong></p><ul><li>overall_feedback: Combined, human-readable evaluation.</li><li>avg_score: Average score across all three dimensions.</li><li>individual_scores: List containing the three individual scores.</li><li>Individual feedback for each evaluation category.</li></ul><p><strong>END</strong></p><p>The workflow finishes after the final evaluation is complete.</p><p>The results can then be displayed to the user, logged, or sent to another system, such as an educational platform or evaluation dashboard.</p><h4>1. Import and Setup</h4><p>First, import the required libraries and components.</p><pre># If using ChatOpenAI<br># from langchain_openai import ChatOpenAI<br><br># If using ChatGoogleGenerativeAI<br>from langchain_google_genai import ChatGoogleGenerativeAI<br><br>from langgraph.graph import StateGraph, START, END<br>from dotenv import load_dotenv<br><br>from typing import TypedDict, Annotated<br>from pydantic import BaseModel, Field<br>import operator</pre><p>Let’s understand the important imports:</p><ul><li><strong>StateGraph, </strong><strong>START, </strong><strong>END:</strong> Core LangGraph components used to construct the workflow.</li><li><strong>ChatGoogleGenerativeAI:</strong> LangChain integration used to interact with Google&#39;s Gemini models.</li><li><strong>load_dotenv:</strong> Loads environment variables from the .env file.</li><li><strong>TypedDict:</strong> Defines the structure of the shared state.</li><li><strong>Annotated:</strong> Allows us to attach a reducer to a state field.</li><li><strong>BaseModel and </strong><strong>Field:</strong> Define the structured output schema returned by the LLM.</li><li><strong>operator:</strong> Provides the add operation used to merge score lists from parallel branches.</li></ul><h4>2. Configure Environment Variables</h4><p>Create a .env file in your project directory and add your API keys.</p><pre>OPENAI_API_KEY=&quot;YOUR_OPENAI_API_KEY&quot;<br>GEMINI_API_KEY=&quot;YOUR_GEMINI_API_KEY&quot;</pre><p>Load the environment variables using load_dotenv().</p><pre>load_dotenv()</pre><p>This makes the configured API keys available to the corresponding LangChain model integration.</p><h4>3. Initialize the LLM</h4><p>Next, initialize the LLM that will evaluate the essay and generate the overall feedback.</p><p>You can use either ChatOpenAI or ChatGoogleGenerativeAI.</p><pre># If using ChatOpenAI<br># model = ChatOpenAI(model=&quot;gpt-4o-mini&quot;)<br><br># If using ChatGoogleGenerativeAI<br>model = ChatGoogleGenerativeAI(model=&quot;gemini-2.5-flash&quot;)</pre><p>For this example, we’ll use Google’s Gemini model.</p><p>LangChain provides a consistent invoke() interface for interacting with these model integrations.</p><h4>4. Define EvaluationSchema</h4><p>We want the LLM to return evaluation results in a structured format rather than unstructured text.</p><p>For this, we’ll define an EvaluationSchema using Pydantic.</p><pre>class EvaluationSchema(BaseModel):<br><br>    feedback: str = Field(<br>        description=&#39;Detailed feedback for the essay&#39;<br>    )<br><br>    score: int = Field(<br>        description=&#39;Score out of 10&#39;,<br>        ge=0,<br>        le=10<br>    )</pre><p>This schema defines two fields:</p><ul><li><strong>feedback:</strong> A detailed explanation of the essay&#39;s performance.</li><li><strong>score:</strong> A numerical score between 0 and 10.</li></ul><p>The ge=0 and le=10 constraints specify the minimum and maximum allowed score.</p><p>Now, configure the model to return responses according to this schema.</p><pre>structured_model = model.with_structured_output(EvaluationSchema)</pre><p>We’ll use structured_model for the three individual evaluation tasks so that each evaluation returns a structured feedback-and-score result.</p><h4>5. Define the Input Essay</h4><p>Next, provide the essay that we want to evaluate.</p><p>The essay is passed to the workflow as a string.</p><pre>essay = &quot;&quot;&quot;<br>[LONG ESSAY CONTENT HERE...]<br>&quot;&quot;&quot;</pre><p>You can replace the placeholder with any essay you want to evaluate.</p><h4>6. Define the State (EssayEvalState)</h4><p>LangGraph uses a shared state to pass information between nodes.</p><p>We’ll define the state using TypedDict.</p><pre>class EssayEvalState(TypedDict):<br><br>    essay: str<br>    language_feedback: str<br>    analysis_feedback: str<br>    clarity_feedback: str<br>    overall_feedback: str<br>    individual_scores: Annotated[list[int], operator.add]<br>    avg_score: float</pre><p>Let’s understand the fields:</p><ul><li><strong>essay:</strong> The original essay provided as input.</li><li><strong>language_feedback:</strong> Feedback generated by the language evaluation node.</li><li><strong>analysis_feedback:</strong> Feedback generated by the analysis evaluation node.</li><li><strong>clarity_feedback:</strong> Feedback generated by the clarity evaluation node.</li><li><strong>overall_feedback:</strong> Combined feedback generated by the final evaluation node.</li><li><strong>individual_scores:</strong> Stores the scores returned by the three parallel evaluation nodes.</li><li><strong>avg_score:</strong> Stores the average of the three individual scores.</li></ul><p><strong>Why do we use </strong><strong>Annotated[list[int], operator.add]?</strong></p><p>This is an important part of our parallel workflow.</p><p>All three evaluation nodes return a score list through the same individual_scores state field.</p><p>When multiple parallel nodes update the same state field, LangGraph needs a way to combine those updates.</p><p>By using operator.add as the reducer, LangGraph knows to concatenate the lists returned by the parallel branches.</p><p>For example:</p><pre>[8] + [7] + [9] = [8, 7, 9]</pre><p>Without this reducer, LangGraph would not know how to merge multiple updates to the same state field.</p><h4>7. Build the Graph</h4><p>Now, initialize the graph using the EssayEvalState schema.</p><pre>graph = StateGraph(EssayEvalState)</pre><p>This constructs the parallel workflow graph using the state structure we defined earlier.</p><h4>8. Define Workflow Nodes (Functions)</h4><p>Now we’ll define four node functions:</p><ol><li>evaluate_language</li><li>evaluate_analysis</li><li>evaluate_thought</li><li>final_evaluation</li></ol><p>The first three nodes evaluate the essay independently, while the final node combines their feedback and calculates the average score.</p><p><strong>Node 1: </strong><strong>evaluate_language</strong></p><p>This node evaluates the linguistic quality of the essay.</p><pre>def evaluate_language(state: EssayEvalState) -&gt; EssayEvalState:<br><br>    prompt = f&quot;&quot;&quot;<br>    Evaluate the language quality of the following essay.<br>    Provide detailed feedback and assign a score out of 10.<br>    {state[&quot;essay&quot;]}<br>    &quot;&quot;&quot;<br>    <br>    output = structured_model.invoke(prompt)<br>    <br>    return {<br>        &#39;language_feedback&#39;: output.feedback,<br>        &#39;individual_scores&#39;: [output.score]<br>    }</pre><p>The node performs the following operations:</p><ol><li>Extracts the essay from the shared state.</li><li>Creates a prompt asking the LLM to evaluate its language quality.</li><li>Invokes the structured LLM.</li><li>Returns the feedback and score.</li></ol><p><strong>Node 2: </strong><strong>evaluate_analysis</strong></p><p>This node evaluates the depth and quality of the essay’s analysis.</p><pre>def evaluate_analysis(state: EssayEvalState) -&gt; EssayEvalState:<br><br>    prompt = f&quot;&quot;&quot;<br>    Evaluate the depth of analysis of the following essay.<br>    Provide detailed feedback and assign a score out of 10.<br>    {state[&quot;essay&quot;]}<br>    &quot;&quot;&quot;<br>    <br>    output = structured_model.invoke(prompt)<br>    <br>    return {<br>        &#39;analysis_feedback&#39;: output.feedback,<br>        &#39;individual_scores&#39;: [output.score]<br>    }</pre><p>It focuses on how deeply the essay explores its subject, how well the arguments are developed, and whether supporting evidence is provided.</p><p><strong>Node 3: </strong><strong>evaluate_thought</strong></p><p>This node evaluates the clarity of the writer’s ideas.</p><pre>def evaluate_thought(state: EssayEvalState) -&gt; EssayEvalState:<br><br>    prompt = f&quot;&quot;&quot;<br>    Evaluate the clarity of thought of the following essay.<br>    Provide detailed feedback and assign a score out of 10.<br>    {state[&quot;essay&quot;]}<br>    &quot;&quot;&quot;<br>    <br>    output = structured_model.invoke(prompt)<br>    <br>    return {<br>        &#39;clarity_feedback&#39;: output.feedback,<br>        &#39;individual_scores&#39;: [output.score]<br>    }</pre><p>It focuses on the logical flow, structure, and clarity of the essay.</p><p><strong>Node 4: </strong><strong>final_evaluation</strong></p><p>After all three evaluation nodes finish, their results are passed to this final node.</p><p>Its responsibility is to combine the individual feedback and calculate the average score.</p><pre>def final_evaluation(state: EssayEvalState) -&gt; EssayEvalState:<br>    <br>    # Generate overall feedback<br>    prompt = f&quot;&quot;&quot;<br>    Based on the following feedback, create a summarized<br>    evaluation of the essay.<br>    Language feedback:<br>    {state[&quot;language_feedback&quot;]}<br>    Depth of analysis feedback:<br>    {state[&quot;analysis_feedback&quot;]}<br>    Clarity of thought feedback:<br>    {state[&quot;clarity_feedback&quot;]}<br>    &quot;&quot;&quot;<br><br>    overall_feedback = model.invoke(prompt).content<br><br>    # Calculate average score<br>    avg_score = (<br>        sum(state[&#39;individual_scores&#39;])<br>        / len(state[&#39;individual_scores&#39;])<br>    )<br><br>    return {<br>        &#39;overall_feedback&#39;: overall_feedback,<br>        &#39;avg_score&#39;: avg_score<br>    }</pre><p>This node performs two important operations:</p><ul><li><strong>Overall Feedback:</strong> Uses the LLM to combine the three individual feedback results into one summarized evaluation.</li><li><strong>Average Score:</strong> Calculates the average of the three individual scores.</li></ul><p>For example, if the three evaluation scores are 8, 7, and 9, the average score will be 8.</p><h4>9. Build the LangGraph Workflow</h4><p>Now that all four nodes are defined, add them to the graph.</p><pre># Add nodes<br>graph.add_node(&#39;evaluate_language&#39;, evaluate_language)<br>graph.add_node(&#39;evaluate_analysis&#39;, evaluate_analysis)<br>graph.add_node(&#39;evaluate_thought&#39;, evaluate_thought)<br>graph.add_node(&#39;final_evaluation&#39;, final_evaluation)</pre><p>Next, define the execution flow using edges.</p><pre># Add parallel edges from START<br>graph.add_edge(START, &#39;evaluate_language&#39;)<br>graph.add_edge(START, &#39;evaluate_analysis&#39;)<br>graph.add_edge(START, &#39;evaluate_thought&#39;)<br><br># Connect parallel branches to final_evaluation<br>graph.add_edge(&#39;evaluate_language&#39;, &#39;final_evaluation&#39;)<br>graph.add_edge(&#39;evaluate_analysis&#39;, &#39;final_evaluation&#39;)<br>graph.add_edge(&#39;evaluate_thought&#39;, &#39;final_evaluation&#39;)<br><br># Connect final_evaluation to END<br>graph.add_edge(&#39;final_evaluation&#39;, END)</pre><p>This creates the following execution flow:</p><blockquote><strong>START → (evaluate_language | evaluate_analysis | evaluate_thought) → final_evaluation → END</strong></blockquote><p>All three evaluation nodes execute in parallel. Once all three branches finish, LangGraph combines their state updates and executes the final_evaluation node.</p><h4>10. Complete Code</h4><p>Here is the complete implementation combining the imports, LLM setup, evaluation schema, shared state, node functions, graph construction, and execution.</p><pre># If using ChatOpenAI<br># from langchain_openai import ChatOpenAI<br><br># If using ChatGoogleGenerativeAI<br>from langchain_google_genai import ChatGoogleGenerativeAI<br>from langgraph.graph import StateGraph, START, END<br>from dotenv import load_dotenv<br>from typing import TypedDict, Annotated<br>from pydantic import BaseModel, Field<br>import operator<br><br><br># Load environment variables<br>load_dotenv()<br><br><br># If using ChatOpenAI<br># model = ChatOpenAI(model=&quot;gpt-4o-mini&quot;)<br><br># If using ChatGoogleGenerativeAI<br>model = ChatGoogleGenerativeAI(model=&quot;gemini-2.5-flash&quot;)<br><br><br># Define Evaluation Schema<br>class EvaluationSchema(BaseModel):<br><br>    feedback: str = Field(<br>        description=&#39;Detailed feedback for the essay&#39;<br>    )<br><br>    score: int = Field(<br>        description=&#39;Score out of 10&#39;,<br>        ge=0,<br>        le=10<br>    )<br><br><br># Configure structured output<br>structured_model = model.with_structured_output(EvaluationSchema)<br><br><br># Define Essay State<br>class EssayEvalState(TypedDict):<br><br>    essay: str<br><br>    language_feedback: str<br>    analysis_feedback: str<br>    clarity_feedback: str<br><br>    overall_feedback: str<br><br>    individual_scores: Annotated[list[int], operator.add]<br><br>    avg_score: float<br><br><br># Node 1: Evaluate Language<br>def evaluate_language(state: EssayEvalState) -&gt; EssayEvalState:<br><br>    prompt = f&quot;&quot;&quot;<br>    Evaluate the language quality of the following essay.<br>    Provide detailed feedback and assign a score out of 10.<br><br>    {state[&quot;essay&quot;]}<br>    &quot;&quot;&quot;<br><br>    output = structured_model.invoke(prompt)<br><br>    return {<br>        &#39;language_feedback&#39;: output.feedback,<br>        &#39;individual_scores&#39;: [output.score]<br>    }<br><br><br># Node 2: Evaluate Analysis<br>def evaluate_analysis(state: EssayEvalState) -&gt; EssayEvalState:<br><br>    prompt = f&quot;&quot;&quot;<br>    Evaluate the depth of analysis of the following essay.<br>    Provide detailed feedback and assign a score out of 10.<br><br>    {state[&quot;essay&quot;]}<br>    &quot;&quot;&quot;<br><br>    output = structured_model.invoke(prompt)<br><br>    return {<br>        &#39;analysis_feedback&#39;: output.feedback,<br>        &#39;individual_scores&#39;: [output.score]<br>    }<br><br><br># Node 3: Evaluate Clarity of Thought<br>def evaluate_thought(state: EssayEvalState) -&gt; EssayEvalState:<br><br>    prompt = f&quot;&quot;&quot;<br>    Evaluate the clarity of thought of the following essay.<br>    Provide detailed feedback and assign a score out of 10.<br><br>    {state[&quot;essay&quot;]}<br>    &quot;&quot;&quot;<br><br>    output = structured_model.invoke(prompt)<br><br>    return {<br>        &#39;clarity_feedback&#39;: output.feedback,<br>        &#39;individual_scores&#39;: [output.score]<br>    }<br><br><br># Node 4: Generate Final Evaluation<br>def final_evaluation(state: EssayEvalState) -&gt; EssayEvalState:<br><br>    # Generate overall feedback<br>    prompt = f&quot;&quot;&quot;<br>    Based on the following feedback, create a summarized<br>    evaluation of the essay.<br><br>    Language feedback:<br>    {state[&quot;language_feedback&quot;]}<br><br>    Depth of analysis feedback:<br>    {state[&quot;analysis_feedback&quot;]}<br><br>    Clarity of thought feedback:<br>    {state[&quot;clarity_feedback&quot;]}<br>    &quot;&quot;&quot;<br><br>    overall_feedback = model.invoke(prompt).content<br><br>    # Calculate average score<br>    avg_score = (<br>        sum(state[&#39;individual_scores&#39;])<br>        / len(state[&#39;individual_scores&#39;])<br>    )<br><br>    return {<br>        &#39;overall_feedback&#39;: overall_feedback,<br>        &#39;avg_score&#39;: avg_score<br>    }<br><br><br># Create Graph<br>graph = StateGraph(EssayEvalState)<br><br><br># Add Nodes<br>graph.add_node(&#39;evaluate_language&#39;, evaluate_language)<br>graph.add_node(&#39;evaluate_analysis&#39;, evaluate_analysis)<br>graph.add_node(&#39;evaluate_thought&#39;, evaluate_thought)<br>graph.add_node(&#39;final_evaluation&#39;, final_evaluation)<br><br><br># Add Parallel Edges<br>graph.add_edge(START, &#39;evaluate_language&#39;)<br>graph.add_edge(START, &#39;evaluate_analysis&#39;)<br>graph.add_edge(START, &#39;evaluate_thought&#39;)<br><br><br># Join Parallel Branches<br>graph.add_edge(&#39;evaluate_language&#39;, &#39;final_evaluation&#39;)<br>graph.add_edge(&#39;evaluate_analysis&#39;, &#39;final_evaluation&#39;)<br>graph.add_edge(&#39;evaluate_thought&#39;, &#39;final_evaluation&#39;)<br><br><br># Connect to END<br>graph.add_edge(&#39;final_evaluation&#39;, END)<br><br><br># Compile Graph<br>workflow = graph.compile()<br><br><br># Input Essay<br>essay = &quot;&quot;&quot;<br>Artificial Intelligence is transforming various industries in India.<br>It is being used in healthcare, education, agriculture, and finance.<br>AI-powered systems can automate repetitive tasks, improve decision-making,<br>and help people access information more efficiently.<br><br>However, the adoption of AI also brings challenges, including data privacy,<br>job displacement, and the need for responsible AI development.<br>India must invest in education, research, and infrastructure to ensure<br>that AI benefits society.<br>&quot;&quot;&quot;<br><br><br># Execute Workflow<br>initial_state = {<br>    &#39;essay&#39;: essay<br>}<br><br>final_output = workflow.invoke(initial_state)<br><br><br># Display Results<br>print(final_output[&quot;language_feedback&quot;])<br>print(final_output[&quot;analysis_feedback&quot;])<br>print(final_output[&quot;clarity_feedback&quot;])<br><br>print(final_output[&quot;overall_feedback&quot;])<br>print(&quot;Individual Scores:&quot;, final_output[&quot;individual_scores&quot;])<br>print(&quot;Average Score:&quot;, final_output[&quot;avg_score&quot;])</pre><p><strong>Note:</strong> The original source uses structured_model.invoke() but does not show how structured_model is initialized. We configure it using model.with_structured_output(EvaluationSchema) so the complete implementation is connected and runnable with a compatible model integration.</p><h4>11. Compile and Execute the Workflow</h4><p>After defining the graph, compile it.</p><pre>workflow = graph.compile()</pre><p>Next, provide the essay as the initial input and invoke the workflow.</p><pre>initial_state = {<br>    &#39;essay&#39;: essay<br>}<br><br>final_output = workflow.invoke(initial_state)</pre><p>To display the results:</p><pre>print(final_output[&quot;overall_feedback&quot;])<br>print(&quot;Average Score:&quot;, final_output[&quot;avg_score&quot;])</pre><p>When the workflow executes:</p><ol><li>The essay is passed to all three evaluation nodes.</li><li>Each node independently evaluates a different dimension.</li><li>The three feedback results and scores are merged into the shared state.</li><li>The final_evaluation node combines the feedback and calculates the average score.</li><li>The final state is returned.</li></ol><h4>Output</h4><p>After execution, the workflow returns:</p><ul><li><strong>Language Feedback:</strong> Evaluation of grammar, vocabulary, and fluency.</li><li><strong>Analysis Feedback:</strong> Evaluation of argument development and supporting evidence.</li><li><strong>Clarity Feedback:</strong> Evaluation of logical flow and clarity of expression.</li><li><strong>Overall Feedback:</strong> A summarized evaluation generated by the LLM.</li><li><strong>Individual Scores:</strong> The three original evaluation scores.</li><li><strong>Average Score:</strong> The average of the three scores out of 10.</li></ul><p>For example, if the model returns scores of 8, 7, and 9, the output score information will look like this:</p><pre>Individual Scores: [8, 7, 9]<br>Average Score: 8.0</pre><p>The actual feedback and scores will vary depending on the essay and the LLM’s evaluation.</p><h4>Workflow Graph</h4><p>We can visualize the compiled workflow using LangGraph’s graph visualization functionality.</p><pre>from IPython.display import Image, display<br><br>display(Image(workflow.get_graph().draw_mermaid_png()))</pre><figure><img alt="A parallel LangGraph workflow where the essay is evaluated by language, analysis, and clarity nodes simultaneously, with all three branches connecting to the final evaluation node before END." src="https://cdn-images-1.medium.com/max/591/1*9VoS0WLivtMM72KdWzrx9A.png" /><figcaption><em>LangGraph visualization of the Essay Evaluation System, showing three parallel evaluation branches converging into the final evaluation node.</em></figcaption></figure><h4>Understanding What We Built</h4><p>Let’s recap the execution:</p><ol><li>The workflow receives an essay as input.</li><li>Three independent LLM evaluation nodes start simultaneously.</li><li>Each node evaluates a different aspect of the essay and returns feedback with a score.</li><li>LangGraph combines the three score lists using the operator.add reducer and collects the individual feedback fields.</li><li>The final evaluation node generates summarized feedback and calculates the average score.</li><li>The workflow reaches END and returns the complete evaluation results.</li></ol><p>This example demonstrates how LangGraph can orchestrate multiple LLM calls in parallel and combine their results into a single evaluation system.</p><h3>Final Thoughts</h3><p>By embracing parallel workflows in LangGraph:</p><ul><li><strong>Faster Execution:</strong> Multiple independent tasks can execute simultaneously, reducing overall execution time.</li><li><strong>Separation of Concerns:</strong> Each node handles a specific responsibility, making workflows easier to understand and maintain.</li><li><strong>Flexibility and Scalability:</strong> You can add, remove, or modify individual branches without restructuring the entire workflow.</li></ul><p>Whether you’re building a cricket statistics calculator or a multi-dimensional essay evaluation system using LLMs, parallel branches in LangGraph help you build workflows that are:</p><ul><li><strong>Declarative:</strong> Clearly define what happens at each step.</li><li><strong>Deterministic:</strong> Maintain control over the workflow’s execution structure.</li><li><strong>Scalable:</strong> Add more independent execution paths without redesigning the entire workflow.</li></ul><p>As LLM-powered applications become more complex and multimodal, tools like LangGraph help bring structure, speed, and clarity to application development.</p><p>Parallelism isn’t just an optimization technique; it’s also a way of designing more efficient workflows.</p><p>So, the next time you have multiple tasks that can run independently, think in graphs, think in nodes, and think in LangGraph.</p><h3>Key Takeaways</h3><p>In this article, we explored how to build <strong>parallel workflows in LangGraph</strong>, where multiple independent tasks execute simultaneously and their results are combined into a single workflow.</p><p>Here are the key concepts to remember:</p><ol><li><strong>Parallel Workflows:</strong> Parallel workflows allow multiple independent nodes to execute simultaneously, reducing the overall execution time when tasks do not depend on one another.</li><li><strong>Branching and Convergence:</strong> A workflow can branch from a starting node into multiple parallel paths. These paths converge at a subsequent node, which executes after the required parallel tasks have completed.</li><li><strong>Shared State:</strong> LangGraph uses a shared state to pass information between nodes. When multiple parallel nodes update the same state field, reducers such as operator.add can combine their updates.</li><li><strong>Faster Execution:</strong> Independent tasks can run concurrently instead of waiting for one another, making parallel workflows useful when efficiency matters.</li><li><strong>Separation of Concerns:</strong> Each node can handle a specific responsibility, making the workflow easier to understand, maintain, and extend.</li><li><strong>Parallel Workflows Without LLMs:</strong> In the Batsman Stats Calculator, three independent nodes calculate Strike Rate, Balls per Boundary, and Boundary Percentage simultaneously. A summary node then combines the results.</li><li><strong>Parallel Workflows With LLMs:</strong> In the Essay Evaluation System, three LLM-powered nodes independently evaluate language quality, depth of analysis, and clarity of thought. A final node combines their feedback and calculates the average score.</li><li><strong>Modular and Scalable Design:</strong> Parallel workflows make it easier to add, remove, or modify independent execution paths without restructuring the entire workflow.</li></ol><p><strong>The key idea:</strong> Whenever multiple tasks can be performed independently, you can use parallel workflows in LangGraph to execute them simultaneously and combine their results when they are ready.</p><h3>Conclusion</h3><p>Parallel workflows are an important part of building efficient and scalable applications with LangGraph. They allow multiple independent tasks to execute simultaneously, helping reduce execution time while keeping each task separate and organized.</p><p>In this article, we explored how parallel workflows work in LangGraph and how multiple branches can start from the same point, execute independently, and converge to combine their results.</p><p>We also built two practical examples:</p><ul><li><strong>Batsman Stats Calculator:</strong> We calculated Strike Rate, Balls per Boundary, and Boundary Percentage through three independent nodes running in parallel, followed by a summary node.</li><li><strong>Essay Evaluation System:</strong> We used multiple LLM-powered nodes to evaluate language quality, depth of analysis, and clarity of thought simultaneously, then combined their feedback into a final evaluation.</li></ul><p>These examples demonstrate how LangGraph can handle both simple computational tasks and more complex LLM-powered workflows using the same graph-based approach.</p><p>The main takeaway is simple: <strong>when tasks are independent, they don’t need to wait for one another.</strong> By organizing them into parallel branches, you can build workflows that are faster, modular, and easier to extend.</p><p>As you build more complex AI applications, understanding when to use sequential and parallel execution will help you design better workflows with LangGraph.</p><h3>What’s Next?</h3><p>In the next part of this series, we’ll explore <strong>Conditional Workflows in LangGraph</strong>.</p><p>So far, we’ve learned how to build sequential workflows, where tasks execute step by step, and parallel workflows, where multiple independent tasks execute simultaneously.</p><p>But what happens when the next step depends on the result of a previous task?</p><p>That’s where <strong>conditional workflows</strong> come in.</p><p>In Part 7, we’ll learn how to use conditional edges to make workflows dynamically choose their next execution path based on the current state.</p><p>We’ll build two practical examples:</p><ul><li><strong>Example 1: Solve a Quadratic Equation (Without LLM)</strong> — Build a workflow that calculates the discriminant and dynamically routes execution to calculate real roots, repeated roots, or handle cases with no real roots.</li><li><strong>Example 2: Customer Review Chatbot (With LLM)</strong> — Build an LLM-powered chatbot that detects whether a customer review is positive or negative. Positive reviews receive a friendly response, while negative reviews go through an additional diagnosis step before generating an empathetic response.</li></ul><blockquote><strong>Next Part:</strong> Agentic AI using LangGraph — Part 7: <strong>Conditional Workflows in LangGraph</strong></blockquote><p>By the end, you’ll understand how conditional edges enable decision-making and dynamic routing in LangGraph.</p><blockquote><strong>Series:</strong> Agentic AI using LangGraph — Part 6 of 27</blockquote><h3>Connect with me</h3><p><strong><em>Connect with me on </em></strong><a href="https://www.linkedin.com/in/shubhamnagar234/"><strong><em>LinkedIn</em></strong></a><strong><em>, </em></strong><a href="https://github.com/shubhamnagar234"><strong><em>GitHub</em></strong></a><strong><em>, </em></strong><a href="https://x.com/nagarshubham234"><strong><em>X (Twitter)</em></strong></a><strong><em>, or explore my </em></strong><a href="https://shubhamnagar234.vercel.app/"><strong><em>Portfolio</em></strong></a><strong><em>.</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a269fe673afc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sequential Workflows in LangGraph: Building Step-by-Step AI Workflows — Part 5]]></title>
            <link>https://medium.com/@shubhamnagar234/sequential-workflows-in-langgraph-building-step-by-step-ai-workflows-part-5-aab9b700e981?source=rss-10b51a93c3a------2</link>
            <guid isPermaLink="false">https://medium.com/p/aab9b700e981</guid>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[agentic-workflow]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[langgraph]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <dc:creator><![CDATA[Shubham Nagar]]></dc:creator>
            <pubDate>Fri, 13 Nov 2026 10:24:04 GMT</pubDate>
            <atom:updated>2026-11-13T10:24:33.491Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Learn How to Build Sequential Workflows in LangGraph Using State, Nodes, and Edges, with Practical Examples With and Without LLMs.</blockquote><p>In the previous part, we explored the core concepts of LangGraph, including graphs, nodes, edges, state, reducers, and the execution model.</p><p>Now, it’s time to put those concepts into practice by building our first workflows.</p><p>We’ll start with <strong>Sequential Workflows</strong>, one of the simplest workflow patterns in LangGraph. A sequential workflow executes tasks one after another in a predefined order, passing shared state from one node to the next.</p><p>To understand how this works, we’ll begin with a simple BMI calculator that performs calculations without using an LLM. Then, we’ll move on to an LLM-powered question-answering chatbot and finally build a two-stage blog generation workflow using prompt chaining.</p><p>Through these examples, we’ll learn how to define a state schema, create nodes, connect them using edges, and compile and execute a LangGraph workflow.</p><p>Let’s get started!</p><h3>Overview</h3><ul><li><strong><em>What Are Workflows?</em></strong></li><li><strong><em>What Is a Sequential Workflow in LangGraph?</em></strong></li><li><strong><em>Core Concepts of LangGraph</em></strong></li><li><strong><em>Example 1: BMI Calculator — Sequential Workflow (Without LLM)</em></strong></li><li><strong><em>Example 2: Simple QA Chatbot — Sequential Workflow (With LLM)</em></strong></li><li><strong><em>Example 3: Two-Stage Blog Generation in Sequential Workflow Using Prompt Chaining</em></strong></li><li><strong><em>Final Thoughts</em></strong></li><li><strong><em>Key Takeaways</em></strong></li><li><strong><em>Conclusion</em></strong></li><li><strong><em>What’s Next?</em></strong></li></ul><h3>What Are Workflows?</h3><p>A workflow is simply a series of steps organized to accomplish a particular task.</p><p>In LangGraph, a workflow is represented as a graph consisting of two fundamental building blocks:</p><ul><li><strong>Nodes:</strong> Each step in a workflow is represented by a node. A node can be a Python function, an AI agent, a tool, or any other operation that performs a specific task.</li><li><strong>Edges:</strong> Edges define how one node connects to another and determine the flow of execution between different steps.</li></ul><p>Together, nodes and edges define how a workflow progresses from its starting point to its final output.</p><h4>Example: A Simple Sequential Workflow</h4><p>Consider a basic data-processing workflow that takes some input, cleans the data, summarizes it, and produces the final output.</p><p>The workflow follows this sequence:</p><blockquote><strong>Input → Clean Data → Summarize → Output</strong></blockquote><p>Here’s how each step works:</p><ol><li><strong>Input:</strong> Receives the initial data.</li><li><strong>Clean Data:</strong> Processes the input and removes unnecessary or inconsistent information.</li><li><strong>Summarize:</strong> Generates a summary of the cleaned data.</li><li><strong>Output:</strong> Returns the final result.</li></ol><p>Each step represents a node, while the connections between these nodes represent edges.</p><p>This is a simple example of how LangGraph organizes individual operations into a structured workflow.</p><h3>What Is a Sequential Workflow in LangGraph?</h3><p>A <strong>sequential workflow</strong> in LangGraph is a linear sequence of tasks where each task is represented by a node, and the output or updated state from one node is passed to the next through edges.</p><p>It is particularly useful for deterministic, step-by-step processes where the execution order is known in advance, such as form filling, data transformation, and content generation pipelines.</p><p>A sequential workflow follows a predefined execution path:</p><blockquote><strong><em>START → Node → END</em></strong></blockquote><blockquote><strong><em>START → Node 1 → Node 2 → END</em></strong></blockquote><blockquote><strong>START → Node 1 → Node 2 → Node 3 → END</strong></blockquote><p>Unlike workflows with parallel branches or loops, each node in a sequential workflow executes one after another in a fixed order.</p><p>Throughout execution, the workflow maintains a shared <strong>State</strong>. Each node can access the existing state, perform its operation, and update the information before passing it to the next node.</p><p>This ensures that every step works with the latest available context.</p><h4>Sequential Workflow in LangGraph</h4><figure><img alt="Diagram illustrating a linear LangGraph workflow from START through multiple connected nodes to END, with no parallel branches or loops." src="https://cdn-images-1.medium.com/max/1024/1*C4MkvoSyxD1_byrgBlOZHA.png" /><figcaption><em>A sequential workflow in LangGraph, where nodes execute one after another in a predefined order, passing shared state through the workflow.</em></figcaption></figure><p>As shown in the diagram, LangGraph provides a structured way to connect individual tasks and control their execution order.</p><p>This approach is ideal for deterministic application pipelines, such as processing prompts, annotating data, and chaining multiple LLM prompts.</p><h3>Core Concepts of LangGraph</h3><p>Before building our first sequential workflow, let’s understand the core components that make it possible.</p><p>LangGraph provides several building blocks that work together to define how a workflow is structured, how information is passed between steps, and how execution begins and ends.</p><p>We’ll explore the following five concepts:</p><ol><li><strong>State (Shared Memory)</strong></li><li><strong>StateGraph</strong></li><li><strong>Nodes</strong></li><li><strong>Edges</strong></li><li><strong>Entry &amp; Exit Points</strong></li></ol><p>Let’s understand each of them.</p><h4>1. State (Shared Memory)</h4><p>In LangGraph, <strong>State</strong> is a structured, typed container that carries information throughout the workflow.</p><p>It acts as shared memory between nodes, allowing each node to access the information produced by previous steps and update it as the workflow progresses.</p><p>A State schema is typically defined using either Python’s TypedDict or Pydantic&#39;s BaseModel.</p><p>It holds all the variables required by the workflow, such as:</p><ul><li><strong>Inputs:</strong> The initial data provided to the workflow.</li><li><strong>Intermediate Results:</strong> Information generated or processed by individual nodes.</li><li><strong>Outputs:</strong> The final results produced by the workflow.</li></ul><p>For example, in a content generation workflow, the shared state might contain:</p><ul><li>topic: The input topic provided by the user.</li><li>outline: The outline generated by the first node.</li><li>content: The final blog content generated by the next node.</li></ul><p>Each node can read the relevant information from the state, perform its task, and return updates for subsequent nodes.</p><p>This allows information to flow consistently throughout the workflow without requiring each node to manage data independently.</p><h4>2. StateGraph</h4><p>StateGraph is the main class used to build sequential workflows in LangGraph.</p><p>It is parameterized by a <strong>State schema</strong>, which defines the structure of the data that flows through the workflow.</p><p>For example:</p><pre>graph = StateGraph(MyState)</pre><p>Here, MyState represents the schema that defines the data your workflow will maintain and pass between nodes.</p><p>Once the graph is initialized, StateGraph provides several methods to define and configure the workflow:</p><ul><li><strong>Add Nodes:</strong> Register individual functions or operations as nodes in the graph.</li><li><strong>Add Edges:</strong> Connect nodes and define the execution order.</li><li><strong>Configure Entry &amp; Exit Points:</strong> Define where workflow execution begins and ends.</li><li><strong>Compile the Graph:</strong> Compile the graph into a runnable object that can execute the workflow.</li></ul><p>In simple terms, StateGraph provides the structure and methods needed to define how your workflow is organized and executed.</p><h4>3. Nodes</h4><p><strong>Nodes</strong> are individual units of logic that perform specific tasks within a LangGraph workflow.</p><p>Each node is typically defined as a Python function that receives the current state, performs a particular operation, and returns an updated state dictionary.</p><p>A node can perform different types of operations, such as:</p><ul><li><strong>Data Processing:</strong> Transforming or cleaning the information available in the state.</li><li><strong>Computations:</strong> Performing calculations or applying business logic.</li><li><strong>LLM Calls:</strong> Sending prompts to an LLM and storing the generated response in the state.</li><li><strong>Tool Execution:</strong> Calling external tools or APIs to perform specific operations.</li></ul><p>For example, in a sequential workflow, one node might collect user information, another might process that information, and a third might generate the final output.</p><p>Each node handles a specific responsibility, making the workflow modular and easier to maintain.</p><h4>4. Edges</h4><p><strong>Edges</strong> define the flow of execution in a LangGraph workflow. They determine how one node connects to another and which node executes next.</p><p>In a sequential workflow, nodes are connected in a predefined order using the add_edge() method.</p><p>For example:</p><pre>graph.add_edge(START, &quot;node1&quot;)<br>graph.add_edge(&quot;node1&quot;, &quot;node2&quot;)<br>...<br>graph.add_edge(&quot;nodeN&quot;, END)</pre><p>Here’s what each connection represents:</p><ul><li>START → node1: Defines the first node where workflow execution begins.</li><li>node1 → node2: Connects the first node to the second node.</li><li>nodeN → END: Marks the completion of the workflow after the final node executes.</li></ul><p>LangGraph provides two reserved markers for controlling the beginning and end of graph execution:</p><ul><li><strong>START</strong>: Represents the beginning of the workflow.</li><li><strong>END</strong>: Represents the end of the workflow.</li></ul><p>By connecting nodes through edges, we define the execution sequence and ensure that each task runs in the intended order.</p><h4>5. Entry &amp; Exit Points</h4><p>In LangGraph, <strong>Entry and Exit Points</strong> define where workflow execution begins and where it finishes.</p><p>LangGraph provides two methods to configure these points:</p><p><strong>1. </strong><strong>set_entry_point(&quot;node_name&quot;)</strong></p><p>This method specifies the node where workflow execution begins.</p><p>For example:</p><pre>graph.set_entry_point(&quot;node1&quot;)</pre><p>Here, the workflow starts execution from node1.</p><p><strong>2. </strong><strong>set_finish_point(&quot;node_name&quot;)</strong></p><p>This method optionally specifies the node where workflow execution finishes.</p><p>For example:</p><pre>graph.set_finish_point(&quot;nodeN&quot;)</pre><p>Here, the workflow finishes after executing nodeN.</p><p>If you don’t explicitly configure a finish point, the workflow follows the default edge structure to determine where execution ends.</p><p>These methods provide another way to configure the starting and finishing points of a workflow.</p><h3>Example 1: BMI Calculator — Sequential Workflow (Without LLM)</h3><h4>Introduction: What We’re Building</h4><p>In this example, we’ll build a simple <strong>BMI (Body Mass Index) Calculator</strong> using a sequential workflow in LangGraph, without using any LLM.</p><p>The workflow will perform three steps:</p><ol><li><strong>Collect Height &amp; Weight:</strong> Take the user’s height and weight as input.</li><li><strong>Calculate BMI:</strong> Calculate the Body Mass Index using the formula:</li></ol><pre>BMI = Weight (kg) / Height (m)²</pre><ol><li><strong>Determine BMI Category:</strong> Based on the calculated BMI, classify the result into one of four categories:</li></ol><ul><li>Underweight</li><li>Normal</li><li>Overweight</li><li>Obese</li></ul><p>This follows a simple linear execution pattern:</p><blockquote><strong>Input → Calculate BMI → Determine Category → Output</strong></blockquote><p>Since each step executes in a predefined order without parallel branches or loops, this is a good example of a sequential workflow.</p><figure><img alt="A sequential workflow for a BMI calculator, where height and weight are provided as input, BMI is calculated, and the result is classified into a BMI category." src="https://cdn-images-1.medium.com/max/1024/1*1Z2MdbLLc-5mGvVoJg20ww.png" /><figcaption><em>BMI Calculator — Sequential workflow without an LLM, showing how input data moves through calculation and classification steps.</em></figcaption></figure><h4>1. Import &amp; Setup</h4><p>First, let’s import the required components from LangGraph and Python.</p><pre>from langgraph.graph import StateGraph, START, END<br>from typing import TypedDict</pre><p>Here’s what we’re importing:</p><ul><li><strong>StateGraph</strong>: Used to define and construct our workflow graph.</li><li><strong>START</strong>: Represents the beginning of the workflow.</li><li><strong>END</strong>: Represents the completion of the workflow.</li><li><strong>TypedDict</strong>: Used to define the structure of the shared state.</li></ul><h4>2. TypedDict for Shared State</h4><p>Next, we’ll define the state schema that holds the information flowing through our workflow.</p><pre># define state<br>class BMIState(TypedDict):<br>    <br>    weight_kg: float<br>    height_m: float<br>    bmi: float<br>    category: str<br></pre><p>Here, BMIState defines four fields:</p><ul><li><strong>weight_kg</strong>: Stores the user&#39;s weight in kilograms.</li><li><strong>height_m</strong>: Stores the user&#39;s height in meters.</li><li><strong>bmi</strong>: Stores the calculated BMI value.</li><li><strong>category</strong>: Stores the BMI category based on the calculated value.</li></ul><p>The first two fields represent the input data, while the last two hold the results generated by the workflow.</p><h4>3. StateGraph to Define the Workflow</h4><p>Now, let’s create a graph using the state schema we defined.</p><pre># define your graph<br>graph = StateGraph(BMIState)</pre><p>By passing BMIState to StateGraph, we tell LangGraph what structure of data the workflow will maintain and pass between its nodes.</p><h4>4. Nodes — Step Functions</h4><p>Next, we’ll define two nodes. Each node receives the current state, performs a specific operation, and returns the updated state.</p><p><strong>Node 1: </strong><strong>calculate_bmi</strong></p><p>This node extracts the user’s height and weight, calculates the BMI, and stores the result in the shared state.</p><pre>def calculate_bmi(state: BMIState) -&gt; BMIState:<br>    <br>    weight = state[&#39;weight_kg&#39;]<br>    height = state[&#39;height_m&#39;]<br>    bmi = weight / (height ** 2)<br>    state[&#39;bmi&#39;] = round(bmi, 2)<br>    return state</pre><p>Let’s understand what happens here:</p><ul><li>Extracts weight_kg and height_m from the incoming state.</li><li>Calculates BMI using the formula weight / height².</li><li>Rounds the calculated value to two decimal places.</li><li>Updates the bmi field in the state.</li><li>Returns the updated state for the next node.</li></ul><p><strong>Node 2: </strong><strong>label_bmi</strong></p><p>After calculating the BMI, the next node determines the corresponding category.</p><pre>def label_bmi(state: BMIState) -&gt; BMIState:<br><br>    bmi = state[&#39;bmi&#39;]<br>    if bmi &lt; 18.5:<br>        state[&quot;category&quot;] = &quot;Underweight&quot;<br>    elif 18.5 &lt;= bmi &lt; 25:<br>        state[&quot;category&quot;] = &quot;Normal&quot;<br>    elif 25 &lt;= bmi &lt; 30:<br>        state[&quot;category&quot;] = &quot;Overweight&quot;<br>    else:<br>        state[&quot;category&quot;] = &quot;Obese&quot;<br>    return state</pre><p>Here’s how the classification works:</p><ul><li><strong>BMI below 18.5:</strong> Underweight</li><li><strong>BMI from 18.5 to below 25:</strong> Normal</li><li><strong>BMI from 25 to below 30:</strong> Overweight</li><li><strong>BMI of 30 or above:</strong> Obese</li></ul><p>The node reads the calculated BMI from the shared state, assigns the corresponding category, and returns the updated state.</p><h4>5. Edges &amp; Linear Flow</h4><p>Now that we’ve defined our nodes, let’s connect them to establish the execution order.</p><pre># add nodes to your graph<br>graph.add_node(&#39;calculate_bmi&#39;, calculate_bmi)<br>graph.add_node(&#39;label_bmi&#39;, label_bmi)<br><br># add edges to the graph<br>graph.add_edge(START, &#39;calculate_bmi&#39;)<br>graph.add_edge(&#39;calculate_bmi&#39;, &#39;label_bmi&#39;)<br>graph.add_edge(&#39;label_bmi&#39;, END)</pre><p>Here’s the execution flow:</p><ul><li>START → calculate_bmi: Begins the workflow by calculating BMI.</li><li>calculate_bmi → label_bmi: Passes the updated state to the category classification node.</li><li>label_bmi → END: Completes the workflow after determining the BMI category.</li></ul><p>This creates the following sequence:</p><blockquote><strong>START → calculate_bmi → label_bmi → END</strong></blockquote><h4>6. Compile &amp; Run</h4><p>Once the nodes and edges are defined, we can compile the graph and execute the workflow.</p><p><strong>Compile the graph:</strong></p><pre># compile the graph<br>workflow = graph.compile()</pre><p>The compile() method prepares the graph for execution and returns a runnable workflow object.</p><p><strong>Execute the workflow:</strong></p><pre># execute the graph<br>initial_state = {&#39;weight_kg&#39;: 80, &#39;height_m&#39;: 1.73}<br><br>final_state = workflow.invoke(initial_state)<br><br>print(final_state)</pre><p>Let’s understand the execution:</p><ol><li>We provide the user’s weight and height through initial_state.</li><li>workflow.invoke(initial_state) starts the graph execution.</li><li>The calculate_bmi node calculates the BMI and updates the state.</li><li>The label_bmi node determines the corresponding category.</li><li>The final updated state is returned and printed.</li></ol><h4>Complete Code</h4><p>Here is the complete implementation of our BMI Calculator using a sequential workflow in LangGraph:</p><pre>from langgraph.graph import StateGraph, START, END<br>from typing import TypedDict<br><br><br># 1. Define State<br>class BMIState(TypedDict):<br>    weight_kg: float<br>    height_m: float<br>    bmi: float<br>    category: str<br><br><br># 2. Create Graph<br>graph = StateGraph(BMIState)<br><br><br># 3. Define Nodes<br>def calculate_bmi(state: BMIState) -&gt; BMIState:<br>    weight = state[&#39;weight_kg&#39;]<br>    height = state[&#39;height_m&#39;]<br><br>    bmi = weight / (height ** 2)<br><br>    state[&#39;bmi&#39;] = round(bmi, 2)<br><br>    return state<br><br><br>def label_bmi(state: BMIState) -&gt; BMIState:<br>    bmi = state[&#39;bmi&#39;]<br><br>    if bmi &lt; 18.5:<br>        state[&quot;category&quot;] = &quot;Underweight&quot;<br>    elif 18.5 &lt;= bmi &lt; 25:<br>        state[&quot;category&quot;] = &quot;Normal&quot;<br>    elif 25 &lt;= bmi &lt; 30:<br>        state[&quot;category&quot;] = &quot;Overweight&quot;<br>    else:<br>        state[&quot;category&quot;] = &quot;Obese&quot;<br><br>    return state<br><br><br># 4. Add Nodes<br>graph.add_node(&#39;calculate_bmi&#39;, calculate_bmi)<br>graph.add_node(&#39;label_bmi&#39;, label_bmi)<br><br><br># 5. Add Edges<br>graph.add_edge(START, &#39;calculate_bmi&#39;)<br>graph.add_edge(&#39;calculate_bmi&#39;, &#39;label_bmi&#39;)<br>graph.add_edge(&#39;label_bmi&#39;, END)<br><br><br># 6. Compile Graph<br>workflow = graph.compile()<br><br><br># 7. Execute Workflow<br>initial_state = {<br>    &#39;weight_kg&#39;: 80,<br>    &#39;height_m&#39;: 1.73<br>}<br><br>final_state = workflow.invoke(initial_state)<br><br>print(final_state)</pre><h4>Output</h4><p>For the input:</p><ul><li>Weight: 80 kg</li><li>Height: 1.73 m</li></ul><p>The workflow produces:</p><pre>{<br>    &#39;weight_kg&#39;: 80,<br>    &#39;height_m&#39;: 1.73,<br>    &#39;bmi&#39;: 26.73,<br>    &#39;category&#39;: &#39;Overweight&#39;<br>}</pre><p>The final state contains the original input values along with the calculated BMI and its corresponding category.</p><h4>Workflow Graph</h4><p>We can also visualize the workflow graph generated by LangGraph using get_graph().draw_mermaid_png().</p><pre>from IPython.display import Image<br><br>Image(workflow.get_graph().draw_mermaid_png())</pre><figure><img alt="LangGraph diagram showing START connected to calculate_bmi, followed by label_bmi, and then END." src="https://cdn-images-1.medium.com/max/144/1*kxUodxzybnWM_2LPtocJpQ.png" /><figcaption><em>Compiled LangGraph representation of the BMI calculator, showing the execution path from START through </em><em>calculate_bmi and </em><em>label_bmi to END.</em></figcaption></figure><h3>Example 2: Simple QA Chatbot — Sequential Workflow (With LLM)</h3><p>In this example, we’ll build a simple <strong>Question-Answering (QA) Chatbot</strong> using LangGraph and an LLM.</p><p>Unlike the previous BMI calculator, where nodes performed mathematical computations, this workflow will use an LLM to understand a user’s question and generate a response.</p><p>The workflow follows a simple sequence:</p><blockquote><strong>User Question → LLM → Generated Answer</strong></blockquote><p>We’ll use ChatGoogleGenerativeAI with Gemini 2.5 Flash in the implementation. You can also use ChatOpenAI if you prefer an OpenAI model.</p><figure><img alt="A sequential LangGraph workflow in which a user submits a question, an LLM processes it, and the generated answer is returned." src="https://cdn-images-1.medium.com/max/1024/1*HLZVW-3dnudl_LQhr5F-_g.png" /><figcaption><em>Simple QA Chatbot — Sequential workflow with an LLM, showing how a user’s question is passed to an LLM to generate an answer.</em></figcaption></figure><h4>1. Import &amp; Setup</h4><p>First, let’s import the required libraries and LangGraph components.</p><pre># If using ChatOpenAI<br># from langchain_openai import ChatOpenAI<br><br># If using ChatGoogleGenerativeAI<br>from langchain_google_genai import ChatGoogleGenerativeAI<br><br>from langgraph.graph import StateGraph, START, END<br>from typing import TypedDict<br>from dotenv import load_dotenv</pre><p>Here’s what we’re importing:</p><ul><li><strong>ChatOpenAI</strong>: LangChain integration used to interact with OpenAI models.</li><li><strong>ChatGoogleGenerativeAI</strong>: LangChain integration used to interact with Google&#39;s Gemini models.</li><li><strong>StateGraph</strong>: Used to define the workflow graph.</li><li><strong>START and </strong><strong>END</strong>: Reserved markers representing the beginning and end of workflow execution.</li><li><strong>TypedDict</strong>: Used to define the structure of the shared state.</li><li><strong>load_dotenv</strong>: Used to load environment variables from a .env file.</li></ul><h4>2. Configure Environment Variables</h4><p>Next, create a .env file in your project directory to store your API keys.</p><pre>OPENAI_API_KEY=&quot;YOUR_OPENAI_API_KEY&quot;<br>GEMINI_API_KEY=&quot;YOUR_GEMINI_API_KEY&quot;</pre><p>These environment variables allow your application to authenticate with the respective LLM providers.</p><p>Load the environment variables in your Python application:</p><pre>load_dotenv()</pre><h4>3. Initialize LLM</h4><p>Now, let’s initialize the LLM that will generate answers to user questions.</p><p>You can choose either OpenAI or Google Gemini.</p><p><strong>Option 1: Using ChatOpenAI</strong></p><pre>from langchain_openai import ChatOpenAI<br><br>model = ChatOpenAI(model=&quot;gpt-4o-mini&quot;)</pre><p><strong>Option 2: Using ChatGoogleGenerativeAI</strong></p><pre>from langchain_google_genai import ChatGoogleGenerativeAI<br><br>model = ChatGoogleGenerativeAI(model=&quot;gemini-2.5-flash&quot;)</pre><p>For this example, we’ll use <strong>Gemini 2.5 Flash</strong>.</p><p>Both integrations provide a consistent invoke() interface through LangChain, allowing us to call the selected model from our workflow node.</p><h4>4. Define State Schema</h4><p>Next, let’s define the shared state using TypedDict.</p><pre># create a state<br>class LLMState(TypedDict):<br>    question: str<br>    answer: str</pre><p>The LLMState schema contains two fields:</p><ul><li><strong>question</strong>: Stores the question provided as input.</li><li><strong>answer</strong>: Stores the response generated by the LLM.</li></ul><p>The question is the initial input, while the answer is populated during workflow execution.</p><h4>5. Build the Graph</h4><p>Now, initialize the LangGraph workflow using the state schema.</p><pre>graph = StateGraph(LLMState)</pre><p>This creates a sequential workflow graph that expects the data structure defined in LLMState.</p><h4>6. Node: llm_qa</h4><p>Next, let’s define the node responsible for generating answers.</p><pre>def llm_qa(state: LLMState) -&gt; LLMState:<br><br>    # extract the question from state<br>    question = state[&#39;question&#39;]<br>    # form a prompt<br>    prompt = f&#39;Answer the following question {question}&#39;<br>    # ask that question to the LLM<br>    answer = model.invoke(prompt).content<br>    # update the answer in the state<br>    state[&#39;answer&#39;] = answer<br>    return state</pre><p>Let’s understand what happens inside this node:</p><ol><li><strong>Extract the Question:</strong> Reads the user’s question from state[&#39;question&#39;].</li><li><strong>Create a Prompt:</strong> Constructs a prompt containing the question.</li><li><strong>Invoke the LLM:</strong> Sends the prompt to the selected model using model.invoke(prompt).</li><li><strong>Extract the Response:</strong> Retrieves the generated text using .content.</li><li><strong>Update the State:</strong> Stores the generated response in state[&#39;answer&#39;].</li><li><strong>Return the State:</strong> Returns the updated state to the workflow.</li></ol><p>This node handles the complete question-answering operation.</p><h4>7. Add Node and Edges</h4><p>Now, let’s register the llm_qa function as a node and connect it to the workflow.</p><pre># add nodes<br>graph.add_node(&#39;llm_qa&#39;, llm_qa)<br><br># add edges<br>graph.add_edge(START, &#39;llm_qa&#39;)<br>graph.add_edge(&#39;llm_qa&#39;, END)</pre><p>Here’s what these connections do:</p><ul><li><strong>START → llm_qa</strong>: Starts workflow execution by calling the question-answering node.</li><li><strong>llm_qa → END</strong>: Completes the workflow after the LLM generates an answer.</li></ul><p>The resulting execution flow is:</p><blockquote><strong>START → llm_qa → END</strong></blockquote><h4>8. Compile Workflow</h4><p>Once we’ve defined the node and connected the edges, we can compile the graph.</p><pre>workflow = graph.compile()</pre><p>The compile() method prepares the graph for execution and returns a runnable workflow object.</p><h4>9. Execute the Workflow</h4><p>Now, let’s provide a question as the initial input and execute the workflow.</p><pre># execute the workflow<br>initial_state = {<br>    &#39;question&#39;: &#39;How far is the Moon from the Earth?&#39;<br>}<br><br>final_state = workflow.invoke(initial_state)<br><br>print(final_state[&#39;answer&#39;])</pre><p>Here’s what happens during execution:</p><ol><li>We provide the user’s question through initial_state.</li><li>workflow.invoke(initial_state) starts the graph execution.</li><li>The llm_qa node extracts the question and creates a prompt.</li><li>The LLM generates an answer.</li><li>The generated response is stored in the answer field.</li><li>The workflow returns the updated state, and we print the generated answer.</li></ol><h4>10. Complete Code</h4><p>Here is the complete implementation of our Simple QA Chatbot using LangGraph and Gemini 2.5 Flash.</p><pre># If using ChatOpenAI<br># from langchain_openai import ChatOpenAI<br># If using ChatGoogleGenerativeAI<br>from langchain_google_genai import ChatGoogleGenerativeAI<br>from langgraph.graph import StateGraph, START, END<br>from typing import TypedDict<br>from dotenv import load_dotenv<br><br># Load environment variables<br>load_dotenv()<br><br># If using ChatOpenAI<br># Initialize ChatOpenAI<br># model = ChatOpenAI(model=&quot;gpt-4o-mini&quot;)<br><br># If using ChatGoogleGenerativeAI<br># 1. Initialize ChatGoogleGenerativeAI<br>model = ChatGoogleGenerativeAI(model=&quot;gemini-2.5-flash&quot;)<br><br># 2. Define State<br>class LLMState(TypedDict):<br>    question: str<br>    answer: str<br><br># 3. Create Graph<br>graph = StateGraph(LLMState)<br><br># 4. Define Node<br>def llm_qa(state: LLMState) -&gt; LLMState:<br>    # extract the question from state<br>    question = state[&#39;question&#39;]<br>    # form a prompt<br>    prompt = f&#39;Answer the following question {question}&#39;<br>    # ask that question to the LLM<br>    answer = model.invoke(prompt).content<br>    # update the answer in the state<br>    state[&#39;answer&#39;] = answer<br>    return state<br><br># 5. Add Node<br>graph.add_node(&#39;llm_qa&#39;, llm_qa)<br><br># 6. Add Edges<br>graph.add_edge(START, &#39;llm_qa&#39;)<br>graph.add_edge(&#39;llm_qa&#39;, END)<br><br># 7. Compile Workflow<br>workflow = graph.compile()<br><br># 8. Execute Workflow<br>initial_state = {<br>    &#39;question&#39;: &#39;How far is the Moon from the Earth?&#39;<br>}<br>final_state = workflow.invoke(initial_state)<br><br>print(final_state[&#39;answer&#39;])</pre><p><strong>Note:</strong> Make sure your .env file contains a valid Gemini API key. If you want to use OpenAI instead, replace the Gemini integration with ChatOpenAI and initialize the model using your OpenAI API key.</p><h4>Output</h4><p>The output will contain the answer generated by the LLM. For example:</p><pre>The average distance between the Earth and the Moon<br>is approximately 384,400 kilometers (238,855 miles).</pre><p>The exact wording may vary depending on the model’s response.</p><h4>Workflow Graph</h4><p>We can visualize the compiled workflow using LangGraph’s graph visualization functionality.</p><pre>from IPython.display import Image<br><br>Image(workflow.get_graph().draw_mermaid_png())</pre><figure><img alt="LangGraph diagram showing START connected to the llm_qa node, followed by END." src="https://cdn-images-1.medium.com/max/106/1*sdFMUhxUiQFhj-suvFTjfQ.png" /><figcaption><em>Compiled LangGraph representation of the Simple QA Chatbot, showing the execution flow from START to the </em><em>llm_qa node and then END.</em></figcaption></figure><h4>Summary Flow</h4><p>Let’s summarize how our QA chatbot works:</p><ol><li>The user provides a question through the initial state.</li><li>The llm_qa node extracts the question and constructs a prompt.</li><li>The node sends the prompt to ChatOpenAI or ChatGoogleGenerativeAI.</li><li>The LLM generates a response, which is stored in the shared state.</li><li>The workflow returns the updated state containing both question and answer.</li><li>The script prints the generated answer.</li></ol><h4>Why This Works</h4><ul><li><strong>Workflow Orchestration:</strong> LangGraph manages the execution order and state passing between nodes.</li><li><strong>LLM Integration:</strong> ChatOpenAI or ChatGoogleGenerativeAI provides a convenient invoke() interface for interacting with the selected model.</li><li><strong>Shared State:</strong> The question and generated answer are maintained within a structured state.</li><li><strong>Modular Architecture:</strong> The workflow is simple and easy to extend with additional nodes for logging, validation, or multiple processing steps.</li></ul><p>This example demonstrates how we can integrate an LLM into a sequential LangGraph workflow while keeping the execution flow structured and manageable.</p><h3>Example 3: Two-Stage Blog Generation in a Sequential Workflow Using Prompt Chaining</h3><h4>What Is Prompt Chaining?</h4><p>Prompt chaining involves linking multiple LLM prompts in a defined sequence. The output of one prompt becomes the input for the next, allowing complex tasks to be divided into smaller, manageable steps.</p><p>For example, instead of asking an LLM to create an entire blog post in one prompt, we can divide the task into two stages:</p><ol><li><strong>Generate an Outline:</strong> Create a structured outline based on the blog title.</li><li><strong>Generate the Blog:</strong> Use the generated outline to write the complete blog post.</li></ol><p>In LangGraph, each stage is represented by a node, and the output is passed through the shared state to the next node.</p><figure><img alt="A sequential LangGraph workflow where the first node generates a blog outline and the second node uses that outline to generate the complete blog post." src="https://cdn-images-1.medium.com/max/1024/1*X3PArEVRgKaUZrpjzJCQ7w.png" /><figcaption><em>Two-stage blog generation workflow using prompt chaining in LangGraph.</em></figcaption></figure><h4>1. Setting Up</h4><p>Before building the workflow, we need to import the required libraries, configure the LLM, define the state schema, and initialize the graph.</p><p><strong>Imports and Environment Setup</strong></p><p>We use the following components:</p><ul><li>StateGraph, START, and END from LangGraph to construct the workflow.</li><li>TypedDict to define the shared state.</li><li>ChatGoogleGenerativeAI to interact with Google&#39;s Gemini model.</li><li>load_dotenv to load environment variables from the .env file.</li></ul><p>If you prefer OpenAI, you can use ChatOpenAI instead.</p><pre># If using ChatOpenAI<br># from langchain_openai import ChatOpenAI<br><br># If using ChatGoogleGenerativeAI<br>from langchain_google_genai import ChatGoogleGenerativeAI<br>from langgraph.graph import StateGraph, START, END<br>from typing import TypedDict<br>from dotenv import load_dotenv</pre><p><strong>Configure Environment Variables</strong></p><p>Create a .env file in your project directory and add your API keys:</p><pre>OPENAI_API_KEY=&quot;YOUR_OPENAI_API_KEY&quot;<br>GEMINI_API_KEY=&quot;YOUR_GEMINI_API_KEY&quot;</pre><p>Load the environment variables:</p><pre>load_dotenv()</pre><p><strong>Initialize the LLM</strong></p><p>You can initialize either ChatOpenAI or ChatGoogleGenerativeAI, depending on the provider you want to use.</p><pre># If using ChatOpenAI<br># from langchain_openai import ChatOpenAI<br># model = ChatOpenAI()<br><br># If using ChatGoogleGenerativeAI<br>model = ChatGoogleGenerativeAI(model=&quot;gemini-2.5-flash&quot;)</pre><p>For this example, we will use Gemini. Both integrations provide the invoke() method to send prompts to the model and retrieve responses.</p><p><strong>Define the State Schema</strong></p><p>Next, define the shared state using TypedDict.</p><pre>class BlogState(TypedDict):<br><br>    title: str<br>    outline: str<br>    content: str</pre><p>The state contains three fields:</p><ul><li>title: The topic or title of the blog post.</li><li>outline: The outline generated by the first node.</li><li>content: The complete blog post generated by the second node.</li></ul><p><strong>Initialize the Graph</strong></p><p>Now, create a StateGraph using the BlogState schema.</p><pre>graph = StateGraph(BlogState)</pre><p>This graph will manage the state as it moves through the two nodes.</p><h4>2. Node 1: create_outline</h4><p><strong>Purpose:</strong> Generate a concise outline based on the blog title.</p><p>The first node is responsible for creating the structure of the blog post.</p><p><strong>Process:</strong></p><ol><li>Extract the blog title from the current state.</li><li>Create a prompt asking the LLM to generate an outline.</li><li>Invoke the LLM and retrieve its response.</li><li>Store the generated outline in state[&#39;outline&#39;].</li><li>Return the updated state.</li></ol><pre>def create_outline(state: BlogState) -&gt; BlogState:<br>    # Fetch title<br>    title = state[&#39;title&#39;]<br><br>    # Generate outline using LLM<br>    prompt = f&quot;Generate a detailed outline for a blog on the topic - {title}&quot;<br>    outline = model.invoke(prompt).content<br>    # Update state<br>    state[&#39;outline&#39;] = outline<br>    return state</pre><p>Once this node executes, the generated outline is stored in the shared state. The next node can access it directly.</p><h4>3. Node 2: create_blog</h4><p><strong>Purpose:</strong> Generate a complete blog post using the outline created by the previous node.</p><p>The second node takes the original title and generated outline from the shared state and uses them to generate the blog content.</p><p><strong>Process:</strong></p><ol><li>Extract the title and outline from the state.</li><li>Construct a prompt containing both values.</li><li>Invoke the LLM to generate the blog post.</li><li>Store the generated content in state[&#39;content&#39;].</li><li>Return the updated state.</li></ol><pre>def create_blog(state: BlogState) -&gt; BlogState:<br>    title = state[&#39;title&#39;]<br>    outline = state[&#39;outline&#39;]<br><br>    prompt = f&quot;&quot;&quot;<br>    Write a detailed blog on the title - {title}<br>    using the following outline:<br>    {outline}<br>    &quot;&quot;&quot;<br>    content = model.invoke(prompt).content<br>    state[&#39;content&#39;] = content<br>    return state</pre><p>Notice that the second node uses the outline generated by the first node. This is how prompt chaining works: the output of one LLM call becomes the input for the next.</p><h4>4. Building the Graph</h4><p>Now that both nodes are defined, we can add them to the graph and connect them using edges.</p><pre># Add nodes<br>graph.add_node(&#39;create_outline&#39;, create_outline)<br>graph.add_node(&#39;create_blog&#39;, create_blog)<br><br># Add edges<br>graph.add_edge(START, &#39;create_outline&#39;)<br>graph.add_edge(&#39;create_outline&#39;, &#39;create_blog&#39;)<br>graph.add_edge(&#39;create_blog&#39;, END)</pre><p>This creates the following execution sequence:</p><blockquote><strong>START → </strong><strong>create_outline → </strong><strong>create_blog → </strong><strong>END</strong></blockquote><p>The workflow first generates the outline and then passes the updated state to the blog generation node.</p><h4>5. Complete Code</h4><p>Here is the complete implementation combining the imports, state schema, both nodes, graph construction, and execution.</p><pre># If using ChatOpenAI<br># from langchain_openai import ChatOpenAI<br># If using ChatGoogleGenerativeAI<br>from langchain_google_genai import ChatGoogleGenerativeAI<br>from langgraph.graph import StateGraph, START, END<br>from typing import TypedDict<br>from dotenv import load_dotenv<br><br># Load environment variables<br>load_dotenv()<br><br># If using ChatOpenAI<br># Initialize ChatOpenAI<br># model = ChatOpenAI(model=&quot;gpt-4o-mini&quot;)<br><br># If using ChatGoogleGenerativeAI<br># Initialize ChatGoogleGenerativeAI<br>model = ChatGoogleGenerativeAI(model=&quot;gemini-2.5-flash&quot;)<br><br># Define State<br>class BlogState(TypedDict):<br><br>    title: str<br>    outline: str<br>    content: str<br><br># Create Node 1: Generate Outline<br>def create_outline(state: BlogState) -&gt; BlogState:<br><br>    title = state[&#39;title&#39;]<br>    prompt = f&quot;Generate a detailed outline for a blog on the topic - {title}&quot;<br>    outline = model.invoke(prompt).content<br>    state[&#39;outline&#39;] = outline<br>    return state<br><br># Create Node 2: Generate Blog<br>def create_blog(state: BlogState) -&gt; BlogState:<br><br>    title = state[&#39;title&#39;]<br>    outline = state[&#39;outline&#39;]<br>    prompt = f&quot;&quot;&quot;<br>    Write a detailed blog on the title - {title}<br>    using the following outline:<br>    {outline}<br>    &quot;&quot;&quot;<br>    content = model.invoke(prompt).content<br>    state[&#39;content&#39;] = content<br>    return state<br><br># Create Graph<br>graph = StateGraph(BlogState)<br><br># Add Nodes<br>graph.add_node(&#39;create_outline&#39;, create_outline)<br>graph.add_node(&#39;create_blog&#39;, create_blog)<br><br># Add Edges<br>graph.add_edge(START, &#39;create_outline&#39;)<br>graph.add_edge(&#39;create_outline&#39;, &#39;create_blog&#39;)<br>graph.add_edge(&#39;create_blog&#39;, END)<br><br># Compile Graph<br>workflow = graph.compile()<br><br># Execute Workflow<br>initial_state = {<br>    &#39;title&#39;: &#39;Rise of AI in India&#39;<br>}<br><br>final_state = workflow.invoke(initial_state)<br><br># Print Final State<br>print(final_state)</pre><h4>6. Compile and Execute</h4><p>After defining the graph, compile it to create an executable workflow.</p><pre>workflow = graph.compile()</pre><p>Now, provide the initial state containing the blog title and invoke the workflow.</p><pre>initial_state = {<br>    &#39;title&#39;: &#39;Rise of AI in India&#39;<br>}<br><br>final_state = workflow.invoke(initial_state)<br><br>print(final_state)</pre><p>The workflow executes both nodes in sequence:</p><ol><li>create_outline generates an outline for <strong>Rise of AI in India</strong>.</li><li>create_blog uses that outline to generate the complete blog post.</li></ol><p>The final state contains the original title, generated outline, and generated blog content.</p><h4>Output</h4><p>The output will be a dictionary containing all three fields:</p><ul><li>title: Rise of AI in India</li><li>outline: The outline generated by the LLM.</li><li>content: The complete blog post generated using that outline.</li></ul><p>The actual outline and blog content will vary depending on the LLM response.</p><h4>Workflow Graph</h4><p>You can visualize the compiled workflow using LangGraph’s graph visualization functionality.</p><pre>from IPython.display import Image, display<br><br>display(Image(workflow.get_graph().draw_mermaid_png()))</pre><figure><img alt="A LangGraph diagram showing the execution flow from START to create_outline, then to create_blog, and finally to END." src="https://cdn-images-1.medium.com/max/147/1*NFe-qvrXjmtbfuBYGCrL1A.png" /><figcaption><em>LangGraph visualization of the two-stage blog generation workflow.</em></figcaption></figure><h4>Why Is This Effective?</h4><ul><li><strong>Modular Design:</strong> Each node handles a specific task. The first generates an outline, while the second creates the complete blog post.</li><li><strong>Manageable Prompts:</strong> Breaking the task into smaller stages reduces prompt complexity and gives us more control over the generation process.</li><li><strong>State Passing:</strong> The intermediate outline is stored in the shared state and passed directly to the next node, maintaining continuity between stages.</li><li><strong>Validation and Extensibility:</strong> We can add more nodes for editing, summarizing, or logging without changing the overall workflow structure.</li></ul><h4>How Does It Compare to Traditional Prompt Chaining?</h4><p>This example follows the traditional sequential chaining pattern, where the output of one LLM call is passed as input to another.</p><p>The difference is how the workflow is organized:</p><ul><li>In traditional prompt chaining, developers often connect multiple LLM calls using ad-hoc code or chaining abstractions such as LangChain’s LLMChain.</li><li>In LangGraph, each step is represented as a node, and edges explicitly define the execution sequence.</li><li>The shared state provides a structured way to pass intermediate results between steps.</li></ul><p>This makes the workflow easier to understand, extend, and manage as the application grows.</p><h3>Final Thoughts</h3><p>With this example, we have built a two-stage blog generation workflow using LangGraph and prompt chaining. Instead of asking an LLM to complete the entire task in one step, we divided it into two independent stages and connected them through shared state.</p><p>This demonstrates how LangGraph can organize multiple LLM calls into a clear, sequential workflow.</p><h3>Key Takeaways</h3><p>In this article, we explored how to build sequential workflows using LangGraph and how different nodes work together to execute tasks in a predefined order.</p><p>Here are the key concepts to remember:</p><ul><li><strong>Workflows:</strong> A workflow is a sequence of steps where each step performs a specific task, and edges define how execution moves between them.</li><li><strong>Sequential Workflows:</strong> Tasks execute one after another in a predefined order, following a linear flow from START to END.</li><li><strong>State:</strong> State acts as shared memory between nodes, storing inputs, intermediate results, and final outputs.</li><li><strong>StateGraph:</strong> StateGraph is the main LangGraph class used to define the state schema and construct the workflow.</li><li><strong>Nodes:</strong> Nodes are Python functions that perform specific operations, such as data processing, calculations, or LLM calls.</li><li><strong>Edges:</strong> Edges connect nodes and define the execution sequence of the workflow.</li><li><strong>Entry and Exit Points:</strong> START and END define where workflow execution begins and finishes.</li><li><strong>LLM Integration:</strong> LangGraph allows us to integrate LLM calls into sequential workflows to perform tasks such as question answering and content generation.</li><li><strong>Prompt Chaining:</strong> Multiple LLM prompts can be connected sequentially, allowing the output of one step to become the input for the next.</li></ul><p>Through the three practical examples, we saw how sequential workflows can be used for:</p><ol><li><strong>BMI Calculator:</strong> Performing calculations and classification without an LLM.</li><li><strong>Simple QA Chatbot:</strong> Integrating an LLM into a workflow to answer user questions.</li><li><strong>Two-Stage Blog Generation:</strong> Using prompt chaining to generate a blog outline first and then create the complete blog post.</li></ol><p>The main idea is that LangGraph provides a structured way to organize tasks, manage shared state, and connect multiple operations into a predictable execution flow.</p><h3>Conclusion</h3><p>In this article, we explored how to build sequential workflows using LangGraph, starting with the fundamental concepts of workflows, state, nodes, edges, and execution flow.</p><p>We also implemented three practical examples to understand how sequential workflows work in real-world scenarios:</p><ul><li>A BMI calculator that performs calculations and classifies results without using an LLM.</li><li>A simple QA chatbot that integrates an LLM to answer user questions.</li><li>A two-stage blog generation workflow that uses prompt chaining to generate an outline first and then create the complete blog post.</li></ul><p>These examples demonstrate how LangGraph helps organize tasks into smaller, manageable steps while maintaining shared state between them.</p><p>Sequential workflows are particularly useful when tasks need to execute in a fixed, predictable order. By representing each operation as a node and connecting them through edges, we can build workflows that are easier to understand, maintain, and extend.</p><p>However, not every AI application follows a simple linear execution path. Some applications require conditional decisions, branching, or repeated execution based on intermediate results.</p><p>That’s where more advanced LangGraph capabilities become useful.</p><h3>What’s Next?</h3><p>In the next part of this series, we’ll explore <strong>Parallel Workflows in LangGraph</strong> and learn how to execute multiple independent tasks simultaneously instead of running them one after another.</p><p>We’ll cover how parallel branches work, how multiple nodes can process the same shared state, and how their results can be combined before moving to the next step.</p><p>We’ll also build two practical examples:</p><ol><li><strong>Batsman Stats Calculator (Without LLM):</strong> Calculate cricket metrics such as Strike Rate, Balls per Boundary, and Boundary Percentage using independent parallel nodes, then combine the results into a summary.</li><li><strong>Essay Evaluation System (With LLM):</strong> Evaluate an essay across three dimensions — language quality, depth of analysis, and clarity of thought — using parallel LLM calls, then combine the feedback and calculate an average score.</li></ol><blockquote><strong>Next Part:</strong> Agentic AI using LangGraph — Part 6: <strong>Parallel Workflows in LangGraph</strong></blockquote><p>By the end, you’ll understand how parallel workflows can improve execution efficiency and help you build more modular and scalable AI applications.</p><blockquote><strong>Series:</strong> Agentic AI using LangGraph — Part 5 of 27</blockquote><h3>Connect with me</h3><p><strong><em>Connect with me on </em></strong><a href="https://www.linkedin.com/in/shubhamnagar234/"><strong><em>LinkedIn</em></strong></a><strong><em>, </em></strong><a href="https://github.com/shubhamnagar234"><strong><em>GitHub</em></strong></a><strong><em>, </em></strong><a href="https://x.com/nagarshubham234"><strong><em>X (Twitter)</em></strong></a><strong><em>, or explore my </em></strong><a href="https://shubhamnagar234.vercel.app/"><strong><em>Portfolio</em></strong></a><strong><em>.</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aab9b700e981" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LangGraph Core Concepts: Understanding How LangGraph Works — Part 4]]></title>
            <link>https://medium.com/@shubhamnagar234/langgraph-core-concepts-understanding-how-langgraph-works-part-4-470a093d2316?source=rss-10b51a93c3a------2</link>
            <guid isPermaLink="false">https://medium.com/p/470a093d2316</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[langgraph]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[agents]]></category>
            <category><![CDATA[ai-agent]]></category>
            <dc:creator><![CDATA[Shubham Nagar]]></dc:creator>
            <pubDate>Thu, 05 Nov 2026 15:33:08 GMT</pubDate>
            <atom:updated>2026-11-05T15:33:57.806Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><em>Explore graphs, nodes, edges, state, reducers, and the execution model that powers Agentic AI workflows.</em></blockquote><p>In the previous parts of this series, we explored the fundamentals of Agentic AI, understood the difference between LangChain and LangGraph, and learned why complex AI applications need advanced workflow orchestration.</p><blockquote>Now it’s time to understand how <strong>LangGraph</strong> actually works.</blockquote><p>LangGraph provides a graph-based approach to building AI workflows. Instead of executing operations only in a predefined sequence, it allows us to define individual tasks, connect them, manage shared state, and control how execution moves through the workflow.</p><p>To build a strong foundation, we need to understand some of its core concepts, including <strong>graphs, nodes, edges, state, reducers, and the LangGraph execution model</strong>.</p><p>We’ll also explore different LLM workflow patterns, such as prompt chaining, routing, parallelization, orchestrator workers, and evaluator optimizer.</p><p>By understanding these concepts, we’ll be able to see how LangGraph structures and executes the workflows that power Agentic AI applications.</p><h3>Overview</h3><ul><li><strong><em>What Is LangGraph?</em></strong></li><li><strong><em>LLM Workflows</em></strong></li><li><strong><em>Graphs, Nodes, and Edges</em></strong></li><li><strong><em>State</em></strong></li><li><strong><em>Reducers</em></strong></li><li><strong><em>LangGraph Execution Model</em></strong></li><li><strong><em>Key Takeaways</em></strong></li><li><strong><em>Conclusion</em></strong></li><li><strong><em>What’s Next?</em></strong></li></ul><h3>What Is LangGraph?</h3><p><strong>LangGraph</strong> is an orchestration framework for building <strong>intelligent, stateful, and multi-step LLM workflows</strong>.</p><p>It enables developers to build advanced AI applications with capabilities such as:</p><ul><li><strong>Parallelism:</strong> Running multiple tasks simultaneously.</li><li><strong>Loops:</strong> Repeating tasks until a specific condition is met.</li><li><strong>Branching:</strong> Choosing different execution paths based on conditions.</li><li><strong>Memory:</strong> Maintaining and updating information throughout workflow execution.</li><li><strong>Resumability:</strong> Pausing a workflow and resuming it later from where it left off.</li></ul><p>These capabilities make LangGraph particularly useful for building agentic and production-grade AI applications.</p><h4>How Does LangGraph Work?</h4><p>Unlike a traditional linear chain, LangGraph represents application logic as a <strong>graph consisting of nodes and edges</strong>.</p><ul><li><strong>Nodes:</strong> Represent individual tasks or operations performed within a workflow.</li><li><strong>Edges:</strong> Define how execution moves from one node to another, including conditional routing.</li></ul><p>Each node performs a specific operation, while edges determine what happens next.</p><p>This graph-based structure gives developers greater control over workflow execution and makes it possible to build complex AI applications involving multiple steps, decisions, and execution paths.</p><figure><img alt="Diagram illustrating a graph-based workflow where nodes represent individual tasks and edges define the execution paths between them." src="https://cdn-images-1.medium.com/max/1024/1*J1-xY6F4Llr9uhoOFXzEUg.png" /><figcaption><em>LangGraph represents LLM workflows as a graph of interconnected nodes and edges.</em></figcaption></figure><h3>LLM Workflows</h3><p>An <strong>LLM workflow</strong> defines how one or more large language model (LLM) calls and other operations work together to complete a particular task.</p><p>Instead of relying on a single LLM call to handle everything, we can break a complex task into smaller steps and organize how those steps are executed.</p><p>Depending on the application’s requirements, these steps can run sequentially, follow different paths, execute in parallel, or repeat based on evaluation and feedback.</p><p>LangGraph makes it possible to represent these workflows as graphs, giving developers control over how tasks are connected and executed.</p><p>Let’s explore five common LLM workflow patterns:</p><ol><li><strong>Prompt Chaining:</strong> Breaking a task into multiple sequential LLM calls, where each step uses the output of the previous step.</li><li><strong>Routing:</strong> Directing an input to different LLM calls or processing paths based on its requirements.</li><li><strong>Parallelization:</strong> Executing multiple independent LLM calls simultaneously and combining their results.</li><li><strong>Orchestrator Workers:</strong> Using a central orchestrator to distribute tasks among multiple workers and combine their outputs.</li><li><strong>Evaluator Optimizer:</strong> Improving generated outputs through an iterative process of evaluation, feedback, and refinement.</li></ol><p>Each pattern solves a different workflow requirement. Understanding them will help us decide how to structure our applications using LangGraph.</p><h4>1. Prompt Chaining</h4><p><strong>Prompt Chaining</strong> involves executing a series of LLM calls sequentially, where the output of one step becomes the input for the next step.</p><p>Instead of asking an LLM to complete a complex task in a single call, we break the task into smaller, manageable subtasks. Each step focuses on a specific part of the overall task and passes its result to the next step.</p><h4>Example</h4><p>Suppose we want an LLM to write a detailed report.</p><p>Instead of asking it to generate the entire report in one step, we can divide the process into smaller steps:</p><ol><li><strong>First LLM Call — Generate an Outline:</strong> The LLM creates an outline based on the given topic.</li><li><strong>Second LLM Call — Write the Report:</strong> The generated outline is passed as input to another LLM call, which writes the full report.</li><li><strong>Final Output:</strong> The completed report is returned.</li></ol><p>The output of each step becomes the input for the next step, creating a sequential workflow.</p><figure><img alt="Flowchart showing an input passing through multiple LLM calls in sequence, with each call using the previous step’s output to generate the final response." src="https://cdn-images-1.medium.com/max/1024/1*w62xrQ6uRxqxGhSfCmTtfA.png" /><figcaption><em>Prompt Chaining — a sequence of LLM calls where each step passes its output to the next step.</em></figcaption></figure><h4>When Is Prompt Chaining Useful?</h4><p>Prompt Chaining is particularly useful when a complex task can be divided into smaller, well-defined steps.</p><p>For example, creating an outline before writing a full report makes the process more structured and allows each step to focus on a specific objective.</p><h4>2. Routing</h4><p><strong>Routing</strong> functions as a decision-making layer in an LLM workflow.</p><p>An initial LLM call analyzes the user’s input and directs the query to the most appropriate tool or specialized LLM based on the user’s requirements.</p><p>Instead of sending every query through the same processing path, routing allows an application to select the most suitable path for each request.</p><h4>Example</h4><p>Consider a customer support chatbot that handles different types of queries.</p><p>A user might ask questions related to technical issues or billing problems. Instead of processing every request in the same way, the system first analyzes the user’s query and determines its category.</p><p>The workflow can then route the request to the appropriate destination:</p><ol><li><strong>User Input:</strong> The user submits a query to the chatbot.</li><li><strong>Input Analysis:</strong> An initial LLM call analyzes the query and identifies its intent.</li><li><strong>Routing Decision:</strong> Based on the identified intent, the system selects the appropriate processing path.</li><li><strong>Specialized Processing:</strong> The query is forwarded to the relevant destination, such as:</li></ol><ul><li><strong>Technical Support:</strong> Handles technical issues and troubleshooting.</li><li><strong>Billing Support:</strong> Handles payment-related questions and billing inquiries.</li></ul><p><strong>5. Final Response:</strong> The selected destination processes the query and returns a response to the user.</p><figure><img alt="Flowchart showing a user query passing through an LLM-based routing decision, which directs the request to one of several specialized processing paths before returning a response." src="https://cdn-images-1.medium.com/max/1024/1*a8Q0iQppF7lUnbFg7moAtA.png" /><figcaption><em>Routing — an initial LLM analyzes the user’s input and directs it to the most appropriate tool or specialized LLM.</em></figcaption></figure><h4>When Is Routing Useful?</h4><p>Routing is useful when an application handles different categories of requests that require different tools, models, or processing logic.</p><p>It helps avoid sending every request through the same workflow and ensures that each query reaches the most suitable destination.</p><h4>3. Parallelization</h4><p><strong>Parallelization</strong> is a workflow pattern that splits a task into multiple independent subtasks that can run simultaneously.</p><p>Instead of executing each operation one after another, the workflow performs multiple tasks at the same time and then aggregates their outputs to produce a final result.</p><p>This approach is particularly useful when different operations don’t depend on each other’s outputs and can be executed independently.</p><h4>Example: Content Moderation</h4><p>Consider a content moderation system that needs to evaluate user-generated content before publishing it.</p><p>Instead of performing all safety checks sequentially, the system can divide the moderation process into multiple independent checks:</p><ol><li><strong>User Input:</strong> The system receives content that needs to be moderated.</li><li><strong>Parallel Execution:</strong> The content is sent to multiple independent evaluation tasks:</li></ol><ul><li><strong>Toxicity Check:</strong> Identifies toxic, abusive, or harmful language.</li><li><strong>Violence Check:</strong> Detects violent or threatening content.</li><li><strong>Safety Check:</strong> Evaluates whether the content violates safety guidelines.</li></ul><p><strong>3. Result Aggregation:</strong> The outputs from all evaluation tasks are collected and combined.</p><p><strong>4. Final Decision:</strong> Based on the combined results, the system determines whether the content should be approved, flagged, or rejected.</p><figure><img alt="Flowchart showing a user input distributed to three parallel processing tasks, followed by an aggregation step that combines their outputs into a final result." src="https://cdn-images-1.medium.com/max/1024/1*56E7bwgVUlCzTuWnP5FgJQ.png" /><figcaption><em>Parallelization — multiple independent subtasks execute simultaneously, and their outputs are aggregated to produce a final result.</em></figcaption></figure><h4>When Is Parallelization Useful?</h4><p>Parallelization is useful when a task can be divided into multiple independent operations that don’t need to wait for one another.</p><p>It helps improve workflow efficiency by allowing multiple tasks to execute simultaneously rather than processing them sequentially.</p><h4>4. Orchestrator Workers</h4><p><strong>Orchestrator Workers</strong> is a workflow pattern similar to parallelization, but with one important difference: the subtasks are dynamically determined by a central <strong>Orchestrator LLM</strong>.</p><p>In parallelization, the subtasks are generally predefined. However, in the Orchestrator Workers pattern, the orchestrator analyzes the input, determines which subtasks need to be performed, and assigns them to different workers based on the current context.</p><p>Each worker handles its assigned task, and the results are collected to produce the final output.</p><h4>How Does It Work?</h4><p>The workflow consists of three main components:</p><ol><li><strong>Orchestrator:</strong> An LLM that analyzes the input, identifies the required subtasks, and dynamically assigns them to workers.</li><li><strong>Workers:</strong> Individual components that execute the tasks assigned by the orchestrator. Multiple workers can operate simultaneously.</li><li><strong>Result Aggregation:</strong> Collects the outputs from different workers and combines them into a final result.</li></ol><figure><img alt="Flowchart showing an input being analyzed by a central orchestrator, which dynamically assigns tasks to multiple workers. Their individual outputs are then collected and aggregated into a final response." src="https://cdn-images-1.medium.com/max/1024/1*b6s3UcVoAGiaTX4w6jCzRQ.png" /><figcaption><em>Orchestrator Workers — a central orchestrator dynamically determines subtasks and distributes them among multiple workers, whose outputs are combined into a final result.</em></figcaption></figure><h4>How Is It Different from Parallelization?</h4><p>The key difference is how subtasks are determined:</p><ul><li><strong>Parallelization:</strong> Tasks are predefined and executed simultaneously.</li><li><strong>Orchestrator Workers:</strong> Tasks are dynamically determined and assigned by a central orchestrator based on the input and current context.</li></ul><p>This pattern is useful when the number or type of subtasks cannot be determined in advance and depends on the specific request.</p><h4>5. Evaluator Optimizer</h4><p><strong>Evaluator Optimizer</strong> is a workflow pattern designed for iterative improvement.</p><p>In this pattern, a Generator LLM creates an initial draft, which is then passed to an Evaluator LLM for assessment.</p><p>The evaluator checks whether the generated output meets specific quality criteria. If the output doesn’t meet those criteria, the evaluator provides feedback, and the generator uses that feedback to create an improved version.</p><p>This process continues in a loop until the output satisfies the required criteria.</p><h4>How Does It Work?</h4><p>The workflow consists of three main steps:</p><ol><li><strong>Generator:</strong> An LLM generates an initial draft based on the given input.</li><li><strong>Evaluator:</strong> Another LLM evaluates the generated draft against predefined quality criteria.</li><li><strong>Feedback &amp; Optimization:</strong></li></ol><ul><li>If the draft meets the required criteria, the workflow returns the final output.</li><li>If the draft doesn’t meet the criteria, the evaluator provides feedback to the generator.</li><li>The generator uses the feedback to refine the draft and produces an improved version.</li></ul><p>This evaluation and refinement cycle continues until the required quality criteria are satisfied.</p><figure><img alt="Flowchart showing an input passed to a generator, followed by an evaluator that checks the generated output. The output either proceeds as the final result or loops back to the generator with feedback for improvement." src="https://cdn-images-1.medium.com/max/1024/1*D1sHU8FYtdbHMqYDwnEcVg.png" /><figcaption><em>Evaluator Optimizer — a generator creates a draft, an evaluator provides feedback, and the generator iteratively refines the output until it meets the required quality criteria.</em></figcaption></figure><h4>When Is Evaluator Optimizer Useful?</h4><p>This pattern is useful when generating a satisfactory output requires multiple rounds of evaluation and refinement.</p><p>Instead of accepting the first generated response, the workflow uses feedback to improve the result through repeated iterations.</p><h3>Graphs, Nodes, and Edges</h3><p>LangGraph represents workflows as a <strong>graph</strong>, where each node represents a task (typically implemented as a Python function), and edges determine the flow of execution between those tasks.</p><p>In simple terms:</p><ul><li><strong>Graph:</strong> Represents the complete workflow.</li><li><strong>Nodes:</strong> Represent individual tasks or operations performed within the workflow.</li><li><strong>Edges:</strong> Define the connections between nodes and determine how execution moves from one task to another.</li></ul><p>Let’s understand these concepts through a practical example.</p><h4>Example: AI-Powered Essay Evaluation System</h4><p>Consider an AI-powered learning platform designed to help students prepare for UPSC examinations.</p><p>The system generates an essay topic, collects the student’s submission, and evaluates the essay across three different dimensions:</p><ul><li><strong>Depth of Analysis:</strong> Evaluates the quality of arguments, depth of analysis, and critical thinking.</li><li><strong>Language Quality:</strong> Evaluates grammar, vocabulary, fluency, and tone.</li><li><strong>Clarity of Thought:</strong> Evaluates coherence, logical flow, and clarity of ideas.</li></ul><p>These three evaluation tasks run in parallel. Their scores are then combined to calculate the total score.</p><p>Based on the combined score, the system either approves the essay or provides feedback for improvement.</p><figure><img alt="Flowchart showing an essay evaluation system with topic generation, essay collection, three parallel evaluation tasks for depth, language, and clarity, result aggregation, conditional routing, feedback, revision, and final approval." src="https://cdn-images-1.medium.com/max/1024/1*zp9STmDfVShfL8uFOcecdg.png" /><figcaption><em>AI-Powered Essay Evaluation Workflow — a LangGraph workflow that generates an essay topic, collects a submission, evaluates it in parallel, aggregates results, and routes the student toward approval or improvement.</em></figcaption></figure><h4>Understanding the Workflow Step by Step</h4><p>Let’s break down the workflow into its individual nodes.</p><p><strong>1. GenerateTopic</strong></p><p>The system generates a relevant UPSC-style essay topic and presents it to the student.</p><p><strong>2. CollectEssay</strong></p><p>The student writes and submits an essay based on the generated topic.</p><p><strong>3. EvaluateEssay (Parallel Evaluation Block)</strong></p><p>Once the essay is submitted, three independent evaluation tasks run simultaneously:</p><ul><li><strong>EvaluateDepth:</strong> Analyzes the depth of analysis, strength of arguments, and critical thinking.</li><li><strong>EvaluateLanguage:</strong> Checks grammar, vocabulary, fluency, and tone.</li><li><strong>EvaluateClarity:</strong> Assesses coherence, logical flow, and clarity of thought.</li></ul><p><strong>4. AggregateResults</strong></p><p>After all three evaluation tasks are completed, their scores are collected and combined to generate a total score, for example, out of 15.</p><p><strong>5. ConditionalRouting</strong></p><p>The system checks the total score against a predefined threshold and determines the next execution path:</p><ul><li>If the score meets the required threshold, the workflow moves to ShowSuccess.</li><li>If the score is below the threshold, the workflow moves to GiveFeedback.</li></ul><p><strong>6. GiveFeedback</strong></p><p>If the essay doesn’t meet the required criteria, the system provides targeted suggestions to help the student improve the weaker areas.</p><p><strong>7. CollectRevision (Optional Loop)</strong></p><p>The student revises and resubmits the essay based on the feedback.</p><p>The workflow then loops back to EvaluateEssay, where the revised submission is evaluated again.</p><p><strong>8. ShowSuccess</strong></p><p>Once the essay meets the required score, the system congratulates the student and ends the workflow.</p><h4>Understanding the Graph Structure</h4><p>This example demonstrates how different graph components work together:</p><ul><li><strong>Nodes:</strong> GenerateTopic, CollectEssay, EvaluateDepth, EvaluateLanguage, EvaluateClarity, AggregateResults, GiveFeedback, and ShowSuccess represent individual tasks.</li><li><strong>Edges:</strong> Connect the nodes and define the execution flow.</li><li><strong>Parallel Execution:</strong> Allows the three essay evaluation tasks to run simultaneously.</li><li><strong>Conditional Routing:</strong> Directs the workflow toward feedback or approval based on the total score.</li><li><strong>Looping:</strong> Allows the student to revise and resubmit the essay for another evaluation.</li></ul><p>This is how LangGraph combines different execution patterns into a single workflow.</p><p>Instead of following only a fixed sequence, the graph can execute tasks in parallel, make decisions, and revisit previous steps when necessary.</p><h3>State</h3><p>In LangGraph, <strong>State</strong> is the shared memory that flows through a workflow. It holds all the data being passed between different nodes as the graph executes.</p><p>State is commonly defined using a typed dictionary (TypedDict), which specifies the structure of the information that needs to be maintained throughout the workflow.</p><p>For example, consider our AI-powered essay evaluation system.</p><p>The workflow needs to maintain information about the essay, its topic, evaluation scores, feedback, and the number of evaluation attempts.</p><p>We can represent this information using the following state structure:</p><pre>from typing import TypedDict, Annotated<br>from operator import add<br><br>class EssayState(TypedDict):<br>    essay_text: str<br>    topic: str<br>    depth_score: int<br>    language_score: int<br>    clarity_score: int<br>    total_score: int<br>    feedback: Annotated[list[str], add]<br>    evaluation_round: int</pre><h4>Understanding the State Fields</h4><p>Let’s understand what each field represents:</p><ol><li><strong>essay_text: str</strong> — Stores the essay submitted by the student.</li><li><strong>topic: str</strong> — Stores the essay topic generated by the system.</li><li><strong>depth_score: int</strong> — Stores the evaluation score for depth of analysis and critical thinking.</li><li><strong>language_score: int</strong> — Stores the evaluation score for grammar, vocabulary, fluency, and tone.</li><li><strong>clarity_score: int</strong> — Stores the evaluation score for coherence and clarity of thought.</li><li><strong>total_score: int</strong> — Stores the combined score calculated from the individual evaluation scores.</li><li><strong>feedback: Annotated[list[str], add]</strong> — Stores feedback provided to the student. The Annotated metadata associates the add reducer with this state field, allowing updates to be accumulated rather than simply replacing the existing list.</li><li><strong>evaluation_round: int</strong> — Tracks how many times the essay has gone through the evaluation process.</li></ol><h4>How Does State Work in a Workflow?</h4><p>As the graph executes, different nodes access the shared state to retrieve the information they need and return updates to it.</p><p>For example:</p><ul><li>GenerateTopic updates the topic field.</li><li>CollectEssay updates the essay_text field.</li><li>EvaluateDepth updates depth_score.</li><li>EvaluateLanguage updates language_score.</li><li>EvaluateClarity updates clarity_score.</li><li>AggregateResults calculates and updates total_score.</li><li>GiveFeedback adds suggestions to feedback.</li><li>The evaluation process updates evaluation_round.</li></ul><p>This allows information to flow between different nodes without requiring each node to independently maintain the entire workflow’s data.</p><p><strong>In short, State acts as the shared memory of a LangGraph workflow.</strong> It maintains the information required by different nodes and keeps track of the workflow as it progresses.</p><h3>Reducers</h3><p><strong>Reducers</strong> in LangGraph define how updates from nodes are applied to the shared state.</p><p>In other words, a reducer determines what happens when a node returns a new value for a particular state field.</p><p>Depending on the reducer associated with a state field, new data can:</p><ul><li><strong>Replace:</strong> Replace the existing value with a new value.</li><li><strong>Add:</strong> Append new data to the existing value.</li><li><strong>Merge:</strong> Combine new data with existing data.</li></ul><p>Each key in the state can have its own reducer, allowing different fields to handle updates differently.</p><h4>Understanding Reducers with Our Essay Evaluation Example</h4><p>Let’s revisit the state structure from our AI-powered essay evaluation system:</p><pre>from typing import TypedDict, Annotated<br>from operator import add<br><br>class EssayState(TypedDict):<br>    essay_text: str<br>    topic: str<br>    depth_score: int<br>    language_score: int<br>    clarity_score: int<br>    total_score: int<br>    feedback: Annotated[list[str], add]<br>    evaluation_round: int</pre><p>Notice this field:</p><pre>feedback: Annotated[list[str], add]</pre><p>Here:</p><ul><li>Annotated attaches additional metadata to the state field.</li><li>list[str] specifies that the field stores a list of strings.</li><li>add is the reducer associated with this field.</li></ul><p>The add operator combines the existing list with the new list instead of replacing the previous feedback.</p><p>For example, suppose the existing state contains:</p><pre>feedback = [&quot;Improve your introduction&quot;]</pre><p>A node returns another update:</p><pre>{&quot;feedback&quot;: [&quot;Add stronger supporting arguments&quot;]}</pre><p>With the add reducer, the updated feedback becomes:</p><pre>[<br>    &quot;Improve your introduction&quot;,<br>    &quot;Add stronger supporting arguments&quot;<br>]</pre><p>This allows feedback from multiple evaluation rounds to accumulate rather than overwrite previously generated suggestions.</p><h4>How Do Reducers Help?</h4><p>Consider our essay evaluation workflow:</p><ul><li>essay_text can be updated with the student&#39;s latest essay.</li><li>depth_score can be replaced with the latest evaluation score.</li><li>total_score can be updated after aggregating the evaluation results.</li><li>feedback can accumulate suggestions across multiple evaluation rounds.</li></ul><p>Different state fields can therefore follow different update strategies depending on the application’s requirements.</p><figure><img alt="Diagram illustrating LangGraph state updates with reducers, showing how node outputs are processed and applied to shared state using different update strategies." src="https://cdn-images-1.medium.com/max/1024/1*C8dinXQ-f8uadeMPkplLag.png" /><figcaption><em>Reducers in LangGraph — reducers determine how updates returned by nodes are applied to the shared state, including replacing existing values or combining new data with existing values.</em></figcaption></figure><p><strong>In short, reducers control how shared state changes over time.</strong> They are especially important when multiple nodes update the same state field or when information needs to accumulate across workflow iterations.</p><h3>LangGraph Execution Model</h3><p>LangGraph manages workflow execution through <strong>message passing and super-steps</strong>.</p><p>Super-steps are execution rounds in which multiple active nodes can run in parallel. This approach allows LangGraph to coordinate complex workflows efficiently, especially when multiple tasks need to execute simultaneously.</p><p>Let’s understand the execution process step by step.</p><h4>1. Graph Definition</h4><p>The first step is defining the graph structure.</p><p>You need to define three things:</p><ul><li><strong>State Schema:</strong> Specifies the structure of the shared state and the data maintained throughout the workflow.</li><li><strong>Nodes:</strong> Python functions that perform individual tasks or operations.</li><li><strong>Edges:</strong> Define the connections between nodes and determine how execution flows through the graph.</li></ul><p>Together, these components describe how your workflow is structured.</p><h4>2. Compilation</h4><p>Once the graph is defined, the next step is compilation.</p><p>You call .compile() on the StateGraph instance:</p><pre>app = graph.compile()</pre><p>Compilation checks the graph structure and prepares it for execution.</p><h4>3. Invocation</h4><p>After compilation, you can execute the graph using .invoke():</p><pre>result = app.invoke(initial_state)</pre><p>Here:</p><ul><li>app represents the compiled graph.</li><li>initial_state contains the initial data required by the workflow.</li></ul><p>LangGraph sends the initial state as a message to the entry node or nodes, initiating graph execution.</p><h4>4. Super-Steps Begin</h4><p>Once execution starts, LangGraph processes the workflow in rounds called <strong>super-steps</strong>.</p><p>During each super-step:</p><ul><li>All active nodes (nodes that have received messages) become eligible for execution.</li><li>Active nodes can run in parallel when the graph structure allows it.</li><li>Each node performs its assigned task and returns an update to the shared state.</li></ul><p>These updates are processed according to the reducers associated with the respective state fields.</p><h4>5. Message Passing &amp; Node Activation</h4><p>After the active nodes complete their execution, messages are passed to downstream nodes through the graph’s edges.</p><ul><li>Messages carry the information required by downstream nodes.</li><li>Nodes that receive messages become active for the next super-step.</li><li>This process continues as execution moves through the graph.</li></ul><p>This mechanism allows LangGraph to coordinate sequential and parallel operations within the same workflow.</p><h4>6. Halting Condition</h4><p>The execution process continues until the workflow reaches its termination condition.</p><p>LangGraph stops execution when:</p><ul><li>No nodes are active.</li><li>No messages are in transit.</li></ul><p>At this point, the graph has completed its execution, and the final result is returned.</p><h3>Key Takeaways</h3><ul><li><strong>LangGraph:</strong> An orchestration framework for building intelligent, stateful, and multi-step LLM workflows using a graph-based architecture.</li><li><strong>Graphs, Nodes, and Edges:</strong> A graph represents the complete workflow, nodes perform individual tasks, and edges define how execution moves between them.</li><li><strong>LLM Workflows:</strong> Complex LLM applications can be structured using different workflow patterns depending on their requirements.</li><li><strong>Prompt Chaining:</strong> Connects multiple LLM calls sequentially, where the output of one step becomes the input for the next.</li><li><strong>Routing:</strong> Directs user queries to the most appropriate tool or specialized LLM based on the input.</li><li><strong>Parallelization:</strong> Executes multiple independent subtasks simultaneously and combines their outputs.</li><li><strong>Orchestrator Workers:</strong> Uses a central orchestrator to dynamically determine subtasks and distribute them among multiple workers.</li><li><strong>Evaluator Optimizer:</strong> Improves generated outputs through repeated cycles of evaluation, feedback, and refinement.</li><li><strong>State:</strong> Acts as shared memory that holds the information passed between nodes during workflow execution.</li><li><strong>Reducers:</strong> Define how updates from nodes are applied to shared state, allowing values to be replaced, added, or merged.</li><li><strong>LangGraph Execution Model:</strong> Manages workflow execution through graph definition, compilation, invocation, super-steps, message passing, and node activation.</li></ul><p><strong>The key takeaway:</strong> LangGraph combines graphs, nodes, edges, shared state, reducers, and different LLM workflow patterns to build and execute complex Agentic AI workflows involving sequential execution, parallel processing, conditional routing, and iterative operations.</p><h3><strong>Conclusion</strong></h3><p>In this part, we explored the core concepts behind LangGraph and how it organizes complex workflows into structured, stateful graphs.</p><p>We started by understanding how LangGraph represents workflows through <strong>nodes and edges</strong>, where nodes perform individual tasks and edges define how execution moves between them.</p><p>We then explored five common LLM workflow patterns:</p><ul><li><strong>Prompt Chaining</strong> — Connecting multiple LLM calls in a sequence.</li><li><strong>Routing</strong> — Directing inputs to the appropriate path based on their content.</li><li><strong>Parallelization</strong> — Running independent tasks simultaneously.</li><li><strong>Orchestrator Workers</strong> — Dynamically assigning tasks to specialized workers.</li><li><strong>Evaluator Optimizer</strong> — Improving outputs through an evaluation and feedback loop.</li></ul><p>Next, we looked at how <strong>state</strong> acts as shared memory across a workflow, allowing nodes to access and update information as execution progresses. We also learned how <strong>reducers</strong> determine how those updates are applied, whether by replacing, adding, or merging values.</p><p>Finally, we explored the <strong>LangGraph execution model</strong>, including graph definition, compilation, invocation, super-steps, message passing, node activation, and halting.</p><p>Together, these concepts provide the foundation for understanding how LangGraph executes sequential, parallel, conditional, and iterative workflows.</p><p>With this foundation, we are ready to move beyond the core concepts and start building more practical LangGraph applications.</p><h3>What’s Next?</h3><p>In the next part of this series, <strong>Part 5: Sequential Workflows in LangGraph</strong>, we’ll move from understanding LangGraph’s core concepts to building practical sequential workflows step by step.</p><p>We’ll explore how to connect nodes in a predefined order, pass shared state between them, and execute a complete workflow using LangGraph.</p><p>To make these concepts easier to understand, we’ll build three practical examples:</p><ol><li><strong>BMI Calculator (Without LLM):</strong> Build a simple sequential workflow that calculates BMI and determines the corresponding category using Python functions.</li><li><strong>Simple QA Chatbot (With LLM):</strong> Create a chatbot that takes a user’s question, sends it to an LLM, and stores the generated answer in the workflow state.</li><li><strong>Two-Stage Blog Generation Using Prompt Chaining:</strong> Build a workflow where one LLM call generates a blog outline and another uses that outline to generate the full blog post.</li></ol><p>Along the way, we’ll work with StateGraph, TypedDict, nodes, edges, START, END, and the graph compilation and execution process.</p><blockquote><strong>Next Part:</strong> Agentic AI using LangGraph — Part 5: <strong>Sequential Workflows in LangGraph</strong></blockquote><p>By the end of Part 5, you’ll have a practical understanding of how to design and run sequential workflows in LangGraph, both with and without LLMs.</p><blockquote><strong>Series:</strong> Agentic AI using LangGraph — Part 4 of 27</blockquote><h3>Connect with me</h3><p><strong><em>Connect with me on </em></strong><a href="https://www.linkedin.com/in/shubhamnagar234/"><strong><em>LinkedIn</em></strong></a><strong><em>, </em></strong><a href="https://github.com/shubhamnagar234"><strong><em>GitHub</em></strong></a><strong><em>, </em></strong><a href="https://x.com/nagarshubham234"><strong><em>X (Twitter)</em></strong></a><strong><em>, or explore my </em></strong><a href="https://shubhamnagar234.vercel.app/"><strong><em>Portfolio</em></strong></a><strong><em>.</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=470a093d2316" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LangChain vs LangGraph: Understanding the Difference and When to Use Each — Part 3]]></title>
            <link>https://medium.com/@shubhamnagar234/langchain-vs-langgraph-understanding-the-difference-and-when-to-use-each-part-3-13fe7c424bf2?source=rss-10b51a93c3a------2</link>
            <guid isPermaLink="false">https://medium.com/p/13fe7c424bf2</guid>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[langgraph]]></category>
            <category><![CDATA[chatbots]]></category>
            <category><![CDATA[ai-agent]]></category>
            <dc:creator><![CDATA[Shubham Nagar]]></dc:creator>
            <pubDate>Wed, 04 Nov 2026 11:13:11 GMT</pubDate>
            <atom:updated>2026-11-04T11:13:39.843Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><em>From simple LLM chains to complex, stateful, and event-driven AI workflows.</em></blockquote><p>When building applications powered by Large Language Models (LLMs), frameworks like LangChain make it easier to connect models, prompts, retrievers, and other components.</p><p>However, as applications become more sophisticated, their workflows often require more than a simple sequence of operations. They may involve conditional decisions, loops, shared state, human approvals, asynchronous execution, and recovery from failures.</p><blockquote>This is where <strong>LangGraph</strong> comes into the picture.</blockquote><p>LangGraph extends the capabilities of LangChain by providing a graph-based approach to building stateful and complex AI workflows. Instead of limiting execution to a predefined sequence of steps, it allows developers to define nodes, edges, and conditional transitions that control how a workflow progresses.</p><p>In this article, we’ll understand why LangGraph exists, how it works, and how it differs from LangChain. We’ll also use an automated hiring workflow to understand why complex agentic applications need more advanced workflow orchestration.</p><h3>Overview</h3><ul><li><strong><em>Why LangGraph Exists?</em></strong></li><li><strong><em>What Is LangChain?</em></strong></li><li><strong><em>What Can You Build with LangChain?</em></strong></li><li><strong><em>Automated Hiring Workflow</em></strong></li><li><strong><em>Challenges in Building Complex AI Workflows</em></strong></li><li><strong><em>The Problem with LangChain</em></strong></li><li><strong><em>What Is LangGraph?</em></strong></li><li><strong><em>When to Use What? (LangChain vs LangGraph)</em></strong></li><li><strong><em>Should We Still Use LangChain?</em></strong></li><li><strong><em>Key Takeaways</em></strong></li><li><strong><em>Conclusion</em></strong></li><li><strong><em>What’s Next?</em></strong></li></ul><h3>Why LangGraph Exists?</h3><p>Before understanding why LangGraph exists, let’s first understand what LangChain offers and where it fits when building LLM-powered applications.</p><figure><img alt="LangChain vs LangGraph" src="https://cdn-images-1.medium.com/max/1024/1*SOS4kpuJvQXCHynQTnGlhQ.png" /><figcaption>LangChain vs LangGraph</figcaption></figure><h3>What Is LangChain?</h3><p><strong>LangChain</strong> is an open-source library designed to simplify the process of building applications powered by Large Language Models (LLMs).</p><p>It provides modular building blocks that allow developers to connect different components and create sophisticated LLM-based workflows without implementing everything from scratch.</p><p>LangChain consists of several components:</p><ol><li><strong>Models:</strong> Provide a unified interface to interact with different LLM providers.</li><li><strong>Prompts:</strong> Help developers design, structure, and manage prompts for language models.</li><li><strong>Retrievers:</strong> Help fetch relevant documents from sources such as vector stores.</li></ol><blockquote>However, one of LangChain’s biggest offerings is <strong>Chains</strong>.</blockquote><p>Chains allow developers to combine multiple components into a sequence of operations, where the output of one step can become the input of the next.</p><h3>What Can You Build with LangChain?</h3><p>LangChain is useful for building several types of LLM-powered applications, including:</p><ol><li><strong>Simple Conversational Workflows:</strong> Chatbots and text summarizers.</li><li><strong>Multi-step Workflows:</strong> Applications that require multiple sequential operations.</li><li><strong>RAG Applications:</strong> Systems that retrieve relevant information and use it to generate context-aware responses.</li><li><strong>Basic Agents:</strong> Agents that can reason about tasks and use tools at a basic level.</li></ol><p>For many applications, these capabilities are sufficient.</p><blockquote>But what happens when a workflow becomes more complex?</blockquote><p>What if it needs conditional decisions, repeated execution, human approvals, long waiting periods, and the ability to resume from where it stopped?</p><p>Let’s understand this through a practical example.</p><h3>Automated Hiring Workflow</h3><p>Consider a company that wants to automate its recruitment process for hiring a Backend Engineer.</p><p>A typical hiring process involves multiple stages, but these stages don’t always follow a simple, fixed sequence. Some steps require decisions, some need to be repeated, and others depend on external events or human approvals.</p><p>For example, the system may need to regenerate a Job Description (JD) if a human supervisor doesn’t approve it. Similarly, if the number of applications is insufficient, it may need to modify the JD and wait for more applications.</p><figure><img alt="Flowchart illustrating an automated hiring process, from receiving a hiring request and creating an approved job description to posting the job, monitoring applications, shortlisting candidates, conducting interviews, sending offer letters, handling negotiations, and onboarding the selected candidate." src="https://cdn-images-1.medium.com/max/906/1*bKEugiX_ldPgS4Ig8ABP1w.png" /><figcaption><em>Automated Hiring Workflow — a recruitment pipeline involving conditional decisions, repeated execution, human approvals, and multiple stages.</em></figcaption></figure><h4>Key Stages of the Automated Hiring Workflow</h4><p>Let’s break down the major stages of this workflow:</p><ol><li><strong>Hiring Request &amp; JD Creation:</strong> The system receives a hiring request and generates a Job Description (JD). The generated JD is then sent to a human supervisor for approval.</li><li><strong>Job Posting:</strong> Once approved, the system uses API tools, such as LinkedIn or Naukri, to publish the job description automatically.</li><li><strong>Monitoring &amp; Application Tracking:</strong> The workflow waits for seven days to collect applications and then checks the application count using an API. If there aren’t enough applications, it can modify the JD and repeat the process.</li><li><strong>Interview Coordination:</strong> The system manages interview-related activities, including providing question banks, scheduling interviews, and tracking candidate progress.</li><li><strong>Selection &amp; Offer Management:</strong> Based on interview performance, candidates are either sent rejection emails or moved to the offer-generation stage. The system can also handle salary negotiations and track offer acceptance.</li><li><strong>Onboarding:</strong> Once a candidate accepts the offer, the system integrates with an HR Management System to automate activities such as welcome emails, knowledge-transfer sessions, and resource provisioning.</li></ol><p>This workflow demonstrates that real-world AI applications often involve much more than executing a fixed sequence of operations.</p><p>They need to make decisions, repeat certain steps, maintain information across multiple stages, and respond to external events.</p><h3>Challenges in Building Complex AI Workflows</h3><h4>Challenge #1 — Control Flow Complexity</h4><p>One of the biggest challenges in building complex AI workflows is managing how execution moves from one step to another.</p><p>Standard LangChain chains are primarily designed to execute operations in a predefined sequence. However, our automated hiring workflow requires more flexible execution because not every step follows a fixed path.</p><p>For example:</p><ul><li>If the generated Job Description (JD) is not approved, the system must go back, regenerate the JD, and request approval again.</li><li>If enough applications are received, the workflow proceeds to shortlisting and interview scheduling.</li><li>If there aren’t enough applications, the system modifies the JD, waits for another 48 hours, and checks the applications again.</li><li>Based on interview results, candidates follow different paths, such as receiving a rejection email or moving to offer generation.</li><li>If an offer is rejected, the system may need to renegotiate and send another offer.</li></ul><p>These scenarios introduce three important control-flow requirements:</p><p><strong>1. Conditional Branches</strong></p><p>The workflow must make decisions based on conditions and route execution accordingly.</p><p>For example, if the JD is approved, the system proceeds to job posting. Otherwise, it returns to JD creation.</p><p><strong>2. Loops</strong></p><p>Some steps need to be repeated until a particular condition is satisfied.</p><p>For example, if the number of applications is insufficient, the system modifies the JD and repeats the monitoring process until enough applications are received.</p><p><strong>3. Jumps</strong></p><p>The workflow sometimes needs to move between different stages depending on the outcome of an operation rather than simply executing the next step in sequence.</p><p>For example, after an interview, a selected candidate moves toward offer generation, while an unsuccessful candidate receives a rejection email.</p><figure><img alt="Diagram comparing a complex automated hiring workflow with its core Python pseudocode and LangGraph state graph, illustrating nodes, edges, conditional routing, and a loop that regenerates a job description when approval is not granted." src="https://cdn-images-1.medium.com/max/1024/1*2uEBmK6sdq7QthP5EWhU8A.png" /><figcaption><em>Control Flow Complexity — an automated hiring workflow requires conditional branches, loops, and jumps to manage different execution paths.</em></figcaption></figure><p>Managing all these execution paths using standard sequential chains can become difficult as the workflow grows.</p><p><strong>LangGraph solves this problem through its graph-based structure</strong>, where developers define nodes for individual operations and edges to control how execution moves between them. Conditional edges allow the workflow to choose different paths, while loops allow it to revisit previous steps when necessary.</p><h4>Challenge #2 — Handling State</h4><p>Another major challenge in building complex AI workflows is <strong>state management</strong>.</p><p>Consider our automated hiring workflow. The recruitment process may take several days or even weeks to complete. During this time, the system needs to remember what has already happened, what is currently happening, and what still needs to be done.</p><p>For example, it needs to keep track of:</p><ul><li>The original hiring goal.</li><li>The generated Job Description (JD) and its approval status.</li><li>Whether the JD has been posted.</li><li>The number of applications received.</li><li>The shortlisted candidates and their evaluation scores.</li><li>Interview questions and candidate progress.</li><li>Offer status, including acceptance and renegotiation.</li><li>Onboarding status.</li></ul><p>Every step of this multi-day process needs access to relevant information and must be able to update it as the workflow progresses.</p><p>This is where <strong>LangGraph’s shared state object</strong> becomes important.</p><p>Unlike the stateless nature of traditional LangChain chains, LangGraph is stateful. It allows every node in the graph to access and modify a shared state object, making it easier to maintain information across different stages of a workflow.</p><h4>Understanding the Workflow State</h4><p>Let’s represent the state of our automated hiring workflow using a Python dictionary:</p><pre>state = {<br>    &quot;goal&quot;: &quot;Hire a backend software engineer&quot;,<br>    &quot;jd&quot;: &quot;&quot;,  # Job description text<br>    &quot;jd_approved&quot;: False,<br>    &quot;jd_posted&quot;: False,<br>    &quot;min_applicants&quot;: 5,<br>    &quot;num_applications&quot;: 0,<br>    &quot;shortlisted_candidates&quot;: {<br>        # &quot;candidate_id&quot;: {&quot;name&quot;: ..., &quot;score&quot;: ..., &quot;status&quot;: ...}<br>    },<br>    &quot;interview_questions&quot;: [],<br>    &quot;offer_status&quot;: {<br>        &quot;sent&quot;: False,<br>        &quot;accepted&quot;: False,<br>        &quot;renegotiated&quot;: False<br>    },<br>    &quot;onboarding_status&quot;: {<br>        &quot;completed&quot;: False,<br>        &quot;start_date&quot;: None,<br>        &quot;employee_id&quot;: None<br>    }<br>}</pre><p>Let’s understand what this state object stores:</p><ol><li><strong>Goal:</strong> Defines the primary objective of the workflow — hiring a Backend Engineer.</li><li><strong>JD Information:</strong> Stores the generated job description and tracks whether it has been approved and posted.</li><li><strong>Application Tracking:</strong> Maintains the minimum required number of applicants and the actual number of applications received.</li><li><strong>Shortlisted Candidates:</strong> Stores candidate information, including their names, evaluation scores, and current status.</li><li><strong>Interview Questions:</strong> Maintains the questions prepared for the interview process.</li><li><strong>Offer Status:</strong> Tracks whether an offer has been sent, accepted, or renegotiated.</li><li><strong>Onboarding Status:</strong> Tracks onboarding completion, the employee’s start date, and employee ID.</li></ol><h4>How Does Shared State Help?</h4><p>As the workflow progresses, individual nodes can read the information they need and update the relevant fields.</p><p>For example:</p><ul><li>The JD creation node generates a description and updates the jd field.</li><li>The approval node updates jd_approved.</li><li>The job posting node updates jd_posted.</li><li>The application monitoring node updates num_applications.</li><li>The shortlisting node updates shortlisted_candidates.</li><li>The offer management node updates offer_status.</li><li>The onboarding node updates onboarding_status.</li></ul><p>This allows different nodes to work with the same workflow information without losing track of previous progress.</p><figure><img alt="Diagram showing an automated hiring workflow state dictionary, how state is used as conversation context, and how LangGraph connects state, workflow logic, and graph memory. It also illustrates TypedDict, Pydantic, state update modes, and the typical state flow." src="https://cdn-images-1.medium.com/max/1024/1*IlL0-UGHx5u2dCN1VOP_Lg.png" /><figcaption><em>Handling State in LangGraph — a shared state object maintains workflow information, enables nodes to access and update data, and supports persistent execution through graph memory and checkpointing.</em></figcaption></figure><blockquote><strong>In short, LangGraph makes state explicit and allows it to be shared across nodes.</strong> This is particularly important for complex workflows where information must be maintained and updated across multiple stages.</blockquote><h4>Challenge #3 — Event-Driven Execution</h4><p>In real-world applications, workflows don’t always execute continuously from beginning to end.</p><blockquote>Sometimes, a workflow needs to <strong>pause and wait for something to happen</strong> before it can continue.</blockquote><p>Consider our automated hiring workflow.</p><p>After posting a Job Description (JD), the system needs to wait for applications to arrive. Instead of continuously checking for new applications, it can enter a waiting state for a specific period, such as seven days.</p><p>Similarly, the workflow may need to pause when:</p><ul><li>A human supervisor needs to review and approve a Job Description.</li><li>The system is waiting for candidates to submit their applications.</li><li>An interviewer needs to provide feedback.</li><li>A candidate needs to respond to an offer letter.</li></ul><p>Once the required event occurs or the waiting period ends, the workflow should resume from exactly where it stopped.</p><h4>How Does LangGraph Handle This?</h4><p>LangGraph supports this type of execution through its <strong>checkpointing system</strong>.</p><p>Checkpointing allows the workflow’s state to be saved at different points during execution. When the workflow needs to pause, its progress can be preserved so that it can resume later without starting the entire process again.</p><p>For example:</p><ol><li>The system generates a Job Description.</li><li>The workflow pauses while waiting for human approval.</li><li>The supervisor reviews and approves the JD.</li><li>The workflow resumes from the approval stage and proceeds to job posting.</li><li>After posting, the system waits for seven days to collect applications.</li><li>Once the waiting period ends, the workflow resumes and checks the application count.</li></ol><p>This makes it possible to build workflows that can handle long-running processes and external interactions.</p><figure><img alt="Diagram illustrating a LangGraph workflow that pauses at a human approval checkpoint, waits for an external event or a specified period, and resumes execution using the saved workflow state." src="https://cdn-images-1.medium.com/max/1024/1*xgklvBfln-iOLkzHfCGkqw.png" /><figcaption><em>Event-Driven Execution in LangGraph — a workflow can pause while waiting for human input or external events, preserve its progress through checkpoints, and resume execution when the required condition is met.</em></figcaption></figure><blockquote><strong>In short, event-driven execution allows workflows to respond to events rather than relying only on continuous, sequential execution.</strong> Combined with checkpointing, it helps LangGraph manage workflows that may run across multiple days and require external input before proceeding.</blockquote><h4>Challenge #4 — Fault Tolerance</h4><p>Another important challenge in building long-running AI workflows is handling unexpected errors and system failures.</p><p>Consider our automated hiring workflow. The recruitment process may run for several days or weeks and involve multiple operations, such as generating job descriptions, posting jobs, tracking applications, scheduling interviews, and managing offers.</p><p>During this process, several things can go wrong:</p><ul><li>An external API might temporarily become unavailable.</li><li>A job-posting request might fail.</li><li>The application monitoring service might encounter an error.</li><li>The system might crash while processing candidate information.</li></ul><p>Without proper fault tolerance, such failures could interrupt the entire workflow and potentially cause previously completed steps to be repeated.</p><h4>How Does LangGraph Handle This?</h4><p>LangGraph provides mechanisms for <strong>checkpointing, retries, and recovery</strong> to make long-running workflows more reliable.</p><p>Let’s understand how these mechanisms help:</p><p><strong>1. Checkpointing</strong></p><p>LangGraph saves the workflow’s state at different points during execution.</p><p>If the system crashes, the previously saved checkpoint allows the workflow to recover its progress instead of starting everything from scratch.</p><p>For example, if the system crashes after successfully posting a job, it can recover the saved state and continue from the subsequent stage rather than generating and posting the same JD again.</p><p><strong>2. Retries</strong></p><p>When an operation fails temporarily, retry mechanisms allow the system to attempt that operation again.</p><p>For example, if the LinkedIn API temporarily fails while posting a job, the workflow can retry the operation instead of immediately terminating the entire process.</p><p><strong>3. Recovery from System Failures</strong></p><p>By combining saved checkpoints with recovery mechanisms, LangGraph helps workflows continue from their previously saved progress after an interruption.</p><figure><img alt="Diagram illustrating fault tolerance in LangGraph, showing workflow execution, state checkpoints, error handling, retries, and recovery from a system failure." src="https://cdn-images-1.medium.com/max/1024/1*vGMgLacM7oEzahw1yilHqA.png" /><figcaption><em>Fault Tolerance in LangGraph — checkpointing preserves workflow progress, retries handle temporary failures, and recovery allows execution to continue after system interruptions.</em></figcaption></figure><blockquote><strong>In short, fault tolerance helps make long-running workflows more resilient.</strong> Instead of losing all progress when an error or crash occurs, the system can use saved checkpoints and retry mechanisms to continue execution more reliably.</blockquote><h4>Challenge #5 — Human-in-the-Loop</h4><p>Another important requirement in complex AI workflows is <strong>human involvement in critical decisions</strong>.</p><p>Although AI agents can perform tasks autonomously, certain actions should not be executed without human supervision or approval.</p><p>Consider our automated hiring workflow.</p><p>The system can independently generate job descriptions, post job openings, shortlist candidates, and coordinate interviews. However, some decisions may require a human supervisor’s approval.</p><p>For example:</p><ul><li><strong>JD Approval:</strong> Before publishing a job description, the system pauses and waits for the HR manager to review and approve it.</li><li><strong>Candidate Selection:</strong> Before moving forward with a final candidate, the system can request confirmation from the hiring manager.</li><li><strong>Offer Approval:</strong> Before sending an offer letter, the system waits for human approval of the salary and employment terms.</li></ul><h4>How Does LangGraph Handle This?</h4><p>LangGraph provides a native <strong>Human-in-the-Loop (HITL)</strong> capability that allows a workflow to pause and wait for human input or approval.</p><p>Unlike a simple automated process that continues executing without supervision, a LangGraph workflow can pause at a specific point and wait indefinitely until a human provides the required response.</p><p>For example, when the system generates a Job Description:</p><ol><li>The workflow generates the JD.</li><li>It pauses and presents the generated JD to a human supervisor.</li><li>The supervisor reviews the JD and provides approval or requests changes.</li><li>Once the required human input is received, the workflow resumes execution.</li><li>If changes are requested, the system can revise the JD and submit it for approval again.</li></ol><p>This ensures that important decisions remain under human control while allowing the rest of the workflow to run autonomously.</p><figure><img alt="Diagram illustrating a LangGraph workflow with a human approval step, showing the system pausing after generating a job description, waiting for human input, and continuing or revising the workflow based on the decision." src="https://cdn-images-1.medium.com/max/1024/1*oVvHNgKAd-EKqU7zxccHPA.png" /><figcaption><em>Human-in-the-Loop in LangGraph — a workflow pauses at a designated checkpoint, waits for human approval or feedback, and resumes execution based on the response.</em></figcaption></figure><blockquote><strong>In short, Human-in-the-Loop allows developers to combine AI autonomy with human supervision.</strong> It is particularly useful when building real-world applications where critical actions require approval, validation, or human judgment.</blockquote><h4>Challenge #6 — Nested Workflows</h4><p>As workflows grow in complexity, managing every operation inside a single graph can become difficult.</p><p>Consider our automated hiring workflow. It consists of several major stages, such as:</p><ul><li>Job Description creation and approval.</li><li>Job posting and application tracking.</li><li>Candidate shortlisting.</li><li>Interview coordination and evaluation.</li><li>Offer generation and negotiation.</li><li>Employee onboarding.</li></ul><p>Each of these stages can involve multiple operations and decision-making steps of its own.</p><p>Instead of placing every operation inside one large graph, we can divide the workflow into smaller, independent graphs and combine them into a larger workflow.</p><blockquote>This is where <strong>Nested Workflows</strong> become useful.</blockquote><p>LangGraph allows developers to create modular and reusable graphs within a larger graph, making it easier to organize complex applications, including multi-agent systems.</p><figure><img alt="Diagram illustrating a parent LangGraph workflow containing multiple nested graphs, where individual sub-workflows handle different stages of a larger process." src="https://cdn-images-1.medium.com/max/1024/1*F-EZmuvFpwBiT6x2iiukMg.png" /><figcaption><em>Nested Workflows in LangGraph — a complex workflow can be divided into smaller, modular graphs, with each graph responsible for a specific part of the overall process.</em></figcaption></figure><h4>Subgraphs</h4><p>To understand nested workflows, we first need to understand <strong>Subgraphs</strong>.</p><blockquote><strong>A subgraph is a graph that is used as a node in another graph.</strong></blockquote><p>This is the concept of encapsulation applied to LangGraph. Instead of exposing every internal operation of a workflow to the parent graph, we can encapsulate those operations inside a subgraph and use that subgraph as a single node.</p><p>For example, in our automated hiring workflow:</p><ul><li>A <strong>JD Creation Subgraph</strong> can handle generating, reviewing, and revising job descriptions.</li><li>A <strong>Candidate Evaluation Subgraph</strong> can manage resume screening, scoring, and shortlisting.</li><li>An <strong>Interview Subgraph</strong> can coordinate interview scheduling and evaluation.</li><li>An <strong>Onboarding Subgraph</strong> can manage employee onboarding activities.</li></ul><p>The parent graph coordinates these subgraphs, while each subgraph manages its own internal operations.</p><figure><img alt="Diagram showing a parent graph containing a subgraph as one of its nodes. The subgraph has its own internal nodes and connections, illustrating how smaller graphs can be encapsulated within a larger workflow." src="https://cdn-images-1.medium.com/max/1024/1*BuR58CTi_re7DuNy4umy6w.png" /><figcaption><em>Subgraphs in LangGraph — a subgraph is used as a node inside a parent graph, allowing complex workflows to be divided into smaller, encapsulated components.</em></figcaption></figure><p>This approach makes it easier to build, organize, maintain, and reuse complex workflows without putting all the logic into a single graph.</p><blockquote><strong>In short, nested workflows and subgraphs help developers manage complexity through modular design.</strong> They are particularly useful when building large-scale applications with multiple interconnected components or agents.</blockquote><h4>Challenge #7 — Observability</h4><p>The final challenge is <strong>Observability</strong>.</p><blockquote>Observability refers to how easily developers can monitor, debug, and understand what a workflow is doing at runtime.</blockquote><p>Consider our automated hiring workflow. It involves multiple nodes, conditional branches, external API calls, human approvals, and long-running operations.</p><p>If something goes wrong, developers need to investigate questions such as:</p><ul><li>Which node was executed?</li><li>What happened at each stage of the workflow?</li><li>Where did an error occur?</li><li>What data was passed between different steps?</li><li>Why did the workflow take a particular execution path?</li><li>Did the workflow successfully complete its intended operation?</li></ul><p>Without proper observability, debugging such complex workflows can become difficult, especially when developers rely on manually written logging and monitoring code.</p><h4>How Does LangGraph Handle This?</h4><p>LangGraph has tight integration with <strong>LangSmith</strong>, which provides visibility into workflow execution.</p><p>It allows developers to inspect individual steps, trace execution paths, identify errors, and understand how different components interact during runtime.</p><p>For example, if our automated hiring workflow fails while scheduling an interview, developers can inspect the execution trace to understand which operation failed and investigate the cause.</p><p>This makes debugging, monitoring, and auditing complex workflows much easier compared to relying entirely on manually written glue code.</p><figure><img alt="Diagram illustrating LangGraph observability through LangSmith, showing workflow execution traces, individual nodes, intermediate steps, and monitoring information used for debugging and understanding application behavior." src="https://cdn-images-1.medium.com/max/1024/1*aEIxfZpUfHLrs-Hn1jke5Q.png" /><figcaption><em>Observability in LangGraph — integration with LangSmith provides visibility into workflow execution, helping developers monitor, trace, and debug individual steps.</em></figcaption></figure><blockquote><strong>In short, observability helps developers understand what is happening inside their AI workflows.</strong> With LangSmith integration, they can inspect execution details and debug complex workflows more effectively.</blockquote><h3>The Problem with LangChain</h3><p>LangChain is excellent for building LLM-powered applications using modular components and linear chains. It provides useful building blocks for connecting language models, prompts, retrievers, tools, and other components.</p><p>However, as applications become more complex, workflows often require capabilities beyond simple sequential execution.</p><p>Consider the automated hiring workflow we explored throughout this article. It requires:</p><ul><li><strong>Conditional Branching:</strong> Making decisions and routing execution through different paths.</li><li><strong>Loops:</strong> Repeating operations, such as regenerating a Job Description until it gets approved.</li><li><strong>State Management:</strong> Maintaining and updating candidate information and workflow progress across multiple stages.</li><li><strong>Event-Driven Execution:</strong> Pausing and resuming workflows based on external events or human input.</li><li><strong>Fault Tolerance:</strong> Recovering from errors and system crashes without losing previously saved progress.</li><li><strong>Human-in-the-Loop:</strong> Waiting for human approval before executing critical actions.</li><li><strong>Nested Workflows:</strong> Organizing complex processes into smaller, reusable graphs.</li><li><strong>Observability:</strong> Monitoring, debugging, and understanding workflow execution.</li></ul><p>Managing all these requirements using standard LangChain chains can become difficult.</p><p>While LangChain provides the building blocks for creating LLM-based applications, it does not offer the same built-in graph-based workflow orchestration capabilities needed to manage complex, non-linear logic and long-running stateful processes.</p><blockquote>This is the problem <strong>LangGraph</strong> is designed to address.</blockquote><h3>What Is LangGraph?</h3><p><strong>LangGraph</strong> is an orchestration framework that enables developers to build <strong>stateful, multi-step, and event-driven workflows</strong> using Large Language Models (LLMs).</p><p>It is designed for building both <strong>single-agent and multi-agent Agentic AI applications</strong>, where workflows may involve complex decisions, multiple execution paths, and interactions between different components.</p><h4>Think of LangGraph as a Flowchart Engine for LLMs</h4><p>A simple way to understand LangGraph is to think of it as a <strong>flowchart engine for LLMs</strong>.</p><p>Just like a flowchart represents a process through connected steps and decision points, LangGraph represents an AI workflow using:</p><ul><li><strong>Nodes:</strong> Define the individual steps or operations in a workflow.</li><li><strong>Edges:</strong> Define how different nodes are connected and how execution moves between them.</li><li><strong>Conditional Edges:</strong> Define the logic that determines which path the workflow should follow based on specific conditions.</li></ul><p>You define the steps, connections, and transition logic. LangGraph manages the execution of the workflow.</p><p>It also provides important capabilities such as:</p><ul><li><strong>State Management:</strong> Maintains shared state across different steps of a workflow.</li><li><strong>Conditional Branching:</strong> Routes execution through different paths based on conditions.</li><li><strong>Looping:</strong> Allows workflows to repeat specific operations when necessary.</li><li><strong>Pausing and Resuming:</strong> Enables workflows to pause and continue later, including when waiting for human input or external events.</li><li><strong>Fault Recovery:</strong> Uses checkpoints to preserve progress and support recovery from failures.</li></ul><p>These capabilities make LangGraph suitable for building robust, production-grade AI systems that require more than simple sequential execution.</p><h4>Built on Top of LangChain</h4><p>LangGraph is a powerful library built on top of <strong>LangChain</strong>. It treats AI workflows as graphs consisting of nodes and edges, making it suitable for managing complex, stateful applications.</p><p>Rather than replacing LangChain, LangGraph extends the workflow orchestration capabilities available to developers.</p><p>This allows developers to use LangChain’s building blocks while relying on LangGraph to coordinate how different steps of an AI application are executed.</p><h3>When to Use What? (<strong><em>LangChain vs LangGraph)</em></strong></h3><p>Both LangChain and LangGraph are useful for building LLM-powered applications, but they are designed to address different workflow requirements.</p><h4>When to Use LangChain?</h4><p>Use <strong>LangChain</strong> when you’re building <strong>simple, linear workflows</strong> where operations follow a predefined sequence.</p><p>For example:</p><ul><li><strong>Prompt Chains:</strong> Connecting multiple prompts where the output of one step becomes the input of the next.</li><li><strong>Text Summarizers:</strong> Processing text and generating a summary.</li><li><strong>Basic Retrieval Systems:</strong> Retrieving relevant documents and passing them to an LLM to generate a response.</li></ul><p>For these use cases, LangChain provides the necessary building blocks without requiring a more complex workflow orchestration structure.</p><h4>When to Use LangGraph?</h4><p>Use <strong>LangGraph</strong> when your application involves <strong>complex, non-linear workflows</strong> that require more control over execution.</p><p>It is particularly useful when your workflow needs:</p><ol><li><strong>Conditional Paths:</strong> Routing execution through different paths based on conditions or decisions.</li><li><strong>Loops:</strong> Repeating specific operations until a particular condition is satisfied.</li><li><strong>Human-in-the-Loop Steps:</strong> Pausing workflows to request human input, review, or approval.</li><li><strong>Multi-Agent Coordination:</strong> Managing interactions and collaboration between multiple agents.</li><li><strong>Asynchronous or Event-Driven Execution:</strong> Pausing and resuming workflows based on external events or user input.</li></ol><p>For example, our automated hiring workflow requires conditional decisions, repeated operations, human approvals, and long-running execution. These requirements make LangGraph a better fit for orchestrating the overall process.</p><p><strong>The key distinction:</strong> Use LangChain for building simple, sequential LLM workflows, and use LangGraph when you need to manage complex workflows with branching, loops, state, and coordination.</p><h3>Should We Still Use LangChain?</h3><p><strong>Yes! Absolutely.</strong></p><blockquote><strong>LangGraph</strong> is built on top of <strong>LangChain</strong>, but it doesn’t replace it.</blockquote><p>Even when building applications with LangGraph, you’ll continue using LangChain components to perform individual operations within your workflows.</p><p>Some commonly used LangChain components include:</p><ul><li><strong>ChatOpenAI:</strong> Interacting with OpenAI language models.</li><li><strong>PromptTemplate:</strong> Creating and managing reusable prompts.</li><li><strong>Retrievers:</strong> Fetching relevant documents from knowledge sources.</li><li><strong>DocumentLoaders:</strong> Loading documents from different data sources.</li><li><strong>Tools:</strong> Enabling AI applications to interact with external systems and perform specific actions.</li></ul><p>These components provide the building blocks needed to develop individual steps of an AI application, while LangGraph manages how those steps are connected and executed.</p><p>Think of it this way:</p><blockquote><strong>LangGraph handles workflow orchestration, while LangChain provides the building blocks for each step in the workflow.</strong></blockquote><p>Therefore, LangChain and LangGraph are complementary technologies. You don’t need to choose one and completely abandon the other. Instead, you can use both together to build more capable and flexible Agentic AI applications.</p><h3>Key Takeaways</h3><ul><li><strong>LangChain</strong> is an open-source library that provides modular building blocks for developing LLM-powered applications, including models, prompts, retrievers, and chains.</li><li><strong>LangGraph</strong> is an orchestration framework built on top of LangChain that enables developers to create stateful, multi-step, and event-driven AI workflows.</li><li><strong>Control Flow Complexity:</strong> LangGraph supports conditional branching, loops, and jumps, making it easier to manage non-linear workflows.</li><li><strong>State Management:</strong> Its shared state object allows different nodes to access and update workflow information.</li><li><strong>Event-Driven Execution:</strong> Workflows can pause for external events or human input and resume from where they stopped using checkpointing.</li><li><strong>Fault Tolerance:</strong> Checkpointing and retry mechanisms help workflows recover from errors and system interruptions.</li><li><strong>Human-in-the-Loop:</strong> Workflows can pause until a human provides the required approval or input.</li><li><strong>Nested Workflows:</strong> Subgraphs allow developers to build modular and reusable graphs within larger workflows.</li><li><strong>Observability:</strong> Integration with LangSmith provides visibility into workflow execution, making monitoring and debugging easier.</li><li><strong>When to Use LangChain:</strong> Choose LangChain for simple, linear workflows such as prompt chains, text summarizers, and basic retrieval systems.</li><li><strong>When to Use LangGraph:</strong> Choose LangGraph for complex, non-linear workflows involving conditional paths, loops, human approvals, multi-agent coordination, and event-driven execution.</li><li><strong>They Work Together:</strong> LangGraph does not replace LangChain. LangChain provides the building blocks, while LangGraph handles workflow orchestration.</li></ul><p><strong>The key takeaway:</strong> LangChain helps you build the individual components of an LLM-powered application, while LangGraph helps you connect and orchestrate those components into complex, stateful, and reliable AI workflows.</p><h3>Conclusion</h3><p>Building simple LLM-powered applications is relatively straightforward with LangChain. It provides modular components that help developers work with language models, prompts, retrievers, tools, and chains.</p><p>However, as AI applications become more sophisticated, their workflows require more than sequential execution. They need conditional branching, loops, shared state, event-driven execution, human approvals, fault recovery, and observability.</p><blockquote>This is where <strong>LangGraph</strong> becomes important.</blockquote><p>With its graph-based architecture, LangGraph makes it possible to build stateful, multi-step, and event-driven workflows. Its nodes, edges, shared state, checkpointing, and subgraphs provide the flexibility needed to orchestrate complex single-agent and multi-agent applications.</p><blockquote>But the important thing to remember is that <strong>LangGraph does not replace LangChain</strong>.</blockquote><p>Both frameworks serve different but complementary purposes:</p><ul><li><strong>LangChain</strong> provides the building blocks for individual operations within an AI application.</li><li><strong>LangGraph</strong> manages how those operations are connected, coordinated, and executed.</li></ul><p>Understanding the difference between these two frameworks is an important step toward building more advanced Agentic AI applications.</p><p>Rather than choosing one over the other, developers can combine their strengths to build flexible, stateful, and reliable AI workflows.</p><p>In the next part of this series, we’ll move beyond the fundamentals and start exploring how to build Agentic AI applications using LangGraph.</p><h3>What’s Next?</h3><p>In the next part of this series, we’ll dive into <strong>LangGraph Core Concepts</strong> and understand how LangGraph structures and executes AI workflows.</p><p>We’ll start by understanding what LangGraph is and how it represents application logic using graphs, nodes, and edges.</p><p>Then, we’ll explore different types of LLM workflows and how they help us build complex AI applications:</p><ul><li><strong>Prompt Chaining:</strong> Executing multiple LLM calls sequentially, where the output of one step becomes the input of the next.</li><li><strong>Routing:</strong> Directing user queries to the appropriate tools or specialized LLMs based on their requirements.</li><li><strong>Parallelization:</strong> Running multiple independent tasks simultaneously and combining their results.</li><li><strong>Orchestrator Workers:</strong> Using a central orchestrator to dynamically assign tasks to different workers.</li><li><strong>Evaluator Optimizer:</strong> Improving generated outputs through an iterative cycle of evaluation and feedback.</li></ul><p>We’ll also build an understanding of some fundamental LangGraph concepts:</p><ul><li><strong>Graphs, Nodes, and Edges:</strong> Understanding how workflows are represented and connected.</li><li><strong>State:</strong> Learning how shared data flows between nodes during workflow execution.</li><li><strong>Reducers:</strong> Understanding how updates from different nodes are applied to shared state.</li><li><strong>LangGraph Execution Model:</strong> Exploring graph definition, compilation, invocation, super-steps, message passing, and workflow termination.</li></ul><blockquote><strong>Next Part:</strong> Agentic AI using LangGraph — Part 4: <strong>LangGraph Core Concepts</strong></blockquote><p>By the end of Part 4, we’ll have a clearer understanding of how LangGraph works internally and how its core concepts come together to power Agentic AI applications.</p><blockquote><strong>Series:</strong> Agentic AI using LangGraph — Part 3 of 27</blockquote><h3>Connect with me</h3><p><strong><em>Connect with me on </em></strong><a href="https://www.linkedin.com/in/shubhamnagar234/"><strong><em>LinkedIn</em></strong></a><strong><em>, </em></strong><a href="https://github.com/shubhamnagar234"><strong><em>GitHub</em></strong></a><strong><em>, </em></strong><a href="https://x.com/nagarshubham234"><strong><em>X (Twitter)</em></strong></a><strong><em>, or explore my </em></strong><a href="https://shubhamnagar234.vercel.app/"><strong><em>Portfolio</em></strong></a><strong><em>.</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=13fe7c424bf2" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>