Last active
May 9, 2025 07:07
-
-
Save DennisTraub/990665122b8128908f6896573cad8572 to your computer and use it in GitHub Desktop.
Image analysis with Claude 3 Sonnet on Amazon Bedrock
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
| import base64 | |
| import boto3 | |
| import json | |
| # Initialize the Amazon Bedrock runtime client | |
| client = self.client or boto3.client(service_name="bedrock-runtime", region_name="us-east-1") | |
| # Encode the image using base64 | |
| with open("path/to/you/image", "rb") as image_file: | |
| base64_image_data = base64.b64encode(image_file.read()).decode("utf8") | |
| # Prepare the invocation request with the prompt and the encoded image | |
| prompt = "What can you see in this image?" | |
| request_body = { | |
| "anthropic_version": "bedrock-2023-05-31", | |
| "max_tokens": 2048, | |
| "messages": [ | |
| { | |
| "role": "user", | |
| "content": [{"type": "text", "text": prompt,}, | |
| { | |
| "type": "image", | |
| "source": { | |
| "type": "base64", | |
| "media_type": "image/png", # Use the file type of your image | |
| "data": base64_image_data, | |
| } | |
| } | |
| ] | |
| } | |
| ] | |
| } | |
| # Invoke the model | |
| response = client.invoke_model(modelId=model_id, body=json.dumps(request_body)) | |
| # Process and print the response | |
| result = json.loads(response.get("body").read()) | |
| input_tokens = result["usage"]["input_tokens"] | |
| output_tokens = result["usage"]["output_tokens"] | |
| output_list = result.get("content", []) | |
| print("Invocation details:") | |
| print(f"- The input length is {input_tokens} tokens.") | |
| print(f"- The output length is {output_tokens} tokens.") | |
| print(f"- The model returned {len(output_list)} response(s):") | |
| for output in output_list: | |
| print(f"Response: output["text"]") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment