AI 与向量

Amazon Bedrock


Amazon Bedrock 是一项全托管服务,提供来自领先AI公司(如AI21 Labs、Anthropic、Cohere、Meta、Mistral AI、Stability AI和Amazon)的高性能基础模型(FMs)选择。每个模型都通过统一的API访问,该API实现了广泛的功能集,旨在帮助构建考虑安全性、隐私性和负责任AI的生成式AI应用。

本指南将带您通过一个使用Amazon Bedrock SDK与vecs的示例。我们将使用Amazon Titan Embeddings G1 – Text v1.2 (amazon.titan-embed-text-v1)模型创建嵌入向量,然后使用vecs将这些嵌入向量插入Postgres数据库,最后查询集合以找到与给定查询语句最相似的句子。

创建环境

首先,您需要设置环境。您需要Python 3.7+并安装vecsboto3库。

可以使用pip安装必要的Python库:

1
pip install vecs boto3

您还需要:

创建嵌入向量

接下来,我们将使用亚马逊的 Titan Embedding G1 - Text v1.2 模型为一组句子创建嵌入向量。

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
import boto3import vecsimport jsonclient = boto3.client( 'bedrock-runtime', region_name='us-east-1', # 使用您的AWS账户凭证 aws_access_key_id='<replace_your_own_credentials>', aws_secret_access_key='<replace_your_own_credentials>', aws_session_token='<replace_your_own_credentials>',)dataset = [ "The cat sat on the mat.", "The quick brown fox jumps over the lazy dog.", "Friends, Romans, countrymen, lend me your ears", "To be or not to be, that is the question.",]embeddings = []for sentence in dataset: # 为每个句子调用嵌入模型 response = client.invoke_model( body= json.dumps({"inputText": sentence}), modelId= "amazon.titan-embed-text-v1", accept = "application/json", contentType = "application/json" ) # 从响应中提取嵌入向量 response_body = json.loads(response["body"].read()) # 将嵌入向量添加到列表中 embeddings.append((sentence, response_body.get("embedding"), {}))

使用vecs存储嵌入向量

现在我们有了嵌入向量,可以使用vecs将它们插入Postgres数据库。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import vecsDB_CONNECTION = "postgresql://<user>:<password>@<host>:<port>/<db_name>"# 创建向量存储客户端vx = vecs.Client(DB_CONNECTION)# 创建一个名为'sentences'的集合,设置1536维向量# 以匹配Titan Embeddings G1 - Text模型的默认维度sentences = vx.get_or_create_collection(name="sentences", dimension=1536)# 将嵌入向量更新或插入到'sentences'集合中sentences.upsert(records=embeddings)# 为'sentences'集合创建索引sentences.create_index()

查询最相似的句子

现在,我们查询 sentences 集合以找到与示例查询句子最相似的句子。首先需要为查询句子创建一个嵌入向量。接着,我们查询之前创建的集合来查找最相似的句子。

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
query_sentence = "A quick animal jumps over a lazy one."# 创建向量存储客户端vx = vecs.Client(DB_CONNECTION)# 为查询句子创建嵌入向量response = client.invoke_model( body= json.dumps({"inputText": query_sentence}), modelId= "amazon.titan-embed-text-v1", accept = "application/json", contentType = "application/json" )response_body = json.loads(response["body"].read())query_embedding = response_body.get("embedding")# 查询 'sentences' 集合获取最相似的句子results = sentences.query( data=query_embedding, limit=3, include_value = True)# 打印结果for result in results: print(result)

这将返回最相似的3条记录及其与查询向量的距离。

1
2
3
('The quick brown fox jumps over the lazy dog.', 0.27600620558852)('The cat sat on the mat.', 0.609986272479202)('To be or not to be, that is the question.', 0.744849503688346)

相关资源