Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 22 additions & 4 deletions packages/genkit-anthropic/src/genkit_anthropic/_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand Down
21 changes: 21 additions & 0 deletions packages/genkit-anthropic/tests/anthropic_generate_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -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}]
20 changes: 20 additions & 0 deletions packages/genkit-anthropic/tests/anthropic_models_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
Loading