
Your first Amazon Bedrock call with Python
Amazon Bedrock lets you use AI models (from Amazon, Anthropic, Meta, Mistral and others) from your code, without managing servers or GPUs. In this article I do the bare minimum: send a prompt from Python and read the response.
What you need
- An AWS account with a user that has the
bedrock:InvokeModelpermission. - Python 3 and the AWS CLI configured (
aws configure ssooraws configure). boto3, the AWS SDK for Python:
1
pip install boto31. Check that you have access to the model
In the console, open Amazon Bedrock → Model catalog and search for Nova Micro. If the model asks you to enable access or fill out a form, do that first. Work in
us-east-1, where almost every model is available.I’m using Nova Micro because it’s one of the cheapest models on Bedrock, which makes it ideal for practice.
2. The script
I’m using the Converse API, which uses the same request format for every model. If you want to try a different one later, you only change the
modelId.python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import boto3
client = boto3.client("bedrock-runtime", region_name="us-east-1")
response = client.converse(
modelId="us.amazon.nova-micro-v1:0",
messages=[
{
"role": "user",
"content": [{"text": "Explain what a PID controller is in 3 sentences."}],
}
],
inferenceConfig={"maxTokens": 300, "temperature": 0.5},
)
print(response["output"]["message"]["content"][0]["text"])
print("Tokens used:", response["usage"]["totalTokens"])Run it:
bash
1
python bedrock_test.py3. What each part does
| Part | What it’s for |
|---|---|
| bedrock-runtime | Client for using models (the bedrock client is for managing them) |
| modelId | The model you’re calling |
| messages | The conversation; each message has a role (user or assistant) |
| maxTokens | Caps response length, and therefore cost |
| temperature | How varied the response is (0 = more predictable) |
| usage | How many tokens you consumed |
4. Common errors
AccessDeniedException: your user lacksbedrock:InvokeModel, or the model isn’t enabled.ValidationExceptionon the model ID: check that the ID and region match.NoCredentialsError: the CLI isn’t configured. Don’t hardcode your keys in the script.
5. A note on cost
Bedrock charges per input and output token, and it’s not part of the Free Tier. With a small model like Nova Micro and a low
maxTokens, a few test calls cost cents, but it’s still worth having a budget alert in place.Next step
With this you can plug a model into any script. Next for me: adding message history for multi-turn conversations, and trying
converse_stream to get the response in real time.Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article