From f878bd04d5b89b4363887f42bedf421305955522 Mon Sep 17 00:00:00 2001 From: Jeff Huang Date: Mon, 30 Nov 2026 20:25:36 +0000 Subject: [PATCH] feat(py/anthropic): explore AmazonBedrock backend for Anthropic --- packages/genkit-anthropic/pyproject.toml | 2 + .../src/genkit_anthropic/__init__.py | 6 + .../src/genkit_anthropic/_amazon_bedrock.py | 283 ++++++++++++ .../src/genkit_anthropic/_backend.py | 5 + .../src/genkit_anthropic/_models.py | 19 +- .../src/genkit_anthropic/_plugin.py | 65 +-- .../tests/anthropic_amazon_bedrock_test.py | 424 ++++++++++++++++++ .../tests/anthropic_google_cloud_test.py | 1 + uv.lock | 10 +- 9 files changed, 784 insertions(+), 31 deletions(-) create mode 100644 packages/genkit-anthropic/src/genkit_anthropic/_amazon_bedrock.py create mode 100644 packages/genkit-anthropic/tests/anthropic_amazon_bedrock_test.py diff --git a/packages/genkit-anthropic/pyproject.toml b/packages/genkit-anthropic/pyproject.toml index d67ce3a3..6bfe096b 100644 --- a/packages/genkit-anthropic/pyproject.toml +++ b/packages/genkit-anthropic/pyproject.toml @@ -59,6 +59,8 @@ version = "0.14.0" [project.optional-dependencies] # Anthropic(backend=GoogleCloud()): google-auth for application default credentials. google-cloud = ["anthropic[vertex]>=0.96.0,<1"] +# Anthropic(backend=AmazonBedrock()): boto3 and botocore for AWS SigV4 signing. +amazon-bedrock = ["anthropic[bedrock]>=0.96.0,<1"] [project.urls] "Bug Tracker" = "https://github.com/genkit-ai/genkit-python/issues" diff --git a/packages/genkit-anthropic/src/genkit_anthropic/__init__.py b/packages/genkit-anthropic/src/genkit_anthropic/__init__.py index a9eba987..e69d0ea4 100644 --- a/packages/genkit-anthropic/src/genkit_anthropic/__init__.py +++ b/packages/genkit-anthropic/src/genkit_anthropic/__init__.py @@ -55,15 +55,21 @@ async def main() -> None: and billed to the project (``uv add 'genkit-anthropic[google-cloud]'``). Refs, config and ``.prompt`` files stay the same. + ``Anthropic(backend=AmazonBedrock(region=...))`` serves Claude from Amazon + Bedrock Runtime with AWS credentials or a Bedrock bearer token + (``uv add 'genkit-anthropic[amazon-bedrock]'``). + See Also: - Anthropic documentation: https://docs.anthropic.com/ """ +from genkit_anthropic._amazon_bedrock import AmazonBedrock from genkit_anthropic._config import AnthropicConfig, Effort, ThinkingDisplay, ThinkingMode from genkit_anthropic._google_cloud import GoogleCloud from genkit_anthropic._plugin import Anthropic __all__ = [ + 'AmazonBedrock', 'Anthropic', 'AnthropicConfig', 'Effort', diff --git a/packages/genkit-anthropic/src/genkit_anthropic/_amazon_bedrock.py b/packages/genkit-anthropic/src/genkit_anthropic/_amazon_bedrock.py new file mode 100644 index 00000000..69001d4f --- /dev/null +++ b/packages/genkit-anthropic/src/genkit_anthropic/_amazon_bedrock.py @@ -0,0 +1,283 @@ +# 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 + +"""Amazon Bedrock as a backend for the Anthropic plugin.""" + +import asyncio +import os +from collections.abc import Mapping +from dataclasses import dataclass +from typing import Any + +from anthropic import AsyncAnthropicBedrock + +from genkit import GenkitError +from genkit_anthropic._backend import Backend, client_kwargs + +_AWS_REGION_FIX = ( + 'pass AmazonBedrock(region=...), set AWS_REGION or AWS_DEFAULT_REGION, or configure a region in ~/.aws/config' +) +_AWS_CREDS_FIX = ( + 'run `aws sso login` or `aws configure` locally, attach an IAM role on AWS, or set AWS_BEARER_TOKEN_BEDROCK' +) + + +@dataclass(frozen=True, kw_only=True) +class AmazonBedrock: + """Serve Claude from Amazon Bedrock, billed to an AWS account. + + Pass ``Anthropic(backend=AmazonBedrock(...))`` to send native Anthropic + Messages API requests to Amazon Bedrock Runtime (``AsyncAnthropicBedrock``). + Requests authenticate with the standard AWS credential chain (SigV4) or a + Bedrock bearer token (``AWS_BEARER_TOKEN_BEDROCK``), and expose the full + ``AnthropicConfig`` surface (extended thinking, effort, task budget, prompt + caching). + + Unlike Google Cloud, Bedrock Runtime expects Bedrock model IDs or + cross-region inference-profile IDs (e.g. ``global.anthropic.claude-sonnet-4-6`` + or ``us.anthropic.claude-sonnet-4-5-20250929-v1:0``) rather than bare + Anthropic API names. + + Example: + ```python + from genkit import Genkit + from genkit_anthropic import AmazonBedrock, Anthropic, AnthropicConfig + + # 1. Serve Claude from Amazon Bedrock using your AWS credentials + ai = Genkit(plugins=[Anthropic(backend=AmazonBedrock(region='us-east-1'))]) + + # 2. Full AnthropicConfig works; pass a Bedrock model or inference-profile ID + res = await ai.generate( + model=Anthropic.claude('global.anthropic.claude-sonnet-4-6'), + prompt='Suggest a dish for a guest with a shellfish allergy.', + config=AnthropicConfig(thinking='adaptive', effort='medium'), + ) + print(res.text) + # => Herb-Roasted Chicken with Lemon Rice + ``` + + Attributes: + region: AWS region. Defaults to ``AWS_REGION``, then + ``AWS_DEFAULT_REGION``, then the active AWS profile's region in + ``~/.aws/config``. There is deliberately no ``us-east-1`` fallback. + profile: Named AWS profile from ``~/.aws/config`` or + ``~/.aws/credentials``. Defaults to the ambient AWS credential + chain. + """ + + region: str | None = None + profile: str | None = None + + +def resolve_region(backend: AmazonBedrock, *, session_region: str | None = None) -> str | None: + """The region from the argument, AWS env vars, or the boto3 session; None if unset.""" + return ( + backend.region or os.environ.get('AWS_REGION') or os.environ.get('AWS_DEFAULT_REGION') or session_region or None + ) + + +def require_boto3() -> None: + """Fail at setup, on the user's line, when the amazon-bedrock extra isn't installed. + + Raises: + ImportError: ``boto3`` or ``botocore`` isn't installed. + """ + # Optional dependency: boto3 and botocore ship with the [amazon-bedrock] extra only. + try: + import boto3 # noqa: F401, PLC0415 + import botocore # noqa: F401, PLC0415 + except ModuleNotFoundError as e: + raise ImportError( + 'Anthropic(backend=AmazonBedrock()) needs the amazon-bedrock extra: ' + "uv add 'genkit-anthropic[amazon-bedrock]'" + ) from e + + +def load_aws_context(backend: AmazonBedrock, *, check_credentials: bool) -> str: + """Resolve the AWS region and verify credentials exist (blocking: may hit IMDS/SSO). + + Running this before building the client serves two purposes: + 1. ``AsyncAnthropicBedrock`` silently defaults to ``us-east-1`` when no region + is set, which can route data to an unintended AWS region. Failing here + enforces an explicit region. + 2. ``AsyncAnthropicBedrock._prepare_request`` resolves boto3 credentials + synchronously on the event loop and raises a bare ``RuntimeError`` when + none are found (which Retry middleware would treat as transient). Checking + here turns missing/stale AWS credentials into ``FAILED_PRECONDITION``. + + Raises: + GenkitError: FAILED_PRECONDITION when the AWS profile is missing, no + region resolves, or no credentials can be resolved. + """ + region = resolve_region(backend) + if region is not None and not check_credentials: + return region + + # Optional dependency, checked by require_boto3 at setup. + import boto3 # noqa: PLC0415 + from botocore.exceptions import BotoCoreError, ProfileNotFound # noqa: PLC0415 + + try: + session = boto3.Session(profile_name=backend.profile) + except ProfileNotFound as e: + raise GenkitError( + status='FAILED_PRECONDITION', + message=f'Anthropic(backend=AmazonBedrock()) could not find AWS profile {backend.profile!r}: {e}', + ) from e + + region = resolve_region(backend, session_region=session.region_name) + if region is None: + raise GenkitError( + status='FAILED_PRECONDITION', + message=f'Anthropic(backend=AmazonBedrock()) needs an AWS region: {_AWS_REGION_FIX}', + ) + + if check_credentials: + try: + credentials = session.get_credentials() + if credentials is None: + raise GenkitError( + status='FAILED_PRECONDITION', + message=f'Anthropic(backend=AmazonBedrock()) found no AWS credentials: {_AWS_CREDS_FIX}', + ) + credentials.get_frozen_credentials() + except GenkitError: + raise + except BotoCoreError as e: + raise GenkitError( + status='FAILED_PRECONDITION', + message=f'Anthropic(backend=AmazonBedrock()) could not resolve AWS credentials: {_AWS_CREDS_FIX}', + ) from e + + return region + + +# aws_region and aws_profile come from AmazonBedrock(region=..., profile=...), so they aren't client options. +_SET_BY_AMAZON_BEDROCK = frozenset({'aws_region', 'aws_profile'}) +# Explicit AWS keys or a Bedrock bearer token mean the caller brings their own credential. +_OWN_CREDENTIAL = frozenset({'aws_access_key', 'aws_secret_key', 'aws_session_token', 'api_key'}) + + +class AmazonBedrockBackend(Backend[AsyncAnthropicBedrock]): + """Claude on Amazon Bedrock Runtime, authenticated with AWS credentials or a Bedrock bearer token.""" + + # Bedrock doesn't offer every Anthropic API beta, so none are assumed. + default_betas = () + # Bedrock Runtime expects Bedrock / inference-profile IDs, not bare Anthropic API names. + include_static_catalog = False + + def __init__( + self, + config: AmazonBedrock, + *, + api_key: str | None, + base_url: str | None, + client_options: Mapping[str, Any] | None, + ) -> None: + """Validate the client settings at setup, on the user's line. + + Raises: + ValueError: ``api_key`` was passed on ``Anthropic(...)``, partial + AWS static keys were passed in ``client_options``, or a Bedrock + bearer token was combined with explicit AWS credentials/profile. + ImportError: The ``amazon-bedrock`` extra isn't installed. + TypeError: An unknown or repeated ``client_options`` key. + """ + if api_key is not None: + raise ValueError('Anthropic(backend=AmazonBedrock()) authenticates with AWS credentials; drop api_key') + require_boto3() + self._options = client_kwargs( + AsyncAnthropicBedrock, client_options, reserved=_SET_BY_AMAZON_BEDROCK, base_url=base_url + ) + has_access = self._options.get('aws_access_key') is not None + has_secret = self._options.get('aws_secret_key') is not None + if has_access != has_secret: + raise ValueError( + 'Anthropic(backend=AmazonBedrock()) client_options requires both aws_access_key and aws_secret_key' + ) + self._has_explicit_aws_creds = ( + config.profile is not None or has_access or has_secret or self._options.get('aws_session_token') is not None + ) + if self._has_bearer_token() and self._has_explicit_aws_creds: + raise ValueError( + 'Anthropic(backend=AmazonBedrock()) cannot combine a Bedrock bearer token ' + '(client_options api_key or AWS_BEARER_TOKEN_BEDROCK) with AWS credentials or profile=' + ) + self._config = config + self._region = resolve_region(config) + self._profile = config.profile + self._has_own_credential = bool(_OWN_CREDENTIAL & self._options.keys()) + self._ready = False + + def _has_bearer_token(self) -> bool: + return self._options.get('api_key') is not None or bool(os.environ.get('AWS_BEARER_TOKEN_BEDROCK')) + + def _new_client(self) -> AsyncAnthropicBedrock: + # Callers await request_client first, which resolves the region; passing + # self._region here lets tests inspect the configured region directly. + return AsyncAnthropicBedrock(aws_region=self._region, aws_profile=self._profile, **self._options) + + async def request_client(self, api_key: str | None) -> AsyncAnthropicBedrock: + """The plugin's client, once its AWS region and credentials are verified. + + Raises: + GenkitError: FAILED_PRECONDITION for a ``context.secrets`` key, + conflicting bearer token + profile, missing region, or missing + AWS credentials. + """ + if api_key is not None: + raise GenkitError( + status='FAILED_PRECONDITION', + message=( + 'A per-request API key from context.secrets cannot be used: ' + 'Anthropic(backend=AmazonBedrock()) authenticates with AWS credentials.' + ), + ) + await self._prepare() + return self.client() + + def api_model_id(self, name: str) -> str: + """The Bedrock model ID or inference-profile ID as given.""" + return name + + async def list_model_ids(self) -> list[str]: + """Nothing: Bedrock Runtime has no Models API (listing requires a control-plane bedrock client).""" + return [] + + async def _prepare(self) -> None: + """Resolve the AWS region and verify credentials before the first client is built. + + A failure isn't cached, so the next call retries after the user logs in + or sets ``AWS_REGION``. + """ + if self._ready: + return + uses_bearer = self._has_bearer_token() + if uses_bearer and self._has_explicit_aws_creds: + raise GenkitError( + status='FAILED_PRECONDITION', + message=( + 'Anthropic(backend=AmazonBedrock()) cannot combine AWS_BEARER_TOKEN_BEDROCK ' + 'with explicit AWS credentials or profile=.' + ), + ) + check_credentials = not self._has_own_credential and not uses_bearer + self._region = await asyncio.to_thread( + load_aws_context, + self._config, + check_credentials=check_credentials, + ) + self._ready = True diff --git a/packages/genkit-anthropic/src/genkit_anthropic/_backend.py b/packages/genkit-anthropic/src/genkit_anthropic/_backend.py index d5e8ba36..8b162c1d 100644 --- a/packages/genkit-anthropic/src/genkit_anthropic/_backend.py +++ b/packages/genkit-anthropic/src/genkit_anthropic/_backend.py @@ -37,6 +37,11 @@ class Backend(ABC, Generic[ClientT_co]): # Sent on beta-surface calls that don't pass their own betas. default_betas: ClassVar[tuple[str, ...]] = () + # Whether list_actions() appends SUPPORTED_ANTHROPIC_MODELS to what the + # backend lists. True when the backend accepts bare Anthropic API ids + # (Anthropic API, Google Cloud); False for backends with their own id scheme + # (Amazon Bedrock Runtime). + include_static_catalog: ClassVar[bool] = True @abstractmethod def _new_client(self) -> ClientT_co: diff --git a/packages/genkit-anthropic/src/genkit_anthropic/_models.py b/packages/genkit-anthropic/src/genkit_anthropic/_models.py index c76fa6eb..72b491ec 100644 --- a/packages/genkit-anthropic/src/genkit_anthropic/_models.py +++ b/packages/genkit-anthropic/src/genkit_anthropic/_models.py @@ -36,6 +36,7 @@ APIStatusError, APITimeoutError, AsyncAnthropic, + AsyncAnthropicBedrock, AsyncAnthropicVertex, ) from anthropic.types import Message as AnthropicMessage @@ -61,7 +62,7 @@ TASK_BUDGET_BETA = 'task-budgets-2026-03-13' # Every SDK client AnthropicModel sends through; they share messages and beta.messages. -ClaudeClient: TypeAlias = AsyncAnthropic | AsyncAnthropicVertex +ClaudeClient: TypeAlias = AsyncAnthropic | AsyncAnthropicVertex | AsyncAnthropicBedrock class _ModelDumpable(Protocol): @@ -602,8 +603,20 @@ async def _generate_streaming( active_client = cast(Any, client or self.client) messages_client = active_client.beta.messages if use_beta else active_client.messages - - async with messages_client.stream(**params) as stream: + stream_params = params + if use_beta and not hasattr(messages_client, 'stream'): + # AsyncAnthropicBedrock.beta.messages exposes create() only, not stream(). + # Its _prepare_options() turns the anthropic-beta header into the body's + # anthropic_beta field on messages.stream(). + stream_params = dict(params) + betas = stream_params.pop('betas', None) + if betas: + headers = dict(stream_params.get('extra_headers') or {}) + headers['anthropic-beta'] = ','.join(str(beta) for beta in betas) + stream_params['extra_headers'] = headers + messages_client = active_client.messages + + async with messages_client.stream(**stream_params) as stream: async for chunk in stream: if chunk.type == 'content_block_start' and hasattr(chunk, 'content_block'): block = chunk.content_block diff --git a/packages/genkit-anthropic/src/genkit_anthropic/_plugin.py b/packages/genkit-anthropic/src/genkit_anthropic/_plugin.py index 609b4de0..68e013d5 100644 --- a/packages/genkit-anthropic/src/genkit_anthropic/_plugin.py +++ b/packages/genkit-anthropic/src/genkit_anthropic/_plugin.py @@ -26,6 +26,7 @@ ActionKind, Plugin, ) +from genkit_anthropic._amazon_bedrock import AmazonBedrock, AmazonBedrockBackend from genkit_anthropic._anthropic_api import AnthropicApiBackend from genkit_anthropic._backend import Backend from genkit_anthropic._config import AnthropicConfig @@ -40,7 +41,7 @@ def _backend_for( - config: GoogleCloud | None, + config: GoogleCloud | AmazonBedrock | None, *, api_key: str | None, base_url: str | None, @@ -48,20 +49,24 @@ def _backend_for( ) -> Backend[ClaudeClient]: """Turn the public ``backend=`` value into the backend that serves the models. - ``GoogleCloud`` is the public choice; ``GoogleCloudBackend`` implements it. - This is the only place a backend is picked; past it, the plugin treats - every backend the same. + ``GoogleCloud`` and ``AmazonBedrock`` are the public choices; their + ``*Backend`` classes implement them. This is the only place a backend is + picked; past it, the plugin treats every backend the same. Every backend takes the same arguments and rejects the ones it can't use. Raises: - TypeError: ``backend`` isn't ``None`` or a ``GoogleCloud``. + TypeError: ``backend`` isn't ``None``, ``GoogleCloud``, or ``AmazonBedrock``. """ if config is None: return AnthropicApiBackend(api_key=api_key, base_url=base_url, client_options=client_options) - if not isinstance(config, GoogleCloud): - raise TypeError(f'Anthropic backend must be GoogleCloud(...) or None, got {type(config).__name__}') - return GoogleCloudBackend(config, api_key=api_key, base_url=base_url, client_options=client_options) + if isinstance(config, GoogleCloud): + return GoogleCloudBackend(config, api_key=api_key, base_url=base_url, client_options=client_options) + if isinstance(config, AmazonBedrock): + return AmazonBedrockBackend(config, api_key=api_key, base_url=base_url, client_options=client_options) + raise TypeError( + f'Anthropic backend must be GoogleCloud(...), AmazonBedrock(...), or None, got {type(config).__name__}' + ) # Only this plugin's namespace. A vertexai/ paste is a different name — @@ -126,7 +131,7 @@ def __init__( base_url: str | None = None, api_version: Literal['stable', 'beta'] | None = None, client_options: Mapping[str, Any] | None = None, - backend: GoogleCloud | None = None, + backend: GoogleCloud | AmazonBedrock | None = None, ) -> None: """Initializes Anthropic plugin with given configuration. @@ -140,38 +145,41 @@ def __init__( # 2. Claude on Google Cloud, billed to your project (application default credentials) Anthropic(backend=GoogleCloud(project='bistro-prod')) - # 3. Refs, config and .prompt files don't change between the two - await ai.generate(model=Anthropic.claude('claude-sonnet-5-5'), prompt='Suggest a dish.') + # 3. Claude on Amazon Bedrock, billed to your AWS account + Anthropic(backend=AmazonBedrock(region='us-east-1')) ``` Args: api_key: Anthropic API key. Defaults to ``ANTHROPIC_API_KEY``. Not - used with ``backend=GoogleCloud(...)``. + used with ``backend=GoogleCloud(...)`` or ``backend=AmazonBedrock(...)``. base_url: Anthropic API origin with no ``/v1`` suffix, e.g. ``https://claude-proxy.example.com``; the SDK appends ``/v1/messages``. Defaults to ``ANTHROPIC_BASE_URL``, then the public API. A value ending in ``/v1`` raises. With - ``backend=GoogleCloud(...)`` it overrides the Google Cloud endpoint. + ``backend=GoogleCloud(...)`` or ``backend=AmazonBedrock(...)`` + it overrides the cloud endpoint. api_version: Default API surface unless overridden by per-request config. An explicit config ``apiVersion`` always takes precedence. Defaults to stable. client_options: Other SDK client settings, such as ``timeout``, ``max_retries``, ``default_headers``, or ``http_client`` - (``AsyncAnthropic``, or ``AsyncAnthropicVertex`` with - ``backend=GoogleCloud(...)``). + (``AsyncAnthropic``, ``AsyncAnthropicVertex`` with + ``backend=GoogleCloud(...)``, or ``AsyncAnthropicBedrock`` with + ``backend=AmazonBedrock(...)``). backend: Where the models are served. ``None`` (the default) is the - Anthropic API; ``GoogleCloud(project=..., location=...)`` - serves them from Google Cloud with application default - credentials. Needs the ``google-cloud`` extra. + Anthropic API; ``GoogleCloud(...)`` serves them from Google + Cloud (needs the ``google-cloud`` extra); ``AmazonBedrock(...)`` + serves them from Amazon Bedrock Runtime (needs the + ``amazon-bedrock`` extra). Raises: ValueError: If ``api_version`` is not ``'stable'``, ``'beta'``, or ``None``, the base URL ends in ``/v1``, or ``api_key`` is - passed with ``backend=GoogleCloud(...)``. - TypeError: If ``backend`` isn't a ``GoogleCloud``, or - ``client_options`` has a key the SDK client doesn't take or - repeats ``api_key`` or ``base_url``. - ImportError: ``backend=GoogleCloud(...)`` without the ``google-cloud`` extra. + passed with a cloud backend. + TypeError: If ``backend`` isn't ``GoogleCloud``, ``AmazonBedrock``, + or ``None``, or ``client_options`` has a key the SDK client + doesn't take or repeats ``api_key`` or ``base_url``. + ImportError: A cloud backend without its optional extra installed. """ if api_version not in (None, 'stable', 'beta'): raise ValueError("api_version must be 'stable', 'beta', or None") @@ -264,6 +272,8 @@ async def list_actions(self) -> list[Action]: model_ids = await self._backend.list_model_ids() except Exception as e: logger.warning('Failed to list Anthropic models, using static model list', error=str(e)) + if not self._backend.include_static_catalog: + return [] return [self._create_model_action(model_id) for model_id in SUPPORTED_ANTHROPIC_MODELS] seen: set[str] = set() @@ -272,10 +282,11 @@ async def list_actions(self) -> list[Action]: if model_id and model_id not in seen: seen.add(model_id) ordered_ids.append(model_id) - for model_id in SUPPORTED_ANTHROPIC_MODELS: - if model_id not in seen: - seen.add(model_id) - ordered_ids.append(model_id) + if self._backend.include_static_catalog: + for model_id in SUPPORTED_ANTHROPIC_MODELS: + if model_id not in seen: + seen.add(model_id) + ordered_ids.append(model_id) actions = [self._create_model_action(model_id) for model_id in ordered_ids] self._list_actions_cache = actions diff --git a/packages/genkit-anthropic/tests/anthropic_amazon_bedrock_test.py b/packages/genkit-anthropic/tests/anthropic_amazon_bedrock_test.py new file mode 100644 index 00000000..8be95dc3 --- /dev/null +++ b/packages/genkit-anthropic/tests/anthropic_amazon_bedrock_test.py @@ -0,0 +1,424 @@ +# 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 + +"""Tests for Anthropic(backend=AmazonBedrock(...)): Claude served from Amazon Bedrock Runtime.""" + +import asyncio +import builtins +import json +from dataclasses import FrozenInstanceError +from types import SimpleNamespace +from typing import Any +from unittest.mock import AsyncMock, MagicMock, patch + +import httpx +import pytest +from anthropic import AsyncAnthropicBedrock +from botocore.exceptions import NoCredentialsError, ProfileNotFound +from genkit_anthropic import AmazonBedrock, Anthropic, AnthropicConfig +from genkit_anthropic._amazon_bedrock import load_aws_context + +from genkit import FinishReason, Genkit, GenkitError + +_AWS_ENV = ( + 'AWS_REGION', + 'AWS_DEFAULT_REGION', + 'AWS_PROFILE', + 'AWS_ACCESS_KEY_ID', + 'AWS_SECRET_ACCESS_KEY', + 'AWS_SESSION_TOKEN', + 'AWS_BEARER_TOKEN_BEDROCK', + 'ANTHROPIC_BEDROCK_BASE_URL', + 'ANTHROPIC_API_KEY', +) + + +@pytest.fixture(autouse=True) +def _clean_env(monkeypatch: pytest.MonkeyPatch) -> None: + for name in _AWS_ENV: + monkeypatch.delenv(name, raising=False) + + +def _client(plugin: Anthropic) -> Any: # noqa: ANN401 - the SDK client under test + async def _get() -> Any: # noqa: ANN401 + return plugin._backend.client() + + return asyncio.run(_get()) + + +def _bedrock_message_json(text: str = 'Herb-Roasted Chicken') -> dict[str, Any]: + return { + 'id': 'msg_bedrock_1', + 'type': 'message', + 'role': 'assistant', + 'model': 'claude-sonnet-4-6', + 'content': [{'type': 'text', 'text': text}], + 'stop_reason': 'end_turn', + 'stop_sequence': None, + 'usage': {'input_tokens': 12, 'output_tokens': 6}, + } + + +def _bedrock_response(text: str = 'Herb-Roasted Chicken') -> Any: # noqa: ANN401 - stub SDK response + return SimpleNamespace( + content=[SimpleNamespace(type='text', text=text)], + stop_reason='end_turn', + usage=SimpleNamespace(input_tokens=12, output_tokens=6), + ) + + +def test_amazon_bedrock_builds_bedrock_client_with_region_and_profile() -> None: + """The plugin's client is AsyncAnthropicBedrock for the configured region and profile.""" + client = _client(Anthropic(backend=AmazonBedrock(region='us-west-2', profile='bistro-prod'))) + + assert isinstance(client, AsyncAnthropicBedrock) + assert client.aws_region == 'us-west-2' + assert client.aws_profile == 'bistro-prod' + + +def test_amazon_bedrock_reads_region_from_env(monkeypatch: pytest.MonkeyPatch) -> None: + """AWS_REGION wins over AWS_DEFAULT_REGION; an explicit region beats both.""" + monkeypatch.setenv('AWS_REGION', 'eu-central-1') + monkeypatch.setenv('AWS_DEFAULT_REGION', 'ap-northeast-1') + + assert _client(Anthropic(backend=AmazonBedrock())).aws_region == 'eu-central-1' + assert _client(Anthropic(backend=AmazonBedrock(region='us-east-2'))).aws_region == 'us-east-2' + + +def test_amazon_bedrock_falls_back_to_aws_default_region(monkeypatch: pytest.MonkeyPatch) -> None: + """AWS_DEFAULT_REGION is used when AWS_REGION is unset.""" + monkeypatch.setenv('AWS_DEFAULT_REGION', 'eu-west-1') + + assert _client(Anthropic(backend=AmazonBedrock())).aws_region == 'eu-west-1' + + +def test_amazon_bedrock_is_frozen() -> None: + """AmazonBedrock is a frozen value, so one instance can be shared safely.""" + backend = AmazonBedrock(region='us-east-1') + with pytest.raises(FrozenInstanceError): + backend.region = 'us-west-2' # type: ignore[misc] + + +def test_amazon_bedrock_rejects_top_level_api_key() -> None: + """An Anthropic API key can't authenticate Amazon Bedrock, so passing one fails at setup.""" + with pytest.raises(ValueError, match='drop api_key'): + Anthropic(backend=AmazonBedrock(region='us-east-1'), api_key='sk-ant-test') + + +def test_amazon_bedrock_validates_client_options_against_bedrock_client() -> None: + """Bedrock-specific options pass; Vertex/Anthropic-only options name AsyncAnthropicBedrock.""" + plugin = Anthropic( + backend=AmazonBedrock(region='us-east-1'), + client_options={'aws_access_key': 'ak', 'aws_secret_key': 'sk', 'max_retries': 1}, + ) + assert _client(plugin).max_retries == 1 + + with pytest.raises(TypeError, match='AsyncAnthropicBedrock accepts'): + Anthropic(backend=AmazonBedrock(region='us-east-1'), client_options={'project_id': 'p'}) + + +@pytest.mark.parametrize('key', ['aws_region', 'aws_profile']) +def test_amazon_bedrock_reserves_region_and_profile(key: str) -> None: + """AmazonBedrock(region=..., profile=...) owns these, so client_options can't contradict them.""" + with pytest.raises(TypeError, match=f'unexpected client_options key {key!r}'): + Anthropic(backend=AmazonBedrock(region='us-east-1'), client_options={key: 'other'}) + + +@pytest.mark.parametrize( + 'options', + [{'aws_access_key': 'ak'}, {'aws_secret_key': 'sk'}], + ids=['access-only', 'secret-only'], +) +def test_amazon_bedrock_rejects_partial_static_keys(options: dict[str, Any]) -> None: + """Passing only half of an AWS key pair fails at setup.""" + with pytest.raises(ValueError, match='both aws_access_key and aws_secret_key'): + Anthropic(backend=AmazonBedrock(region='us-east-1'), client_options=options) + + +def test_amazon_bedrock_rejects_bearer_token_with_profile(monkeypatch: pytest.MonkeyPatch) -> None: + """A Bedrock bearer token cannot be combined with an AWS profile or static credentials.""" + with pytest.raises(ValueError, match='cannot combine a Bedrock bearer token'): + Anthropic(backend=AmazonBedrock(region='us-east-1', profile='prod'), client_options={'api_key': 'tok'}) + + monkeypatch.setenv('AWS_BEARER_TOKEN_BEDROCK', 'env-tok') + with pytest.raises(ValueError, match='cannot combine a Bedrock bearer token'): + Anthropic(backend=AmazonBedrock(region='us-east-1', profile='prod')) + + +def test_amazon_bedrock_accepts_base_url() -> None: + """base_url overrides the Bedrock Runtime endpoint (e.g. a VPC PrivateLink endpoint).""" + client = _client( + Anthropic( + backend=AmazonBedrock(region='us-east-1'), + base_url='https://vpce-123.bedrock-runtime.us-east-1.vpce.amazonaws.com', + ) + ) + assert str(client.base_url).rstrip('/') == 'https://vpce-123.bedrock-runtime.us-east-1.vpce.amazonaws.com' + + +def test_amazon_bedrock_without_extra_names_install_command(monkeypatch: pytest.MonkeyPatch) -> None: + """Missing boto3 fails at setup with the uv add command for the extra.""" + real_import = builtins.__import__ + + def _missing_boto3(name: str, *args: Any, **kwargs: Any) -> Any: # noqa: ANN401 + if name == 'boto3' or name.startswith('boto3.'): + raise ModuleNotFoundError("No module named 'boto3'", name='boto3') + return real_import(name, *args, **kwargs) + + monkeypatch.setattr(builtins, '__import__', _missing_boto3) + + with pytest.raises(ImportError, match=r'genkit-anthropic\[amazon-bedrock\]'): + Anthropic(backend=AmazonBedrock(region='us-east-1')) + + +def test_load_aws_context_fails_loudly_without_region() -> None: + """Unlike AsyncAnthropicBedrock, missing region fails instead of silently routing to us-east-1.""" + session = MagicMock() + session.region_name = None + with patch('boto3.Session', return_value=session), pytest.raises(GenkitError) as exc_info: + load_aws_context(AmazonBedrock(), check_credentials=True) + + assert exc_info.value.status == 'FAILED_PRECONDITION' + assert 'AmazonBedrock(region=...)' in str(exc_info.value) + assert 'AWS_REGION' in str(exc_info.value) + + +def test_load_aws_context_reads_region_from_profile() -> None: + """When no arg or env var is set, region comes from ~/.aws/config via the boto3 session.""" + session = MagicMock() + session.region_name = 'eu-west-2' + creds = MagicMock() + session.get_credentials.return_value = creds + + with patch('boto3.Session', return_value=session) as session_cls: + assert load_aws_context(AmazonBedrock(profile='kitchen'), check_credentials=True) == 'eu-west-2' + + session_cls.assert_called_once_with(profile_name='kitchen') + creds.get_frozen_credentials.assert_called_once() + + +def test_load_aws_context_missing_profile_fails_precondition() -> None: + """An unknown AWS profile fails as FAILED_PRECONDITION naming the profile.""" + with ( + patch('boto3.Session', side_effect=ProfileNotFound(profile='ghost')), + pytest.raises(GenkitError) as exc_info, + ): + load_aws_context(AmazonBedrock(region='us-east-1', profile='ghost'), check_credentials=True) + + assert exc_info.value.status == 'FAILED_PRECONDITION' + assert "'ghost'" in str(exc_info.value) + + +def test_load_aws_context_missing_or_broken_credentials_fails_precondition() -> None: + """Missing or unreadable AWS credentials become FAILED_PRECONDITION rather than a raw RuntimeError.""" + session = MagicMock() + session.region_name = 'us-east-1' + session.get_credentials.return_value = None + + with patch('boto3.Session', return_value=session), pytest.raises(GenkitError) as exc_info: + load_aws_context(AmazonBedrock(region='us-east-1'), check_credentials=True) + assert exc_info.value.status == 'FAILED_PRECONDITION' + assert 'found no AWS credentials' in str(exc_info.value) + + creds = MagicMock() + creds.get_frozen_credentials.side_effect = NoCredentialsError() + session.get_credentials.return_value = creds + with patch('boto3.Session', return_value=session), pytest.raises(GenkitError) as exc_info: + load_aws_context(AmazonBedrock(region='us-east-1'), check_credentials=True) + assert exc_info.value.status == 'FAILED_PRECONDITION' + assert 'could not resolve AWS credentials' in str(exc_info.value) + + +@pytest.mark.asyncio +async def test_amazon_bedrock_prepare_retries_after_failure_and_caches_success() -> None: + """A failed AWS lookup is not cached; once credentials appear, preparation runs once.""" + plugin = Anthropic(backend=AmazonBedrock(region='us-east-1')) + with patch( + 'genkit_anthropic._amazon_bedrock.load_aws_context', + side_effect=[GenkitError(status='FAILED_PRECONDITION', message='no creds'), 'us-east-1'], + ) as load_ctx: + with pytest.raises(GenkitError): + await plugin._backend.request_client(None) + first = await plugin._backend.request_client(None) + second = await plugin._backend.request_client(None) + + assert first is second + assert load_ctx.call_count == 2 + + +@pytest.mark.asyncio +async def test_amazon_bedrock_bearer_token_skips_sigv4_credential_check(monkeypatch: pytest.MonkeyPatch) -> None: + """AWS_BEARER_TOKEN_BEDROCK authenticates without probing boto3 credentials.""" + monkeypatch.setenv('AWS_BEARER_TOKEN_BEDROCK', 'bedrock-token') + plugin = Anthropic(backend=AmazonBedrock(region='us-east-1')) + with patch('boto3.Session') as session_cls: + client = await plugin._backend.request_client(None) + + assert isinstance(client, AsyncAnthropicBedrock) + assert client.api_key == 'bedrock-token' + session_cls.assert_not_called() + + +@pytest.mark.asyncio +async def test_amazon_bedrock_rejects_secrets_key_before_probing_aws() -> None: + """A context.secrets key cannot bill an AWS account and fails before touching AWS.""" + plugin = Anthropic(backend=AmazonBedrock()) + ai = Genkit(plugins=[plugin]) + with ( + patch('genkit_anthropic._amazon_bedrock.load_aws_context') as load_ctx, + patch('anthropic.resources.messages.AsyncMessages.create', AsyncMock()) as create, + ): + response = await ai.generate( + model=Anthropic.claude('global.anthropic.claude-sonnet-4-6'), + prompt='Suggest a dish.', + context={'secrets': {'api_key': 'tenant-secret-key'}}, + ) + + assert response.finish_reason == FinishReason.FAILED + assert response.error is not None + assert response.error.status == 'FAILED_PRECONDITION' + assert 'AWS credentials' in response.error.message + assert 'tenant-secret-key' not in response.error.message + load_ctx.assert_not_called() + create.assert_not_called() + + +@pytest.mark.asyncio +async def test_amazon_bedrock_list_actions_does_not_advertise_bare_anthropic_ids() -> None: + """Bedrock Runtime rejects bare Anthropic names like claude-sonnet-5-5, so list_actions stays empty.""" + plugin = Anthropic(backend=AmazonBedrock(region='us-east-1')) + assert await plugin.list_actions() == [] + + +@pytest.mark.asyncio +async def test_amazon_bedrock_generate_sends_bedrock_invoke_request() -> None: + """End-to-end generate hits Bedrock Runtime /model//invoke with AnthropicConfig fields.""" + captured: list[dict[str, Any]] = [] + + def handler(request: httpx.Request) -> httpx.Response: + captured.append({ + 'url': str(request.url), + 'auth': request.headers.get('authorization'), + 'body': json.loads(request.content.decode()), + }) + return httpx.Response(200, json=_bedrock_message_json('Grilled Sea Bass')) + + async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as http_client: + ai = Genkit( + plugins=[ + Anthropic( + backend=AmazonBedrock(region='us-west-2'), + client_options={'api_key': 'test-bedrock-token', 'http_client': http_client}, + ) + ] + ) + res = await ai.generate( + model=Anthropic.claude('global.anthropic.claude-sonnet-4-6'), + prompt='Suggest a fish dish.', + config=AnthropicConfig(thinking='adaptive', effort='medium'), + ) + + assert res.text == 'Grilled Sea Bass' + assert len(captured) == 1 + assert captured[0]['url'] == ( + 'https://bedrock-runtime.us-west-2.amazonaws.com/model/global.anthropic.claude-sonnet-4-6/invoke' + ) + assert captured[0]['auth'] == 'Bearer test-bedrock-token' + assert captured[0]['body']['anthropic_version'] == 'bedrock-2023-05-31' + assert captured[0]['body']['thinking'] == {'type': 'adaptive'} + assert captured[0]['body']['output_config'] == {'effort': 'medium'} + + +@pytest.mark.asyncio +async def test_amazon_bedrock_beta_generate_sends_only_field_required_betas() -> None: + """Anthropic API default betas stay off Bedrock; task_budget still brings its header.""" + captured: list[dict[str, Any]] = [] + + def handler(request: httpx.Request) -> httpx.Response: + captured.append(json.loads(request.content.decode())) + return httpx.Response(200, json=_bedrock_message_json('Done')) + + async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as http_client: + ai = Genkit( + plugins=[ + Anthropic( + backend=AmazonBedrock(region='us-east-1'), + client_options={'api_key': 'test-bedrock-token', 'http_client': http_client}, + ) + ] + ) + await ai.generate( + model=Anthropic.claude('global.anthropic.claude-sonnet-4-6'), + prompt='Suggest a dish.', + config={'apiVersion': 'beta'}, + ) + await ai.generate( + model=Anthropic.claude('global.anthropic.claude-sonnet-4-6'), + prompt='Suggest a dish.', + config={'taskBudget': 20000}, + ) + + assert 'anthropic_beta' not in captured[0] + assert captured[1]['anthropic_beta'] == ['task-budgets-2026-03-13'] + + +@pytest.mark.asyncio +async def test_amazon_bedrock_beta_streaming_falls_back_to_messages_stream_with_header() -> None: + """AsyncAnthropicBedrock.beta.messages lacks .stream(); beta streaming routes via messages.stream.""" + plugin = Anthropic( + backend=AmazonBedrock(region='us-east-1'), + client_options={'api_key': 'test-bedrock-token'}, + ) + ai = Genkit(plugins=[plugin]) + client = await plugin._backend.request_client(None) + assert not hasattr(client.beta.messages, 'stream') + + class _FakeStream: + async def __aenter__(self) -> '_FakeStream': + return self + + async def __aexit__(self, *args: object) -> None: + return None + + def __aiter__(self) -> '_FakeStream': + self._events = iter([ + SimpleNamespace(type='content_block_delta', delta=SimpleNamespace(type='text_delta', text='Ok')) + ]) + return self + + async def __anext__(self) -> Any: # noqa: ANN401 + try: + return next(self._events) + except StopIteration as e: + raise StopAsyncIteration from e + + async def get_final_message(self) -> Any: # noqa: ANN401 + return _bedrock_response('Ok') + + with patch.object(client.messages, 'stream', return_value=_FakeStream()) as stream_mock: + stream_response = ai.generate_stream( + model=Anthropic.claude('global.anthropic.claude-sonnet-4-6'), + prompt='Suggest a dish.', + config={'taskBudget': 20000}, + ) + chunks = [chunk.text async for chunk in stream_response.stream] + final = await stream_response.response + + assert chunks == ['Ok'] + assert final.text == 'Ok' + stream_mock.assert_called_once() + assert 'betas' not in stream_mock.call_args.kwargs + assert stream_mock.call_args.kwargs['extra_headers'] == {'anthropic-beta': 'task-budgets-2026-03-13'} diff --git a/packages/genkit-anthropic/tests/anthropic_google_cloud_test.py b/packages/genkit-anthropic/tests/anthropic_google_cloud_test.py index 79475fdb..47f71c99 100644 --- a/packages/genkit-anthropic/tests/anthropic_google_cloud_test.py +++ b/packages/genkit-anthropic/tests/anthropic_google_cloud_test.py @@ -249,6 +249,7 @@ async def test_google_cloud_retries_credentials_after_a_failed_load(fake_adc: Ma await plugin._backend.request_client(None) client = await plugin._backend.request_client(None) + assert isinstance(client, AsyncAnthropicVertex) assert client.credentials is FAKE_CREDENTIALS assert fake_adc.call_count == 2 diff --git a/uv.lock b/uv.lock index ff0edd59..cca75d3c 100644 --- a/uv.lock +++ b/uv.lock @@ -172,6 +172,10 @@ wheels = [ ] [package.optional-dependencies] +bedrock = [ + { name = "boto3" }, + { name = "botocore" }, +] vertex = [ { name = "google-auth", extra = ["requests"] }, ] @@ -1736,6 +1740,9 @@ dependencies = [ ] [package.optional-dependencies] +amazon-bedrock = [ + { name = "anthropic", extra = ["bedrock"] }, +] google-cloud = [ { name = "anthropic", extra = ["vertex"] }, ] @@ -1743,10 +1750,11 @@ google-cloud = [ [package.metadata] requires-dist = [ { name = "anthropic", specifier = ">=0.96.0,<1" }, + { name = "anthropic", extras = ["bedrock"], marker = "extra == 'amazon-bedrock'", specifier = ">=0.96.0,<1" }, { name = "anthropic", extras = ["vertex"], marker = "extra == 'google-cloud'", specifier = ">=0.96.0,<1" }, { name = "genkit", editable = "packages/genkit" }, ] -provides-extras = ["google-cloud"] +provides-extras = ["google-cloud", "amazon-bedrock"] [[package]] name = "genkit-django"