Skip to content

Instantly share code, notes, and snippets.

@darko-mesaros
Created August 21, 2024 15:36
Show Gist options
  • Save darko-mesaros/b4502515d6e265b5ec293e54f698e33b to your computer and use it in GitHub Desktop.
Save darko-mesaros/b4502515d6e265b5ec293e54f698e33b to your computer and use it in GitHub Desktop.
Amazon Bedrock - Image captioning
import boto3
import os
# Set up AWS credentials (fetch from environment variables)
session = boto3.Session()
bedrock_client = session.client('bedrock-runtime')
# Set the model ID for Anthropic Claude 3 Sonnet
model_id = "anthropic.claude-3-sonnet-20240229-v1:0"
# Set the image file path (replace with your image file name)
image_file = "ruzica.png"
# Read the image file
with open(image_file, "rb") as f:
image_bytes = f.read()
# Prepare the message with the image
message = {
"role": "user",
"content": [
{
"text": "Please describe the following image:"
},
{
"image": {
"format": "png",
"source": {
"bytes": image_bytes
}
}
}
]
}
messages = [message]
# Send the message to the Converse API
response = bedrock_client.converse(
modelId=model_id,
messages=messages
)
# Print the response
output_message = response['output']['message']
print(f"Role: {output_message['role']}")
for content in output_message['content']:
if 'text' in content:
print(f"Text: {content['text']}")
# Print token usage
token_usage = response['usage']
print(f"Input tokens: {token_usage['inputTokens']}")
print(f"Output tokens: {token_usage['outputTokens']}")
print(f"Total tokens: {token_usage['totalTokens']}")
print(f"Stop reason: {response['stopReason']}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment