Skip to content
Learn Agentic AI11 min read0 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:

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

Share this article
C

CallSphere Team

Expert insights on AI voice agents and customer communication automation.

Try CallSphere AI Voice Agents

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