From f83525ed106e3c44ded7cef6c464ace305fe69ea Mon Sep 17 00:00:00 2001 From: Jeff Huang Date: Tue, 10 Nov 2026 20:10:39 -0600 Subject: [PATCH] fix(py/anthropic): bound sampling config and map cache usage Declare common_field_bounds ([0.0, 1.0]) on AnthropicConfig for temperature and top_p so out-of-range values fail locally with INVALID_ARGUMENT and advertise minimum/maximum in the Dev UI schema. Map Anthropic cache_read_input_tokens and cache_creation_input_tokens onto cached_content_tokens and cache_write_tokens, and include both in input_tokens and total_tokens so cached counts are subsets of input_tokens (matching Go, Gemini, OpenAI, and OpenTelemetry GenAI) while preserving Anthropic's raw keys on usage.custom. --- .../src/genkit_anthropic/_config.py | 3 + .../src/genkit_anthropic/_models.py | 8 +- .../src/genkit_anthropic/_utils.py | 21 +- .../tests/anthropic_models_test.py | 9 +- .../tests/anthropic_utils_test.py | 41 ++- .../tests/config_bounds_usage_test.py | 269 ++++++++++++++++++ 6 files changed, 327 insertions(+), 24 deletions(-) create mode 100644 packages/genkit-anthropic/tests/config_bounds_usage_test.py diff --git a/packages/genkit-anthropic/src/genkit_anthropic/_config.py b/packages/genkit-anthropic/src/genkit_anthropic/_config.py index 318bb6c92..394f84e5b 100644 --- a/packages/genkit-anthropic/src/genkit_anthropic/_config.py +++ b/packages/genkit-anthropic/src/genkit_anthropic/_config.py @@ -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.', diff --git a/packages/genkit-anthropic/src/genkit_anthropic/_models.py b/packages/genkit-anthropic/src/genkit_anthropic/_models.py index 838d9ad6c..828c770b5 100644 --- a/packages/genkit-anthropic/src/genkit_anthropic/_models.py +++ b/packages/genkit-anthropic/src/genkit_anthropic/_models.py @@ -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: diff --git a/packages/genkit-anthropic/src/genkit_anthropic/_utils.py b/packages/genkit-anthropic/src/genkit_anthropic/_utils.py index 16970b31c..8d6f9cc92 100644 --- a/packages/genkit-anthropic/src/genkit_anthropic/_utils.py +++ b/packages/genkit-anthropic/src/genkit_anthropic/_utils.py @@ -261,15 +261,22 @@ 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: @@ -277,13 +284,17 @@ def build_cache_usage( 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, ) diff --git a/packages/genkit-anthropic/tests/anthropic_models_test.py b/packages/genkit-anthropic/tests/anthropic_models_test.py index 5f6db6d8a..51b77ca54 100644 --- a/packages/genkit-anthropic/tests/anthropic_models_test.py +++ b/packages/genkit-anthropic/tests/anthropic_models_test.py @@ -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 diff --git a/packages/genkit-anthropic/tests/anthropic_utils_test.py b/packages/genkit-anthropic/tests/anthropic_utils_test.py index 4316b0017..ad6aa7929 100644 --- a/packages/genkit-anthropic/tests/anthropic_utils_test.py +++ b/packages/genkit-anthropic/tests/anthropic_utils_test.py @@ -293,10 +293,12 @@ 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, @@ -304,12 +306,15 @@ def test_usage_with_cache_creation(self) -> None: 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, @@ -317,12 +322,15 @@ def test_usage_with_cache_read(self) -> None: 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, @@ -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, @@ -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 diff --git a/packages/genkit-anthropic/tests/config_bounds_usage_test.py b/packages/genkit-anthropic/tests/config_bounds_usage_test.py new file mode 100644 index 000000000..991a0fbf3 --- /dev/null +++ b/packages/genkit-anthropic/tests/config_bounds_usage_test.py @@ -0,0 +1,269 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 + +"""AnthropicConfig sampling bounds and cache usage mapping.""" + +import json +from typing import Any, Literal +from unittest.mock import AsyncMock, MagicMock + +import httpx +import pytest +from genkit_anthropic import Anthropic, AnthropicConfig +from genkit_anthropic._models import AnthropicModel +from genkit_anthropic._utils import build_cache_usage +from pydantic import ValidationError + +from genkit import Genkit, GenkitError, Message, Part, Role +from genkit.model import GenerationUsage, ModelRequest + + +@pytest.mark.parametrize( + ('field', 'value'), + [('temperature', 1.5), ('temperature', -0.1), ('top_p', 1.1), ('top_p', -0.5)], +) +def test_out_of_range_sampling_values_fail_validation(field: str, value: float) -> None: + """Anthropic accepts temperature and top_p in [0, 1]; anything else fails before a request.""" + with pytest.raises(ValidationError, match=f'{field} must be between 0.0 and 1.0'): + AnthropicConfig.model_validate({field: value}) + + +@pytest.mark.parametrize('value', [0.0, 0.7, 1.0]) +def test_in_range_sampling_values_pass(value: float) -> None: + """Bounds are inclusive.""" + config = AnthropicConfig(temperature=value, top_p=value) + + assert (config.temperature, config.top_p) == (value, value) + + +def test_bounds_show_in_the_dev_ui_schema() -> None: + """The JSON schema the Dev UI reads advertises the range.""" + props = AnthropicConfig.model_json_schema()['properties'] + + assert (props['temperature']['minimum'], props['temperature']['maximum']) == (0.0, 1.0) + assert (props['topP']['minimum'], props['topP']['maximum']) == (0.0, 1.0) + + +def test_cache_tokens_map_to_inclusive_input_and_shared_usage_fields() -> None: + """Cache reads and writes are added into input_tokens/total_tokens and fill shared cache fields.""" + usage = build_cache_usage( + input_tokens=40, + output_tokens=20, + basic_usage=GenerationUsage(), + cache_creation_input_tokens=10, + cache_read_input_tokens=50, + ) + + assert (usage.input_tokens, usage.output_tokens, usage.total_tokens) == (100, 20, 120) + assert (usage.cached_content_tokens, usage.cache_write_tokens) == (50, 10) + assert usage.custom == {'cache_creation_input_tokens': 10, 'cache_read_input_tokens': 50} + + +def test_no_cache_tokens_leaves_the_fields_unset() -> None: + """A response without cache activity reports None, not 0.""" + usage = build_cache_usage(input_tokens=40, output_tokens=20, basic_usage=GenerationUsage()) + + assert (usage.input_tokens, usage.output_tokens, usage.total_tokens) == (40, 20, 60) + assert (usage.cached_content_tokens, usage.cache_write_tokens, usage.custom) == (None, None, None) + + +@pytest.mark.asyncio +async def test_generate_rejects_out_of_range_sampling_before_calling_client() -> None: + """AnthropicModel.generate raises INVALID_ARGUMENT before sending the request.""" + mock_client = MagicMock() + mock_client.messages.create = AsyncMock() + model = AnthropicModel(model_name='claude-sonnet-4-5', client=mock_client) + request = ModelRequest( + messages=[Message(role=Role.USER, content=[Part.from_text('Suggest a dish.')])], + config={'temperature': 1.4}, + ) + + with pytest.raises(GenkitError, match='temperature must be between 0.0 and 1.0') as exc_info: + await model.generate(request) + + assert exc_info.value.status == 'INVALID_ARGUMENT' + mock_client.messages.create.assert_not_called() + + +def _build_genkit_with_usage( + *, + start_usage: dict[str, int], + delta_usage: dict[str, int], + final_usage: dict[str, int], + text: str = 'Smoked Salmon Tartine', +) -> Genkit: + """Wire a Genkit Anthropic plugin against a mock HTTP transport serving JSON and SSE.""" + + def handler(request: httpx.Request) -> httpx.Response: + body: dict[str, Any] = json.loads(request.content) + if body.get('stream'): + events = [ + ( + 'message_start', + { + 'type': 'message_start', + 'message': { + 'id': 'msg_1', + 'type': 'message', + 'role': 'assistant', + 'model': 'claude-sonnet-4-6', + 'content': [], + 'stop_reason': None, + 'stop_sequence': None, + 'usage': start_usage, + }, + }, + ), + ( + 'content_block_start', + {'type': 'content_block_start', 'index': 0, 'content_block': {'type': 'text', 'text': ''}}, + ), + ( + 'content_block_delta', + {'type': 'content_block_delta', 'index': 0, 'delta': {'type': 'text_delta', 'text': text}}, + ), + ('content_block_stop', {'type': 'content_block_stop', 'index': 0}), + ( + 'message_delta', + { + 'type': 'message_delta', + 'delta': {'stop_reason': 'end_turn', 'stop_sequence': None}, + 'usage': delta_usage, + }, + ), + ('message_stop', {'type': 'message_stop'}), + ] + sse = ''.join(f'event: {name}\ndata: {json.dumps(data)}\n\n' for name, data in events) + return httpx.Response(200, text=sse, headers={'content-type': 'text/event-stream'}) + + return httpx.Response( + 200, + json={ + 'id': 'msg_1', + 'type': 'message', + 'role': 'assistant', + 'model': 'claude-sonnet-4-6', + 'content': [{'type': 'text', 'text': text}], + 'stop_reason': 'end_turn', + 'stop_sequence': None, + 'usage': final_usage, + }, + ) + + http_client = httpx.AsyncClient(transport=httpx.MockTransport(handler)) + return Genkit(plugins=[Anthropic(api_key='test-key', client_options={'http_client': http_client})]) + + +@pytest.mark.parametrize('api_version', ['stable', 'beta']) +@pytest.mark.asyncio +async def test_streaming_and_non_streaming_produce_identical_cache_usage( + api_version: Literal['stable', 'beta'], +) -> None: + """ai.generate and ai.generate_stream compute identical inclusive GenerationUsage.""" + ai = _build_genkit_with_usage( + start_usage={ + 'input_tokens': 40, + 'output_tokens': 1, + 'cache_creation_input_tokens': 10, + 'cache_read_input_tokens': 1834, + }, + delta_usage={'output_tokens': 20}, + final_usage={ + 'input_tokens': 40, + 'output_tokens': 20, + 'cache_creation_input_tokens': 10, + 'cache_read_input_tokens': 1834, + }, + ) + + non_stream = await ai.generate( + model='anthropic/claude-sonnet-4-6', + prompt='Suggest a dish.', + config={'api_version': api_version}, + ) + stream_res = ai.generate_stream( + model='anthropic/claude-sonnet-4-6', + prompt='Suggest a dish.', + config={'api_version': api_version}, + ) + chunks = [chunk.text async for chunk in stream_res.stream] + streamed = await stream_res.response + + assert ''.join(chunks) == 'Smoked Salmon Tartine' + assert non_stream.usage is not None + assert streamed.usage == non_stream.usage + assert (non_stream.usage.input_tokens, non_stream.usage.output_tokens, non_stream.usage.total_tokens) == ( + 1884, + 20, + 1904, + ) + assert (non_stream.usage.cached_content_tokens, non_stream.usage.cache_write_tokens) == (1834, 10) + assert non_stream.usage.custom == {'cache_creation_input_tokens': 10, 'cache_read_input_tokens': 1834} + + +@pytest.mark.asyncio +async def test_streaming_message_delta_cumulative_cache_usage_updates_totals() -> None: + """Cumulative input/cache counts emitted on message_delta produce the same inclusive usage.""" + ai = _build_genkit_with_usage( + start_usage={ + 'input_tokens': 25, + 'output_tokens': 1, + 'cache_creation_input_tokens': 5, + 'cache_read_input_tokens': 1000, + }, + delta_usage={ + 'input_tokens': 40, + 'output_tokens': 20, + 'cache_creation_input_tokens': 10, + 'cache_read_input_tokens': 1834, + }, + final_usage={ + 'input_tokens': 40, + 'output_tokens': 20, + 'cache_creation_input_tokens': 10, + 'cache_read_input_tokens': 1834, + }, + ) + + non_stream = await ai.generate(model='anthropic/claude-sonnet-4-6', prompt='Suggest a dish.') + streamed = await ai.generate_stream(model='anthropic/claude-sonnet-4-6', prompt='Suggest a dish.').response + + assert streamed.usage == non_stream.usage + assert streamed.usage is not None + assert (streamed.usage.input_tokens, streamed.usage.output_tokens, streamed.usage.total_tokens) == (1884, 20, 1904) + assert (streamed.usage.cached_content_tokens, streamed.usage.cache_write_tokens) == (1834, 10) + + +@pytest.mark.asyncio +async def test_streaming_and_non_streaming_without_cache_leave_cache_fields_unset() -> None: + """Uncached calls leave cached_content_tokens, cache_write_tokens, and custom unset in both modes.""" + ai = _build_genkit_with_usage( + start_usage={'input_tokens': 40, 'output_tokens': 1}, + delta_usage={'output_tokens': 20}, + final_usage={'input_tokens': 40, 'output_tokens': 20}, + ) + + non_stream = await ai.generate(model='anthropic/claude-sonnet-4-6', prompt='Suggest a dish.') + streamed = await ai.generate_stream(model='anthropic/claude-sonnet-4-6', prompt='Suggest a dish.').response + + assert streamed.usage == non_stream.usage + assert streamed.usage is not None + assert (streamed.usage.input_tokens, streamed.usage.output_tokens, streamed.usage.total_tokens) == (40, 20, 60) + assert (streamed.usage.cached_content_tokens, streamed.usage.cache_write_tokens, streamed.usage.custom) == ( + None, + None, + None, + )