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
3 changes: 3 additions & 0 deletions packages/genkit-anthropic/src/genkit_anthropic/_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -219,6 +219,9 @@ class AnthropicConfig(ModelConfig):
# (api_version).
CREATE_KWARGS: ClassVar[frozenset[str]] = frozenset({'temperature', 'top_k', 'top_p', 'stop_sequences'})

# Anthropic's documented ranges; out-of-range values fail before the request.
common_field_bounds = {'temperature': (0.0, 1.0), 'top_p': (0.0, 1.0)}

thinking: ThinkingMode | None = Field(
default=None,
description='Extended thinking mode. A thinking_budget alone means enabled.',
Expand Down
8 changes: 6 additions & 2 deletions packages/genkit-anthropic/src/genkit_anthropic/_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -437,12 +437,16 @@ def _build_usage(self, response: AnthropicMessage, basic_usage: GenerationUsage)
Returns:
GenerationUsage with token and character counts.
"""
raw_creation: object = getattr(response.usage, 'cache_creation_input_tokens', None)
raw_read: object = getattr(response.usage, 'cache_read_input_tokens', None)
return build_cache_usage(
input_tokens=response.usage.input_tokens,
output_tokens=response.usage.output_tokens,
basic_usage=basic_usage,
cache_creation_input_tokens=getattr(response.usage, 'cache_creation_input_tokens', None) or 0,
cache_read_input_tokens=getattr(response.usage, 'cache_read_input_tokens', None) or 0,
cache_creation_input_tokens=(
raw_creation if isinstance(raw_creation, int) and not isinstance(raw_creation, bool) else 0
),
cache_read_input_tokens=raw_read if isinstance(raw_read, int) and not isinstance(raw_read, bool) else 0,
)

def _client_for_key(self, api_key: str | None) -> object:
Expand Down
21 changes: 16 additions & 5 deletions packages/genkit-anthropic/src/genkit_anthropic/_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -261,29 +261,40 @@ def build_cache_usage(
) -> GenerationUsage:
"""Build GenerationUsage with cache-aware token counts.

Anthropic's ``input_tokens`` leaves out tokens read from and written to the
prompt cache, so both are added back to make ``input_tokens`` the full
prompt (matching Gemini, OpenAI, Go, and OpenTelemetry GenAI), with
``cached_content_tokens`` and ``cache_write_tokens`` as subsets.

Args:
input_tokens: Number of input tokens from the API response.
output_tokens: Number of output tokens from the API response.
input_tokens: Uncached input token count from the API response.
output_tokens: Output token count from the API response.
basic_usage: Basic character/image usage from message content.
cache_creation_input_tokens: Tokens for newly created cache entries.
cache_read_input_tokens: Tokens read from existing cache entries.

Returns:
GenerationUsage with token, character, and cache counts.
GenerationUsage with inclusive ``input_tokens`` and ``total_tokens``,
``cached_content_tokens`` / ``cache_write_tokens`` set when non-zero,
and Anthropic's raw key names preserved on ``custom``.
"""
custom: dict[str, float] = {}
if cache_creation_input_tokens:
custom['cache_creation_input_tokens'] = cache_creation_input_tokens
if cache_read_input_tokens:
custom['cache_read_input_tokens'] = cache_read_input_tokens

total_input_tokens = input_tokens + cache_read_input_tokens + cache_creation_input_tokens

return GenerationUsage(
input_tokens=input_tokens,
input_tokens=total_input_tokens,
output_tokens=output_tokens,
total_tokens=input_tokens + output_tokens,
total_tokens=total_input_tokens + output_tokens,
input_characters=basic_usage.input_characters,
output_characters=basic_usage.output_characters,
input_images=basic_usage.input_images,
output_images=basic_usage.output_images,
cached_content_tokens=cache_read_input_tokens or None,
cache_write_tokens=cache_creation_input_tokens or None,
custom=custom if custom else None,
)
9 changes: 5 additions & 4 deletions packages/genkit-anthropic/tests/anthropic_models_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -541,11 +541,12 @@ async def test_cache_token_tracking_in_usage() -> None:
response = await model.generate(request)

assert response.usage is not None
assert response.usage.input_tokens == 100
assert response.usage.input_tokens == 200
assert response.usage.output_tokens == 50
assert response.usage.custom is not None
assert response.usage.custom['cache_creation_input_tokens'] == 80
assert response.usage.custom['cache_read_input_tokens'] == 20
assert response.usage.total_tokens == 250
assert response.usage.cached_content_tokens == 20
assert response.usage.cache_write_tokens == 80
assert response.usage.custom == {'cache_creation_input_tokens': 80, 'cache_read_input_tokens': 20}


@pytest.mark.asyncio
Expand Down
41 changes: 28 additions & 13 deletions packages/genkit-anthropic/tests/anthropic_utils_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -293,36 +293,44 @@ def test_basic_usage_without_cache(self) -> None:
assert result.total_tokens == 150
assert result.input_characters == 10
assert result.output_characters == 20
assert result.cached_content_tokens is None
assert result.cache_write_tokens is None
assert result.custom is None

def test_usage_with_cache_creation(self) -> None:
"""Includes cache_creation_input_tokens in custom."""
"""Includes cache_creation_input_tokens in input_tokens, total_tokens, cache_write_tokens, and custom."""
basic = GenerationUsage()
result = build_cache_usage(
input_tokens=100,
output_tokens=50,
basic_usage=basic,
cache_creation_input_tokens=200,
)
assert result.custom is not None
assert result.custom['cache_creation_input_tokens'] == 200
assert 'cache_read_input_tokens' not in result.custom
assert result.input_tokens == 300
assert result.output_tokens == 50
assert result.total_tokens == 350
assert result.cached_content_tokens is None
assert result.cache_write_tokens == 200
assert result.custom == {'cache_creation_input_tokens': 200}

def test_usage_with_cache_read(self) -> None:
"""Includes cache_read_input_tokens in custom."""
"""Includes cache_read_input_tokens in input_tokens, total_tokens, cached_content_tokens, and custom."""
basic = GenerationUsage()
result = build_cache_usage(
input_tokens=100,
output_tokens=50,
basic_usage=basic,
cache_read_input_tokens=300,
)
assert result.custom is not None
assert result.custom['cache_read_input_tokens'] == 300
assert 'cache_creation_input_tokens' not in result.custom
assert result.input_tokens == 400
assert result.output_tokens == 50
assert result.total_tokens == 450
assert result.cached_content_tokens == 300
assert result.cache_write_tokens is None
assert result.custom == {'cache_read_input_tokens': 300}

def test_usage_with_both_cache_fields(self) -> None:
"""Includes both cache token fields when both are present."""
"""Includes both cache token fields in inclusive totals, shared fields, and custom."""
basic = GenerationUsage()
result = build_cache_usage(
input_tokens=100,
Expand All @@ -331,12 +339,15 @@ def test_usage_with_both_cache_fields(self) -> None:
cache_creation_input_tokens=200,
cache_read_input_tokens=300,
)
assert result.custom is not None
assert result.custom['cache_creation_input_tokens'] == 200
assert result.custom['cache_read_input_tokens'] == 300
assert result.input_tokens == 600
assert result.output_tokens == 50
assert result.total_tokens == 650
assert result.cached_content_tokens == 300
assert result.cache_write_tokens == 200
assert result.custom == {'cache_creation_input_tokens': 200, 'cache_read_input_tokens': 300}

def test_zero_cache_tokens_are_excluded(self) -> None:
"""Zero cache tokens don't appear in custom field."""
"""Zero cache tokens leave shared cache fields and custom unset."""
basic = GenerationUsage()
result = build_cache_usage(
input_tokens=100,
Expand All @@ -345,4 +356,8 @@ def test_zero_cache_tokens_are_excluded(self) -> None:
cache_creation_input_tokens=0,
cache_read_input_tokens=0,
)
assert result.input_tokens == 100
assert result.total_tokens == 150
assert result.cached_content_tokens is None
assert result.cache_write_tokens is None
assert result.custom is None
Loading
Loading