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: 2 additions & 0 deletions packages/genkit-anthropic/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
6 changes: 6 additions & 0 deletions packages/genkit-anthropic/src/genkit_anthropic/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand Down
283 changes: 283 additions & 0 deletions packages/genkit-anthropic/src/genkit_anthropic/_amazon_bedrock.py
Original file line number Diff line number Diff line change
@@ -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
5 changes: 5 additions & 0 deletions packages/genkit-anthropic/src/genkit_anthropic/_backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
19 changes: 16 additions & 3 deletions packages/genkit-anthropic/src/genkit_anthropic/_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
APIStatusError,
APITimeoutError,
AsyncAnthropic,
AsyncAnthropicBedrock,
AsyncAnthropicVertex,
)
from anthropic.types import Message as AnthropicMessage
Expand All @@ -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):
Expand Down Expand Up @@ -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
Expand Down
Loading
Loading