-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclaude_3.py
More file actions
212 lines (176 loc) · 7.55 KB
/
Copy pathclaude_3.py
File metadata and controls
212 lines (176 loc) · 7.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
import base64
import json
import logging
import boto3
from botocore.exceptions import ClientError
logger = logging.getLogger(__name__)
def invoke_claude_3_with_text(prompt):
"""
Invokes Anthropic Claude 3 Sonnet to run an inference using the input
provided in the request body.
:param prompt: The prompt that you want Claude 3 to complete.
:return: Inference response from the model.
"""
client = boto3.client(service_name="bedrock-runtime", region_name="us-east-1")
# Invoke Claude 3 with the text prompt
model_id = "anthropic.claude-3-sonnet-20240229-v1:0"
try:
response = client.invoke_model(
modelId=model_id,
body=json.dumps(
{
"anthropic_version": "bedrock-2023-05-31",
"max_tokens": 4096,
"messages": [
{
"role": "user",
"content": [{"type": "text", "text": prompt}],
}
],
}
),
)
# 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(output["text"])
final_result=output["text"]
return final_result
except ClientError as err:
logger.error(
"Couldn't invoke Claude 3 Sonnet. Here's why: %s: %s",
err.response["Error"]["Code"],
err.response["Error"]["Message"],
)
raise
# snippet-start:[python.example_code.bedrock-runtime.Claude3Wrapper.class]
class Claude3Wrapper:
"""Encapsulates Claude 3 model invocations using the Amazon Bedrock Runtime client."""
def __init__(self, client=None):
"""
:param client: A low-level client representing Amazon Bedrock Runtime.
Describes the API operations for running inference using Bedrock models.
Default: None
"""
self.client = client
# snippet-start:[python.example_code.bedrock-runtime.InvokeAnthropicClaude3Text]
def invoke_claude_3_with_text(self, prompt):
"""
Invokes Anthropic Claude 3 Sonnet to run an inference using the input
provided in the request body.
:param prompt: The prompt that you want Claude 3 to complete.
:return: Inference response from the model.
"""
# Initialize the Amazon Bedrock runtime client
client = self.client or boto3.client(
service_name="bedrock-runtime", region_name="us-east-1"
)
# Invoke Claude 3 with the text prompt
model_id = "anthropic.claude-3-sonnet-20240229-v1:0"
try:
response = client.invoke_model(
modelId=model_id,
body=json.dumps(
{
"anthropic_version": "bedrock-2023-05-31",
"max_tokens": 4096,
"messages": [
{
"role": "user",
"content": [{"type": "text", "text": prompt}],
}
],
"temperature": .01,
}
),
)
# 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(output["text"])
return result
except ClientError as err:
logger.error(
"Couldn't invoke Claude 3 Sonnet. Here's why: %s: %s",
err.response["Error"]["Code"],
err.response["Error"]["Message"],
)
raise
# snippet-end:[python.example_code.bedrock-runtime.InvokeAnthropicClaude3Text]
# snippet-start:[python.example_code.bedrock-runtime.InvokeAnthropicClaude3Multimodal]
def invoke_claude_3_multimodal(self, prompt, base64_image_data):
"""
Invokes Anthropic Claude 3 Sonnet to run a multimodal inference using the input
provided in the request body.
:param prompt: The prompt that you want Claude 3 to use.
:param base64_image_data: The base64-encoded image that you want to add to the request.
:return: Inference response from the model.
"""
# Initialize the Amazon Bedrock runtime client
client = self.client or boto3.client(
service_name="bedrock-runtime", region_name="us-east-1"
)
# Invoke the model with the prompt and the encoded image
model_id = "anthropic.claude-3-sonnet-20240229-v1:0"
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",
"data": base64_image_data,
},
},
],
}
],
}
try:
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(output["text"])
return result
except ClientError as err:
logger.error(
"Couldn't invoke Claude 3 Sonnet. Here's why: %s: %s",
err.response["Error"]["Code"],
err.response["Error"]["Message"],
)
raise
# snippet-end:[python.example_code.bedrock-runtime.InvokeAnthropicClaude3Multimodal]