LangChain & LangGraph
LangChain (LCEL)
Chain Composition
from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser
prompt = ChatPromptTemplate.from_template("Explain {topic} in simple terms")
model = ChatOpenAI(model="gpt-4o")
chain = prompt | model | StrOutputParser()
result = chain.invoke({"topic": "quantum computing"})
Tool Binding
from langchain_core.tools import tool
@tool
def search(query: str) -> str:
"""Search the web for information."""
return web_search(query)
model_with_tools = model.bind_tools([search])
LangGraph (State Machines)
Core Concepts
from langgraph.graph import StateGraph, START, END
from typing import TypedDict, Annotated
from operator import add
class State(TypedDict):
messages: Annotated[list, add]
next_step: str
graph = StateGraph(State)
def analyze(state: State) -> dict:
response = model.invoke(state["messages"])
return {"messages": [response]}
def decide(state: State) -> dict:
last = state["messages"][-1]
if "DONE" in last.content:
return {"next_step": "end"}
return {"next_step": "analyze"}
graph.add_node("analyze", analyze)
graph.add_node("decide", decide)
graph.add_edge(START, "analyze")
graph.add_edge("analyze", "decide")
graph.add_conditional_edges("decide", lambda s: s["next_step"],
{"analyze": "analyze", "end": END})
app = graph.compile()
result = app.invoke({"messages": [("user", "Review this code")]})
Checkpointing (Memory)
from langgraph.checkpoint.memory import MemorySaver
memory = MemorySaver()
app = graph.compile(checkpointer=memory)
# Resume from checkpoint
config = {"configurable": {"thread_id": "session-1"}}
result = app.invoke({"messages": [msg]}, config=config)
Human-in-the-Loop
from langgraph.types import interrupt, Command
def sensitive_action(state: State) -> dict:
approval = interrupt({"action": "delete_file", "path": "/important.txt"})
if approval == "yes":
delete_file("/important.txt")
return {"messages": ["Action completed"]}
Multi-Agent Pattern
# Supervisor routes to specialized agents
def supervisor(state):
response = model.invoke(
"Route to: researcher, coder, or reviewer. " + state["messages"][-1]
)
return {"next_step": response.content.strip().lower()}
graph.add_node("supervisor", supervisor)
graph.add_node("researcher", researcher_fn)
graph.add_node("coder", coder_fn)
graph.add_node("reviewer", reviewer_fn)
graph.add_conditional_edges("supervisor", lambda s: s["next_step"],
{"researcher": "researcher", "coder": "coder", "reviewer": "reviewer"})
When to Use
| Scenario |
Use |
| Simple chains |
LangChain LCEL |
| Stateful workflows |
LangGraph |
| Multi-agent orchestration |
LangGraph with supervisor |
| RAG pipelines |
LangChain + retrievers |
| Human approval flows |
LangGraph interrupt |
Sources