Amazon Bedrock Deep Dive · lab exercise

Exercise 2: a tool-using Converse call

Part of Amazon Bedrock Deep Dive (BDR-101), with lesson 2-3, tool use. You do this in your own AWS account; Gazeek gives no AWS access.

Cost: two short calls to Amazon Nova Micro, a small fraction of a cent. Nothing is created, so there is nothing to clean up.

Before you start

  • Exercise 1 done (credentials, boto3, Bedrock in us-east-1).

Steps

  1. Save tool_use.py. It has three parts:

    • The tool: an ordinary Python function, word_count.
    • toolConfig: how the model learns about the tool: a name, a description, and a JSON schema for its input.
    • The loop: call converse; if stopReason is tool_use, run the tool, add a toolResult message, and call again; stop when the model answers. A cap of four turns stops a confused model looping for ever.
  2. Run it:

    python tool_use.py
    

What you should see

Gazeek's test run, 27 Nov 2026:

turn 1: stopReason = tool_use
  the model asked for word_count({'text': 'the quick brown fox jumps over the lazy dog'}); our code says 9
turn 2: stopReason = end_turn
answer: The phrase "the quick brown fox jumps over the lazy dog" contains 9 words.

The model never ran anything. It asked; your code ran word_count; you sent the answer back; then it replied.

Try this

  • Make the tool lie (return 3) and run it again. The model trusts the tool: whoever writes the tools is responsible for the answers.
  • Add a second tool, char_count, and ask a question that needs both.

Clean up

Nothing to clean up.

What you learned

Tool use is a loop you can run yourself with Converse: the model's tool_use, your code, your toolResult. An agent framework such as Strands (exercise 5) runs exactly this loop for you.

tool_use.py

"""Exercise 2: a tool-using Converse call (Amazon Bedrock Deep Dive, BDR-101).

You run the loop yourself: the model asks for a tool, your code runs it, you send the result back.
Run:  python tool_use.py
Needs: Python 3.10+, boto3, AWS credentials that can call Bedrock in us-east-1.
Cost: two short calls to Amazon Nova Micro, a small fraction of a cent.
"""
import boto3

MODEL_ID = "amazon.nova-micro-v1:0"
client = boto3.client("bedrock-runtime", region_name="us-east-1")


def word_count(text: str) -> int:
    return len(text.split())


tool_config = {
    "tools": [{
        "toolSpec": {
            "name": "word_count",
            "description": "Count the words in a piece of text.",
            "inputSchema": {"json": {
                "type": "object",
                "properties": {"text": {"type": "string", "description": "The text to count words in."}},
                "required": ["text"],
            }},
        }
    }]
}

messages = [{"role": "user", "content": [{"text": 'How many words are in "the quick brown fox jumps over the lazy dog"?'}]}]

for turn in range(1, 5):  # a small cap, so a confused model can't loop for ever
    response = client.converse(modelId=MODEL_ID, messages=messages, toolConfig=tool_config,
                               inferenceConfig={"maxTokens": 300})
    message = response["output"]["message"]
    messages.append(message)
    print(f"turn {turn}: stopReason = {response['stopReason']}")

    if response["stopReason"] != "tool_use":
        print("answer:", " ".join(block["text"] for block in message["content"] if "text" in block))
        break

    results = []
    for block in message["content"]:
        if "toolUse" in block:
            use = block["toolUse"]
            value = word_count(**use["input"])
            print(f"  the model asked for {use['name']}({use['input']}); our code says {value}")
            results.append({"toolResult": {"toolUseId": use["toolUseId"], "content": [{"json": {"words": value}}]}})
    messages.append({"role": "user", "content": results})

← Back to Amazon Bedrock Deep Dive