Created
July 12, 2024 02:50
-
-
Save VioletVivirand/e9c0dbb22037945a328ef0f2a3a6e932 to your computer and use it in GitHub Desktop.
Invoke Amazon Bedrock Claude 3 with an image in message block
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Use the native inference API to send a text message to Anthropic Claude. | |
import boto3 | |
import json | |
import base64 | |
import httpx | |
from botocore.exceptions import ClientError | |
# Create a Bedrock Runtime client in the AWS Region of your choice. | |
client = boto3.client("bedrock-runtime", region_name="us-east-1") | |
# Set the model ID, e.g., Claude 3 Haiku. | |
model_id = "anthropic.claude-3-haiku-20240307-v1:0" | |
# Get an image and encode it to Base64 format | |
image1_url = "https://upload.wikimedia.org/wikipedia/commons/a/a7/Camponotus_flavomarginatus_ant.jpg" | |
image1_media_type = "image/jpeg" | |
image1_data = base64.b64encode(httpx.get(image1_url).content).decode("utf-8") | |
# Format the request payload using the model's native structure. | |
native_request = { | |
"anthropic_version": "bedrock-2023-05-31", | |
"max_tokens": 512, | |
"temperature": 0.5, | |
"messages": [ | |
{ | |
"role": "user", | |
"content": [ | |
{ | |
"type": "image", | |
"source": { | |
"type": "base64", | |
"media_type": image1_media_type, | |
"data": image1_data, | |
}, | |
}, | |
{ | |
"type": "text", | |
"text": "Describe this image." | |
} | |
], | |
} | |
], | |
} | |
# Convert the native request to JSON. | |
request = json.dumps(native_request) | |
try: | |
# Invoke the model with the request. | |
response = client.invoke_model(modelId=model_id, body=request) | |
except (ClientError, Exception) as e: | |
print(f"ERROR: Can't invoke '{model_id}'. Reason: {e}") | |
exit(1) | |
# Decode the response body. | |
model_response = json.loads(response["body"].read()) | |
# Extract and print the response text. | |
response_text = model_response["content"][0]["text"] | |
print(response_text) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment