AWS Builder Center

手把手搭建 Bedrock Knowledge Base:S3 数据源 + OpenSearch Serverless 向量库实战

今天的文章,让我们继续学习 AWS Bedrock平台的另一个重要服务:Knowledge Base,它是基于 AWS 云平台开发 RAG系统的核心服务。

背景

今天的文章,让我们继续学习  AWS Bedrock  AI 平台的另一个重要服务: Knowledge Base ,它是基于 AWS 云平台开发  RAG  系统的核心服务。
我们会利用  AWS S3  服务作为数据源来存储非结构化数据,然后使用  AWS OpenSearch Serverless (AOSS)服务作为  RAG  系统的向量存储。而  Bedrock Knowledge Base  则封装和托管了  RAG  数据流的其他主要功能:数据摄取、建立索引、检索生成等。
另外,为了构建安全的  RAG  系统,我们还会介绍如何使用  AWS IAM  服务来控制访问权限。如果你对上面的几个核心组件感兴趣,那么这篇文章一定值得收藏!
除此之外,我之前的 Azure 系列文章里,曾经花了很大的精力介绍使用  Azure AI Search  服务打造  RAG  系统的方案。从功能定位上, Bedrock Knowledge Base  跟它是纯竞品关系,大家也可以仔细分析它们的差异,寻找最适合你的方案!



架构设计

这套  RAG  系统的几个核心组件/服务如下:
  •  AWS S3 : AWS  的对象存储服务,类似于  Azure Blob Storage  的作用。本篇文章中,我们使用  S3  作为数据源来存储 PDF 文件。
  •  Bedrock Model Catalog :构造一个  RAG  系统需要两个模型:一个  embedding  模型,一个基础模型。在本篇文章中,我们分别使用  amazon.titan-embed-text-v2:0  和  amazon.nova-pro-v1:0 ,这两个 Amazon 自研的模型。
  •  Bedrock Knowledge Base :这是一个全托管的  RAG  服务,提供完整  RAG  数据流的各种功能:数据源连接和导入、数据切片、向量化转化、检索生成等,后面的章节中我们会详细介绍。
  •  AWS OpenSearch Serverless : OpenSearch  是  ElasticSearch  的开源版本,它支持向量搜索,是  Knowledge Base  的向量存储层。
  •  AWS IAM :各个服务之间,通过  IAM Role  和  IAM Policy  来管理身份和访问权限。
下面我们就来逐一拆解。

基于 IAM 的访问权限管理

在搭建具体的  RAG  系统之前,让我们先来谈谈身份和权限管理,因为它会应用到后续所创建的各个服务之间。这是在  AWS  上搭建各种解决方案都要依赖的基础能力,不限于  RAG  系统。
让我们先来回顾一下,Azure 是如何做的?如果你读过我之前关于 Azure 的文章,应该对 Azure 的 Role-Based Access Control(RBAC)权限管理机制比较熟悉,它包含三个关键元素:
  • Security Principal:表示 ID,包括用户、组、service principal、managed identity;
  • Role Definition:定义允许的操作列表,Azure 提供了大量的预定义 Role,以及每个 Role 对应的合法操作;
  • Scope:规定权限的作用范围,比如 management group、subscription、resource group 或者某个具体资源等。
 AWS  的身份和权限管理基于  IAM  服务,但是它采用了非常不同的策略,其中比较大的不同有:
  • AWS 没有预定义的  IAM Role ,对于你的应用或者 workload,你需要创建一个  IAM Role ;
  • AWS 提供了预定义的  IAM Policy ,这些 Policy 定义了允许的操作,作为开发者需要把对应的 Policy 绑定到自己创建的 Role 上,这样 Role 就拥有了权限;
  • AWS 创建一个 workload 的时候,比如我们这篇文章的  Bedrock Knowledge Base ,把这个添加了 Policy 的 Role 赋给这个 workload,表示这个 workload 将会担任(assume)这个 Role 来执行后续的操作。
所以整体的流程是:
创建 Role -> 绑定 Policy -> 担任 Role
另外,对于 Policy 还有一个说明,IAM 框架里常用的有两种 Policy:
  •  Permission Policy :指定对哪些资源可以做哪些操作,这是后续动态附加到 Role 之上的,也就是上面说的情况;
  •  Trust Policy :指定哪些服务主体可以担任这个 Role,这是在创建 Role 的时候就需要指定的信息。
理论上就是这样,可能比较抽象,不够具体。下面我们就来结合  Bedrock Knowledge Base  开发  RAG  系统这个实例来介绍,相信大家就比较好理解了!
基于上面架构设计部分的介绍,大家应该发现了,几个核心组件之间, Bedrock Knowledge Base  是承上启下、需要连接和访问其他组件的枢纽:
  • 它需要访问  S3  bucket,读取原始数据;
  • 它需要访问  Bedrock Model Catalog ,把原始数据进行  embedding  处理,转化为向量数据;
  • 它需要访问  OpenSearch Serverless  服务,读写向量数据。
所以在我们这个案例里,我们需要给  Knowledge Base  创建一个 Role,并附加三个  Permission Policy 。

创建 Role

创建 Role 需要使用  IAM  client,具体如下:
import json
import boto3

# 1. Create the IAM client
iam_client = boto3.client("iam")

# 2. Define the trust policy (who can assume this role)
trust_policy = {
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Service": "bedrock.amazonaws.com"
},
"Action": "sts:AssumeRole"
}
]
}

# 3. Create the role
response = iam_client.create_role(
RoleName="MyExampleRole",
AssumeRolePolicyDocument=json.dumps(trust_policy),
Description="Amazon Bedrock Knowledge Base Execution Role for accessing OSS and S3"
)

role_arn = response["Role"]["Arn"]
print("Role created:", role_arn)
我们来重点关注  Trust Policy  的定义:
{
"Effect": "Allow",
"Principal": {
"Service": "bedrock.amazonaws.com"
},
"Action": "sts:AssumeRole"
}
 Principal  字段定义了哪个主体可以担任这个角色,这里就是  Bedrock  服务; Action  字段定义了允许的操作列表,这里表示允许这个 Role 调用  STS (Security Token Service)服务的  AssumeRole  接口来担任这个角色。
就能得到下面这个 Role:

但是暂时它还没有任何访问其他服务的权限,下面我们就来创建并附加  Permission Policy 。

创建 Permission Policy

第一个 Permission Policy 定义了  S3  bucket 的读数据权限。
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"s3:GetObject",
"s3:ListBucket"
],
"Resource": [
"arn:aws:s3:::bedrock-kb-us-east-1-86629",
"arn:aws:s3:::bedrock-kb-us-east-1-86629/*"
],
"Condition": {
"StringEquals": {
"aws:ResourceAccount": "399863052849"
}
}
}
]
}
第二个 Permission Policy 定义了  Bedrock Model Catalog  的调用权限:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"bedrock:InvokeModel"
],
"Resource": [
"arn:aws:bedrock:us-east-1::foundation-model/amazon.titan-embed-text-v1",
"arn:aws:bedrock:us-east-1::foundation-model/amazon.titan-embed-text-v2:0"
]
}
]
}
第三个 Permission Policy 定义了  AOSS  的调用权限:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"aoss:APIAccessAll"
],
"Resource": [
"arn:aws:aoss:us-east-1:399863052849:collection/j37nmwjmxof8yjrvwu2h"
]
}
]
}
从上面三个例子中,可以看出  Permission Policy  的关键字段是: Action  字段指定允许的操作; Resource  字段指定操作的范围。
代码层面,可以通过  IAM  client 的  create_policy  方法轻松实现:
iam_client.create_policy(PolicyName, PolicyDocument, Description)

为 Role 附加权限

然后,通过  IAM  client 的  attach_role_policy  方法可以附加权限:
for policy_response in [s3_policy_response, fm_policy_response, oss_policy_response]:
iam_client.attach_role_policy(
RoleName=role_name,
PolicyArn=policy_response["Policy"]["Arn"],
)
这样我们就创建了一个可以访问  S3 、 Model Catalog  和  AOSS  服务的 Role。后续到了相应的地方,可以看看  Knowledge Base  是如何担任这个角色的。

大家可以发现, AWS IAM  的设计跟 Azure 还是有挺大不同的。之后的文章中,我会继续给大家分享更有意思、有实战价值的方案,希望大家关注我的频道!

创建基于 S3 的数据源

 Bedrock Knowledge Base  支持各种数据源,我们这里使用最为经典的  S3  对象存储服务。
首先,我们要利用  S3  的 client 来创建 Bucket:
import boto3
from botocore.exceptions import ClientError

boto_session = boto3.Session()
aws_region = boto_session.region_name
s3_client = boto3.client("s3")

# Check if bucket exists, and if not create S3 bucket for KB data source
try:
s3_client.head_bucket(Bucket=s3_bucket_name)
print(f"Bucket '{s3_bucket_name}' already exists..")
except ClientError:
print(f"Creating bucket: '{s3_bucket_name}'..")
if aws_region == "us-east-1":
s3_client.create_bucket(Bucket=s3_bucket_name)
else:
s3_client.create_bucket(
Bucket=s3_bucket_name,
CreateBucketConfiguration={"LocationConstraint": aws_region},
)

然后,上传文件:
import os
from urllib.request import urlretrieve

# URLs of shareholder letters to download
urls = [
"https://s2.q4cdn.com/299287126/files/doc_financials/2023/ar/2022-Shareholder-Letter.pdf",
"https://s2.q4cdn.com/299287126/files/doc_financials/2022/ar/2021-Shareholder-Letter.pdf",
"https://s2.q4cdn.com/299287126/files/doc_financials/2021/ar/Amazon-2020-Shareholder-Letter-and-1997-Shareholder-Letter.pdf",
"https://s2.q4cdn.com/299287126/files/doc_financials/2020/ar/2019-Shareholder-Letter.pdf",
]

# Corresponding local file names
filenames = [
"AMZN-2022-Shareholder-Letter.pdf",
"AMZN-2021-Shareholder-Letter.pdf",
"AMZN-2020-Shareholder-Letter.pdf",
"AMZN-2019-Shareholder-Letter.pdf",
]

# Create local staging directory if it doesn't exist
os.makedirs(local_data_dir, exist_ok=True)

# Download each file and print confirmation
for url, filename in zip(urls, filenames):
file_path = os.path.join(local_data_dir, filename)
urlretrieve(url, file_path)
print(f"Downloaded: '{filename}' to '{local_data_dir}'..")

for root, _, files in os.walk(local_data_dir):
for file in files:
full_path = os.path.join(root, file)
s3_client.upload_file(full_path, s3_bucket_name, file)
print(f"Uploaded: '{file}' to 's3://{s3_bucket_name}'..")

从功能上, AWS S3  服务跟  Azure Blob Storage  是一样的,都属于对象存储的范畴。后续我会给大家更多地拆解它们之间的相似和不同!
这个部分比较简单,下面我们进入向量存储的部分。

创建基于 AOSS 的向量索引

 Bedrock Knowledge Base  能够集成各种向量数据库,在本案例中,我们使用 AWS 自己的  OpenSearch Serverless  服务。

OpenSearch

 OpenSearch  项目源于  ElasticSearch  项目,但是因为开源许可证问题, OpenSearch  从原有项目基础上 fork 了一份,继续使用 Apache 2.0 许可证。
 OpenSearch  除了保留了之前的全文搜索功能,还添加了向量搜索的功能,让它成为  RAG  系统的好选择!
在  AWS  云平台上,有两种  OpenSearch  服务: Managed Cluster  和  Serverless ,本案例中我们使用简单快捷的  Serverless  服务。

OpenSearch Serverless 架构

 OpenSearch Serverless  定义了三层数据架构:
Collection (e.g. bedrock-kb-collection-123)
└── Index(es) (e.g. bedrock-kb-index)
└── Documents (vectors + metadata for each text chunk)
  •  collection  是核心的存储和计算单元,对应于传统的集群概念。
  •  index :是向量数据的索引。
  •  documents :在数据导入的过程中,每个 chunk 会对应于一个 document。

创建 Collection

创建  OpenSearch  的 collection 非常直接,关键要标明  VECTORSEARCH  的类型定义。
import boto3

boto_session = boto3.Session()
aoss_client = boto3.client("opensearchserverless")

aoss_collection = aoss_client.create_collection(
name=aoss_collection_name,
type="VECTORSEARCH",
)
如下所示:


创建 Collection 的安全规则

对于  OpenSearch  这样的数据服务,一般都会额外添加一些安全规则,这样能够更好地保证数据的安全。比如我们这个案例里,需要添加三个安全规则:
  •  加密 :决定数据在存储状态的加密方法,简单起见,这里我使用 AWS 的 key。

  •  网络 :决定这个 collection 的网络访问限制。这里也是方便起见,我们允许公网访问,但是更加安全的方案是使用 AWS 的虚拟私有网络服务 VPC,今后我会给大家介绍!

  •  访问权限 :决定了谁或者哪些服务可以访问这个 collection,以及具体的访问和操作范围。
比如在我这个案例里,我自己作为 Root User 和刚刚给  Bedrock  创建的 Role 可以访问。我需要这个权限,是因为下一步我就要手动创建 Vector Index,而  Bedrock  需要读写向量数据!

上面这三个安全规则施加在  OpenSearch  服务这一层,所以创建依赖于  OpenSearch  的 Client:
import boto3

boto_session = boto3.Session()
aoss_client = boto3.client("opensearchserverless")
aoss_client.create_security_policy(PolicyName, PolicyConfiguration, PolicyType)
注意这跟  IAM  的  Permission Policy  并不冲突。从具体的规则内容来看, AOSS  自己的安全规则要更加具体和细节。如上所说,除了  AOSS  之外,AWS 上的很多数据服务,比如  S3 、database 等,都有施加在自己服务层面的安全规则!

创建向量 Index

collection 已经搭好,下一步我们来创建具体的 Vector Index。这里我们要使用  OpenSearch  自己的 SDK  opensearchpy ,基于 collection 的公网 endpoint 来建立连接:
from opensearchpy import OpenSearch, RequestsHttpConnection
from requests_aws4auth import AWS4Auth

# Use default credential configuration for authentication
credentials = boto_session.get_credentials()
awsauth = AWS4Auth(
credentials.access_key,
credentials.secret_key,
aws_region,
"aoss",
session_token=credentials.token,
)

# Construct AOSS endpoint host
host = (
f"{aoss_collection['createCollectionDetail']['id']}.{aws_region}.aoss.amazonaws.com"
)

# Build the OpenSearch client
os_client = OpenSearch(
hosts=[{"host": host, "port": 443}],
http_auth=awsauth,
use_ssl=True,
verify_certs=True,
connection_class=RequestsHttpConnection,
timeout=300,
)
然后配置 Vector Index 的具体行为:
# Define the configuration for the AOSS vector index
index_definition = {
"settings": {
"index.knn": "true",
"number_of_shards": 1,
"knn.algo_param.ef_search": 512,
"number_of_replicas": 0,
},
"mappings": {
"properties": {
"vector": {
"type": "knn_vector",
"dimension": embedding_model_dim,
"method": {"name": "hnsw", "engine": "faiss", "space_type": "l2"},
},
"text": {"type": "text"},
"text-metadata": {"type": "text"},
}
},
}

# Create an OpenSearch index
response = os_client.indices.create(index=aoss_index_name, body=index_definition)
这里面的关键点就是向量搜索的具体算法和引擎。算法上,我使用 Hierarchical Navigable Small World(HNSW),关于这个算法,我之前的文章曾经非常深入地剖析过,这里就不再赘述了,非常有意思的算法,具体信息大家参考那篇文章。而具体实现上,我们选择 FAISS(Facebook AI Similarity Search)引擎。
可以看到,因为还没有导入数据,所以这个 Vector Index 暂时还是空的。

上下游依赖都已经创建好了,下面就来创建  Knowledge Base  服务。

创建 Bedrock Knowledge Base

首先我们需要配置存储层信息,可以看到,我们选择刚刚创建的  AOSS  collection。
storage_config = {
"type": "OPENSEARCH_SERVERLESS",
"opensearchServerlessConfiguration": {
"collectionArn": aoss_collection["createCollectionDetail"]["arn"],
"vectorIndexName": aoss_index_name,
"fieldMapping": {
"vectorField": "vector",
"textField": "text",
"metadataField": "text-metadata",
},
},
}
然后是  Knowledge Base  的配置信息,指定所需的  embedding  模型:
embedding_model_id = "amazon.titan-embed-text-v2:0"
embedding_model_arn = (
f"arn:aws:bedrock:{aws_region}::foundation-model/{embedding_model_id}"
)

knowledge_base_config = {
"type": "VECTOR",
"vectorKnowledgeBaseConfiguration": {"embeddingModelArn": embedding_model_arn},
}
下面,我们就可以创建  Knowledge Base :
import boto3

boto_session = boto3.Session()
bedrock_agent_client = boto3.client("bedrock-agent")

bedrock_agent_client.create_knowledge_base(
name=bedrock_kb_name,
description="Amazon shareholder letter knowledge base.",
roleArn=bedrock_kb_execution_role_arn,
knowledgeBaseConfiguration=knowledge_base_config,
storageConfiguration=storage_config,
)
这里可以呼应一下上面的问题, Knowledge Base  是如何担任新创的那个 Role 的呢?从上面的代码很明显可以看到, create_knowledge_base  方法要求传入  roleArn  这个参数,指定需要的 Role!


连接数据源

下一步,就可以指定  S3  bucket 作为  Knowledge Base  的数据源,同时配置原始数据的分片策略:
# Data Source Configuration
data_source_config = {
"type": "S3",
"s3Configuration": {
"bucketArn": f"arn:aws:s3:::{s3_bucket_name}"
},
}

# Vector Ingestion Configuration
vector_ingestion_config = {
"chunkingConfiguration": {
"chunkingStrategy": "FIXED_SIZE",
"fixedSizeChunkingConfiguration": {"maxTokens": 512, "overlapPercentage": 20},
}
}

bedrock_agent_client.create_data_source(
name=bedrock_kb_name,
description="Amazon shareholder letter knowledge base.",
knowledgeBaseId=bedrock_kb_id,
dataSourceConfiguration=data_source_config,
vectorIngestionConfiguration=vector_ingestion_config,
)
下面就能看到这个数据源非常明确地连接到 S3 bucket 上。


数据摄取

 Bedrock Knowledge Base  支持全托管的数据导入流程:

可以通过下面的代码,启动一个数据摄取 job:
bedrock_agent_client.start_ingestion_job(KnowledgeBaseId, DataSourceId)
job 完成之后,就可以看到上游的数据被成功添加到 Vector Index 里!

这样,我们的  RAG  系统就搭建完成了,赶紧来试试!

Demo

从下面的测试可以看出,它不但返回了检索生成的结果,还提供了参考的 chunk 信息,这对于评估 RAG 系统非常重要!

Any opinions in this article are those of the individual author and may not reflect the opinions of AWS.
Enjoyed reading this content? Let the author know!

Your likes, comments, shares, and saves help creators reach more builders.

Loading recommendations

Loading article