Amazon Bedrock & the Converse API

Generative & Agentic AI · GenAI on the Cloud · Intermediate · 24 min

Call any Bedrock model with one message format, read stop reasons and token usage, and run a full tool-use loop.

A universal travel adapter. Every model provider has a differently shaped plug (request format); Converse is the adapter that lets your one app plug into all of them, and the stop reason is the little light telling you whether the device finished charging, needs a tool, or ran out of power.

The idea in everyday words

Ordering at a restaurant through a waiter. You hand over the whole order history every time (the waiter has no memory), say any house rules (system prompt) and how big a portion you want (maxTokens). Sometimes the chef sends the waiter back with a question: 'Which side do you want?' (a tool request). You answer, the waiter goes back, and only then does the dish arrive.

Before the first call: access, IAM and Regions

Three things must be true before any code works:

  1. The model is available to your account in your Region. Not every model is in every Region. Some models need a one-time access request or use-case form in the Bedrock console. The exact process has changed over time, so follow the current "model access" page in the Bedrock docs.
  2. Your IAM identity is allowed to call it. Converse needs the bedrock:InvokeModel permission and ConverseStream needs bedrock:InvokeModelWithResponseStream, on the model (or inference profile) resource.
  3. You use the right client. boto3.client("bedrock-runtime") sends prompts. boto3.client("bedrock") is the control plane (list models, create guardrails, start fine-tuning jobs).

Most day-one errors are one of these three, not a bug in your code. Read the exception name: AccessDeniedException (IAM or access), ValidationException (bad request or unsupported model feature), ThrottlingException (quota: retry with backoff), ResourceNotFoundException (wrong model ID or Region).

InvokeModel vs Converse vs ConverseStream

  • InvokeModel: you send a raw JSON body in each provider's own format (Anthropic's, Meta's, Amazon's are all different). Switching models means rewriting the body and the parsing.
  • Converse: one request and response format for every chat model. Bedrock translates for you. Switching models is changing one string.
  • ConverseStream: the same, but the answer arrives as a stream of events, so users see text as it is generated.

Real boto3 code (needs AWS credentials, so it is shown here, not run):

import boto3

client = boto3.client("bedrock-runtime", region_name="us-east-1")
resp = client.converse(
    modelId="<model ID or inference profile ID from the Bedrock console>",
    system=[{"text": "You are a concise assistant."}],
    messages=[{"role": "user", "content": [{"text": "Explain RAG in one sentence."}]}],
    inferenceConfig={"maxTokens": 200, "temperature": 0.2, "stopSequences": ["</answer>"]},
)
print(resp["output"]["message"]["content"][0]["text"])
print(resp["stopReason"], resp["usage"])     # e.g. end_turn {'inputTokens': 21, ...}

# Streaming: print text as it arrives
stream = client.converse_stream(modelId="<model id>", messages=[...])
for event in stream["stream"]:
    if "contentBlockDelta" in event:
        print(event["contentBlockDelta"]["delta"].get("text", ""), end="")
    elif "messageStop" in event:
        print("\nstop:", event["messageStop"]["stopReason"])
    elif "metadata" in event:
        print(event["metadata"]["usage"])

Use InvokeModel only for things Converse does not cover (for example some image or embedding models, which have their own body formats).

The message format

A Converse request is plain data:

Field What it holds
modelId a model ID, or an inference profile ID
messages the conversation: a list of {"role": "user" or "assistant", "content": [blocks]}
system a list of system prompt blocks, such as [{"text": "You are…"}]
inferenceConfig maxTokens, temperature, topP, stopSequences
toolConfig the tools the model may request
additionalModelRequestFields model-specific extras (for example top_k)

Content blocks are the key idea: one message can mix several. Common ones are text, image, document, toolUse and toolResult. Not every model supports every block or feature, so check the Converse supported-features table in the docs.

The response:

{"output": {"message": {"role": "assistant", "content": [{"text": "..."}]}},
 "stopReason": "end_turn",
 "usage": {"inputTokens": 21, "outputTokens": 30, "totalTokens": 51},
 "metrics": {"latencyMs": 640}}

Converse is stateless. Bedrock does not remember the last call. Your app appends each reply to messages and sends the whole history next time, which is also why long chats get more expensive per turn.

Tool use: the model asks, your code acts

You describe tools with a JSON schema in toolConfig:

toolConfig = {"tools": [{"toolSpec": {
    "name": "get_weather",
    "description": "Current weather for a city",
    "inputSchema": {"json": {"type": "object",
                             "properties": {"city": {"type": "string"}},
                             "required": ["city"]}}}}]}

The loop:

  1. Call converse with the tools.
  2. If stopReason == "tool_use", the assistant message contains one or more toolUse blocks: {"toolUseId", "name", "input"}.
  3. Your code runs each tool (validate the input first!).
  4. Append the assistant message, then one user message holding a toolResult block per call: {"toolUseId": same id, "content": [{"json": result}], "status": "success"}.
  5. Call converse again. Repeat until the stop reason is not tool_use, and cap the number of loops so a confused model cannot spin forever.

The model never executes anything. It only produces a structured request. Security, permissions and side effects are your code's job.

blocks = [{"text": "Checking."},
          {"toolUse": {"toolUseId": "t1", "name": "get_weather", "input": {"city": "Oslo"}}},
          {"toolUse": {"toolUseId": "t2", "name": "get_weather", "input": {"city": "Rome"}}}]
results = [{"toolResult": {"toolUseId": b["toolUse"]["toolUseId"],
                           "content": [{"json": {"city": b["toolUse"]["input"]["city"], "temp_c": 18}}]}}
           for b in blocks if "toolUse" in b]
reply = {"role": "user", "content": results}     # ONE message, two results
print(len(reply["content"]), "tool results in one user message")

Stop reasons, tokens, cost and cross-region inference

Always branch on stopReason:

stopReason Meaning What your code does
end_turn model finished show the answer
tool_use model wants a tool run it, send the result back
max_tokens hit your cap answer is incomplete: raise the cap or continue
stop_sequence hit one of your stop strings treat as finished
guardrail_intervened / content_filtered blocked by safety checks show a safe message, log it

New stop reasons can be added over time, so always have a default branch.

Pricing is per token, with separate prices for input and output tokens (output usually costs more). usage tells you exactly what you were billed for. Estimate cost = input tokens × input price + output tokens × output price, using the Amazon Bedrock pricing page. Levers: shorter prompts, smaller models, lower maxTokens, prompt caching for long repeated prefixes on models that support it, and batch inference for offline jobs.

Quotas limit requests and tokens per minute. On ThrottlingException, retry with exponential backoff (boto3 has built-in retry modes).

Cross-region inference profiles let Bedrock route your request to another Region in the same geography when one is busy, which raises your effective throughput. You call them with an inference profile ID, which looks like the model ID with a geography prefix (for example us. or eu.). Some newer models can only be called through an inference profile. Check the docs for which profiles exist and how data residency works for each.

Step by step

  1. Request 1:

    messages = [user: "What's the weather in Paris?"], plus toolConfig with get_weather, maxTokens 300.

  2. Response 1:

    stopReason = tool_use. Content: [text "Let me check the weather.", toolUse {id tooluse_1, name get_weather, input {city: Paris}}]. Usage: 120 in, 40 out.

  3. Run the tool:

    Your code calls get_weather(city="Paris") → {temp_c: 18, sky: cloudy}.

  4. Request 2:

    Append the assistant message and a user message with toolResult {toolUseId: tooluse_1, content: [{json: …}]}. History now has 3 messages.

  5. Response 2:

    stopReason = end_turn, text "It is 18°C and cloudy in Paris." Usage: 190 in, 14 out.

  6. Cost:

    Total 364 tokens over two calls. Input grew from 120 to 190 because the history is resent every turn.

Code example

# A full Converse tool-use loop against a MOCK client that returns the real response shape.
class MockBedrockRuntime:
    """Stands in for boto3.client("bedrock-runtime") so this runs anywhere."""
    def converse(self, modelId, messages, system=None, inferenceConfig=None, toolConfig=None):
        last = messages[-1]["content"][0]
        if "toolResult" in last:
            data = last["toolResult"]["content"][0]["json"]
            text = "It is " + str(data["temp_c"]) + "°C and " + data["sky"] + " in " + data["city"] + "."
            return {"output": {"message": {"role": "assistant", "content": [{"text": text}]}},
                    "stopReason": "end_turn",
                    "usage": {"inputTokens": 190, "outputTokens": 14, "totalTokens": 204},
                    "metrics": {"latencyMs": 380}}
        return {"output": {"message": {"role": "assistant", "content": [
                    {"text": "Let me check the weather."},
                    {"toolUse": {"toolUseId": "tooluse_1", "name": "get_weather", "input": {"city": "Paris"}}}]}},
                "stopReason": "tool_use",
                "usage": {"inputTokens": 120, "outputTokens": 40, "totalTokens": 160},
                "metrics": {"latencyMs": 510}}

def get_weather(city):
    return {"city": city, "temp_c": 18, "sky": "cloudy"}

TOOLS = {"get_weather": get_weather}
TOOL_CONFIG = {"tools": [{"toolSpec": {
    "name": "get_weather", "description": "Current weather for a city",
    "inputSchema": {"json": {"type": "object", "properties": {"city": {"type": "string"}}, "required": ["city"]}}}}]}

client = MockBedrockRuntime()
messages = [{"role": "user", "content": [{"text": "What's the weather in Paris?"}]}]
used = {"inputTokens": 0, "outputTokens": 0}
for turn in range(5):                                   # always cap the loop
    resp = client.converse(modelId="us.example-model-id", messages=messages,
                           system=[{"text": "You are a weather bot."}],
                           inferenceConfig={"maxTokens": 300, "temperature": 0},
                           toolConfig=TOOL_CONFIG)
    msg = resp["output"]["message"]
    messages.append(msg)
    for k in used:
        used[k] += resp["usage"][k]
    print("turn", turn + 1, "| stopReason:", resp["stopReason"])
    if resp["stopReason"] != "tool_use":
        # content is a list of blocks: join every text block, never assume content[0]
        print("answer:", "\n".join(b["text"] for b in msg["content"] if "text" in b))
        break
    results = []
    for block in msg["content"]:
        if "toolUse" in block:
            call = block["toolUse"]
            out = TOOLS[call["name"]](**call["input"])
            print("  tool", call["name"], call["input"], "->", out)
            results.append({"toolResult": {"toolUseId": call["toolUseId"], "content": [{"json": out}], "status": "success"}})
    messages.append({"role": "user", "content": results})

# Made-up example prices in dollars per million tokens. Check the Bedrock pricing page for real ones.
cost = used["inputTokens"] * 3 / 1e6 + used["outputTokens"] * 15 / 1e6
print("messages:", len(messages), "| tokens:", used, "| example cost: 
quot; + format(cost, ".6f"))

Interview tips

  • InvokeModel vs Converse: provider-specific bodies vs one unified message format; ConverseStream for token streaming.

  • Walk through a tool-use loop: toolConfig, stopReason tool_use, run the tool, send toolResult with the same toolUseId, repeat with a loop cap.

  • Why is the API stateless, and how does that affect cost as conversations grow? (History is resent; summarise or trim old turns.)

  • What IAM permissions does a Lambda need to call Converse and ConverseStream? (bedrock:InvokeModel and bedrock:InvokeModelWithResponseStream on the model or inference profile.)

  • What are cross-region inference profiles for? (Higher throughput and resilience by routing within a geography.)

Challenge: Decide the Next Step from a Converse Response

Write next_action(response) that reads a Bedrock Converse response and tells your app what to do next.

Return {"action": ..., "text": ..., "tools": [...], "tokens": ...}:

  • text: all text blocks in response["output"]["message"]["content"], joined with "\n" (empty string if none).
  • tools: the name of every toolUse block, in order.
  • tokens: response["usage"]["totalTokens"], or 0 if usage is missing.
  • action from stopReason:
    • "tool_use" → "call_tools"
    • "end_turn" or "stop_sequence" → "done"
    • "max_tokens" → "continue"
    • "guardrail_intervened" or "content_filtered" → "blocked"
    • anything else → "error" (new stop reasons appear over time)

Example:

next_action({"output": {"message": {"role": "assistant", "content": [
    {"text": "Let me check."},
    {"toolUse": {"toolUseId": "t1", "name": "get_weather", "input": {"city": "Paris"}}}]}},
  "stopReason": "tool_use", "usage": {"inputTokens": 120, "outputTokens": 40, "totalTokens": 160}})
→ {"action": "call_tools", "text": "Let me check.", "tools": ["get_weather"], "tokens": 160}

Solve it in the browser with tests, hints and an AI coach.

Practice problems

More in GenAI on the Cloud

Previous: GenAI on AWS: The Big Picture · Next: Guardrails & Responsible AI on Bedrock