Calling Foundation Models from Application Code with Amazon Bedrock
This lesson explains how application code calls foundation models through the Amazon Bedrock Runtime API, how requests choose a model or inference profile, how tool use works, and how to handle errors, quotas and cost.
Learning outcomes
After completing this lesson, you will be able to:
- Explain the difference between the Converse, ConverseStream and InvokeModel APIs.
- Interpret the stop reason and token usage in a Converse response.
- Describe how cross-Region inference profiles affect throughput, permissions and data residency.
- Explain how tool use lets a model request actions that the application performs.
- Identify the cause and fix for common Bedrock errors such as throttling.
The Bedrock Runtime APIs
A foundation model (FM) is a large model trained on broad data that can generate text, summarise, classify or reason from a prompt. Amazon Bedrock hosts many FMs as a serverless service, so an application sends a request and pays per token without provisioning or scaling any infrastructure. Inference calls go to the bedrock-runtime endpoint, while configuration calls, such as creating a guardrail, go to the bedrock control-plane endpoint.
The Converse API is the recommended way to call a model. Its request has the same shape for every supported model: a list of messages, each with a role of user or assistant and a list of content blocks; an optional system prompt; inferenceConfig settings such as maxTokens, temperature and stopSequences; and an optional toolConfig. Because the format is shared, switching to another model usually means changing only the model ID. ConverseStream returns the same response as a stream of events, so a chat interface can show text as it is generated.
The older InvokeModel and InvokeModelWithResponseStream operations take the provider's native JSON body, which differs between model families. They are still used for embedding models and for provider-specific features that Converse does not expose. A third option, the bedrock-mantle endpoint, offers OpenAI-compatible Chat Completions and Responses APIs, so code written for the OpenAI SDK can call Bedrock models after changing only the base URL and credentials. The following comparison summarises the choices.
Calling Converse from code
The following Python example calls Converse with the AWS SDK for Python (boto3). The client is created once, outside any Lambda handler, and the call is signed with the IAM role of the compute that runs it, so no keys appear in the code.
import boto3
bedrock = boto3.client("bedrock-runtime")
response = bedrock.converse(
modelId="us.amazon.nova-micro-v1:0", # a cross-Region inference profile
system=[{"text": "You write short, factual product descriptions."}],
messages=[{"role": "user", "content": [{"text": "Describe a 1-litre steel water bottle."}]}],
inferenceConfig={"maxTokens": 300, "temperature": 0.3},
)
print(response["output"]["message"]["content"][0]["text"])
print(response["stopReason"], response["usage"]) # e.g. end_turn {'inputTokens': 32, 'outputTokens': 87, ...}The response contains the generated message, a stopReason that explains why generation stopped, and token usage. A stopReason of max_tokens means the answer was cut off and maxTokens should be raised; end_turn means the model finished; tool_use means the model is asking the application to run a tool; and guardrail_intervened means a guardrail blocked the content. A multi-turn conversation is kept by the application, which sends the earlier messages again with each request, because Converse itself is stateless.
Call models with Converse
Model IDs and inference profiles
A request names either a model ID, such as amazon.nova-micro-v1:0, which runs the model in the current Region, or an inference profile. A cross-Region inference profile routes each request to one of several Regions with available capacity: geographic profiles, whose IDs start with a prefix such as us. or eu., stay within one geography, and global profiles can use any supported commercial Region. Cross-Region inference raises throughput and absorbs traffic peaks without extra cost, but the prompt may be processed outside the source Region, which matters for data residency requirements. Some newer models are offered only through inference profiles.
Permissions follow the same path. A role that invokes a cross-Region profile needs bedrock:InvokeModel on the inference profile ARN and on the foundation model in each destination Region; the next module, Securing AI Service Integrations, shows such a policy. Application inference profiles, which a team creates around a model or system profile, carry cost allocation tags, so each application's usage appears separately in billing.
Letting the model call tools
Tool use, also called function calling, lets a model ask the application to run code, for example to look up an order status. The model never runs anything itself. The exchange follows these steps.
-
Describe the tools
The request's
toolConfiglists each tool with a name, a description and a JSON schema for its input. -
Model requests a tool
If a tool would help, the response has a
stopReasonoftool_useand atoolUseblock with the tool name and input. -
Application runs the tool
The application validates the input, calls its own function or API with its own permissions, and checks that the user may see the result.
-
Return the result
The application sends a new request that adds a
toolResultblock to the conversation, and the model writes its final answer.
Because the model chooses the tool and its arguments from text that a user may control, the application must treat the tool input as untrusted: validate it against the schema, check authorisation for the signed-in user, and keep each tool's permissions as narrow as possible. A tool whose input schema is precise also gives a reliable way to obtain structured output, because the model must return JSON that matches the schema.
The following diagram shows the requests exchanged during one tool call.

A tool use exchange
Errors, quotas and cost
Bedrock enforces quotas per model and Region, measured in requests per minute and tokens per minute. When a quota is exceeded, the API returns ThrottlingException, which the SDKs retry with exponential backoff; persistent throttling calls for a cross-Region inference profile, a quota increase, or a queue in front of the model to smooth traffic. The following table lists the errors that developers meet most often.
| Error | Usual cause | Fix |
|---|---|---|
ThrottlingException | Requests or tokens per minute above the quota | Retry with backoff; cross-Region inference; request a quota increase |
AccessDeniedException | Missing bedrock:InvokeModel permission, a deny policy, or model access not yet enabled | Check IAM and SCPs; complete first-use requirements |
ValidationException | Malformed request, unsupported parameter or input too long for the model | Fix the request; shorten or split the input |
ModelTimeoutException | The model took too long to respond | Retry; stream the response; reduce maxTokens |
Cost is charged per input and output token, so prompts are kept concise and maxTokens is set to what the answer needs. Prompt caching reduces the cost and latency of prompts that repeat a long prefix, such as a large set of instructions, and batch inference, described in the next topic, lowers the price of work that can wait. Synchronous integrations have time limits, such as API Gateway's default 29-second integration timeout, so long generations are streamed to the client or processed asynchronously through a queue.
Decode the Bedrock error
A product description service
A retailer adds a button that drafts a product description from a few attributes. Descriptions must appear word by word, and the team expects traffic spikes during catalogue imports.
The developer builds a Lambda function with response streaming behind a function URL and calls ConverseStream, forwarding each contentBlockDelta event to the browser so text appears as it is generated.
The function uses a geographic cross-Region inference profile to absorb peaks, and the SDK's adaptive retry mode backs off on ThrottlingException. Bulk imports do not call the function at all: they write their items to S3 and run a batch inference job overnight at a lower price. The function's role allows bedrock:InvokeModelWithResponseStream only on the chosen profile and its underlying model.
A chatbot built on Converse forgets what the user said two messages earlier. What is the likely cause?
Show answer
Converse is stateless, so the application must send the earlier user and assistant messages in the messages list with every request. The code is probably sending only the latest message.
Exam Tips
Remember for the exam
- One request format for every model, so switching models is a one-line change: Converse.
- Show text as it is generated: ConverseStream (or InvokeModelWithResponseStream).
- A stopReason of max_tokens means the output was truncated.
- Converse is stateless: the application resends earlier messages to continue a conversation.
- Persistent ThrottlingException: cross-Region inference profile, quota increase or a queue.