Skip to content
Closed
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
2 changes: 1 addition & 1 deletion packages/genkit-anthropic/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ classifiers = [
"Typing :: Typed",
"License :: OSI Approved :: Apache Software License",
]
dependencies = ["genkit>=0.14.0,<2", "anthropic>=0.96.0,<1"]
dependencies = ["genkit>=0.14.0,<2", "anthropic>=0.98.0,<3"]
description = "Claude on Genkit"
keywords = [
"genkit",
Expand Down
55 changes: 55 additions & 0 deletions packages/genkit-anthropic/src/genkit_anthropic/_compat.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
# 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

"""What differs across the supported ``anthropic`` range, read off the installed SDK.

anthropic 1.0 changed two things the plugin depends on:

- The transport moved from ``httpx`` to ``httpx2``, an API-compatible fork in
a different module. Exceptions raised mid-stream come from whichever one the
SDK uses, so ``httpx`` here is that module.
- ``temperature``, ``top_p`` and ``top_k`` left the ``messages.create()``
signature. The API still takes them, so they go in ``extra_body`` when the
installed SDK has no named parameter for them.
"""

import importlib
import inspect
from typing import TYPE_CHECKING

from anthropic import DefaultAsyncHttpxClient
from anthropic.resources.beta.messages import AsyncMessages as AsyncBetaMessages
from anthropic.resources.messages import AsyncMessages

if TYPE_CHECKING:
# Type checkers run against the locked SDK, which is on httpx2.
import httpx2 as httpx
else:
_transport_client = next(c for c in DefaultAsyncHttpxClient.__mro__ if c.__name__ == 'AsyncClient')
httpx = importlib.import_module(_transport_client.__module__.partition('.')[0])

__all__ = ['SDK_MESSAGE_KWARGS', 'TRANSPORT_DROP_ERRORS', 'TRANSPORT_TIMEOUT_ERRORS', 'httpx']

TRANSPORT_TIMEOUT_ERRORS: tuple[type[Exception], ...] = (httpx.TimeoutException,)
TRANSPORT_DROP_ERRORS: tuple[type[Exception], ...] = (httpx.NetworkError, httpx.RemoteProtocolError)

# Named parameters every request method the plugin calls accepts.
SDK_MESSAGE_KWARGS: frozenset[str] = frozenset.intersection(
*(
frozenset(inspect.signature(method).parameters)
for method in (AsyncMessages.create, AsyncMessages.stream, AsyncBetaMessages.create, AsyncBetaMessages.stream)
)
)
12 changes: 8 additions & 4 deletions packages/genkit-anthropic/src/genkit_anthropic/_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@
import json
from typing import Any, Literal, Protocol, cast

import httpx
from anthropic import (
APIConnectionError,
APIError,
Expand All @@ -41,6 +40,7 @@
from genkit import FinishReason, GenkitError, Message, ModelResponse, ModelResponseChunk, Part, Role, get_logger
from genkit.model import ConstrainedSupport, GenerationUsage, ModelContext, ModelRequest, ToolRequest
from genkit.plugin_api import StatusName, provider_error
from genkit_anthropic._compat import SDK_MESSAGE_KWARGS, TRANSPORT_DROP_ERRORS, TRANSPORT_TIMEOUT_ERRORS
from genkit_anthropic._config import AnthropicConfig
from genkit_anthropic._model_info import get_model_info
from genkit_anthropic._secrets import context_api_key
Expand Down Expand Up @@ -286,7 +286,7 @@ def _merge_config_extra(params: dict[str, Any], extra: dict[str, Any] | None) ->
'and cannot be set from config'
)
raise GenkitError(status='INVALID_ARGUMENT', message=message)
extra_body = dict(extra)
extra_body = {**params.get('extra_body', {}), **extra}
if 'tools' not in params:
extra_body.pop('tool_choice', None)
if extra_body:
Expand Down Expand Up @@ -382,9 +382,9 @@ async def generate(self, request: ModelRequest, ctx: ModelContext | None = None)
raise _from_anthropic_error(error) from error
# The SDK wraps httpx failures only while sending; a connection that
# drops while the stream is being read comes out raw.
except httpx.TimeoutException as error:
except TRANSPORT_TIMEOUT_ERRORS as error:
raise provider_error(error, status='DEADLINE_EXCEEDED') from error
except (httpx.NetworkError, httpx.RemoteProtocolError) as error:
except TRANSPORT_DROP_ERRORS as error:
raise provider_error(error, status='UNAVAILABLE') from error

logger.debug(
Expand Down Expand Up @@ -503,6 +503,8 @@ def _build_params(
# Only the fields create() takes as is; a new config field stays out
# of the request until it's listed here or built below.
params = config.model_dump(include=set(AnthropicConfig.CREATE_KWARGS), exclude_none=True)
# anthropic>=1 dropped temperature/top_p/top_k from create(); the API still reads them from the body.
body_only = {key: params.pop(key) for key in sorted(params.keys() - SDK_MESSAGE_KWARGS)}
extra = config.extra
max_tokens = config.max_output_tokens if config.max_output_tokens is not None else DEFAULT_MAX_OUTPUT_TOKENS
betas = config.betas
Expand Down Expand Up @@ -591,6 +593,8 @@ def _build_params(
if tool_choice is not None:
params['tool_choice'] = tool_choice

if body_only:
params['extra_body'] = body_only
_merge_config_extra(params, extra)
return params

Expand Down
8 changes: 4 additions & 4 deletions packages/genkit-anthropic/tests/anthropic_config_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -240,7 +240,7 @@ def test_json_schema_advertises_js_shaped_keys() -> None:
@pytest.mark.parametrize(
('raw', 'expected'),
[
({'extra': {'speed': 'fast'}}, {'speed'}),
({'extra': {'context_management': {'edits': []}}}, {'context_management'}),
({'betas': ['x']}, {'betas'}),
# Setting a beta-only feature at all is intent, even when the value is empty.
({'extra': {'mcp_servers': []}}, {'mcp_servers'}),
Expand All @@ -261,7 +261,7 @@ def test_beta_only_fields_detection(raw: dict, expected: set[str]) -> None:
'raw',
[
{'apiVersion': 'stable', 'betas': ['x']},
{'apiVersion': 'stable', 'extra': {'speed': 'fast'}},
{'apiVersion': 'stable', 'extra': {'context_management': {'edits': []}}},
{'apiVersion': 'stable', 'taskBudget': 20000},
],
)
Expand All @@ -274,8 +274,8 @@ def test_beta_only_fields_rejected_on_stable_surface(raw: dict) -> None:
@pytest.mark.parametrize(
'raw',
[
{'apiVersion': 'beta', 'extra': {'speed': 'fast'}},
{'extra': {'speed': 'fast'}},
{'apiVersion': 'beta', 'extra': {'context_management': {'edits': []}}},
{'extra': {'context_management': {'edits': []}}},
{'apiVersion': 'stable', 'temperature': 0.5},
],
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@
from typing import Any
from unittest.mock import AsyncMock, MagicMock

import httpx
import pytest
from anthropic import (
APIConnectionError,
Expand All @@ -31,6 +30,7 @@
APITimeoutError,
AsyncAnthropic,
)
from genkit_anthropic._compat import httpx
from genkit_anthropic._models import AnthropicModel

from genkit import GenkitError, Message, Part, Role
Expand Down
15 changes: 10 additions & 5 deletions packages/genkit-anthropic/tests/anthropic_generate_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,9 @@
from collections.abc import Callable
from typing import Any, Literal, cast

import httpx
import pytest
from genkit_anthropic import Anthropic, AnthropicConfig
from genkit_anthropic._compat import httpx

from genkit import FinishReason, Genkit, GenkitError, Message, Part, Role
from genkit.middleware import Middleware
Expand Down Expand Up @@ -98,7 +98,12 @@ def body(self, index: int = -1) -> dict[str, Any]:
return json.loads(self.requests[index].content)

def api_key(self, index: int = -1) -> str | None:
return self.requests[index].headers.get('x-api-key')
# anthropic<2 sends the key as x-api-key; 2.x sends it as Authorization: Bearer.
headers = self.requests[index].headers
if 'x-api-key' in headers:
return headers['x-api-key']
scheme, _, key = headers.get('authorization', '').partition(' ')
return key if scheme == 'Bearer' else None


def _genkit(
Expand Down Expand Up @@ -274,7 +279,7 @@ async def test_plugin_without_key_and_no_tenant_key_raises_naming_both() -> None
@pytest.mark.parametrize('streaming', [False, True], ids=['generate', 'generate_stream'])
@pytest.mark.asyncio
async def test_anthropic_per_request_key_still_overrides_plugin_key(streaming: bool) -> None:
"""`context={'secrets': {'api_key': k}}` sends `x-api-key: k` instead of the plugin's key."""
"""`context={'secrets': {'api_key': k}}` sends key `k` instead of the plugin's key."""
api = FakeClaudeApi()
ai = _genkit(api)
context: dict[str, object] = {'secrets': {'api_key': TENANT_KEY}}
Expand Down Expand Up @@ -838,7 +843,7 @@ async def test_anthropic_without_models_still_resolves_any_claude_model() -> Non

@pytest.mark.asyncio
async def test_anthropic_without_api_key_uses_anthropic_api_key_env(monkeypatch: pytest.MonkeyPatch) -> None:
"""Anthropic() with ANTHROPIC_API_KEY=env-key sends x-api-key: env-key."""
"""Anthropic() with ANTHROPIC_API_KEY=env-key sends env-key as its API key."""
monkeypatch.setenv('ANTHROPIC_API_KEY', 'env-key')
api = FakeClaudeApi()
ai = _genkit(api, api_key=None)
Expand All @@ -850,7 +855,7 @@ async def test_anthropic_without_api_key_uses_anthropic_api_key_env(monkeypatch:

@pytest.mark.asyncio
async def test_anthropic_api_key_is_sent_as_x_api_key() -> None:
"""Anthropic(api_key='plugin-key') sends x-api-key: plugin-key on ai.generate."""
"""Anthropic(api_key='plugin-key') sends plugin-key as its API key on ai.generate."""
api = FakeClaudeApi()
ai = _genkit(api, api_key=PLUGIN_KEY)

Expand Down
44 changes: 27 additions & 17 deletions packages/genkit-anthropic/tests/anthropic_models_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@

"""Tests for Anthropic models."""

from collections.abc import Mapping
from typing import Any
from unittest.mock import AsyncMock, MagicMock, patch

Expand Down Expand Up @@ -198,12 +199,12 @@ async def test_generate_with_config() -> None:

await model.generate(request)

call_args = mock_client.messages.create.call_args
assert call_args.kwargs['temperature'] == 0.0
assert call_args.kwargs['max_tokens'] == 100
assert call_args.kwargs['top_p'] == 0.9
assert call_args.kwargs['top_k'] == 40
assert call_args.kwargs['stop_sequences'] == ['STOP']
sent = _wire(mock_client.messages.create.call_args.kwargs)
assert sent['temperature'] == 0.0
assert sent['max_tokens'] == 100
assert sent['top_p'] == 0.9
assert sent['top_k'] == 40
assert sent['stop_sequences'] == ['STOP']


def test_extract_system() -> None:
Expand Down Expand Up @@ -875,6 +876,16 @@ def _mock_vertex_client_for_generate() -> MagicMock:
return mock_client


def _wire(kwargs: Mapping[str, Any]) -> dict[str, Any]:
"""The JSON body the SDK sends: named kwargs with ``extra_body`` merged over them.

anthropic>=1 has no ``temperature``/``top_p``/``top_k`` parameters, so the plugin
sends those through ``extra_body`` there and as named kwargs on 0.x.
"""
body = {key: value for key, value in kwargs.items() if key != 'extra_body'}
return {**body, **kwargs.get('extra_body', {})}


def _text_request(config: Any) -> ModelRequest:
return ModelRequest(
messages=[Message(role=Role.USER, content=[Part.from_text('Hi')])],
Expand Down Expand Up @@ -1070,7 +1081,7 @@ async def test_camelcase_sampling_aliases_normalized() -> None:
})
)

kwargs = mock_client.messages.create.call_args.kwargs
kwargs = _wire(mock_client.messages.create.call_args.kwargs)
assert kwargs['top_p'] == 0.9
assert kwargs['top_k'] == 20
assert kwargs['stop_sequences'] == ['x']
Expand Down Expand Up @@ -1106,7 +1117,7 @@ async def test_sampling_params_reach_streaming_request() -> None:
ctx,
)

kwargs = mock_client.messages.stream.call_args.kwargs
kwargs = _wire(mock_client.messages.stream.call_args.kwargs)
assert kwargs['temperature'] == 0.2
assert kwargs['top_p'] == 0.8
assert kwargs['top_k'] == 30
Expand All @@ -1124,7 +1135,7 @@ async def test_sampling_params_pass_through_for_newest_models(model_name: str) -
# These models enforce sampling restrictions server-side; match JS and Go by forwarding unchanged.
await model.generate(_text_request({'temperature': 0.7, 'top_p': 0.9, 'top_k': 40}))

kwargs = mock_client.messages.create.call_args.kwargs
kwargs = _wire(mock_client.messages.create.call_args.kwargs)
assert kwargs['temperature'] == 0.7
assert kwargs['top_p'] == 0.9
assert kwargs['top_k'] == 40
Expand Down Expand Up @@ -1178,7 +1189,7 @@ class TaggedConfig(AnthropicConfig):
)

assert 'menu_tag' not in params
assert params['temperature'] == 0.2
assert _wire(params)['temperature'] == 0.2
assert params['stop_sequences'] == ['END']


Expand All @@ -1190,9 +1201,9 @@ async def test_dict_config_extra_reaches_sdk() -> None:

await model.generate(_text_request({'temperature': 0.3, 'extra': {'future_option': 'x'}}))

kwargs = mock_client.messages.create.call_args.kwargs
kwargs = _wire(mock_client.messages.create.call_args.kwargs)
assert kwargs['temperature'] == 0.3
assert kwargs['extra_body'] == {'future_option': 'x'}
assert kwargs['future_option'] == 'x'


@pytest.mark.asyncio
Expand Down Expand Up @@ -1382,16 +1393,15 @@ def test_backward_compat_plain_model_config() -> None:

params = model._build_params(_text_request(ModelConfig(temperature=0.7, max_output_tokens=100, top_p=0.9)))

assert params['temperature'] == 0.7
assert _wire(params)['temperature'] == 0.7
assert params['max_tokens'] == 100
assert params['top_p'] == 0.9
assert _wire(params)['top_p'] == 0.9


@pytest.mark.asyncio
@pytest.mark.parametrize(
('config', 'kwarg'),
[
({'speed': 'fast'}, 'speed'),
({'mcp_servers': [{'type': 'url', 'name': 'x', 'url': 'https://example.com'}]}, 'mcp_servers'),
({'context_management': {'edits': []}}, 'context_management'),
],
Expand Down Expand Up @@ -1428,10 +1438,10 @@ async def test_unknown_params_still_route_to_extra_body_on_beta() -> None:
mock_client = _mock_client_for_generate()
model = AnthropicModel(model_name='claude-sonnet-4', client=mock_client)

await model.generate(_text_request({'extra': {'speed': 'fast', 'future_option': 'x'}}))
await model.generate(_text_request({'extra': {'context_management': {'edits': []}, 'future_option': 'x'}}))

kwargs = mock_client.beta.messages.create.call_args.kwargs
assert kwargs['extra_body'] == {'speed': 'fast', 'future_option': 'x'}
assert kwargs['extra_body'] == {'context_management': {'edits': []}, 'future_option': 'x'}


@pytest.mark.asyncio
Expand Down
Loading
Loading