Skip to content

The agent engineering platform.

fix(langchain): (SummarizationMiddleware) retry summary step on context overflow (#41159)

ccurmee7ca68b92062
diff --git a/libs/langchain_v1/langchain/agents/middleware/_retry.py b/libs/langchain_v1/langchain/agents/middleware/_retry.py
index c384e929bd..e24592756a 100644
--- a/libs/langchain_v1/langchain/agents/middleware/_retry.py
+++ b/libs/langchain_v1/langchain/agents/middleware/_retry.py
@@ -67,8 +67,10 @@ def validate_retry_params(
raise ValueError(msg)
-def default_retry_on(exc: Exception) -> bool:
+def default_retry_on(exc: BaseException) -> bool:
"""Return whether an exception should be retried by default."""
+ if not isinstance(exc, Exception):
+ return False
if isinstance(exc, ModelError):
return exc.is_retryable
return True
diff --git a/libs/langchain_v1/langchain/agents/middleware/summarization.py b/libs/langchain_v1/langchain/agents/middleware/summarization.py
index 407194087b..585de9ba95 100644
--- a/libs/langchain_v1/langchain/agents/middleware/summarization.py
+++ b/libs/langchain_v1/langchain/agents/middleware/summarization.py
@@ -7,6 +7,7 @@ from collections.abc import Callable, Iterable, Mapping
from functools import partial
from typing import Any, Literal, TypedDict, cast
+from langchain_core.exceptions import ContextOverflowError
from langchain_core.messages import (
AIMessage,
AnyMessage,
@@ -20,12 +21,14 @@ from langchain_core.messages.utils import (
get_buffer_string,
trim_messages,
)
+from langchain_core.runnables import RunnableConfig
from langgraph.graph.message import (
REMOVE_ALL_MESSAGES,
)
from langgraph.runtime import Runtime
from typing_extensions import override
+from langchain.agents.middleware._retry import default_retry_on
from langchain.agents.middleware.internal_call_transformer import (
InternalCallTransformer,
internal_call_metadata,
@@ -113,6 +116,11 @@ _LS_PROVIDER_ALIASES: dict[str, frozenset[str]] = {
}
+def _summary_config() -> RunnableConfig:
+ """Config for summary model calls."""
+ return {"metadata": {"lc_source": "summarization", **internal_call_metadata()}}
+
+
def _provider_matches(message_provider: str, model_ls_provider: str | None) -> bool:
if model_ls_provider is None:
return False
@@ -236,10 +244,12 @@ class SummarizationMiddleware(AgentMiddleware[AgentState[ResponseT], ContextT, R
messages when a threshold is reached, preserving recent messages and maintaining
context continuity by ensuring AI/Tool message pairs remain together.
- Transient summary-generation errors (rate limits, timeouts) are retried
- in-process, up to 3 attempts total, via `Runnable.with_retry`. If a summary call
- still fails after those attempts, the underlying error propagates rather than
- fabricating a summary.
+ Summary-generation errors are retried in-process, up to 3 attempts total, via
+ `Runnable.with_retry`, unless the error is a `ModelError` marked non-retryable
+ (e.g. authentication or invalid request errors). If the summary prompt exceeds
+ the model's context window (`ContextOverflowError`), the call is retried once with
+ the middle of the history cut out. If a summary call still fails, the
+ underlying error propagates rather than fabricating a summary.
"""
transformers = (InternalCallTransformer,)
@@ -354,9 +364,8 @@ class SummarizationMiddleware(AgentMiddleware[AgentState[ResponseT], ContextT, R
model = init_chat_model(model)
self.model = model
- # Retry transient errors (rate limits, timeouts) in-process, up to 3 attempts
- # total, before giving up. See `Runnable.with_retry`.
- self._summary_model = self.model.with_retry()
+ # Retry up to 3 attempts total, skipping errors marked non-retryable.
+ self._summary_model = self.model.with_retry(retry_if_exception_type=default_retry_on)
self.trigger: ContextSize | TriggerClause | list[ContextSize | TriggerClause] | None = (
self._copy_trigger(trigger)
@@ -849,14 +858,14 @@ class SummarizationMiddleware(AgentMiddleware[AgentState[ResponseT], ContextT, R
if not trimmed_messages:
return "Previous conversation was too long to summarize."
- # Serialize as XML so URL-based multimodal blocks remain visible in the summary
- # prompt while excluding raw message metadata from the token budget.
- formatted_messages = get_buffer_string(trimmed_messages, format="xml")
-
- response = self._summary_model.invoke(
- self.summary_prompt.format(messages=formatted_messages).rstrip(),
- config={"metadata": {"lc_source": "summarization", **internal_call_metadata()}},
- )
+ prompt = self._format_summary_prompt(trimmed_messages)
+ try:
+ response = self._summary_model.invoke(prompt, config=_summary_config())
+ except ContextOverflowError:
+ retry_prompt = self._overflow_retry_prompt(trimmed_messages)
+ if retry_prompt is None:
+ raise
+ response = self._summary_model.invoke(retry_prompt, config=_summary_config())
return response.text.strip()
async def _acreate_summary(self, messages_to_summarize: list[AnyMessage]) -> str:
@@ -879,15 +888,55 @@ class SummarizationMiddleware(AgentMiddleware[AgentState[ResponseT], ContextT, R
if not trimmed_messages:
return "Previous conversation was too long to summarize."
+ prompt = self._format_summary_prompt(trimmed_messages)
+ try:
+ response = await self._summary_model.ainvoke(prompt, config=_summary_config())
+ except ContextOverflowError:
+ retry_prompt = self._overflow_retry_prompt(trimmed_messages)
+ if retry_prompt is None:
+ raise
+ response = await self._summary_model.ainvoke(retry_prompt, config=_summary_config())
+ return response.text.strip()
+
+ def _format_summary_prompt(self, messages: list[AnyMessage]) -> str:
+ """Render the summary prompt for the given messages."""
# Serialize as XML so URL-based multimodal blocks remain visible in the summary
# prompt while excluding raw message metadata from the token budget.
- formatted_messages = get_buffer_string(trimmed_messages, format="xml")
+ formatted_messages = get_buffer_string(messages, format="xml")
+ return self.summary_prompt.format(messages=formatted_messages).rstrip()
+
+ def _overflow_retry_prompt(self, messages: list[AnyMessage]) -> str | None:
+ """Build a smaller summary prompt after the summary call overflowed.
- response = await self._summary_model.ainvoke(
- self.summary_prompt.format(messages=formatted_messages).rstrip(),
- config={"metadata": {"lc_source": "summarization", **internal_call_metadata()}},
+ Cuts the middle out of the formatted history, keeping its start (where the
+ objective is usually stated) and its most recent part, within half of its
+ token count and 40% of the model's `max_input_tokens` when known.
+
+ Returns:
+ The retry prompt, or `None` if nothing fits the budget.
+ """
+ formatted = get_buffer_string(messages, format="xml")
+ tokens = self._partial_token_counter([HumanMessage(content=formatted)])
+ budget = tokens // 2
+ if (max_input_tokens := self._get_profile_limits()) is not None:
+ # 40% rather than half absorbs up to 1.25x usage-metadata scaling.
+ budget = min(budget, max_input_tokens * 2 // 5)
+ keep_chars = len(formatted) * budget // max(tokens, 1)
+ if keep_chars <= 0:
+ return None
+ head_chars = keep_chars // 4
+ tail_chars = keep_chars - head_chars
+ logger.debug(
+ "Summary prompt exceeded the model's context window; retrying with "
+ "~%d of ~%d history tokens.",
+ budget,
+ tokens,
)
- return response.text.strip()
+ truncated = (
+ f"{formatted[:head_chars]}\n\n[... middle of conversation omitted ...]\n\n"
+ f"{formatted[-tail_chars:]}"
+ )
+ return self.summary_prompt.format(messages=truncated).rstrip()
def _trim_messages_for_summary(self, messages: list[AnyMessage]) -> list[AnyMessage]:
"""Trim messages to fit within summary generation limits."""
diff --git a/libs/langchain_v1/pyproject.toml b/libs/langchain_v1/pyproject.toml
index 83fb05b2eb..c8bed6e7c9 100644
--- a/libs/langchain_v1/pyproject.toml
+++ b/libs/langchain_v1/pyproject.toml
@@ -24,7 +24,7 @@ classifiers = [
version = "1.4.3"
requires-python = ">=3.10.0,<4.0.0"
dependencies = [
- "langchain-core>=1.6.3,<2.0.0",
+ "langchain-core>=1.6.9,<2.0.0",
"langgraph>=1.2.11,<1.3.0",
"pydantic>=2.7.4,<3.0.0",
]
diff --git a/libs/langchain_v1/tests/unit_tests/agents/middleware/implementations/test_summarization.py b/libs/langchain_v1/tests/unit_tests/agents/middleware/implementations/test_summarization.py
index 1c6a34579f..7315ba6a0d 100644
--- a/libs/langchain_v1/tests/unit_tests/agents/middleware/implementations/test_summarization.py
+++ b/libs/langchain_v1/tests/unit_tests/agents/middleware/implementations/test_summarization.py
@@ -5,6 +5,7 @@ from unittest.mock import patch
import pytest
from langchain_core.callbacks import AsyncCallbackManagerForLLMRun, CallbackManagerForLLMRun
+from langchain_core.exceptions import ContextOverflowError, ModelAuthenticationError
from langchain_core.language_models import ModelProfile
from langchain_core.language_models.base import (
LangSmithParams,
@@ -360,6 +361,97 @@ async def test_acreate_summary_raises_on_failure() -> None:
await middleware._acreate_summary([HumanMessage(content="hi")])
+class _OverflowingModel(BaseChatModel):
+ """Raises `ContextOverflowError` for prompts longer than `max_chars`."""
+
+ max_chars: int
+ prompts: list[str] = Field(default_factory=list)
+
+ @override
+ def _generate(
+ self,
+ messages: list[BaseMessage],
+ stop: list[str] | None = None,
+ run_manager: CallbackManagerForLLMRun | None = None,
+ **kwargs: Any,
+ ) -> ChatResult:
+ prompt = messages[-1].text
+ self.prompts.append(prompt)
+ if len(prompt) > self.max_chars:
+ msg = "prompt is too long"
+ raise ContextOverflowError(msg)
+ return ChatResult(generations=[ChatGeneration(message=AIMessage(content="Summary."))])
+
+ @property
+ def _llm_type(self) -> str:
+ return "mock"
+
+
+def _long_history() -> list[AnyMessage]:
+ return [HumanMessage(content=f"turn-{i} " * 500) for i in range(10)]
+
+
+def test_create_summary_does_not_retry_non_retryable_errors() -> None:
+ class AuthFailingModel(BaseChatModel):
+ attempts: int = 0
+
+ @override
+ def _generate(
+ self,
+ messages: list[BaseMessage],
+ stop: list[str] | None = None,
+ run_manager: CallbackManagerForLLMRun | None = None,
+ **kwargs: Any,
+ ) -> ChatResult:
+ self.attempts += 1
+ msg = "invalid api key"
+ raise ModelAuthenticationError(msg)
+
+ @property
+ def _llm_type(self) -> str:
+ return "mock"
+
+ model = AuthFailingModel()
+ middleware = SummarizationMiddleware(model=model)
+ middleware._summary_model.wait_exponential_jitter = False # type: ignore[attr-defined]
+
+ with pytest.raises(ModelAuthenticationError):
+ middleware._create_summary([HumanMessage(content="hi")])
+ assert model.attempts == 1
+
+
+def test_create_summary_recovers_from_context_overflow() -> None:
+ model = _OverflowingModel(max_chars=25_000)
+ middleware = SummarizationMiddleware(model=model, trim_tokens_to_summarize=None)
+
+ assert middleware._create_summary(_long_history()) == "Summary."
+ assert len(model.prompts) == 2
+ retry_prompt = model.prompts[1]
+ assert "turn-0" in retry_prompt
+ assert "turn-5" not in retry_prompt
+ assert "turn-9" in retry_prompt
+
+
+async def test_acreate_summary_recovers_from_context_overflow() -> None:
+ model = _OverflowingModel(max_chars=25_000)
+ middleware = SummarizationMiddleware(model=model, trim_tokens_to_summarize=None)
+
+ assert await middleware._acreate_summary(_long_history()) == "Summary."
+ assert len(model.prompts) == 2
+ assert "turn-0" in model.prompts[1]
+ assert "turn-5" not in model.prompts[1]
+ assert "turn-9" in model.prompts[1]
+
+
+def test_create_summary_raises_on_persistent_context_overflow() -> None:
+ model = _OverflowingModel(max_chars=10)
+ middleware = SummarizationMiddleware(model=model, trim_tokens_to_summarize=None)
+
+ with pytest.raises(ContextOverflowError):
+ middleware._create_summary(_long_history())
+ assert len(model.prompts) == 2
+
+
def test_summarization_middleware_before_model_raises_on_summary_failure() -> None:
"""A failed summary generation must raise, never fabricate a summary or delete history."""
middleware = SummarizationMiddleware(
diff --git a/libs/langchain_v1/uv.lock b/libs/langchain_v1/uv.lock
index 16d02f6e4a..6e966f3811 100644
--- a/libs/langchain_v1/uv.lock
+++ b/libs/langchain_v1/uv.lock
@@ -31,7 +31,7 @@ resolution-markers = [
"python_full_version < '3.11' and platform_python_implementation == 'PyPy'",
]
dependencies = [
- { name = "caio", version = "0.9.25", source = { registry = "https://pypi.org/simple" } },
+ { name = "caio", version = "0.9.25", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" },
]
sdist = { url = "https://files.pythonhosted.org/packages/67/e2/d7cb819de8df6b5c1968a2756c3cb4122d4fa2b8fc768b53b7c9e5edb646/aiofile-3.9.0.tar.gz", hash = "sha256:e5ad718bb148b265b6df1b3752c4d1d83024b93da9bd599df74b9d9ffcf7919b", size = 17943, upload-time = "2024-10-08T10:39:35.846Z" }
wheels = [
@@ -55,7 +55,7 @@ resolution-markers = [
"python_full_version == '3.11.*' and platform_python_implementation == 'PyPy'",
]
dependencies = [
- { name = "caio", version = "0.12.2", source = { registry = "https://pypi.org/simple" } },
+ { name = "caio", version = "0.12.2", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" },
]
sdist = { url = "https://files.pythonhosted.org/packages/14/31/edb06aabd8f8f0b56d659f30800795f40b93cba96be946ce179f6931e3a5/aiofile-3.12.3.tar.gz", hash = "sha256:caa6aa746b5e47e2165f7abd741b6415e49cf4d44fddc0f61844612cc3924d41", size = 21600, upload-time = "2026-08-04T22:59:27.171Z" }
wheels = [
@@ -1532,12 +1532,12 @@ resolution-markers = [
"python_full_version < '3.11' and platform_python_implementation == 'PyPy'",
]
dependencies = [
- { name = "google-api-core" },
- { name = "google-auth" },
- { name = "google-cloud-core" },
- { name = "google-crc32c" },
- { name = "google-resumable-media" },
- { name = "requests" },
+ { name = "google-api-core", marker = "python_full_version < '3.13'" },
+ { name = "google-auth", marker = "python_full_version < '3.13'" },
+ { name = "google-cloud-core", marker = "python_full_version < '3.13'" },
+ { name = "google-crc32c", marker = "python_full_version < '3.13'" },
+ { name = "google-resumable-media", marker = "python_full_version < '3.13'" },
+ { name = "requests", marker = "python_full_version < '3.13'" },
]
sdist = { url = "https://files.pythonhosted.org/packages/6d/98/c0c6d10f893509585c755a6567689e914df3501ae269f46b0d67d7e7c70a/google_cloud_storage-3.5.0.tar.gz", hash = "sha256:10b89e1d1693114b3e0ca921bdd28c5418701fd092e39081bb77e5cee0851ab7", size = 17242207, upload-time = "2025-11-05T12:41:02.715Z" }
wheels = [
@@ -1557,12 +1557,12 @@ resolution-markers = [
"python_full_version == '3.13.*' and platform_python_implementation != 'PyPy'",
]
dependencies = [
- { name = "google-api-core" },
- { name = "google-auth" },
- { name = "google-cloud-core" },
- { name = "google-crc32c" },
- { name = "google-resumable-media" },
- { name = "requests" },
+ { name = "google-api-core", marker = "python_full_version >= '3.13'" },
+ { name = "google-auth", marker = "python_full_version >= '3.13'" },
+ { name = "google-cloud-core", marker = "python_full_version >= '3.13'" },
+ { name = "google-crc32c", marker = "python_full_version >= '3.13'" },
+ { name = "google-resumable-media", marker = "python_full_version >= '3.13'" },
+ { name = "requests", marker = "python_full_version >= '3.13'" },
]
sdist = { url = "https://files.pythonhosted.org/packages/ce/7e/73bb7512df1d1aad6ce3f9aed847cd40e0cd400ba4a85d86ab8eb412e9cc/google_cloud_storage-3.13.1.tar.gz", hash = "sha256:a80bf8cac2794808aa61c50c5f769ecbbe2d10331bacd0d69d30e59b14b346b2", size = 17341051, upload-time = "2026-08-06T06:24:42.229Z" }
wheels = [
@@ -2001,7 +2001,7 @@ name = "importlib-metadata"
version = "9.0.0"
source = { registry = "https://pypi.org/simple" }
dependencies = [
- { name = "zipp" },
+ { name = "zipp", marker = "python_full_version < '3.12'" },
]
sdist = { url = "https://files.pythonhosted.org/packages/a9/01/15bb152d77b21318514a96f43af312635eb2500c96b55398d020c93d86ea/importlib_metadata-9.0.0.tar.gz", hash = "sha256:a4f57ab599e6a2e3016d7595cfd72eb4661a5106e787a95bcc90c7105b831efc", size = 56405, upload-time = "2026-03-20T06:42:56.999Z" }
wheels = [
@@ -2581,7 +2581,7 @@ wheels = [
[[package]]
name = "langchain-core"
-version = "1.6.7"
+version = "1.6.8"
source = { editable = "../core" }
dependencies = [
{ name = "httpx" },
@@ -2785,7 +2785,7 @@ wheels = [
[[package]]
name = "langchain-openai"
-version = "1.6.7"
+version = "1.7.0"
source = { editable = "../partners/openai" }
dependencies = [
{ name = "certifi" },