Skip to content

py/anthropic: cache_control on system parts is dropped #149

Done

Description

@huangjeff5

Problem

cache_control on a system part never reaches Anthropic. The request still returns 200, so nothing looks wrong, but every turn pays full input tokens for the system prompt.

# 1. Cache a large allergen policy; add a per-table rule each turn
res = await ai.generate(
    model=Anthropic.claude('claude-sonnet-4-6'),
    system=[Part.from_text(ALLERGEN_MANUAL, metadata={'cache_control': {'type': 'ephemeral'}})],
    messages=[
        Message(role=Role.SYSTEM, content=[Part.from_text('Table 4 avoids peanuts.')]),
        Message(role=Role.USER, content=[Part.from_text('Suggest an appetizer.')]),
    ],
)

# 2. What goes out on POST /v1/messages today
# => "system": "<ALLERGEN_MANUAL>\n\nTable 4 avoids peanuts."
#    cache_control is gone; usage shows no cache writes or reads

AnthropicModel says it supports "Prompt caching via cache_control metadata on content parts" (_models.py:316). That holds for user and model parts, but system parts lose it.

There's no workaround: extra={'system': [...]} raises INVALID_ARGUMENT because system is in _MANAGED_BODY_FIELDS (_models.py:235).

Mechanism

  • _to_anthropic_messages skips Role.SYSTEM (_models.py:727), so the get_cache_control pass at line 736 never runs on system parts.
  • _extract_system (_models.py:707) joins the system text into a single str and throws away part metadata.
  • The JSON fallback concatenates its schema instruction onto that string (_models.py:561). Even if caching worked, a cached prefix would share a block with text that varies from call to call.

Proposed fix

Send system as list[TextBlockParam], which messages.create already accepts (system: str | Iterable[TextBlockParam]):

# => "system": [
#      {"type": "text", "text": "<ALLERGEN_MANUAL>", "cache_control": {"type": "ephemeral"}},
#      {"type": "text", "text": "Table 4 avoids peanuts."}
#    ]
  • One text block per non-empty system text part, in order, with cache_control copied from part metadata.
  • Skip empty text. The API rejects empty text blocks.
  • The JSON fallback instruction goes in as its own trailing block instead of being string-concatenated.
  • Pin it through ai.generate + FakeClaudeApi in anthropic_generate_test.py: cached system part, multiple system messages, empty system text, and JSON fallback.

Users don't see this change. The value is private and Anthropic accepts both shapes. Internal tests that do '...' in params['system'] will need updating. Users who already cache on user turns get one cache miss after the upgrade, because the rendered prefix changes.

References: Go's Anthropic plugin already sends every system message as a TextBlockParam. JS forwards cache_control on system blocks. Python Bedrock keeps cachePoint on system blocks (genkit_amazon_bedrock/_converters.py, _system_blocks).

Related: #146 keeps every system message, joined as a string. This issue is the follow-up and doesn't block that PR.

Activity

  1. ssbushi commented on Nov 18, 2026

    @ssbushi
    Contributor
  2. genkit-bot commented on Nov 18, 2026

    @genkit-bot

    Triage: P2 · S · implement: AnthropicModel._extract_system flattens only the first system message into a plain string and drops cache_control metadata on system parts.

    Area: python

    Root cause: AnthropicModel._extract_system in packages/genkit-anthropic/src/genkit_anthropic/_models.py joins system text parts from only the first Role.SYSTEM message into a plain str and discards part.metadata['cache_control'], while _build_params string-concatenates the JSON fallback instruction onto system.

    Plan:

    • Update _extract_system in packages/genkit-anthropic/src/genkit_anthropic/_models.py to collect non-empty text parts across all Role.SYSTEM messages as {'type': 'text', 'text': ...} block dicts and attach cache_control via get_cache_control(part).
    • Append the JSON fallback instruction in _build_params as its own trailing text block instead of concatenating strings.
    • Reproduce before and verify after with uv run --no-sync pytest packages/genkit-anthropic/tests, adding unit and FakeClaudeApi tests in anthropic_models_test.py and anthropic_generate_test.py for cached system parts, multiple system messages, empty system text, and JSON fallback blocks.
    Details
    • packages/genkit-anthropic/src/genkit_anthropic/_models.py: _extract_system (lines 707-716) returns early on the first Role.SYSTEM message and never calls get_cache_control(part), unlike _to_anthropic_messages (lines 736-738).
    • packages/genkit-anthropic/src/genkit_anthropic/_models.py: _build_params (lines 535-564) builds system and appends the JSON fallback instruction by string concatenation.
    • packages/genkit-anthropic/tests/anthropic_models_test.py: test_extract_system (line 209) and structured-output fallback tests (lines 710-828) assert against params['system'] as a string and will need updating for block lists.

    Run 8d7d4149-e6ed-46ec-aae6-8c163bb931f5 · Cloud Run logs

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions