Ravindra BagaleCourses & study guides मराठी Track your progress

AWS Cloud

AWS SDK AI Examples: Rekognition Image Labels and Bedrock Text Generation (Python, PHP, Node.js)

AWS has ready-made AI you call like any other API. From Python, PHP and Node.js we detect labels and text in photos with Rekognition, moderate uploads, and generate text with Amazon Bedrock using the Converse API, including streaming. The example: a second-hand marketplace with Giulia in Milan and Meera in Kochi.

In this chapter

  • Detect labels in an image
  • Read text and moderate content
  • Call Bedrock Converse
  • Stream model output
  • Control cost and safety

1. The big picture: the shop assistant

A seller uploads a photo of a bicycle. One assistant looks at it and says "bicycle, wheel, outdoor". Another writes a friendly listing: "Lightly used city bike, €180". Rekognition is the first assistant, Bedrock the second.

Rekognition takes an Image (bytes or S3Object) and returns labels with Confidence. Bedrock Converse takes a modelId and messages and returns the reply plus token usage. Enable model access in the Bedrock console first.

Photo to listingUpload photo to S3DetectLabels + DetectModerationLabelsReject unsafe photosConverse: write a listing from labelsSave listing
Bedrock runtime calls use the bedrock-runtime client, not bedrock.

2. Detect labels

Start with a harmless image you can inspect yourself. In the sample, Rekognition receives a bucket and key for bike-221.jpg. The service needs access to that object in the appropriate Region for the request. An SDK example that reads a local file passes its bytes instead. Those are two ways to supply the image. A bad reference or missing permission prevents the inference from reading the intended picture.

Look at the returned names and confidence fields for the known subject. Lowering the requested minimum can include more tentative labels. Raising it can leave out uncertain ones. Compare one known subject with one noticeably different image and record which output changes. A label result is a model’s estimate. If a later application uses it for an important decision, set explicit review criteria and measure results on representative sample images.

Giulia wants each photo tagged so buyers can search "bicycle" or "sofa".

DetectLabels with MaxLabels and MinConfidence. Use S3Object for photos already in S3 (same region).

  1. Python.
import boto3
rk = boto3.client("rekognition", region_name="eu-west-1")
r = rk.detect_labels(Image={"S3Object": {"Bucket": "market-photos-mi", "Name": "bike-221.jpg"}},
    MaxLabels=5, MinConfidence=80)
for l in r["Labels"]: print(l["Name"], round(l["Confidence"]))

Expected output:

Bicycle 99
Wheel 98
Vehicle 97
Outdoors 88
City 82
  1. Node.js: from local bytes.
import { readFileSync } from "node:fs";
import { RekognitionClient, DetectLabelsCommand } from "@aws-sdk/client-rekognition";
const rk = new RekognitionClient({ region: "ap-south-1" });
const r = await rk.send(new DetectLabelsCommand({ Image: { Bytes: readFileSync("sofa-88.jpg") }, MaxLabels: 3 }));
console.log(r.Labels.map(l => l.Name).join(", "));

Expected output:

Couch, Furniture, Living Room
  1. PHP.
<?php
require "vendor/autoload.php";
$rk = new Aws\Rekognition\RekognitionClient(["region" => "eu-west-1"]);
$r = $rk->detectLabels(["Image" => ["Bytes" => file_get_contents("lamp.jpg")], "MaxLabels" => 2]);
echo implode(", ", array_column($r["Labels"], "Name")), PHP_EOL;

Expected output:

Lamp, Lampshade
  1. Verify with the CLI.
aws rekognition detect-labels --image "S3Object={Bucket=market-photos-mi,Name=bike-221.jpg}" --max-labels 1 --region eu-west-1 --query "Labels[0].Name" --output text

Expected output:

Bicycle

3. Read text and moderate

Meera blocks unsafe photos and reads the price tag in a photo of a Kochi spice tin: ₹350.

DetectText returns LINE and WORD items. DetectModerationLabels returns categories like "Violence"; an empty list means it looks safe.

  1. Python: text lines.
r = rk.detect_text(Image={"Bytes": open("tin.jpg", "rb").read()})
print([t["DetectedText"] for t in r["TextDetections"] if t["Type"] == "LINE"])

Expected output:

['KERALA PEPPER', 'MRP ₹350', '200 g']
  1. Node.js: moderation.
import { DetectModerationLabelsCommand } from "@aws-sdk/client-rekognition";
const r = await rk.send(new DetectModerationLabelsCommand({ Image: { Bytes: readFileSync("sofa-88.jpg") }, MinConfidence: 60 }));
console.log(r.ModerationLabels.length === 0 ? "safe" : r.ModerationLabels.map(m => m.Name));

Expected output:

safe
  1. PHP: reject in an upload handler.
<?php
$m = $rk->detectModerationLabels(["Image" => ["Bytes" => file_get_contents($_FILES["p"]["tmp_name"])], "MinConfidence" => 70]);
if (count($m["ModerationLabels"])) { http_response_code(422); exit("Photo not allowed"); }
echo "accepted", PHP_EOL;

Expected output:

accepted
  1. Verify: a test image.
aws rekognition detect-text --image-bytes fileb://tin.jpg --region ap-south-1 --query "TextDetections[?Type=='LINE'] | [1].DetectedText" --output text

Expected output:

MRP ₹350

4. Generate text with Bedrock

Keep the two AI jobs separate. Rekognition label detection analyzes an image and returns labels and confidence values. Bedrock text generation sends a prompt to a selected model and returns generated content. A label confidence is a model estimate. A fluent generated sentence is still something you should verify against the information you gave the model.

Test a synthetic image with a known subject and inspect which labels and confidence values appear. For text generation, use a short prompt with three classroom facts and ask for one sentence based on them. Compare the answer with those facts. When streaming, pieces of the response arrive as the model generates them. Assemble them before judging the final text and check that the model and Region match your setup.

From labels and a price, write a short, honest listing in English or Italian.

Converse uses the same request shape for every model: messages, system, inferenceConfig. Use a model ID or inference profile enabled in your account.

  1. Python.
br = boto3.client("bedrock-runtime", region_name="eu-west-1")
r = br.converse(modelId="amazon.nova-lite-v1:0",
    system=[{"text": "You write short marketplace listings. Max 25 words. No made-up facts."}],
    messages=[{"role": "user", "content": [{"text": "Labels: Bicycle, City. Price €180. Condition: lightly used. Italian."}]}],
    inferenceConfig={"maxTokens": 120, "temperature": 0.4})
print(r["output"]["message"]["content"][0]["text"]); print(r["usage"])

Expected output:

Bici da città poco usata, pronta per Milano. €180.
{'inputTokens': 41, 'outputTokens': 17, 'totalTokens': 58}
  1. Node.js.
import { BedrockRuntimeClient, ConverseCommand } from "@aws-sdk/client-bedrock-runtime";
const br = new BedrockRuntimeClient({ region: "ap-south-1" });
const r = await br.send(new ConverseCommand({ modelId: "apac.amazon.nova-lite-v1:0",
  messages: [{ role: "user", content: [{ text: "Write a 20-word listing: Couch, 3-seater, ₹9,500, Kochi pickup." }] }],
  inferenceConfig: { maxTokens: 100 } }));
console.log(r.output.message.content[0].text);

Expected output:

Comfortable 3-seater couch in great shape. ₹9,500. Pickup in Kochi.
  1. PHP.
<?php
$br = new Aws\BedrockRuntime\BedrockRuntimeClient(["region" => "eu-west-1"]);
$r = $br->converse(["modelId" => "amazon.nova-lite-v1:0",
  "messages" => [["role" => "user", "content" => [["text" => "One-line listing: Lamp, brass, £25, London."]]]],
  "inferenceConfig" => ["maxTokens" => 60]]);
echo $r["output"]["message"]["content"][0]["text"], PHP_EOL;

Expected output:

Vintage brass lamp, warm light, £25 — collect in London.
  1. Verify: model access is enabled.
aws bedrock list-foundation-models --region eu-west-1 --by-provider amazon --query "modelSummaries[?modelId=='amazon.nova-lite-v1:0'].modelId" --output text

Expected output:

amazon.nova-lite-v1:0

5. Stream the answer

In the chat helper, buyers in Dubai should see words appear at once, not wait 5 seconds.

ConverseStream returns an event stream: contentBlockDelta events carry text pieces; metadata carries usage.

  1. Python.
r = br.converse_stream(modelId="amazon.nova-lite-v1:0",
    messages=[{"role": "user", "content": [{"text": "Is a used bike for AED 700 a fair price? 2 lines."}]}])
for ev in r["stream"]:
    if "contentBlockDelta" in ev: print(ev["contentBlockDelta"]["delta"]["text"], end="", flush=True)
print()

Expected output:

For a lightly used city bike, AED 700 is fair.
Check brakes and gears before paying.
  1. Node.js.
import { ConverseStreamCommand } from "@aws-sdk/client-bedrock-runtime";
const r = await br.send(new ConverseStreamCommand({ modelId: "apac.amazon.nova-lite-v1:0",
  messages: [{ role: "user", content: [{ text: "Give 3 tips to sell a sofa fast." }] }] }));
for await (const ev of r.stream) if (ev.contentBlockDelta) process.stdout.write(ev.contentBlockDelta.delta.text);

Expected output:

1. Clear photos in daylight. 2. Fair price. 3. Offer pickup times.
  1. PHP.
<?php
$r = $br->converseStream(["modelId" => "amazon.nova-lite-v1:0",
  "messages" => [["role" => "user", "content" => [["text" => "Say hello in Italian and Malayalam."]]]]]);
foreach ($r["stream"] as $ev) if (isset($ev["contentBlockDelta"])) echo $ev["contentBlockDelta"]["delta"]["text"];
echo PHP_EOL;

Expected output:

Ciao! നമസ്കാരം!
  1. Verify: token usage metric.
aws cloudwatch get-metric-statistics --namespace AWS/Bedrock --metric-name OutputTokenCount --dimensions Name=ModelId,Value=amazon.nova-lite-v1:0 --statistics Sum --period 3600 --start-time $(date -u -d "-1 hour" +%FT%TZ) --end-time $(date -u +%FT%TZ) --region eu-west-1 --query "Datapoints[0].Sum"

Expected output:

112.0

6. The same call in Java, Go, .NET and the CLI

Teams often mix languages. Once you know the call in Python, PHP and Node.js, the other SDKs are the same API with different syntax.

All of them call the Converse API. Use the CLI line to test it quickly from a terminal.

StackCode
AWS CLIaws bedrock-runtime converse --model-id amazon.nova-lite-v1:0 --messages '[{"role":"user","content":[{"text":"Hi"}]}]'
Java v2var r = br.converse(b -> b.modelId("amazon.nova-lite-v1:0").messages(Message.builder().role(ConversationRole.USER).content(ContentBlock.fromText("Hi")).build()));
Go v2out, _ := client.Converse(ctx, &bedrockruntime.ConverseInput{ModelId: aws.String("amazon.nova-lite-v1:0"), Messages: msgs})
.NETvar r = await br.ConverseAsync(new ConverseRequest { ModelId = "amazon.nova-lite-v1:0", Messages = msgs });

7. Clean up so nothing keeps costing

Lab resources left running cost money and can be a security risk.

Delete in reverse order: children first, then parents.

  1. Nothing to delete for on-demand calls; remove test photos.
aws s3 rm s3://market-photos-mi/bike-221.jpg

Expected output:

(no output means success)

Ravindra Bagale's Tip

Always set maxTokens and log usage; an unbounded prompt in a loop can cost real money fast.

8. Interview questions and answers

Q. Rekognition input options?

Image bytes (up to 5 MB) or an S3Object in the same region.

Q. Which client calls models?

bedrock-runtime (Converse, InvokeModel); bedrock is for management.

Q. Why Converse over InvokeModel?

One request format for all models, plus tools and streaming.

Q. How do you stream?

ConverseStream and read contentBlockDelta events.

Q. What does an empty ModerationLabels mean?

No unsafe content above MinConfidence.

Try at home

  1. Chain it: Python reads labels for an S3 photo and asks Bedrock for a listing in Marathi.
  2. Add a 1-cent budget guard in Node.js that stops when totalTokens > 2,000.

In short

  1. DetectLabels with confidence.
  2. DetectText / Moderation.
  3. Converse = one format.
  4. ConverseStream for chat.
  5. Limit tokens, log usage.

Choose inputs whose use you can explain

Try a synthetic image and a harmless text prompt. Compare response labels/confidence and measure the actual input/output limits. Check the selected Bedrock model's Region, authorization and API before changing code. Do not use private faces or customer documents in a lab.

Interview check Is a high-confidence label ground truth?

No. It is a model score. Review false positives and verify outcomes against known sample data.

Reference documentation

Practise this chapter

Interview questions and answers

How would you test two AI integrations without assuming the model is always right?

I would use a harmless image with a known subject and inspect the returned labels and confidence. For generation, I would provide known classroom facts and check that the final text matches them. I would verify model, Region and output type separately from the accuracy of the result.

Check your understanding

Choose an answer, then compare your reasoning with the explanation.

0 of 3 answered correctly
1. Which output is typical of Rekognition label detection?

Answer and explanation

C. Image labels with confidence values

The image model reports estimated labels and confidence, which can be checked against a known image.

2. What should you do with a fluent Bedrock result about classroom facts?

Answer and explanation

A. Compare its claims with the given facts

Generated text can add or misstate details. Verify it against the input and expected requirements.

3. What is different when streaming text generation?

Answer and explanation

C. Chunks arrive before the full answer is assembled

Streaming changes how the response is delivered. Assemble it before judging the complete output.

Practice Tasks

Practice checks run in your browser. They check the answer for this exercise; they do not create resources or connect to your AWS account.

About this scenario

Bengaluru HealthTech is a health technology business in Bengaluru. Arjun Rao looks after its IT and cloud work. They count money in INR and run their AWS resources in the ap-south-1 Region. In the tasks below you do real jobs for them using what this lesson teaches. All names, account IDs, IP addresses and numbers are made up for practice.

0 / 10

Easy List Bedrock models

See which foundation models are offered in your Region.

List the foundation models available in Amazon Bedrock.

  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. Flags can be in any order. Click Check answer.

Easy List SageMaker endpoints

Endpoints cost money every hour; list them to find forgotten ones.

List SageMaker endpoints.

  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. Flags can be in any order. Click Check answer.

Easy How many addresses in a /16?

Picking a VPC size needs this count.

Bengaluru HealthTech plans the VPC 10.130.0.0/16. How many IP addresses does it hold in total?

  1. Write down the numbers the task gives you.
  2. Work it out step by step on paper.
  3. Type only the final answer in the box.
  4. Click Check answer.

Easy Port for SSH

Security group rules need the right port.

Which TCP port must the security group open for SSH?

  1. Write down the numbers the task gives you.
  2. Work it out step by step on paper.
  3. Type only the final answer in the box.
  4. Click Check answer.

Easy Show where you are

Before you copy or delete anything, you must know which folder you are in.

Arjun Rao logged in to the Bengaluru HealthTech server and is not sure which folder the terminal is in. Print the current folder path.

  1. Find the Linux command that does this job.
  2. Add the options (like -r or -h) the task needs.
  3. Add the file names, folders or users in the right order.
  4. Use sudo if the job changes system files or users. Click Check answer.

Easy Read-only access to one bucket

Least privilege: give only the actions and the bucket the job needs.

Write an identity policy that lets the user read objects (s3:GetObject) only in bucket blrhealthtech-data.

  1. Start with { "Version": "2012-10-17", "Statement": [ ... ] }.
  2. In each statement write Effect, Action and Resource.
  3. Give only what the task needs (least privilege).
  4. Use double quotes and commas correctly. Click Check answer.

Medium Detect labels in an image

Rekognition names objects in a photo, e.g. to tag product images.

Detect labels in s3://blrhealthtech-media/shop/p1.jpg (Bucket=blrhealthtech-media, Name=shop/p1.jpg), max 10 labels.

  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. Flags can be in any order. Click Check answer.

Medium Allow one Bedrock model

Limit apps to the approved model so costs stay predictable.

Allow bedrock:InvokeModel on arn:aws:bedrock:ap-south-1::foundation-model/amazon.nova-lite-v1:0 only.

  1. Start with { "Version": "2012-10-17", "Statement": [ ... ] }.
  2. In each statement write Effect, Action and Resource.
  3. Give only what the task needs (least privilege).
  4. Use double quotes and commas correctly. Click Check answer.

Medium Usable IPs in an AWS /24 subnet

AWS keeps 5 addresses in every subnet.

How many addresses can Bengaluru HealthTech use for servers in subnet 10.130.1.0/24 on AWS?

  1. Write down the numbers the task gives you.
  2. Work it out step by step on paper.
  3. Type only the final answer in the box.
  4. Click Check answer.

Hard Ask a model a question

Converse is one API shape for many models.

Call converse on model amazon.nova-lite-v1:0 with the messages in msgs.json.

  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. Flags can be in any order. Click Check answer.

Revision, comparison and interview cards

Revise this lesson in a few minutes. Save the cards on your phone or download them as PNG files. The QR code on each card opens this lesson.

Rekognition labels. DetectLabels with MinConfidence. Bytes up to 5 MB, or S3Object. DetectText: LINE and WORD. Empty moderation = safe.
Revision card: Rekognition labels · Download PNG · Open card page
Bedrock Converse. Client: bedrock-runtime. Enable model access first. Set maxTokens, log usage. ConverseStream for chat.
Revision card: Bedrock Converse · Download PNG · Open card page
Rekognition vs Bedrock. Ready-made vision API. / Foundation models API.
Comparison: Rekognition vs Bedrock · Download PNG · Open card page
Bedrock AccessDeniedException?. Model access not enabled. Wrong region for the model. IAM needs bedrock:InvokeModel.
Interview card: Bedrock AccessDeniedException? · Download PNG · Open card page

More cards: Ravi Sir's Cards.