-
Notifications
You must be signed in to change notification settings - Fork 4.8k
feat: Add AWS Bedrock client with SigV4 authentication #3170
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
prashanthkvs
wants to merge
2
commits into
openai:main
Choose a base branch
from
prashanthkvs:feat/aws-bedrock-mantle-sigv4
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,80 @@ | ||
| """Example: Using AwsOpenAI (sync) and AsyncAwsOpenAI (async) with SigV4 signing. | ||
|
|
||
| Requires: | ||
| - botocore installed (pip install botocore) | ||
| - AWS credentials configured (env vars, ~/.aws/credentials, IAM role, etc.) | ||
| - AWS_REGION or AWS_DEFAULT_REGION set (or pass region= explicitly) | ||
|
|
||
| Run: | ||
| export AWS_REGION=us-west-2 | ||
| PYTHONPATH=src python3 examples/aws_client.py | ||
| """ | ||
|
|
||
| import asyncio | ||
|
|
||
| from openai.lib.aws import AwsOpenAI, AsyncAwsOpenAI | ||
|
|
||
| # --- Synchronous usage --- | ||
|
|
||
| client = AwsOpenAI(region="us-west-2") | ||
|
|
||
| response = client.chat.completions.create( | ||
| model="openai.gpt-oss-120b", | ||
| messages=[{"role": "user", "content": "Hello, how are you?"}], | ||
| ) | ||
|
|
||
| print("Sync:", response.choices[0].message.content) | ||
|
|
||
|
|
||
| # --- Asynchronous usage --- | ||
|
|
||
|
|
||
| async def main() -> None: | ||
| async_client = AsyncAwsOpenAI(region="us-west-2") | ||
|
|
||
| response = await async_client.chat.completions.create( | ||
| model="openai.gpt-oss-120b", | ||
| messages=[{"role": "user", "content": "Hello from async!"}], | ||
| ) | ||
|
|
||
| print("Async:", response.choices[0].message.content) | ||
|
|
||
|
|
||
| asyncio.run(main()) | ||
|
|
||
|
|
||
| # --- Streaming usage (sync) --- | ||
|
|
||
| print("\nStreaming: ", end="") | ||
| stream = client.chat.completions.create( | ||
| model="openai.gpt-oss-120b", | ||
| messages=[{"role": "user", "content": "Count from 1 to 5."}], | ||
| stream=True, | ||
| ) | ||
| for chunk in stream: | ||
| delta = chunk.choices[0].delta.content | ||
| if delta: | ||
| print(delta, end="", flush=True) | ||
| print() | ||
|
|
||
|
|
||
| # --- Streaming usage (async) --- | ||
|
|
||
|
|
||
| async def stream_async() -> None: | ||
| async_client = AsyncAwsOpenAI(region="us-west-2") | ||
|
|
||
| print("Async streaming: ", end="") | ||
| stream = await async_client.chat.completions.create( | ||
| model="openai.gpt-oss-120b", | ||
| messages=[{"role": "user", "content": "Count from 1 to 5."}], | ||
| stream=True, | ||
| ) | ||
| async for chunk in stream: | ||
| delta = chunk.choices[0].delta.content | ||
| if delta: | ||
| print(delta, end="", flush=True) | ||
| print() | ||
|
|
||
|
|
||
| asyncio.run(stream_async()) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,144 @@ | ||
| """Example: Using AwsOpenAI with a custom credential provider and auto-refresh. | ||
|
|
||
| This shows how to: | ||
| 1. Use a custom credential provider that returns fresh credentials on each call | ||
| 2. Use botocore's RefreshableCredentials for automatic STS assume-role refresh | ||
| 3. Use an async credential provider with AsyncAwsOpenAI | ||
|
|
||
| Requires: | ||
| - botocore installed (pip install botocore) | ||
| - boto3 installed (pip install boto3) — for the STS assume-role example | ||
| - AWS credentials configured for the initial session | ||
| - AWS_REGION or AWS_DEFAULT_REGION set (or pass region= explicitly) | ||
|
|
||
| Run: | ||
| export AWS_REGION=us-west-2 | ||
| PYTHONPATH=src python3 examples/aws_credential_provider.py | ||
| """ | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import asyncio | ||
| from typing import Any, Callable | ||
| from dataclasses import dataclass | ||
|
|
||
| from openai.lib.aws import AwsOpenAI, AsyncAwsOpenAI | ||
|
|
||
| # --------------------------------------------------------------------------- | ||
| # 1. Simple custom credential provider | ||
| # --------------------------------------------------------------------------- | ||
|
|
||
|
|
||
| @dataclass | ||
| class MyCredentials: | ||
| """Minimal object satisfying the Credentials protocol.""" | ||
|
|
||
| access_key: str | ||
| secret_key: str | ||
| token: str | None = None | ||
|
|
||
|
|
||
| def my_credential_provider() -> MyCredentials: | ||
| """Return credentials from your own secret store, vault, etc. | ||
|
|
||
| This callable is invoked before every request, so returning fresh | ||
| credentials here is all you need for auto-refresh. | ||
| """ | ||
| # Replace with your actual credential fetching logic | ||
| return MyCredentials( | ||
| access_key="AKIA...", | ||
| secret_key="wJalr...", | ||
| token="FwoGZX...", # optional session token | ||
| ) | ||
|
|
||
|
|
||
| client = AwsOpenAI( | ||
| region="us-west-2", | ||
| credential_provider=my_credential_provider, | ||
| ) | ||
|
|
||
| response = client.chat.completions.create( | ||
| model="openai.gpt-oss-120b", | ||
| messages=[{"role": "user", "content": "Hello from custom credentials!"}], | ||
| ) | ||
| print("Custom provider:", response.choices[0].message.content) | ||
|
|
||
|
|
||
| # --------------------------------------------------------------------------- | ||
| # 2. Auto-refreshing STS assume-role credentials via botocore | ||
| # --------------------------------------------------------------------------- | ||
|
|
||
|
|
||
| def make_sts_credential_provider(role_arn: str, session_name: str = "bedrock-mantle") -> Callable[[], Any]: | ||
| """Create a credential provider that assumes an IAM role and auto-refreshes. | ||
|
|
||
| botocore's RefreshableCredentials handles expiry checks and refresh | ||
| transparently — accessing .access_key / .secret_key / .token on the | ||
| returned object triggers a refresh if the credentials are expired. | ||
| """ | ||
| import botocore.session # type: ignore[import-untyped, import-not-found] | ||
| import botocore.credentials # type: ignore[import-untyped, import-not-found] | ||
|
|
||
| session: Any = botocore.session.get_session() # pyright: ignore[reportUnknownVariableType, reportUnknownMemberType] | ||
| sts: Any = session.create_client("sts") # pyright: ignore[reportUnknownVariableType, reportUnknownMemberType] | ||
|
|
||
| def fetch_credentials() -> dict[str, Any]: | ||
| resp: Any = sts.assume_role(RoleArn=role_arn, RoleSessionName=session_name)["Credentials"] # pyright: ignore[reportUnknownVariableType, reportUnknownMemberType] | ||
| return { | ||
| "access_key": resp["AccessKeyId"], | ||
| "secret_key": resp["SecretAccessKey"], | ||
| "token": resp["SessionToken"], | ||
| "expiry_time": resp["Expiration"].isoformat(), # pyright: ignore[reportUnknownMemberType] | ||
| } | ||
|
|
||
| refreshable: Any = botocore.credentials.RefreshableCredentials.create_from_metadata( # pyright: ignore[reportUnknownVariableType, reportUnknownMemberType] | ||
| metadata=fetch_credentials(), | ||
| refresh_using=fetch_credentials, | ||
| method="sts-assume-role", | ||
| ) | ||
|
|
||
| # Return a provider that gives back the refreshable object. | ||
| # Accessing its attributes auto-refreshes when expired. | ||
| def provider() -> Any: | ||
| return refreshable # pyright: ignore[reportUnknownVariableType] | ||
|
|
||
| return provider | ||
|
|
||
|
|
||
| # Uncomment to use: | ||
| # sts_client = AwsOpenAI( | ||
| # region="us-west-2", | ||
| # credential_provider=make_sts_credential_provider("arn:aws:iam::123456789012:role/MyRole"), | ||
| # ) | ||
|
|
||
|
|
||
| # --------------------------------------------------------------------------- | ||
| # 3. Async credential provider | ||
| # --------------------------------------------------------------------------- | ||
|
|
||
|
|
||
| async def async_credential_provider() -> MyCredentials: | ||
| """An async provider — useful when credentials come from an async API.""" | ||
| # Simulate async credential fetch (e.g., from an async HTTP vault client) | ||
| await asyncio.sleep(0) | ||
| return MyCredentials( | ||
| access_key="AKIA...", | ||
| secret_key="wJalr...", | ||
| token="FwoGZX...", | ||
| ) | ||
|
|
||
|
|
||
| async def main() -> None: | ||
| async_client = AsyncAwsOpenAI( | ||
| region="us-west-2", | ||
| credential_provider=async_credential_provider, | ||
| ) | ||
|
|
||
| response = await async_client.chat.completions.create( | ||
| model="openai.gpt-oss-120b", | ||
| messages=[{"role": "user", "content": "Hello from async credentials!"}], | ||
| ) | ||
| print("Async provider:", response.choices[0].message.content) | ||
|
|
||
|
|
||
| asyncio.run(main()) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
src/openai/__init__.pyis Stainless-generated — theAwsOpenAI/AsyncAwsOpenAIexports added there would be dropped on the next generated release unless they're added to the generator config (similar to how theAzureOpenAIexports persist today). Thepyproject.tomlchange for the[aws]extra may have the same concern.@apcha-oai Could you advise on how you'd like the
__init__.pyexports andpyproject.tomldependency handled? Should these go through the Stainless generator config, or is there a preferred approach for adding new provider integrations?