📡 You're offline — showing cached content
New version available!
Quick Access
Tutorials Generative AI Engineering LangGraph for Agent Workflows

LangGraph for Agent Workflows

6 min read
Build stateful agent loops in LangGraph: define nodes, conditional edges, and tool-execution cycles.

LangGraph for Stateful Agent Workflows

LangGraph builds controllable agent loops as directed graphs — with cycles, conditionals, and human-in-the-loop.

# pip install langgraph
from langgraph.graph import StateGraph, END
from typing import TypedDict, Annotated
import operator

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

def call_agent(state: AgentState) -> AgentState:
    response = llm_with_tools.invoke(state['messages'])
    return {'messages': [response]}

def run_tools(state: AgentState) -> AgentState:
    tool_results = execute_tools(state['messages'][-1])
    return {'messages': tool_results}

def should_continue(state: AgentState) -> str:
    last_msg = state['messages'][-1]
    if has_tool_calls(last_msg):
        return 'tools'
    return END

# Build graph
graph = StateGraph(AgentState)
graph.add_node('agent', call_agent)
graph.add_node('tools', run_tools)
graph.set_entry_point('agent')
graph.add_conditional_edges('agent', should_continue,
    {'tools':'tools', END:END})
graph.add_edge('tools', 'agent')  # loop back!

agent = graph.compile()
result = agent.invoke({
    'messages': [{'role':'user','content':'Research Docker best practices'}]
})