forked from aws-samples/amazon-bedrock-samples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbedrock_ai21.py
57 lines (42 loc) · 1.15 KB
/
bedrock_ai21.py
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
import boto3
import json
#Create the connection to Bedrock
bedrock = boto3.client(
service_name='bedrock',
region_name='us-west-2',
)
bedrock_runtime = boto3.client(
service_name='bedrock-runtime',
region_name='us-west-2',
)
# Let's see all available AI21 Models
available_models = bedrock.list_foundation_models()
for model in available_models['modelSummaries']:
if 'ai21' in model['modelId']:
print(model)
# Define prompt and model parameters
prompt_data = """Write me a poem about apples"""
body = {
"prompt": prompt_data,
"maxTokens": 200,
"temperature": 0.7,
"topP": 1,
"stopSequences": [],
"countPenalty": {
"scale": 0
},
"presencePenalty": {
"scale": 0
},
"frequencyPenalty": {
"scale": 0
}
}
body = json.dumps(body) # Encode body as JSON string
modelId = 'ai21.j2-ultra'
accept = 'application/json'
contentType = 'application/json'
#Invoke the model
response = bedrock_runtime.invoke_model(body=body, modelId=modelId, accept=accept, contentType=contentType)
response_body = json.loads(response.get('body').read())
print(response_body.get('completions')[0].get('data').get('text'))