|
| 1 | +"""Example: Using AwsOpenAI with a custom credential provider and auto-refresh. |
| 2 | +
|
| 3 | +This shows how to: |
| 4 | + 1. Use a custom credential provider that returns fresh credentials on each call |
| 5 | + 2. Use botocore's RefreshableCredentials for automatic STS assume-role refresh |
| 6 | + 3. Use an async credential provider with AsyncAwsOpenAI |
| 7 | +
|
| 8 | +Requires: |
| 9 | + - botocore installed (pip install botocore) |
| 10 | + - boto3 installed (pip install boto3) — for the STS assume-role example |
| 11 | + - AWS credentials configured for the initial session |
| 12 | + - AWS_REGION or AWS_DEFAULT_REGION set (or pass region= explicitly) |
| 13 | +
|
| 14 | +Run: |
| 15 | + export AWS_REGION=us-west-2 |
| 16 | + PYTHONPATH=src python3 examples/bedrock_mantle_credential_provider.py |
| 17 | +""" |
| 18 | + |
| 19 | +from __future__ import annotations |
| 20 | + |
| 21 | +import asyncio |
| 22 | +from typing import Any, Callable |
| 23 | +from dataclasses import dataclass |
| 24 | + |
| 25 | +from openai.lib.aws import AwsOpenAI, AsyncAwsOpenAI |
| 26 | + |
| 27 | +# --------------------------------------------------------------------------- |
| 28 | +# 1. Simple custom credential provider |
| 29 | +# --------------------------------------------------------------------------- |
| 30 | + |
| 31 | + |
| 32 | +@dataclass |
| 33 | +class MyCredentials: |
| 34 | + """Minimal object satisfying the Credentials protocol.""" |
| 35 | + |
| 36 | + access_key: str |
| 37 | + secret_key: str |
| 38 | + token: str | None = None |
| 39 | + |
| 40 | + |
| 41 | +def my_credential_provider() -> MyCredentials: |
| 42 | + """Return credentials from your own secret store, vault, etc. |
| 43 | +
|
| 44 | + This callable is invoked before every request, so returning fresh |
| 45 | + credentials here is all you need for auto-refresh. |
| 46 | + """ |
| 47 | + # Replace with your actual credential fetching logic |
| 48 | + return MyCredentials( |
| 49 | + access_key="AKIA...", |
| 50 | + secret_key="wJalr...", |
| 51 | + token="FwoGZX...", # optional session token |
| 52 | + ) |
| 53 | + |
| 54 | + |
| 55 | +client = AwsOpenAI( |
| 56 | + region="us-west-2", |
| 57 | + credential_provider=my_credential_provider, |
| 58 | +) |
| 59 | + |
| 60 | +response = client.chat.completions.create( |
| 61 | + model="openai.gpt-oss-120b", |
| 62 | + messages=[{"role": "user", "content": "Hello from custom credentials!"}], |
| 63 | +) |
| 64 | +print("Custom provider:", response.choices[0].message.content) |
| 65 | + |
| 66 | + |
| 67 | +# --------------------------------------------------------------------------- |
| 68 | +# 2. Auto-refreshing STS assume-role credentials via botocore |
| 69 | +# --------------------------------------------------------------------------- |
| 70 | + |
| 71 | + |
| 72 | +def make_sts_credential_provider(role_arn: str, session_name: str = "bedrock-mantle") -> Callable[[], Any]: |
| 73 | + """Create a credential provider that assumes an IAM role and auto-refreshes. |
| 74 | +
|
| 75 | + botocore's RefreshableCredentials handles expiry checks and refresh |
| 76 | + transparently — accessing .access_key / .secret_key / .token on the |
| 77 | + returned object triggers a refresh if the credentials are expired. |
| 78 | + """ |
| 79 | + import botocore.session # type: ignore[import-untyped, import-not-found] |
| 80 | + import botocore.credentials # type: ignore[import-untyped, import-not-found] |
| 81 | + |
| 82 | + session: Any = botocore.session.get_session() # pyright: ignore[reportUnknownVariableType, reportUnknownMemberType] |
| 83 | + sts: Any = session.create_client("sts") # pyright: ignore[reportUnknownVariableType, reportUnknownMemberType] |
| 84 | + |
| 85 | + def fetch_credentials() -> dict[str, Any]: |
| 86 | + resp: Any = sts.assume_role(RoleArn=role_arn, RoleSessionName=session_name)["Credentials"] # pyright: ignore[reportUnknownVariableType, reportUnknownMemberType] |
| 87 | + return { |
| 88 | + "access_key": resp["AccessKeyId"], |
| 89 | + "secret_key": resp["SecretAccessKey"], |
| 90 | + "token": resp["SessionToken"], |
| 91 | + "expiry_time": resp["Expiration"].isoformat(), # pyright: ignore[reportUnknownMemberType] |
| 92 | + } |
| 93 | + |
| 94 | + refreshable: Any = botocore.credentials.RefreshableCredentials.create_from_metadata( # pyright: ignore[reportUnknownVariableType, reportUnknownMemberType] |
| 95 | + metadata=fetch_credentials(), |
| 96 | + refresh_using=fetch_credentials, |
| 97 | + method="sts-assume-role", |
| 98 | + ) |
| 99 | + |
| 100 | + # Return a provider that gives back the refreshable object. |
| 101 | + # Accessing its attributes auto-refreshes when expired. |
| 102 | + def provider() -> Any: |
| 103 | + return refreshable # pyright: ignore[reportUnknownVariableType] |
| 104 | + |
| 105 | + return provider |
| 106 | + |
| 107 | + |
| 108 | +# Uncomment to use: |
| 109 | +# sts_client = AwsOpenAI( |
| 110 | +# region="us-west-2", |
| 111 | +# credential_provider=make_sts_credential_provider("arn:aws:iam::123456789012:role/MyRole"), |
| 112 | +# ) |
| 113 | + |
| 114 | + |
| 115 | +# --------------------------------------------------------------------------- |
| 116 | +# 3. Async credential provider |
| 117 | +# --------------------------------------------------------------------------- |
| 118 | + |
| 119 | + |
| 120 | +async def async_credential_provider() -> MyCredentials: |
| 121 | + """An async provider — useful when credentials come from an async API.""" |
| 122 | + # Simulate async credential fetch (e.g., from an async HTTP vault client) |
| 123 | + await asyncio.sleep(0) |
| 124 | + return MyCredentials( |
| 125 | + access_key="AKIA...", |
| 126 | + secret_key="wJalr...", |
| 127 | + token="FwoGZX...", |
| 128 | + ) |
| 129 | + |
| 130 | + |
| 131 | +async def main() -> None: |
| 132 | + async_client = AsyncAwsOpenAI( |
| 133 | + region="us-west-2", |
| 134 | + credential_provider=async_credential_provider, |
| 135 | + ) |
| 136 | + |
| 137 | + response = await async_client.chat.completions.create( |
| 138 | + model="openai.gpt-oss-120b", |
| 139 | + messages=[{"role": "user", "content": "Hello from async credentials!"}], |
| 140 | + ) |
| 141 | + print("Async provider:", response.choices[0].message.content) |
| 142 | + |
| 143 | + |
| 144 | +asyncio.run(main()) |
0 commit comments