AI Services, AI Security and AI Developer Tools

Topics Covered

Calling Amazon Bedrock From Application Code

Getting access to a model

The IAM actions that matter

InvokeModel and Converse

Streaming responses

Handling errors in the handler

What the exam is checking in this area

DVA-C03 adds a new kind of dependency to the developer's toolbox: managed AI services that your code calls like any other AWS API. The exam guide lists integrating managed AI services into applications as a skill in domain 1, and it adds a whole task in the security domain about the risks of doing so. It also adds AI-assisted development tools to the coding, testing, deployment and troubleshooting tasks. This lesson covers all three from a developer's point of view. It does not teach you how to pick a model, write prompts or design a retrieval system; the guide puts those jobs out of scope, and the questions follow it. What the exam does test is whether you can call the service correctly, give the code the right permissions, keep data private, filter what goes in and out, secure agents and keep sensitive content out of your logs.

The centre of it is Amazon Bedrock, a fully managed service that gives you API access to foundation models from Amazon and other providers. You do not run servers, load model weights or manage GPUs. You send a request with a model identifier and some input, and you get a response. From your code's point of view, Bedrock is a regional AWS service with a control plane client named bedrock, for things like guardrails, logging configuration and custom models, and a runtime client named bedrock-runtime, for actually running inference.

Getting access to a model

Two things must be true before a call succeeds: the model must be available to the account, and the caller must have IAM permission to invoke it. For most serverless models, Bedrock now enables access automatically the first time an authorized principal invokes the model in the account, so there is no separate access request to file. Some models from some providers still ask for a one time use case form, and the first invocation needs AWS Marketplace permissions so the subscription can start; after that, callers only need the Bedrock permission. Model availability is also per Region, so a model you can call in one Region may not exist in another.

The consequence for an administrator is that blocking a model is done with IAM, not by refusing an access request. A deny on bedrock:InvokeModel for a model ARN, in an IAM policy or a service control policy, stops anyone in scope from using it. The consequence for a developer is that an AccessDeniedException on the very first call usually means IAM, a condition key in the policy, or missing Marketplace permissions for the first use, not a bug in the request body.

The IAM actions that matter

Inference permissions are few and the exam expects you to know them. bedrock:InvokeModel allows the InvokeModel API and also the Converse API. bedrock:InvokeModelWithResponseStream allows the streaming versions, InvokeModelWithResponseStream and ConverseStream. The resource is the model, written as a foundation model ARN, which has a Region but no account ID because the model is not owned by your account, or an inference profile ARN, which does include your account. A least privilege execution role for a function that uses one model looks like this:

json
1{
2  "Version": "2012-10-17",
3  "Statement": [
4    {
5      "Effect": "Allow",
6      "Action": ["bedrock:InvokeModel", "bedrock:InvokeModelWithResponseStream"],
7      "Resource": "arn:aws:bedrock:us-east-1::foundation-model/example.text-model-v1"
8    }
9  ]
10}

Granting bedrock:* on every resource is the AI version of s3:* on every bucket. It lets the function create guardrails, change logging settings and call every model in the account, including the most expensive ones. In an exam option, a wildcard like that is almost always the wrong answer when a scoped alternative exists. The IAM lesson covers policy evaluation in general; here the point is only which actions Bedrock inference uses.

InvokeModel and Converse

Bedrock has two styles of inference API. InvokeModel takes a request body in the native JSON format of the chosen model, and each model family has its own field names for the prompt, the maximum output length and the sampling settings. That gives full access to provider specific features, but switching models means rewriting the body and the parsing code.

The Converse API is a single, consistent interface across the models that support it. You send a list of messages with roles, an optional system prompt, an inference configuration with fields such as maxTokens, temperature and topP, and optionally tool definitions. The response has the same shape for every model: the generated message, a stopReason that explains why generation ended, and a usage object with inputTokens, outputTokens and totalTokens. For application code that might change models later, Converse is the better default, and on the exam it is the answer when a question wants one code path that works across several models.

A Converse call is an ordinary signed AWS API call: IAM authorizes it, then the model runs.

Here is a Lambda handler that summarises a support ticket with Converse. The model ID comes from an environment variable, so changing models is a configuration change and not a deploy of new code.

python
1import os
2import boto3
3from botocore.config import Config
4
5cfg = Config(retries={"max_attempts": 6, "mode": "adaptive"},
6             connect_timeout=5, read_timeout=120)
7brt = boto3.client("bedrock-runtime", config=cfg)
8MODEL_ID = os.environ["MODEL_ID"]
9
10def handler(event, context):
11    resp = brt.converse(
12        modelId=MODEL_ID,
13        system=[{"text": "Summarize the ticket in three short bullet points."}],
14        messages=[{"role": "user", "content": [{"text": event["ticket"]}]}],
15        inferenceConfig={"maxTokens": 400, "temperature": 0.2},
16    )
17    text = resp["output"]["message"]["content"][0]["text"]
18    usage = resp["usage"]
19    print(f"tokens in={usage['inputTokens']} out={usage['outputTokens']}")
20    return {"summary": text, "stopReason": resp["stopReason"]}

Three details in that code are worth noticing. The client is created outside the handler, so warm invocations reuse it and its connections, exactly as the Lambda lesson recommends for any SDK client. The retry and timeout settings are explicit, which the next section explains. And the code reads stopReason, because a value of max_tokens means the answer was cut off at the cap, which a careful application handles instead of showing half a sentence.

Streaming responses

A model writes its answer token by token, and a long answer can take many seconds. With a non streaming call, the user waits for the whole thing. With ConverseStream or InvokeModelWithResponseStream, Bedrock sends the output as a stream of events while the model is still generating. For ConverseStream, the stream starts with a messageStart event, carries the text in contentBlockDelta events, ends the message with messageStop, and finishes with a metadata event that holds the token usage and latency.

Streaming sends tokens as they are generated, so the user sees text in under a second.

Streaming does not make the total generation faster. It reduces the time to the first visible word, which is what users notice in a chat interface. To pass a stream through to a browser you need a path that supports it end to end: a Lambda function URL with response streaming, a WebSocket API that pushes each delta to the client, or a container service that holds the connection open. A plain synchronous API that buffers the whole response before replying turns a streaming call back into a waiting one. When a question says users complain that a chat feature feels slow even though total time is acceptable, the answer is streaming, not a bigger Lambda function.

Handling errors in the handler

Wrap the model call so each failure is handled on purpose. Catch the SDK's client error and read its error code. ThrottlingException and ServiceUnavailableException that survive the SDK's own retries should surface as a retryable failure, so an event source such as SQS can try the message again later. ValidationException means the request itself is wrong, often an input longer than the model accepts, so log the request ID and token estimate and fail the message to a dead letter queue rather than retrying. AccessDeniedException is a configuration problem that no retry will fix; alarm on it. Return a friendly message to the user in every case, and never echo the raw prompt into the error log.

What the exam is checking in this area

Questions on Bedrock integration are mostly about choosing the right call and the right permission. A team wants to swap models without changing request parsing: Converse. A function gets AccessDeniedException calling ConverseStream but Converse works: the role has bedrock:InvokeModel but not bedrock:InvokeModelWithResponseStream. A function in us-west-2 cannot find a model that works in us-east-1: model availability is regional, or the call needs an inference profile. Keep the model ID in configuration, scope the role to the models the code uses, and read the usage and stopReason fields the API gives you.

Converse is the portable default

Use the Converse API when code may change models: one request and response shape, token usage on every reply, and the same bedrock:InvokeModel permission. Reach for InvokeModel with a native body only when you need a provider specific feature that Converse does not expose.