2121from ..types .exceptions import ContextWindowOverflowException , ModelThrottledException
2222from ..types .streaming import StreamEvent
2323from ..types .tools import ToolChoice , ToolResult , ToolSpec , ToolUse
24+ from ._openai_bedrock import AwsConfig , resolve_bedrock_client_args
2425from ._validation import _has_location_source , validate_config_keys
2526from .model import BaseModelConfig , Model
2627
@@ -71,6 +72,7 @@ def __init__(
7172 self ,
7273 client : Client | None = None ,
7374 client_args : dict [str , Any ] | None = None ,
75+ aws_config : AwsConfig | None = None ,
7476 ** model_config : Unpack [OpenAIConfig ],
7577 ) -> None :
7678 """Initialize provider instance.
@@ -87,23 +89,53 @@ def __init__(
8789 Note: The client should not be shared across different asyncio event loops.
8890 client_args: Arguments for the OpenAI client (legacy approach).
8991 For a complete list of supported arguments, see https://pypi.org/project/openai/.
92+ May be combined with ``aws_config``; transport-level options like ``http_client``,
93+ ``timeout``, or ``default_headers`` are preserved, while ``base_url`` and
94+ ``api_key`` are always overridden by ``aws_config`` when both are set.
95+ aws_config: Route requests through Amazon Bedrock's Mantle (OpenAI-compatible)
96+ endpoint. Provide ``{"region": "us-east-1"}`` at minimum. Accepts optional
97+ ``credentials_provider`` (a botocore ``CredentialProvider``) and ``expiry``
98+ (a ``datetime.timedelta`` up to 12h). When set, a fresh bearer token is minted
99+ on every request via ``aws-bedrock-token-generator`` and the OpenAI client is
100+ pointed at ``https://bedrock-mantle.<region>.api.aws/v1``. Cannot be combined
101+ with a pre-built ``client``.
90102 **model_config: Configuration options for the OpenAI model.
91103
92104 Raises:
93- ValueError: If both `client` and `client_args` are provided.
105+ ValueError: If ``client`` is combined with ``client_args`` or ``aws_config``,
106+ or if ``aws_config`` is missing a region.
94107 """
95108 validate_config_keys (model_config , self .OpenAIConfig )
96109 self .config = dict (model_config )
97110
98- # Validate that only one client configuration method is provided
99- if client is not None and client_args is not None and len (client_args ) > 0 :
111+ # Validate that client configuration methods are mutually exclusive where they conflict.
112+ # client_args + aws_config is allowed — aws_config will override base_url / api_key only.
113+ client_args_provided = client_args is not None and len (client_args ) > 0
114+ if client is not None and client_args_provided :
100115 raise ValueError ("Only one of 'client' or 'client_args' should be provided, not both." )
116+ if aws_config is not None :
117+ if client is not None :
118+ raise ValueError ("'aws_config' cannot be combined with a pre-built 'client'." )
119+ if not aws_config .get ("region" ):
120+ raise ValueError ("aws_config must include a non-empty 'region'." )
101121
102122 self ._custom_client = client
103123 self .client_args = client_args or {}
124+ self ._aws_config = aws_config
104125
105126 logger .debug ("config=<%s> | initializing" , self .config )
106127
128+ def _resolve_client_args (self ) -> dict [str , Any ]:
129+ """Return the kwargs to pass to ``openai.AsyncOpenAI`` for the current request.
130+
131+ When ``aws_config`` is set, a fresh Bedrock Mantle bearer token is minted on every
132+ call and ``base_url`` / ``api_key`` are overridden. Any other entries from
133+ ``client_args`` (e.g. ``http_client``, ``timeout``) are preserved.
134+ """
135+ if self ._aws_config is not None :
136+ return resolve_bedrock_client_args (self ._aws_config , self .client_args )
137+ return self .client_args
138+
107139 @override
108140 def update_config (self , ** model_config : Unpack [OpenAIConfig ]) -> None : # type: ignore[override]
109141 """Update the OpenAI model configuration with the provided arguments.
@@ -590,11 +622,11 @@ async def _get_client(self) -> AsyncIterator[Any]:
590622 # Use the injected client (caller manages lifecycle)
591623 yield self ._custom_client
592624 else :
593- # Create a new client from client_args
625+ # Create a new client from resolved args (static client_args or freshly-minted Bedrock creds).
594626 # We initialize an OpenAI context on every request so as to avoid connection sharing in the underlying
595627 # httpx client. The asyncio event loop does not allow connections to be shared. For more details, please
596628 # refer to https://github.com/encode/httpx/discussions/2959.
597- async with openai .AsyncOpenAI (** self .client_args ) as client :
629+ async with openai .AsyncOpenAI (** self ._resolve_client_args () ) as client :
598630 yield client
599631
600632 @override
0 commit comments