Skip to content
Learn Agentic AI
Learn Agentic AI11 min read1 views

LangGraph Getting Started: Your First Stateful Agent Graph in Python

Learn how to install LangGraph, define a StateGraph with typed state, add nodes and edges, compile the graph, and invoke your first stateful agent workflow in Python.

Why LangGraph for Agent Workflows

Most agent frameworks treat execution as a linear pipeline: prompt in, response out, maybe a tool call in between. This works for simple question-answering but breaks down the moment you need branching logic, cycles, or persistent state across multiple reasoning steps. LangGraph solves this by modeling agent workflows as directed graphs where each node is a computation step, each edge defines the transition logic, and the entire graph operates on a shared, typed state object.

Built on top of LangChain but fully usable as a standalone library, LangGraph gives you explicit control over the flow of execution. You decide when the agent reasons, when it calls tools, when it loops back for another attempt, and when it terminates. There is no hidden orchestration magic — every transition is visible in the graph definition.

Installation

Install LangGraph alongside the LangChain OpenAI integration:

flowchart TD
    START(["LangGraph Getting Started: Your First<br/>Stateful Agent Graph in Python"])
    S0["Why LangGraph for Agent<br/>Workflows"]
    START --> S0
    S1["Installation"]
    S0 --> S1
    S2["Defining State"]
    S1 --> S2
    S3["Building the Graph"]
    S2 --> S3
    S4["Invoking the Graph"]
    S3 --> S4
    S5["Visualizing the Graph"]
    S4 --> S5
    S6["Key Concepts Summary"]
    S5 --> S6
    S7["FAQ"]
    S6 --> S7
    DONE(["Key Takeaways"])
    S7 --> DONE
    style START fill:#4f46e5,stroke:#4338ca,color:#fff
    style DONE fill:#059669,stroke:#047857,color:#fff
pip install langgraph langchain-openai

Set your API key:

export OPENAI_API_KEY="sk-your-key-here"

Defining State

Every LangGraph workflow starts with a state schema. This is a TypedDict that defines what data flows through the graph:

from typing import TypedDict, Annotated
from langgraph.graph.message import add_messages

class AgentState(TypedDict):
    messages: Annotated[list, add_messages]
    current_step: str

The Annotated type with add_messages tells LangGraph to append new messages rather than overwrite the list. This is called a reducer and it controls how state updates merge.

Building the Graph

Create a StateGraph, add nodes as functions, and connect them with edges:

See AI Voice Agents Handle Real Calls

Book a free demo or calculate how much you can save with AI voice automation.

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

llm = ChatOpenAI(model="gpt-4o-mini")

def call_model(state: AgentState) -> dict:
    response = llm.invoke(state["messages"])
    return {"messages": [response], "current_step": "completed"}

# Build the graph
builder = StateGraph(AgentState)
builder.add_node("agent", call_model)
builder.add_edge(START, "agent")
builder.add_edge("agent", END)

graph = builder.compile()

The START and END constants define entry and exit points. The compiled graph is an executable runnable.

Invoking the Graph

Run the graph with an initial state:

from langchain_core.messages import HumanMessage

result = graph.invoke({
    "messages": [HumanMessage(content="What is LangGraph?")],
    "current_step": "starting",
})

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

The invoke call processes input through every node following the defined edges and returns the final state. You now have a working stateful agent graph.

Visualizing the Graph

LangGraph can render your graph for debugging:

from IPython.display import Image, display

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

This outputs a Mermaid diagram showing all nodes and edges, which is invaluable for understanding complex multi-step workflows.

Key Concepts Summary

The core building blocks are: StateGraph for the container, nodes for computation functions, edges for transitions, compile to produce an executable, and invoke to run it. Every node receives the current state and returns a partial state update that gets merged back. This explicit model gives you full visibility and control over agent behavior.

FAQ

How is LangGraph different from LangChain?

LangChain provides chains and agents as high-level abstractions. LangGraph sits underneath as a lower-level orchestration layer that models workflows as graphs with explicit state management. You can use LangGraph without LangChain, though they integrate seamlessly.

Can I use LangGraph with models other than OpenAI?

Yes. LangGraph is model-agnostic. You can use any LangChain chat model integration including Anthropic, Google, Mistral, or local models via Ollama. The graph structure itself has no dependency on any specific model provider.

Does LangGraph support async execution?

Yes. LangGraph supports both sync and async execution. You can define async node functions and use await graph.ainvoke() for non-blocking execution, which is essential for production web servers.


#LangGraph #StatefulAgents #Python #GettingStarted #AgentWorkflows #AgenticAI #LearnAI #AIEngineering

flowchart LR
    IN(["Input prompt"])
    subgraph PRE["Pre processing"]
        TOK["Tokenize"]
        EMB["Embed"]
    end
    subgraph CORE["Model Core"]
        ATTN["Self attention layers"]
        MLP["Feed forward layers"]
    end
    subgraph POST["Post processing"]
        SAMP["Sampling"]
        DETOK["Detokenize"]
    end
    OUT(["Generated text"])
    IN --> TOK --> EMB --> ATTN --> MLP --> SAMP --> DETOK --> OUT
    style IN fill:#f1f5f9,stroke:#64748b,color:#0f172a
    style CORE fill:#ede9fe,stroke:#7c3aed,color:#1e1b4b
    style OUT fill:#059669,stroke:#047857,color:#fff
flowchart TD
    HUB(("FAQ"))
    HUB --> L0["How is LangGraph different<br/>from LangChain?"]
    style L0 fill:#e0e7ff,stroke:#6366f1,color:#1e293b
    HUB --> L1["Can I use LangGraph with<br/>models other than OpenAI?"]
    style L1 fill:#e0e7ff,stroke:#6366f1,color:#1e293b
    HUB --> L2["Does LangGraph support async<br/>execution?"]
    style L2 fill:#e0e7ff,stroke:#6366f1,color:#1e293b
    style HUB fill:#4f46e5,stroke:#4338ca,color:#fff
Share

Try CallSphere AI Voice Agents

See how AI voice agents work for your industry. Live demo available -- no signup required.

Related Articles You May Like

AI Interview Prep

7 AI Coding Interview Questions From Anthropic, Meta & OpenAI (2026 Edition)

Real AI coding interview questions from Anthropic, Meta, and OpenAI in 2026. Includes implementing attention from scratch, Anthropic's progressive coding screens, Meta's AI-assisted round, and vector search — with solution approaches.

Learn Agentic AI

AI Agent Framework Comparison 2026: LangGraph vs CrewAI vs AutoGen vs OpenAI Agents SDK

Side-by-side comparison of the top 4 AI agent frameworks: LangGraph, CrewAI, AutoGen, and OpenAI Agents SDK — architecture, features, production readiness, and when to choose each.

AI Interview Prep

7 Agentic AI & Multi-Agent System Interview Questions for 2026

Real agentic AI and multi-agent system interview questions from Anthropic, OpenAI, and Microsoft in 2026. Covers agent design patterns, memory systems, safety, orchestration frameworks, tool calling, and evaluation.

Learn Agentic AI

Stateful vs Stateless AI Agents: Architecture Trade-Offs for Production Systems

When to use stateful agents with session history versus stateless agents with external state. Covers hybrid approaches and state externalization patterns.

Learn Agentic AI

Building a Multi-Agent Data Pipeline: Ingestion, Transformation, and Analysis Agents

Build a three-agent data pipeline with ingestion, transformation, and analysis agents that process data from APIs, CSVs, and databases using Python.

Learn Agentic AI

Building a Research Agent with Web Search and Report Generation: Complete Tutorial

Build a research agent that searches the web, extracts and synthesizes data, and generates formatted reports using OpenAI Agents SDK and web search tools.