Шаг 5 из 6 - Около 75 мин
Lab 05 - Generative AI: Bedrock and guardrails
Foundation models, guardrails, and retrieval augmented generation (RAG) with Amazon Bedrock.
Time: about 75 minutes (the optional Knowledge Base takes most of it).
Overview
Amazon Bedrock gives you API access to foundation models (FMs) from Amazon and other providers, without managing servers. In this lab you:
- find the models available to your account and pick one,
- call it with the Converse API (one request format for every model) and the InvokeModel API (each provider's own format),
- change inference parameters such as temperature and the token limit,
- create embeddings with Amazon Titan Text Embeddings V2,
- filter harmful content with a guardrail that Terraform creates,
- optionally build a Knowledge Base for RAG.
What gets created
<account-id> is your 12-digit AWS account ID.
| Component | Resources |
|---|---|
s3-bucket |
Bucket ai-05-genai-test-genai-data-<account-id> with input/prompts/, input/documents/, output/responses/, knowledge-base/ |
bedrock |
Guardrail ai_05_genai_test_bedrock and a published guardrail version |
Role ai-05-genai-test-bedrock-role that Bedrock can assume to invoke models |
|
| Off by default: model invocation logging (log group, role, account setting) | |
| Off by default: Knowledge Base, OpenSearch Serverless collection, KB role, KB data bucket |
Architecture
+---------------------------------------------------------------+
| Your prompt |
| "Explain machine learning in simple terms" |
+-------------------------------+-------------------------------+
|
v
+---------------------------------------------------------------+
| Bedrock guardrail |
| content filters on input and output (hate, insults, |
| sexual, violence, misconduct) |
+-------------------------------+-------------------------------+
|
v
+---------------------------------------------------------------+
| Amazon Bedrock runtime APIs |
| Converse | InvokeModel | ApplyGuardrail |
| |
| +-------------------------------------------------------+ |
| | Foundation models: Amazon and third-party providers | |
| | (text, embeddings, image); list them for your region | |
| +-------------------------------------------------------+ |
+-------------------------------+-------------------------------+
| optional
v
+---------------------------------------------------------------+
| Knowledge Base: S3 documents -> embeddings -> OpenSearch |
| Serverless vector index -> Retrieve / RetrieveAndGenerate |
+---------------------------------------------------------------+Before you start
- Complete the Prerequisites in the README.
- Bedrock is billed per token. There is no free tier for model calls.
Model access
Bedrock no longer has a "Model access" page where you request each model. Serverless foundation models are available in supported regions the first time you call them, if your IAM identity allows the call. Two things can still stop a first call:
- Anthropic models need a one-time use case form per account. The console shows it the first time you open an Anthropic model in the model catalog or a playground.
- Some third-party models are sold through AWS Marketplace. The first
call also needs
aws-marketplace:Subscribeandaws-marketplace:ViewSubscriptionson your identity.
If a call fails with AccessDeniedException, read the message: it says
which of these is missing.
Deploy
The stack stacks/labs/05-genai/test.yaml has an s3-bucket and the
bedrock component. It has no iam-role and no !terraform.output, so the
two components can be applied in any order. The guardrail filter strengths
and the optional features are variables
in that file.
cd atmos-aws-ai-infra # the lab folder
# Check the stack
atmos validate stacks
atmos describe stacks -s lab-05-genai-test --process-functions=false
atmos terraform apply s3-bucket -s lab-05-genai-test
atmos terraform apply bedrock -s lab-05-genai-testSet shell variables
STACK=lab-05-genai-test
BUCKET=$(atmos terraform output s3-bucket -s $STACK --skip-init -- -raw bucket_id)
GUARDRAIL_ID=$(atmos terraform output bedrock -s $STACK --skip-init -- -raw guardrail_id)
GUARDRAIL_VERSION=$(atmos terraform output bedrock -s $STACK --skip-init -- -raw guardrail_version)
echo "$BUCKET $GUARDRAIL_ID $GUARDRAIL_VERSION"Pick a model
Model IDs change as providers release and retire models, so this guide does not hard-code a text model. Look up what your account can call today.
# Text models you can call on demand in us-east-1, with their lifecycle status
aws bedrock list-foundation-models \
--region us-east-1 \
--by-output-modality TEXT \
--by-inference-type ON_DEMAND \
--query 'modelSummaries[].[modelId,providerName,modelLifecycle.status]' \
--output table
# Inference profiles. Many newer models are called through a profile ID
# (for example one that starts with "us.") instead of the base model ID.
aws bedrock list-inference-profiles \
--region us-east-1 \
--query 'inferenceProfileSummaries[].[inferenceProfileId,inferenceProfileName]' \
--output tableChoose an ACTIVE model (a small, low-cost model is fine for this lab) and
put its model ID or inference profile ID in a variable:
MODEL_ID="<paste a modelId or inferenceProfileId from the tables above>"If a model is listed by list-foundation-models but a call says on-demand
throughput is not supported, use the matching
inference profile
ID instead.
Converse API
The Converse API uses the same request and response shape for every model that supports it.
aws bedrock-runtime converse \
--model-id "$MODEL_ID" \
--messages '[{"role": "user", "content": [{"text": "Explain machine learning in 3 sentences."}]}]' \
--inference-config '{"maxTokens": 300, "temperature": 0.5}' \
--region us-east-1 \
--query 'output.message.content[0].text' --output textSystem prompt and token usage
aws bedrock-runtime converse \
--model-id "$MODEL_ID" \
--system '[{"text": "You are a concise AWS tutor. Answer in at most two sentences."}]' \
--messages '[{"role": "user", "content": [{"text": "What are the main AWS AI services and their use cases?"}]}]' \
--inference-config '{"maxTokens": 200}' \
--region us-east-1 \
--query '{answer: output.message.content[0].text, usage: usage, stop: stopReason}'usage shows input and output tokens, which is what you pay for.
stopReason is max_tokens when the answer was cut off by maxTokens.
Inference parameters
Run the same prompt with a low and a high temperature, three times each, and compare how much the answers vary:
for t in 0 1; do
echo "temperature=$t"
for i in 1 2 3; do
aws bedrock-runtime converse \
--model-id "$MODEL_ID" \
--messages '[{"role": "user", "content": [{"text": "Write a one-line slogan for a cloud AI course."}]}]' \
--inference-config "{\"maxTokens\": 50, \"temperature\": $t}" \
--region us-east-1 \
--query 'output.message.content[0].text' --output text
done
doneLow temperature gives repeatable, focused answers; high temperature gives more varied ones.
Summarization and code generation
aws bedrock-runtime converse \
--model-id "$MODEL_ID" \
--messages '[{"role": "user", "content": [{"text": "Summarize in one sentence: Amazon Web Services (AWS) provides on-demand cloud computing platforms and APIs to individuals, companies, and governments on a metered, pay-as-you-go basis. One of these services is Amazon EC2, which gives users a virtual cluster of computers through the internet."}]}]' \
--inference-config '{"maxTokens": 100}' \
--region us-east-1 \
--query 'output.message.content[0].text' --output text
aws bedrock-runtime converse \
--model-id "$MODEL_ID" \
--messages '[{"role": "user", "content": [{"text": "Write a Python function that uses boto3 to list all S3 buckets."}]}]' \
--inference-config '{"maxTokens": 800}' \
--region us-east-1 \
--query 'output.message.content[0].text' --output textInvokeModel API
InvokeModel sends the provider's native request body. With AWS CLI v2 you
must add --cli-binary-format raw-in-base64-out so the CLI sends --body as
raw JSON instead of expecting base64.
Embeddings with Titan Text Embeddings V2
aws bedrock-runtime invoke-model \
--model-id amazon.titan-embed-text-v2:0 \
--content-type application/json \
--accept application/json \
--cli-binary-format raw-in-base64-out \
--body '{"inputText": "Machine learning is fascinating.", "dimensions": 1024, "normalize": true}' \
--region us-east-1 \
embedding-response.json
jq '{dimensions: (.embedding | length), tokens: .inputTextTokenCount}' embedding-response.jsonAn embedding is a vector of numbers that represents meaning. Texts with similar meaning get vectors that are close together, which is how the Knowledge Base below finds relevant documents.
A text model with its native body
The native body differs by provider; check the model's page in the Bedrock
documentation ("Inference request parameters"). For example, if MODEL_ID
is an Anthropic Claude model, the body uses the Anthropic Messages format:
aws bedrock-runtime invoke-model \
--model-id "$MODEL_ID" \
--content-type application/json \
--accept application/json \
--cli-binary-format raw-in-base64-out \
--body '{"anthropic_version": "bedrock-2023-05-31", "max_tokens": 300, "messages": [{"role": "user", "content": "What is Amazon Bedrock?"}]}' \
--region us-east-1 \
claude-response.json
jq -r '.content[0].text' claude-response.jsonThis is why the Converse API exists: the same Converse call works for every supported model, while InvokeModel needs a different body per provider.
Streaming
The AWS CLI does not support the streaming operations (ConverseStream and
InvokeModelWithResponseStream). To see tokens arrive as they are
generated, use an AWS SDK. With Python and boto3:
import boto3
client = boto3.client("bedrock-runtime", region_name="us-east-1")
response = client.converse_stream(
modelId="<your MODEL_ID>",
messages=[{"role": "user", "content": [{"text": "Write a haiku about cloud computing."}]}],
)
for event in response["stream"]:
if "contentBlockDelta" in event:
print(event["contentBlockDelta"]["delta"].get("text", ""), end="", flush=True)
print()Guardrails
The bedrock component created a
guardrail
with content filters and published version $GUARDRAIL_VERSION.
Test the guardrail on its own
ApplyGuardrail checks text against the guardrail without calling a model,
so it is the cheapest way to test filters:
aws bedrock-runtime apply-guardrail \
--guardrail-identifier "$GUARDRAIL_ID" \
--guardrail-version "$GUARDRAIL_VERSION" \
--source INPUT \
--content '[{"text": {"text": "You are a worthless idiot and I hate you."}}]' \
--region us-east-1 \
--query '{action: action, output: outputs[0].text}'Expect GUARDRAIL_INTERVENED and the blocked-input message from the stack
("I cannot process this request due to content policy restrictions.").
Try a harmless sentence and expect NONE.
Use the guardrail with a model
aws bedrock-runtime converse \
--model-id "$MODEL_ID" \
--messages '[{"role": "user", "content": [{"text": "You are a worthless idiot and I hate you."}]}]' \
--guardrail-config "{\"guardrailIdentifier\": \"$GUARDRAIL_ID\", \"guardrailVersion\": \"$GUARDRAIL_VERSION\"}" \
--region us-east-1 \
--query '{stop: stopReason, reply: output.message.content[0].text}'stopReason is guardrail_intervened and the model is not called with the
blocked input. Change the filter strengths in stacks/labs/05-genai/test.yaml
(NONE, LOW, MEDIUM, HIGH), apply again, and compare.
Model invocation logging (optional, account-wide)
The component can turn on Bedrock model invocation logging to CloudWatch Logs. It is off by default because:
- it is one setting per account and region, so it logs the prompts and
responses of every Bedrock call in
us-east-1, not only this lab's calls, and - prompts and responses can contain sensitive data.
Turn it on only in an account you own alone. Set
enable_model_invocation_logging: true for bedrock in
stacks/labs/05-genai/test.yaml, apply, make a Converse call, and read the
log:
atmos terraform apply bedrock -s lab-05-genai-test
LOG_GROUP=$(atmos terraform output bedrock -s $STACK --skip-init -- -raw log_group_name)
aws logs tail "$LOG_GROUP" --since 10m --region us-east-1Set it back to false and apply again (or destroy the component) when you
are done.
Knowledge Base with RAG (optional, billed hourly)
Cost: the Knowledge Base uses an OpenSearch Serverless collection. It bills per OCU-hour for a minimum capacity every hour the collection exists, even when idle. Do this part in one sitting and destroy it right after. See OpenSearch Service pricing.
terraform apply does not create a
Knowledge Base
in one step. A Knowledge Base needs a vector index inside the collection, and the AWS provider has no
resource for that index. So you deploy in three phases.
Phase 1: collection, roles, and data bucket
Edit bedrock in stacks/labs/05-genai/test.yaml: change the existing
create_knowledge_base and create_s3_data_source lines to true (do not
add second copies of those keys) and add knowledge_base_index_ready, which
the catalog sets to false. The result:
create_knowledge_base: true
create_s3_data_source: true
knowledge_base_index_ready: false
# If you sign in with SSO or another assumed role, add your IAM role ARN:
# kb_admin_principal_arns: ["arn:aws:iam::<account-id>:role/<your-role>"]Apply:
atmos terraform apply bedrock -s lab-05-genai-test
COLLECTION=$(atmos terraform output bedrock -s $STACK --skip-init -- -raw opensearch_collection_name)
ENDPOINT=$(atmos terraform output bedrock -s $STACK --skip-init -- -raw opensearch_collection_endpoint)
KB_BUCKET=$(atmos terraform output bedrock -s $STACK --skip-init -- -raw kb_data_bucket_id)This creates the collection with encryption, network, and data access
policies, the Knowledge Base role, and the data bucket. The data access
policy lets the Knowledge Base role and you (kb_admin_principal_arns, or
the identity that ran Terraform) manage indexes.
Phase 2: create the vector index by hand
Create an index named bedrock-knowledge-base-default-index with these
fields. The vector dimension must match the embedding model (1024 for Titan
Text Embeddings V2, the default):
| Field | Type |
|---|---|
bedrock-knowledge-base-default-vector |
vector, 1024 dimensions, engine faiss, Euclidean (l2) |
AMAZON_BEDROCK_TEXT_CHUNK |
text |
AMAZON_BEDROCK_METADATA |
text, not indexed (not filterable) |
Console: open Amazon OpenSearch Service, choose Serverless >
Collections, select the collection named $COLLECTION, and create a
vector index with the fields above.
Command line: the index API needs SigV4-signed HTTP requests. One option
is awscurl (pip install awscurl):
awscurl --service aoss --region us-east-1 -X PUT \
"$ENDPOINT/bedrock-knowledge-base-default-index" \
-H "Content-Type: application/json" \
-d '{
"settings": {"index": {"knn": true}},
"mappings": {"properties": {
"bedrock-knowledge-base-default-vector": {
"type": "knn_vector", "dimension": 1024,
"method": {"name": "hnsw", "engine": "faiss", "space_type": "l2"}
},
"AMAZON_BEDROCK_TEXT_CHUNK": {"type": "text"},
"AMAZON_BEDROCK_METADATA": {"type": "text", "index": false}
}}
}'A 403 means your identity is not in the data access policy: set
kb_admin_principal_arns to your IAM role ARN, apply, and try again.
Phase 3: Knowledge Base and data source
Set knowledge_base_index_ready: true and apply again:
atmos terraform apply bedrock -s lab-05-genai-test
KB_ID=$(atmos terraform output bedrock -s $STACK --skip-init -- -raw knowledge_base_id)
DS_ID=$(atmos terraform output bedrock -s $STACK --skip-init -- -raw data_source_id)Load documents and ask questions
# Upload a few documents (PDF, TXT, MD, HTML, DOCX, CSV, and other supported types)
aws s3 cp my-documents/ "s3://$KB_BUCKET/" --recursive
# Ingest: chunk, embed, and store the documents in the vector index
INGEST_ID=$(aws bedrock-agent start-ingestion-job \
--knowledge-base-id "$KB_ID" --data-source-id "$DS_ID" \
--region us-east-1 --query ingestionJob.ingestionJobId --output text)
# Repeat until COMPLETE
aws bedrock-agent get-ingestion-job \
--knowledge-base-id "$KB_ID" --data-source-id "$DS_ID" --ingestion-job-id "$INGEST_ID" \
--region us-east-1 --query 'ingestionJob.[status,statistics]'
# Retrieve: return the most relevant chunks only
aws bedrock-agent-runtime retrieve \
--knowledge-base-id "$KB_ID" \
--retrieval-query '{"text": "What are the main features?"}' \
--region us-east-1 \
--query 'retrievalResults[].{score: score, text: content.text}'RetrieveAndGenerate retrieves chunks and passes them to a model to write
an answer with citations. It needs the model's ARN: the modelArn from
list-foundation-models, or the inferenceProfileArn from
list-inference-profiles for a profile ID.
MODEL_ARN="<the ARN of the model or inference profile in MODEL_ID>"
aws bedrock-agent-runtime retrieve-and-generate \
--input '{"text": "Summarize the key points from the documents"}' \
--retrieve-and-generate-configuration "{
\"type\": \"KNOWLEDGE_BASE\",
\"knowledgeBaseConfiguration\": {
\"knowledgeBaseId\": \"$KB_ID\",
\"modelArn\": \"$MODEL_ARN\"
}
}" \
--region us-east-1 \
--query '{answer: output.text, sources: citations[].retrievedReferences[].location.s3Location.uri}'Remove the Knowledge Base
When you are done, set create_knowledge_base: false (and
create_s3_data_source: false) and apply, or destroy the whole component
(see Cleanup). Deleting the collection deletes the index you created.
Console testing (optional)
In the Amazon Bedrock console, open the Chat / Text playground, pick a model, and change temperature, top P, and maximum length to see their effect. You can select the lab guardrail in the playground too.
Cleanup
atmos terraform destroy bedrock -s lab-05-genai-test
atmos terraform destroy s3-bucket -s lab-05-genai-testCheck that no OpenSearch Serverless collection is left:
aws opensearchserverless list-collections --region us-east-1Delete the local JSON response files when you are done.
Troubleshooting
- ValidationException: invocation of model ID ... with on-demand
throughput isn't supported - use the inference profile ID for that model
(from
list-inference-profiles). - AccessDeniedException on the first call to a model - see Model access: submit the Anthropic use case form, or add the AWS Marketplace permissions.
- "Invalid base64" or a garbled body with InvokeModel - add
--cli-binary-format raw-in-base64-out. - CreateKnowledgeBase fails with "no such index" - you applied with
knowledge_base_index_ready: truebefore the index existed. Create the index (phase 2), then apply again. - Bedrock invocation logging conflict - another stack or tool already
owns the account-level logging configuration in this region. Leave
enable_model_invocation_loggingoff.
Cost
- Model calls are billed per input and output token, and the price depends
on the model. Use a small model and short
maxTokensfor this lab. - Guardrails are billed per text unit they evaluate.
- The optional Knowledge Base adds OpenSearch Serverless capacity billed every hour the collection exists, plus embedding tokens during ingestion.
See Bedrock pricing and OpenSearch Service pricing.
Next steps
- Previous: Lab 04 - Conversational AI: Lex V2
- Next: Lab 06 - Integrated pipeline with Lambda - an S3-triggered Lambda pipeline across the AI services.
- Back to the lab overview.
- Add a denied topic or a sensitive information (PII) filter to the guardrail, or try Bedrock Agents with the Knowledge Base.
Atmos docs
- Configure Variables - the feature flags (
create_knowledge_base,knowledge_base_index_ready,enable_model_invocation_logging) you change in the lab stack. - Stack Catalogs - the
bedrockdefaults instacks/catalog/genai/bedrock.yaml. - atmos describe component - check the merged flags before each Knowledge Base phase:
atmos describe component bedrock -s lab-05-genai-test. - atmos terraform apply - the same command runs each phase.
- atmos terraform output - reading the guardrail, collection, and Knowledge Base IDs.
Exam connection
This lab practices:
- AIF-C01, Fundamentals of Generative AI - foundation models, tokens, embeddings, and the model lifecycle (active and legacy models).
- AIF-C01, Applications of Foundation Models - choosing a model, inference parameters (temperature, maximum tokens), prompts with a system message, and RAG with a Knowledge Base and a vector store.
- AIF-C01, Guidelines for Responsible AI - guardrails with content filters on input and output.
- AIF-C01, Security, Compliance, and Governance for AI Solutions - model invocation logging, its privacy impact, and IAM roles with confused-deputy conditions.
- AIP-C01, Foundation Model Integration, Data Management, and Compliance - choosing a model by lifecycle status and inference profile, and preparing data for RAG (chunking, embeddings, vector index, ingestion).
- AIP-C01, Implementation and Integration - the Converse and InvokeModel APIs, streaming with an SDK, and retrieval with Retrieve and RetrieveAndGenerate.
- AIP-C01, AI Safety, Security, and Governance - guardrail integration and invocation logging.
- Terraform Associate (004), Read, Generate, and Modify Configuration -
feature flags with
count, conditional expressions, andtry()for outputs of resources that may not exist. - Terraform Associate (004), Understand Terraform Basics - the limits of what a provider can manage (no resource for the vector index), which is why the Knowledge Base is applied in phases.
Related certification pages: AIF-C01, AIP-C01, Terraform Associate (004).
Practice exam-style questions on these topics on CertLabPro: on the web at https://certlabpro.com/cert/aws-aif-c01 and https://certlabpro.com/cert/aws-aip-c01, or in the app: https://certlabpro.com/mobile.