The short version
- What I tried: a single Python script that calls Claude on Amazon Bedrock with a Bedrock API key, using the Converse API, streaming and the raw InvokeModel API.
- What happened: the request shapes pass botocore's validation against the real Bedrock service model, and the helper functions pass stubbed tests. I have not yet run it against Bedrock itself.
- What I would do next: run it live with a real key, then compare the token counts it predicts with the usage Bedrock reports.
The problem and the context
Most Claude examples call Anthropic's own API. I wanted the same thing on Bedrock, where the account, billing and access controls already exist. The aim was a small file I can read in one sitting and reuse: one call that works, and clear places where I can change what the model sees and how many tokens a call may use.
The API key is a stub. The script reads it from an environment variable, or from one constant at the top of the file.
What I tried
| Item | Detail |
|---|---|
| Model and version | Claude Sonnet through the us.anthropic.claude-sonnet-4-6 inference profile, the ID used in AWS's own example. Change it with BEDROCK_MODEL_ID. |
| Tools and settings | Bedrock API key, Converse API, Region us-east-1 by default |
| Inputs used | Stubbed responses only so far. No live calls. |
| Date run | 2026-11-12 |
The code
| Item | Detail |
|---|---|
| Language and version | Python 3.9 or later |
| Packages and versions | boto3 1.39.0 or later. AWS says earlier versions ignore the API key variable. |
| How to run it | python claude_bedrock.py "your prompt" |
The full script is claude_bedrock.py. The core of it is one Converse call:
client = boto3.client("bedrock-runtime", region_name="us-east-1")
response = client.converse(
modelId="us.anthropic.claude-sonnet-4-6",
system=[{"text": "You are a concise, accurate assistant."}],
messages=[{"role": "user", "content": [{"text": "Hello"}]}],
inferenceConfig={"maxTokens": 512, "temperature": 0.2},
)
text = response["output"]["message"]["content"][0]["text"]
Authentication
Bedrock recognises an API key in the AWS_BEARER_TOKEN_BEDROCK environment variable, and boto3 picks it up when you create the client. The script checks the variable first, then the constant at the top of the file, and exits with a message if both are empty. Bedrock API keys cover Bedrock and Bedrock Runtime actions only.
Passing context
There are three places to put what the model should know, and they behave differently.
- System prompt. Standing instructions: role, tone, rules. It is sent on every call.
- A pinned document.
--context-filereads a text file and adds it to the system blocks inside<document>tags. Because it lives in the system prompt, trimming the conversation never removes it. - Conversation history. The model keeps nothing between calls, so a chat resends every earlier user and assistant message each turn.
--chatshows this: it appends each reply to a list and sends the whole list again.
The trade-off is cost. Everything in all three places counts as input tokens on every call, so a long document or a long chat gets more expensive each turn.
Managing tokens
- Count before sending. Bedrock has a CountTokens operation that returns the input tokens a Converse or InvokeModel request would use. The script calls it first and refuses to send anything over
--budget. Not every model supports it, so the script falls back to a rough estimate of four characters per token. - Cap the output.
maxTokenslimits how long the reply can be. If the model hits it, the stop reason ismax_tokensand the script prints a warning, because the answer was cut off. - Trim the history. In chat mode, when the input is over budget, the script drops the oldest user and assistant pair and counts again. The newest message is always kept.
- Read the usage. Every response includes input and output token counts, and Converse adds latency. The script prints them after each call. If you fill in the two price constants, it also prints a cost estimate. They are blank on purpose, so it never guesses a price.
- Retries. The client is set to retry throttled requests with adaptive backoff, which matters once you send many calls.
The API options
| Option | What it does | Use it when |
|---|---|---|
converse | One request format across models. Returns the full reply. | Default choice. Easiest to switch models. |
converse_stream | Same request, but text arrives in pieces. Usage comes in a final metadata event. | A person is watching the output. |
invoke_model | The model's own request format. For Claude, Anthropic's Messages shape with anthropic_version. | You need something Converse does not expose. |
count_tokens | Returns the input token count for a request without running the model. | Checking a budget before you send. |
Beyond the call type, these settings change the result:
temperatureortopP: how random the output is. The script sets one, not both.stopSequences: strings that end generation early.- Model ID or inference profile ID: a profile prefix such as
us.orglobal.lets Bedrock route across Regions. additionalModelRequestFields: model-specific extras. It is left as a commented example.
AWS's getting-started page also lists two other routes: Anthropic's own Messages API pointed at a Bedrock endpoint, and OpenAI-style Responses and Chat Completions endpoints. The script does not use them. Converse can also take tool definitions and guardrails, which this script leaves out.
Tests and edge cases
- Converse, CountTokens and InvokeModel requests passed botocore's Stubber, which checks parameters against the real service model. A wrong field name would fail here. Passed.
- ConverseStream request parameters validated against the service model. Passed. The streaming loop ran against a fake event stream, including a
max_tokensstop. Passed. - History trimming dropped one pair and kept the newest message when over budget. Passed.
- CountTokens returning an error fell back to the estimate. Passed.
- No key set: the script exits with a clear message. Passed.
- Live calls to Bedrock, real token counts, throttling behaviour. Not run yet.
What it still gets wrong
- It has only been tested against stubs, so a live difference in response shape would only show up on the first real call.
- The model ID is the one in AWS's example. A newer model, or one not enabled for your account and Region, needs a different ID.
- Trimming drops whole old turns. It does not summarise them, so early facts in a long chat are lost.
- The fallback estimate of four characters per token is rough, and worse for code and non-English text.
- AWS recommends short-term API keys for production use, and the script does not refresh keys.
What I would change
I would add prompt caching for the pinned document, so a long reference file is not billed in full on every turn, and summarise old history instead of dropping it. Both come after I have a live run to measure against.
Open questions
- How closely does the CountTokens number match the usage Bedrock reports for the same request?
- Which Claude models support CountTokens, and under which ID form (plain model or inference profile)?
- What does the same prompt cost and how long does it take through Converse compared with InvokeModel?