AWS Bedrock Free code examples in C#, Python, Java and JavaScript
One AWS API in front of Anthropic, Meta, Mistral, Amazon Nova and others.
WHAT THIS PAGE COVERS
The Converse API, which gives every model one request shape.
us.anthropic.claude-3-haiku-20240307-v1:0
boto3 / aws-sdk
Model ids change. If a sample returns a 404 on the model, that is the first thing to check against the official docs.
No API key. The SDK resolves credentials from the environment, the shared profile, or an attached IAM role. Enable model access in the Bedrock console first.
dotnet add package AWSSDK.BedrockRuntime
dotnet add package AWSSDK.Bedrock
setx AWS_REGION "us-east-1"
Ids are per model and per region. Two clients: AmazonBedrockClient lists, AmazonBedrockRuntimeClient invokes. Mixing them up gives a compile error, which is the friendliest failure on this page.
using Amazon.Bedrock;
using Amazon.Bedrock.Model;
using AmazonBedrockClient control = new();
var profiles = await control.ListInferenceProfilesAsync(
new ListInferenceProfilesRequest());
foreach (var profile in profiles.InferenceProfileSummaries)
{
Console.WriteLine($"{profile.InferenceProfileId} - {profile.InferenceProfileName}");
}
Content is a List<ContentBlock>, not a string. Register AmazonBedrockRuntimeClient as a singleton in DI — it owns an HTTP pool.
using Amazon.BedrockRuntime;
using Amazon.BedrockRuntime.Model;
using AmazonBedrockRuntimeClient client = new();
// Example id from the AWS docs — list yours with the step above.
string modelId = Environment.GetEnvironmentVariable("BEDROCK_MODEL_ID")
?? "us.anthropic.claude-3-haiku-20240307-v1:0";
ConverseResponse response = await client.ConverseAsync(new ConverseRequest
{
ModelId = modelId,
System = [new SystemContentBlock { Text = "You are a concise technical assistant." }],
Messages =
[
new Message
{
Role = ConversationRole.User,
Content = [new ContentBlock { Text = "Explain a database index in two sentences." }],
},
],
InferenceConfig = new InferenceConfiguration { MaxTokens = 500, Temperature = 0.2f },
});
Console.WriteLine(response.Output.Message.Content[0].Text);
Console.WriteLine($"{response.Usage.InputTokens} in, {response.Usage.OutputTokens} out");
ConverseStreamAsync yields typed events. The three failures below each report something other than their cause.
using Amazon.BedrockRuntime.Model;
var streamed = await client.ConverseStreamAsync(new ConverseStreamRequest
{
ModelId = modelId,
Messages =
[
new Message
{
Role = ConversationRole.User,
Content = [new ContentBlock { Text = "Write a haiku about indexes." }],
},
],
});
foreach (var chunk in streamed.Stream)
{
if (chunk is ContentBlockDeltaEvent delta)
{
Console.Write(delta.Delta.Text);
}
}
// 1. AccessDeniedException — model not enabled for the account in that
// region, OR the IAM policy lacks bedrock:InvokeModel. Same message
// for both.
// 2. ValidationException "model identifier is invalid" — a plain model
// id where an inference profile is required, or the wrong region.
// 3. ThrottlingException with no traffic — quotas are per model, per
// region, and start low. Raise them in Service Quotas.
No Bedrock-specific package and no API key. boto3 picks up whatever the AWS credential chain finds — environment variables, ~/.aws/credentials, an EC2 or ECS role. Enable the models you want in the Bedrock console first; a fresh account has none.
pip install boto3
# Any one of these works. A role is preferred in production.
export AWS_REGION="us-east-1"
export AWS_ACCESS_KEY_ID="..."
export AWS_SECRET_ACCESS_KEY="..."
Bedrock ids are per model AND per region, and newer models require an inference profile with a regional prefix (us., eu., apac.). Guessing produces ValidationException or AccessDeniedException, neither of which says 'wrong region'.
import boto3
# Note: bedrock, not bedrock-runtime. Listing is the control plane.
control = boto3.client("bedrock", region_name="us-east-1")
# Most current models must be called through an inference profile.
for profile in control.list_inference_profiles()["inferenceProfileSummaries"]:
print(profile["inferenceProfileId"], "-", profile["inferenceProfileName"])
# Older models can be called by their plain id.
for model in control.list_foundation_models()["modelSummaries"]:
if "TEXT" in model.get("outputModalities", []):
print(model["modelId"])
# Put the one you want in configuration — it differs per environment.
content is a LIST of blocks, not a string; that is what lets the same call carry text, images and documents. Swap modelId for a Llama or Nova profile and nothing else changes.
import os
import boto3
client = boto3.client("bedrock-runtime", region_name=os.environ["AWS_REGION"])
# Example id from the AWS docs — list yours with the step above.
MODEL_ID = os.environ.get(
"BEDROCK_MODEL_ID", "us.anthropic.claude-3-haiku-20240307-v1:0")
response = client.converse(
modelId=MODEL_ID,
system=[{"text": "You are a concise technical assistant."}],
messages=[{
"role": "user",
"content": [{"text": "Explain a database index in two sentences."}],
}],
inferenceConfig={"maxTokens": 500, "temperature": 0.2},
)
print(response["output"]["message"]["content"][0]["text"])
print(response["usage"]["inputTokens"], response["usage"]["outputTokens"])
print(response["stopReason"])
converse_stream returns an event dict per chunk. The three failures below all report something other than their cause.
stream = client.converse_stream(
modelId=MODEL_ID,
messages=[{"role": "user", "content": [{"text": "Write a haiku about indexes."}]}],
)
for event in stream["stream"]:
if "contentBlockDelta" in event:
print(event["contentBlockDelta"]["delta"]["text"], end="", flush=True)
print()
# 1. AccessDeniedException on a real model id
# Either the model is not enabled for your account in that region
# (Bedrock console -> Model access), or the IAM policy is missing
# bedrock:InvokeModel. The message does not distinguish them.
# 2. ValidationException: "model identifier is invalid"
# Usually a plain model id where an inference profile is required,
# or the right id in the wrong region.
# 3. ThrottlingException immediately, with no traffic
# Bedrock quotas are per model, per region, and start low. Raise
# them in Service Quotas; retrying will not help.
AWS SDK v2. No API key — the default credentials provider chain reads the environment, the shared profile, or an attached role.
<dependency>
<groupId>software.amazon.awssdk</groupId>
<artifactId>bedrockruntime</artifactId>
<version>2.32.0</version>
</dependency>
<dependency>
<groupId>software.amazon.awssdk</groupId>
<artifactId>bedrock</artifactId>
<version>2.32.0</version>
</dependency>
Ids are per model and per region. Two clients: BedrockClient lists, BedrockRuntimeClient invokes.
import software.amazon.awssdk.services.bedrock.BedrockClient;
import software.amazon.awssdk.services.bedrock.model.ListInferenceProfilesRequest;
try (BedrockClient control = BedrockClient.create()) {
control.listInferenceProfiles(ListInferenceProfilesRequest.builder().build())
.inferenceProfileSummaries()
.forEach(profile -> System.out.println(
profile.inferenceProfileId() + " - " + profile.inferenceProfileName()));
}
ContentBlock.fromText builds the block. Swap the modelId for a Llama or Nova profile and nothing else changes.
import software.amazon.awssdk.services.bedrockruntime.BedrockRuntimeClient;
import software.amazon.awssdk.services.bedrockruntime.model.ContentBlock;
import software.amazon.awssdk.services.bedrockruntime.model.ConversationRole;
import software.amazon.awssdk.services.bedrockruntime.model.ConverseResponse;
import software.amazon.awssdk.services.bedrockruntime.model.Message;
import software.amazon.awssdk.services.bedrockruntime.model.SystemContentBlock;
BedrockRuntimeClient client = BedrockRuntimeClient.create();
// Example id from the AWS docs — list yours with the step above.
String modelId = System.getenv().getOrDefault(
"BEDROCK_MODEL_ID", "us.anthropic.claude-3-haiku-20240307-v1:0");
Message message = Message.builder()
.role(ConversationRole.USER)
.content(ContentBlock.fromText("Explain a database index in two sentences."))
.build();
ConverseResponse response = client.converse(request -> request
.modelId(modelId)
.system(SystemContentBlock.fromText("You are a concise technical assistant."))
.messages(message)
.inferenceConfig(config -> config.maxTokens(500).temperature(0.2F)));
System.out.println(response.output().message().content().get(0).text());
System.out.println(response.usage().inputTokens() + " in, "
+ response.usage().outputTokens() + " out");
Streaming uses the ASYNC client — BedrockRuntimeAsyncClient — with a response handler. The three failures below each report something other than their cause.
import software.amazon.awssdk.services.bedrockruntime.BedrockRuntimeAsyncClient;
import software.amazon.awssdk.services.bedrockruntime.model.ContentBlock;
import software.amazon.awssdk.services.bedrockruntime.model.ConversationRole;
import software.amazon.awssdk.services.bedrockruntime.model.ConverseStreamResponseHandler;
import software.amazon.awssdk.services.bedrockruntime.model.Message;
BedrockRuntimeAsyncClient async = BedrockRuntimeAsyncClient.create();
Message prompt = Message.builder()
.role(ConversationRole.USER)
.content(ContentBlock.fromText("Write a haiku about indexes."))
.build();
ConverseStreamResponseHandler handler = ConverseStreamResponseHandler.builder()
.subscriber(ConverseStreamResponseHandler.Visitor.builder()
.onContentBlockDelta(chunk -> System.out.print(chunk.delta().text()))
.build())
.build();
async.converseStream(r -> r.modelId(modelId).messages(prompt), handler).join();
// 1. AccessDeniedException — model not enabled in that region, OR the
// IAM policy lacks bedrock:InvokeModel. Same message for both.
// 2. ValidationException "model identifier is invalid" — a plain id
// where an inference profile is required, or the wrong region.
// 3. ThrottlingException with no traffic — quotas are per model, per
// region, and start low. Raise them in Service Quotas.
No API key. The SDK uses the AWS credential chain — environment, shared config, or an attached role. Enable model access in the Bedrock console first.
npm install @aws-sdk/client-bedrock-runtime @aws-sdk/client-bedrock
export AWS_REGION="us-east-1"
export AWS_ACCESS_KEY_ID="..."
export AWS_SECRET_ACCESS_KEY="..."
Ids are per model and per region, and current models need an inference profile with a regional prefix. Two different clients: bedrock lists, bedrock-runtime invokes.
import { BedrockClient, ListInferenceProfilesCommand } from "@aws-sdk/client-bedrock";
const control = new BedrockClient({ region: process.env.AWS_REGION });
const { inferenceProfileSummaries } = await control.send(
new ListInferenceProfilesCommand({}),
);
for (const profile of inferenceProfileSummaries) {
console.log(profile.inferenceProfileId, "-", profile.inferenceProfileName);
}
// Put the one you want in configuration — it differs per environment.
content is an array of blocks, not a string. Swap modelId for a Llama or Nova profile and nothing else in this call changes.
import {
BedrockRuntimeClient,
ConverseCommand,
} from "@aws-sdk/client-bedrock-runtime";
const client = new BedrockRuntimeClient({ region: process.env.AWS_REGION });
// Example id from the AWS docs — list yours with the step above.
const MODEL_ID = process.env.BEDROCK_MODEL_ID
?? "us.anthropic.claude-3-haiku-20240307-v1:0";
const response = await client.send(new ConverseCommand({
modelId: MODEL_ID,
system: [{ text: "You are a concise technical assistant." }],
messages: [{
role: "user",
content: [{ text: "Explain a database index in two sentences." }],
}],
inferenceConfig: { maxTokens: 500, temperature: 0.2 },
}));
console.log(response.output.message.content[0].text);
console.log(response.usage.inputTokens, response.usage.outputTokens);
ConverseStreamCommand returns an async iterable of events. The three failures below each report something other than their cause.
import { ConverseStreamCommand } from "@aws-sdk/client-bedrock-runtime";
const response = await client.send(new ConverseStreamCommand({
modelId: MODEL_ID,
messages: [{ role: "user", content: [{ text: "Write a haiku about indexes." }] }],
}));
for await (const event of response.stream) {
if (event.contentBlockDelta) {
process.stdout.write(event.contentBlockDelta.delta.text);
}
}
// 1. AccessDeniedException — the model is not enabled for your account
// in that region, OR the IAM policy lacks bedrock:InvokeModel. The
// message does not tell you which.
// 2. ValidationException "model identifier is invalid" — usually a
// plain model id where an inference profile is required, or the
// right id in the wrong region.
// 3. ThrottlingException with no traffic — Bedrock quotas are per
// model, per region, and start low. Raise them in Service Quotas.
QUESTIONS
Which languages are the AWS Bedrock examples in?
C#, Python, Java and JavaScript. Every sample runs as pasted and reads its credentials from an environment variable — no key is ever written into the code.
Which package do I install for AWS Bedrock?
The samples use boto3 / aws-sdk. The install step on each language tab gives the exact command.
Which AWS Bedrock model do these examples use?
us.anthropic.claude-3-haiku-20240307-v1:0, checked against the official documentation on 25 September 2026. Model ids change often; if a call returns a model-not-found error, check the current list in the official docs.
Where is the official AWS Bedrock documentation?
https://docs.aws.amazon.com/bedrock/ — it is linked at the bottom of this page, and it is the authority whenever it disagrees with a sample here.
ALSO IN LANGUAGE MODELS
The authority
Official AWS Bedrock documentation
Model names, pricing and rate limits change faster than any page here can. When this page and the official docs disagree, the official docs are right.
https://docs.aws.amazon.com/bedrock/