|
| 1 | +"""Internal helpers for routing OpenAI-compatible clients to Bedrock Mantle. |
| 2 | +
|
| 3 | +Converts a ``bedrock_mantle_config`` dict into the ``base_url`` and ``api_key`` that the |
| 4 | +OpenAI Python SDK consumes. Tokens are minted on demand via |
| 5 | +``aws_bedrock_token_generator.provide_token`` so long-running agents survive the |
| 6 | +bearer token's maximum lifetime. |
| 7 | +
|
| 8 | +``aws_bedrock_token_generator`` is part of the ``openai`` extras group |
| 9 | +(``pip install strands-agents[openai]``) but is *not* included in the ``litellm`` |
| 10 | +or ``sagemaker`` extras, which also pull in the ``openai`` package. The import is |
| 11 | +therefore lazy — it happens inside :func:`resolve_bedrock_client_args` so that |
| 12 | +those other extras never trigger an ``ImportError`` at module load. |
| 13 | +""" |
| 14 | + |
| 15 | +from __future__ import annotations |
| 16 | + |
| 17 | +from datetime import timedelta |
| 18 | +from typing import Any, TypedDict |
| 19 | + |
| 20 | +import boto3 |
| 21 | +from botocore.credentials import CredentialProvider |
| 22 | + |
| 23 | +_MANTLE_BASE_URL_TEMPLATE = "https://bedrock-mantle.{region}.api.aws/v1" |
| 24 | +_MANTLE_DOCS_URL = "https://docs.aws.amazon.com/bedrock/latest/userguide/inference-openai.html" |
| 25 | + |
| 26 | + |
| 27 | +class BedrockMantleConfig(TypedDict, total=False): |
| 28 | + """Config for routing an OpenAI-compatible client through Bedrock Mantle. |
| 29 | +
|
| 30 | + Attributes: |
| 31 | + region: AWS region hosting the Bedrock Mantle endpoint. If omitted, resolved |
| 32 | + from ``boto_session`` (if provided) or the standard boto3 chain |
| 33 | + (``AWS_REGION`` / ``AWS_DEFAULT_REGION`` / active profile / EC2 metadata). |
| 34 | + A :class:`ValueError` is raised if none resolve. |
| 35 | + boto_session: Optional :class:`boto3.Session` used to resolve the region when |
| 36 | + ``region`` is not provided. Useful for picking up a non-default profile |
| 37 | + without exporting env vars. |
| 38 | + credentials_provider: Optional botocore :class:`~botocore.credentials.CredentialProvider` |
| 39 | + forwarded to ``provide_token``. Omit to let the token generator use the |
| 40 | + standard AWS credential chain. |
| 41 | + expiry: Optional ``timedelta`` for the bearer token's lifetime, forwarded to |
| 42 | + ``provide_token``. Defaults to the generator's built-in lifetime when |
| 43 | + omitted. |
| 44 | + """ |
| 45 | + |
| 46 | + region: str |
| 47 | + boto_session: boto3.Session |
| 48 | + credentials_provider: CredentialProvider |
| 49 | + expiry: timedelta |
| 50 | + |
| 51 | + |
| 52 | +def _resolve_region(config: BedrockMantleConfig) -> str: |
| 53 | + """Resolve the AWS region, preferring explicit config then falling back to boto3. |
| 54 | +
|
| 55 | + Raises: |
| 56 | + ValueError: If no region can be resolved from the config, an attached session, |
| 57 | + or the standard boto3 credential chain. |
| 58 | + """ |
| 59 | + region = config.get("region") |
| 60 | + if region: |
| 61 | + return region |
| 62 | + |
| 63 | + session = config.get("boto_session") |
| 64 | + if session is not None and session.region_name: |
| 65 | + return str(session.region_name) |
| 66 | + |
| 67 | + # ``boto3.Session()`` with no args reads ``AWS_REGION`` / ``AWS_DEFAULT_REGION``, |
| 68 | + # the active profile, and falls back to EC2 instance metadata — the same chain |
| 69 | + # :class:`BedrockModel` uses. |
| 70 | + default_region = boto3.Session().region_name |
| 71 | + if default_region: |
| 72 | + return str(default_region) |
| 73 | + |
| 74 | + raise ValueError( |
| 75 | + "Could not resolve an AWS region for Bedrock Mantle. Pass 'region' in " |
| 76 | + "bedrock_mantle_config, attach a boto_session with a configured region, or set " |
| 77 | + f"AWS_REGION in the environment. See {_MANTLE_DOCS_URL} for supported regions." |
| 78 | + ) |
| 79 | + |
| 80 | + |
| 81 | +def resolve_bedrock_client_args( |
| 82 | + config: BedrockMantleConfig, client_args: dict[str, Any] | None = None |
| 83 | +) -> dict[str, Any]: |
| 84 | + """Resolve a ``BedrockMantleConfig`` (plus optional ``client_args``) into OpenAI client kwargs. |
| 85 | +
|
| 86 | + Mints a fresh bearer token on every call. Callers are expected to validate that |
| 87 | + ``client_args`` does not contain ``base_url`` or ``api_key`` before calling this |
| 88 | + function (typically at ``__init__`` time for fail-fast behavior). |
| 89 | +
|
| 90 | + Raises: |
| 91 | + ValueError: If no region can be resolved. |
| 92 | + ImportError: If ``aws-bedrock-token-generator`` is not installed. |
| 93 | + RuntimeError: If token minting fails (e.g. missing AWS credentials). |
| 94 | + """ |
| 95 | + region = _resolve_region(config) |
| 96 | + |
| 97 | + # ``aws-bedrock-token-generator`` is included in the ``openai`` extras group but not in |
| 98 | + # ``litellm`` or ``sagemaker`` (which also depend on the ``openai`` package). The lazy |
| 99 | + # import keeps those extras from hitting an ImportError at module load. |
| 100 | + try: |
| 101 | + from aws_bedrock_token_generator import provide_token |
| 102 | + except ImportError as e: |
| 103 | + raise ImportError( |
| 104 | + "bedrock_mantle_config requires the 'aws-bedrock-token-generator' package. " |
| 105 | + "Install it with: pip install strands-agents[openai]" |
| 106 | + ) from e |
| 107 | + |
| 108 | + # Only forward kwargs the user set; provide_token rejects expiry=None. |
| 109 | + token_kwargs: dict[str, Any] = {"region": region} |
| 110 | + if "credentials_provider" in config: |
| 111 | + token_kwargs["aws_credentials_provider"] = config["credentials_provider"] |
| 112 | + if "expiry" in config: |
| 113 | + token_kwargs["expiry"] = config["expiry"] |
| 114 | + |
| 115 | + try: |
| 116 | + token = provide_token(**token_kwargs) |
| 117 | + except Exception as e: |
| 118 | + raise RuntimeError( |
| 119 | + f"Failed to mint Bedrock Mantle bearer token for region '{region}'. " |
| 120 | + "Verify your AWS credentials and network connectivity." |
| 121 | + ) from e |
| 122 | + |
| 123 | + resolved: dict[str, Any] = dict(client_args or {}) |
| 124 | + resolved["base_url"] = _MANTLE_BASE_URL_TEMPLATE.format(region=region) |
| 125 | + resolved["api_key"] = token |
| 126 | + return resolved |
0 commit comments