Amazon Bedrock with Lambda Function

2023/09/30閱讀時間約 6 分鐘

Continue from here

Using Amazon Bedrock from Boto3


Prerequisites

Create an IAM role with access to Bedrock

Create an "IAM Role" that defines the permissions needed to call Bedrock API.

The policy for accessing permissions is defined as follows:

{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": "bedrock:*",
"Resource": "*"
}
]
}

The policy definition of the trust relationship is as follows:

{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"sts:AssumeRole"
],
"Principal": {
"Service": [
"lambda.amazonaws.com"
]
}
}
]
}


Lambda

raw-image

Execution role

raw-image

First of all, you need to confirm the Boto3 version, otherwise you will encounter "errorMessage: "Unknown service: 'bedrock-runtime'".

raw-image

How to check

import json
import botocore
import boto3

def lambda_handler(event, context):

print('botocore vertion: {0}'.format(botocore.__version__))
print('boto3 vertion: {0}'.format(boto3.__version__))

The result is the old version

raw-image

What can I do?

Get the latest Boto3 library and create a zip file.

$ mkdir boto3
$ pip install -t ./boto3 boto3
$ mv ./boto3 ./python
$ zip -r boto3-1.28.57.zip ./python


Create Lambda Layer

raw-image

Upload a file and select a supported version

raw-image

Add Layer to Lambda Function

raw-image

Select the just created upload

raw-image

Retesting

raw-image


sample code

import boto3
import json

bedrock_runtime = boto3.client('bedrock-runtime')

def lambda_handler(event, context):

prompt = event.get('prompt')

modelId = 'ai21.j2-mid-v1'
accept = 'application/json'
contentType = 'application/json'

body = json.dumps({
"prompt": prompt,
"maxTokens": 100,
"temperature": 0.7,
"topP": 1,
})

response = bedrock_runtime.invoke_model(
modelId=modelId,
accept=accept,
contentType=contentType,
body=body
)

response_body = json.loads(response.get('body').read())

outputText = response_body.get('completions')[0].get('data').get('text')

print(outputText)

Enter the text you want to ask

raw-image
{
"prompt": "Highest mountain in the world?"
}


Results

raw-image

I got a good answer.


13會員
57內容數
留言0
查看全部
發表第一個留言支持創作者!