~/wiki

LangGraph Agent Patterns

Confiance : high
langgraphagent-patternsreact-frameworkstate-managementtool-callingconversational-aigraph-based-agentsstreaming-responsesmulti-tool-orchestrationhuman-in-loopconfirmation-workflowsend-to-end-implementationproduction-patterns

Advanced implementation patterns for building sophisticated AI agents using LangGraph, focusing on ReAct frameworks, state management, and production-ready conversational systems.

Core Architecture Patterns

ReAct Agent Implementation

Pattern: Reason-Act-Observe cycle with tool integration

from langgraph import StateGraph, START, END
from langchain_core.messages import HumanMessage, AIMessage

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

# Agent node with streaming support
async def agent_node(state: AgentState):
    messages = state["messages"]
    model = get_model().bind_tools(tools)
    response = await model.ainvoke(messages)
    return {"messages": response, "sender": "assistant"}

Multi-Tool Orchestration

Challenge: Coordinating complex workflows across multiple business domains Solution: Modular tool design with error handling and fallback patterns

tools = [
    query_stock_tool,
    query_ventes_tool, 
    send_email_tool,
    get_weather_tool,
    analyze_rentability_tool,
    create_production_plan_tool,
    calculate_baking_schedule_tool,
    check_stock_alerts_tool
]

Human-in-the-Loop Workflows

Pattern: Confirmation steps for sensitive operations

def should_continue(state: AgentState) -> str:
    messages = state["messages"]
    last_message = messages[-1]
    
    # Check if tool requires confirmation
    if hasattr(last_message, 'tool_calls'):
        for tool_call in last_message.tool_calls:
            if tool_call["name"] == "send_email":
                return "confirm_action"
    
    return END

State Management Patterns

Conversational Memory

  • Multi-turn conversation tracking
  • Context preservation across tool calls
  • Message history optimization for token efficiency

Stream Processing

  • Real-time response streaming
  • Progressive result display
  • Cancellable long-running operations

Production Implementation

Error Handling

try:
    result = await tool.ainvoke(params)
except Exception as e:
    return {
        "messages": AIMessage(
            content=f"Erreur lors de l'exécution: {str(e)}"
        ),
        "sender": "system"
    }

Configuration Management

  • Environment-based model selection
  • API key rotation support
  • Deployment-specific tool sets

Integration Challenges

Notion API Integration:

  • SDK compatibility issues with Python 3.14
  • Direct REST API client implementation
  • Multi-database coordination patterns

Email Integration:

  • SMTP configuration for production
  • Template-based message generation
  • Confirmation workflows before sending

UI Integration Patterns

Chainlit Integration

import chainlit as cl

@cl.on_chat_start
async def start_chat():
    cl.user_session.set("agent", create_agent())

@cl.on_message
async def main(message: cl.Message):
    agent = cl.user_session.get("agent")
    response = await agent.ainvoke({"messages": [HumanMessage(content=message.content)]})

CLI Interface

def run_cli():
    agent = create_agent()
    while True:
        user_input = input("Vous: ")
        if user_input.lower() in ['quit', 'exit']:
            break
        
        response = agent.invoke({"messages": [HumanMessage(content=user_input)]})
        print(f"Assistant: {response['messages'][-1].content}")

Framework Comparison Context

LangGraph serves as the primary implementation framework, designed for comparison with:

  • OpenAI Agents SDK: Native function calling
  • Smolagents: HuggingFace code-based approach
  • CrewAI: Multi-agent orchestration
  • Pydantic AI: Type-safe agent development

Business Application Examples

Bakery Management Agent ("La Boulangère Augmentée")

  • Stock management with automatic reorder suggestions
  • Sales analysis with trend identification
  • Production planning based on weather forecasts
  • Supplier communication with approval workflows

Success Metrics

  • End-to-end scenario completion rates
  • Tool integration reliability
  • Response time for complex multi-step workflows
  • User experience quality in conversational flow

See also