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-openai/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,8 @@ version = "0.14.0"
[project.optional-dependencies]
# OpenAICompatible(backend=GoogleCloud()): google-auth for application default credentials.
google-cloud = ["google-auth[requests]>=2.14.1"]
# OpenAICompatible(backend=AmazonBedrock()): boto3 and botocore for AWS SigV4 signing.
amazon-bedrock = ["boto3>=1.37.24,<2", "botocore>=1.37.24,<2"]

[project.urls]
"Bug Tracker" = "https://github.com/genkit-ai/genkit-python/issues"
Expand Down
6 changes: 5 additions & 1 deletion packages/genkit-openai/src/genkit_openai/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,9 @@
``OpenAICompatible(backend=GoogleCloud())`` serves Model Garden's
OpenAI-compatible models (Llama, Mistral and others) under ``modelgarden/``
by default, or any ``name=`` you pick (``uv add 'genkit-openai[google-cloud]'``).
``OpenAICompatible(backend=AmazonBedrock())`` serves Amazon Bedrock's
OpenAI-compatible models under ``bedrock/`` by default, or any ``name=`` you
pick (``uv add 'genkit-openai[amazon-bedrock]'``).

Example:
```python
Expand Down Expand Up @@ -65,9 +68,10 @@ async def main() -> None:
- OpenAI documentation: https://platform.openai.com/docs/
"""

from ._amazon_bedrock import AmazonBedrock
from ._compatible import OpenAICompatible
from ._google_cloud import GoogleCloud
from ._openai_plugin import Mistral, OpenAI
from ._typing import OpenAIConfig

__all__ = ['GoogleCloud', 'Mistral', 'OpenAI', 'OpenAICompatible', 'OpenAIConfig']
__all__ = ['AmazonBedrock', 'GoogleCloud', 'Mistral', 'OpenAI', 'OpenAICompatible', 'OpenAIConfig']
333 changes: 333 additions & 0 deletions packages/genkit-openai/src/genkit_openai/_amazon_bedrock.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,333 @@
# 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's OpenAI-compatible endpoint as a backend for OpenAICompatible."""

import asyncio
import os
from collections.abc import Mapping
from dataclasses import dataclass
from typing import Any, cast
from urllib.parse import urlsplit

import httpx
from openai import AsyncOpenAI

from genkit import GenkitError
from genkit.plugin_api import loop_local_client
from genkit_openai._openai_plugin import ApiKey, _client_kwargs

# Default namespace for OpenAICompatible(backend=AmazonBedrock()) when name= isn't passed.
BEDROCK_NAME = 'bedrock'
_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'
)
# AmazonBedrockServer supplies SigV4 or AWS_BEARER_TOKEN_BEDROCK, so client_options cannot set api_key.
_SET_BY_AMAZON_BEDROCK = frozenset({'api_key'})
_STRIP_BEFORE_SIGN = frozenset({'authorization', 'connection', 'x-amz-date', 'x-amz-security-token'})


@dataclass(frozen=True, kw_only=True)
class AmazonBedrock:
"""Serve Amazon Bedrock's OpenAI-compatible models from an AWS account.

Pass it as ``OpenAICompatible(backend=AmazonBedrock(...))``. Requests go to
``https://bedrock-runtime.<region>.amazonaws.com/openai/v1`` (or ``base_url=``,
for example a Bedrock Mantle endpoint or VPC PrivateLink endpoint) and
authenticate with the AWS credential chain (SigV4) or a Bedrock bearer
token (``AWS_BEARER_TOKEN_BEDROCK``). Models register as ``bedrock/<id>`` by
default, or ``<name>/<id>`` when you pass ``name=`` to ``OpenAICompatible``.

Example:
```python
from genkit import Genkit
from genkit_openai import AmazonBedrock, OpenAICompatible

# 1. Amazon Bedrock through your AWS credentials or AWS_BEARER_TOKEN_BEDROCK
bedrock = OpenAICompatible(backend=AmazonBedrock(region='us-west-2'))
ai = Genkit(plugins=[bedrock])

# 2. The ref for any Bedrock model served on the OpenAI-compatible endpoint
res = await ai.generate(model=bedrock.model('openai.gpt-oss-20b-1:0'), prompt='Suggest a dish.')
print(res.text)
# => Grilled salmon with lemon and dill
```

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(config: AmazonBedrock, *, session_region: str | None = None) -> str | None:
"""The region from the argument, AWS env vars, or the boto3 session; None if unset."""
return (
config.region or os.environ.get('AWS_REGION') or os.environ.get('AWS_DEFAULT_REGION') or session_region or None
)


def bedrock_base_url(*, region: str) -> str:
"""Amazon Bedrock Runtime's OpenAI-compatible endpoint; the SDK appends ``/chat/completions``."""
return f'https://bedrock-runtime.{region}.amazonaws.com/openai/v1'


def _signing_service(base_url: str) -> str:
"""SigV4 signing service name: ``bedrock-mantle`` on Mantle hosts, ``bedrock`` on Bedrock Runtime."""
host = (urlsplit(base_url).hostname or '').lower()
return 'bedrock-mantle' if host.startswith('bedrock-mantle.') else 'bedrock'


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(
'OpenAICompatible(backend=AmazonBedrock()) needs the amazon-bedrock extra: '
"uv add 'genkit-openai[amazon-bedrock]'"
) from e


def load_aws_context(config: AmazonBedrock, *, need_credentials: bool) -> tuple[str, Any]:
"""Resolve the AWS region and SigV4 credentials (blocking: may hit IMDS/SSO).

Returns:
``(region, credentials)``. ``credentials`` is ``None`` when
``need_credentials`` is False (Bedrock bearer-token auth).

Raises:
GenkitError: FAILED_PRECONDITION when the AWS profile is missing, no
region resolves (there is deliberately no ``us-east-1`` fallback),
or no AWS credentials can be resolved.
"""
region = resolve_region(config)
if region is not None and not need_credentials:
return region, None

# 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=config.profile)
except ProfileNotFound as e:
raise GenkitError(
status='FAILED_PRECONDITION',
message=f'OpenAICompatible(backend=AmazonBedrock()) could not find AWS profile {config.profile!r}: {e}',
cause=e,
) from e

region = resolve_region(config, session_region=session.region_name)
if region is None:
raise GenkitError(
status='FAILED_PRECONDITION',
message=f'OpenAICompatible(backend=AmazonBedrock()) needs an AWS region: {_AWS_REGION_FIX}',
)

if not need_credentials:
return region, None

try:
credentials = session.get_credentials()
if credentials is None:
raise GenkitError(
status='FAILED_PRECONDITION',
message=f'OpenAICompatible(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'OpenAICompatible(backend=AmazonBedrock()) could not resolve AWS credentials: {_AWS_CREDS_FIX}',
cause=e,
) from e

return region, credentials


class _SigV4OpenAI(AsyncOpenAI):
"""``AsyncOpenAI`` that signs each outgoing request with AWS SigV4.

Overrides the OpenAI SDK's built-in ``_prepare_request`` hook (the same
Stainless hook Anthropic uses in ``AsyncAnthropicBedrock``), so custom
``http_client``, ``timeout``, and ``max_retries`` options keep working.
"""

def __init__(
self,
*,
aws_credentials: Any, # noqa: ANN401 - botocore credentials are untyped
aws_region: str,
aws_service: str,
**kwargs: Any, # noqa: ANN401 - forwarded AsyncOpenAI options
) -> None:
super().__init__(api_key='', **kwargs)
self._aws_credentials = aws_credentials
self._aws_region = aws_region
self._aws_service = aws_service

@property
def auth_headers(self) -> dict[str, str]:
return {}

async def _prepare_request(self, request: httpx.Request) -> None:
# Optional dependency, checked by require_boto3 at setup.
from botocore.auth import SigV4Auth # noqa: PLC0415
from botocore.awsrequest import AWSRequest # noqa: PLC0415
from botocore.exceptions import BotoCoreError # noqa: PLC0415

try:
frozen = await asyncio.to_thread(self._aws_credentials.get_frozen_credentials)
except BotoCoreError as e:
raise GenkitError(
status='FAILED_PRECONDITION',
message=(
f'OpenAICompatible(backend=AmazonBedrock()) could not refresh AWS credentials: {_AWS_CREDS_FIX}'
),
cause=e,
) from e

headers = {k: v for k, v in request.headers.items() if k.lower() not in _STRIP_BEFORE_SIGN}
aws_request = AWSRequest(
method=request.method.upper(), url=str(request.url), headers=headers, data=request.read()
)
SigV4Auth(frozen, self._aws_service, self._aws_region).add_auth(aws_request)
prepared = aws_request.prepare()
for key, value in prepared.headers.items():
if value is not None:
request.headers[key] = value


class AmazonBedrockServer:
"""Amazon Bedrock's OpenAI-compatible endpoint, authenticated with AWS SigV4 or a Bedrock bearer token."""

def __init__(
self,
config: AmazonBedrock,
*,
api_key: ApiKey | None,
base_url: str | None,
client_options: Mapping[str, Any] | None,
) -> None:
"""Validate Amazon Bedrock settings at setup, on the user's line.

Raises:
ValueError: ``api_key`` was passed on ``OpenAICompatible(...)``, or
``AWS_BEARER_TOKEN_BEDROCK`` was combined with ``profile=``.
ImportError: The ``amazon-bedrock`` extra isn't installed.
TypeError: An unknown, reserved, or repeated ``client_options`` key.
"""
if api_key is not None:
raise ValueError(
'OpenAICompatible(backend=AmazonBedrock()) authenticates with AWS credentials; drop api_key'
)
require_boto3()
options = _client_kwargs(
api_key=None,
base_url=base_url,
client_options=client_options,
plugin='OpenAICompatible',
reserved=_SET_BY_AMAZON_BEDROCK,
)
if config.profile is not None and os.environ.get('AWS_BEARER_TOKEN_BEDROCK'):
raise ValueError(
'OpenAICompatible(backend=AmazonBedrock()) cannot combine AWS_BEARER_TOKEN_BEDROCK with profile='
)
self._config = config
self._base_url: str | None = options.pop('base_url', None)
self._options = options
self._region: str | None = resolve_region(config)
self._bearer_token: str | None = None
self._credentials: Any = None
self._ready = False

@loop_local_client
def _client(self) -> AsyncOpenAI:
# Only request_client builds the client, after _prepare resolved region and auth.
region = cast(str, self._region)
base_url = self._base_url or bedrock_base_url(region=region)
if self._bearer_token is not None:
return AsyncOpenAI(base_url=base_url, api_key=self._bearer_token, **self._options)
return _SigV4OpenAI(
aws_credentials=self._credentials,
aws_region=region,
aws_service=_signing_service(base_url),
base_url=base_url,
**self._options,
)

async def request_client(self, api_key: str | None) -> AsyncOpenAI:
"""The client, once 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: '
'OpenAICompatible(backend=AmazonBedrock()) authenticates with AWS credentials.'
),
)
await self._prepare()
return self._client()

async def model_ids(self) -> list[str]:
"""Nothing: Bedrock Runtime's ``/openai/v1`` endpoint has no ``/models``; any id resolves when called."""
return []

async def _prepare(self) -> None:
"""Resolve region and credentials once (in a thread); a failure isn't cached."""
if self._ready:
return
bearer_token = os.environ.get('AWS_BEARER_TOKEN_BEDROCK') or None
if bearer_token is not None and self._config.profile is not None:
raise GenkitError(
status='FAILED_PRECONDITION',
message=(
'OpenAICompatible(backend=AmazonBedrock()) cannot combine AWS_BEARER_TOKEN_BEDROCK with profile=.'
),
)
region, credentials = await asyncio.to_thread(
load_aws_context,
self._config,
need_credentials=bearer_token is None,
)
self._region = region
self._bearer_token = bearer_token
self._credentials = credentials
self._ready = True
Loading
Loading