From 212cf67980befa0b5b99900e9ad3f271e5694e64 Mon Sep 17 00:00:00 2001 From: Alex Castillo Date: Wed, 18 Nov 2026 22:27:48 -0400 Subject: [PATCH] fix(py/anthropic): keep cache_control on system prompt parts _extract_system flattened system text into a plain string and dropped metadata.cache_control, so prompt caching never applied to system parts. When any system text part carries cache_control, send text blocks (with the marker) instead; the JSON fallback instruction becomes a trailing block. Without cache_control the string form is unchanged. Fixes #149 --- .../src/genkit_anthropic/_models.py | 26 ++++++++++++++++--- .../tests/anthropic_generate_test.py | 21 +++++++++++++++ .../tests/anthropic_models_test.py | 20 ++++++++++++++ 3 files changed, 63 insertions(+), 4 deletions(-) diff --git a/packages/genkit-anthropic/src/genkit_anthropic/_models.py b/packages/genkit-anthropic/src/genkit_anthropic/_models.py index 8dec656c..6799b535 100644 --- a/packages/genkit-anthropic/src/genkit_anthropic/_models.py +++ b/packages/genkit-anthropic/src/genkit_anthropic/_models.py @@ -558,7 +558,10 @@ def _build_params( if request.output_schema is not None: schema_str = json.dumps(request.output_schema, indent=2) instruction += f'\n\nFollow this JSON schema:\n{schema_str}' - system = (system or '') + instruction + if isinstance(system, list): + system = [*system, {'type': 'text', 'text': instruction.lstrip()}] + else: + system = (system or '') + instruction if system: params['system'] = system @@ -704,12 +707,27 @@ async def _generate_streaming( return cast(AnthropicMessage, await stream.get_final_message()) - def _extract_system(self, messages: list[Message]) -> str | None: + def _extract_system(self, messages: list[Message]) -> str | list[dict[str, Any]] | None: """Extract system prompt from messages. - Text from every system message is kept, in order, joined by blank lines. - System messages with no text are skipped. + Text from every system message is kept, in order. System messages with + no text are skipped. Without ``cache_control`` metadata the text is + joined by blank lines into one string. If any text part carries + ``cache_control``, a list of text blocks is returned instead, so the + marker reaches the API. """ + parts = [part for msg in messages if msg.role == Role.SYSTEM for part in msg.content if part.text is not None] + if any(get_cache_control(part) for part in parts): + blocks: list[dict[str, Any]] = [] + for part in parts: + if not part.text: + continue + block: dict[str, Any] = {'type': 'text', 'text': part.text} + cache_meta = get_cache_control(part) + if cache_meta: + block['cache_control'] = cache_meta + blocks.append(block) + return blocks or None system_texts = [] for msg in messages: if msg.role == Role.SYSTEM: diff --git a/packages/genkit-anthropic/tests/anthropic_generate_test.py b/packages/genkit-anthropic/tests/anthropic_generate_test.py index 63e34cec..056aaf1e 100644 --- a/packages/genkit-anthropic/tests/anthropic_generate_test.py +++ b/packages/genkit-anthropic/tests/anthropic_generate_test.py @@ -879,3 +879,24 @@ async def test_anthropic_client_options_reach_the_client() -> None: await ai.generate(model=MODEL, prompt='hi') assert api.requests[-1].headers['x-team'] == 'search' + + +@pytest.mark.asyncio +async def test_generate_claude_sends_system_cache_control() -> None: + """A cached system part is sent as a block with cache_control, not flattened.""" + api = FakeClaudeApi() + ai = _genkit(api) + cache = {'type': 'ephemeral'} + + await ai.generate( + model=MODEL, + messages=[ + Message( + role=Role.SYSTEM, + content=[Part.from_text('Long reference.', metadata={'cache_control': cache})], + ), + ], + prompt='Hi', + ) + + assert api.body()['system'] == [{'type': 'text', 'text': 'Long reference.', 'cache_control': cache}] diff --git a/packages/genkit-anthropic/tests/anthropic_models_test.py b/packages/genkit-anthropic/tests/anthropic_models_test.py index 1d36eef6..7d61b2ab 100644 --- a/packages/genkit-anthropic/tests/anthropic_models_test.py +++ b/packages/genkit-anthropic/tests/anthropic_models_test.py @@ -220,6 +220,26 @@ def test_extract_system() -> None: assert system == 'You are helpful.' +def test_extract_system_keeps_cache_control_on_system_parts() -> None: + """cache_control on a system part reaches the API as a text block.""" + mock_client = MagicMock() + model = AnthropicModel(model_name='claude-sonnet-4', client=mock_client) + cache = {'type': 'ephemeral'} + + messages = [ + Message( + role=Role.SYSTEM, + content=[Part.from_text('Long reference.', metadata={'cache_control': cache}), Part.from_text('Be brief.')], + ), + Message(role=Role.USER, content=[Part.from_text('Hello')]), + ] + + assert model._extract_system(messages) == [ + {'type': 'text', 'text': 'Long reference.', 'cache_control': cache}, + {'type': 'text', 'text': 'Be brief.'}, + ] + + def test_extract_system_keeps_all_system_messages() -> None: """Every system message is sent, not only the first.""" mock_client = MagicMock()