-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcreate_vector_embeddings.py
More file actions
136 lines (113 loc) · 4.05 KB
/
Copy pathcreate_vector_embeddings.py
File metadata and controls
136 lines (113 loc) · 4.05 KB
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
import asyncio
import uuid
from google.cloud.alloydb.connector import AsyncConnector, IPTypes
from langchain.docstore.document import Document
from langchain_community.document_loaders import CSVLoader
from langchain_google_alloydb_pg import AlloyDBEngine, AlloyDBVectorStore, Column
from langchain_google_vertexai import VertexAIEmbeddings
from sqlalchemy.ext.asyncio import create_async_engine
EMBEDDING_COUNT = 100
# AlloyDB info
PROJECT_ID = "duwenxin-space"
REGION = "us-central1" # @param {type:"string"}
CLUSTER_NAME = "my-alloydb-cluster" # @param {type:"string"}
INSTANCE_NAME = "my-alloydb-instance" # @param {type:"string"}
DATABASE_NAME = "netflix" # @param {type:"string"}
USER = "postgres" # @param {type:"string"}
PASSWORD = "postgres" # @param {type:"string"}
vector_table_name = "wine_reviews_vector"
# Dataset
DATASET_PATH = "wine_reviews_dataset.csv"
dataset_columns = [
"country",
"description",
"designation",
"points",
"price",
"province",
"region_1",
"region_2",
"taster_name",
"taster_twitter_handle",
"title",
"variety",
"winery",
]
connection_string = f"projects/{PROJECT_ID}/locations/{REGION}/clusters/{CLUSTER_NAME}/instances/{INSTANCE_NAME}"
# initialize Connector object
connector = AsyncConnector()
async def getconn():
conn = await connector.connect(
connection_string,
"asyncpg",
user=USER,
password=PASSWORD,
db=DATABASE_NAME,
enable_iam_auth=False,
ip_type=IPTypes.PUBLIC,
)
return conn
# create connection pool
pool = create_async_engine(
"postgresql+asyncpg://", async_creator=getconn, isolation_level="AUTOCOMMIT"
)
async def load_csv_documents(dataset_path=DATASET_PATH):
"""Loads documents directly from a CSV file using LangChain."""
loader = CSVLoader(file_path=dataset_path)
documents = loader.load()
documents = [
Document(page_content=str(doc.dict()), metadata=doc.metadata)
for doc in documents
]
return documents
async def create_vector_store_table(documents):
engine = await AlloyDBEngine.afrom_instance(
project_id=PROJECT_ID,
region=REGION,
cluster=CLUSTER_NAME,
instance=INSTANCE_NAME,
database=DATABASE_NAME,
user=USER,
password=PASSWORD,
)
print("Successfully connected to AlloyDB database.")
print("Initializaing Vectorstore tables...")
await engine.ainit_vectorstore_table(
table_name=vector_table_name,
vector_size=768,
metadata_columns=[
Column("country", "VARCHAR", nullable=True),
Column("description", "VARCHAR", nullable=True),
Column("designation", "VARCHAR", nullable=True),
Column("points", "VARCHAR", nullable=True),
Column("price", "INTEGER", nullable=True),
Column("province", "VARCHAR", nullable=True),
Column("region_1", "VARCHAR", nullable=True),
Column("region_2", "VARCHAR", nullable=True),
Column("taster_name", "VARCHAR", nullable=True),
Column("taster_twitter_handle", "VARCHAR", nullable=True),
Column("title", "VARCHAR", nullable=True),
Column("variety", "VARCHAR", nullable=True),
Column("winery", "VARCHAR", nullable=True),
],
overwrite_existing=True, # Enabling this will recreate the table if exists.
)
embedding = VertexAIEmbeddings(
model_name="textembedding-gecko@latest", project=PROJECT_ID
)
# Initialize AlloyDBVectorStore
print("Initializing VectorStore...")
vector_store = await AlloyDBVectorStore.create(
engine=engine,
table_name=vector_table_name,
embedding_service=embedding,
metadata_columns=dataset_columns,
)
ids = [str(uuid.uuid4()) for i in range(EMBEDDING_COUNT)]
await vector_store.aadd_documents(documents, ids)
print("Vector table created.")
async def main():
documents = await load_csv_documents()
await create_vector_store_table(documents)
if __name__ == "__main__":
asyncio.run(main())