Lang-Graph




LangGraph: From State, Nodes, and Edges to a Practical AI Agent

A hands-on guide to understanding LangGraph by building workflows step by step—from basic state and routing to loops, memory, human approval, tools, and a complete interactive agent.

Building an AI agent is not only about calling an LLM. Real agents need memory, routing, tools, retries, approval checkpoints, and a reliable way to move from one task to the next. LangGraph provides a graph-based way to model those behaviors explicitly.

This guide starts with the core mental model and gradually turns those concepts into working Python examples.

Pre-requisites
Before we start with LangGraph, this demo is used in Jupyter Notebook, also make sure you have OpenAI API Key, Gain enough knowledge on Python OOPS, also learn about LangChain

LangGraph: Building AI Agents as Stateful Workflows

The Mental Model: How LangGraph Organizes an AI Agent

Node
The present task or unit of work.
Edge
The path that determines the next task.
State
The memory or context carried through the workflow.
Transition
The rule that moves execution from one node to another.

Key Features of LangGraph

Looping and Branching — Model conditions and loops

State persistence

Human in the loop

Streaming outputs

LangGraph: Loop, Pause, Retry, and Streaming

StateGraph: The Heart of a LangGraph Workflow

Define states - input  ,output , context

Define Nodes

Define Transition or edges

%pip install -U langgraph langchain-openai
import os

os.environ["OPENAI_API_KEY"] = "YOUR_API_KEY_HERE"
from typing import TypedDict

from langgraph.graph import StateGraph, START, END
from langchain_openai import ChatOpenAI

class State(TypedDict):
    question: str
    greeting: str
    answer: str

llm = ChatOpenAI(model="gpt-5.4-mini")

def greet(state: State):
    print("➡️ Greet node running...")
    
    return {
        "greeting": "Hello! Welcome to LangGraph."
    }

def answer(state: State):
    print("➡️ Answer node running...")
    
    prompt = f"""
    {state["greeting"]}

    Answer this question clearly and briefly:

    {state["question"]}
    """
    
    response = llm.invoke(prompt)

    return {
        "answer": response.content
    }

builder = StateGraph(State)

builder.add_node("greet", greet)
builder.add_node("answer", answer)


builder.add_edge(START, "greet")
builder.add_edge("greet", "answer")
builder.add_edge("answer", END)

graph = builder.compile()

result = graph.invoke({
    "question": "What is LangGraph?",
    "greeting": "",
    "answer": ""
})
from typing import TypedDict

from langgraph.graph import StateGraph, START, END





class State(TypedDict):

    name: str

    message: str





def node_a(state: State):

    print("NODE A received:")

    print(state)



    return {

        "message": f"Hello {state['name']}"

    }





def node_b(state: State):

    print("NODE B received:")

    print(state)



    return {

        "message": state["message"] + " — welcome to LangGraph!"

    }





builder = StateGraph(State)



#builder.add_node("NODE_NAME", PYTHON_FUNCTION)

builder.add_node("node_a", node_a)

builder.add_node("node_b", node_b)



builder.add_edge(START, "node_a")

builder.add_edge("node_a", "node_b")

builder.add_edge("node_b", END)



graph = builder.compile()



from IPython.display import Image, display



display(Image(graph.get_graph().draw_mermaid_png()))



result = graph.invoke({

    "name": "Sagar",

    "message": ""

})



print("\nFINAL STATE:")

print(result)

State Reducers: 

Combining Multiple Updates

Append to list , multiple updates in single place

from typing import TypedDict, Annotated

import operator

from typing import TypedDict, Annotated
import operator

from langgraph.graph import StateGraph, START, END


class State(TypedDict):
    messages: Annotated[list[str], operator.add]


def node_a(state: State):
    return {
        "messages": ["Message from A"]
    }


def node_b(state: State):
    return {
        "messages": ["Message from B"]
    }


graph = StateGraph(State)

graph.add_node("a", node_a)
graph.add_node("b", node_b)

graph.add_edge(START, "a")
graph.add_edge("a", "b")
graph.add_edge("b", END)

app = graph.compile()

result = app.invoke({"messages": []})

print(result)

Conditional Edges

as in edges, it decides where to go next instead of edge a > b, it decides where to go from a to b or a to c.

Assume you asked a question to AI agent, about billing or order, now from your question-- it has to search in billing databases for your answer,

if question is billing > go for billing database and if it is about order search for orders databases

Syntax of conditional edge

graph.add_conditional_edges(

"SOURCE_NODE",

ROUTING_FUNCTION,

{

"ROUTE_1": "DESTINATION_NODE_1",

"ROUTE_2": "DESTINATION_NODE_2",

}

)

from typing import TypedDict

from langgraph.graph import StateGraph, START, END

from IPython.display import Image, display


# -----------------------------------
# 1. Define State
# -----------------------------------

class State(TypedDict):
    question: str
    category: str
    answer: str


# -----------------------------------
# 2. Define the classifier node
# -----------------------------------

def classify(state: State):

    question = state["question"].lower()

    if "bill" in question or "payment" in question or "charge" in question:
        return {
            "category": "billing"
        }

    return {
        "category": "general"
    }


# -----------------------------------
# 3. Define the routing function
# -----------------------------------

def route_question(state: State):

    if state["category"] == "billing":
        return "billing"

    return "general"


# -----------------------------------
# 4. Define Billing node
# -----------------------------------

def billing(state: State):

    return {
        "answer": "This question is about billing or payment."
    }


# -----------------------------------
# 5. Define General node
# -----------------------------------

def general(state: State):

    return {
        "answer": "This is a general question."
    }


# -----------------------------------
# 6. Create the graph
# -----------------------------------

graph = StateGraph(State)


# Add nodes
graph.add_node("classify", classify)
graph.add_node("billing", billing)
graph.add_node("general", general)


# -----------------------------------
# 7. Normal edge
# -----------------------------------

graph.add_edge(START, "classify")


# -----------------------------------
# 8. Conditional edge
# -----------------------------------

graph.add_conditional_edges(
    "classify",
    route_question,
    {
        "billing": "billing",
        "general": "general"
    }
)


# -----------------------------------
# 9. Connect both branches to END
# -----------------------------------

graph.add_edge("billing", END)
graph.add_edge("general", END)


# -----------------------------------
# 10. Compile
# -----------------------------------

app = graph.compile()


# -----------------------------------
# 11. Visualize
# -----------------------------------

display(Image(app.get_graph().draw_mermaid_png()))


# -----------------------------------
# 12. Run the graph
# -----------------------------------

result = app.invoke({
    "question": "Why was I charged twice?",
    "category": "",
    "answer": ""
})


print(result)

Loops: Letting an Agent Try Again

A loop allows the graph to go backward and execute a node again:

Loops are useful when an AI system needs to try something, evaluate it, and try again if necessary.


from typing import TypedDict



from langgraph.graph import StateGraph, START, END



from IPython.display import Image, display





# -----------------------------------

# 1. Define State

# -----------------------------------



class State(TypedDict):

    count: int





# -----------------------------------

# 2. Define the increment node

# -----------------------------------



def increment(state: State):



    print(f"Increment node running. Current count = {state['count']}")



    return {

        "count": state["count"] + 1

    }





# -----------------------------------

# 3. Define the routing function

# -----------------------------------



def check_count(state: State):



    if state["count"] < 3:

        return "continue"



    return "finish"





# -----------------------------------

# 4. Create the graph

# -----------------------------------



graph = StateGraph(State)





# Add node

graph.add_node("increment", increment)





# -----------------------------------

# 5. Start -> increment

# -----------------------------------



graph.add_edge(START, "increment")





# -----------------------------------

# 6. Conditional edge

# -----------------------------------



graph.add_conditional_edges(

    "increment",

    check_count,

    {

        "continue": "increment",

        "finish": END

    }

)





# -----------------------------------

# 7. Compile

# -----------------------------------



app = graph.compile()





# -----------------------------------

# 8. Visualize

# -----------------------------------



display(Image(app.get_graph().draw_mermaid_png()))





# -----------------------------------

# 9. Run the graph

# -----------------------------------



result = app.invoke({

    "count": 0

})





print("\nFinal result:")

print(result)

Message State

MessagesState is a convenient LangGraph state schema designed for message-based workflows.

class State(TypedDict):

messages: str

can be replaced with

from langgraph.graph import MessagesState


from langgraph.graph import StateGraph, START, END, MessagesState

from langchain_openai import ChatOpenAI

from IPython.display import Image, display


# -----------------------------------
# 1. Create the OpenAI model
# -----------------------------------

llm = ChatOpenAI(
    model="gpt-5.4-mini"
)


# -----------------------------------
# 2. Define the LLM node
# -----------------------------------

def call_model(state: MessagesState):

    response = llm.invoke(state["messages"])

    return {
        "messages": [response]
    }


# -----------------------------------
# 3. Create the graph
# -----------------------------------

graph = StateGraph(MessagesState)


# Add the LLM node
graph.add_node("llm", call_model)


# -----------------------------------
# 4. Connect the graph
# -----------------------------------

graph.add_edge(START, "llm")
graph.add_edge("llm", END)


# -----------------------------------
# 5. Compile
# -----------------------------------

app = graph.compile()


# -----------------------------------
# 6. Visualize
# -----------------------------------

display(Image(app.get_graph().draw_mermaid_png()))


# -----------------------------------
# 7. Run the graph
# -----------------------------------

result = app.invoke({
    "messages": [
        {
            "role": "user",
            "content": "Explain LangGraph in one simple sentence."
        }
    ]
})


# -----------------------------------
# 8. Print the final messages
# -----------------------------------

for message in result["messages"]:
    print(type(message).__name__, ":", message.content)

now try

result = app.invoke({

    "messages": [

        {

            "role": "user",

            "content": "What is the difference between LangChain and LangGraph?"

        }

    ]

})

for message in result["messages"]:

    print(type(message).__name__, ":", message.content)

Tool Calling

from langgraph.graph import StateGraph, START, END, MessagesState
from langgraph.prebuilt import ToolNode
from langchain_openai import ChatOpenAI
from langchain_core.tools import tool
from IPython.display import Image, display


# -----------------------------------
# 1. Define a tool
# -----------------------------------

@tool
def add(a: int, b: int) -> int:
    """Add two numbers together."""
    return a + b

@tool
def multiply(a: int, b: int) -> int:
    """Multiply two numbers together."""
    return a * b
    


tools = [add, multiply]


# -----------------------------------
# 2. Create the LLM
# -----------------------------------

llm = ChatOpenAI(
    model="gpt-5.4-mini"
)


# Give the LLM access to our tools
llm_with_tools = llm.bind_tools(tools)


# -----------------------------------
# 3. Define the LLM node
# -----------------------------------

def call_model(state: MessagesState):

    response = llm_with_tools.invoke(
        state["messages"]
    )

    return {
        "messages": [response]
    }


# -----------------------------------
# 4. Define the ToolNode
# -----------------------------------

tool_node = ToolNode(tools)


# -----------------------------------
# 5. Decide where to go next
# -----------------------------------

def should_continue(state: MessagesState):

    last_message = state["messages"][-1]

    if last_message.tool_calls:
        return "tools"

    return END


# -----------------------------------
# 6. Build the graph
# -----------------------------------

graph = StateGraph(MessagesState)

graph.add_node("llm", call_model)
graph.add_node("tools", tool_node)

graph.add_edge(START, "llm")

graph.add_conditional_edges(
    "llm",
    should_continue,
    {
        "tools": "tools",
        END: END
    }
)

graph.add_edge("tools", "llm")


# -----------------------------------
# 7. Compile
# -----------------------------------

app = graph.compile()


# -----------------------------------
# 8. Visualize
# -----------------------------------

display(
    Image(
        app.get_graph().draw_mermaid_png()
    )
)


# -----------------------------------
# 9. Run
# -----------------------------------

result = app.invoke(
    {
        "messages": [
            {
                "role": "user",
                "content": "What is 7+8?"
            }
        ]
    }
)


# -----------------------------------
# 10. Print the messages
# -----------------------------------

print("\n--- Messages ---")

for message in result["messages"]:
    print(
        type(message).__name__,
        ":",
        message.content
    )

    if hasattr(message, "tool_calls") and message.tool_calls:
        print("Tool calls:", message.tool_calls)

Persistent Memory

from langgraph.graph import StateGraph, START, END, MessagesState
from langgraph.checkpoint.memory import InMemorySaver
from langchain_openai import ChatOpenAI
from IPython.display import Image, display


# -----------------------------------
# 1. Create the LLM
# -----------------------------------

llm = ChatOpenAI(
    model="gpt-5.4-mini"
)


# -----------------------------------
# 2. Define the LLM node
# -----------------------------------

def call_model(state: MessagesState):

    response = llm.invoke(
        state["messages"]
    )

    return {
        "messages": [response]
    }


# -----------------------------------
# 3. Build the graph
# -----------------------------------

graph = StateGraph(MessagesState)

graph.add_node("llm", call_model)

graph.add_edge(START, "llm")
graph.add_edge("llm", END)


# -----------------------------------
# 4. Create a checkpointer
# -----------------------------------

checkpointer = InMemorySaver()


# -----------------------------------
# 5. Compile with persistence
# -----------------------------------

app = graph.compile(
    checkpointer=checkpointer
)


# -----------------------------------
# 6. Visualize the graph
# -----------------------------------

display(
    Image(
        app.get_graph().draw_mermaid_png()
    )
)


# -----------------------------------
# 7. Create a conversation/thread
# -----------------------------------

config = {
    "configurable": {
        "thread_id": "conversation-1"
    }
}

config2 = {
    "configurable": {
        "thread_id": "conversation-2"
    }
}


# -----------------------------------
# 8. First interaction
# -----------------------------------

result1 = app.invoke(
    {
        "messages": [
            {
                "role": "user",
                "content": "My name is Alex."
            }
        ]
    },
    config
)

result2 = app.invoke(
    {
        "messages": [
            {
                "role": "user",
                "content": "My name is Sagar."
            }
        ]
    },
    config2
)

print("\n--- First response ---")

print(
    result1["messages"][-1].content
)


# -----------------------------------
# 9. Second interaction
# -----------------------------------

result3 = app.invoke(
    {
        "messages": [
            {
                "role": "user",
                "content": "What is my name?"
            }
        ]
    },
    config
)


print("\n--- Second response ---")

print(
    result3["messages"][-1].content
)

Human-in-the-Loop

from typing import TypedDict

from langgraph.graph import StateGraph, START, END
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.types import interrupt, Command

from IPython.display import Image, display


# -----------------------------------
# 1. Define the state
# -----------------------------------

class State(TypedDict):
    request: str
    approved: bool
    result: str


# -----------------------------------
# 2. Create the request
# -----------------------------------

def create_request(state: State):

    print("Creating request...")

    return {
        "request": "Send an email to the customer"
    }


# -----------------------------------
# 3. Human approval node
# -----------------------------------

def human_approval(state: State):

    print("\nWaiting for human approval...")

    approved = interrupt(
        f"Do you approve this request?\n\n"
        f"Request: {state['request']}"
    )

    return {
        "approved": approved
    }


# -----------------------------------
# 4. Routing function
# -----------------------------------

def check_approval(state: State):

    if state["approved"]:
        return "approved"

    return "rejected"


# -----------------------------------
# 5. Approved node
# -----------------------------------

def approved_node(state: State):

    return {
        "result": "Request approved and executed."
    }


# -----------------------------------
# 6. Rejected node
# -----------------------------------

def rejected_node(state: State):

    return {
        "result": "Request rejected."
    }


# -----------------------------------
# 7. Build graph
# -----------------------------------

graph = StateGraph(State)

graph.add_node("create_request", create_request)
graph.add_node("human_approval", human_approval)
graph.add_node("approved", approved_node)
graph.add_node("rejected", rejected_node)


# -----------------------------------
# 8. Define edges
# -----------------------------------

graph.add_edge(START, "create_request")

graph.add_edge(
    "create_request",
    "human_approval"
)

graph.add_conditional_edges(
    "human_approval",
    check_approval,
    {
        "approved": "approved",
        "rejected": "rejected"
    }
)

graph.add_edge("approved", END)
graph.add_edge("rejected", END)


# -----------------------------------
# 9. Add persistence
# -----------------------------------

checkpointer = InMemorySaver()


# -----------------------------------
# 10. Compile
# -----------------------------------

app = graph.compile(
    checkpointer=checkpointer
)


# -----------------------------------
# 11. Visualize
# -----------------------------------

display(
    Image(
        app.get_graph().draw_mermaid_png()
    )
)


# -----------------------------------
# 12. Create thread
# -----------------------------------

config = {
    "configurable": {
        "thread_id": "approval-1"
    }
}


# -----------------------------------
# 13. Start graph
# -----------------------------------

result = app.invoke(
    {
        "request": "",
        "approved": False,
        "result": ""
    },
    config
)


# -----------------------------------
# 14. Show interrupt
# -----------------------------------

print("\n--- Graph paused ---")

print(result["__interrupt__"])

and now to approve run the command below

result = app.invoke(
    Command(resume=True),
    config
)

print("\n--- Final result ---")

print(result)

lets build our Own AI agent with concepts learned

# ============================================================
# 1. IMPORTS
# ============================================================

from typing import TypedDict

import ipywidgets as widgets
from IPython.display import display, Image

from langgraph.graph import StateGraph, START, END, MessagesState
from langgraph.prebuilt import ToolNode
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.types import interrupt, Command

from langchain_openai import ChatOpenAI
from langchain_core.tools import tool
from langchain_core.messages import SystemMessage


# ============================================================
# 2. STATE
# ============================================================

class AgentState(MessagesState):
    approved: bool


# ============================================================
# 3. TOOLS
# ============================================================

@tool
def add(a: int, b: int) -> int:
    """Add two numbers together."""
    return a + b


@tool
def multiply(a: int, b: int) -> int:
    """Multiply two numbers together."""
    return a * b


# Simple notes store for this demo
notes = []


@tool
def save_note(note: str) -> str:
    """
    Save an important note for the user.

    Use this whenever the user explicitly or implicitly
    wants the agent to remember, save, store, or keep
    a preference, fact, instruction, or personal note.
    """
    notes.append(note)
    return f"Note saved successfully: {note}"


@tool
def read_notes() -> str:
    """Read all saved notes."""

    if not notes:
        return "There are no saved notes."

    return "\n".join(
        f"- {note}"
        for note in notes
    )


tools = [
    add,
    multiply,
    save_note,
    read_notes
]


# ============================================================
# 4. LLM
# ============================================================

llm = ChatOpenAI(
    model="gpt-5.4-mini"
)

llm_with_tools = llm.bind_tools(tools)


# ============================================================
# 5. SYSTEM INSTRUCTIONS
# ============================================================

SYSTEM_PROMPT = """
You are a personal AI assistant with memory.

IMPORTANT MEMORY RULE:

If the user expresses a preference, fact, instruction,
or piece of information that they want you to remember,
save, store, or keep in mind, you MUST use the save_note tool.

Examples:

User: "I prefer Python examples."
→ Use save_note.

User: "I prefer my Python notes."
→ Use save_note.

User: "Remember that I like concise explanations."
→ Use save_note.

User: "Keep in mind that I use Jupyter notebooks."
→ Use save_note.

Do NOT merely reply that you will remember it.

The save_note tool will require human approval before
the note is actually saved.

For normal questions, do not save anything.

For arithmetic questions, use the appropriate calculation tool
when useful.

After a tool result is returned, continue the conversation
normally.
"""


# ============================================================
# 6. LLM NODE
# ============================================================

def call_model(state: AgentState):

    messages = [
        SystemMessage(content=SYSTEM_PROMPT),
        *state["messages"]
    ]

    response = llm_with_tools.invoke(messages)

    return {
        "messages": [response]
    }


# ============================================================
# 7. ROUTER AFTER LLM
# ============================================================

def route_after_llm(state: AgentState):

    last_message = state["messages"][-1]

    # No tool call → finish
    if not last_message.tool_calls:
        return "end"

    # save_note requires human approval
    for tool_call in last_message.tool_calls:

        if tool_call["name"] == "save_note":
            return "approval"

    # Other tools execute automatically
    return "tools"


# ============================================================
# 8. HUMAN APPROVAL NODE
# ============================================================

def human_approval(state: AgentState):

    last_message = state["messages"][-1]

    tool_call = next(
        call
        for call in last_message.tool_calls
        if call["name"] == "save_note"
    )

    note = tool_call["args"]["note"]

    approved = interrupt(
        {
            "type": "approval",
            "message": "The AI wants to save this note:",
            "note": note
        }
    )

    return {
        "approved": approved
    }


# ============================================================
# 9. ROUTER AFTER APPROVAL
# ============================================================

def route_after_approval(state: AgentState):

    if state["approved"]:
        return "tools"

    return "rejected"


# ============================================================
# 10. REJECTED NODE
# ============================================================

def rejected(state: AgentState):

    return {
        "messages": [
            {
                "role": "assistant",
                "content": (
                    "I did not save the note because "
                    "you rejected the action."
                )
            }
        ]
    }


# ============================================================
# 11. TOOL NODE
# ============================================================

tool_node = ToolNode(tools)


# ============================================================
# 12. BUILD GRAPH
# ============================================================

graph = StateGraph(AgentState)

graph.add_node("llm", call_model)
graph.add_node("human_approval", human_approval)
graph.add_node("tools", tool_node)
graph.add_node("rejected", rejected)


# START → LLM

graph.add_edge(
    START,
    "llm"
)


# LLM → conditional routing

graph.add_conditional_edges(
    "llm",
    route_after_llm,
    {
        "tools": "tools",
        "approval": "human_approval",
        "end": END
    }
)


# Human approval → conditional routing

graph.add_conditional_edges(
    "human_approval",
    route_after_approval,
    {
        "tools": "tools",
        "rejected": "rejected"
    }
)


# Tools → LLM

graph.add_edge(
    "tools",
    "llm"
)


# Rejected → END

graph.add_edge(
    "rejected",
    END
)


# ============================================================
# 13. CHECKPOINTER
# ============================================================

checkpointer = InMemorySaver()


# ============================================================
# 14. COMPILE
# ============================================================

app = graph.compile(
    checkpointer=checkpointer
)


# ============================================================
# 15. GRAPH VISUALIZATION
# ============================================================

display(
    Image(
        app.get_graph().draw_mermaid_png()
    )
)


# ============================================================
# 16. JUPYTER UI
# ============================================================

THREAD_ID = "interactive-agent-1"

config = {
    "configurable": {
        "thread_id": THREAD_ID
    }
}


# Chat display

chat_output = widgets.Output(
    layout=widgets.Layout(
        border="1px solid #ccc",
        padding="15px",
        width="800px",
        min_height="400px"
    )
)


# Input box

message_box = widgets.Textarea(
    placeholder="Type your message here...",
    layout=widgets.Layout(
        width="650px",
        height="70px"
    )
)


# Send button

send_button = widgets.Button(
    description="Send",
    button_style="primary",
    icon="paper-plane"
)


# Approval buttons

approve_button = widgets.Button(
    description="Approve",
    button_style="success",
    icon="check",
    disabled=True
)

reject_button = widgets.Button(
    description="Reject",
    button_style="danger",
    icon="times",
    disabled=True
)


# Status

status_label = widgets.HTML(
    value="<b>Status:</b> Ready"
)


# ============================================================
# 17. HELPER FUNCTIONS
# ============================================================

def show_message(sender, message):

    with chat_output:

        if sender == "You":
            print(f"\nšŸ§‘ You:\n{message}")

        else:
            print(f"\nšŸ¤– Agent:\n{message}")


def set_status(message):

    status_label.value = (
        f"<b>Status:</b> {message}"
    )


def disable_approval_buttons():

    approve_button.disabled = True
    reject_button.disabled = True


def enable_approval_buttons():

    approve_button.disabled = False
    reject_button.disabled = False


# ============================================================
# 18. SEND MESSAGE
# ============================================================

def send_message(_):

    user_message = message_box.value.strip()

    if not user_message:
        return

    message_box.value = ""

    show_message(
        "You",
        user_message
    )

    set_status("Thinking...")

    send_button.disabled = True

    try:

        result = app.invoke(
            {
                "messages": [
                    {
                        "role": "user",
                        "content": user_message
                    }
                ],
                "approved": False
            },
            config
        )

        # ----------------------------------------------------
        # GRAPH PAUSED FOR HUMAN APPROVAL
        # ----------------------------------------------------

        if "__interrupt__" in result:

            interrupt_data = (
                result["__interrupt__"][0].value
            )

            note = interrupt_data["note"]

            with chat_output:

                print("\n⚠️ HUMAN APPROVAL REQUIRED")
                print("--------------------------------")
                print(
                    "The AI wants to save this note:\n\n"
                    f'"{note}"'
                )
                print("--------------------------------")

            enable_approval_buttons()

            set_status(
                "Waiting for your approval..."
            )

        # ----------------------------------------------------
        # NORMAL RESPONSE
        # ----------------------------------------------------

        else:

            last_message = result["messages"][-1]

            show_message(
                "Agent",
                last_message.content
            )

            set_status("Ready")

            send_button.disabled = False

    except Exception as e:

        show_message(
            "Agent",
            f"Error: {e}"
        )

        set_status("Error")

        send_button.disabled = False


# ============================================================
# 19. APPROVE
# ============================================================

def approve_action(_):

    disable_approval_buttons()

    set_status(
        "Approved. Continuing..."
    )

    try:

        result = app.invoke(
            Command(resume=True),
            config
        )

        last_message = result["messages"][-1]

        show_message(
            "Agent",
            last_message.content
        )

        set_status("Ready")

        send_button.disabled = False

    except Exception as e:

        show_message(
            "Agent",
            f"Error: {e}"
        )

        set_status("Error")

        send_button.disabled = False


# ============================================================
# 20. REJECT
# ============================================================

def reject_action(_):

    disable_approval_buttons()

    set_status(
        "Rejected. Continuing..."
    )

    try:

        result = app.invoke(
            Command(resume=False),
            config
        )

        last_message = result["messages"][-1]

        show_message(
            "Agent",
            last_message.content
        )

        set_status("Ready")

        send_button.disabled = False

    except Exception as e:

        show_message(
            "Agent",
            f"Error: {e}"
        )

        set_status("Error")

        send_button.disabled = False


# ============================================================
# 21. CONNECT BUTTONS
# ============================================================

send_button.on_click(send_message)

approve_button.on_click(approve_action)

reject_button.on_click(reject_action)


# ============================================================
# 22. DISPLAY UI
# ============================================================

title = widgets.HTML(
    value="""
    <h2>šŸ¤– Personal AI Agent</h2>
    <p>
        LangGraph + OpenAI + Tools + Memory + Human Approval
    </p>
    """
)

approval_buttons = widgets.HBox(
    [
        approve_button,
        reject_button
    ]
)

input_row = widgets.HBox(
    [
        message_box,
        send_button
    ]
)

ui = widgets.VBox(
    [
        title,
        status_label,
        chat_output,
        approval_buttons,
        input_row
    ]
)

display(ui)

What You Should Take Away

  • State carries the information your workflow needs.
  • Nodes perform individual units of work.
  • Edges connect tasks and control execution flow.
  • Conditional edges let the workflow choose a route.
  • Loops let an agent evaluate and try again.
  • Persistence keeps conversation or workflow state across interactions.
  • Human-in-the-loop adds approval before sensitive actions.
  • Tools let the model interact with functions and external capabilities.

The final agent in this guide combines these ideas into one workflow: an LLM can call tools, remember notes, pause for human approval, resume execution, and continue the conversation inside a Jupyter interface.

Comments