diff --git a/packages/genkit-openai/pyproject.toml b/packages/genkit-openai/pyproject.toml index f544afd5..7fffb567 100644 --- a/packages/genkit-openai/pyproject.toml +++ b/packages/genkit-openai/pyproject.toml @@ -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" diff --git a/packages/genkit-openai/src/genkit_openai/__init__.py b/packages/genkit-openai/src/genkit_openai/__init__.py index d2302645..be2f48a8 100644 --- a/packages/genkit-openai/src/genkit_openai/__init__.py +++ b/packages/genkit-openai/src/genkit_openai/__init__.py @@ -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 @@ -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'] diff --git a/packages/genkit-openai/src/genkit_openai/_amazon_bedrock.py b/packages/genkit-openai/src/genkit_openai/_amazon_bedrock.py new file mode 100644 index 00000000..8a1ed875 --- /dev/null +++ b/packages/genkit-openai/src/genkit_openai/_amazon_bedrock.py @@ -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..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/`` by + default, or ``/`` 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 diff --git a/packages/genkit-openai/src/genkit_openai/_compatible.py b/packages/genkit-openai/src/genkit_openai/_compatible.py index fcc75996..f1d2673b 100644 --- a/packages/genkit-openai/src/genkit_openai/_compatible.py +++ b/packages/genkit-openai/src/genkit_openai/_compatible.py @@ -25,6 +25,7 @@ from genkit.embedder import EmbedContext, Embedder, EmbedderInfo, EmbedderSupports, EmbedRequest, EmbedResponse from genkit.model import Model, ModelContext, ModelInfo, ModelRef, ModelRequest from genkit.plugin_api import Action, ActionKind, Plugin, loop_local_client +from genkit_openai._amazon_bedrock import BEDROCK_NAME, AmazonBedrock, AmazonBedrockServer from genkit_openai._google_cloud import MODEL_GARDEN_NAME, GoogleCloud, GoogleCloudServer from genkit_openai._models._handler import OpenAIModelHandler from genkit_openai._models._mistral import is_mistral @@ -140,7 +141,7 @@ def __init__( def __init__( self, *, - backend: GoogleCloud, + backend: GoogleCloud | AmazonBedrock, name: str | None = None, base_url: str | None = None, client_options: Mapping[str, Any] | None = None, @@ -152,39 +153,41 @@ def __init__( base_url: str | None = None, api_key: ApiKey | None = None, client_options: Mapping[str, Any] | None = None, - backend: GoogleCloud | None = None, + backend: GoogleCloud | AmazonBedrock | None = None, ) -> None: - """Point the plugin at one OpenAI-compatible server, or at Model Garden. + """Point the plugin at one OpenAI-compatible server, Google Cloud, or Amazon Bedrock. Args: name: The namespace for this server's models and embedders, e.g. ``'openrouter'`` gives ``openrouter/``. Required without a - backend. With ``backend=GoogleCloud(...)`` it defaults to - ``'modelgarden'``; pass another name to use a different - namespace (for example, to run two regions or projects side by - side). + backend. Defaults to ``'modelgarden'`` with ``GoogleCloud(...)`` + and ``'bedrock'`` with ``AmazonBedrock(...)``; pass another name + to use a different namespace (for example, to run two regions + side by side). base_url: The server's API base URL up to and including ``/v1``, e.g. ``https://openrouter.ai/api/v1``; the SDK appends - ``/chat/completions``. Required without a backend. With - ``backend=GoogleCloud(...)`` it overrides the Model Garden endpoint. + ``/chat/completions``. Required without a backend. With a cloud + backend it overrides the derived endpoint. api_key: The server's key, or an async function that returns one before each request (for a token that expires). ``None`` sends no real key, for local servers. ``OPENAI_API_KEY`` is never - read. Not used with ``backend=GoogleCloud(...)``. + read. Not used with a cloud backend. client_options: Other ``AsyncOpenAI`` settings, such as ``timeout``, ``max_retries``, ``default_headers``, or ``http_client``. - backend: ``GoogleCloud(project=..., location=...)`` serves Model - Garden's OpenAI-compatible models with application default - credentials. Needs the ``google-cloud`` extra. + backend: ``GoogleCloud(...)`` serves Model Garden's OpenAI-compatible + models (needs the ``google-cloud`` extra); ``AmazonBedrock(...)`` + serves Amazon Bedrock's OpenAI-compatible models (needs the + ``amazon-bedrock`` extra). Raises: ValueError: ``name`` or ``base_url`` missing without a backend, a - ``name`` that is empty or contains ``/``, or ``api_key`` with - ``GoogleCloud``. - TypeError: ``backend`` isn't a ``GoogleCloud``, or a - ``client_options`` key ``AsyncOpenAI`` doesn't take. - ImportError: ``backend=GoogleCloud(...)`` without the ``google-cloud`` extra. + ``name`` that is empty or contains ``/``, or ``api_key`` with a + cloud backend. + TypeError: ``backend`` isn't ``GoogleCloud``, ``AmazonBedrock``, or + ``None``, or a ``client_options`` key ``AsyncOpenAI`` doesn't + take or that the backend reserves. + ImportError: A cloud backend without its optional extra installed. """ if backend is None: resolved_name = _validate_name(name) @@ -196,14 +199,21 @@ def __init__( options.setdefault('api_key', _NO_KEY) self._server: _Server = _BaseUrlServer(options) self.name = resolved_name - else: - if not isinstance(backend, GoogleCloud): - raise TypeError( - f'OpenAICompatible backend must be GoogleCloud(...) or None, got {type(backend).__name__}' - ) + elif isinstance(backend, GoogleCloud): resolved_name = _validate_name(MODEL_GARDEN_NAME if name is None else name) self._server = GoogleCloudServer(backend, api_key=api_key, base_url=base_url, client_options=client_options) self.name = resolved_name + elif isinstance(backend, AmazonBedrock): + resolved_name = _validate_name(BEDROCK_NAME if name is None else name) + self._server = AmazonBedrockServer( + backend, api_key=api_key, base_url=base_url, client_options=client_options + ) + self.name = resolved_name + else: + raise TypeError( + f'OpenAICompatible backend must be GoogleCloud(...), AmazonBedrock(...), or None, ' + f'got {type(backend).__name__}' + ) self._list_actions_cache: list[Action] | None = None def model(self, name: str, *, config: OpenAIConfig | None = None) -> ModelRef[OpenAIConfig]: diff --git a/packages/genkit-openai/tests/openai_compatible_amazon_bedrock_test.py b/packages/genkit-openai/tests/openai_compatible_amazon_bedrock_test.py new file mode 100644 index 00000000..7c981d68 --- /dev/null +++ b/packages/genkit-openai/tests/openai_compatible_amazon_bedrock_test.py @@ -0,0 +1,367 @@ +# 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 + +"""OpenAICompatible(backend=AmazonBedrock()): Bedrock's OpenAI-compatible models, against a fake endpoint.""" + +import builtins +import json +from dataclasses import FrozenInstanceError +from typing import Any, cast +from unittest.mock import MagicMock, patch + +import httpx +import pytest +from botocore.credentials import Credentials +from botocore.exceptions import NoCredentialsError, ProfileNotFound +from genkit_openai import AmazonBedrock, OpenAI, OpenAICompatible +from genkit_openai._amazon_bedrock import bedrock_base_url, load_aws_context + +from genkit import FinishReason, Genkit, GenkitError + +MODEL_ID = 'openai.gpt-oss-20b-1:0' +_AWS_ENV = ( + 'AWS_REGION', + 'AWS_DEFAULT_REGION', + 'AWS_PROFILE', + 'AWS_ACCESS_KEY_ID', + 'AWS_SECRET_ACCESS_KEY', + 'AWS_SESSION_TOKEN', + 'AWS_BEARER_TOKEN_BEDROCK', + 'OPENAI_API_KEY', +) + + +@pytest.fixture(autouse=True) +def _clean_env(monkeypatch: pytest.MonkeyPatch) -> None: + for name in _AWS_ENV: + monkeypatch.delenv(name, raising=False) + + +class FakeBedrock: + """Answers OpenAI chat completions like Bedrock Runtime's /openai/v1 endpoint, recording requests.""" + + def __init__(self) -> None: + self.requests: list[httpx.Request] = [] + + def handler(self, request: httpx.Request) -> httpx.Response: + self.requests.append(request) + body = json.loads(request.content) + return httpx.Response( + 200, + json={ + 'id': 'chatcmpl-bedrock-1', + 'object': 'chat.completion', + 'created': 0, + 'model': body['model'], + 'choices': [ + {'index': 0, 'message': {'role': 'assistant', 'content': 'Grilled salmon'}, 'finish_reason': 'stop'} + ], + 'usage': {'prompt_tokens': 1, 'completion_tokens': 1, 'total_tokens': 2}, + }, + ) + + +def _fake_credentials() -> Credentials: + return Credentials('AKIAEXAMPLE', 'SECRETEXAMPLE', 'SESSIONTOKEN') + + +def _bedrock( + server: FakeBedrock, + *, + name: str | None = None, + base_url: str | None = None, + **config: Any, # noqa: ANN401 +) -> OpenAICompatible: + http_client = httpx.AsyncClient(transport=httpx.MockTransport(server.handler)) + return OpenAICompatible( + name=name, + base_url=base_url, + backend=AmazonBedrock(**config), + client_options={'http_client': http_client}, + ) + + +@pytest.mark.asyncio +async def test_generate_signs_request_with_sigv4_for_bedrock_runtime() -> None: + """Default auth signs outgoing requests to bedrock-runtime..amazonaws.com/openai/v1 with SigV4.""" + server = FakeBedrock() + bedrock = _bedrock(server, region='us-west-2') + ai = Genkit(plugins=[bedrock]) + + with patch('genkit_openai._amazon_bedrock.load_aws_context', return_value=('us-west-2', _fake_credentials())): + response = await ai.generate(model=bedrock.model(MODEL_ID), prompt='Suggest a dish.') + + assert response.text == 'Grilled salmon' + request = server.requests[-1] + assert str(request.url) == 'https://bedrock-runtime.us-west-2.amazonaws.com/openai/v1/chat/completions' + auth_header = request.headers['authorization'] + assert auth_header.startswith('AWS4-HMAC-SHA256 ') + assert '/us-west-2/bedrock/aws4_request' in auth_header + assert 'x-amz-date' in request.headers + assert request.headers['x-amz-security-token'] == 'SESSIONTOKEN' + assert json.loads(request.content)['model'] == MODEL_ID + + +@pytest.mark.asyncio +async def test_mantle_base_url_signs_with_bedrock_mantle_service_name() -> None: + """Overriding base_url to a Bedrock Mantle host signs requests for the bedrock-mantle SigV4 service.""" + server = FakeBedrock() + bedrock = _bedrock(server, region='us-east-2', base_url='https://bedrock-mantle.us-east-2.api.aws/v1') + ai = Genkit(plugins=[bedrock]) + + with patch('genkit_openai._amazon_bedrock.load_aws_context', return_value=('us-east-2', _fake_credentials())): + await ai.generate(model=bedrock.model(MODEL_ID), prompt='hi') + + request = server.requests[-1] + assert str(request.url) == 'https://bedrock-mantle.us-east-2.api.aws/v1/chat/completions' + assert '/us-east-2/bedrock-mantle/aws4_request' in request.headers['authorization'] + + +@pytest.mark.asyncio +async def test_bearer_token_authenticates_without_sigv4(monkeypatch: pytest.MonkeyPatch) -> None: + """AWS_BEARER_TOKEN_BEDROCK sends a Bearer token and skips boto3 credential lookup.""" + monkeypatch.setenv('AWS_BEARER_TOKEN_BEDROCK', 'bedrock-bearer-tok') + server = FakeBedrock() + bedrock = _bedrock(server, region='us-east-1') + ai = Genkit(plugins=[bedrock]) + + with patch('boto3.Session') as session_cls: + response = await ai.generate(model=bedrock.model(MODEL_ID), prompt='hi') + + assert response.text == 'Grilled salmon' + assert server.requests[-1].headers['authorization'] == 'Bearer bedrock-bearer-tok' + session_cls.assert_not_called() + + +def test_bedrock_base_url_format() -> None: + """Bedrock Runtime's OpenAI-compatible URL uses the regional bedrock-runtime host.""" + assert bedrock_base_url(region='eu-central-1') == 'https://bedrock-runtime.eu-central-1.amazonaws.com/openai/v1' + + +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] + + +@pytest.mark.parametrize( + ('name', 'expected'), + [(None, 'bedrock'), ('bedrock', 'bedrock'), ('bedrock-eu', 'bedrock-eu')], +) +def test_name_defaults_to_bedrock_and_accepts_custom_names(name: str | None, expected: str) -> None: + """With AmazonBedrock the namespace defaults to bedrock, and any valid single-segment name is allowed.""" + plugin = OpenAICompatible(backend=AmazonBedrock(region='us-east-1'), name=name) + + assert plugin.name == expected + assert plugin.model(MODEL_ID).name == f'{expected}/{MODEL_ID}' + + +@pytest.mark.asyncio +async def test_custom_names_allow_multiple_regions_and_openai_side_by_side(monkeypatch: pytest.MonkeyPatch) -> None: + """Custom names let multiple AWS regions coexist with OpenAI() in one Genkit instance.""" + monkeypatch.setenv('AWS_BEARER_TOKEN_BEDROCK', 'tok') + us_server, eu_server = FakeBedrock(), FakeBedrock() + us = _bedrock(us_server, name='bedrock-us', region='us-west-2') + eu = _bedrock(eu_server, name='bedrock-eu', region='eu-central-1') + ai = Genkit(plugins=[OpenAI(api_key='sk-openai'), us, eu]) + + await ai.generate(model=us.model(MODEL_ID), prompt='hi') + await ai.generate(model=eu.model(MODEL_ID), prompt='hi') + + assert str(us_server.requests[-1].url).startswith('https://bedrock-runtime.us-west-2.amazonaws.com/openai/v1/') + assert str(eu_server.requests[-1].url).startswith('https://bedrock-runtime.eu-central-1.amazonaws.com/openai/v1/') + assert await ai.lookup_model('openai/gpt-4o') is not None + + +@pytest.mark.parametrize('bad_name', ['', 'bedrock/eu']) +def test_invalid_name_with_amazon_bedrock_raises(bad_name: str) -> None: + """Custom names still enforce the single-segment namespace rule.""" + with pytest.raises(ValueError, match='non-empty string without'): + OpenAICompatible(backend=AmazonBedrock(region='us-east-1'), name=bad_name) + + +def test_setup_validation_rejects_api_key_reserved_options_and_conflicts(monkeypatch: pytest.MonkeyPatch) -> None: + """Invalid auth combinations and reserved/duplicate options fail on the constructor line.""" + with pytest.raises(ValueError, match='drop api_key'): + OpenAICompatible(backend=AmazonBedrock(region='us-east-1'), **cast(Any, {'api_key': 'sk-x'})) + + with pytest.raises(TypeError, match="unexpected client_options key 'api_key'"): + OpenAICompatible(backend=AmazonBedrock(region='us-east-1'), client_options={'api_key': 'sk-x'}) + + with pytest.raises(TypeError, match='base_url both as an argument and in client_options'): + OpenAICompatible( + backend=AmazonBedrock(region='us-east-1'), + base_url='https://a.example.internal/v1', + client_options={'base_url': 'https://b.example.internal/v1'}, + ) + + monkeypatch.setenv('AWS_BEARER_TOKEN_BEDROCK', 'tok') + with pytest.raises(ValueError, match='cannot combine AWS_BEARER_TOKEN_BEDROCK with profile='): + OpenAICompatible(backend=AmazonBedrock(region='us-east-1', profile='prod')) + + +@pytest.mark.asyncio +async def test_client_options_base_url_overrides_endpoint_cleanly(monkeypatch: pytest.MonkeyPatch) -> None: + """base_url supplied via client_options overrides the derived URL without colliding on AsyncOpenAI.""" + monkeypatch.setenv('AWS_BEARER_TOKEN_BEDROCK', 'tok') + server = FakeBedrock() + http_client = httpx.AsyncClient(transport=httpx.MockTransport(server.handler)) + bedrock = OpenAICompatible( + backend=AmazonBedrock(region='us-east-1'), + client_options={'base_url': 'https://vpce.example.internal/openai/v1', 'http_client': http_client}, + ) + ai = Genkit(plugins=[bedrock]) + + await ai.generate(model=bedrock.model(MODEL_ID), prompt='hi') + + assert str(server.requests[-1].url) == 'https://vpce.example.internal/openai/v1/chat/completions' + + +def test_without_boto3_names_the_extra() -> None: + """Missing boto3 fails on the constructor line with the uv add command for the extra.""" + real_import = builtins.__import__ + + def _no_boto3(name: str, *args: Any, **kwargs: Any) -> Any: # noqa: ANN401 + if name == 'boto3' or name.startswith('boto3.'): + raise ModuleNotFoundError(name=name) + return real_import(name, *args, **kwargs) + + with ( + patch('builtins.__import__', _no_boto3), + pytest.raises(ImportError, match=r'genkit-openai\[amazon-bedrock\]'), + ): + OpenAICompatible(backend=AmazonBedrock(region='us-east-1')) + + +def test_load_aws_context_region_precedence_and_no_silent_default(monkeypatch: pytest.MonkeyPatch) -> None: + """Region resolves from arg -> AWS_REGION -> AWS_DEFAULT_REGION -> profile, and fails if unset.""" + session = MagicMock() + session.region_name = None + with patch('boto3.Session', return_value=session), pytest.raises(GenkitError) as exc_info: + load_aws_context(AmazonBedrock(), need_credentials=True) + assert exc_info.value.status == 'FAILED_PRECONDITION' + assert 'AmazonBedrock(region=...)' in str(exc_info.value) + + session.region_name = 'eu-west-2' + creds = MagicMock() + session.get_credentials.return_value = creds + with patch('boto3.Session', return_value=session) as session_cls: + region, resolved_creds = load_aws_context(AmazonBedrock(profile='kitchen'), need_credentials=True) + assert region == 'eu-west-2' + assert resolved_creds is creds + session_cls.assert_called_once_with(profile_name='kitchen') + + monkeypatch.setenv('AWS_DEFAULT_REGION', 'ap-northeast-1') + assert load_aws_context(AmazonBedrock(), need_credentials=False) == ('ap-northeast-1', None) + monkeypatch.setenv('AWS_REGION', 'us-east-2') + assert load_aws_context(AmazonBedrock(), need_credentials=False) == ('us-east-2', None) + assert load_aws_context(AmazonBedrock(region='us-west-2'), need_credentials=False) == ('us-west-2', None) + + +def test_load_aws_context_missing_profile_or_credentials_fails_precondition() -> None: + """Missing profile, missing credentials, and botocore credential errors map to FAILED_PRECONDITION.""" + 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'), need_credentials=True) + assert exc_info.value.status == 'FAILED_PRECONDITION' + assert "'ghost'" in str(exc_info.value) + + 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'), need_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'), need_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_failed_prepare_is_not_cached_and_retries_after_login() -> None: + """A failed AWS lookup isn't cached; once credentials resolve, preparation runs once.""" + server = FakeBedrock() + ai = Genkit(plugins=[_bedrock(server, region='us-east-1')]) + with patch( + 'genkit_openai._amazon_bedrock.load_aws_context', + side_effect=[ + GenkitError(status='FAILED_PRECONDITION', message='no creds'), + ('us-east-1', _fake_credentials()), + ], + ) as load_ctx: + first = await ai.generate(model=f'bedrock/{MODEL_ID}', prompt='hi') + second = await ai.generate(model=f'bedrock/{MODEL_ID}', prompt='hi') + third = await ai.generate(model=f'bedrock/{MODEL_ID}', prompt='hi') + + assert first.error is not None and first.error.status == 'FAILED_PRECONDITION' + assert second.text == 'Grilled salmon' + assert third.text == 'Grilled salmon' + assert load_ctx.call_count == 2 + + +@pytest.mark.asyncio +async def test_mid_run_expired_credentials_map_to_failed_precondition() -> None: + """If refreshable AWS credentials fail mid-run during SigV4 signing, the error is FAILED_PRECONDITION.""" + server = FakeBedrock() + ai = Genkit(plugins=[_bedrock(server, region='us-east-1')]) + creds = MagicMock() + creds.get_frozen_credentials.side_effect = NoCredentialsError() + + with patch('genkit_openai._amazon_bedrock.load_aws_context', return_value=('us-east-1', creds)): + response = await ai.generate(model=f'bedrock/{MODEL_ID}', prompt='hi') + + assert response.finish_reason == FinishReason.FAILED + assert response.error is not None + assert response.error.status == 'FAILED_PRECONDITION' + assert 'could not refresh AWS credentials' in response.error.message + assert server.requests == [] + + +@pytest.mark.asyncio +async def test_secrets_key_refused_before_probing_aws() -> None: + """A context.secrets key cannot bill an AWS account and fails before touching AWS.""" + server = FakeBedrock() + ai = Genkit(plugins=[_bedrock(server, region='us-east-1')]) + + with patch('genkit_openai._amazon_bedrock.load_aws_context') as load_ctx: + response = await ai.generate( + model=f'bedrock/{MODEL_ID}', + prompt='hi', + context={'secrets': {'api_key': 'sk-tenant-secret'}}, + ) + + assert response.error is not None + assert response.error.status == 'FAILED_PRECONDITION' + assert 'AWS credentials' in response.error.message + assert 'sk-tenant-secret' not in response.error.message + load_ctx.assert_not_called() + assert server.requests == [] + + +@pytest.mark.asyncio +async def test_lists_nothing_and_calls_no_models_endpoint() -> None: + """Bedrock Runtime's /openai/v1 has no /models, so list_actions stays empty and sends no request.""" + server = FakeBedrock() + bedrock = _bedrock(server, region='us-east-1') + + assert await bedrock.list_actions() == [] + assert server.requests == [] diff --git a/uv.lock b/uv.lock index f26fbb66..699eb2c0 100644 --- a/uv.lock +++ b/uv.lock @@ -1567,18 +1567,24 @@ dependencies = [ ] [package.optional-dependencies] +amazon-bedrock = [ + { name = "boto3" }, + { name = "botocore" }, +] google-cloud = [ { name = "google-auth", extra = ["requests"] }, ] [package.metadata] requires-dist = [ + { name = "boto3", marker = "extra == 'amazon-bedrock'", specifier = ">=1.37.24,<2" }, + { name = "botocore", marker = "extra == 'amazon-bedrock'", specifier = ">=1.37.24,<2" }, { name = "genkit", editable = "packages/genkit" }, { name = "google-auth", extras = ["requests"], marker = "extra == 'google-cloud'", specifier = ">=2.14.1" }, { name = "openai", specifier = ">=1.106.0,<3" }, { name = "strenum", marker = "python_full_version < '3.11'", specifier = ">=0.4.15" }, ] -provides-extras = ["google-cloud"] +provides-extras = ["google-cloud", "amazon-bedrock"] [[package]] name = "genkit-otel"