From eb5082c59edcf18430f450f008957aeb461ba4d2 Mon Sep 17 00:00:00 2001 From: Mackenzie Zastrow Date: Tue, 4 Nov 2025 16:09:01 -0500 Subject: [PATCH] fix: Handle "prompt is too long" from Anthropic PR#1078 mentioned that context overflows were not handled, but I wasn't able to reproduce using the code changes in it. However, in testing (using @dea's suggested test) I was able to reproduce and consistently got a "prompt is too long:" error --- src/strands/models/anthropic.py | 1 + tests_integ/models/test_model_anthropic.py | 30 ++++++++++++++++++++++ 2 files changed, 31 insertions(+) diff --git a/src/strands/models/anthropic.py b/src/strands/models/anthropic.py index 48351da19..68b234729 100644 --- a/src/strands/models/anthropic.py +++ b/src/strands/models/anthropic.py @@ -39,6 +39,7 @@ class AnthropicModel(Model): } OVERFLOW_MESSAGES = { + "prompt is too long:", "input is too long", "input length exceeds context window", "input and output tokens exceed your context limit", diff --git a/tests_integ/models/test_model_anthropic.py b/tests_integ/models/test_model_anthropic.py index 62a95d06d..9a0d19dff 100644 --- a/tests_integ/models/test_model_anthropic.py +++ b/tests_integ/models/test_model_anthropic.py @@ -5,7 +5,10 @@ import strands from strands import Agent +from strands.agent import NullConversationManager from strands.models.anthropic import AnthropicModel +from strands.types.content import ContentBlock, Message +from strands.types.exceptions import ContextWindowOverflowException """ These tests only run if we have the anthropic api key @@ -152,3 +155,30 @@ def test_structured_output_multi_modal_input(agent, yellow_img, yellow_color): tru_color = agent.structured_output(type(yellow_color), content) exp_color = yellow_color assert tru_color == exp_color + + +@pytest.mark.asyncio +def test_input_and_max_tokens_exceed_context_limit(): + """Test that triggers 'input length and max_tokens exceed context limit' error.""" + + # Note that this test is written specifically in a style that allows us to swap out conversation_manager and + # verify behavior + + model = AnthropicModel( + model_id="claude-sonnet-4-20250514", + max_tokens=64000, + ) + + large_message = "This is a very long text. " * 10000 + + messages = [ + Message(role="user", content=[ContentBlock(text=large_message)]), + Message(role="assistant", content=[ContentBlock(text=large_message)]), + Message(role="user", content=[ContentBlock(text=large_message)]), + ] + + # NullConversationManager will propagate ContextWindowOverflowException directly instead of handling it + agent = Agent(model=model, conversation_manager=NullConversationManager()) + + with pytest.raises(ContextWindowOverflowException): + agent(messages)