Amazon Bedrock with boto3
boto3 is the AWS SDK for Python, and its bedrock-runtime client is how Python apps call Amazon Bedrock with converse and invoke_model. Pointed at the Spanway gateway, the same calls reach the Bedrock models the gateway serves, but the app authenticates with a Spanway virtual key instead of AWS credentials. The gateway signs the call to AWS with its own role, applies the key's budget and rate limit, and records the cost, so application teams never hold AWS keys for Bedrock.
A real-world scenario
An insurance team runs a claims assistant in Python that calls client.converse on Claude in Bedrock. Every developer needed an IAM user with bedrock:InvokeModel, and the security team wanted those users gone. The admin registers Claude on Bedrock in the gateway under the public name claude-sonnet-5-5, signed with the gateway's own IAM role, and gives the team a virtual key named claims-assistant. The team sets the endpoint URL and the key, removes the IAM users, and the assistant keeps calling converse exactly as before.
Prerequisites
- A running gateway and its address, written here as
https://gateway.example.com. - A Bedrock model registered on the gateway. In Models + Endpoints (
/ui/models-and-endpoints) the admin clicks Add Model, picks Amazon Bedrock as the Provider, chooses the model and sets the Public Model Name, for exampleclaude-sonnet-5-5. The public name must point at Amazon Bedrock deployments, because this route forwards the Bedrock request body as it is. For models from other providers, use the OpenAI or Anthropic SDK pages instead. - Python 3.10 or later and boto3, installed with
pip install --upgrade boto3. The bearer token method below needs a boto3 version that supports Amazon Bedrock API keys. Older versions can use the access key method.
Make a key for this app
- In the Admin UI open Virtual Keys (
/ui/api-keys) and click + Create New Key. - Under Key Details, set Key Name to
claims-assistantand leave Key Type on AI APIs, which includes the/bedrockroutes. - In Models, pick every public name the app calls, for example
claude-sonnet-5-5, plus the smaller model it uses for background steps such asclaude-haiku-5-5. A Bedrock model id that is not on the list is refused with 403. - Open Optional Settings, set Max Budget (USD) with Reset Budget, for example 500 USD monthly, and Requests per minute Limit (RPM), for example 120. Leave Tags empty unless the gateway has an Enterprise license, because key tags need one and without it the key is not created (
Only premium users can add tags to keys). The key name already keeps this tool's spend apart in Usage. - Click Create Key and copy the key. It is shown once.
The same key from the API:
curl -X POST https://gateway.example.com/key/generate \
-H "Authorization: Bearer $SPANWAY_MASTER_KEY" -H "Content-Type: application/json" \
-d '{"key_alias": "claims-assistant", "key_type": "llm_api", "models": ["claude-sonnet-5-5", "claude-haiku-5-5"], "max_budget": 500, "budget_duration": "30d", "rpm_limit": 120}'
Steps
-
Check the key and the model names. The Bedrock control plane, such as
list_foundation_models, is not served, so use the OpenAI model list.curl https://gateway.example.com/v1/models -H "Authorization: Bearer $SPANWAY_API_KEY" -
Set
endpoint_urlto the gateway address followed by/bedrock, with no/v1. boto3 adds/model/<modelId>/converseand the other paths after it. -
Give boto3 the virtual key. Pick one of the two methods.
-
Bearer token. Set
AWS_BEARER_TOKEN_BEDROCKto the virtual key. boto3 then sendsAuthorization: Bearer <key>, the way it sends an Amazon Bedrock API key.export AWS_BEARER_TOKEN_BEDROCK="sk-...your virtual key..." -
Access key. Pass the virtual key as
aws_access_key_idand any text asaws_secret_access_key. boto3 signs the request with SigV4, and the gateway reads the key from theCredential=part of the signature header. It does not check the signature itself, the virtual key is the credential.
-
-
Set
region_name, for exampleus-east-1. boto3 needs one to sign, and the gateway uses the region of the deployment, not this one. -
Use the public model name as
modelId, run the app once and find the request on Logs (/ui/logs).
A base URL without /bedrock, or with /v1 in front of it, fails with 404.
Configuration
import os
import boto3
from botocore.config import Config
client = boto3.client(
"bedrock-runtime",
region_name="us-east-1",
endpoint_url="https://gateway.example.com/bedrock",
aws_access_key_id=os.environ["SPANWAY_API_KEY"],
aws_secret_access_key="not-used",
config=Config(retries={"max_attempts": 2, "mode": "standard"}),
)
response = client.converse(
modelId="claude-sonnet-5-5",
messages=[{"role": "user", "content": [{"text": "Explain a model group in one sentence."}]}],
inferenceConfig={"maxTokens": 200},
)
print(response["output"]["message"]["content"][0]["text"])
print(response["ResponseMetadata"]["HTTPHeaders"].get("x-spanway-call-id"))
With the bearer token method, drop aws_access_key_id and aws_secret_access_key and export AWS_BEARER_TOKEN_BEDROCK instead. Keep your real AWS credentials out of this client, because a profile or role found in the environment is not needed and would only confuse a later reader.
Expected result
The script prints the answer and the call id. response["usage"] holds the token counts, and response["ResponseMetadata"]["HTTPHeaders"] holds every gateway header in lower case. x-spanway-call-id is the id to search for on Logs, x-spanway-model-id names the deployment that answered, and x-spanway-response-cost is the call's cost.
On Logs (/ui/logs), click Filters, pick Key Alias = claims-assistant and click Apply Filters. Each row shows the model, the tokens, the cost and the status.
Streaming, tools, images, caching and reasoning
| Feature | How to use it through the gateway | Notes |
|---|---|---|
| Converse streaming | client.converse_stream(...) and for event in response["stream"]: | The gateway returns the Bedrock event stream, which boto3 decodes as usual. |
| Invoke | client.invoke_model(modelId=..., body=json.dumps({...})) and invoke_model_with_response_stream | The body is the model's native format, see Bedrock Invoke. |
| Tools | toolConfig={"tools": [{"toolSpec": {...}}]} on converse. | Handled by the Bedrock model as usual. |
| Images and documents | image and document content blocks with bytes. | The model must accept them. |
| Prompt caching | cachePoint blocks in messages or system. | Handled by Bedrock for models that support it. Cached tokens show in usage. |
| Reasoning | additionalModelRequestFields with the model's reasoning setting. | Passed to Bedrock unchanged. |
| Guardrails | guardrailConfig for a Bedrock guardrail. | Gateway guardrails apply as well. |
| Token counting | client.count_tokens(...) | Served on the same /bedrock route. |
| Inference profiles | An application inference profile ARN as modelId. | Served under /model/application-inference-profile/.... |
| Bidirectional streaming | invoke_model_with_bidirectional_stream | Not served. The gateway's Bedrock route covers Converse, Invoke, their streaming forms and token counting. |
boto3 retries throttling errors and 5xx answers on its own, and the gateway has its own retries and fallbacks. The example above sets max_attempts to 2 so a failing request does not turn into many provider calls.
Errors
boto3 raises botocore.exceptions.ClientError for every error answer. For errors the gateway raises itself, the error code is the HTTP status and the message is empty, because the gateway answers in the OpenAI shape {"error": {"message": "..."}} and boto3 looks for a Bedrock message field. It prints as An error occurred (403) when calling the Converse operation: . Read e.response["ResponseMetadata"]["HTTPStatusCode"] and the x-spanway-call-id in e.response["ResponseMetadata"]["HTTPHeaders"], then open the call on Logs to read the gateway's text. Errors that AWS itself returns keep the Bedrock shape, so boto3 shows their name, such as ValidationException or ThrottlingException, and their message.
| Case | Code in e.response["Error"] | Text the gateway sends | Cause and fix |
|---|---|---|---|
| No key on the request | 401 | Authentication Error, No api key passed in. | Neither AWS_BEARER_TOKEN_BEDROCK nor aws_access_key_id reached the gateway. Check the client setup. |
| Wrong or deleted key | 401 | Authentication Error, Invalid proxy server token passed. key=<hash>, not found in db. | A real AWS access key id was sent instead of the virtual key, or the key is wrong. |
| Blocked key | 401 | Authentication Error, Key is blocked. Update via `/key/unblock` if you're an admin. | Ask the admin to open the key in Virtual Keys and click Unblock Key. |
| Expired key | 401 | Authentication Error - Expired Key. Key Expiry time <time> and current time <time> | Ask the admin to extend the key or issue a new one. |
| The key may not use the model | 403 | The requested model '<model>' is not available for this API key, or the model name is invalid. | Add the public name to the key in Virtual Keys. |
| The budget is spent | 422 | Budget has been exceeded! Key=<key alias> Current cost: <spend>, Max budget: <max> | Wait for the reset or ask for a higher budget. |
| Over the key or team rate limit | 429 | Rate limit exceeded for <scope>: <value>. Limit type: <type>. | Slow down or ask for a higher limit. |
| The public name points at a model that is not on Bedrock | 500 | The provider's own message, followed by the model group that failed | This route forwards Bedrock bodies only. Ask the admin to point the name at Bedrock, or use the OpenAI or Anthropic SDK. |
Wrong path, no /bedrock or an added /v1 | 404 | Not Found | Set endpoint_url to https://gateway.example.com/bedrock. |
| Bedrock does not know the model id | ValidationException | AWS's own message | A name the gateway does not know is sent to Bedrock as a Bedrock model id. Use a public name from GET /v1/models. |
| The gateway's AWS role may not call the model | AccessDeniedException | AWS's own message | The admin adds bedrock:InvokeModel for that model to the gateway's IAM role. |
| Bedrock is throttling | ThrottlingException | AWS's own message | The admin adds a deployment in another region as a fallback. |
| Nothing listens at the address | EndpointConnectionError | None. Could not connect to the endpoint URL: "<url>" | Check the address, port and that the gateway runs. In Docker use host.docker.internal. |
| TLS certificate not trusted | SSLError | None. SSL validation failed for <url> followed by CERTIFICATE_VERIFY_FAILED | Pass verify="/path/to/company-root.pem" to boto3.client, or set AWS_CA_BUNDLE to that file. |
See the client error reference for the same cases in every SDK.
Troubleshooting
- In
except client.exceptions.ClientError as e:, log the status code andx-spanway-call-idfrome.response["ResponseMetadata"]. - Open Logs (
/ui/logs), search for the call id or filter by Key Alias, and open the row. It holds the gateway's full error text, which boto3 does not show, plus the deployment and AWS's answer. - If the request is not on Logs, it never reached the gateway. Turn on boto3's wire log with
boto3.set_stream_logger("botocore", logging.DEBUG)to see the URL it calls. The log also prints theAuthorizationheader with your key, so never paste it anywhere. - A 401 with a key you know is right usually means boto3 signed with real AWS credentials from the environment or
~/.aws. Passaws_access_key_idexplicitly, or use the bearer token method. - Read
x-spanway-routing-reasonandx-spanway-attemptsin the response headers to see retries and fallbacks, explained on routing decision headers.
More symptoms are in troubleshooting.
Rotation and removal
Open the key in Virtual Keys, click Regenerate Key, set a Grace Period such as 24h, and deploy the new key before it ends. From the API this is POST /key/{key}/regenerate with {"grace_period": "24h"}, which needs an Enterprise license. Without one, create a new key, switch the app and delete the old key.
Block Key (POST /key/block) stops the app at once and Unblock Key undoes it. Deleting the key (POST /key/delete with {"keys": ["<key>"]}) is permanent. To take the app off the gateway, remove endpoint_url and give boto3 AWS credentials again.
Related
- Amazon Bedrock with the JavaScript SDK for the same steps in Node.js.
- Bedrock Converse API and Bedrock Invoke API for the request formats.
- Bedrock pass-through for other Bedrock runtime paths.
- Connect any client for base URLs and headers on every API surface.
- Client error reference for every gateway error.