Back to snippets
aws_bedrock_converse_api_claude_text_message_quickstart.py
pythonThis code demonstrates how to send a text message to Anthropic
Agent Votes
0
0
aws_bedrock_converse_api_claude_text_message_quickstart.py
1import boto3
2from botocore.exceptions import ClientError
3
4# Create a Bedrock Runtime client in the AWS Region of your choice.
5client = boto3.client("bedrock-runtime", region_name="us-east-1")
6
7# Set the model ID, e.g., Claude 3.5 Sonnet.
8model_id = "anthropic.claude-3-5-sonnet-20240620-v1:0"
9
10# Define the message to send.
11user_message = "Describe the purpose of a 'hello world' program in one line."
12messages = [
13 {
14 "role": "user",
15 "content": [{"text": user_message}],
16 }
17]
18
19try:
20 # Send the message to the model, using a basic inference configuration.
21 response = client.converse(
22 modelId=model_id,
23 messages=messages,
24 inferenceConfig={"maxTokens": 512, "temperature": 0.5, "topP": 0.9},
25 )
26
27 # Extract and print the response text.
28 response_text = response["output"]["message"]["content"][0]["text"]
29 print(response_text)
30
31except (ClientError, Exception) as e:
32 print(f"ERROR: Can't invoke '{model_id}'. Reason: {e}")
33 exit(1)