08F.15 Patterns, Pitfalls and Migration
Twelve lessons taught you what LangChain and LangGraph can do. This one is about what happens next: the application is real, it has users and a bill, and the libraries underneath it change every week. Three questions decide whether it stays healthy. What does a good production application built on this stack look like (the patterns that survive contact with traffic)? What do bad ones look like (the anti-patterns, each with the symptom you will actually see)? And how do you move code that was written for an older version, or copied from an older tutorial, onto the current API without breaking behaviour you cannot see?
The third question gets the most room, because it is the one nobody can avoid. LangChain 0.x, LangChain 1.x, AgentExecutor, langgraph.prebuilt.create_react_agent, create_agent, langchain-classic, langchain-community and langgraph-supervisor are all in circulation at the same time, and a model that helps you write code was trained on all of them. So this lesson runs the old and the new side by side with the same scripted model, shows you what is different in the results and not only in the imports, hands you a scanner that inventories legacy usage in a repository, and turns deprecation warnings into build failures so that the next migration is never a surprise. It then covers the part everyone forgets until it hurts: dependency hygiene for a stack that installs 39 packages when you ask for one (the numbers are measured below), including a real lockfile diff that shows what a routine upgrade quietly adds. It closes by putting LangChain next to the frameworks of 08F.1 without repeating that lesson, and by giving you the checklists to use on Monday.
What you'll learn
- The production patterns that matter: one agent factory with house defaults, a deterministic workflow around agentic steps, state that is small and typed, side effects behind a decision and an idempotency key, one owner for every retry, a bound on every loop, a test ladder and a deprecation gate in CI
- The anti-patterns, each with a symptom, a cause, a fix and a runnable demonstration where one is cheap: over-chaining, hidden state, unbounded loops, swallowed errors, hiding tools as access control, framework types leaking into your domain, tests that assert model text
- A migration playbook: the version history and the release and deprecation policy (so you know what "deprecated" promises), a scanner that inventories legacy code, a gate that turns warnings into errors, and the order in which to move things
- Worked migrations, run for real:
AgentExecutortocreate_agent(includingmax_iterations, intermediate steps and what the old and new results look like),langgraph.prebuilt.create_react_agenttocreate_agent(prompt, hooks, node names),ConversationBufferWindowMemoryandLLMChainto a checkpointer andprompt | model, plus state, packages and behaviour changes - A ledger of every deprecation, rename and retirement found while writing this module (with the status each has today) and a table of every place the docs and the installed packages disagree
- Dependency hygiene for this stack: what an install pulls in, interlocking version bounds, lockfile diffs, a cooldown on new releases, integrations that nobody audits, retired packages, advisories, and building images from a lockfile
- How the LangChain stack compares with the other frameworks of 08F.1 once you stop comparing features, and what an exit plan looks like
What you don't need
- An API key, a running service or a database. Every sample here uses scripted fake chat models, plain-Python nodes, in-memory or SQLite checkpointers and the standard library, and every output shown is the real output of that code (15 November 2026). The few snippets that would need a provider or a server are labelled illustrative.
- The features themselves. This lesson links to the lesson that owns each one (08F.5 models, 08F.6 prompts and parsers, 08F.7 LCEL, 08F.8 agents and middleware, 08F.9 RAG, 08F.10 graphs, 08F.11 persistence, 08F.12 interrupts and failures, 08F.13 multi-agent) and adds what only becomes visible when you put them together or change versions.
- The four-way framework comparison. 08F.1 owns it. Part 5 here only asks what is different about leaving or joining the LangChain stack.
Setup
You need Python 3.11 or newer and uv (08F.4, Part 5). New to uv? The first uv add fails outside a project, so create one first.
uv init upgrade-lab --bare --python 3.13 && cd upgrade-lab # first time only
uv add langchain langgraph
uv add langchain-classic langgraph-checkpoint-sqlite # only for the legacy-versus-current samples in Part 3
uv add --dev pytest # only for the deprecation gate in 3.4
# or: pip install langchain langgraph langchain-classic langgraph-checkpoint-sqlite pytestNo == pins: uv add records a lower bound in pyproject.toml and the exact resolution in uv.lock. No API key is needed anywhere in this lesson. Every runnable sample imports one small helper file, fakes.py, a scripted chat model that accepts bind_tools (the same idea as the one built in 08F.8, 1.3), and a variant that records exactly what the model was shown on each call, which is how this lesson compares old and new code:
# fakes.py: a scripted chat model that accepts bind_tools (the same idea as 08F.8 and 08F.13)
from langchain_core.language_models.fake_chat_models import GenericFakeChatModel
class FakeToolCallingModel(GenericFakeChatModel):
"""Replays the AIMessages you give it, one per model call. It ignores the prompt."""
def bind_tools(self, tools, **kwargs):
return self
class RecordingModel(FakeToolCallingModel):
"""Like FakeToolCallingModel, but remembers what each call received."""
seen: list = []
def _generate(self, messages, *args, **kwargs):
self.seen.append([(type(m).__name__, m.text) for m in messages])
return super()._generate(messages, *args, **kwargs)Put fakes.py next to the samples and run each one with uv run python file.py. A scripted model returns its next prepared AIMessage on every call, so each sample decides in advance which tool to call; everything else (the real agents, graphs, middleware, checkpointers, and the legacy classes from langchain-classic) is the real library. When a script runs out, the next call raises StopIteration: if you copy a sample and see that, you have called an agent more times than it has replies.
Versions (current at time of writing). Facts about the packages, their history and their policies were verified on 14 November 2026 against PyPI, GitHub and docs.langchain.com; every sample was run on 15 November 2026 on Python 3.13 with langchain 1.5.0, langchain-core 1.8.0, langgraph 1.2.22, langgraph-prebuilt 1.1.2, langgraph-checkpoint 4.3.2, langgraph-checkpoint-sqlite 3.1.3 and langchain-classic 1.0.8 (the sample v00_versions.py printed exactly these). Re-running it on 18 November 2026 printed the same list except langchain-core 1.8.2 (a patch released on 17 November), and an independent re-run of the samples that day produced the same output. langgraph ships a patch most weeks and langchain a minor every few months, so treat every version number here as a dated observation and read 08F.4, 5.10 for upgrading on purpose.
What you must be able to do after this lesson#
- Apply the production patterns for a LangChain agent codebase
- Spot the common anti-patterns and fix them
- Migrate legacy code such as AgentExecutor to create_agent
- Pin and review dependencies for the LangChain stack
Why this matters for an AI engineer#
| You'll hear... | You'll understand it after... |
|---|---|
"Our agent uses AgentExecutor. Is that a problem?" |
3.5 |
"This tutorial imports create_react_agent from langgraph.prebuilt." |
3.6 |
"ConversationBufferMemory is gone. Where did the memory go?" |
3.7 |
| "How long do deprecated APIs keep working?" | 3.2 |
| "How do I find every legacy import in a large repository?" | 3.3 |
| "Make the build fail when someone writes deprecated code." | 3.4 |
"What is langchain-classic and is it safe to depend on it?" |
3.8 |
"langgraph-supervisor and langchain-community are dead?" |
3.10, 5.5 |
| "Which names changed, and which docs are wrong?" | Part 4: the ledger and 4.2 |
| "What should every production agent have by default?" | 1.2 |
| "Retries seem to multiply." | 1.6 |
| "Our agents leak data between users." | 2.2 |
| "Do we really need five chained prompts?" | 2.1 |
"A routine uv lock --upgrade added packages. Is that normal?" |
5.4 |
| "Should we leave LangChain?" | Part 6 |
Part 1: Production patterns#
A pattern in this lesson is not a new API. It is a decision that the previous lessons made possible and that teams that run these systems for a year tend to converge on. Each one below says what to do, why, what it costs, and which lesson owns the mechanism. They fit together: the factory of 1.2 applies the limits of 1.7, the workflow of 1.3 uses the state discipline of 1.4 and the effect rules of 1.5, and the tests of 1.8 prove all of it.
1.1 The default shape: three layers, and where you stop#
The stack has layers, and the first decision is how far down you go.
flowchart TB
subgraph yours ["Your code: what you own and test"]
tools["Tools as plain functions"]
prompts["Versioned prompts"]
domain["Domain types and policies"]
end
subgraph lc ["langchain: the agent framework"]
factory["agent factory with house defaults"]
agent["create_agent loop"]
mw["middleware: limits, retries, approval, PII"]
end
subgraph lg ["langgraph: the runtime"]
sg["StateGraph, state, reducers"]
cp["checkpointer and Store"]
intr["interrupt, streaming, timeouts"]
end
providers["provider packages: langchain-openai, langchain-anthropic, ..."]
smith["LangSmith: traces, datasets, evals"]
yours --> factory
factory --> agent
agent --> mw
agent --> sg
sg --> cp
sg --> intr
agent --> providers
agent -.-> smith
sg -.-> smith08F.4, Part 1 named the layers: the framework (langchain, with create_agent and middleware), the runtime (langgraph, with state, checkpoints, interrupts and streaming) and, above them, a harness (Deep Agents) for long multi-step work. The v1 release notes make a point that shapes everything here: you do not need to learn LangGraph to use the persistence, streaming, human-in-the-loop and time-travel features of create_agent, because they come with the graph it returns (08F.8, 7.8). You drop a layer when you need what only the lower one offers: fine-grained control of the flow, durable execution, or a mix of deterministic and agentic steps (the product documentation's own criteria).
| You need | Stop at | Why |
|---|---|---|
| A tool-using assistant with standard limits, approval and redaction | create_agent + middleware |
The loop, state, streaming and persistence come free; the hooks cover the usual customization (08F.8) |
| A fixed pipeline with no loop (retrieve, rank, answer) | LCEL or plain Python | No agent needed (08F.7) |
| Branches, fan-out, your own loop conditions, humans at several points | StateGraph with create_agent nodes where useful |
You own the shape (08F.10) |
| Multi-hour research or coding with planning and files | A harness (Deep Agents, survey in 08F.4, Part 6) | It packages those capabilities |
| One call, or an existing loop you trust | Provider SDK or your own loop (08A.2) | Fewest moving parts (08F.4, 7.4) |
1.2 Pattern: one factory with house defaults#
The most valuable ten lines in a codebase with several agents are the ones that build every agent. Without them each agent gets its own subset of the safety settings, and the one that is missing a limit is the one that loops overnight. A factory function centralizes the defaults, and a test proves they hold.
# p01_factory.py: ONE function that builds every agent with the house defaults,
# and checks that the defaults really bound a runaway model and a repeated side effect.
import itertools
from dataclasses import dataclass
from langgraph.checkpoint.memory import InMemorySaver
from langchain.agents import create_agent
from langchain.agents.middleware import ModelCallLimitMiddleware, ToolCallLimitMiddleware, ToolRetryMiddleware
from langchain.messages import AIMessage, HumanMessage, ToolCall
from langchain.tools import tool
from fakes import FakeToolCallingModel
@dataclass(frozen=True)
class HouseDefaults:
model_calls_per_run: int = 8 # a little above the longest healthy run seen in traces
model_calls_per_thread: int = 60 # a conversation budget (needs a checkpointer)
retries_for_read_tools: int = 2
def build_agent(model, tools, *, name, system_prompt, checkpointer, read_only=(), one_per_run=(), defaults=HouseDefaults()):
"""read_only: tool names that are safe to retry. one_per_run: side-effect tools capped at one call per run."""
middleware = [
ModelCallLimitMiddleware(run_limit=defaults.model_calls_per_run, thread_limit=defaults.model_calls_per_thread, exit_behavior="end"),
*[ToolCallLimitMiddleware(tool_name=t, run_limit=1) for t in one_per_run],
]
if read_only: # never retry a tool that has side effects
middleware.append(ToolRetryMiddleware(max_retries=defaults.retries_for_read_tools, tools=list(read_only), on_failure="error"))
return create_agent(model, tools=tools, name=name, system_prompt=system_prompt, middleware=middleware, checkpointer=checkpointer)
@tool
def lookup_order(order_id: str) -> str:
"""Look up an order."""
return f"Order {order_id}: shipped"
REFUNDS: list[str] = []
@tool
def issue_refund(order_id: str) -> str:
"""Refund an order (a side effect)."""
REFUNDS.append(order_id)
return f"refunded {order_id}"
def calls(*pairs):
return AIMessage(content="", tool_calls=[ToolCall(name=n, args={"order_id": o}, id=f"c{i}-{n}") for i, (n, o) in enumerate(pairs)])
def agent_for(script):
return build_agent(FakeToolCallingModel(messages=script), [lookup_order, issue_refund], name="support",
system_prompt="You are a support agent.", checkpointer=InMemorySaver(),
read_only=["lookup_order"], one_per_run=["issue_refund"])
def config(thread):
return {"configurable": {"thread_id": thread}}
# 1. a model that never stops is ended by the run limit, normally, with its state intact
runaway = agent_for(calls(("lookup_order", "A-1")) for _ in itertools.count())
result = runaway.invoke({"messages": [HumanMessage("go")]}, config("t1"))
print("1) runaway model ->", result["messages"][-1].text)
# 2. a model that asks for the refund twice in one run: the second call is refused, the run continues
REFUNDS.clear()
script = iter([calls(("issue_refund", "A-1")), calls(("issue_refund", "A-1")), AIMessage(content="done")])
result = agent_for(script).invoke({"messages": [HumanMessage("refund it")]}, config("t2"))
print("2) refunds actually issued:", REFUNDS)
print(" tool messages:", [m.content for m in result["messages"] if m.type == "tool"])
print(" final:", result["messages"][-1].text)1) runaway model -> Model call limits exceeded: run limit (8/8)
2) refunds actually issued: ['A-1']
tool messages: ['refunded A-1', "Tool call limit exceeded. Do not call 'issue_refund' again."]
final: doneWhat each default is for, and how to choose it:
| Default | What it does | How to pick the number |
|---|---|---|
ModelCallLimitMiddleware(run_limit=8, exit_behavior="end") |
Ends a run normally, with a message and the state intact, after eight model calls (check 1 above: the runaway model stopped at 8/8) | A little above the longest healthy run you see in traces (11A.5); exit_behavior="error" instead for batch jobs where an overrun should page someone |
thread_limit=60 |
A budget for a whole conversation. It needs a checkpointer (the factory takes one as a required argument for that reason) | From the longest conversation a user should reasonably have before a new thread |
ToolCallLimitMiddleware(tool_name=..., run_limit=1) for side-effect tools |
A second issue_refund in one run is refused with a message and the run continues (check 2: only one refund was issued) |
One per run for anything that costs money or cannot be undone; a handful for searches |
ToolRetryMiddleware(..., tools=[read-only names]) |
Retries transient failures of tools that are safe to repeat, and only those | Two retries is plenty; see 1.6 for who else may be retrying |
name= |
The agent's node name when it becomes part of a graph, and its label in traces | Always set it (08F.13, 3.5) |
Three things the factory deliberately leaves out, because they differ by product: PII redaction, human approval and summarization are middleware you add per agent, in the order that 08F.8, 8.6 gives. Extend the factory with an extra_middleware=() argument if you want them to flow through the same door.
1.3 Pattern: a deterministic workflow around the agentic step#
The most reliable LLM systems in production are not "one big agent". They are ordinary programs in which one or two steps are agentic and everything around them is code. 08A.9 gave the argument (every step you turn into code has a probability of failure of zero for the part you wrote, and the compounding arithmetic of 08A.9, 5.1 punishes every extra model call). In this stack the expression of it is a StateGraph whose nodes are mostly plain functions, with a bounded create_agent as one node.
flowchart LR
inp["input"] --> validate["validate (plain code)"]
validate -->|"invalid"| reject["reject with a reason"]
validate -->|"ok"| agentstep["research agent (create_agent, bounded)"]
agentstep --> gate{"quality gate (deterministic)"}
gate -->|"fails, attempts left"| agentstep
gate -->|"fails, no attempts left"| human["human review (interrupt)"]
gate -->|"passes"| approve{"irreversible step?"}
approve -->|"yes"| human
approve -->|"no"| effect["effect node (idempotency key)"]
human -->|"approved"| effect
human -->|"rejected"| reject
effect --> done["done"]| Step | Make it | Why |
|---|---|---|
| Validate the request (shape, size, authorization) | Plain code, first | It is free, certain and fails fast. An agent should never see a request that code could have refused |
| The open-ended work (research, drafting, tool use) | A bounded create_agent node with a name and a typed result (structured response) |
It is the one place the model's judgement is needed; the types make the next step checkable |
| The quality gate | Deterministic checks first (citations present, schema valid, length, banned content), a model grader only for what code cannot test | Cheap checks catch most failures; the loop back to the agent has an attempts counter in state |
| The irreversible step (send, pay, delete) | Its own node, after the decision, behind an interrupt() when a human should approve, and carrying an idempotency key (1.5) |
Retries and resumes re-run a node from its first line |
| Failure and escalation | An explicit path (human review, a polite refusal), never "try again forever" | Every loop needs an exit |
08F.13, Part 6 builds exactly this with a supervisor inside, and 08F.12, Part 11 builds the refund workflow with its tests. Use them as templates. The test of whether you have the pattern right is whether you can draw the graph and point at the model calls: each one should be there for a reason you can state.
1.4 Pattern: state discipline#
Almost every LangGraph bug that is not a typo is a state bug: a key with no reducer, a list that doubles, a value that vanished on resume, a global that two users share. The discipline fits in one table (which of the three kinds of data goes where) and five rules.
| The data | Put it in | Because |
|---|---|---|
| The run's input and what later nodes must read | State (a TypedDict) |
It is checkpointed and visible to every node (08F.10, Part 3) |
| Static per-run facts: user id, tenant, locale, a database handle | Context (context_schema, runtime.context) |
It is typed and per run. It is not saved in checkpoints, so pass it again on every call, including the resume (08F.10, Part 9, 08F.12, 6.2) |
| The conversation inside one thread | State + a checkpointer + a stable thread_id |
Short-term memory (08F.11, Part 1) |
| Facts that outlive a thread (preferences, profile) | The Store | Long-term memory, with namespaces and TTL (08F.11, Part 7) |
| Data you can cheaply recompute from state | Nowhere: recompute it | The official guidance is to persist only what later nodes need and cannot cheaply recompute |
| Large blobs (files, tables, images) | Object storage, with a reference in state | Checkpoints are rewritten at every step (08F.11, 5.6) |
| Secrets, API keys, connection objects | The environment and your process | Never in state: state is written to a database |
The five rules:
- Return updates, never mutate. Nodes "should return updates to the state directly". 08F.10, 15.1 showed what in-place mutation does: a shared list appears to change, a reassigned key is lost, and the
updatesstream showsNone. - Any key that two parallel nodes can write needs a reducer. Otherwise you get an
InvalidUpdateErrorat best and an overwrite at worst (08F.10, 3.3). - Use
TypedDictfor state.create_agentrequires it (the migration guide says Pydantic and dataclass state are no longer supported). The official graph docs also warn that Pydantic state performs runtime type coercion, which "can also produce unexpected values". Section 3.9 shows what 1.5.0 actually does with a Pydantic class. - Mark optional keys
NotRequired, and give callers an input and output schema so that the internals are not a public contract (08F.10, Part 8). - Evolve the schema like a database table. Adding a key is compatible. Renaming one drops the saved value for threads in flight, so add the new key, migrate, then remove the old one; stamp a
flow_versionin state if business logic changes (08F.10, 14.1).
1.5 Pattern: decide, then act#
A LangGraph node can run more than once. A retry re-runs it, a resume after a crash re-runs it, and an interrupt() re-runs it from its first line when the human answers. That gives you at-least-once execution, and it is the rule behind every durable-execution bug (08F.10, 4.7, 08F.11, 4.2). The pattern that makes it safe has three parts.
- Split the decision from the effect. One node decides ("refund 49.90 to this order") and writes the decision to state. The next node performs it. The checkpoint between them stops a retry of the effect from deciding twice.
- Derive the idempotency key from durable state, not from the node. A key generated inside the node (
uuid4()) is different on every attempt and protects nothing. A key built from what is already saved is the same every time:
# illustrative: `payments` stands for your payment client; nothing here calls a real service
def refund_node(state: RefundState) -> dict:
key = f"refund:{state['case_id']}:{state['decision_version']}" # same on every attempt
receipt = payments.refund(order_id=state["order_id"], cents=state["amount_cents"], idempotency_key=key)
return {"receipt_id": receipt.id}- Put any
interrupt()before the side effect, or make what comes before it idempotent. Code above an interrupt runs again on resume (08F.12, 4.4).
This sample is illustrative, because it needs a payment service. The mechanism, with the real retry and resume behaviour, is taught and run in 08F.11, 4.3 and 08F.12, 7.4. At the agent level the same rule is why 08F.8 says never to retry a side-effect tool with a blanket retry middleware.
1.6 Pattern: one owner for every retry#
Retries are the one reliability feature that is implemented at many layers, and the layers do not know about each other.
| Layer | Where it lives | What it retries |
|---|---|---|
| The provider SDK | max_retries on the model class is the SDK client's own retry, not a separate layer (as 08F.5 measured: OpenAI the SDK's own default, Anthropic 2, Google 6; the docs page that says 6 is not accurate for all). ChatOllama ignores it: it has no such field (08F.5, 2.3), so for Ollama there is no SDK owner at all |
Transport failures inside one call, including a streamed call (which with_retry does not cover) |
with_retry |
A runnable, in an LCEL chain (08F.7) | Whatever exception you list (default: all of them), but only for invoke, ainvoke, batch and abatch: under stream, astream and astream_events it is skipped with no error (08F.7, 6.2) |
ModelRetryMiddleware |
create_agent (08F.8, 8.10) |
The model call. Its default is on_failure="continue": when the attempts run out it returns an AIMessage saying the call failed instead of raising, so an outer fallback never fires |
ModelFallbackMiddleware |
create_agent (same section) |
The next model, on every exception: it has no exception filter, so your own bug or a revoked key fails over too |
ToolRetryMiddleware |
create_agent |
A tool call |
RetryPolicy on a node |
add_node(..., retry_policy=...) (08F.12, 7.2) |
The whole node body |
| Your HTTP client or task queue | Outside the framework | The whole request or job |
| The caller | A user pressing "retry" | Everything |
Stack two of them and the attempts multiply. This run puts a tool that always fails behind with_retry (3 attempts) and a node RetryPolicy (3 attempts):
# a03_retry_stack.py: retries multiply when two layers both own them. A tool that always fails,
# wrapped in with_retry (3 attempts) inside a graph node with a RetryPolicy (3 attempts).
from langchain_core.runnables import RunnableLambda
from langgraph.graph import END, START, StateGraph
from langgraph.types import RetryPolicy
from typing_extensions import TypedDict
attempts = {"count": 0}
def flaky_api(_: dict) -> dict:
attempts["count"] += 1 # every real attempt hits the (paid, rate-limited) service
raise ConnectionError("upstream is down")
class State(TypedDict, total=False):
result: dict
inner = RunnableLambda(flaky_api).with_retry(
retry_if_exception_type=(ConnectionError,), stop_after_attempt=3, wait_exponential_jitter=False
)
def call_service(state: State) -> dict:
return {"result": inner.invoke({})}
def run(label: str, node_retry: RetryPolicy | None, with_inner: bool) -> None:
attempts["count"] = 0
fn = call_service if with_inner else (lambda state: {"result": flaky_api({})})
builder = StateGraph(State)
builder.add_node("call", fn, retry_policy=node_retry)
graph = builder.add_edge(START, "call").add_edge("call", END).compile()
try:
graph.invoke({})
except ConnectionError:
pass
print(f"{label:<52} real attempts: {attempts['count']}")
policy = RetryPolicy(max_attempts=3, initial_interval=0.01, jitter=False)
run("with_retry only (3 attempts)", None, True)
run("node RetryPolicy only (3 attempts)", policy, False)
run("both: with_retry inside a node with RetryPolicy", policy, True)with_retry only (3 attempts) real attempts: 3
node RetryPolicy only (3 attempts) real attempts: 3
both: with_retry inside a node with RetryPolicy real attempts: 9Three plus three is not six, it is nine, and each of the nine hits a service that may charge per call or throttle you for the very storm you are creating. The rule is choose one owner per failure class:
| Failure | Owner | Not |
|---|---|---|
| A transient network error talking to a model | The provider package's max_retries (small), or ModelRetryMiddleware. Google and Ollama connection failures and timeouts are raw transport exceptions (httpx.TransportError, or httpx2.TransportError where google-genai 3.x is installed), which are not ModelError subclasses: name both in retry_if_exception_type, retry_on and exceptions_to_handle, or nobody retries and nothing fails over. On ChatOllama the middleware is the only owner; on a streaming endpoint the SDK max_retries or the middleware is, because with_retry is skipped |
Both, and not with_retry as well (08F.5, 11.1 and 11.2, 08F.7, 6.1) |
| A model that returned malformed structured output | The structured-output strategy's own correction path (08F.6) | A blanket with_retry around the whole chain, which re-bills the whole generation |
| A flaky read-only tool | ToolRetryMiddleware on that tool |
A node RetryPolicy around the agent |
| A non-agent graph node that calls an API | RetryPolicy on the node (restrict retry_on) |
A with_retry inside the node as well |
| A side-effect tool | Nobody, unless it carries an idempotency key | Any automatic retry |
08F.12, 7.8 and 08F.8, 8.10 have the details, including the order of fallback and retry middleware (fallback outside, retry inside, and ModelRetryMiddleware(on_failure="error"), because with its default "continue" the fallback is never reached) and the fact that an interrupt() bypasses retries entirely. Provoke each provider's real errors once, against a dead port, before you write the exception list: the class that arrives is the provider package's choice, not yours.
1.7 Pattern: bound everything#
An agent system is a set of loops, and an unbounded loop is a cost incident waiting for the right input. Write the bound for each loop next to the loop, the way you write a timeout next to a network call. This is the inventory:
| Loop or growth | The bound | Default if you do nothing | Where taught |
|---|---|---|---|
| The agent's model-and-tool loop | ModelCallLimitMiddleware (run_limit, thread_limit) |
None. The recursion limit is 10,007 steps for a graph (the older 25 applies only to plain runnables) | 08F.8, 7.5 |
| Calls to one tool | ToolCallLimitMiddleware(tool_name=..., run_limit=...) |
None (and a tool limit alone is not a loop limit) | 08F.8, 7.5 |
| A cycle in a graph you drew | A counter in state plus a conditional edge; RemainingSteps to route to a finish path before the error; a top-level recursion_limit |
10,007 (a limit under configurable is silently ignored) |
08F.10, Part 11 |
| Handoffs between agents | A dispatch node that counts them | The recursion limit | 08F.13, 4.5 |
| A quality-gate or reflection loop | An attempts counter, with a human or refusal exit | None | 08F.13, Part 6 |
| A human validation loop | A conditional edge back to the node, never while True around interrupt() |
None | 08F.12, 3.4 |
| Retries | max_attempts, stop_after_attempt, max_retries |
Varies by layer (1.6) | 08F.12, 7.2 |
| Parallel fan-out | max_concurrency; remember that cost multiplies |
Unbounded fan-out | 08F.10, 7.4 |
| Wall-clock time | Model and tool timeout=, node TimeoutPolicy (async nodes only), a request deadline, RunControl drain for shutdown |
None | 08F.12, Parts 8 and 10 |
| Money and tokens | Track usage_metadata per call; alert on a distribution, not an average |
Nothing counts for you | 08A.14, 2.6 |
| History length | SummarizationMiddleware or trimming in a model-call hook |
The thread grows forever | 08F.8, 8.8 |
| Checkpoint and store growth | Retention and pruning, TTL on the store, DeltaChannel (beta) for long lists |
Everything is kept | 08F.11, 5.5 and 5.6 |
1.8 Pattern: a test ladder, and what each rung cannot tell you#
Everything in this module can be tested without a key, and the cheapest tests catch the most expensive bugs. The ladder, from cheapest to most expensive:
| Rung | What it tests | Tool | Cannot tell you |
|---|---|---|---|
| 1. Tools as plain functions | Business logic, argument handling | pytest |
Whether the model will call them well |
| 2. Nodes as plain functions | State in, update out | pytest, a dict |
How nodes combine |
3. Graph or agent with a scripted model and InMemorySaver |
The path taken, the message history, the budgets, interrupts and resumes | GenericFakeChatModel subclasses (08F.8, Part 12, 08F.10, 13.3, 08F.13, Part 9) |
Whether the real model chooses that path |
| 4. Recorded integration tests | The provider package's request and response handling | pytest markers and cassettes (stale after any prompt or tool change) |
Drift in the live API |
| 5. Trajectory and outcome evaluations | The real model's behaviour on a dataset | LangSmith experiments, Module 10A | Anything outside the dataset |
| 6. Live smoke tests | One cheap real call per provider and release | A small marked test | Correctness: it only shows the wiring works |
Four habits that make the ladder work:
- Assert structure, not prose. Assert the tools called, their arguments, the nodes visited and the final state keys; assert that the history is valid (every tool call answered). Asserting an exact model sentence is a test of the scripted reply, and it breaks the day you reword a prompt.
- Build the fake inside the test. A scripted model holds an iterator that is consumed once, so a module-level fixture shared between tests gives each test whatever the previous one left behind. Use a function-scoped fixture or a factory.
- Keep one golden-trajectory test per agent: fixed input, fixed scripted replies, exact assertions on tool calls and final output. It catches the class of bugs frameworks introduce silently (reordered messages, dropped ids, changed defaults), which is exactly what a version upgrade is (08F.1, 5.2).
- Assert the topology too.
agent.get_graph()lists the nodes; a test that fails when a node disappears catches a middleware that was dropped by a refactor (08F.10, 13.3).
A rung that has become non-optional is the deprecation gate of 3.4: a test configuration that turns this stack's deprecation warnings into failures, so that deprecated code cannot be merged without someone deciding to.
1.9 Pattern: make every run findable#
When something goes wrong at 2 a.m. the first question is "which run was that?". Answer it before it is asked: name the graph and the agents, and put a run name, tags and metadata on every call. 08F.7, 4.1 explained the config keys, and 11A.5 owns tracing. The habit is a few lines in your call wrapper:
# illustrative: the config keys are real (08F.7); wire them into whatever calls your agent
config = {
"configurable": {"thread_id": conversation_id}, # stable per conversation (08F.11)
"run_name": "support-agent", # the label you will search for
"tags": ["prod", "support"], # filter dimensions
"metadata": {"release": "2026-11-15", "tenant_hash": tenant_hash}, # never raw PII
}
result = agent.invoke({"messages": [("user", question)]}, config, context=Ctx(user_id=user_id))This fragment is illustrative: agent, Ctx, conversation_id and the other names come from your application, and nothing in it calls a provider by itself.
The release tag earns its keep during a migration: it lets you compare traces from before and after for the same inputs (3.12).
1.10 Pattern: a secure default stance#
Security belongs to Module 12, and 08A.14 owns agent safety. What this stack adds is a handful of places where it is easy to be unsafe by default. Treat the table as a review checklist.
| Default to | Because | Taught in |
|---|---|---|
| Least privilege for tools and credentials (read-only where possible, sandboxed code execution) | The official security guidance is to assume misuse and use defence in depth | 08A.14, 2.8, 12.6 |
| Filtering the tool list is not authorization | A tool the model was not offered still ran when the model emitted its name. Check inside the tool or in wrap_tool_call |
08F.8, 9.3, 08F.13, 4.4 |
| Checkpoints are trusted data | Deserializing a checkpoint is code you did not write running; pickle is a code-execution format; keep pickle_fallback off, consider strict msgpack mode and encryption at rest |
08F.11, Part 6 |
Never load() data you did not write |
It instantiates the Python objects named in the data | 08F.5 |
| A pulled prompt is configuration, not text | A prompt manifest can carry a model's base_url or headers, so a manifest from someone else can point your traffic at their server |
08F.6 |
No jinja2 templates from untrusted sources |
The sandbox reduces damage; it is not a security boundary | 08F.6 |
| Do not let a request choose configurable model fields freely | configurable_fields="any" lets api_key and base_url be set at run time |
08F.7 |
| A string MCP target can be a script path | User input became a launched process | 08F.8, 6.6 |
| A skill is trusted text; a retrieved document is untrusted text | Both become instructions in the context; "no prompt or delimiter strategy fully prevents indirect prompt injection" | 08F.13, 5.3, 08F.9 |
| Do not forward raw event streams to a browser | Events carry full prompts and outputs | 08F.7, 08F.14 |
| Plan erasure at the thread level, and for the store separately | A summary does not remove the originals from earlier checkpoints, and deleting a thread leaves the store alone | 08F.11, 5.5 |
| Treat dependencies as part of the attack surface | The advisories on these repositories are mostly deserialization and injection bugs | Part 5 |
1.11 Pattern: operating the thing (a survey)#
Deployment is 11A.5's subject. A few facts from the official documentation belong in a patterns lesson because they are the ones that surprise teams.
langgraph devand Docker Compose are not production. The self-hosting docs point production at Kubernetes with the Helm chart; other orchestrators have "known gaps that you must implement and maintain yourself".- The server provides its own persistence. On the Agent Server, "do not configure" a checkpointer or store in your graph code: the platform injects them. A graph that works locally with
InMemorySaveris not the artefact you deploy. - Keep graph factories light. Factory functions run per invocation on the server; prefer exporting a compiled graph.
- Image builds can ignore your lockfile. A
langgraph.jsonwith"dependencies": ["."]re-resolves packages frompyproject.tomlwhen the image is built and does not useuv.lock. Usesource: {"kind": "uv"}for lockfile reproducibility (5.7). - Deployments follow the stable stream unless you pin it. The Agent Server has
latest,rcandstablestreams, and a deployment moves to the newest stable on each revision unlessapi_versionis pinned inlanggraph.json. - Upgrade clients before the server. The
langchain-core1.7.0 changelog (October 2026) says so for a streaming change, and notes thatlangchainanddeepagentsaccept anylangchain-core1.x, so an unrelated upgrade can pull a new core silently. Holding a server back meant pinninglangchain-core<1.7.0, in the docs' own words. - Fault tolerance is first-class since LangGraph 1.2 (May 2026): per-node timeouts and error handlers, graceful drain, retry policies, and
DeltaChannel(beta) to shrink checkpoints (08F.12).
Part 2: Anti-patterns#
An anti-pattern is a design that looks reasonable, works in the demo and fails in production in a way that is expensive to diagnose. Each section below gives the smell, the symptom you will actually see, the cause, and the fix. Where a demonstration is cheap it is run for real. Section 2.7 collects every anti-pattern from this module into one catalogue.
2.1 Over-chaining#
The smell. One task is split into a chain of model calls because each step feels separate: classify, then extract the name, then extract the order id, then judge the sentiment, then assemble. Chains are easy to write in LCEL (a | b | c), which is exactly why they multiply.
The symptom. Latency adds up, because the calls are serial. The bill grows faster than the feature, because each step re-sends the ticket and the answers so far. Reliability drops, because the chain only succeeds if every link does. Each step is also another prompt to write, version, test and keep consistent with the others. The same job, run both ways with scripted models that count what they receive:
# a01_overchain.py: the same ticket-triage job as a four-call chain and as ONE structured call.
# Scripted models count how many model calls happen and how many characters are sent.
from pydantic import BaseModel
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.runnables import RunnableLambda, RunnablePassthrough
from langchain.messages import AIMessage, ToolCall
from fakes import FakeToolCallingModel
TICKET = "Hi, I'm Asha Rao. Order A-1042 (a desk lamp) arrived with a cracked base and I want a refund. Very annoyed."
class Triage(BaseModel):
category: str
customer: str
order_id: str
sentiment: str
class CountingModel(FakeToolCallingModel):
"""Counts calls and characters sent; replays its script."""
calls: int = 0
chars_sent: int = 0
def _generate(self, messages, *args, **kwargs):
self.calls += 1
self.chars_sent += sum(len(m.text) for m in messages)
return super()._generate(messages, *args, **kwargs)
# ---- A: four chained calls, each re-sending the ticket and the earlier answers -----------------
model_a = CountingModel(messages=iter([AIMessage(content=t) for t in ["refund", "Asha Rao", "A-1042", "negative"]]))
def step(template: str):
return ChatPromptTemplate.from_template(template) | model_a | StrOutputParser()
chain = (
RunnablePassthrough.assign(category=step("Classify this ticket: {ticket}"))
| RunnablePassthrough.assign(customer=step("Customer name in: {ticket} (category {category})"))
| RunnablePassthrough.assign(order_id=step("Order id in: {ticket} (customer {customer})"))
| RunnablePassthrough.assign(sentiment=step("Sentiment of: {ticket} (order {order_id})"))
| RunnableLambda(lambda d: Triage(**{k: d[k] for k in Triage.model_fields}))
)
print("A) four-call chain ->", chain.invoke({"ticket": TICKET}))
print(f" model calls: {model_a.calls}, characters sent: {model_a.chars_sent}")
# ---- B: one structured-output call ----------------------------------------------------------------
call = ToolCall(name="Triage", args={"category": "refund", "customer": "Asha Rao", "order_id": "A-1042", "sentiment": "negative"}, id="c1")
model_b = CountingModel(messages=iter([AIMessage(content="", tool_calls=[call])]))
structured = ChatPromptTemplate.from_template("Fill in the triage record for this ticket: {ticket}") | model_b.with_structured_output(Triage)
print("B) one structured call ->", structured.invoke({"ticket": TICKET}))
print(f" model calls: {model_b.calls}, characters sent: {model_b.chars_sent}")A) four-call chain -> category='refund' customer='Asha Rao' order_id='A-1042' sentiment='negative'
model calls: 4, characters sent: 548
B) one structured call -> category='refund' customer='Asha Rao' order_id='A-1042' sentiment='negative'
model calls: 1, characters sent: 150The results are identical; the cost is not. Four calls instead of one, and about three and a half times the text sent (characters, a rough proxy for tokens; the ratio is the lesson, because these are scripted replies and not a real tokenizer, 02.2). The compounding arithmetic is in 08A.9, 5.1: if each call were right 95 times in 100, four in a row would be right about 81 times in 100, whereas the single call keeps its 95. This is illustrative arithmetic, not a measurement of any model.
When a chain is right. Splitting is justified when a step needs something a merged call cannot have. Ask whether any of these is true; if none is, merge the steps.
| A chain earns its place when... | Example |
|---|---|
| A deterministic check or tool must run between the calls | Look up the order in the database after extraction, then draft the reply from what was found |
| The steps need different models, permissions or tools | A cheap model classifies; a strong model writes; only the writer may call the refund tool |
| The input is too large for one call | Map-reduce over many documents (08F.10, Part 7) |
| The steps are independent and can run in parallel | RunnableParallel (08F.7), not a serial chain |
| A step's output is reviewed by a human or a gate | Draft, then approval, then send |
The fix. Ask for all the fields in one structured-output call (08F.6), let tools fetch what only data can supply, run independent parts in parallel, and use plain code for transformation. The test for any chain is the question: what would change if I put a deterministic function between these two calls? If nothing, they are one call.
2.2 Hidden state#
The smell. "Memory" kept in a module-level variable, a class attribute, a closure, a default argument or a cache, instead of in graph state under a thread_id.
The symptom. It works in a notebook with one user and fails in production in the worst possible way: one user sees another user's data. It also fails quietly in other forms: the value is gone after a restart, each of four server workers has a different copy, and a test passes alone and fails in the suite because an earlier test left something behind. Here is the whole bug in thirty lines, with a correct version next to it:
# a02_hidden_state.py: "memory" kept in a module-level variable versus in graph state with a thread_id.
from typing import Any
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.graph import END, START, StateGraph
from typing_extensions import TypedDict
LAST_ORDER: dict[str, str] = {} # hidden state: shared by every user of this process
class State(TypedDict, total=False):
user: str
message: str
order: str
reply: str
def remember_hidden(state: State) -> dict[str, Any]:
if state["message"].startswith("order "):
LAST_ORDER["id"] = state["message"].split()[1]
return {"reply": f"saved {LAST_ORDER['id']}"}
return {"reply": f"your last order is {LAST_ORDER.get('id', 'unknown')}"}
def remember_in_state(state: State) -> dict[str, Any]:
if state["message"].startswith("order "):
return {"order": state["message"].split()[1], "reply": f"saved {state['message'].split()[1]}"}
return {"reply": f"your last order is {state.get('order', 'unknown')}"}
def build(fn, checkpointer=None):
return StateGraph(State).add_node("n", fn).add_edge(START, "n").add_edge("n", END).compile(checkpointer=checkpointer)
def cfg(thread: str) -> dict:
return {"configurable": {"thread_id": thread}}
hidden = build(remember_hidden, InMemorySaver())
print("HIDDEN (module global)")
print(" alice:", hidden.invoke({"message": "order A-1042"}, cfg("alice"))["reply"])
print(" bob asks:", hidden.invoke({"message": "where is my order?"}, cfg("bob"))["reply"], " <- Alice's order")
proper = build(remember_in_state, InMemorySaver())
print("STATE (thread-scoped)")
print(" alice:", proper.invoke({"message": "order A-1042"}, cfg("alice"))["reply"])
print(" bob asks:", proper.invoke({"message": "where is my order?"}, cfg("bob"))["reply"])
print(" alice asks:", proper.invoke({"message": "where is my order?"}, cfg("alice"))["reply"])HIDDEN (module global)
alice: saved A-1042
bob asks: your last order is A-1042 <- Alice's order
STATE (thread-scoped)
alice: saved A-1042
bob asks: your last order is unknown
alice asks: your last order is A-1042Bob asked about his order and was told Alice's. The graph even had a checkpointer, and it did not help, because the data never went through it. The fixed version uses the order key of the state, scoped by thread_id, and Bob gets "unknown" while Alice still gets her own.
Where hidden state hides in this stack:
| Form | Why it is shared |
|---|---|
A module-level dict or list read and written by a node or tool |
One per process, so one per worker, shared by every user |
A mutable default argument (def node(state, seen=[])) |
Created once at import time |
| A closure over a list in your agent factory | The list lives as long as the agent object, which is every call |
An instance attribute on a custom middleware (self.count += 1) |
One middleware instance serves every run of the agent |
functools.lru_cache on a function whose arguments include user data |
The cache outlives the request, and may hold the data |
| A global "current user" set at the start of a request | Concurrent requests overwrite each other |
| A scripted fake model's iterator in a module-level test fixture | Consumed once; the next test inherits the leftovers (1.8) |
The fix. Per-run facts go in context, per-conversation facts in state with a checkpointer, cross-conversation facts in the Store (1.4). Sharing is fine for things that are immutable or thread-safe and do not hold user data: a compiled graph, a model object, an HTTP client, a connection pool, a compiled regex. The test is whether two concurrent users could ever observe each other through it.
2.3 Unbounded loops#
The smell. A loop whose only exit is the model deciding to stop: an agent with no step budget, a reflection loop with no attempt counter, two agents that hand the user back and forth, a validation loop that asks the human again forever.
The symptom. It depends on which loop. A single bound never covers all of them, so the symptoms are worth knowing:
| Loop | What you see | Why the default does not save you |
|---|---|---|
| The agent's model-and-tool loop | A bill spike with no errors; one run with hundreds of model calls | The recursion limit of a graph is 10,007 steps, roughly five thousand model calls, which is not a safety limit. The older 25 applies only to plain runnables |
| A cycle in a hand-built graph | GraphRecursionError after thousands of steps, or a run that never returns |
Same limit; and a recursion_limit placed under configurable is silently ignored: only the top-level key counts |
| Handoffs between agents | The user is passed back and forth; every turn costs two model calls | A Command.PARENT jump bypasses the edges after the node, so a router "after the agent" never sees the handoff (08F.13, 4.5) |
| A reflection or quality-gate loop | The same draft is regenerated until the limit | The gate has no attempts counter |
| A human validation loop | The same question is asked again and again | while True around interrupt() in one node re-runs from the top each time (08F.12, 3.4) |
| A tool that is capped but a model that keeps asking | The tool answers "limit exceeded" a hundred times | ToolCallLimitMiddleware with the default exit_behavior="continue" refuses the tool and lets the run go on. A tool limit alone is not a loop limit (08F.8, 7.5) |
thread_limit with no checkpointer |
The limit never counts | Thread-level limits need a checkpointer |
The cause, in one sentence: nothing in the loop counts anything you pay for. The fix is the inventory of 1.7: a counter next to every loop, an explicit exit path that ends with a human or a refusal, and the factory of 1.2 so that no agent is built without one. Do not raise the recursion limit to make an error go away: the error is the loop telling you it has no exit.
2.4 Swallowed and mishandled errors#
The smell. Error handling written to make the exception disappear instead of to decide what should happen.
| Anti-pattern | What goes wrong | Fix | Taught in |
|---|---|---|---|
A bare try/except around interrupt() |
The pause is implemented as an exception; swallowing it turns "wait for the human" into "carry on without asking" | Never wrap it; catch only specific exceptions around other code | 08F.12, 4.1 |
A blanket try/except in tool error middleware |
Hides your own bugs from the model and from you; network failures are retried by nothing | Catch only runtime input errors, use retry middleware for transient failures, let implementation bugs bubble | 08F.8, Part 4 |
Retrying every exception (with_retry default, ToolRetryMiddleware default retry_on, default_retry_on) |
A KeyError or a validation error is retried three times with backoff and three times the cost; a 401 is retried |
Restrict to the retryable family, and never retry what is not safe to repeat | 08F.7, 08F.8, 08F.12, 7.2 |
ModelRetryMiddleware left on its default on_failure="continue" |
The attempts run out and the run ends normally, with an AIMessage that says the call failed as the last message; an outer ModelFallbackMiddleware never fires |
Use on_failure="error" when a fallback sits outside, and read result["messages"][-1] before treating a run as a success |
08F.8, 8.10 |
ModelFallbackMiddleware with no exception filter |
It fails over on every exception, so a bug in your own code or a revoked key silently runs on the backup model | Log response_metadata["model_name"] so the switch is visible, and fix bugs instead of failing over them |
08F.8, 8.10 |
| Retrying a parse failure by re-running the chain | Re-bills the whole generation, which may be malformed in the same way | Use the structured-output strategy's own correction path | 08F.6 |
Using respond in human-in-the-loop to deny a side-effecting tool |
The response is treated as a successful tool result | Use reject |
08F.8, 8.9, 08F.12 |
An error_handler that returns a plain dict |
The update is saved but the failed node's outgoing edges do not fire; the branch ends (observed in 08F.12) | Return a Command(goto=...) when the flow must continue |
08F.12, 7.5 |
| Catching failures you cannot handle | The run continues with a wrong or empty value | Let unexpected exceptions bubble; handle the ones you have a plan for | 08F.12, Part 7 |
return_direct=True combined with other parallel tool calls |
It does not end the loop; control returns to the model with all the tool messages | Do not combine, or accept the model's follow-up | 08F.8 |
2.5 Trusting the framework's silence#
The smell. "It ran without an exception, so it worked." Several of the worst failures in this stack do not raise. The following were observed while writing this module, each in the lesson that owns it:
| Silent failure | What you see | Where |
|---|---|---|
| An unannotated router returns a name that is not a node | The run ends silently, with only a log warning | 08F.10, 15.2 |
| A node connected to nothing | compile() accepts it and it never runs |
08F.10 |
| In-place mutation of state | A half-applied change; {'node': None} in the stream |
08F.10, 15.1 |
runtime.context when context= was not passed (and after a resume that omitted it) |
None, even when the dataclass has defaults |
08F.10, Part 9 |
| A static breakpoint on a graph with no checkpointer | The graph compiles and silently stops, returning partial state | 08F.12, 5.3 |
A resume on an unknown thread_id |
It does not raise: it starts a run and pauses again at the first question | 08F.12 |
@task calls reordered, or called with different arguments, while threads are in flight |
A saved result for the same task name and call position is returned with no error (lookup("bob") returned Ada's data); results are matched by name plus position, never by arguments |
08F.11, 4.5 |
invoke(None, config) on a finished thread |
Returns the saved result without running anything | 08F.11, 2.2 |
A handoff tool that forgets the ToolMessage |
No error in the graph; the provider rejects the next call | 08F.13, 4.3 |
Native structured output with a Pydantic Field(ge=, le=) |
Providers support only a subset of JSON Schema and some ignore numeric bounds, so the constraint may not be enforced; your own validation is the guarantee | 08F.6, 03.4 |
| Strict msgpack mode blocking an unlisted type | The object comes back as a plain dict; the failure is a later AttributeError that does not mention serialization |
08F.11, 6.3 |
durability="sync" on a graph with no checkpointer |
Not silent, but baffling: AttributeError: 'SyncPregelLoop' object has no attribute '_put_checkpoint_fut' (08F.11, langgraph 1.2.22) |
08F.11, 4.1 |
The fix is a habit, not a feature. Test the final state of every path, including the escalations and the refusals; assert on get_graph() for topology; run the suite once with warnings enabled and deprecations as errors (3.4); and read the logs of your first real run for warnings your tests suppressed.
2.6 Framework types in your domain#
The smell. Your business logic imports AIMessage, BaseMessage or RunnableConfig, takes a LangGraph State as a parameter, and returns a framework object. The pricing rule that decides a refund cannot be called without building a message list.
The symptom. You cannot test the rule without the framework, cannot reuse it from a script or another service, and every library upgrade touches code that has nothing to do with LLMs. This is the dependency-direction rule you already know from layered architectures: the domain must not depend on the transport.
The fix. Keep tools as plain functions with typed arguments and docstrings, in modules that import nothing from LangChain (08F.1, 5.1 gave the ToolSpec pattern). Keep prompts as versioned text (04.10). Define your own dataclasses or Pydantic models for domain objects (Ticket, RefundDecision) and convert to messages and state at the edge, in one adapter module. Part 6 runs this pattern, and it is also the cheapest migration insurance there is: when the framework changes, the adapter changes and the rules do not.
2.7 The catalogue#
Every anti-pattern named in this lesson, and the ones owned by earlier lessons, in one table. Use it as a review checklist for a pull request.
| Smell | Symptom | Fix | Where |
|---|---|---|---|
Old patterns as the recommended path: LLMChain, AgentExecutor, create_react_agent, 0.0.x memory classes |
Deprecation warnings, a langchain-classic dependency, tutorials that do not match the docs |
Migrate (Part 3) | 3.5 to 3.7 |
| A chain of chains for one task | More latency, cost and failure points for the same output | One structured call, or tools and code between the calls | 2.1 |
| An agent where the steps are fixed | Variable cost and quality for a deterministic job | A workflow or a chain | 08A.9 |
| One agent with dozens of tools | Wrong tool choices, large prompts | Subagents, skills, dynamic tool selection | 08F.8, 5.7, 08F.13 |
A pre-bound model (bind_tools before) passed to create_agent |
Rejected: pass the plain model and the tool list | Plain model + tools=[...] |
3.6 |
Prompted structured output, response_format=("prompt", Schema) |
Removed in 1.0 because it "has not proven to be particularly reliable" | ToolStrategy or ProviderStrategy |
08F.6 |
| Hidden state in globals and closures | Users see each other's data | State, context, Store | 2.2 |
| Mutating state in a node | Lost or leaked updates | Return updates | 08F.10 |
| Parallel writers without a reducer | InvalidUpdateError or overwritten data |
Annotated reducer |
08F.10, 3.3 |
| Derived data stored in state | Large checkpoints, stale copies | Recompute | 1.4 |
A new thread_id per request |
"The chatbot has no memory" | Generate once per conversation, send it back | 08F.11, 2.1 |
| Interrupts or time travel without a checkpointer | A missing-checkpointer error | Add one (the Agent Server injects its own) | 08F.11, 08F.12 |
Command(update=...) as input to a finished thread |
Nothing runs | A plain input dict | 08F.10, 6.4 |
| Context not passed on resume | runtime.context is None after the approval |
Pass it again | 08F.12, 6.2 |
| Side effects with no idempotency | Double refunds after a retry or resume | Decide then act, with a key | 1.5 |
| Several layers of retries | Nine attempts for three | One owner | 1.6 |
| No bound on a loop | Cost incidents | The inventory | 1.7, 2.3 |
| Hiding tools as authorization | A "hidden" tool still ran | Enforce inside the tool | 08F.8, 9.3 |
| Skills or retrieved text treated as trusted | Prompt injection through your own content | Review, version, restrict writers; treat as data | 1.10 |
| Pickle fallback on, shared checkpoint database | Code execution through a poisoned checkpoint | Off by default; strict msgpack; encrypt | 08F.11, Part 6 |
| Tests that assert model text | Break on every prompt edit | Assert structure | 1.8 |
| A module-level fake model shared between tests | Order-dependent test results | Build per test | 1.8 |
langgraph dev or Compose as production |
Known gaps you must fill yourself | Kubernetes and Helm, or the managed platform | 1.11 |
| Image builds that re-resolve dependencies | A different set of packages than you tested | Build from uv.lock |
5.7 |
| Agents with broad permissions | A prompt injection reaches everything the agent can | Least privilege, read-only credentials, sandboxing | 1.10 |
| Framework types in domain code | Untestable business rules, upgrade churn | Plain functions and your own types | 2.6 |
| Rolling back Deep Agents after threads persisted on 0.6 or later | Not supported: checkpoints use a new DeltaChannel format (docs) |
Plan forward-only upgrades for pre-1.0 packages | 3.2 |
| Copying a docs example without running it | Wrong imports, stale defaults (see 4.2) | Run the smallest example first and read the exception | 4.3 |
Part 3: Migration, a playbook#
Most readers of this lesson will migrate something: an application written for LangChain 0.2 or 0.3, a notebook from a course, a service that a colleague built on AgentExecutor, or code that an assistant produced from its (older) training data. 08F.4, Part 4 taught the vocabulary: how to date old code, where old imports went, and the legacy-to-current table. This part is the larger piece: a strategy, the tools to find and gate legacy code, and worked migrations that run old and new side by side so that you can see what changes in the results.
3.1 A strategy: inventory, baseline, bridge, migrate, remove#
The order matters, because each step leaves the project in a state you can test and ship.
flowchart TD
a["1. Inventory: scan the repository"] --> b["2. Baseline: tests and traces on the OLD versions"]
b --> c["3. Raise Python, upgrade the family together, install langchain-classic as a bridge"]
c --> d["4. Fix imports: move to partner packages and langchain_core"]
d --> e["5. Turn deprecations into errors in CI"]
e --> f["6. Migrate agents, one at a time, comparing what the model sees"]
f --> g["7. Migrate memory and state to checkpointer and Store"]
g --> h["8. Remove langchain-classic and community imports"]
h --> i["9. Re-run evals, compare traces, roll out behind a switch"]- Inventory with the scanner of 3.3. You cannot plan what you have not counted.
- Baseline on the old versions: run the tests, and record traces or outputs for a handful of representative inputs. If there are no tests, write fake-model tests for the paths that matter first (1.8). A migration without a baseline is a rewrite with no way to know whether you broke it.
- Bridge: raise Python to 3.11 or newer, upgrade
langchain,langchain-core,langgraphand the provider packages together, and addlangchain-classicso the old imports keep working (3.8). - Fix imports that have one-line replacements: partner packages and
langchain_coreinstead oflangchain.*re-exports (08F.4, 4.2). - Gate deprecations in CI (3.4) so that the migrated parts cannot regress while the rest is in progress.
- Migrate agents one at a time (3.5, 3.6), comparing what the model is shown before and after.
- Migrate memory and state (3.7, 3.9).
- Remove the bridge when nothing imports it, or keep it deliberately (3.8).
- Prove it with evals, a trace comparison and a staged rollout (3.12).
Do you have to? Not always, and "not now" is a legitimate answer if it is a conscious one.
| Situation | Reasonable choice | Why |
|---|---|---|
| New feature touching old code | Migrate the part you touch, not the neighbours | The boy-scout rule: leave it newer than you found it |
| Old service, nobody touches it, tests pass | Freeze it on langchain-classic and a lockfile, schedule the migration |
Deprecated features keep working through all of 1.x (3.2); note it in your dependency register with the 2.0 removal date as the trigger |
| Still on 0.3 | Move soon | 0.3 is in maintenance (security and critical fixes only) until December 2026, about a month after this lesson was verified |
| An application with in-flight threads and approvals | Migrate in a branch with a copy of the real checkpoint data in the test | Saved state is the part that does not roll back (3.9) |
| A prototype | Rewrite it | It is faster than migrating, and the prototype taught you what you need |
3.2 The version history and what "deprecated" promises#
Knowing the history makes old code legible and tells you how much time you have. These are PyPI release dates (UTC), checked on 14 November 2026:
| Package | First on PyPI | 0.1.0 | 0.2.0 | 0.3.0 | 1.0.0 | Latest stable |
|---|---|---|---|---|---|---|
langchain |
0.0.1, 25 Oct 2022 | 6 Jan 2024 | 17 May 2024 | 13 Sep 2024 | 17 Oct 2025 | 1.5.0 (11 Nov 2026) |
langchain-core |
0.0.1, 20 Nov 2023 | 12 Dec 2023 | 17 May 2024 | 13 Sep 2024 | 17 Oct 2025 | 1.8.2 (17 Nov 2026; 1.8.0 on 11 Nov) |
langgraph |
0.0.8, 8 Jan 2024 | n/a | 0.2.0, 7 Aug 2024 | 0.3.0, 26 Feb 2025 | 17 Oct 2025 | 1.2.22 (14 Nov 2026) |
langchain-classic |
1.0.0a1, 7 Oct 2025 | n/a | n/a | n/a | 17 Oct 2025 | 1.0.8 (10 Jun 2026) |
langchain-community |
0.0.1rc1, 8 Dec 2023 | n/a | 17 May 2024 | 13 Sep 2024 | n/a | 0.4.2 (22 May 2026), the last release |
The docs' changelog dates the 1.0 release as 20 October 2025 while the PyPI upload is 17 October 2025 (alphas came earlier), so say "October 2025". After 1.0, langchain shipped 1.1.0 (24 Nov 2025), 1.2.0 (15 Dec 2025), 1.3.0 (12 May 2026), 1.4.0 (3 Sep 2026) and 1.5.0 (11 Nov 2026): a minor release every one to five months. langgraph 1.x shipped 1.1.0 (10 Mar 2026) and 1.2.0 (12 May 2026).
The official history page (docs.langchain.com/oss/python/langchain/philosophy) gives the story that old code encodes:
| When | What happened | What it left in old code |
|---|---|---|
| Oct 2022 | v0.0.1: LLM abstractions and "chains" | LLMChain, .run(), SequentialChain |
| Dec 2022 | First ReAct-style agents that parse text or JSON | AgentExecutor, {agent_scratchpad}, initialize_agent |
| Mar 2023 | OpenAI function calling | Tool-calling agents, create_openai_functions_agent |
| Jun 2023 | LangSmith released (closed source) | LANGCHAIN_TRACING_V2 in old tutorials |
| Jan 2024 | 0.1.0 | The first stable-looking API, from langchain.chat_models import ChatOpenAI |
| Feb 2024 | LangGraph released as open source | StateGraph, MessageGraph |
| Jun 2024 | Over 700 integrations, split into standalone packages or langchain-community |
from langchain_community... everywhere |
| Oct 2024 | "LangGraph becomes the preferred way to build any AI application that is more than a single LLM call"; most chains and agents are marked deprecated, with migration guides | langgraph.prebuilt.create_react_agent |
| Oct 2025 | 1.0: "all chains and agents are now replaced with only one high level abstraction: an agent abstraction built on top of LangGraph"; legacy moves to langchain-classic |
create_agent, middleware |
Python. Current langchain (1.5.0) and langchain-core (1.8.x) require Python 3.11 or newer: the 11 November 2026 changelog entry says "langchain 1.5 and langchain-core 1.8 drop Python 3.10 support", and PyPI's requires_python agrees. The 1.0 guides and the install page still say 3.10+. langgraph itself still accepts 3.10. A Python floor raised in a minor release is a thing that happens in this ecosystem; read the changelog before every upgrade.
What the policy promises. From docs.langchain.com/oss/python/release-policy and /versioning (verified 14 November 2026):
LangChain (langchain-core, langchain, partner packages) |
LangGraph | Deep Agents | |
|---|---|---|---|
| Versioning | Semantic versioning since 1.0 | Semantic versioning; majors "at least 6 to 12 months" apart, minors typically every 1 to 2 months | Pre-1.0 |
| Breaking changes | "Only in major version releases (e.g., 2.0.0)"; minors "do not include breaking changes" | Stable APIs keep backward compatibility within a major | Minor releases "may contain new features and potentially breaking changes" |
| Deprecation | Avoided until a better alternative exists; deprecated features "will continue to work throughout the entire 1.x release series"; removal only in a major; clearly marked, with migration guidance and security fixes through all 1.x | Marked with guidance; remain functional "for at least one minor version"; removed only in majors | Removed in subsequent minor releases |
| Support | 1.0 is designated LTS: ACTIVE until 2.0, then MAINTENANCE for at least a year. 0.3: MAINTENANCE until December 2026 | 1.0 is LTS on the same terms. 0.4: MAINTENANCE until December 2026 | Reaches 1.0 when the APIs stabilise |
| Labels | Stable, Beta, Alpha, Deprecated, Internal (the versioning page); a previous major gets security updates and critical fixes for 12 months after the next major | Stable, beta (feature-complete, may change), experimental and alpha (may change significantly), underscore-prefixed (no guarantee) |
n/a |
How to read that in practice:
- Deprecated is not broken. A deprecated API keeps working until the next major release, which has no announced date (check the release policy page, not this lesson, for it). A migration is scheduled work, not an emergency. But "works for now" is a reason to schedule, not to skip: the classes carry
removal="2.0.0". - 0.x is about to end. 0.3 and 0.4 patches end in December 2026. If you run them you are close to unsupported.
- Beta means beta. Several things this module taught are beta or experimental as of November 2026:
langchain.mcp(beta namespace), event streaming v3 (LangChainBetaWarning: ... experimental),AutoModeMiddlewareandModelRouterMiddleware(decision-driven middleware, beta in 1.5),DeltaChannel(beta),load()(beta, warns unless you passallowed_objects), and the whole ofdeepagents. A beta label is a promise that it may change in a minor release. - Pre-1.0 packages break in minors.
deepagents0.7.0 (24 July 2026) made planning todos opt-in and removed backend compatibility shims; 0.6.0 notes that rolling back is not supported once threads have persisted, because checkpoints use the newDeltaChannelformat. Pin and read the changelog for anything that is not 1.x. - Behaviour can change without an API change. A new default in a provider package, a different retry count, a changed message shape: 08F.1, 5.8 says to treat framework upgrades like model upgrades and re-run your evals. 3.11 lists the ones that happened in 1.0.
To check a version at run time, use importlib.metadata.version("langgraph"). The versioning page suggests langgraph.__version__, which raises AttributeError in 1.2.22 (observed in 08F.4).
3.3 Inventory first: a legacy scanner#
A regular expression is a crude tool, and it is the right first tool: it finds every file that mentions something, quickly, across a repository, with no import of the code. This scanner (standard library only) encodes the rules of this module: what breaks on 1.x, what still works but warns, and what deserves a look. It prints one line per hit with the replacement and the lesson that teaches it.
# legacy_scan.py: a first inventory of pre-1.0 LangChain and LangGraph usage in a source tree.
# Standard library only. A regex scan is a starting list, not a proof: read what it flags.
# usage: python legacy_scan.py <directory>
import re
import sys
from collections import Counter
from pathlib import Path
# (severity, regex, what to do, where this course teaches the replacement)
# breaks = fails to import or run on langchain 1.x without langchain-classic
# warns = still works on 1.x but is deprecated (removal is scheduled for 2.0)
# review = works, but check it
RULES = [
("breaks", r"from langchain\.chains import (?!.*(RetrievalQA|ConversationalRetrievalChain))|\b(LLMChain|SequentialChain|ConversationChain)\b", "prompt | model (LCEL), or create_agent", "08F.7"),
("breaks", r"from langchain\.agents import .*\b(AgentExecutor|initialize_agent|create_react_agent|create_tool_calling_agent|create_openai_functions_agent)\b", "create_agent", "08F.8"),
("breaks", r"from langchain\.memory import|\bConversation(Buffer|BufferWindow|Summary)Memory\b", "checkpointer + thread_id; Store for long-term", "08F.11"),
("breaks", r"from langchain\.prompts import", "from langchain_core.prompts import ...", "08F.6"),
("breaks", r"from langchain\.schema import", "from langchain.messages import ... (or langchain_core)", "08F.5"),
("breaks", r"from langchain\.text_splitter import", "from langchain_text_splitters import ...", "08F.9"),
("breaks", r"from langchain\.(vectorstores|document_loaders) import", "a partner package such as langchain_chroma, or langchain_core.vectorstores", "08F.9"),
("breaks", r"from langchain\.llms import", "a chat model: init_chat_model or a partner package", "08F.5"),
("breaks", r"from langchain\.chat_models import (?!init_chat_model|BaseChatModel)", "a partner package (langchain_openai ...) or init_chat_model", "08F.5"),
("breaks", r"from langchain\.embeddings import (?!init_embeddings|Embeddings)", "a partner package or init_embeddings", "08F.9"),
("breaks", r"from langchain import hub|\bhub\.pull\(|\bhub\.push\(", "the LangSmith SDK (pull_prompt / push_prompt)", "08F.6"),
("breaks", r"from langchain\.retrievers import|\bRetrievalQA\b|\bConversationalRetrievalChain\b", "a retrieval tool + create_agent, or langchain_classic as a bridge", "08F.9"),
("breaks", r"langchain_mcp_adapters|MultiServerMCPClient", "langchain.mcp.MCPAdapter (extra: langchain[mcp])", "08F.8"),
("warns", r"from langgraph\.prebuilt import .*\bcreate_react_agent\b|\bcreate_react_agent\(", "langchain.agents.create_agent (prompt= becomes system_prompt=)", "08F.8"),
("warns", r"\b(pre_model_hook|post_model_hook|state_modifier)\b", "before_model / after_model / wrap_model_call middleware", "08F.8"),
("warns", r"\bMessageGraph\b", "StateGraph with a messages key (MessagesState)", "08F.10"),
("warns", r"config_schema\s*=", "context_schema=", "08F.10"),
("warns", r"add_node\(.*\bretry\s*=", "retry_policy=", "08F.12"),
("warns", r"\bNodeInterrupt\b", "interrupt()", "08F.12"),
("warns", r"\b(HumanInterruptConfig|ActionRequest|HumanInterrupt)\b", "HumanInTheLoopMiddleware types (InterruptOnConfig, HITLRequest)", "08F.12"),
("warns", r"checkpoint_during\s*=", "durability=", "08F.11"),
("warns", r"from langgraph\.constants import .*\b(Send|Interrupt)\b", "from langgraph.types import ...", "08F.10"),
("warns", r"\.text\(\)", ".text (a property in 1.x)", "08F.5"),
("warns", r"\bRunnableWithMessageHistory\b|\bInMemoryChatMessageHistory\b", "a checkpointer + thread_id", "08F.7"),
("warns", r"astream_events\(.*version\s*=\s*[\"']v1[\"']", "version=\"v2\" (or LangGraph stream modes)", "08F.7, 08F.14"),
("review", r"langchain_community", "a dedicated partner package; langchain-community is sunset and archived (19 June 2026)", "08F.4"),
("review", r"langchain_experimental", "sunset 22 May 2026 and archived; anything that runs model-written code is a security decision", "08F.4"),
("review", r"langgraph_supervisor|langgraph_swarm", "subagents as tools (supervisor is archived)", "08F.13"),
("review", r"langchain_classic", "a bridge: plan its removal", "08F.4"),
("review", r"\bMemorySaver\b", "InMemorySaver (MemorySaver still works as an alias)", "08F.11"),
("review", r"gpt-4o|claude-3|gemini-1\.5|text-embedding-ada-002", "a retired or old model id: look it up on the provider page", "08F.5"),
("review", r"temperature\s*=", "many current models reject or ignore sampling parameters", "02.5"),
]
COMPILED = [(sev, re.compile(rx), fix, ref) for sev, rx, fix, ref in RULES]
def scan(root: Path) -> None:
totals: Counter[str] = Counter()
for path in sorted(root.rglob("*.py")):
for number, line in enumerate(path.read_text().splitlines(), 1):
for severity, rx, fix, ref in COMPILED:
if rx.search(line):
totals[severity] += 1
print(f"{path.relative_to(root)}:{number:<3} [{severity:<6}] {line.strip()[:70]}")
print(f"{'':>26}-> {fix} ({ref})")
print("\nsummary:", ", ".join(f"{totals[s]} {s}" for s in ("breaks", "warns", "review")))
scan(Path(sys.argv[1]))It was run on a small sample tree of four files (support_agent.py written the way a 2024 tutorial wrote it, a LangGraph workflow, a RAG script, and one file already in the current style). Output (ran on 15 November 2026 with a system Python 3.14; any 3.11+ works, no packages needed; trimmed to the first 24 lines and the summary):
rag.py:1 [breaks] from langchain import hub
-> the LangSmith SDK (pull_prompt / push_prompt) (08F.6)
rag.py:2 [breaks] from langchain.chains import RetrievalQA
-> a retrieval tool + create_agent, or langchain_classic as a bridge (08F.9)
rag.py:3 [breaks] from langchain.embeddings import OpenAIEmbeddings
-> a partner package or init_embeddings (08F.9)
rag.py:4 [breaks] from langchain.text_splitter import RecursiveCharacterTextSplitter
-> from langchain_text_splitters import ... (08F.9)
rag.py:5 [breaks] from langchain.vectorstores import Chroma
-> a partner package such as langchain_chroma, or langchain_core.vectorstores (08F.9)
rag.py:6 [review] from langchain_community.document_loaders import PyPDFLoader
-> a dedicated partner package; langchain-community is sunset and archived (19 June 2026) (08F.4)
rag.py:7 [review] from langchain_community.tools import DuckDuckGoSearchRun
-> a dedicated partner package; langchain-community is sunset and archived (19 June 2026) (08F.4)
rag.py:8 [breaks] from langchain_mcp_adapters.client import MultiServerMCPClient
-> langchain.mcp.MCPAdapter (extra: langchain[mcp]) (08F.8)
rag.py:9 [review] from langgraph_supervisor import create_supervisor
-> subagents as tools (supervisor is archived) (08F.13)
rag.py:11 [breaks] prompt = hub.pull("rlm/rag-prompt")
-> the LangSmith SDK (pull_prompt / push_prompt) (08F.6)
rag.py:12 [breaks] qa = RetrievalQA.from_chain_type(llm=llm, retriever=Chroma(embedding_f
-> a retrieval tool + create_agent, or langchain_classic as a bridge (08F.9)
support_agent.py:1 [breaks] from langchain.agents import AgentExecutor, create_tool_calling_agent
-> create_agent (08F.8)
...
summary: 13 breaks, 12 warns, 7 reviewReading the output:
breakslines fail on a 1.x install the moment the import runs (ModuleNotFoundErrororImportError, as 08F.4 showed with real errors). They are your first work list, and installinglangchain-classicis the way to make them run again while you port them.warnslines work on 1.x and print a deprecation warning (3.4 shows which). They can wait, but they are exactly what the gate will catch.reviewlines are judgement calls: a community import may have a partner package, an old model id may be retired, atemperature=may be rejected by a current model (02.5).
Three limits, so that you trust it correctly. It cannot see imports through aliases, importlib or code generated at run time. It does not read notebooks (.ipynb; export them or extend the glob). And it matches text, so a comment that mentions LLMChain is a hit. Use it for the inventory and the "count goes down" ratchet (run it in CI and fail if the breaks count rises), not as proof. When the migration is done, a plain grep -r langchain_classic src/ is the check that the bridge is unused.
3.4 A deprecation gate for CI#
A deprecation warning that nobody sees is not a warning. Python's default filters hide DeprecationWarning unless it is raised from __main__, and an agent's logs rarely show it. The cure is to make the test suite treat this stack's deprecations as failures, so that no one can merge deprecated code without a decision.
This stack raises its warnings with three families of classes, and all three derive from the built-in DeprecationWarning:
| Warning class | Raised by | Example in 1.x |
|---|---|---|
langgraph.warnings.LangGraphDeprecatedSinceV10 (and ...SinceV05, ...SinceV11, all subclasses of LangGraphDeprecationWarning) |
LangGraph and langgraph-prebuilt |
create_react_agent, MessageGraph, NodeInterrupt |
langchain_core._api.deprecation.LangChainDeprecationWarning |
langchain-core and langchain-classic |
LLMChain, ConversationBufferMemory, RunnableWithMessageHistory, .text() |
langchain_core._api.LangChainBetaWarning |
Beta APIs | langchain.mcp, event streaming v3 |
LangChainBetaWarning is a different class from LangChainDeprecationWarning, but it also derives from DeprecationWarning (checked with the class's __mro__). That is why the gate below names the two deprecation classes instead of using a blanket error::DeprecationWarning: a blanket rule would also fail your build on every beta API you chose to use on purpose. Which legacy calls actually warn? This sample probes thirteen of them and prints the class each raises (a probe records the warning and moves on):
# m07_warnings.py: which legacy calls still work on 1.x but warn, and with which warning class.
# This is the raw material for a "deprecations are errors in CI" gate.
import warnings
from typing import Any
from langchain_classic.chains import LLMChain
from langchain_classic.memory import ConversationBufferMemory
from langchain_core.chat_history import InMemoryChatMessageHistory
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.runnables.history import RunnableWithMessageHistory
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.errors import NodeInterrupt
from langgraph.graph import START, MessageGraph, StateGraph
from langgraph.prebuilt import create_react_agent
from langgraph.types import Interrupt, RetryPolicy
from typing_extensions import TypedDict
from langchain.messages import AIMessage
from fakes import FakeToolCallingModel
class State(TypedDict):
n: int
class Ctx(TypedDict):
user: str
def node(state: State) -> dict[str, Any]:
return {"n": state["n"] + 1}
def probe_checkpoint_during():
g = StateGraph(State).add_node("a", node).add_edge(START, "a").compile(checkpointer=InMemorySaver())
g.invoke({"n": 0}, {"configurable": {"thread_id": "t"}}, checkpoint_during=True)
def probe_constants_import():
from langgraph.constants import Send # noqa: F401
PROBES = {
"create_react_agent(...)": lambda: create_react_agent(FakeToolCallingModel(messages=iter([])), []),
"MessageGraph()": lambda: MessageGraph(),
"StateGraph(State, config_schema=Ctx)": lambda: StateGraph(State, config_schema=Ctx),
"add_node('a', fn, retry=RetryPolicy())": lambda: StateGraph(State).add_node("a", node, retry=RetryPolicy()),
"NodeInterrupt('stop')": lambda: NodeInterrupt("stop"),
"Interrupt(value=1).interrupt_id": lambda: Interrupt(value=1).interrupt_id,
"invoke(..., checkpoint_during=True)": probe_checkpoint_during,
"from langgraph.constants import Send": probe_constants_import,
"AIMessage('x').text() (method form)": lambda: AIMessage("x").text(),
"RunnableWithMessageHistory(...)": lambda: RunnableWithMessageHistory(
ChatPromptTemplate.from_template("{q}") | FakeToolCallingModel(messages=iter([])),
lambda session_id: InMemoryChatMessageHistory(),
),
"LLMChain(llm=..., prompt=...)": lambda: LLMChain(llm=FakeToolCallingModel(messages=iter([])), prompt=ChatPromptTemplate.from_template("{q}")),
"ConversationBufferMemory()": lambda: ConversationBufferMemory(),
"InMemorySaver() (the current name)": lambda: InMemorySaver(),
}
for label, probe in PROBES.items():
with warnings.catch_warnings(record=True) as caught:
warnings.simplefilter("always")
try:
probe()
outcome = ""
except Exception as error: # noqa: BLE001
outcome = f" [raised {type(error).__name__}]"
seen = sorted({w.category.__name__ for w in caught})
print(f"{label:<42} -> {', '.join(seen) if seen else 'no warning'}{outcome}")create_react_agent(...) -> LangGraphDeprecatedSinceV10
MessageGraph() -> LangGraphDeprecatedSinceV10
StateGraph(State, config_schema=Ctx) -> LangGraphDeprecatedSinceV10
add_node('a', fn, retry=RetryPolicy()) -> LangGraphDeprecatedSinceV05
NodeInterrupt('stop') -> LangGraphDeprecatedSinceV10
Interrupt(value=1).interrupt_id -> LangGraphDeprecatedSinceV10
invoke(..., checkpoint_during=True) -> LangGraphDeprecatedSinceV10
from langgraph.constants import Send -> LangGraphDeprecatedSinceV10
AIMessage('x').text() (method form) -> LangChainDeprecationWarning
RunnableWithMessageHistory(...) -> LangChainDeprecationWarning
LLMChain(llm=..., prompt=...) -> LangChainDeprecationWarning
ConversationBufferMemory() -> LangChainDeprecationWarning
InMemorySaver() (the current name) -> no warningTwo things to notice. The current name InMemorySaver() raises nothing, while the alias MemorySaver is accepted without a warning too (the scanner lists it as review, since only the new name is documented). And add_node(..., retry=...) raises the older class LangGraphDeprecatedSinceV05: some names have been deprecated since 0.5, long before 1.0, so a project that "ran clean on 0.6" can have warnings that predate the migration.
Now the gate. pytest's filterwarnings setting turns a warning class into an error for every test. In pyproject.toml:
[tool.pytest.ini_options]
filterwarnings = [
"error::langgraph.warnings.LangGraphDeprecationWarning",
"error::langchain_core._api.deprecation.LangChainDeprecationWarning",
]With that setting, a test that uses current code passes and a test that calls the deprecated function fails the build, with the replacement in the failure message (fakes.py sits next to the test file):
from langgraph.prebuilt import create_react_agent
from langchain.agents import create_agent
from fakes import FakeToolCallingModel
def test_new_style_passes():
create_agent(FakeToolCallingModel(messages=iter([])), tools=[])
def test_old_style_fails_the_build():
create_react_agent(FakeToolCallingModel(messages=iter([])), [])E langgraph.warnings.LangGraphDeprecatedSinceV10: create_react_agent has been moved to `langchain.agents`. Please update your import to `from langchain.agents import create_agent`. Deprecated in LangGraph V1.0 to be removed in V2.0.
FAILED test_gate.py::test_old_style_fails_the_build - langgraph.warnings.Lang...
1 failed, 1 passed in 0.12sHow to introduce it without stopping the team. First run with the two lines as default:: instead of error:: to list every warning in the suite. Then switch to error:: and add one ignore::...:module_name line per module you have not migrated yet, so that the gate protects what is done and the ignore list is the visible, shrinking to-do list. Scope the filter to your own code if a dependency you cannot change (the archived langgraph-supervisor builds its supervisor on the deprecated create_react_agent) raises the warning internally. Keep the ratchet in CI, not on a laptop.
3.5 AgentExecutor to create_agent#
There is no current official guide named for this migration. A search of the documentation index and of every migration page found no AgentExecutor page, and the old address (python.langchain.com/docs/how_to/migrate_agent/) redirects to the overview. What exists is (a) the API reference of the class (AgentExecutor, in langchain_classic, extending Chain), and (b) an archived notebook on the GitHub v0.3 branch, docs/docs/how_to/migrate_agent.ipynb, "How to migrate from legacy LangChain agents to LangGraph". Its target at the time was LangGraph's create_react_agent, which is itself deprecated now, so the full path is two hops:
AgentExecutor → (the 0.3 notebook) langgraph.prebuilt.create_react_agent → (the 1.0 guide) langchain.agents.create_agent.
This lesson does the two hops as one. The archived notebook walks through basic usage, prompt templates, memory, iterating through steps, return_intermediate_steps, max_iterations, max_execution_time, early_stopping_method and trim_intermediate_steps, and those are exactly the knobs to translate:
AgentExecutor |
In create_agent |
Notes |
|---|---|---|
AgentExecutor(agent=..., tools=[...]) |
create_agent(model, tools=[...]) |
The loop is the graph it returns (08F.8, 7.8) |
create_tool_calling_agent(llm, tools, prompt) with an {agent_scratchpad} placeholder |
system_prompt="..." |
You no longer maintain the scratchpad: the loop manages the message list |
executor.invoke({"input": q})["output"] |
agent.invoke({"messages": [...]})["messages"][-1].text |
Input and output keys are replaced by a message list (run below) |
return_intermediate_steps=True |
Nothing to turn on: the steps are the messages | Read AIMessage.tool_calls and the ToolMessages (run below) |
max_iterations=N |
ModelCallLimitMiddleware(run_limit=N, exit_behavior="end") |
A graph run can be bounded by recursion_limit, but its default is 10,007; use the middleware (1.7) |
early_stopping_method="force" (the default) |
exit_behavior="end" |
Ends with a canned message (run below) |
early_stopping_method="generate" (one more model call to write a final answer) |
No built-in equivalent in the sources checked | A @before_model hook that jumps to "end" with your own message, or a final node |
max_execution_time=seconds |
Nothing counts wall-clock time for you | Model timeout=, tool timeouts, a request deadline, and for graph nodes a TimeoutPolicy (1.7) |
handle_parsing_errors=True |
Mostly moot: tool-calling models return structured calls, not text to parse | Schema errors in tool arguments come back to the model as tool messages (08F.8, 4.1) |
trim_intermediate_steps= |
SummarizationMiddleware, or a hook that slices the model's input |
08F.8, 8.8, 3.7 |
memory=ConversationBufferMemory(...) |
checkpointer= and a thread_id |
3.7 |
verbose=True |
Tracing and stream_mode="updates" |
A structured trace instead of print (11A.5, 08F.14) |
callbacks=[...] |
The same: config={"callbacks": [...]} on the call |
(08F.7, 4.2) |
Text-ReAct agents (create_react_agent from classic, Thought/Action text) |
Tool calling | Only models without tool calling needed the text form |
Now run it. The same scripted conversation (one tool call, then an answer; and a model that never stops asking for the tool) goes through the legacy executor and through create_agent. Because the scripted model cannot stream tool calls, the legacy agent is wrapped with stream_runnable=False, a one-line detail that a real model does not need.
# m01_agentexecutor.py: the SAME scripted conversation run through the legacy AgentExecutor
# (langchain-classic) and through create_agent, so the two result shapes can be compared.
import itertools
import warnings
from langchain_classic.agents import AgentExecutor, create_tool_calling_agent
from langchain_classic.agents.agent import RunnableMultiActionAgent
from langchain_core.prompts import ChatPromptTemplate
from langchain.agents import create_agent
from langchain.agents.middleware import ModelCallLimitMiddleware
from langchain.messages import AIMessage, HumanMessage, ToolCall
from langchain.tools import tool
from fakes import FakeToolCallingModel
warnings.simplefilter("ignore") # we look at warnings separately (see m07)
@tool
def lookup_order(order_id: str) -> str:
"""Look up an order by its ID."""
return f"Order {order_id}: shipped"
def one_tool_then_answer():
yield AIMessage(content="", tool_calls=[ToolCall(name="lookup_order", args={"order_id": "A-1042"}, id="call_1")])
yield AIMessage(content="Order A-1042 has shipped.")
def endless():
for i in itertools.count(1):
yield AIMessage(content="", tool_calls=[ToolCall(name="lookup_order", args={"order_id": "A-1042"}, id=f"call_{i}")])
QUESTION = "Where is order A-1042?"
# ---------- LEGACY: AgentExecutor -------------------------------------------------------------
prompt = ChatPromptTemplate.from_messages(
[("system", "You are a support agent."), ("human", "{input}"), ("placeholder", "{agent_scratchpad}")]
)
def legacy(script, **executor_kwargs):
model = FakeToolCallingModel(messages=script)
runnable = create_tool_calling_agent(model, [lookup_order], prompt)
# stream_runnable=False because the scripted model cannot stream tool calls (a real model can)
agent = RunnableMultiActionAgent(runnable=runnable, stream_runnable=False)
return AgentExecutor(agent=agent, tools=[lookup_order], **executor_kwargs)
print("== legacy, normal run")
result = legacy(one_tool_then_answer(), return_intermediate_steps=True).invoke({"input": QUESTION})
print("keys:", sorted(result))
print("output:", result["output"])
for action, observation in result["intermediate_steps"]:
print("step:", action.tool, action.tool_input, "->", observation)
print("== legacy, runaway loop with max_iterations=3")
result = legacy(endless(), max_iterations=3).invoke({"input": QUESTION})
print("output:", result["output"])
# ---------- CURRENT: create_agent -------------------------------------------------------------
print("== current, normal run")
agent = create_agent(
FakeToolCallingModel(messages=one_tool_then_answer()),
tools=[lookup_order],
system_prompt="You are a support agent.",
middleware=[ModelCallLimitMiddleware(run_limit=3, exit_behavior="end")],
)
result = agent.invoke({"messages": [HumanMessage(QUESTION)]})
print("keys:", sorted(result))
print("output:", result["messages"][-1].text)
for message in result["messages"]:
for call in getattr(message, "tool_calls", []):
print("step:", call["name"], call["args"])
if message.type == "tool":
print(" ->", message.content)
print("== current, runaway loop with ModelCallLimitMiddleware(run_limit=3)")
agent = create_agent(
FakeToolCallingModel(messages=endless()),
tools=[lookup_order],
system_prompt="You are a support agent.",
middleware=[ModelCallLimitMiddleware(run_limit=3, exit_behavior="end")],
)
result = agent.invoke({"messages": [HumanMessage(QUESTION)]})
print("output:", result["messages"][-1].text)
print("messages in history:", len(result["messages"]))== legacy, normal run
keys: ['input', 'intermediate_steps', 'output']
output: Order A-1042 has shipped.
step: lookup_order {'order_id': 'A-1042'} -> Order A-1042: shipped
== legacy, runaway loop with max_iterations=3
output: Agent stopped due to max iterations.
== current, normal run
keys: ['messages']
output: Order A-1042 has shipped.
step: lookup_order {'order_id': 'A-1042'}
-> Order A-1042: shipped
== current, runaway loop with ModelCallLimitMiddleware(run_limit=3)
output: Model call limits exceeded: run limit (3/3)
messages in history: 8What the run shows, line by line:
- Result shape. The executor returns a dict with
input,intermediate_stepsandoutput; the agent returns{'messages': [...]}and nothing else. Everything the old keys held is in the messages: the tool call (with its arguments) is on anAIMessage, the observation is aToolMessage. Code that readresult["output"]becomesresult["messages"][-1].text, and code that iterated overintermediate_stepsbecomes a loop over the messages, as the sample does. - The same trajectory. In both runs the model called
lookup_orderwith{'order_id': 'A-1042'}, gotOrder A-1042: shipped, and answeredOrder A-1042 has shipped.That equality is the migration test you want (3.12). - Runaway loops end differently. The legacy
max_iterations=3returned the stringAgent stopped due to max iterations.as the output, which a caller cannot distinguish from a real answer unless it checks the text. The current limit ends the run with anAIMessagereadingModel call limits exceeded: run limit (3/3)and eight messages of history (the question, three tool round trips and the notice), andexit_behavior="error"raisesModelCallLimitExceededErrorinstead, which is usually what you want for a batch job. Decide which you want and test it. - No
AgentExecutordeprecation warning here. The executor class itself has no@deprecateddecorator inlangchain-classic1.0.8 (08F.4 checked the source); the deprecation is carried byinitialize_agentand by the docs. That is why a quiet console tells you nothing about whether you should migrate.
Porting the rest. Work in this order for each agent: (1) tools keep working, change from langchain.tools import tool; (2) replace ChatOpenAI(...) with a model string or a partner-package object and drop retired model ids and sampling parameters; (3) move the system text into system_prompt and delete {input}, {chat_history} and {agent_scratchpad}; (4) replace memory= with a checkpointer; (5) add the limits; (6) change the call and the result handling; (7) change streaming consumers (the node name "agent" is now "model"); (8) run the old and new agents on the same scripted conversation and compare. 08F.8 owns each of those pieces.
3.6 langgraph.prebuilt.create_react_agent to create_agent#
This is the migration with an official guide (the LangChain v1 migration guide, docs.langchain.com/oss/python/migrate/langchain-v1), and the rename is mostly mechanical. The surprise is in what the old hooks did versus what their replacements do.
create_react_agent |
create_agent |
Note |
|---|---|---|
from langgraph.prebuilt import create_react_agent |
from langchain.agents import create_agent |
The old one is deprecated since 1.0 and still imports through all of 1.x |
prompt="..." |
system_prompt="..." |
A SystemMessage was replaced by its string; langchain 1.1.0 later added support for passing a SystemMessage |
| A prompt function | @dynamic_prompt middleware |
Reads request.state and request.runtime.context |
pre_model_hook that edits messages |
@before_model middleware |
Returns a state update |
pre_model_hook returning llm_input_messages |
@wrap_model_call with request.override(messages=...) |
Changes only what this call sends; the stored history is untouched (run below) |
post_model_hook |
@after_model middleware |
|
state_modifier |
Gone | Use a hook or @dynamic_prompt |
interrupt_before=["tools"] |
HumanInTheLoopMiddleware(interrupt_on=...) or interrupt() inside the tool |
The docs advise against static breakpoints for human approval (08F.12, Part 5) |
state_schema= with a Pydantic model or dataclass |
A TypedDict extending langchain.agents.AgentState, via state_schema= or a middleware's state_schema |
The guide says "TypedDict only" (3.9 shows what 1.5.0 does) |
model= with .bind_tools(...) already applied |
A model string or a plain model, plus tools=[...] |
Pre-bound models are no longer accepted |
| Dynamic model selection | @wrap_model_call with request.override(model=...) |
08F.8, 9.2 |
tools=ToolNode([...]) |
A plain list of tools, or callables with a docstring and type hints | Tool error handling moves to middleware; ValidationNode is removed (validation is automatic) |
response_format= with the prompted form |
ToolStrategy(Schema) or ProviderStrategy(Schema) (from langchain.agents.structured_output) |
Generated in the main loop, with no extra model call; the result is result["structured_response"] |
Streaming node name "agent" |
"model" |
Anything that filters stream events by node name needs the change |
config["configurable"] for static data |
context_schema= and context= |
configurable still works for backward compatibility |
Now run both. Same scripted model, same tool, a system prompt, a hook that limits the model's view to the last two messages, a hook that runs after every model call, and an in-memory checkpointer. The model records what it was shown.
# m02_react_agent.py: langgraph.prebuilt.create_react_agent (deprecated) next to create_agent,
# with the same scripted model, a prompt, a pre-model hook, a post-model hook and a checkpointer.
import warnings
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.prebuilt import create_react_agent
from langchain.agents import create_agent
from langchain.agents.middleware import after_model, dynamic_prompt, wrap_model_call
from langchain.messages import AIMessage, HumanMessage, ToolCall
from langchain.tools import tool
from fakes import RecordingModel
@tool
def lookup_order(order_id: str) -> str:
"""Look up an order by its ID."""
return f"Order {order_id}: shipped"
def script():
yield AIMessage(content="", tool_calls=[ToolCall(name="lookup_order", args={"order_id": "A-1042"}, id="call_1")])
yield AIMessage(content="It has shipped.")
yield AIMessage(content="Anything else?")
CONFIG = {"configurable": {"thread_id": "t1"}}
LOG: list[str] = []
# ---------- OLD: create_react_agent ------------------------------------------------------------
def pre_hook(state):
# llm_input_messages: what the model sees THIS call; the stored history is not changed
return {"llm_input_messages": state["messages"][-2:]}
def post_hook(state):
LOG.append(f"post_model_hook saw {len(state['messages'])} messages")
return {}
old_model = RecordingModel(messages=script())
with warnings.catch_warnings(record=True) as caught:
warnings.simplefilter("always")
old = create_react_agent(old_model, [lookup_order], prompt="You are a support agent.",
pre_model_hook=pre_hook, post_model_hook=post_hook, checkpointer=InMemorySaver())
print("warning:", caught[0].category.__name__)
print("OLD nodes:", sorted(set(old.get_graph().nodes)))
for chunk in old.stream({"messages": [HumanMessage("Where is A-1042?")]}, CONFIG, stream_mode="updates"):
print("OLD update from node:", list(chunk))
print("OLD model saw", [[kind for kind, _ in call] for call in old_model.seen])
print("OLD log:", LOG)
# ---------- NEW: create_agent + middleware -----------------------------------------------------
NEW_LOG: list[str] = []
@dynamic_prompt # prompt= became system_prompt=; a prompt FUNCTION became @dynamic_prompt
def support_prompt(request) -> str:
return "You are a support agent."
@wrap_model_call # the replacement for llm_input_messages: change only what THIS call sends
def last_two(request, handler):
return handler(request.override(messages=request.messages[-2:]))
@after_model # post_model_hook
def log_after(state, runtime):
NEW_LOG.append(f"after_model saw {len(state['messages'])} messages")
return None
new_model = RecordingModel(messages=script())
new = create_agent(new_model, tools=[lookup_order],
middleware=[support_prompt, last_two, log_after], checkpointer=InMemorySaver())
print("NEW nodes:", sorted(set(new.get_graph().nodes)))
for chunk in new.stream({"messages": [HumanMessage("Where is A-1042?")]}, CONFIG, stream_mode="updates"):
print("NEW update from node:", list(chunk))
print("NEW model saw", [[kind for kind, _ in call] for call in new_model.seen])
print("NEW log:", NEW_LOG)Output (ran on 15 November 2026; the old agent also printed its deprecation warning, which the sample captured):
warning: LangGraphDeprecatedSinceV10
OLD nodes: ['__end__', '__start__', 'agent', 'post_model_hook', 'pre_model_hook', 'tools']
OLD update from node: ['pre_model_hook']
OLD update from node: ['agent']
OLD update from node: ['post_model_hook']
OLD update from node: ['tools']
OLD update from node: ['pre_model_hook']
OLD update from node: ['agent']
OLD update from node: ['post_model_hook']
OLD model saw [['SystemMessage', 'HumanMessage'], ['SystemMessage', 'AIMessage', 'ToolMessage']]
OLD log: ['post_model_hook saw 2 messages', 'post_model_hook saw 4 messages']
NEW nodes: ['__end__', '__start__', 'log_after.after_model', 'model', 'tools']
NEW update from node: ['model']
NEW update from node: ['log_after.after_model']
NEW update from node: ['tools']
NEW update from node: ['model']
NEW update from node: ['log_after.after_model']
NEW model saw [['SystemMessage', 'HumanMessage'], ['SystemMessage', 'AIMessage', 'ToolMessage']]
NEW log: ['after_model saw 2 messages', 'after_model saw 4 messages']What it shows:
- The warning class. Building the old agent raised
LangGraphDeprecatedSinceV10, the class the gate of 3.4 turns into an error. - The same view for the model. Both agents showed the model the same thing on both calls: first a system message and the human message, then the system message, the tool-call
AIMessageand theToolMessage(the last two messages plus the system prompt). The oldllm_input_messageshook and the new@wrap_model_callhook are equivalent. Abefore_modelhook that returned trimmed messages would have rewritten the stored history instead. - The same log.
post_model_hookand@after_modeleach fired after both model calls and saw 2 and then 4 messages. - The graph differs, and the difference is the migration. The old graph had nodes
agent,tools,pre_model_hookandpost_model_hook. The new graph hasmodel,toolsand one node perbefore_*andafter_*middleware hook (herelog_after.after_model). The wrap-style hooks (@wrap_model_call,@dynamic_prompt) add no node: they run inside themodelnode. If your dashboards, streaming UI or tests refer toagentorpre_model_hookby name, they need updating; theupdatesstream above is where you see it.
The old arguments fail at build time with clear messages, which is a gift: prompt=, pre_model_hook=, post_model_hook= and state_modifier= each raise TypeError: create_agent() got an unexpected keyword argument ..., tools=ToolNode([...]) raises TypeError: 'ToolNode' object is not iterable, and response_format=("prompt", Schema) raises a ValueError listing the supported schema types. 08F.8, Part 13 ran all six, and 08F.4, 4.4 explains the second function that shares the name (the text-ReAct factory in langchain_classic).
3.7 Memory and chains: ConversationBufferMemory, LLMChain and friends#
Memory. The old memory classes were objects attached to a chain or executor that stored and replayed text. The replacement splits what they did into two separate features.
| Old | Replacement | Owner |
|---|---|---|
ConversationBufferMemory (keep everything) |
A checkpointer and a thread_id: the thread is the buffer |
08F.11, Part 1 |
ConversationBufferWindowMemory(k=...) (keep the last k exchanges) |
A hook that slices what the model sees (@wrap_model_call), or trim_messages |
08F.11, 08F.6 |
ConversationSummaryMemory (summarize older turns) |
SummarizationMiddleware |
08F.8, 8.8 |
Cross-session recall (the archived guide's long_term_memory_agent) |
The Store, with semantic search if you want it | 08F.11, Parts 7 and 8 |
RunnableWithMessageHistory + BaseChatMessageHistory |
A checkpointer. It now warns (LangChainDeprecationWarning: ... Use LangGraph's built-in persistence instead) |
08F.7 |
The archived 0.3 memory guide told users of RunnableWithMessageHistory that they needed no changes. That advice is out of date: in 1.x constructing it emits a deprecation warning, as the probe in 3.4 showed. This is a good example of why you date your sources.
The sample runs the same four-turn conversation through a legacy ConversationBufferWindowMemory(k=1) with an LLMChain, and through a create_agent with a SQLite checkpointer and a model-call hook that keeps the last three messages. The agent is then rebuilt over the same database file halfway, which is what a restart is.
# m03_memory.py: ConversationBufferWindowMemory + LLMChain (legacy) versus a checkpointer + thread_id.
# The scripted model records exactly what it was shown on every turn.
import os
import sqlite3
import tempfile
import warnings
from langchain_classic.chains import LLMChain
from langchain_classic.memory import ConversationBufferWindowMemory
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
from langgraph.checkpoint.sqlite import SqliteSaver
from langchain.agents import create_agent
from langchain.agents.middleware import wrap_model_call
from langchain.messages import AIMessage, HumanMessage
from fakes import RecordingModel
warnings.simplefilter("ignore") # the deprecation text is shown in m07
TURNS = ["My name is Asha.", "I ordered a lamp.", "It arrived cracked.", "What is my name?"]
def replies():
for text in ["Hello Asha.", "Noted: a lamp.", "Sorry to hear that.", "I no longer see your name."]:
yield AIMessage(content=text)
def show(model, label):
print(label)
for number, call in enumerate(model.seen, 1):
print(f" turn {number}: model saw", [text for _, text in call])
# ---------- LEGACY: memory object attached to a chain; window of the last k exchanges ----------
model = RecordingModel(messages=replies())
prompt = ChatPromptTemplate.from_messages([("system", "You are helpful."), MessagesPlaceholder("history"), ("human", "{input}")])
memory = ConversationBufferWindowMemory(k=1, memory_key="history", return_messages=True)
chain = LLMChain(llm=model, prompt=prompt, memory=memory)
for turn in TURNS:
chain.invoke({"input": turn})
show(model, "LEGACY ConversationBufferWindowMemory(k=1) + LLMChain")
# ---------- CURRENT: a checkpointer stores the thread; a model-call hook windows what is sent ----
@wrap_model_call
def window(request, handler):
return handler(request.override(messages=request.messages[-3:])) # the last 3 messages only
path = os.path.join(tempfile.mkdtemp(), "threads.sqlite")
def build(model):
saver = SqliteSaver(sqlite3.connect(path, check_same_thread=False))
return create_agent(model, tools=[], system_prompt="You are helpful.", middleware=[window], checkpointer=saver)
config = {"configurable": {"thread_id": "asha-1"}}
model = RecordingModel(messages=replies())
agent = build(model)
for turn in TURNS[:2]:
agent.invoke({"messages": [HumanMessage(turn)]}, config)
# "restart": a brand-new agent object (a new process in real life) over the same database file
model2 = RecordingModel(messages=iter([AIMessage(content="Sorry to hear that."), AIMessage(content="I no longer see your name.")]))
agent2 = build(model2)
for turn in TURNS[2:]:
agent2.invoke({"messages": [HumanMessage(turn)]}, config)
show(model, "CURRENT checkpointer + window of 3 messages: before the restart")
show(model2, "CURRENT after the restart (same thread_id, new agent object)")
stored = agent2.get_state(config).values["messages"]
print("stored in the thread:", len(stored), "messages (the window only limits what is SENT)")LEGACY ConversationBufferWindowMemory(k=1) + LLMChain
turn 1: model saw ['You are helpful.', 'My name is Asha.']
turn 2: model saw ['You are helpful.', 'My name is Asha.', 'Hello Asha.', 'I ordered a lamp.']
turn 3: model saw ['You are helpful.', 'I ordered a lamp.', 'Noted: a lamp.', 'It arrived cracked.']
turn 4: model saw ['You are helpful.', 'It arrived cracked.', 'Sorry to hear that.', 'What is my name?']
CURRENT checkpointer + window of 3 messages: before the restart
turn 1: model saw ['You are helpful.', 'My name is Asha.']
turn 2: model saw ['You are helpful.', 'My name is Asha.', 'Hello Asha.', 'I ordered a lamp.']
CURRENT after the restart (same thread_id, new agent object)
turn 1: model saw ['You are helpful.', 'I ordered a lamp.', 'Noted: a lamp.', 'It arrived cracked.']
turn 2: model saw ['You are helpful.', 'It arrived cracked.', 'Sorry to hear that.', 'What is my name?']
stored in the thread: 8 messages (the window only limits what is SENT)Compare the model's input, turn by turn. The window memory and the hook feed the model the same text: on the third turn, the previous exchange plus the new message. The differences are what you migrate for:
- Durability. After the "restart" (a fresh agent object over the same file) the conversation continued from
thread_id="asha-1". The legacy memory lived in the memory object and was gone with the process. - What is stored versus what is sent. The old window memory discarded older turns. The new design keeps all eight messages in the thread (the last line of the output) and only limits what is sent. That is more flexible (you can summarize instead, fork or time-travel) and it means the thread grows without bound unless you add summarization or retention (1.7).
- Identity. The old memory belonged to the chain object, so two users needed two objects. The new design keys everything by
thread_id, so one agent object serves everyone and the id is the isolation boundary (08F.11, 2.1).
Chains. The 0.x chain classes become LCEL or a graph (08F.7). The result shape changes too, which breaks callers that index the dict:
# m04_chain_and_state.py: two smaller migrations, run for real.
# (1) LLMChain -> prompt | model | parser: the call shape and the result shape change.
# (2) create_agent state: a Pydantic state class is rejected; a TypedDict extending AgentState works.
import warnings
from langchain_classic.chains import LLMChain
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate
from pydantic import BaseModel
from langchain.agents import AgentState, create_agent
from langchain.messages import AIMessage, HumanMessage
from typing_extensions import NotRequired
from fakes import FakeToolCallingModel
warnings.simplefilter("ignore")
prompt = ChatPromptTemplate.from_template("Summarize this ticket in one line: {ticket}")
TICKET = "My desk lamp arrived with a cracked base."
old = LLMChain(llm=FakeToolCallingModel(messages=iter([AIMessage(content="Cracked lamp base.")] * 2)), prompt=prompt)
print("legacy LLMChain.invoke ->", old.invoke({"ticket": TICKET}))
print("legacy LLMChain.run ->", end=" ")
try:
print(old.run(ticket=TICKET))
except Exception as error: # noqa: BLE001
print(type(error).__name__, str(error).splitlines()[0][:90])
new = prompt | FakeToolCallingModel(messages=iter([AIMessage(content="Cracked lamp base.")])) | StrOutputParser()
print("current prompt | model | parser .invoke ->", repr(new.invoke({"ticket": TICKET})))
# ---------- agent state ------------------------------------------------------------------------
class PydanticState(BaseModel):
messages: list = []
note: str = ""
class TypedState(AgentState):
note: NotRequired[str]
model = FakeToolCallingModel(messages=iter([AIMessage(content="hi")]))
try:
odd = create_agent(model, tools=[], state_schema=PydanticState)
result = odd.invoke({"messages": [HumanMessage("x")], "note": "vip"})
print("Pydantic state -> built and ran, note =", result["note"], "(the docs say TypedDict only)")
except Exception as error: # noqa: BLE001
print("Pydantic state ->", type(error).__name__, str(error).splitlines()[0][:110])
model = FakeToolCallingModel(messages=iter([AIMessage(content="hi")]))
agent = create_agent(model, tools=[], state_schema=TypedState)
print("TypedDict state ->", agent.invoke({"messages": [HumanMessage("x")], "note": "vip"})["note"])legacy LLMChain.invoke -> {'ticket': 'My desk lamp arrived with a cracked base.', 'text': 'Cracked lamp base.'}
legacy LLMChain.run -> Cracked lamp base.
current prompt | model | parser .invoke -> 'Cracked lamp base.'
Pydantic state -> built and ran, note = vip (the docs say TypedDict only)
TypedDict state -> vipLLMChain.invoke returns a dict containing the inputs and a text key; .run(...) (also deprecated) returned the string; prompt | model | StrOutputParser() returns the string, and without the parser an AIMessage. A caller that wrote chain.invoke(x)["text"] must change with the chain. The last two lines are the agent state check of 3.9.
| Legacy chain or helper | Current | Owner |
|---|---|---|
LLMChain, .run(), .predict() |
prompt | model | parser |
08F.7 |
SequentialChain, TransformChain |
LCEL with RunnablePassthrough.assign and RunnableLambda, or a small graph |
08F.7, 08F.10 |
RetrievalQA, ConversationalRetrievalChain, load_qa_chain |
A retrieval tool with create_agent, or a two-step retrieve-then-answer chain |
08F.9, Part 14 |
create_stuff_documents_chain (deprecated since 0.2.13) |
The same, per its notice | 08F.9 |
create_retrieval_chain, create_history_aware_retriever |
No deprecation marker in the source (08F.9 checked), but the same replacement applies | 08F.9 |
MultiQueryRetriever, EnsembleRetriever, the old retrievers module |
Moved to langchain_classic.retrievers, or custom retrieval logic |
08F.9 |
StructuredOutputParser + ResponseSchema, create_structured_output_runnable |
with_structured_output and a Pydantic model |
08F.6 |
from langchain import hub, hub.pull/hub.push |
The LangSmith SDK (pull_prompt, push_prompt); the classic hub functions are deprecated since classic 1.0.6 and treat manifests as untrusted input |
08F.6 |
OutputFixingParser, RetryOutputParser |
In langchain_classic; prefer the structured-output strategy's own correction path |
08F.6 |
3.8 The bridge: langchain-classic and how to leave it#
langchain-classic (import langchain_classic) is the home of everything 1.0 removed from langchain. It is not abandoned: PyPI lists version 1.0.8 (10 June 2026) as Production/Stable (its PyPI licence field is empty; the monorepo it lives in is MIT-licensed), the source lives in the langchain-ai/langchain monorepo (at libs/langchain, while the current langchain package is libs/langchain_v1), and the docs say that legacy functionality "has moved to langchain-classic to keep the core packages lean" and that users who do not want to upgrade "can continue using old LangChain by installing the langchain-classic package". The docs call the move to create_agent a recommendation.
What you should know before depending on it:
| Fact | Consequence |
|---|---|
Its deprecated classes carry removal="2.0.0" |
The bridge has an end date, even if the date is not announced |
| No published end-of-support date was found on the release-policy or versioning pages | Check the policy page yourself; "no date" is not "no end" |
It resolves to 36 packages on its own (measured, 5.1), including sqlalchemy, requests and pyyaml, and offers extras for many providers |
It is not free to keep |
langchain-community depends on it |
Installing community pulls the bridge in whether or not you import it |
PyPI says requires_python >=3.10,<4 while the GitHub master pyproject says >=3.11 |
Check PyPI, not the repository, for what you can install |
| Its reference root carries no deprecation statement | Silence is not safety: individual classes are deprecated, the package is not |
Use it as a bridge, not a destination. The exit is a count that reaches zero: the scanner reports langchain_classic imports, and grep -r langchain_classic src/ is the final check. A few things have no one-line replacement (MultiQueryRetriever, the SQLRecordManager of the indexing API, CacheBackedEmbeddings); for those, staying on langchain-classic is a legitimate end state, if you make it a conscious one: keep it in pyproject.toml on purpose, review it on each upgrade, and write down in your dependency register that 2.0 removes it. Never "fix" an old tutorial by installing the bridge and moving on, as 08F.4, 4.2 warned.
3.9 LangGraph API changes, state and saved data#
LangGraph's own migration is small. The v1 guide calls it "largely backwards compatible", and the v1 release notes describe a "stability-focused release" that "keeps the core graph APIs and execution model unchanged": custom StateGraph graphs, checkpointers, interrupt(), Command, Send and ToolNode all continue to work. What changed is a set of names, each of which warns today (3.4) and has a replacement:
| Old | New | Notes |
|---|---|---|
MessageGraph |
StateGraph with a messages key, or MessagesState |
08F.10, 14.2 |
AgentState, AgentStatePydantic, AgentStateWithStructuredResponse* from langgraph.prebuilt |
langchain.agents.AgentState |
|
HumanInterruptConfig, ActionRequest, HumanInterrupt |
InterruptOnConfig and HITLRequest in langchain.agents.middleware.human_in_the_loop |
The old names still import without a warning in 1.2.22 (08F.12) |
ValidationNode |
Nothing: create_agent validates tool input |
|
NodeInterrupt |
interrupt() |
08F.12 |
Interrupt.interrupt_id |
Interrupt.id |
|
StateGraph(..., config_schema=...), @entrypoint(config_schema=...) |
context_schema= |
Deprecated since 0.6 |
StateGraph(input=..., output=...) |
input_schema=, output_schema= |
|
add_node(..., retry=...), @task(retry=...) |
retry_policy= |
Deprecated since 0.5 (the SinceV05 class) |
invoke(..., checkpoint_during=bool) |
durability="async", "exit" or "sync" |
Do not pass durability to a graph with no checkpointer: "sync" raised AttributeError: 'SyncPregelLoop' object has no attribute '_put_checkpoint_fut' in 1.2.22 (08F.11, 4.1) |
from langgraph.constants import Send, Interrupt |
from langgraph.types import Send, Interrupt |
|
MemorySaver |
InMemorySaver |
The old name is kept as an alias |
config["configurable"] for application data |
context= with Runtime[Context] |
thread_id stays in configurable |
The default stream chunk shapes (version="v1") |
version="v2" typed StreamPart dicts; invoke(version="v2") returns a GraphOutput |
v1 is still the default in 1.2.22: check the docs for the current default (08F.14) |
get_stream_writer() in async code before Python 3.11 |
A writer: StreamWriter parameter |
Moot on 3.11 or newer |
ToolNode in create_agent(tools=...) |
A plain tool list | ToolNode itself stays for hand-built graphs |
State. The migration guide says create_agent state must be a TypedDict, and that Pydantic models and dataclasses are no longer supported. The sample in 3.7 tested this: with langchain 1.5.0 an agent built with a Pydantic state_schema built and ran (a custom note key survived the run). The docs, not the observation, are the contract, and a behaviour the docs say is unsupported can disappear in any release. Use a TypedDict extending AgentState, and do not rely on what happens to work.
Saved data is the part that does not roll back. Code can be reverted from a lockfile in minutes. The checkpoints your old version wrote, and the new version reads, cannot. Before you upgrade a service with threads in flight:
- Read the official backward-compatibility page (
docs.langchain.com/oss/python/langgraph/backward-compatibility; it exists, and this lesson did not analyse it in detail, so read it). - Know what you can change with threads in flight: adding a state key is compatible; renaming one drops its saved value; edge topology is not persisted in the checkpoint (08F.10, 14.1); nodes that were mid-flight when you deployed (08F.11, 4.6); and never reorder
@taskcalls orinterrupt()calls under in-flight threads, because replay matches a saved result by task name plus call position, so add new tasks after the existing ones (08F.11, 4.5, 08F.12, 4.2). - Run your tests against a copy of real checkpoint data, once with
LANGGRAPH_STRICT_MSGPACK=trueif you plan to adopt strict mode (08F.11, 6.3). - For pre-1.0 packages, assume forward-only:
deepagents0.6 states that rolling back is unsupported once threads have persisted.
3.10 Retired and moved packages#
A list of packages that are archived, sunset or replaced, with the evidence and the status as of 14 November 2026. Tutorials that depend on them keep circulating; this table is how you recognize them.
| Package or repository | Status | Replacement | Evidence |
|---|---|---|---|
langchain-community |
Sunset from 22 May 2026: "we are making the decision to sunset the langchain-community package... This sunset will take effect immediately." Repository archived on 19 June 2026 ("No longer maintained"); 0.4.2 (22 May 2026) is the last release |
Standalone langchain-<provider> packages, MCP servers, or your own tools. The extra langchain[community] still exists, and the LangChain Academy requirements.txt still lists the package |
Issue 674 in langchain-ai/langchain-community; PyPI |
langchain-experimental |
Sunset the same day (22 May 2026, issue 87 in langchain-ai/langchain-experimental) and repository archived; PyPI 0.4.2 (22 May 2026) is the last release |
Your own code. Anything that runs model-written code is a security decision | Issue 87; GitHub API archived: true; PyPI |
langchain-mcp-adapters |
Repository archived; last release 0.3.2 (6 Aug 2026) | langchain.mcp.MCPAdapter, installed with langchain[mcp] (needs langchain>=1.4.0; a beta namespace). The old package and the new extra pull different major versions of mcp and cannot be imported together (cannot import name 'RequestContext', observed in 08F.8) |
Migration guide; 08F.8 |
langgraph-supervisor |
Repository archived (last push 15 Jul 2026); 0.0.31 (19 Nov 2025); the docs say it is "no longer actively maintained"; it builds on the deprecated create_react_agent |
Subagents as tools: a create_agent supervisor whose tools wrap the workers (08F.13, 7.3) |
Docs migration page; GitHub |
langgraph-swarm |
0.1.0 (4 Dec 2025); repository not archived (last push 28 Oct 2026); no guide in the LangGraph docs | Hand-built handoffs (08F.13, Part 4); the helper is a convenience if you accept a dependency the docs do not cover | 08F.13 |
langserve |
Repository archived | The current deployment path (11A.5) | GitHub |
The langsmith-sdk repository |
Archived 16 Oct 2026: the Python SDK moved to langchain-ai/langsmith-python (JavaScript to langsmith-javascript) |
Nothing for you to change: the PyPI package is still langsmith. Links in old tutorials to the old repository are stale |
GitHub |
langchainhub and langchain.hub |
Deprecated: "All functionality going forward will live in the langsmith package" |
The LangSmith SDK | Docs; langchain-classic source |
langgraph-studio repository |
404 | The Studio of the LangSmith docs (11A.5) | GitHub |
agent-chat-ui, open-agent-platform, open_deep_research, executive-ai-assistant, langgraph-example and langgraph-example-monorepo |
Archived | They are examples, not dependencies; anything copied from them is yours to maintain | GitHub |
langgraph-checkpoint-duckdb |
Last released January 2025 | Treat as stale; use SQLite or Postgres | PyPI |
langmem |
Not released since 27 Oct 2025, although the docs still use it in a summarization recipe | A manual node or SummarizationMiddleware |
PyPI (08F.11) |
How to check any package yourself. Four lookups take a minute and decide whether to depend on something: the PyPI release history (is the last release recent?), the repository page (is there an "archived" banner?), the date of the last push, and the maintainers' own words in the docs or in an issue. With the GitHub CLI:
gh api repos/langchain-ai/langgraph-supervisor-py --jq '{archived, pushed_at}'JavaScript differs. The JS packages are langchain, @langchain/core, @langchain/langgraph and @langchain/community; the JS community library is its own thing and lives in langchainjs/libs/langchain-community, so its Python sunset does not apply to it, and the MCP adapter package is reported still current on the JS side (08F.4, 4.7). Several error-code pages are marked "currently only used in langchainjs". This lesson did not verify JavaScript APIs: read the JavaScript tabs of the same migration pages.
3.11 Silent behaviour changes from 0.x to 1.x#
Renames are loud. These are not: they change what the program does without raising anything. Each is from the 1.0 migration guide or was found by a lesson in this module, and each belongs in a test.
| Change | What you would notice | What to do |
|---|---|---|
Chat models return AIMessage, not BaseMessage |
Type checkers complain; custom bind_tools signatures break |
Update hints and isinstance checks |
langchain-openai: Responses API items are stored in message content by default |
Message content is a list of blocks where it used to be a string |
output_version="v0" (or LC_OUTPUT_VERSION=v0) restores the old shape |
message.content_blocks: a provider-independent view |
New code can read text, reasoning and tool calls uniformly. Serializing the standard blocks into content is opt-in (output_version="v1") |
08F.5, 4.4 |
langchain-anthropic: the max_tokens default is no longer 1024 |
Outputs longer (or costlier) than before | Set max_tokens explicitly if you relied on 1024 |
.text() became the .text property |
The method form still works but warns, and is removed in v2 | Drop the parentheses |
AIMessage(example=...) removed |
A TypeError |
Remove the argument |
| Files are opened as UTF-8 by default | A different decode for legacy files | Check any loader that read non-UTF-8 files |
The streamed agent node is named model, not agent |
A UI or test that filters on the name sees nothing | Update the filter |
create_agent generates structured output in the main loop |
One fewer model call than the old two-step pattern | Re-check cost and latency assumptions |
| Provider package defaults | with_structured_output defaults to json_schema for ChatOpenAI but function_calling for Anthropic; the OpenAI integration page says otherwise (08F.5, 08F.6) |
Pass method= explicitly when it matters |
init_chat_model("gemini-...") with no prefix |
Goes to Vertex AI, with a deprecation warning, not the Gemini API | Write google_genai:gemini-... (underscore; the hyphen form in one docs page fails) |
max_retries differs by provider package |
More or fewer hidden attempts than you assumed. On ChatOllama the argument is ignored, so there are none |
Read each package's default (1.6) |
ChatOpenAI with a gpt-6* model and any tool bound (langchain-openai 1.8.0) |
The class switches to the Responses API as soon as tools are bound, so the same agent that worked on a plain call now returns content as a list of blocks |
Check which API a payload will use before assuming Chat Completions; output_version="v0" (or LC_OUTPUT_VERSION=v0) restores the old shape (08F.5, 2.7) |
ChatOllama and max_tokens, timeout, max_retries |
Silently ignored: no output cap, no timeout, no retries, and no error | Use num_predict for the cap and client_kwargs={"timeout": ...} for the timeout; add middleware as the retry owner (08F.5, 2.3) |
Streamed tool calls (from langchain-core 1.6.13, in the 1.7 changelog) |
Iterating message.tool_calls on a streamed message yields only the new part of each call's arguments |
Accumulate chunks before reading the call (08F.5) |
Python 3.10 dropped by langchain 1.5 and langchain-core 1.8 |
The upgrade is refused on 3.10 | Raise Python first |
The reliable way to find all of these is the technique of this part: build a recording model, run the old and the new code on the same inputs, and compare what the model was shown and what came back (3.12).
3.12 Proving the migration#
"It runs" is not "it behaves". Four layers of evidence, from cheapest to most convincing:
- Scripted parity. For each agent, feed the same scripted replies to the old code and the new code and compare the normalized trajectory: the sequence of
(tool, arguments), the final text and what the model was shown on each call.m01,m02andm03above are exactly this, and they cost nothing and need no key. Keep them as regression tests after the migration. - A fixed evaluation set. Run the same dataset of real inputs through the old and the new code with a live model, and compare outcomes and trajectories (Module 10A, 08A.14, Part 4, and the experiments of 11A.5). A framework upgrade is a model upgrade as far as behaviour is concerned.
- A trace comparison. Tag runs with the release (1.9) and compare the traces of the same few inputs before and after: the number of model calls, the tool arguments, the latency, the tokens.
- A staged rollout. Ship the migrated path behind a switch, run it on a small share of traffic (or in shadow, compared against the old path without serving its answer), and keep the kill switch (08A.14, 7.2). Treat the old path as deletable only after a quiet period.
Finish by running the legacy scanner (the breaks and warns counts should be zero or an explicit, written exception), the deprecation gate (green with no ignore lines for migrated modules), and a clean install from the lockfile on a fresh machine.
Part 4: The deprecation and rename ledger#
Reference
Every lesson of this module found names that changed. This part collects them in one place, with what each is today, so that you have one table to search when an old tutorial or a warning mentions something you do not recognize. It also lists, separately, every place where the documentation and the installed package disagreed, because those cost an afternoon each and the right response is to trust what runs.
How to read the status column.
| Status | Meaning |
|---|---|
| Removed | The import or call fails on langchain 1.x. A bridge may exist in langchain-classic |
| Moved | Works only from a different package or module |
| Deprecated | Works on 1.x, warns, and is scheduled for removal (the source usually says removal="2.0.0") |
| Renamed | The old name is kept as an alias or still accepted |
| Retired | The package or repository is archived or sunset (3.10) |
| Beta | Current, but allowed to change in a minor release |
All entries were verified on 14 November 2026 against the installed packages or the official pages, in the lesson named in the last column. Where an entry says "observed", the lesson ran it.
4.1 The ledger#
Packages and imports (the first three rows were run as real imports in 08F.4, 4.2):
| Old | Status on 1.x | Current | Lesson |
|---|---|---|---|
langchain.chains (LLMChain, ConversationChain, SequentialChain) |
Removed; bridge langchain_classic.chains |
prompt | model (LCEL) |
08F.4, 08F.7 |
langchain.agents.AgentExecutor, initialize_agent |
Removed; bridge langchain_classic.agents |
create_agent |
08F.4, 08F.8 |
langchain.memory |
Removed; bridge langchain_classic.memory |
Checkpointer, Store, SummarizationMiddleware |
08F.4, 08F.11 |
langchain.hub, langchainhub |
Removed; classic copy deprecated since classic 1.0.6 | LangSmith SDK | 08F.4, 08F.6 |
langchain.llms, langchain.chat_models.ChatOpenAI |
Removed | A partner package or init_chat_model |
08F.4, 08F.5 |
langchain.embeddings.OpenAIEmbeddings |
Removed | The partner package class, or init_embeddings |
08F.4, 08F.9 |
langchain.vectorstores, langchain.document_loaders |
Removed | A partner package, langchain_core.vectorstores |
08F.9 |
langchain.text_splitter |
Removed | langchain_text_splitters (not installed by langchain) |
08F.4, 08F.9 |
langchain.prompts, langchain.schema |
Removed | langchain_core.prompts, langchain.messages |
08F.4, 08F.6 |
langchain.retrievers, langchain.indexes, CacheBackedEmbeddings |
Moved to langchain_classic |
The same classes there, or custom logic | 08F.9 |
langchain_community.* |
Retired (sunset 22 May 2026, archived 19 June 2026) | Partner packages, MCP, your own tools | 08F.4, 08F.9 |
langchain_experimental.* |
Retired (sunset 22 May 2026, archived) | Your own code | 08F.4 |
langchain_mcp_adapters |
Retired (archived) | langchain.mcp.MCPAdapter (beta) |
08F.8 |
langgraph_supervisor |
Retired (archived) | Subagents as tools | 08F.13 |
Agents, chains, prompts and memory:
| Old | Status | Current | Lesson |
|---|---|---|---|
LLMChain |
Deprecated since 0.1.17, removal 2.0.0 | prompt | model |
08F.4 |
ConversationChain |
Deprecated since 0.2.7 | create_agent with a checkpointer |
08F.4 |
ConversationBufferMemory and the other memory classes |
Deprecated since 0.3.1 | Checkpointer (short-term), Store (long-term) |
08F.4, 08F.11 |
RetrievalQA, ConversationalRetrievalChain |
Deprecated since 0.1.17 | A retrieval tool with create_agent, or a two-step chain |
08F.9 |
create_stuff_documents_chain |
Deprecated since 0.2.13 | The same | 08F.9 |
create_retrieval_chain, create_history_aware_retriever |
Not marked as deprecated in the source | The same replacement, nonetheless | 08F.9 |
initialize_agent |
Deprecated since 0.1.0 | create_agent |
08F.4 |
AgentExecutor |
Not marked in the source (the docs treat it as legacy) | create_agent |
08F.4, 3.5 |
langgraph.prebuilt.create_react_agent |
Deprecated since LangGraph 1.0 (LangGraphDeprecatedSinceV10), removal 2.0 |
create_agent; prompt= becomes system_prompt= |
08F.4, 3.6 |
pre_model_hook, post_model_hook, state_modifier |
Removed from create_agent (TypeError) |
Middleware (before_model, after_model, wrap_model_call) |
08F.8 |
tools=ToolNode([...]) in create_agent; ValidationNode |
Removed; validation is automatic | A plain tool list | 08F.8 |
| Pre-bound models, Pydantic or dataclass agent state | Not supported per the migration guide | Plain model; TypedDict extending AgentState |
08F.8, 3.9 |
response_format=("prompt", Schema) |
Removed ("has not proven to be particularly reliable") | ToolStrategy, ProviderStrategy |
08F.6, 08F.8 |
StructuredOutputParser, create_structured_output_runnable |
Classic only | with_structured_output |
08F.6 |
RunnableWithMessageHistory, InMemoryChatMessageHistory |
Deprecated (warns: "Use LangGraph's built-in persistence instead") | Checkpointer + thread_id |
08F.7 |
OutputFixingParser, RetryOutputParser |
Moved to langchain_classic |
Structured-output correction paths | 08F.6 |
InjectedState, InjectedStore, InjectedToolCallId, get_runtime() |
Older injection helpers | runtime: ToolRuntime[...] |
08F.8 |
handle_tool_error flags, handle_parsing_errors |
Older error knobs | ToolException + handle_tool_error, or middleware |
08F.8 |
Models and messages:
| Old | Status | Current | Lesson |
|---|---|---|---|
message.text() |
Deprecated since langchain-core 1.0.0, removal 2.0.0 |
message.text |
08F.5 |
AIMessage(example=...) |
Removed | Remove the argument | 08F.4 |
Chat models returning BaseMessage |
Changed to AIMessage |
Update hints | 08F.4 |
init_chat_model("gemini-...") |
Resolves to Vertex AI today, with a deprecation warning ("will change to google_genai in the next major release") |
google_genai:gemini-... |
08F.5 |
load() without allowed_objects |
Beta, warns | allowed_objects="messages" (or "core", "all", a list) |
08F.5 |
LangGraph:
| Old | Status | Current | Lesson |
|---|---|---|---|
MessageGraph |
Deprecated since 1.0.0, removal 2.0 | StateGraph with messages / MessagesState |
08F.10 |
AgentState* from langgraph.prebuilt |
Deprecated | langchain.agents.AgentState |
08F.10 |
HumanInterruptConfig, ActionRequest, HumanInterrupt |
Deprecated (import without a warning in 1.2.22) | InterruptOnConfig, HITLRequest |
08F.12 |
NodeInterrupt |
Deprecated (SinceV10) |
interrupt() |
08F.12 |
Interrupt.interrupt_id |
Deprecated | Interrupt.id |
08F.12 |
config_schema= (graph, entrypoint, supervisor, swarm) |
Deprecated since 0.6 | context_schema= |
08F.10, 08F.13 |
input=, output= on StateGraph |
Deprecated | input_schema=, output_schema= |
08F.10 |
retry= on add_node, @task, @entrypoint |
Deprecated since 0.5 (SinceV05) |
retry_policy= |
08F.12, 08F.14 |
checkpoint_during= |
Deprecated (SinceV10) |
durability= |
08F.11 |
from langgraph.constants import Send, Interrupt |
Deprecated import path | from langgraph.types import ... |
08F.10 |
MemorySaver |
Alias (no warning) | InMemorySaver |
08F.11 |
interrupt_before / interrupt_after for approvals |
Static breakpoints, not recommended for HITL | interrupt(), HumanInTheLoopMiddleware |
08F.12 |
Streaming and events:
| Old | Status | Current | Lesson |
|---|---|---|---|
astream_events(version="v1") |
Deprecated since langchain-core 1.3.3, removal 2.0.0 |
version="v2" for runnables, or LangGraph stream modes |
08F.7 |
Default stream_mode chunk shapes (version="v1") |
Still the default in 1.2.22 | version="v2" typed StreamPart dicts |
08F.14 |
Dict-style access on a GraphOutput |
Deprecated (with invoke(version="v2")) |
result.value, result.interrupts |
08F.12, 08F.14 |
Stream node name agent |
Renamed model |
n/a | 08F.4, 08F.8 |
| Event streaming v3 for graphs | Beta (LangChainBetaWarning) |
Stream modes where stability matters | 08F.8, 08F.14 |
| Callback plumbing for token streaming | Superseded | messages stream mode |
08F.14 |
Beta and experimental surfaces (current, but allowed to change in a minor): langchain.mcp; event streaming v3; AutoModeMiddleware and ModelRouterMiddleware; DeltaChannel; load(); the interrupt_mode="per_call" of HumanInTheLoopMiddleware (present since langchain 1.4.6, with the docs saying LangChain plans to make it the default in the next major release); and everything in deepagents. A beta API is one you may use, but wrap it in a thin adapter of your own so that a change touches one file.
4.2 Where the docs and the installed packages disagree#
Every row below was found by a lesson in this module while preparing it, either by running the code or by reading the package source. In every case the lesson teaches what the package does, and in every case the right response is the same: run the smallest example, read the exception, and read the source in your environment (python -c "import langchain, inspect; ..." or open the file in site-packages). The docs have an edit link on every page, and the repository takes issues.
| Where | What the docs (or an older source) say | What the installed package does | Found in |
|---|---|---|---|
| Python floor | "Requires Python 3.10+" (install page and the 1.0 guides) | langchain 1.5 and langchain-core 1.8 require 3.11 or newer |
08F.4 |
| Version attribute | The versioning page suggests langgraph.__version__ |
AttributeError in 1.2.22; use importlib.metadata |
08F.4 |
AgentExecutor deprecation |
Docs treat it as legacy | No @deprecated on the class in classic 1.0.8 |
08F.4 |
| The v1 migration guide, chains tab | The "v0 (old)" block shows from langchain_classic.chains import LLMChain |
The old import was from langchain.chains import LLMChain: a docs typo |
08F.4 |
| Gemini prefix | One docs example writes google-genai: |
Only google_genai: works; a bare gemini-... goes to Vertex AI |
08F.5 |
max_retries default |
"6" on a docs page | OpenAI: the SDK default; Anthropic: 2; Google: 6; Ollama: ignored (no field) | 08F.5 |
with_structured_output default |
The OpenAI page says function calling | ChatOpenAI defaults to json_schema; Anthropic to function_calling |
08F.5, 08F.6 |
| Ollama usage metadata | The feature table says no token usage | The source builds usage_metadata (not run) |
08F.5 |
GenericFakeChatModel streaming |
The docstring says not implemented | Text streams; tool calls are dropped, so a streamed agent fails with "No generations found in stream" | 08F.5, 08F.8 |
FakeListChatModel.batch |
Looks like a parallel batch | A sequential loop that ignores max_concurrency and return_exceptions |
08F.5 |
PromptTemplate from a file |
Some write-ups call it from_template_file |
The method is from_file |
08F.6 |
| Few-shot class docstrings | Import SemanticSimilarityExampleSelector from langchain_core.prompts |
Those paths do not exist as written | 08F.6 |
RunnableWithMessageHistory |
A research note said no deprecation marker | It warns | 08F.7 |
astream_events(version="v3") on a plain Runnable |
Said to raise NotImplementedError |
The call returns an awaitable and the error appears when awaited | 08F.7 |
| Headless tools | tool(name=..., args_schema=...) returns a HeadlessTool |
TypeError; no HeadlessTool class |
08F.8 |
Gating MCP tools by annotations with when= |
Described as working | Only in per_call mode: in batched mode the predicate receives tool=None |
08F.8 |
| Event streaming | Recommended for new applications | Emits LangChainBetaWarning ... experimental |
08F.8 |
| Dynamic-model example in the migration guide | request.state.messages |
State is a TypedDict: request.state["messages"] |
08F.8 |
| Recursion limit | "25" on some LangChain pages | The agent default is 10,007; 25 is for plain runnables | 08F.8 |
tools_condition docstring |
Imports ToolNode from langchain.tools |
It is exported from langgraph.prebuilt |
08F.8, 08F.10 |
| RAG URL in deprecation messages | The classic notices print docs.langchain.com/oss/python/langchain/rag |
It now redirects to the Deep Agents RAG page | 08F.9 |
OpenAIEmbeddings default |
Looks current | The default model is text-embedding-ada-002 |
08F.9 |
langsmith.evaluate(..., upload_results=False) |
Reads as "do not upload" | With no API key it still POSTed the run data to the LangSmith API (and got a 401). Do not call evaluate offline expecting privacy |
08F.9 |
| Orphan nodes | The docs say compile() catches them |
An unconnected node compiles and never runs | 08F.10 |
| A router with an unknown destination | Expected to raise | With no Literal annotation and no path_map the run ends silently with a log warning |
08F.10 |
create_agent state |
"TypedDict only" | A Pydantic state_schema built and ran in 1.5.0 (3.9). Do not rely on it |
this lesson |
durability without a checkpointer |
The source warns "has no effect" | For "sync" it raised AttributeError: 'SyncPregelLoop' object has no attribute '_put_checkpoint_fut' |
08F.11 |
| Fake embeddings in a concepts page | [[1.0, 2.0] * len(texts)] |
A single flat vector of the wrong shape; return one vector per text | 08F.11 |
__interrupt__ in an invoke result |
A tuple | A list of Interrupt (the GraphOutput.interrupts attribute is a tuple) |
08F.12 |
default_retry_on |
5xx only for HTTP errors | requests.HTTPError is retried for every status (the source tests exc.response for truthiness and an error Response is falsy) |
08F.12 |
Command(resume=None) on a paused thread |
Not documented | UnboundLocalError: ... 'resume_is_map'; the thread stays paused |
08F.12 |
checkpointer=False on a subgraph |
The docs say a stateless subgraph supports no interrupts | The interrupt still paused and resumed; what changed is that the subgraph restarted from its first node | 08F.13 |
add_active_agent_router docstring |
Imports InMemorySaver from langchain.checkpoint.memory |
The real import is langgraph.checkpoint.memory |
08F.13 |
langgraph-swarm handoff tool for an agent named Bob |
Reads as transfer_to_Bob |
The name is lower-cased: transfer_to_bob |
08F.13 |
InMemoryChatMessageHistory deprecation text |
Says "deprecated in LangChain 1.6.4" | The newest langchain on PyPI is 1.5.0 (the text is quoted as printed; worth rechecking) |
08F.7 |
4.3 Keeping a ledger of your own#
A table like this goes stale in a month. The habit that outlives it is a small file in your repository, docs/dependencies.md or similar, with one row per dependency the application chose: the package, why it is there, the version range you tested, who owns upgrading it, the status you last checked (maintained, beta, sunset, archived) and the date you checked it. Add a row when you add a package, and review the rows when you run the upgrade routine of 5.3. It is ten minutes of work that turns "why do we depend on langchain-community?" from an archaeology question into a lookup.
Part 5: Dependency hygiene for the LangChain stack#
Deep-dive
03.11, 13.9 taught the habits (exact resolution committed in a lockfile, hashes, reviewed upgrades, least privilege), 08F.1, 5.9 applied them to agent frameworks, and 12.7, Part 5 is the full security treatment (hashes, cooldowns, scanners, SBOMs, signing, CI). This part does not repeat them. It adds what is specific to this stack: how much it installs, how its packages constrain one another, a real lockfile diff that shows what a routine upgrade adds, why a name in the docs is not a promise of maintenance, and how to build an image from your lockfile. A reminder of why it matters, from the earlier lessons: an agent framework runs your tools with your credentials, so a compromised dependency is a compromised agent.
5.1 What an install pulls in#
You type one package name and many arrive. The first table is what the packages declare (from PyPI metadata, 14 November 2026). The second is what they resolve to.
| Package (version) | Direct requirements, and what is notable |
|---|---|
langchain 1.5.0 |
Three required (langchain-core>=1.8.0,<2, langgraph>=1.2.12,<1.3, pydantic>=2.7.4) plus 19 optional extras: anthropic, aws, azure-ai, baseten, community, deepseek, fireworks, google-genai, google-vertexai, groq, huggingface, mcp (pulls fastmcp>=4.0.11), meta, mistralai, ollama, openai, perplexity, together, xai. Note that langchain[community] still exists although langchain-community has been sunset |
langchain-core 1.8.0 |
Eleven required: certifi, httpx, jsonpatch, langchain-protocol, langsmith, packaging, pydantic, pyyaml, tenacity, typing-extensions, uuid-utils |
langgraph 1.2.22 |
Six required: langchain-core, langgraph-checkpoint, langgraph-prebuilt, langgraph-sdk, pydantic, xxhash |
langgraph-checkpoint 4.3.2, langgraph-prebuilt 1.1.2, langgraph-sdk 0.4.14 |
Small: ormsgpack; the SDK adds httpx, orjson, websockets |
langsmith 0.14.17 |
Fourteen base entries (including httpx2 and zstandard) and many extras (otel, pytest, vcr, openai-agents, google-adk, claude-agent-sdk, livekit, pipecat, and others) |
langchain-openai 1.8.0, langchain-anthropic 1.7.10 |
The provider SDK (openai>=2.45.0, anthropic>=0.120.0), langchain-core, and for OpenAI tiktoken and certifi |
langchain-text-splitters 1.1.3 |
langchain-core only |
deepagents 0.7.38 |
langchain, langchain-core, langchain-anthropic and langchain-google-genai, langsmith, packaging, wcmatch: the default install carries two provider integrations whether or not you use them |
langgraph-cli 0.4.43 |
click, httpx, langgraph-sdk, pathspec, python-dotenv; the extra inmem adds langgraph-api and langgraph-runtime-inmem, the server runtime, which is under the Elastic-2.0 licence rather than MIT: read the licence before you embed it |
langgraph-api 0.18.0 |
37 base requirement lines (some platform-conditional): grpcio, cryptography, starlette, uvicorn, mcp, protobuf, OpenTelemetry packages and more |
langchain-community 0.4.2 |
langchain-classic, langchain-core, langsmith, aiohttp, numpy, requests, sqlalchemy, pydantic-settings, httpx-sse, pyyaml, tenacity |
The resolved weight, measured with uv pip compile (one platform and one Python, so the figures are comparable with each other):
# deps_count.py: how many packages does each install resolve to? (standard library; needs `uv`)
# Resolves for one platform and one Python, so the numbers are comparable with each other.
import subprocess
import tempfile
from pathlib import Path
SPECS = {
"openai + anthropic (two SDKs, no framework)": ["openai", "anthropic"],
"langgraph": ["langgraph"],
"langchain": ["langchain"],
"langchain + langchain-openai": ["langchain", "langchain-openai"],
"langchain + langchain-community": ["langchain", "langchain-community"],
"langchain-classic": ["langchain-classic"],
"deepagents": ["deepagents"],
"langchain[mcp]": ["langchain[mcp]"],
"langgraph-cli[inmem]": ["langgraph-cli[inmem]"],
}
for label, packages in SPECS.items():
requirements = Path(tempfile.mkdtemp()) / "req.in"
requirements.write_text("\n".join(packages))
result = subprocess.run(
["uv", "pip", "compile", "--python-version", "3.13", "--python-platform", "aarch64-apple-darwin",
"-q", "--no-header", "--no-annotate", str(requirements)],
capture_output=True, text=True, check=True,
)
count = sum("==" in line for line in result.stdout.splitlines())
print(f"{label:<46}{count:>4}")openai + anthropic (two SDKs, no framework) 17
langgraph 38
langchain 39
langchain + langchain-openai 44
langchain + langchain-community 55
langchain-classic 36
deepagents 56
langchain[mcp] 86
langgraph-cli[inmem] 86Read it as a ratio. The two bare SDKs are 17 packages; langchain alone is 39; a provider package adds five; langchain-community adds 16 (and drags langchain-classic in with it); the mcp extra more than doubles the tree to 86 because of the MCP server stack; deepagents is 56; the local server extra of the CLI is 86. 08F.4, 3.2 reports 18, 39 and 62 installed packages (uv pip list --format freeze | wc -l) for two SDKs plus python-dotenv, for langchain, and for the full lab project. The 17 here is the same two SDKs without python-dotenv, and for langchain the resolved count and the installed count agree (39). The lockfile (uv.lock) records two to three more entries than are installed (20, 41 and 65 in 08F.4), so say which one you are counting. Expect a difference of a few packages from the method and from a day of releases. Transitive counts were deliberately not computed for every configuration of this stack: run deps_count.py on your own requirements.in and read the tree with uv tree.
None of that is a verdict. The extra packages buy the graph runtime, tracing and the message model. The point is that every one of them is a place a compromised release can enter, and that the cost of an extra is easy to miss: adding langchain[mcp] for one tool server more than doubled the surface.
5.2 Interlocking bounds and install habits#
The packages of the family constrain one another, which is why you should let the resolver pick:
langchain1.5.0 requireslanggraph>=1.2.12,<1.3: a LangChain minor is tied to a LangGraph minor line.langgraph1.2.22 requireslanggraph-prebuilt<1.2,langgraph-checkpoint<5andlanggraph-sdk<0.5.langchainanddeepagentsaccept anylangchain-core1.x, so an upgrade of an unrelated package can silently pull a newer core. Thelangchain-core1.7.0 changelog (22 October 2026) made this concrete: a streaming change meant clients had to be upgraded before servers, and the docs' own workaround for holding a server back was to constrainlangchain-corebelow 1.7.0.
The habits that follow:
| Habit | How |
|---|---|
| Install names, let the resolver choose compatible versions | uv add langchain langgraph. uv add writes a lower bound into pyproject.toml (for example langchain>=1.5.0); the lockfile records the exact versions |
| For an application, the lockfile is the pin; for a library you publish, publish ranges only | Commit uv.lock. This course's install commands name packages and never use ==; the docs' own upgrade snippets show == forms, which is a choice for you to make deliberately, not a default to copy |
| Install from the lock, never from "latest" | uv sync --locked in CI and in images (it fails if pyproject.toml and uv.lock disagree) |
| Verify content, not just versions | uv.lock records hashes by default; uv pip install --require-hashes refuses unhashed input (12.7, 5.2) |
| Upgrade the family together | langchain, langchain-core, langgraph, the checkpointer and the provider packages move in one change |
| Keep the dependency list short, on purpose | Each extra you add is a decision (5.5) |
5.3 Upgrading on purpose: a cooldown, a branch and a diff#
Most malicious releases and many broken ones are noticed within hours. A cooldown tells the resolver to ignore anything newer than a minimum age, so that you are not the first to install a release (12.7, 5.2 gives the setting). Here is what it does to this stack. The project in the sample was created with uv init --bare and uv add langchain langchain-openai; its lockfile after a plain resolution on 18 November 2026 is compared with the lockfile from uv lock --exclude-newer "7 days" (uv 0.12.1; the lock records the span as exclude-newer-span = "P7D"; check your version of uv for the exact syntax). One step comes first, because the recipe fails without it:
With the bounds removed, the comparison, again from a real run on 18 November:
46 packages -> 46 packages
ADDED (0) <- review each one: this is a new thing you now trust
REMOVED (0)
UPGRADED OR DOWNGRADED (11)
~ httpcore2: 2.16.2 -> 2.16.0
~ httpx2: 2.16.2 -> 2.16.0
~ langchain: 1.5.0 -> 1.4.10
~ langchain-core: 1.8.2 -> 1.7.7
~ langchain-openai: 1.8.1 -> 1.7.4
~ langgraph: 1.2.22 -> 1.2.20
~ langgraph-checkpoint: 4.3.2 -> 4.3.1
~ langgraph-prebuilt: 1.1.2 -> 1.1.1
~ langsmith: 0.15.0 -> 0.14.17
~ openai: 3.55.0 -> 3.49.0
~ regex: 2026.11.18 -> 2026.11.9With a seven-day cooldown on that date, langchain stays on 1.4.10 instead of 1.5.0 (released 11 November), langchain-core on 1.7.7 instead of 1.8.2 (released 17 November), and langgraph on 1.2.20 instead of 1.2.22 (released 14 November). Notice that 1.4.9, 1.7.6 and 1.2.20 were the versions 08F.1 quoted a few days earlier, and that a run three days earlier gave 1.4.9 and 1.7.6 where this one gives 1.4.10 and 1.7.7: the cutoff moves with the calendar, so a cooldown result is a dated observation too. In a fast ecosystem a week is a long time, and a cooldown is a conscious trade of freshness for safety.
The cooldown has a cost, and the honest statement of it is that it also delays fixes, including security fixes. The pattern that works: keep the cooldown on for routine upgrades, and for an urgent advisory run a deliberate upgrade of that one package with an absolute date, read the diff, and ship it.
The routine, which extends 08F.4, 5.10:
- Upgrade on a branch, with the cooldown on:
uv lock --upgrade-package langchainfor one package,uv lock --upgradefor all. - Read the changelog entries between your version and the new one, not only the latest (Python floors, default changes, renamed events, beta changes). The changelog has an RSS feed.
- Diff the lockfile (5.4) and review every added package.
- Run the gate and the tests (3.4, 1.8): the deprecation gate, the scripted parity tests and the golden trajectories.
- Re-run the evaluation set and compare a few traces (3.12).
- Deploy in order: clients before servers where a streaming or protocol change is noted.
- Never mix the upgrade with a feature. If something breaks you want one suspect.
5.4 Reading a lockfile diff#
A lockfile diff is the cheapest supply-chain review there is, and almost nobody reads it. This script (standard library only) compares two uv.lock files and lists what was added (new things you now trust), what was removed and what changed version.
# lock_diff.py: what changed between two uv.lock files? (standard library only, Python 3.11+)
# usage: python lock_diff.py old.lock new.lock
import sys
import tomllib
from pathlib import Path
def load(path: str) -> dict[str, str]:
data = tomllib.loads(Path(path).read_text())
return {p["name"]: p.get("version", "?") for p in data["package"]}
old, new = load(sys.argv[1]), load(sys.argv[2])
added = sorted(set(new) - set(old))
removed = sorted(set(old) - set(new))
changed = sorted(n for n in set(old) & set(new) if old[n] != new[n])
print(f"{len(old)} packages -> {len(new)} packages")
print(f"\nADDED ({len(added)}) <- review each one: this is a new thing you now trust")
for name in added:
print(f" + {name} {new[name]}")
print(f"\nREMOVED ({len(removed)})")
for name in removed:
print(f" - {name} {old[name]}")
print(f"\nUPGRADED OR DOWNGRADED ({len(changed)})")
for name in changed:
print(f" ~ {name}: {old[name]} -> {new[name]}")The two lockfiles are real. old.lock was resolved as if on 1 May 2026 (--exclude-newer 2026-05-01), new.lock is the same project upgraded on 15 November 2026. Output:
43 packages -> 46 packages
ADDED (5) <- review each one: this is a new thing you now trust
+ httpcore2 2.16.0
+ httpx2 2.16.0
+ httpx2-jsfetch 1.0
+ truststore 0.10.5
+ websockets 17.4
REMOVED (2)
- colorama 0.4.6
- tqdm 4.67.3
UPGRADED OR DOWNGRADED (32)
~ annotated-types: 0.7.0 -> 0.8.0
~ anyio: 4.13.0 -> 4.16.0
~ certifi: 2026.4.22 -> 2026.10.23
~ charset-normalizer: 3.4.7 -> 3.5.2
~ idna: 3.13 -> 3.20
~ jiter: 0.14.0 -> 0.19.0
~ jsonpatch: 1.33 -> 1.47
~ jsonpointer: 3.1.1 -> 3.12
~ langchain: 1.2.17 -> 1.5.0
~ langchain-core: 1.3.2 -> 1.8.0
~ langchain-openai: 1.2.1 -> 1.8.0
~ langchain-protocol: 0.0.14 -> 0.0.21
~ langgraph: 1.1.10 -> 1.2.22
~ langgraph-checkpoint: 4.0.3 -> 4.3.2
~ langgraph-prebuilt: 1.0.13 -> 1.1.2
~ langgraph-sdk: 0.3.13 -> 0.4.14
~ langsmith: 0.8.0 -> 0.14.17
~ openai: 2.33.0 -> 3.51.0
~ orjson: 3.11.8 -> 3.13.0
~ ormsgpack: 1.12.2 -> 1.13.1
~ packaging: 26.2 -> 26.3
~ pydantic: 2.13.3 -> 2.14.3
~ pydantic-core: 2.46.3 -> 2.50.4
~ regex: 2026.4.4 -> 2026.11.9
~ requests: 2.33.1 -> 2.34.2
~ tenacity: 9.1.4 -> 9.2.1
~ tiktoken: 0.12.0 -> 0.14.0
~ typing-extensions: 4.15.0 -> 4.16.0
~ typing-inspection: 0.4.2 -> 0.4.5
~ urllib3: 2.6.3 -> 2.8.0
~ uuid-utils: 0.14.1 -> 0.19.0
~ xxhash: 3.7.0 -> 4.1.0Six and a half months of upgrades, and the interesting part is not the version numbers. Three things deserve a reviewer's attention:
- Five package names appeared that nobody on the team chose, and each can be identified. The review question is who requires this, and is it what it claims to be? Answered on 18 November 2026 from PyPI's JSON metadata, the GitHub API and the repositories (not from the PyPI "maintainers" tab, which does not render without JavaScript, so the publisher claims rest on metadata, repository and README):
| Package | Who publishes it | Why it arrived | First upload |
|---|---|---|---|
httpx2 and httpcore2 |
Pydantic, from github.com/pydantic/httpx2 (BSD-3-Clause, not archived; the PyPI author is Tom Christie, who also wrote httpx) |
langsmith (0.8 to 0.14) and openai (2 to 3) now require httpx2 |
11 May 2026 |
httpx2-jsfetch |
Hood Chatham of the Pyodide project: "httpx2 transports for Emscripten/Pyodide" | httpx2 requires it only where sys_platform == 'emscripten': it sits in the lock for every platform and is installed on none of the usual ones |
5 Aug 2026 |
truststore |
Seth Michael Larson, github.com/sethmlarson/truststore (system certificate stores) |
Required by httpx2 |
10 Mar 2022 |
websockets |
A long-established package | Already required by langgraph-sdk and langsmith |
not checked |
So on a laptop four of the five packages are installed, and none is an unknown quantity. The README of httpx2 says it is "a continuation of" the work on httpx and that Pydantic is "picking up stewardship under the HTTPX2 name", because httpx has seen limited activity (encode/httpx itself is not archived). That is the same fact 03.1, 4.5 teaches from the SDK side: openai 3.x and anthropic 2.x use httpx2, Pydantic's fork of httpx. A current LangChain environment therefore carries both: langchain-core and langgraph-sdk still require httpx, langsmith and openai require httpx2, which is why 08F.5 collects "whichever of the two is installed" when it lists transport errors (1.6). The age is the review finding: httpx2 was a six-month-old package when it landed in this lock, which is exactly what a cooldown or a minimum-age check would flag. The habit stays the point, because new names in a diff are exactly where a supply-chain compromise would show up; this time the review ends in "expected, and explained".
- The lock answers "who requires it" and
uv tree --invert --package httpx2prints the chain (run on 18 November in the cooldown project of 5.3, trimmed to the first lines):
httpx2 v2.16.0
├── langsmith v0.14.17
│ └── langchain-core v1.7.7
│ ├── langchain v1.4.10
│ │ └── probe v0.1.0
│ ├── langchain-openai v1.7.4
│ │ └── probe v0.1.0
│ ├── langgraph v1.2.20
│ │ └── langchain v1.4.10 (*)
│ ├── langgraph-checkpoint v4.3.1
│ │ ├── langgraph v1.2.20 (*)
│ │ └── langgraph-prebuilt v1.1.1
│ │ └── langgraph v1.2.20 (*)
│ ├── langgraph-prebuilt v1.1.1 (*)httpx2 is required by langsmith and by openai (the 3.x SDK), the two packages at the centre of the tree. It brings httpcore2, truststore and, on Emscripten only, httpx2-jsfetch. websockets is required by langgraph-sdk and langsmith.
- A major version moved under you:
openaiwent from 2.33.0 to 3.51.0 andlangsmithfrom 0.8.0 to 0.14.17, because the packages above them declare open-ended ranges (langchain-openai, for one, requires onlyopenai>=2.45.0). A change of major version in a transitive dependency is a reason to run the evaluations, not only the unit tests.
The "removed" lines matter too: tqdm (progress bars) and a terminal-colour helper (the Windows-only dependency of tqdm, as 08F.4 notes) disappeared, which is usually harmless and occasionally means a feature your code used implicitly is gone.
5.5 Integrations nobody audits#
The LangChain documentation says it lists "1000+ integrations", and the page of provider cards, counted on 14 November 2026, has about 677 cards, many of them third-party packages that are not LangChain's (middleware and tool packages, for instance). The contributing rules explain why: new integrations are not accepted as pull requests to any langchain-ai repository; they must be published as independent packages on PyPI, and hosted guides require eligibility. So:
The sunset of langchain-community (3.10) is the most instructive case, and the maintainers' reasons are a checklist for your own dependencies: many integrations of varying maintenance, a large number of optional dependencies, and a shared release cycle. Their suggested replacements are standalone provider packages, MCP, or a tool written in your application code.
A review checklist before you add an integration package:
| Question | Where to look |
|---|---|
| Who publishes it: the provider, LangChain, an organization or one person? | PyPI page, repository owner |
| When was the last release, and is the repository archived? | PyPI release history, the repository banner (3.10 has the gh api check) |
| How many packages does it add, and does it need native builds? | deps_count.py on the new list |
What does it run when installed or imported (setup.py, .pth files)? |
03.11, 13.9 |
| What credentials will it receive? Remember it runs your tools with your keys | 08A.14, 2.8 |
| Is its licence compatible with your use? | PyPI classifiers, repository |
| Could twenty lines of your own code, or an MCP server you vet, do the same job? | 08F.8, Part 6 |
An installer that pipes to a shell deserves the same scepticism: Deep Agents Code is installed with curl -LsSf https://langch.in/dcode | bash (documented in the docs and the README). That is a trust decision about a script that will run on your machine; download it and read it before you run it.
5.6 Advisories, and what they teach#
As of 14 November 2026 the official repositories had published security advisories on GitHub: 9 for langchain, 13 for langgraph, 2 for deepagents and none for langchain-community. This lesson does not list the identifiers (check the repositories' Security tabs for current ones). What matters is the pattern, because it tells you where this stack is soft:
| Class of issue | Why an agent framework has it | What to do |
|---|---|---|
Deserialization (load(), the checkpoint serializer and msgpack) |
Persisted state and prompts are objects rebuilt from data | Treat checkpoints and load() inputs as trusted-source only (08F.11, Part 6) |
| Template injection | Prompts are templates, and templates can be programmable | No jinja2 from untrusted input (08F.6) |
| SSRF and path traversal | Loaders and tools fetch URLs and read files named by a model or a user | Allow-lists, and validate arguments in the tool (08F.8, 9.3) |
| SQL injection (in the SQLite checkpointer and store) | Persistence layers build queries | Upgrade promptly; keep filters and namespaces from untrusted input out of the store API |
| Authorization gaps | Servers expose threads, runs and stores | Per-user scoping and the platform's auth hooks (11A.5) |
The mitigation is boring and effective: upgrade routinely (the routine of 5.3, not an emergency), turn on Dependabot or GitHub security alerts for the repositories you depend on, run pip-audit or osv-scanner in CI (12.7, 5.2: they catch known advisories and are blind to a brand-new malicious release, which is what the cooldown and the lockfile diff are for), and keep to the stance of 1.10. The March and October 2026 compromises of litellm (the gateway library that 03.11 and 12.7 analyse) were not LangChain incidents, and are the reason the habits exist.
5.7 Building images from a lockfile#
A lockfile only helps if the thing you deploy is built from it. Two places this goes wrong:
- A plain image.
uv sync --locked --no-devinstalls exactly the locked set and fails ifpyproject.tomlanduv.lockdisagree. A barepip install .oruv pip install .in a Dockerfile resolves afresh. - The Agent Server build. A
langgraph.jsonthat lists"dependencies": ["."]re-resolves packages frompyproject.tomlat image build time and does not useuv.lock, per the CLI documentation. To build from the lockfile, usesource: {"kind": "uv"}; read the CLI page for the exact shape of the entry in your version (11A.5 owns deployment). A deployment also moves to the newest stable server on each revision unlessapi_versionis pinned inlanggraph.json(1.11).
Then verify what shipped: list the installed packages in the built image and compare with uv.lock, and pin base images by digest (12.7, 5.2).
5.8 A dependency checklist#
-
uv.lockis committed, and CI and images install withuv sync --locked - The dependency list contains only packages you chose on purpose, each with a row in your ledger (4.3)
- Every integration package passed the checklist of 5.5, and none is
langchain-community,langchain-experimental,langchain-mcp-adaptersorlanggraph-supervisorwithout a written reason - Upgrades happen on a branch, with a cooldown, a changelog read and a lockfile diff that someone reviewed
- The family (
langchain,langchain-core,langgraph, checkpointers, provider packages) moves together, and clients move before servers - The deprecation gate is green and the scanner's
breakscount is zero (3.3, 3.4) - Advisories for the repositories you depend on reach a person
- Images are built from the lockfile, with the base image pinned by digest and
api_versionpinned - No production credentials exist in CI that only runs unit tests (every test in this module needs no key)
Part 6: The LangChain stack against the other frameworks#
Deep-dive
Lesson 08F.1 compared the field feature by feature and built one agent four ways. This part does not redo that. After a dozen lessons inside one stack, a different question is worth asking: what would it cost to leave it, or to add a second one, and what should you do now so that the cost stays small? The answer is about where the lock-in actually lives, which is not where most people look.
6.1 Where lock-in lives#
Teams worry about the wrong thing. They compare how many lines a hello-world takes in each framework, and then discover, a year later, that the expensive part to move was something else. There are four places a framework holds you, and they differ a lot in how hard they are to move:
| What | How hard to move | How to keep it portable |
|---|---|---|
| The code you wrote against the API (agent construction, middleware, graph nodes) | Moderate: it is mostly mechanical, and it is the part Part 3 trained you to do | Keep the framework at the edge: one adapter module builds agents; business rules are plain functions (2.6) |
| Tools and prompts | Easy, if you kept them plain: a name, a description, a JSON Schema and a function | The framework-neutral ToolSpec of 08F.1, 5.1; prompts as versioned text (04.10) |
| Durable state (checkpoints, threads, in-flight approvals, long-term memory) | Hard, and the one most often forgotten: the state shape is the framework's, and a run paused mid-graph cannot be resumed by another framework | Treat conversations as data you own (messages in your own schema); let in-flight runs finish or drain before you switch (6.5) |
| Traces and evaluations | Easy to hard: datasets and graders can be yours; traces are portable if they are OpenTelemetry, and tied to a vendor if they are not | Keep evaluation datasets in your own format (Module 10A); prefer a trace backend that ingests OpenTelemetry (08F.1, 5.3) |
| The operating model (a hosted server, its API, its auth, its cron) | Depends on how much of it you adopted | Use it for deployment, keep the agent core library-shaped (11A.5) |
08F.1, 5.4 made the same point from the other side: durability is a spectrum, and every durable layer adds a state schema you now own and must migrate. A framework with sessions, a framework with a checkpointer, and a durable-execution engine lock you in to different degrees. That is the real cost of choosing LangGraph's persistence, and it is also a good reason to choose it, because the alternative is to build and own the same thing yourself.
6.2 What the official documentation says about the others#
The honest reading of the vendor's own pages, which are statements of positioning and not neutral benchmarks:
- The product overview (
docs.langchain.com/oss/python/concepts/products) lays the stack out in tiers, and names alternatives for each: runtimes (Temporal, Inngest), frameworks (Vercel AI SDK, CrewAI, OpenAI Agents SDK, Google ADK, LlamaIndex) and harnesses (Deep Agents SDK, Claude Agent SDK, Manus). It also says to reach for LangGraph when you need "fine-grained, low-level control", durable execution, or a mix of deterministic and agentic steps. - The only head-to-head comparison page in the Deep Agents docs compares Deep Agents with the Claude Agent SDK, in a table that covers the execution backend, model providers, deployment, multi-tenancy and licence (Deep Agents is MIT). It does not compare
create_agentor LangGraph with the OpenAI, Google or Pydantic frameworks. - The tiering is the useful idea. LangChain's stack is three products that you can adopt separately (a harness over a framework over a runtime), while several competitors are one package that does the middle two. That is why the choice is rarely "LangChain or X" and more often "which layer do I take from whom" (the question 08F.1, 2.1 ended on).
6.3 The same idea, in each framework's words#
If you learned another framework first, this table translates the concepts of this module. It uses only what 08F.1 established; for anything not in 08F.1, read the framework's own documentation.
| Concept | LangChain and LangGraph | OpenAI Agents SDK | Pydantic AI | Claude Agent SDK | Google ADK |
|---|---|---|---|---|---|
| Define a tool | @tool (or StructuredTool) |
@function_tool |
@agent.tool or @agent.tool_plain |
@tool(name, description, schema) |
A plain function in tools=[...] |
| Pause for human approval | interrupt() and Command(resume=...), or HumanInTheLoopMiddleware |
needs_approval on a tool; the run pauses with interruptions, and you resume the serialized RunState |
requires_approval=True; the run returns DeferredToolRequests and you start a new run with the results |
A can_use_tool callback, permission_mode or hooks (PreToolUse can deny) |
The tool confirmation flow and callbacks |
| Where the approval state lives | The checkpointer, external and auditable | The run state | Your result object or store | The Claude Code session | Session state |
| Conversation memory | Checkpointer + thread_id; Store for cross-thread |
Sessions (SQLiteSession and others) |
A persistence capability | The session | Session services (InMemorySessionService in tests) |
| A fake model for tests | A GenericFakeChatModel subclass that accepts bind_tools |
The SDK's test helpers | TestModel, FunctionModel, agent.override(...) |
query() over a fake transport |
A fake model= and an in-memory session service |
| Tracing | LangSmith, or OpenTelemetry | OpenAI's tracing UI, with a processor interface | Logfire, or any OpenTelemetry backend | The message stream you consume | OpenTelemetry GenAI conventions |
| Guardrails | Middleware hooks (PIIMiddleware, before_model, custom) |
@input_guardrail and @output_guardrail |
Capabilities and hooks, output types | can_use_tool and PreToolUse hooks |
Callbacks and plugins |
Two things to take from the table. First, the mechanisms are the same (08F.1, 5.5 says it as "pause, serialize enough state to resume, record the decision, continue"). What differs is how much machinery you get and where the pending state lives, and that is a durability question, not a syntax question. Second, one row should make you cautious in every framework: the approval rows describe a pause in the top-level run, and a pause inside a sub-agent is the place frameworks differ and where hand-rolled loops go wrong (08F.13, 3.8 tested it here).
6.4 The adapter: keep the framework at the edge#
The cheapest portability work is the boundary. The sample below is the pattern of 08F.1's toolspec.py with a LangChain adapter at the end: the tool is a plain function with its schema; one ten-line function turns it into a LangChain tool; the agent is built from the adapter's output. A second framework would get a second adapter of five to fifteen lines (08F.1, 5.1).
# x01_adapter.py: tools and prompts live in YOUR modules; LangChain gets a ten-line adapter.
# The same ToolSpec idea as 08F.1 (5.1): a name, a description, a JSON Schema and a plain function.
import inspect
import typing
from dataclasses import dataclass
from typing import Any, Callable
from langchain_core.tools import StructuredTool
from langchain.agents import create_agent
from langchain.messages import AIMessage, HumanMessage, ToolCall
from fakes import FakeToolCallingModel
# ---------- your code: no framework imports ----------------------------------------------------
@dataclass(frozen=True)
class ToolSpec:
name: str
description: str
fn: Callable[..., Any]
parameters: dict
def register(fn: Callable[..., Any]) -> ToolSpec:
hints = typing.get_type_hints(fn)
kinds = {int: "integer", float: "number", bool: "boolean", str: "string"}
sig = inspect.signature(fn)
props = {p: {"type": kinds.get(hints.get(p, str), "string")} for p in sig.parameters}
required = [p for p, v in sig.parameters.items() if v.default is inspect.Parameter.empty]
schema = {"type": "object", "properties": props, "required": required, "additionalProperties": False}
return ToolSpec(fn.__name__, (fn.__doc__ or "").strip(), fn, schema)
def lookup_order(order_id: str) -> str:
"""Look up an order by its ID."""
return f"Order {order_id}: shipped"
SYSTEM_PROMPT = "You are a support agent." # in real code: loaded from a versioned prompt file
# ---------- the adapter: the ONLY place that knows about LangChain -----------------------------
def to_langchain(spec: ToolSpec) -> StructuredTool:
return StructuredTool(name=spec.name, description=spec.description, args_schema=spec.parameters, func=spec.fn)
tools = [to_langchain(register(lookup_order))]
print("tool name:", tools[0].name, "| schema:", tools[0].args_schema)
script = iter([
AIMessage(content="", tool_calls=[ToolCall(name="lookup_order", args={"order_id": "A-1042"}, id="c1")]),
AIMessage(content="It has shipped."),
])
agent = create_agent(FakeToolCallingModel(messages=script), tools=tools, system_prompt=SYSTEM_PROMPT)
result = agent.invoke({"messages": [HumanMessage("Where is A-1042?")]})
print([f"{m.type}: {m.content}" for m in result["messages"]])tool name: lookup_order | schema: {'type': 'object', 'properties': {'order_id': {'type': 'string'}}, 'required': ['order_id'], 'additionalProperties': False}
['human: Where is A-1042?', 'ai: ', 'tool: Order A-1042: shipped', 'ai: It has shipped.']Everything above the adapter imports nothing from LangChain: the ToolSpec, the schema builder, the function and the prompt can be tested alone and reused. Everything LangChain-specific is to_langchain and the lines under it. That is what "framework at the edge" means in code, and it is why a migration inside LangChain (Part 3) and a move to another framework (6.5) cost the same kind of work: rewrite the adapter, not the logic.
6.5 An exit plan#
You do not need to plan to leave. You need to know what leaving would take, because that knowledge changes how you build today.
| Step | What to do | Why |
|---|---|---|
| 1 | Keep tools, prompts, domain types and rules in framework-free modules (2.6, 6.4) | They are most of the value, and they move for free |
| 2 | Keep conversations as your own data: store a copy of messages in your schema, not only in checkpoints | Messages move; graph positions do not |
| 3 | Version your datasets and graders yourself (Module 10A) | The evaluation set is how you know the replacement behaves |
| 4 | Keep scripted parity tests (3.12) | They are the same tool for a framework switch as for a version upgrade |
| 5 | Switch by traffic, not by flag day: new threads go to the new stack; threads in flight finish on the old one (drain, or wait; RunControl drain is in 08F.12) |
A run paused mid-graph cannot be resumed elsewhere, and this is the strangler pattern applied to agents |
| 6 | Retire the old stack when its in-flight count is zero | Not before |
6.6 Stay, add or leave#
A decision table by symptom, honest about costs on both sides. The costs of the LangChain stack are in 08F.4, 7.4 (churn, docs that lag the code, dependency weight, naming confusion, beta surface), and Part 4 and Part 5 here added evidence for each.
| What you are seeing | Likely response | Reason |
|---|---|---|
| The dependency tree is the problem | Remove extras and unused integrations first; if it is still too heavy, use the provider SDK and your own loop (08A.2, 03.11) | 39 packages for langchain alone against 17 for two SDKs (18 with python-dotenv, as in 08F.4) (5.1) |
| Docs and code disagree and you lose time | Pin by lockfile, keep scripted tests, trust the installed package (4.2) | The disagreements are at the edges; the core held up |
| You only call one provider and want its newest feature today | Use that provider's SDK for that call; keep LangChain where it adds value | Provider packages lag native SDKs by days; escape hatches narrow but do not remove the gap |
| You need durable human approval, resumable runs, time travel | Stay with LangGraph's checkpointer, or accept building the same state layer yourself | This is the part most teams should not build (08F.1, 5.5) |
| Your agent is one prompt, one schema, no tools | You do not need an agent framework | 08F.5, 03.4 |
| You are all-in on one provider and its hosting | That provider's framework may be less glue (08F.1, 2.3) | Reference implementations, fewer layers |
| You have a team of Python engineers who like types and want fast tests | Compare Pydantic AI seriously (08F.1) | Different strengths, not worse ones |
| You depend on a retired package (community, supervisor, MCP adapters) | Migrate that piece (Part 3), do not leave the whole stack over it | The replacement is usually small (08F.13, 7.3) |
| Everything is working, the tests are green, the bill is fine | Do nothing | A working system plus tracing beats a migration you do not need (08F.1, 2.3) |
Part 7: Checklists and a failure gallery#
Reference
7.1 A production-readiness checklist#
Before an agent built on this stack takes real traffic:
Structure
- The control flow is the simplest that works:
create_agent, or a graph with an agent node, or a chain (1.1); no chain exists where one structured call would do (2.1) - Agents are built by one factory with house defaults, and every agent and graph has a
name(1.2) - Deterministic steps are code; the irreversible step is its own node behind a decision and an idempotency key (1.3, 1.5)
State and persistence
- State is a
TypedDictwith reducers where parallel nodes write; nothing mutates state; no global holds user data (1.4, 2.2) - A durable checkpointer, a stable
thread_idand context passed on every call, including resumes - Retention and erasure are planned for both the threads and the store
Bounds
- Every loop has a bound next to it (1.7); timeouts exist on models, tools and the request
- Exactly one owner for each class of retry (1.6)
Safety
- Least privilege, enforcement inside tools (not only a filtered tool list), untrusted text treated as data, checkpoint database trusted-write only (1.10, Module 12)
Quality
- The test ladder up to scripted-path tests exists, with a golden trajectory per agent, and an evaluation set for the real model (1.8)
- Every run is findable: names, tags, release, thread id (1.9)
Dependencies and operations
- The checklist of 5.8 is green, the deprecation gate passes and the scanner reports no
breaks(3.4) - The deploy path is production-grade, built from the lockfile, with
api_versionpinned (1.11, 5.7)
7.2 A migration checklist#
- Inventory run; list of
breaks,warnsandreviewkept (3.3) - Baseline recorded on the old versions: tests, traces, an evaluation run (3.1)
- Python 3.11 or newer; the family upgraded together;
langchain-classicadded as an explicit, temporary bridge - Imports with one-line replacements fixed; retired packages replaced (3.10)
- Deprecation gate on, with a shrinking
ignorelist (3.4) - Each agent migrated with scripted parity tests comparing trajectory and what the model saw (3.5, 3.6, 3.12)
- Memory moved to checkpointer and Store; saved-state compatibility checked on a copy of real data (3.7, 3.9)
- Silent behaviour changes reviewed (3.11)
-
langchain-classicremoved or kept on purpose, with a note about 2.0 - Evals re-run, traces compared, rollout staged behind a switch
7.3 A failure gallery#
The symptoms you will meet, as the symptoms, with where to look.
| Symptom | Cause | Fix | Section |
|---|---|---|---|
ModuleNotFoundError: No module named 'langchain.chains' (or .memory, .llms, .prompts) |
Old tutorial code on a 1.x install | Port, or bridge with langchain-classic |
3.3, 08F.4 |
TypeError: create_agent() got an unexpected keyword argument 'prompt' |
create_react_agent arguments |
system_prompt=, middleware |
3.6 |
| The migrated agent runs but answers differently | A silent change: default, message shape, max_tokens, content blocks, history window |
Compare what the model was shown, old and new | 3.11, 3.12 |
| A chain that used memory "forgets" after a port | The memory variable was dropped (optional placeholder), or thread_id changes per request |
Required MessagesPlaceholder; one thread_id per conversation |
3.7, 08F.11 |
| A bill spike with no errors | An agent with no model-call limit | The factory | 1.2, 2.3 |
| A failing tool is hit nine times | Two layers of retries | One owner | 1.6 |
| One user sees another's data | A global, closure or cache holds it | State, context, Store | 2.2 |
After an approval, runtime.context is None or an AttributeError appears |
Context is not saved in checkpoints | Pass context= again on resume |
1.4, 08F.12 |
ModuleNotFoundError: No module named 'fastmcp' after import langchain.mcp |
The extra is not installed | uv add "langchain[mcp]" |
08F.4 |
ImportError: cannot import name 'RequestContext' |
The old MCP adapter package and the new extra pull different mcp majors |
Use one stack, preferably langchain.mcp |
3.10 |
AttributeError: 'SyncPregelLoop' object has no attribute '_put_checkpoint_fut' |
durability="sync" with no checkpointer |
Add a checkpointer or drop the argument | 3.9 |
GraphRecursionError after 10,007 steps |
A loop with no exit, or recursion_limit under configurable |
A counter, a model-call limit, a top-level key | 2.3 |
| The build is green but production behaves differently | An image that re-resolved dependencies | Build from uv.lock |
5.7 |
| An upgrade added five packages | A transitive dependency changed | Read the lockfile diff, find who requires each | 5.4 |
| Nobody noticed a deprecation until it was removed | Warnings are hidden by default | The gate in CI | 3.4 |
install refused on Python 3.10 |
langchain 1.5 and langchain-core 1.8 need 3.11 |
Raise Python | 3.2 |
create_supervisor(...).invoke fails |
The helper returns an uncompiled graph, and the package is archived | Move to subagents as tools | 08F.13, 3.10 |
| A tutorial's model id is rejected | Retired model, or a sampling parameter the model refuses | Look up the provider's current page | 3.3, 02.9 |
Common misconceptions#
| Misconception | Reality |
|---|---|
| "Deprecated means it is broken, so I must migrate today." | Deprecated code keeps working through all of 1.x and the source says removal="2.0.0". It is scheduled work, not an emergency, but it is a reason to schedule (3.2). |
| "If the old code runs without an error, the migration is done." | The dangerous changes are silent: a default, a message shape, a dropped memory variable, a node renamed. Compare what the model was shown, not whether the code ran (3.7, 3.11). |
"AgentExecutor is deprecated, so I will see a warning." |
The class carries no @deprecated decorator in langchain-classic 1.0.8, so a quiet console proves nothing (3.5). |
"There is an official guide from AgentExecutor to create_agent." |
There is not. The archived 0.3 notebook goes to create_react_agent, and the 1.0 guide goes from there to create_agent: two hops (3.5). |
"langchain-classic is the safe way to keep old code." |
It is a bridge with a 2.0 removal date on its deprecated classes and 36 packages of its own. Using it on purpose is fine; never "fixing" a tutorial by installing it and moving on is the rule (3.8). |
"create_react_agent is the same as create_agent with a different name." |
The arguments are renamed, and the hooks changed meaning: llm_input_messages became a wrap hook that edits only one call, and the graph's node names changed (3.6). |
| "Memory moved from the memory classes to LangGraph, and nothing else changed." | The old window memory discarded old turns; a checkpointed thread keeps them and only limits what is sent. State now grows unless you summarize or prune (3.7). |
| "More chain steps make the answer more reliable." | Each step is another call that can be wrong, and the steps multiply cost and latency. Merge steps unless something deterministic or a different model or permission sits between them (2.1). |
| "A global variable is fine, it is just a cache." | It is shared by every user of the process and is invisible to checkpoints: one user can see another's data (2.2). |
| "Retries make it more reliable, so add them everywhere." | Layers multiply: three plus three attempts is nine. One owner per failure class (1.6). |
| "The recursion limit protects me from runaway agents." | For a graph it is 10,007 steps, which is thousands of paid model calls. Use model-call and tool-call limits, and set the limit under the top-level config key (1.7). |
| "A model-call limit is a budget." | It counts calls. It does not bound money, tokens or wall-clock time (1.2). |
| "Everything in the LangChain docs is maintained by LangChain." | Listing is not endorsement: new integrations must be independent PyPI packages, and the project sunset its own community package (5.5). |
| "Pinning versions is enough supply-chain defence." | A pin stops silent upgrades, not a compromised release you pinned. Hashes, a cooldown, lockfile-diff review and fewer dependencies work together (5.3, 12.7). |
| "A routine upgrade only changes versions." | The real diff added five packages nobody on the team chose (all identified in 5.4) and moved openai across a major version (5.4). |
| "The docs are the specification." | In 30-odd places this module found the docs and the installed package disagreeing. Run the smallest example and trust the package (4.2). |
| "Switching frameworks is a rewrite of the code." | The code is the easy part. Durable state, in-flight runs and traces are what stay behind (6.1). |
Key takeaways#
- Start at the highest layer that expresses your control flow.
create_agent, then aStateGraphwith agent nodes, then lower. The choice is reversible in one direction only. - Build every agent through one factory with house defaults: a model-call limit that ends the run normally, per-tool limits on side-effect tools, retries only on read-only tools, a
name. Test that the defaults hold. - Make the workflow deterministic and the agent one bounded step in it. Validate first, gate with code, put irreversible actions in their own node behind an approval and an idempotency key derived from durable state.
- Keep state small and typed, return updates, give parallel writes a reducer, pass context on every call including resumes, and never keep user data in a global.
- One owner for every retry. Stacked layers multiply attempts (3 and 3 gave 9).
- Bound every loop with a counter next to it. The recursion limit is 10,007, and counters are not budgets or timeouts.
- Over-chaining, hidden state, unbounded loops, swallowed errors and silent failures are the anti-patterns to review for. Test the final state of every path, not only that it ran.
- Migration is inventory, baseline, bridge, migrate, remove. Scan the repository, record a baseline, bridge with
langchain-classic, port agents one at a time, remove the bridge or keep it on purpose. - Turn deprecations into errors in CI with the two deprecation classes (not a blanket
DeprecationWarning, which also catches beta). Run a ratchet: the count only goes down. - Prove a migration by comparing what the model was shown with the same scripted replies on old and new code.
AgentExecutor,create_react_agentand window memory all gave the same trajectory once ported. - Know what your result shape changes to:
outputandintermediate_stepsbecome messages,agentbecomesmodel,LLMChainreturns a dict withtext, a checkpointed thread keeps what a window memory discarded. - Deprecated works through 1.x; 0.3 and 0.4 patches end in December 2026; beta and pre-1.0 packages change in minors, and saved checkpoints are the part that does not roll back.
- A stack that installs 39 packages for one needs lockfile hygiene: commit
uv.lock, install withuv sync --locked, upgrade on a branch with a cooldown, read the lockfile diff, build images from the lock. - Listed is not audited. Retired packages (community, experimental, supervisor, MCP adapters) and unaudited integrations are decisions to make deliberately.
- Lock-in lives in durable state, traces and operations, not in the syntax. Keep tools, prompts and domain rules in framework-free modules, and put the framework at the edge behind an adapter.
Terms introduced in this lesson#
| Term | One-line definition |
|---|---|
| Migration | Moving working code from an old API to its replacement without changing what the program does |
| Deprecated | Still works, but scheduled for removal, with a documented replacement and usually a warning |
| Removed | No longer present: the import or call fails on the new version |
| Bridge package | A compatibility package (here langchain-classic) that keeps old imports working while you port |
langchain-classic |
The package that holds everything LangChain 1.0 removed from langchain: legacy chains, AgentExecutor, memory classes, old retrievers, the hub |
| Sunset (package) | The maintainers' decision to stop developing and releasing a package, as with langchain-community in May 2026 |
| Archived repository | A read-only GitHub repository: no fixes, patches or merged pull requests |
| LTS (long-term support) | A release line promised bug and security fixes for a stated period; LangChain and LangGraph 1.0 are LTS |
| Beta API | A feature that is current but allowed to change in a minor release |
| Deprecation gate | A test configuration that turns the stack's deprecation warnings into failures |
| Legacy scanner | A script that inventories pre-1.0 usage in a source tree, by severity (breaks, warns, review) |
| Ratchet | A check that a count may only go down, used so that a migration cannot regress |
| Parity test | A test that feeds the same scripted model replies to old and new code and compares trajectory and what the model saw |
| Silent behaviour change | A change in defaults, shapes or ordering that raises no error but changes the output |
| Strangler pattern | Replacing a system gradually by sending new traffic to the new one while the old one finishes what it started |
| Agent factory | One function that builds every agent with the same safety defaults |
| House defaults | The limits, retries and names every agent in an application gets by default |
| Over-chaining | Splitting one task into a chain of model calls that a single call could do, multiplying cost, latency and failure points |
| Hidden state | State kept outside the graph state (a global, closure or cache), shared across users and invisible to checkpoints |
| Retry owner | The single layer designated to retry a given class of failure |
| Idempotency key | A value, derived from durable state and identical on every attempt, sent with a side effect so repeats are ignored |
| At-least-once execution | The guarantee that a retried or resumed node body runs one or more times, so side effects need deduplication |
| Lockfile diff | The comparison of two lockfiles, listing added, removed and changed packages, used as a supply-chain review |
| Cooldown (minimum release age) | A resolver setting that ignores releases newer than N days |
| Transitive dependency | A package your dependency needs that you never named |
| Ledger (dependency) | A file listing each dependency you chose on purpose, with its owner, tested range and last-checked status |
Exercises#
The first nine need no API key. Samples refer to the files built in this lesson: fakes.py, legacy_scan.py, m01_agentexecutor.py, m02_react_agent.py, m03_memory.py, m07_warnings.py, a02_hidden_state.py, a03_retry_stack.py, p01_factory.py and lock_diff.py. Answers follow the list.
-
A ratchet for the scanner. Change
legacy_scan.pyso that it takes an optional--max-breaks Nargument and exits with status 1 when the number ofbreakshits exceeds N. Run it onlegacy_appwith N set to 13 and then 12. Why is a ratchet better than "must be zero" for a migration that takes a quarter? -
Make the gate fail, then pass. Create the
pyproject.tomland test of 3.4, confirm that the deprecated test fails, then migrate the test tocreate_agentand add anignoreline for one module instead. Which of the two ways of making it green is the better habit, and when is the other acceptable? -
Port with a limit and a second turn. Take
m01_agentexecutor.pyand extend the current half so that it asks two questions on onethread_idwith anInMemorySaver, andthread_limit=2on theModelCallLimitMiddleware. What happens on the second question, and why doesrun_limitnot apply the same way? -
Port a
create_react_agentsnippet. Rewrite the following legacy call withcreate_agent, keeping the behaviour. (The namesmodel,toolsandtrim_historyexist in the surrounding code.) Say which pieces became middleware and which became arguments.python agent = create_react_agent( model, tools, prompt=lambda state: [("system", "You are a support agent.")] + state["messages"], pre_model_hook=trim_history, interrupt_before=["tools"], checkpointer=InMemorySaver(), )This snippet is illustrative: the names around it are not defined here.
-
Write the test that would have caught the memory trap. In
m03_memory.py, use the optional form("placeholder", "{history}")and write an assertion overmodel.seenthat fails. Then useMessagesPlaceholder("history")and watch it pass. Which rung of the ladder in 1.8 is this? -
A leak through a closure. Write a version of
a02_hidden_state.pyin which the leak comes from a closure in an agent factory (def make_node(): seen = []... returning a node that appends toseen) instead of a module global. Show two users colliding, then fix it with state. -
One retry owner. Starting from
a03_retry_stack.py, change the design so that exactly three real attempts happen for aConnectionErrorand exactly one for aValueError. Which layer did you keep? -
Read a real lockfile diff. In a scratch project,
uv add langchainwith an old cutoff (uv add langchain --exclude-newer 2026-05-01), copy theuv.lock, then runuv lock --upgradewith no cutoff and copy it again. Runlock_diff.pyon the pair. For each added package, runuv tree --invert --package <name>and write down who requires it and one thing you would check on its PyPI page. -
Extend the factory. Add an
extra_middleware=()argument tobuild_agentinp01_factory.pyand write a test, usingget_graph()or a recording middleware, that proves the call-limit middleware is still the first middleware even when callers pass others. Why does the order matter? -
Date and translate a tutorial (reading). Find a LangChain tutorial online that is more than a year old. Date it with the vocabulary of 08F.4, 4.5, run the scanner over its code, and write the replacement for each hit using the ledger of Part 4.
Answers
- Parse
--max-breakswithsys.argv, keep theCounter, and end withsys.exit(1 if totals["breaks"] > limit else 0). With N set to 13 the exit status is 0 and with 12 it is 1 (the sample tree has 13breaks). A ratchet lets you merge partial progress and blocks regressions, while "must be zero" either blocks all merges until the end or gets disabled. Lower N as the count falls, so the count only moves one way. - Migrating the call is the better habit: the gate exists to push the code forward. An
ignore::...:moduleline is acceptable as a temporary, visible marker for a module you have not reached yet, because the ignore list is then your to-do list. An ignore with no owner and no date is the failure mode. - With
thread_limit=2the first question uses its model calls, and when the thread's total reaches two, the second question's run ends immediately withModel call limits exceeded: thread limit (2/2)(this was run: the first question used two model calls, the tool call and the answer; a thread limit needs the checkpointer to count across calls).run_limitcounts within oneinvokeand resets for each question, so it cannot bound a long conversation: that is whatthread_limitis for. create_agent(model, tools, system_prompt="You are a support agent.", middleware=[...], checkpointer=InMemorySaver()). The prompt function issystem_prompt(a static prompt) or a@dynamic_promptif it must read state or context;pre_model_hookbecomes a@before_modelhook if it rewrites stored history, or a@wrap_model_callwithrequest.override(messages=...)if it should only change what the model sees on that call;interrupt_before=["tools"]becomesHumanInTheLoopMiddleware(interrupt_on=...)or aninterrupt()inside the sensitive tool, since static breakpoints are not the recommended way to approve.checkpointerstays an argument.- Assert that some earlier human text appears in a later call: for example
assert any("My name is Asha." in text for _, text in model.seen[1]). With the optional placeholder it fails because the memory variable is dropped; withMessagesPlaceholderit passes. This is rung 3: a graph or chain with a scripted model asserting what the model was shown. - A factory
def make_node(): seen = []that returns a node reading and appending toseengives one list per factory call, so if the compiled graph is created once (as it should be) every user shares it. Two threads collide as in the module-global case. Fix by writing the value into a state key under thethread_id, as the second half ofa02_hidden_state.pydoes. - Keep a single owner and remove the other. For example keep the node
RetryPolicy(max_attempts=3, retry_on=(ConnectionError,))and removewith_retry: aConnectionErrorgives three attempts and aValueErrorgives one, becauseretry_onrestricts what is retried. (This was run:ConnectionError -> 3 attempt(s),ValueError -> 1 attempt(s).) The other valid answer is to keepwith_retrywithretry_if_exception_typeand drop the policy; the point is that exactly one layer decides. - The expected shape is the one in 5.4: dozens of version changes, a few added packages and a couple removed. For each added name,
uv tree --invert --package <name>shows the dependency chain back to your project; on PyPI check who publishes it, the date of its first release and last release, the repository and the licence. Do not conclude that something is unsafe from the name alone: conclude that it needs the review. - Build
middleware = [ModelCallLimitMiddleware(...), *per_tool_limits, *extra_middleware, *retry]so the limit comes first, then assert that the first element of the middleware list (or the first hook node) is the limit. Order matters because cheap checks should fail the run before heavier hooks do work and because a middleware earlier in the list wraps the later ones (08F.8, 8.6). - There is no single answer. A good result lists the dates and the vocabulary that placed the tutorial (for example
LLMChainand.run()for 2023), the hits by severity, and the replacement and the lesson for each, plus a note of anything the scanner could not see (aliases, notebooks, dynamic imports).
Check yourself#
- What does "deprecated" promise in LangChain 1.x, and what does it not promise?It promises the feature keeps working through the entire 1.x series, that it is clearly marked with migration guidance, and that it gets security fixes during 1.x. It does not promise a date for 2.0, where it is removed, and it does not mean the replacement behaves identically (3.2).
- Why is there no single official guide from
AgentExecutortocreate_agent, and what are the two hops?The official 1.0 guide coverscreate_react_agenttocreate_agent, and the onlyAgentExecutorguide is an archived 0.3 notebook whose target wascreate_react_agent. SoAgentExecutortocreate_react_agent(the notebook) and then tocreate_agent(the 1.0 guide) (3.5). - In the migration run, what did the legacy executor return when
max_iterationswas hit, and what doesModelCallLimitMiddlewarereturn withexit_behavior="end"and with"error"?The executor returned the stringAgent stopped due to max iterations.as itsoutput. The middleware with"end"ends the run with anAIMessagereadingModel call limits exceeded: run limit (3/3)and the history intact; with"error"it raisesModelCallLimitExceededError(3.5). - What did the old
llm_input_messageshook ofcreate_react_agentbecome, and why is it different from abefore_modelhook?A@wrap_model_callhook that usesrequest.override(messages=...), which changes only what that one call sends. Abefore_modelhook returns a state update, so trimmed messages would replace the stored history (3.6). - Which graph nodes does a
create_agentagent with an@after_modelhook have, and which hook styles add no node?__start__,model,tools,__end__and one node<name>.after_modelfor the hook.@wrap_model_calland@dynamic_promptadd no node because they run inside themodelnode (3.6). - Why did the legacy
LLMChainmemory sample show no history when the prompt used the optional("placeholder", "{history}")form?LLMChainselects the inputs it passes withprompt.input_variables, and an optional"placeholder"is not listed, so the memory'shistoryvariable was dropped silently.MessagesPlaceholder("history")is required, so it is included (3.7). - What is the difference between a window memory and a checkpointed thread with a hook that slices the model's input?A window memory discarded older turns, and its state lived in the object. A checkpointed thread keeps every message, survives a restart, is keyed by
thread_id, and a hook only limits what is sent, so you must add summarization or retention to bound growth (3.7). - Name the three families of deprecation warning classes, and explain why the CI gate should not use a blanket
error::DeprecationWarning.LangGraphDeprecationWarning(and its...SinceV05,...V10and...V11subclasses),LangChainDeprecationWarning, andLangChainBetaWarning. All three derive fromDeprecationWarning, so a blanket rule would also fail the build on every beta API you use deliberately (3.4). - A tool that always fails sits behind
with_retry(3 attempts) inside a node with aRetryPolicy(3 attempts). How many real attempts happen, and what is the rule?Nine. Choose one owner per failure class: the SDK or model middleware for transport errors (naminghttpx.TransportErrorandhttpx2.TransportErrortoo for Google and Ollama, andon_failure="error"on the retry middleware when a fallback sits outside it), the structured-output path for malformed output, tool retry middleware for read-only tools, a nodeRetryPolicyonly for non-agent nodes, and nobody for side-effect tools without an idempotency key (1.6). - Give three forms of hidden state in an agent application and the correct place for each kind of data.
- What are the three or four things a lockfile diff of a routine upgrade showed in this lesson, and what review question do you ask about an added package?Dozens of version changes, five added packages (
httpx2,httpcore2,httpx2-jsfetch,truststore,websockets), two removed (tqdmand a terminal-colour helper), andopenaimoving from 2.33.0 to 3.51.0. For an added package ask who requires it (uv tree --invert) and whether it is what it claims to be (publisher, history, repository): herehttpx2andhttpcore2are Pydantic's continuation ofhttpx, required bylangsmithandopenai, first uploaded in May 2026 (5.4). - What does a cooldown (
exclude-newer) do, what did it do tolangchainon 18 November 2026, what must you check first, and what is its cost?It makes the resolver ignore releases newer than N days. With seven days on 18 November it heldlangchainat 1.4.10 instead of 1.5.0,langchain-coreat 1.7.7 instead of 1.8.2 andlanggraphat 1.2.20 instead of 1.2.22 (after the lower bounds thatuv addwrote were removed: a cooldown cannot choose a version older than a bound). The cost is that it also delays fixes, so urgent security upgrades are done deliberately with an absolute date (5.3). - What does "listed in the LangChain docs" not mean, and what happened to
langchain-community? - Where does lock-in to a framework really live, and what is the exit pattern for in-flight runs?
- Which end dates are close: when do 0.3 and 0.4 patches end, and what does a Deep Agents rollback look like after version 0.6?0.3 and 0.4 patches end in December 2026. After
deepagents0.6, checkpoints use a newDeltaChannelformat and the release notes say rolling back is not supported once threads have persisted (3.2).
Further resources#
-
08A.4 — Harness Engineering: the framework-neutral view of the same controls, and the build-to-delete audit for migrations. Official sources only. This lesson is a consolidation: the documentation is larger and moves faster than any lesson, and where it is more complete (the integrations, the per-package changelogs, the API references), read it. 08F.17 maps the whole documentation and shows how to keep current.
-
Migration guides: LangChain v1 migration guide, LangGraph v1 migration guide, migrate from
langgraph-supervisor, migrate fromlangchain-mcp-adapters, LangGraph backward compatibility -
Releases and policy: changelog (an RSS feed is at
/changelog/rss.xml), what is new in LangChain v1, what is new in LangGraph v1, release policy, versioning, philosophy and history -
The archived 0.x documentation (the only place old guides survive): the
v0.3branch docs, the notebookmigrate_agent.ipynb, the memory migration guide and the 0.3 release notes -
The legacy package:
langchain-classicon PyPI, its API reference and theAgentExecutorreference -
Patterns and middleware: built-in middleware, multi-agent patterns, LangChain products and layers, Deep Agents versus the Claude Agent SDK
-
Operating and supply chain: Agent Server changelog, self-hosted release versions, CI/CD pipeline example, the integrations catalogue, the
langchain-communitysunset notice,uvdocumentation -
Repositories:
langchain-ai/langchain,langchain-ai/langgraph,langchain-ai/langgraph-supervisor-py(archived),langchain-ai/langgraph-swarm-py -
In this course: 08F.1, Part 5 and Part 7 for the cross-framework view; 08F.4, Part 4 for the legacy vocabulary; 08F.8 for agents and middleware; 08F.10 to 08F.13 for graphs, persistence, interrupts and multi-agent; 08F.14 and 11A.5 for streaming, tracing and deployment; 03.11, 13.9 and 12.7 for dependency hygiene and the supply chain; Module 10A for evaluating before and after a migration
← 08F.14: The Functional API and Streaming | Module 08F overview | 08F.16: Low-Code Agent Platforms: n8n and Dify (awareness) →