Skip to content

The agent engineering platform.

feat(anthropic): add async implementation to middleware (#33506)

Eugene Yurtseva39132787c31
diff --git a/libs/partners/anthropic/langchain_anthropic/middleware/prompt_caching.py b/libs/partners/anthropic/langchain_anthropic/middleware/prompt_caching.py
index 4f4d91b740..5fdd0ef79f 100644
--- a/libs/partners/anthropic/langchain_anthropic/middleware/prompt_caching.py
+++ b/libs/partners/anthropic/langchain_anthropic/middleware/prompt_caching.py
@@ -64,12 +64,18 @@ class AnthropicPromptCachingMiddleware(AgentMiddleware):
self.min_messages_to_cache = min_messages_to_cache
self.unsupported_model_behavior = unsupported_model_behavior
- def wrap_model_call(
- self,
- request: ModelRequest,
- handler: Callable[[ModelRequest], ModelResponse],
- ) -> ModelCallResult:
- """Modify the model request to add cache control blocks."""
+ def _should_apply_caching(self, request: ModelRequest) -> bool:
+ """Check if caching should be applied to the request.
+
+ Args:
+ request: The model request to check.
+
+ Returns:
+ True if caching should be applied, False otherwise.
+
+ Raises:
+ ValueError: If model is unsupported and behavior is set to "raise".
+ """
if not isinstance(request.model, ChatAnthropic):
msg = (
"AnthropicPromptCachingMiddleware caching middleware only supports "
@@ -79,18 +85,41 @@ class AnthropicPromptCachingMiddleware(AgentMiddleware):
raise ValueError(msg)
if self.unsupported_model_behavior == "warn":
warn(msg, stacklevel=3)
- return handler(request)
+ return False
messages_count = (
len(request.messages) + 1
if request.system_prompt
else len(request.messages)
)
- if messages_count < self.min_messages_to_cache:
- return handler(request)
+ return messages_count >= self.min_messages_to_cache
+ def _apply_cache_control(self, request: ModelRequest) -> None:
+ """Apply cache control settings to the request.
+
+ Args:
+ request: The model request to modify.
+ """
request.model_settings["cache_control"] = {"type": self.type, "ttl": self.ttl}
+ def wrap_model_call(
+ self,
+ request: ModelRequest,
+ handler: Callable[[ModelRequest], ModelResponse],
+ ) -> ModelCallResult:
+ """Modify the model request to add cache control blocks.
+
+ Args:
+ request: The model request to potentially modify.
+ handler: The handler to execute the model request.
+
+ Returns:
+ The model response from the handler.
+ """
+ if not self._should_apply_caching(request):
+ return handler(request)
+
+ self._apply_cache_control(request)
return handler(request)
async def awrap_model_call(
@@ -98,26 +127,17 @@ class AnthropicPromptCachingMiddleware(AgentMiddleware):
request: ModelRequest,
handler: Callable[[ModelRequest], Awaitable[ModelResponse]],
) -> ModelCallResult:
- """Modify the model request to add cache control blocks (async version)."""
- if not isinstance(request.model, ChatAnthropic):
- msg = (
- "AnthropicPromptCachingMiddleware caching middleware only supports "
- f"Anthropic models, not instances of {type(request.model)}"
- )
- if self.unsupported_model_behavior == "raise":
- raise ValueError(msg)
- if self.unsupported_model_behavior == "warn":
- warn(msg, stacklevel=3)
- return await handler(request)
+ """Modify the model request to add cache control blocks (async version).
- messages_count = (
- len(request.messages) + 1
- if request.system_prompt
- else len(request.messages)
- )
- if messages_count < self.min_messages_to_cache:
- return await handler(request)
+ Args:
+ request: The model request to potentially modify.
+ handler: The async handler to execute the model request.
- request.model_settings["cache_control"] = {"type": self.type, "ttl": self.ttl}
+ Returns:
+ The model response from the handler.
+ """
+ if not self._should_apply_caching(request):
+ return await handler(request)
+ self._apply_cache_control(request)
return await handler(request)
diff --git a/libs/partners/anthropic/tests/unit_tests/middleware/test_prompt_caching.py b/libs/partners/anthropic/tests/unit_tests/middleware/test_prompt_caching.py
index 170a1a4e0d..e06ebebaf5 100644
--- a/libs/partners/anthropic/tests/unit_tests/middleware/test_prompt_caching.py
+++ b/libs/partners/anthropic/tests/unit_tests/middleware/test_prompt_caching.py
@@ -244,3 +244,68 @@ async def test_anthropic_prompt_caching_middleware_async_min_messages() -> None:
assert isinstance(result, ModelResponse)
# Cache control should NOT be added when message count is below minimum
assert fake_request.model_settings == {}
+
+
+async def test_anthropic_prompt_caching_middleware_async_with_system_prompt() -> None:
+ """Test async path counts system prompt in message count."""
+ middleware = AnthropicPromptCachingMiddleware(
+ type="ephemeral", ttl="1h", min_messages_to_cache=3
+ )
+
+ # Create a mock ChatAnthropic instance
+ mock_chat_anthropic = MagicMock(spec=ChatAnthropic)
+
+ # Test with system prompt: 2 messages + 1 system = 3 total (meets minimum)
+ fake_request = ModelRequest(
+ model=mock_chat_anthropic,
+ messages=[HumanMessage("Hello"), HumanMessage("World")],
+ system_prompt="You are a helpful assistant",
+ tool_choice=None,
+ tools=[],
+ response_format=None,
+ state={"messages": [HumanMessage("Hello"), HumanMessage("World")]},
+ runtime=cast(Runtime, object()),
+ model_settings={},
+ )
+
+ async def mock_handler(req: ModelRequest) -> ModelResponse:
+ return ModelResponse(result=[AIMessage(content="mock response")])
+
+ result = await middleware.awrap_model_call(fake_request, mock_handler)
+ assert isinstance(result, ModelResponse)
+ # Cache control should be added when system prompt pushes count to minimum
+ assert fake_request.model_settings == {
+ "cache_control": {"type": "ephemeral", "ttl": "1h"}
+ }
+
+
+async def test_anthropic_prompt_caching_middleware_async_default_values() -> None:
+ """Test async path with default middleware initialization."""
+ # Test with default values (min_messages_to_cache=0)
+ middleware = AnthropicPromptCachingMiddleware()
+
+ # Create a mock ChatAnthropic instance
+ mock_chat_anthropic = MagicMock(spec=ChatAnthropic)
+
+ # Single message should trigger caching with default settings
+ fake_request = ModelRequest(
+ model=mock_chat_anthropic,
+ messages=[HumanMessage("Hello")],
+ system_prompt=None,
+ tool_choice=None,
+ tools=[],
+ response_format=None,
+ state={"messages": [HumanMessage("Hello")]},
+ runtime=cast(Runtime, object()),
+ model_settings={},
+ )
+
+ async def mock_handler(req: ModelRequest) -> ModelResponse:
+ return ModelResponse(result=[AIMessage(content="mock response")])
+
+ result = await middleware.awrap_model_call(fake_request, mock_handler)
+ assert isinstance(result, ModelResponse)
+ # Check that model_settings were added with default values
+ assert fake_request.model_settings == {
+ "cache_control": {"type": "ephemeral", "ttl": "5m"}
+ }
diff --git a/libs/partners/anthropic/uv.lock b/libs/partners/anthropic/uv.lock
index 42f9c10c28..baf527916b 100644
--- a/libs/partners/anthropic/uv.lock
+++ b/libs/partners/anthropic/uv.lock
@@ -274,7 +274,7 @@ name = "exceptiongroup"
version = "1.3.0"
source = { registry = "https://pypi.org/simple" }
dependencies = [
- { name = "typing-extensions", marker = "python_full_version < '3.13'" },
+ { name = "typing-extensions", marker = "python_full_version < '3.11'" },
]
sdist = { url = "https://files.pythonhosted.org/packages/0b/9f/a65090624ecf468cdca03533906e7c69ed7588582240cfe7cc9e770b50eb/exceptiongroup-1.3.0.tar.gz", hash = "sha256:b241f5885f560bc56a59ee63ca4c6a8bfa46ae4ad651af316d4e81817bb9fd88", size = 29749, upload-time = "2025-05-10T17:42:51.123Z" }
wheels = [
@@ -597,7 +597,7 @@ typing = [
[[package]]
name = "langchain-core"
-version = "1.0.0a8"
+version = "1.0.0rc1"
source = { editable = "../../core" }
dependencies = [
{ name = "jsonpatch" },