使用 AnalyticDB 作为 OpenAI 嵌入的向量数据库

2023年4月6日
在 Github 中打开

本 notebook 将逐步指导您如何使用 AnalyticDB 作为 OpenAI 嵌入的向量数据库。

本 notebook 演示了端到端的过程,包括:

  1. 使用 OpenAI API 创建的预计算嵌入。
  2. 将嵌入存储在 AnalyticDB 的云实例中。
  3. 使用 OpenAI API 将原始文本查询转换为嵌入。
  4. 使用 AnalyticDB 在创建的集合中执行最近邻搜索。

什么是 AnalyticDB

AnalyticDB 是一个高性能分布式向量数据库。它完全兼容 PostgreSQL 语法,您可以轻松地使用它。AnalyticDB 是阿里云托管的云原生数据库,具有强大的向量计算引擎。开箱即用的体验允许扩展到数十亿的数据向量处理,并具有丰富的功能,包括索引算法、结构化和非结构化数据特征、实时更新、距离度量、标量过滤、时间旅行搜索等。还配备了完整的 OLAP 数据库功能和 SLA 承诺,保证生产环境使用;

部署选项

前提条件

为了进行本练习,我们需要准备以下几项:

  1. AnalyticDB 云服务器实例。
  2. 用于与向量数据库交互的 'psycopg2' 库。任何其他 postgresql 客户端库都可以。
  3. 一个 OpenAI API 密钥

我们可以通过运行一个简单的 curl 命令来验证服务器是否成功启动

安装 requirements

本 notebook 显然需要 openaipsycopg2 包,但我们还将使用其他一些额外的库。以下命令将安装所有这些库

! pip install openai psycopg2 pandas wget
# Test that your OpenAI API key is correctly set as an environment variable
# Note. if you run this notebook locally, you will need to reload your terminal and the notebook for the env variables to be live.
import os

# Note. alternatively you can set a temporary env variable like this:
# os.environ["OPENAI_API_KEY"] = "sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"

if os.getenv("OPENAI_API_KEY") is not None:
    print("OPENAI_API_KEY is ready")
else:
    print("OPENAI_API_KEY environment variable not found")
OPENAI_API_KEY is ready

连接到 AnalyticDB

首先将其添加到您的环境变量。或者您可以直接更改下面的 "psycopg2.connect" 参数

使用官方 Python 库可以轻松连接到正在运行的 AnalyticDB 服务器实例

import os
import psycopg2

# Note. alternatively you can set a temporary env variable like this:
# os.environ["PGHOST"] = "your_host"
# os.environ["PGPORT"] "5432"),
# os.environ["PGDATABASE"] "postgres"),
# os.environ["PGUSER"] "user"),
# os.environ["PGPASSWORD"] "password"),

connection = psycopg2.connect(
    host=os.environ.get("PGHOST", "localhost"),
    port=os.environ.get("PGPORT", "5432"),
    database=os.environ.get("PGDATABASE", "postgres"),
    user=os.environ.get("PGUSER", "user"),
    password=os.environ.get("PGPASSWORD", "password")
)

# Create a new cursor object
cursor = connection.cursor()

我们可以通过运行任何可用的方法来测试连接


# Execute a simple query to test the connection
cursor.execute("SELECT 1;")
result = cursor.fetchone()

# Check the query result
if result == (1,):
    print("Connection successful!")
else:
    print("Connection failed.")
Connection successful!
import wget

embeddings_url = "https://cdn.openai.com/API/examples/data/vector_database_wikipedia_articles_embedded.zip"

# The file is ~700 MB so this will take some time
wget.download(embeddings_url)
100% [......................................................................] 698933052 / 698933052
'vector_database_wikipedia_articles_embedded.zip'

下载的文件必须解压

import zipfile
import os
import re
import tempfile

current_directory = os.getcwd()
zip_file_path = os.path.join(current_directory, "vector_database_wikipedia_articles_embedded.zip")
output_directory = os.path.join(current_directory, "../../data")

with zipfile.ZipFile(zip_file_path, "r") as zip_ref:
    zip_ref.extractall(output_directory)


# check the csv file exist
file_name = "vector_database_wikipedia_articles_embedded.csv"
data_directory = os.path.join(current_directory, "../../data")
file_path = os.path.join(data_directory, file_name)


if os.path.exists(file_path):
    print(f"The file {file_name} exists in the data directory.")
else:
    print(f"The file {file_name} does not exist in the data directory.")
The file vector_database_wikipedia_articles_embedded.csv exists in the data directory.

索引数据

AnalyticDB 将数据存储在关系中,其中每个对象都由至少一个向量描述。我们的关系将被称为 articles,每个对象将由 titlecontent 向量描述。

我们将从创建一个关系开始,并在 titlecontent 上创建向量索引,然后我们将用我们预计算的嵌入填充它。

create_table_sql = '''
CREATE TABLE IF NOT EXISTS public.articles (
    id INTEGER NOT NULL,
    url TEXT,
    title TEXT,
    content TEXT,
    title_vector REAL[],
    content_vector REAL[],
    vector_id INTEGER
);

ALTER TABLE public.articles ADD PRIMARY KEY (id);
'''

# SQL statement for creating indexes
create_indexes_sql = '''
CREATE INDEX ON public.articles USING ann (content_vector) WITH (distancemeasure = l2, dim = '1536', pq_segments = '64', hnsw_m = '100', pq_centers = '2048');

CREATE INDEX ON public.articles USING ann (title_vector) WITH (distancemeasure = l2, dim = '1536', pq_segments = '64', hnsw_m = '100', pq_centers = '2048');
'''

# Execute the SQL statements
cursor.execute(create_table_sql)
cursor.execute(create_indexes_sql)

# Commit the changes
connection.commit()

加载数据

在本节中,我们将加载会话之前准备好的数据,因此您不必使用自己的额度重新计算维基百科文章的嵌入。

import io

# Path to your local CSV file
csv_file_path = '../../data/vector_database_wikipedia_articles_embedded.csv'

# Define a generator function to process the file line by line
def process_file(file_path):
    with open(file_path, 'r') as file:
        for line in file:
            # Replace '[' with '{' and ']' with '}'
            modified_line = line.replace('[', '{').replace(']', '}')
            yield modified_line

# Create a StringIO object to store the modified lines
modified_lines = io.StringIO(''.join(list(process_file(csv_file_path))))

# Create the COPY command for the copy_expert method
copy_command = '''
COPY public.articles (id, url, title, content, title_vector, content_vector, vector_id)
FROM STDIN WITH (FORMAT CSV, HEADER true, DELIMITER ',');
'''

# Execute the COPY command using the copy_expert method
cursor.copy_expert(copy_command, modified_lines)

# Commit the changes
connection.commit()
# Check the collection size to make sure all the points have been stored
count_sql = """select count(*) from public.articles;"""
cursor.execute(count_sql)
result = cursor.fetchone()
print(f"Count:{result[0]}")
Count:25000

搜索数据

一旦数据被放入 Qdrant,我们将开始查询集合以查找最近的向量。我们可以提供一个额外的参数 vector_name 来切换从标题到内容的搜索。由于预计算的嵌入是使用 text-embedding-3-small OpenAI 模型创建的,因此我们在搜索期间也必须使用它。

def query_analyticdb(query, collection_name, vector_name="title_vector", top_k=20):

    # Creates embedding vector from user query
    embedded_query = openai.Embedding.create(
        input=query,
        model="text-embedding-3-small",
    )["data"][0]["embedding"]

    # Convert the embedded_query to PostgreSQL compatible format
    embedded_query_pg = "{" + ",".join(map(str, embedded_query)) + "}"

    # Create SQL query
    query_sql = f"""
    SELECT id, url, title, l2_distance({vector_name},'{embedded_query_pg}'::real[]) AS similarity
    FROM {collection_name}
    ORDER BY {vector_name} <-> '{embedded_query_pg}'::real[]
    LIMIT {top_k};
    """
    # Execute the query
    cursor.execute(query_sql)
    results = cursor.fetchall()

    return results
import openai

query_results = query_analyticdb("modern art in Europe", "Articles")
for i, result in enumerate(query_results):
    print(f"{i + 1}. {result[2]} (Score: {round(1 - result[3], 3)})")
1. Museum of Modern Art (Score: 0.75)
2. Western Europe (Score: 0.735)
3. Renaissance art (Score: 0.728)
4. Pop art (Score: 0.721)
5. Northern Europe (Score: 0.71)
6. Hellenistic art (Score: 0.706)
7. Modernist literature (Score: 0.694)
8. Art film (Score: 0.687)
9. Central Europe (Score: 0.685)
10. European (Score: 0.683)
11. Art (Score: 0.683)
12. Byzantine art (Score: 0.682)
13. Postmodernism (Score: 0.68)
14. Eastern Europe (Score: 0.679)
15. Europe (Score: 0.678)
16. Cubism (Score: 0.678)
17. Impressionism (Score: 0.677)
18. Bauhaus (Score: 0.676)
19. Surrealism (Score: 0.674)
20. Expressionism (Score: 0.674)
# This time we'll query using content vector
query_results = query_analyticdb("Famous battles in Scottish history", "Articles", "content_vector")
for i, result in enumerate(query_results):
    print(f"{i + 1}. {result[2]} (Score: {round(1 - result[3], 3)})")
1. Battle of Bannockburn (Score: 0.739)
2. Wars of Scottish Independence (Score: 0.723)
3. 1651 (Score: 0.705)
4. First War of Scottish Independence (Score: 0.699)
5. Robert I of Scotland (Score: 0.692)
6. 841 (Score: 0.688)
7. 1716 (Score: 0.688)
8. 1314 (Score: 0.674)
9. 1263 (Score: 0.673)
10. William Wallace (Score: 0.671)
11. Stirling (Score: 0.663)
12. 1306 (Score: 0.662)
13. 1746 (Score: 0.661)
14. 1040s (Score: 0.656)
15. 1106 (Score: 0.654)
16. 1304 (Score: 0.653)
17. David II of Scotland (Score: 0.65)
18. Braveheart (Score: 0.649)
19. 1124 (Score: 0.648)
20. July 27 (Score: 0.646)