AI Help Center › GenAI / LLM › Build Your First AI Agent with LangGraph
GenAI / LLM · PRACTITIONER GUIDE

How to Build Your First AI Agent in Python with LangGraph

A working accounts assistant with two tools, one graph, a step limit and a human approval gate, plus the same loop written without a framework.

14 min readPublished 8 Nov 2026Last reviewed 8 Nov 2026
Quick insight

An agent is a loop you can read. The model asks for a tool, your code runs it, the result goes back into the conversation, and the model decides again. LangGraph gives that loop a shape you can pause, inspect and limit.

To build your first AI agent in Python, write a few typed functions as tools, bind them to a tool-calling LLM, and wire a LangGraph StateGraph with a model node, a ToolNode and a tools_condition edge that loops until the model stops asking for tools. Then add a step limit and human approval before any action that changes data.

Summary: the short version

  • An AI agent is an LLM in a loop: it picks a tool, your code runs it, the result goes back into the conversation, and the model decides again.
  • In LangGraph that loop is a StateGraph with a model node and a ToolNode, joined by tools_condition, which routes to the tools when there are tool calls and ends otherwise.
  • Tools are Python functions with the @tool decorator; their docstrings and type hints are what the model reads.
  • Cap every run with recursion_limit, and put an interrupt() approval step in front of any tool that writes, pays, sends or deletes.
  • The core loop is under 20 lines of plain Python; LangGraph earns its place once you need pauses, persistence or several paths through the work.
GenAI / LLM

What is an AI agent, in Python terms?

In code, an AI agent is a while-loop around an LLM call, where the model can request functions and your program runs them and feeds the results back. The model never executes anything itself. It returns a structured request such as "call lookup_invoice with invoice_no='INV-1002'", and your code decides whether and how to honour it.

The pattern traces back to research such as ReAct (Yao et al., 2022), which interleaved reasoning steps with actions; every major model API now supports it as tool calling. Our guide to advanced prompting techniques covers ReAct-style prompts, and what agentic AI is covers the concepts. If you are unsure whether you need an agent or plain retrieval, read RAG vs AI agents vs agentic AI first. Three ingredients make the loop work: tools (the model sees only their names, descriptions and argument types), state (the running list of messages, re-read on every call) and a stopping rule (no more tool requests, or a step limit).

The agent graph you will build START agentLLM + bound tools tools_condition no tool calls END tool calls tools (ToolNode)calculate_gst, lookup_invoice tool result appended to messages State: MessagesState
The whole agent is two nodes and one decision. The loop runs until the model answers without asking for a tool.
Setup

What do you need to install for a LangGraph agent?

You need Python 3.10 or newer, three pip packages (langgraph, langchain-openai and pandas) and an API key for a model that supports tool calling. Use a virtual environment, and pick any current tool-calling model through AGENT_MODEL.

terminal
python -m venv .venv
source .venv/bin/activate           # Windows: .venv\Scripts\activate
pip install -U langgraph langchain-openai pandas
# Prefer Claude? pip install -U langchain-anthropic and use ChatAnthropic instead

export OPENAI_API_KEY="your-key"    # Windows PowerShell: $env:OPENAI_API_KEY="your-key"
export AGENT_MODEL="model-name"     # a current tool-calling model from your provider's model list
  • langgraph is the orchestration library; langchain-openai provides ChatOpenAI; langchain-core (installed with it) provides @tool and the message types. For Claude, install langchain-anthropic and use ChatAnthropic. The graph code does not change.
  • Model names change fast: OpenAI has already scheduled older snapshots such as gpt-4o-mini for removal, so the code reads the model from AGENT_MODEL instead of hard-coding one.
  • We ran every LangGraph listing here against langgraph 1.2 in November 2026, with a stubbed model standing in for the API, using the documented imports (StateGraph, MessagesState, ToolNode, tools_condition, interrupt). APIs still move, so if an import fails, check the LangGraph docs for your version.
Tools

How do you define tools for an AI agent?

Write a normal Python function with type hints and a clear docstring, then add the @tool decorator; LangChain turns the signature into the JSON schema the model sees. The model chooses tools purely from their names, descriptions and argument types, so the docstring is effectively part of your prompt.

Our accounts assistant gets two tools: calculate_gst does the arithmetic (never let the model multiply rupees in its head), and lookup_invoice reads a small pandas DataFrame standing in for a Tally or ERP export.

agent.py (part 1: data and tools)
import os

import pandas as pd
from langchain_core.messages import SystemMessage
from langchain_core.tools import tool
from langchain_openai import ChatOpenAI
from langgraph.graph import StateGraph, MessagesState, START
from langgraph.prebuilt import ToolNode, tools_condition

# A tiny invoice register standing in for your Tally or ERP export
INVOICES = pd.DataFrame({
    "invoice_no": ["INV-1001", "INV-1002", "INV-1003", "INV-1004"],
    "customer": ["Retailer, Pune", "Distributor, Nagpur", "Hospital, Kolkata", "Retailer, Pune"],
    "taxable_value": [125000, 48000, 310000, 76500],
    "gst_rate": [18, 18, 5, 18],
    "same_state": [True, False, False, True],
    "status": ["paid", "unpaid", "unpaid", "paid"],
    "due_date": ["2026-10-15", "2026-11-05", "2026-11-20", "2026-10-30"],
})


@tool
def calculate_gst(amount: float, rate: float, same_state: bool = True) -> dict:
    """Calculate GST on a taxable amount in INR.

    Args:
        amount: Taxable value in rupees, before GST.
        rate: GST rate in percent, for example 5 or 18.
        same_state: True if supplier and buyer are in the same state
            (CGST + SGST); False for an inter-state supply (IGST).
    """
    gst = round(amount * rate / 100, 2)
    split = {"cgst": gst / 2, "sgst": gst / 2} if same_state else {"igst": gst}
    return {"taxable_value": amount, "rate": rate, "gst": gst, **split,
            "invoice_total": round(amount + gst, 2)}


@tool
def lookup_invoice(invoice_no: str) -> dict:
    """Return the details of one invoice, looked up by number such as INV-1002."""
    rows = INVOICES[INVOICES["invoice_no"] == invoice_no.strip().upper()]
    if rows.empty:
        return {"error": f"No invoice found with number {invoice_no}"}
    return rows.to_dict(orient="records")[0]
  • Return structured data. A dict with named fields is easier for the model to read correctly than a sentence.
  • Return errors as data. {"error": "No invoice found"} lets the model explain the problem; an unhandled exception can stop the run.
  • Keep outputs JSON-friendly. to_dict(orient="records") converts pandas values to plain Python types.
  • Take rates as inputs. GST slabs were rationalised in September 2025 and will change again; hard-coded slabs go stale quietly.
From our classrooms

In the LangGraph and LCEL agent modules of Ivy Professional School's Advanced Generative AI course, when a learner's agent picks the wrong tool, the cause is usually a vague docstring, not a weak model. Rewriting "Gets invoice" as "Return the details of one invoice, looked up by number such as INV-1002" fixes more agents than a bigger model does.

LangGraph

How do you build the agent loop with a LangGraph StateGraph?

Create a StateGraph(MessagesState), add a model node and a ToolNode, connect them with tools_condition, and add an edge from the tools back to the model. That is the entire agent.

agent.py (part 2: model, graph and run)
tools = [calculate_gst, lookup_invoice]
llm = ChatOpenAI(model=os.environ["AGENT_MODEL"], temperature=0)  # drop temperature if your model rejects it
llm_with_tools = llm.bind_tools(tools)

SYSTEM = SystemMessage(content=(
    "You are an accounts assistant for an Indian SME. Amounts are in INR. "
    "Use the tools for every figure; never do GST arithmetic yourself. "
    "If a tool returns an error, say so plainly instead of guessing."
))


def call_model(state: MessagesState):
    response = llm_with_tools.invoke([SYSTEM] + state["messages"])
    return {"messages": [response]}


builder = StateGraph(MessagesState)
builder.add_node("agent", call_model)
builder.add_node("tools", ToolNode(tools))
builder.add_edge(START, "agent")
builder.add_conditional_edges("agent", tools_condition)  # -> "tools" or END
builder.add_edge("tools", "agent")
graph = builder.compile()

if __name__ == "__main__":
    question = "What is the total payable on INV-1002 including GST?"
    result = graph.invoke({"messages": [("user", question)]},
                          config={"recursion_limit": 10})
    for message in result["messages"]:
        message.pretty_print()
  • bind_tools(tools) sends the tool schemas with every call. Forget it and the model answers from memory, confidently and wrongly.
  • MessagesState has one key, messages, whose reducer appends rather than replaces. That is why call_model returns only the new reply.
  • ToolNode(tools) reads the tool calls on the last AI message, runs each one, and appends a ToolMessage per call. Invalid arguments come back to the model as an error it can fix; other exceptions stop the run unless you set handle_tool_errors=True.
  • tools_condition returns "tools" when there are tool calls and END otherwise, so name the tool node exactly "tools".
  • The edge from tools back to agent closes the loop.
Worked example

Worked example: what happens when a Pune accounts team asks about an invoice?

The agent makes two tool calls and then answers, and the trace shows every step, which is what a reviewer needs to see. Picture the receivables desk of a mid-sized distributor in Pune, fielding "what is the total on this invoice, and is it paid?" from sales colleagues all day. Here the question is about INV-1002, an inter-state invoice to a Nagpur distributor: ₹48,000 taxable at 18% GST. Run python agent.py. Your model's wording will differ from our run below; the shape will not.

output (abridged)
================================ Human Message =================================
What is the total payable on INV-1002 including GST?
================================== Ai Message ==================================
Tool Calls:
  lookup_invoice (call_1)
  Args:
    invoice_no: INV-1002
================================= Tool Message =================================
Name: lookup_invoice
{"invoice_no": "INV-1002", "customer": "Distributor, Nagpur", "taxable_value": 48000,
 "gst_rate": 18, "same_state": false, "status": "unpaid", "due_date": "2026-11-05"}
================================== Ai Message ==================================
Tool Calls:
  calculate_gst (call_2)
  Args:
    amount: 48000
    rate: 18
    same_state: False
================================= Tool Message =================================
Name: calculate_gst
{"taxable_value": 48000.0, "rate": 18.0, "gst": 8640.0, "igst": 8640.0, "invoice_total": 56640.0}
================================== Ai Message ==================================
INV-1002 is an inter-state invoice, so IGST applies. Taxable value Rs 48,000,
IGST at 18% is Rs 8,640, total payable Rs 56,640. It was due on 5 Nov 2026
and is still unpaid.
StepNodeWhat happenedWhat to check
1agentModel asks for lookup_invoice("INV-1002")Did it pick the right tool and argument?
2toolsReturns taxable value ₹48,000, rate 18%, inter-stateIs the data source current?
3agentModel asks for calculate_gst(48000, 18, same_state=False)Was the inter-state flag passed on?
4toolsIGST ₹8,640; total ₹56,640Arithmetic came from code, not the model
5agentWrites the final answer, no tool calls, so the graph endsDoes every number match a tool result?

The last row matters most: a number no tool returned is a number the model invented. Our guide on why LLMs hallucinate has a short Python check for it. To watch steps live, stream updates:

stream_updates.py
from agent import graph

inputs = {"messages": [("user", "Which unpaid invoices are due this month?")]}
for update in graph.stream(inputs, config={"recursion_limit": 10}, stream_mode="updates"):
    for node, payload in update.items():
        print(f"--- {node} ---")
        payload["messages"][-1].pretty_print()
Guardrails

How do you stop an agent from looping forever?

Set recursion_limit on every call and catch GraphRecursionError; it caps node runs so a confused model cannot burn tokens forever. Each tool round costs two steps, so a limit of 10 allows roughly four rounds before the final answer. The default has changed across versions, so set it explicitly.

step_limit.py
from langgraph.errors import GraphRecursionError

from agent import graph

question = "What is the total payable on INV-1002 including GST?"
try:
    result = graph.invoke({"messages": [("user", question)]},
                          config={"recursion_limit": 10})
except GraphRecursionError:
    result = None
    print("Agent hit its step limit. Routing the question to a person.")

Loops usually have a boring cause: a tool keeps returning an error the model cannot fix. Read the trace before raising the limit, because every extra round re-sends the whole history.

Input tokens per model call in one run (illustrative) 900Call 1 1,150Call 2 1,400Call 3 1,650Call 4 1,900Call 5 Illustrative: ~900 starting tokens plus ~250 per round, about 7,000 in total.
Cost grows with every round because each model call re-reads the full history. A step limit is a budget limit.
Human in the loop

How do you add human approval before an agent acts?

Route risky tool calls to an approval node that calls interrupt(), compile the graph with a checkpointer, and resume with Command(resume=...) once a person decides. Nothing executes until someone approves.

Here a third tool that changes data, mark_invoice_paid, needs approval; read-only tools run straight away.

agent_with_approval.py
from typing import Literal

from langchain_core.messages import ToolMessage
from langchain_core.tools import tool
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.graph import StateGraph, MessagesState, START, END
from langgraph.prebuilt import ToolNode
from langgraph.types import Command, interrupt

from agent import INVOICES, SYSTEM, calculate_gst, llm, lookup_invoice


@tool
def mark_invoice_paid(invoice_no: str) -> str:
    """Mark an invoice as paid in the register. This changes data."""
    mask = INVOICES["invoice_no"] == invoice_no.strip().upper()
    if not mask.any():
        return f"No invoice found with number {invoice_no}"
    INVOICES.loc[mask, "status"] = "paid"
    return f"{invoice_no} marked as paid"


tools = [calculate_gst, lookup_invoice, mark_invoice_paid]
llm_with_tools = llm.bind_tools(tools)
NEEDS_APPROVAL = {"mark_invoice_paid"}


def call_model(state: MessagesState):
    return {"messages": [llm_with_tools.invoke([SYSTEM] + state["messages"])]}


def route(state: MessagesState) -> Literal["approval", "tools", "__end__"]:
    last = state["messages"][-1]
    if not last.tool_calls:
        return END
    if any(call["name"] in NEEDS_APPROVAL for call in last.tool_calls):
        return "approval"
    return "tools"


def approval(state: MessagesState) -> Command[Literal["tools", "agent"]]:
    calls = state["messages"][-1].tool_calls
    decision = interrupt({"pending": [{"tool": c["name"], "args": c["args"]} for c in calls]})
    if decision == "approve":
        return Command(goto="tools")
    rejected = [ToolMessage(content="Rejected by the accounts reviewer. Do not retry.",
                            tool_call_id=c["id"]) for c in calls]
    return Command(goto="agent", update={"messages": rejected})


builder = StateGraph(MessagesState)
builder.add_node("agent", call_model)
builder.add_node("approval", approval)
builder.add_node("tools", ToolNode(tools))
builder.add_edge(START, "agent")
builder.add_conditional_edges("agent", route)
builder.add_edge("tools", "agent")
graph = builder.compile(checkpointer=InMemorySaver())  # interrupts need a checkpointer

if __name__ == "__main__":
    config = {"configurable": {"thread_id": "ap-review-1"}, "recursion_limit": 12}
    result = graph.invoke(
        {"messages": [("user", "The hospital says INV-1003 is settled. Mark it paid.")]}, config)
    if "__interrupt__" in result:
        print("Waiting for approval:", result["__interrupt__"][0].value)
        decision = input("Type approve or reject: ").strip().lower()
        result = graph.invoke(Command(resume=decision), config)
    print(result["messages"][-1].content)

Interrupts need a checkpointer and a thread_id; use a database-backed checkpointer in production so a pause survives a restart. And a rejection must still answer each pending tool call with a ToolMessage, or the model API will reject the conversation.

Rule of thumb

If a tool writes, pays, sends or deletes, it goes behind approval: the maker-checker control finance teams already run. Read-only lookups can run freely.

Under the hood

What does LangGraph do that a plain Python loop does not?

For one model and a few tools, very little: the core loop is under 20 lines of plain Python, and writing it once shows you what LangGraph automates. Here is the same agent with the OpenAI SDK's Chat Completions API; the newer Responses API follows the same loop.

plain_agent.py
import json
import os

from openai import OpenAI

client = OpenAI()  # reads OPENAI_API_KEY from the environment
MODEL = os.environ["AGENT_MODEL"]
INVOICES = {"INV-1002": {"taxable_value": 48000, "gst_rate": 18, "same_state": False}}


def calculate_gst(amount, rate, same_state=True):
    gst = round(amount * rate / 100, 2)
    return {"gst": gst, "invoice_total": round(amount + gst, 2), "igst": not same_state}


def lookup_invoice(invoice_no):
    return INVOICES.get(invoice_no.upper(), {"error": "invoice not found"})


FUNCS = {"calculate_gst": calculate_gst, "lookup_invoice": lookup_invoice}
TOOLS = [
    {"type": "function", "function": {"name": "calculate_gst", "description": "GST on a taxable INR amount",
     "parameters": {"type": "object", "required": ["amount", "rate"], "properties": {
         "amount": {"type": "number"}, "rate": {"type": "number"}, "same_state": {"type": "boolean"}}}}},
    {"type": "function", "function": {"name": "lookup_invoice", "description": "Invoice details by number",
     "parameters": {"type": "object", "required": ["invoice_no"], "properties": {
         "invoice_no": {"type": "string"}}}}},
]


def run_agent(question, max_steps=6):
    messages = [{"role": "system", "content": "Use the tools for every figure."},
                {"role": "user", "content": question}]
    for _ in range(max_steps):                      # the step limit
        msg = client.chat.completions.create(model=MODEL, messages=messages,
                                             tools=TOOLS).choices[0].message
        messages.append(msg)                        # the state is just this list
        if not msg.tool_calls:                      # no tool requested: done
            return msg.content
        for call in msg.tool_calls:                 # the "ToolNode"
            result = FUNCS[call.function.name](**json.loads(call.function.arguments))
            messages.append({"role": "tool", "tool_call_id": call.id,
                             "content": json.dumps(result)})
    return "Stopped: step limit reached."


if __name__ == "__main__":
    print(run_agent("What is the total payable on INV-1002 including GST?"))

The messages list is MessagesState, the if not msg.tool_calls check is tools_condition, the inner loop is ToolNode, and max_steps is recursion_limit. Anthropic's guide on building effective agents also advises starting with direct API calls, since frameworks can hide what you need to debug.

ConcernPlain Python loopLangGraph
Conversation stateA list you append toMessagesState or your own typed state
Routingif statementsConditional edges, tools_condition, Command(goto=...)
Running toolsDict lookup, your own error handlingToolNode: parallel calls, configurable error handling
Step limitfor _ in range(max_steps)recursion_limit and GraphRecursionError
Pause for approvalYou build storage and resume logicinterrupt() plus a checkpointer
Resume after a crash or days laterYour own database codeCheckpointers keyed by thread_id
Streaming and inspectionPrint statementsStream modes, graph drawing, tracing
Strong opinion

One model, three tools, no pauses: ship the plain loop. Move to LangGraph the day you need approvals, persistence or a second path through the work. That is also when multi-agent designs start to make sense, and not before.

Debugging

What are the most common LangGraph agent errors?

Most first-agent bugs come from an unbound model, a misnamed tool node, a missing return edge or broken message pairs. In our workshops these cover nearly every "my agent doesn't work" question.

SymptomLikely causeFix
Agent answers without ever calling a toolModel not bound with tools, or vague tool docstringsUse llm.bind_tools(tools); say in each docstring when to use the tool
Error about an unknown node toolstools_condition routes to "tools" but your node has another nameName the ToolNode "tools" or pass a path map to add_conditional_edges
Graph stops right after a tool runsNo edge from tools back to the modelbuilder.add_edge("tools", "agent")
GraphRecursionErrorModel retrying a failing toolRead the trace; fix the tool's error message first
400 error saying a tool message must follow a tool callHistory was trimmed or edited and an AI tool call lost its ToolMessageTrim history in whole rounds; answer every tool call, even rejected ones
Watch out

Treat tool arguments as untrusted input. Validate them before they reach SQL or a shell; see connecting LLMs to SQL.

Next steps

What should you build after your first agent?

Make this agent trustworthy before making it bigger. Tests, limits and approvals are also the habits our AI engineer roadmap puts ahead of new frameworks.

  • Swap the DataFrame for a read-only connection to a test invoice table.
  • Write ten test questions with known answers, two of them with invoice numbers that do not exist, and rerun them after every change (see evaluating LLM applications).
  • Set recursion_limit on every call and log every GraphRecursionError.
  • Put every write action behind interrupt() approval with a database-backed checkpointer.
  • Expose the agent through an API such as FastAPI only after the tests pass.
  • If several assistants need the same tools, expose them through MCP.
FAQ

Frequently asked questions

Do I need LangGraph to build an AI agent in Python?

No. A tool-calling agent is a loop you can write in about 20 lines with any model SDK. LangGraph becomes useful when you need human approval pauses, saved state between runs, streaming of intermediate steps, or several nodes with different jobs. Learn the plain loop first.

Can I use Claude or an open-source model with LangGraph instead of OpenAI?

Yes. Install the matching LangChain package, such as langchain-anthropic for Claude or langchain-ollama for local models, and swap the chat model class. The graph, tools and edges stay the same. The model must support tool calling, and smaller open models are less reliable at choosing tools.

What is the difference between ToolNode and tools_condition in LangGraph?

tools_condition is a routing function: it looks at the last message and returns "tools" if the model requested tool calls, or END if it did not. ToolNode is the node that actually runs the requested tools and appends their results as ToolMessages. You normally use them together.

How many tools should my first AI agent have?

Start with two to five tools that each do one clear job. Every tool adds text the model must read and another way to choose wrongly. Above ten or fifteen tools, group them, split the work across specialised agents, or load only the tools the current task needs.

Why does my LangGraph agent keep calling the same tool?

Usually the tool returns an error or an unhelpful result, and the model retries with small variations. Read the trace, make the tool's error message say what input it expects, and tell the model to stop and report after a failed lookup. Keep recursion_limit as a backstop.

Sources

Sources