Semantic search using Amazon Bedrock Titan in another account
출처: 문서
본문
다른 계정의 Amazon Bedrock Titan을 사용한 시맨틱 검색
Amazon OpenSearch Service를 호스팅하는 계정과 다른 계정에서 호스팅되는 Amazon Bedrock 모델에 대한 커넥터를 구성할 수 있어요. 이 튜토리얼에서는 다른 계정에서 호스팅되는 Amazon Bedrock Titan embedding model을 사용해 Amazon OpenSearch Service에서 시맨틱 검색을 구현하는 방법을 알아봐요. 자세한 정보는 시맨틱 검색을 참고하세요.
Amazon Bedrock에는 쿼터 제한이 있어요. 이 제한을 늘리는 방법에 대한 자세한 정보는 Amazon Bedrock에서 Provisioned Throughput으로 모델 호출 용량 늘리기를 참고하세요. {: .warning}
your_ 접두사로 시작하는 플레이스홀더는 여러분의 값으로 바꾸세요.
{: .note}
크로스 계정 설정
이 튜토리얼에서는 두 개의 AWS 계정을 사용해요. Amazon OpenSearch Service를 호스팅하는 계정 A와 Amazon Bedrock 모델을 호스팅하는 계정 B예요.
Amazon OpenSearch Service를 호스팅하는 계정과 다른 계정에서 호스팅되는 모델을 호출하려면 커넥터 자격 증명에 두 개의 역할을 구성해야 해요:
roleArn: 계정 B의 외부 계정 역할을 수임하는 데 사용되는 계정 A의 역할이에요.externalAccountRoleArn: Amazon Bedrock 모델을 호출하는 데 사용되는 계정 B의 역할이에요.
이 튜토리얼에서는 다음과 같은 역할 이름을 사용해요:
-
계정 A:
my_cross_account_role_accountAAmazon Resource Name(ARN):
arn:aws:iam::<your_aws_account_A>:role/my_cross_account_role_accountA -
계정 B:
my_invoke_bedrock_role_accountBARN:
arn:aws:iam::<your_aws_account_B>:role/my_invoke_bedrock_role_accountB
사전 준비: OpenSearch 클러스터 생성
Amazon OpenSearch Service 콘솔로 이동해 OpenSearch 도메인을 생성하세요.
도메인 ARN을 기록해 두세요. 이후 단계에서 사용하게 돼요.
1단계: 계정 B에서 IAM 역할 생성
Amazon Bedrock에서 모델을 호출하려면 적절한 권한을 가진 AWS Identity and Access Management(IAM) 역할을 생성해야 해요. 커넥터는 이 역할을 사용해 모델을 호출해요.
IAM 콘솔로 이동해 my_invoke_bedrock_role_accountB라는 이름의 새 IAM 역할을 생성하고 다음 신뢰 정책과 권한을 추가하세요:
- 사용자 지정 신뢰 정책:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "",
"Effect": "Allow",
"Principal": {
"AWS": "arn:aws:iam::<your_aws_account_A>:role/my_cross_account_role_accountA"
},
"Action": "sts:AssumeRole"
}
]
}
{% include copy.html %}
- 권한:
{
"Version": "2012-10-17",
"Statement": [
{
"Action": [
"bedrock:InvokeModel"
],
"Effect": "Allow",
"Resource": "arn:aws:bedrock:*::foundation-model/amazon.titan-embed-text-v1"
}
]
}
{% include copy.html %}
역할 ARN을 기록해 두세요. 이후 단계에서 사용하게 돼요.
2. 계정 A에서 IAM 역할 생성
다음 단계에 따라 Amazon OpenSearch Service에서 IAM 역할을 구성하세요.
2.1단계: externalAccountRoleArn을 수임하기 위한 IAM 역할 생성
계정 B의 externalAccountRoleArn을 수임하기 위한 IAM 역할을 생성하세요.
IAM 콘솔로 이동해 my_cross_account_role_accountA라는 이름의 새 IAM 역할을 생성하고 다음 신뢰 정책과 권한을 추가하세요:
- 사용자 지정 신뢰 정책:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Service": "es.amazonaws.com"
},
"Action": "sts:AssumeRole"
}
]
}
{% include copy.html %}
- 권한:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": "sts:AssumeRole",
"Resource": "arn:aws:iam::<your_aws_account_B>:role/my_invoke_bedrock_role_accountB"
}
]
}
{% include copy.html %}
역할 ARN을 기록해 두세요. 이후 단계에서 사용하게 돼요.
2.2단계: 커넥터 요청 서명을 위한 IAM 역할 생성
Create Connector API 요청에 서명하기 위한 새 IAM 역할을 별도로 생성하세요.
다음 신뢰 정책과 권한을 가진 my_create_connector_role_accountA라는 이름의 IAM 역할을 생성하세요:
- 사용자 지정 신뢰 정책:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"AWS": "your_iam_user_arn"
},
"Action": "sts:AssumeRole"
}
]
}
{% include copy.html %}
3단계에서 your_iam_user_arn IAM 사용자를 사용해 이 역할을 수임하게 돼요.
- 권한:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": "iam:PassRole",
"Resource": "arn:aws:iam::<your_aws_account_A>:role/my_cross_account_role_accountA"
},
{
"Effect": "Allow",
"Action": "es:ESHttpPost",
"Resource": "your_opensearch_domain_arn_created"
}
]
}
{% include copy.html %}
이 역할 ARN을 기록해 두세요. 이후 단계에서 사용하게 돼요.
2.3단계: 백엔드 역할 매핑
다음 단계에 따라 백엔드 역할을 매핑하세요:
- OpenSearch Dashboards에 로그인하고 상단 메뉴에서 Security를 선택하세요.
- Roles를 선택한 다음 ml_full_access 역할을 선택하세요.
- ml_full_access 역할 상세 페이지에서 Mapped users를 선택한 다음 Manage mapping을 선택하세요.
- 다음 이미지와 같이 Backend roles 필드에 2.2단계에서 생성한 IAM 역할 ARN(
arn:aws:iam::<your_aws_account_A>:role/my_create_connector_role_accountA)을 입력하세요.
- Map을 선택하세요.
이제 OpenSearch 클러스터에 IAM 역할이 성공적으로 구성됐어요.
3단계: 커넥터 생성
다음 단계에 따라 모델용 커넥터를 생성하세요. 커넥터 생성에 대한 자세한 정보는 커넥터를 참고하세요.
AWS에서 가져온 임시 자격 증명으로 다음 Python 코드를 실행하세요.
import boto3
import requests
from requests_aws4auth import AWS4Auth
host = 'your_amazon_opensearch_domain_endpoint_created'
region = 'your_amazon_opensearch_domain_region'
service = 'es'
assume_role_response = boto3.Session().client('sts').assume_role(
RoleArn="your_iam_role_arn_created_in_step2.2",
RoleSessionName="your_session_name"
)
credentials = assume_role_response["Credentials"]
awsauth = AWS4Auth(credentials["AccessKeyId"], credentials["SecretAccessKey"], region, service, session_token=credentials["SessionToken"])
path = '/_plugins/_ml/connectors/_create'
url = host + path
bedrock_model_region='your_bedrock_model_region'
payload = {
"name": "Amazon Bedrock Connector: titan embedding v1",
"description": "The connector to bedrock Titan embedding model",
"version": 1,
"protocol": "aws_sigv4",
"parameters": {
"region": bedrock_model_region,
"service_name": "bedrock"
},
"credential": {
"roleArn": "arn:aws:iam::<your_aws_account_A>:role/my_cross_account_role_accountA",
"externalAccountRoleArn": "arn:aws:iam::<your_aws_account_B>:role/my_invoke_bedrock_role_accountB"
},
"actions": [
{
"action_type": "predict",
"method": "POST",
"url": f"https://bedrock-runtime.{bedrock_model_region}.amazonaws.com/model/amazon.titan-embed-text-v1/invoke",
"headers": {
"content-type": "application/json",
"x-amz-content-sha256": "required"
},
"request_body": "{ \"inputText\": \"${parameters.inputText}\" }",
"pre_process_function": "connector.pre_process.bedrock.embedding",
"post_process_function": "connector.post_process.bedrock.embedding"
}
]
}
headers = {"Content-Type": "application/json"}
r = requests.post(url, auth=awsauth, json=payload, headers=headers)
print(r.text)
{% include copy.html %}
스크립트는 커넥터 ID를 출력해요:
{"connector_id":"N0qpQY0BOhavBOmfOCnw"}
커넥터 ID를 기록해 두세요. 다음 단계에서 사용하게 돼요.
4단계: 모델 생성 및 테스트
OpenSearch Dashboards에 로그인하고 DevTools 콘솔을 연 다음, 다음 요청을 실행해 모델을 생성하고 테스트하세요.
-
모델 그룹을 생성하세요:
POST /_plugins/_ml/model_groups/_register { "name": "Bedrock_embedding_model", "description": "Test model group for bedrock embedding model" }{% include copy-curl.html %}
응답에는 모델 그룹 ID가 포함돼요:
{ "model_group_id": "LxWiQY0BTaDH9c7t9xeE", "status": "CREATED" } -
모델을 등록하세요:
POST /_plugins/_ml/models/_register { "name": "bedrock titan embedding model v1", "function_name": "remote", "description": "test embedding model", "model_group_id": "LxWiQY0BTaDH9c7t9xeE", "connector_id": "N0qpQY0BOhavBOmfOCnw" }{% include copy-curl.html %}
응답에는 모델 ID가 포함돼요:
{ "task_id": "O0q3QY0BOhavBOmf1SmL", "status": "CREATED", "model_id": "PEq3QY0BOhavBOmf1Sml" } -
모델을 배포하세요:
POST /_plugins/_ml/models/PEq3QY0BOhavBOmf1Sml/_deploy{% include copy-curl.html %}
응답에는 배포 작업의 task ID가 포함돼요:
{ "task_id": "PUq4QY0BOhavBOmfBCkQ", "task_type": "DEPLOY_MODEL", "status": "COMPLETED" } -
모델을 테스트하세요:
POST /_plugins/_ml/models/PEq3QY0BOhavBOmf1Sml/_predict { "parameters": { "inputText": "hello world" } }{% include copy-curl.html %}
응답에는 모델이 생성한 임베딩이 포함돼요:
{ "inference_results": [ { "output": [ { "name": "sentence_embedding", "data_type": "FLOAT32", "shape": [ 1536 ], "data": [ 0.7265625, -0.0703125, 0.34765625, ...] } ], "status_code": 200 } ] }
5단계: 시맨틱 검색 구성
다음 단계에 따라 시맨틱 검색을 구성하세요.
5.1단계: ingest pipeline 생성
먼저 Amazon SageMaker의 모델을 사용해 입력 텍스트에서 임베딩을 생성하는 ingest pipeline을 생성하세요:
PUT /_ingest/pipeline/my_bedrock_embedding_pipeline
{
"description": "text embedding pipeline",
"processors": [
{
"text_embedding": {
"model_id": "your_bedrock_embedding_model_id_created_in_step4",
"field_map": {
"text": "text_knn"
}
}
}
]
}
{% include copy-curl.html %}
5.2단계: 벡터 인덱스 생성
다음으로, 입력 텍스트와 생성된 임베딩을 저장하기 위한 벡터 인덱스를 생성하세요:
PUT my_index
{
"settings": {
"index": {
"knn.space_type": "cosinesimil",
"default_pipeline": "my_bedrock_embedding_pipeline",
"knn": "true"
}
},
"mappings": {
"properties": {
"text_knn": {
"type": "knn_vector",
"dimension": 1536
}
}
}
}
{% include copy-curl.html %}
5.3단계: 데이터 ingest
인덱스에 샘플 문서를 ingest하세요:
POST /my_index/_doc/1000001
{
"text": "hello world."
}
{% include copy-curl.html %}
5.4단계: 인덱스 검색
벡터 검색을 실행해 벡터 인덱스에서 문서를 조회하세요:
POST /my_index/_search
{
"query": {
"neural": {
"text_knn": {
"query_text": "hello",
"model_id": "your_embedding_model_id_created_in_step4",
"k": 100
}
}
},
"size": "1",
"_source": ["text"]
}
{% include copy-curl.html %}