Example agent built with LangChain’s native create_agent (the recommended modern pattern).
A create_agent tool-calling loop composed with middleware. It reproduces the toolkit’s custom
create_react_agent behavior using only public LangChain middleware:
ContextEditingMiddleware— bound the context window non-destructively: once tokens pass the trigger, clear OLD tool outputs (keeping the most recent), reclaiming tokens while keeping the conversation text. Chosen overSummarizationMiddleware(which destructively replaces history with a summary).ImmediateGenerationMiddleware— the graceful loop bound: near the recursion limit, drop tools and ask the model to answer from what it already gathered, instead of stalling or erroring (ports the custom router’simmediate_generation). This is the loop bound — a separate hard tool-call cap is intentionally omitted, since it would end abruptly and preempt this graceful synthesis.ClearIntermediateToolCallsMiddleware— token reduction: keep only the latest result per tool from earlier turns (configurable via theCLEAR_INTERMEDIATE_TOOL_CALLS*settings).SanitizeHistoryMiddleware— repair broken tool-call/result pairing (interrupted runs, post trim/clear orphans).ToolRetryMiddleware— resilience: retry a failed tool call with backoff, and after retries are exhausted return the error as a ToolMessage so a single flaky tool (e.g. a search timeout) doesn’t abort the whole run.
Compare with blueprints/react: the same agent built with the toolkit’s create_react_agent.