Spaces:
Runtime error
Runtime error
File size: 15,451 Bytes
105b369 |
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 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 |
from typing import Optional, List, Union, Dict, Any
from hashlib import md5
try:
from sqlalchemy.dialects import postgresql
from sqlalchemy.engine import create_engine, Engine
from sqlalchemy.inspection import inspect
from sqlalchemy.orm import Session, sessionmaker
from sqlalchemy.schema import MetaData, Table, Column
from sqlalchemy.sql.expression import text, func, select
from sqlalchemy.types import DateTime, String
except ImportError:
raise ImportError("`sqlalchemy` not installed")
try:
from pgvector.sqlalchemy import Vector
except ImportError:
raise ImportError("`pgvector` not installed")
from phi.document import Document
from phi.embedder import Embedder
from phi.vectordb.base import VectorDb
from phi.vectordb.distance import Distance
from phi.vectordb.pgvector.index import Ivfflat, HNSW
from phi.utils.log import logger
class PgVector2(VectorDb):
def __init__(
self,
collection: str,
schema: Optional[str] = "ai",
db_url: Optional[str] = None,
db_engine: Optional[Engine] = None,
embedder: Optional[Embedder] = None,
distance: Distance = Distance.cosine,
index: Optional[Union[Ivfflat, HNSW]] = HNSW(),
):
_engine: Optional[Engine] = db_engine
if _engine is None and db_url is not None:
_engine = create_engine(db_url)
if _engine is None:
raise ValueError("Must provide either db_url or db_engine")
# Collection attributes
self.collection: str = collection
self.schema: Optional[str] = schema
# Database attributes
self.db_url: Optional[str] = db_url
self.db_engine: Engine = _engine
self.metadata: MetaData = MetaData(schema=self.schema)
# Embedder for embedding the document contents
_embedder = embedder
if _embedder is None:
from phi.embedder.openai import OpenAIEmbedder
_embedder = OpenAIEmbedder()
self.embedder: Embedder = _embedder
self.dimensions: int = self.embedder.dimensions
# Distance metric
self.distance: Distance = distance
# Index for the collection
self.index: Optional[Union[Ivfflat, HNSW]] = index
# Database session
self.Session: sessionmaker[Session] = sessionmaker(bind=self.db_engine)
# Database table for the collection
self.table: Table = self.get_table()
def get_table(self) -> Table:
return Table(
self.collection,
self.metadata,
Column("id", String, primary_key=True),
Column("name", String),
Column("meta_data", postgresql.JSONB, server_default=text("'{}'::jsonb")),
Column("content", postgresql.TEXT),
Column("embedding", Vector(self.dimensions)),
Column("usage", postgresql.JSONB),
Column("created_at", DateTime(timezone=True), server_default=text("now()")),
Column("updated_at", DateTime(timezone=True), onupdate=text("now()")),
Column("content_hash", String),
extend_existing=True,
)
def table_exists(self) -> bool:
logger.debug(f"Checking if table exists: {self.table.name}")
try:
return inspect(self.db_engine).has_table(self.table.name, schema=self.schema)
except Exception as e:
logger.error(e)
return False
def create(self) -> None:
if not self.table_exists():
with self.Session() as sess:
with sess.begin():
logger.debug("Creating extension: vector")
sess.execute(text("create extension if not exists vector;"))
if self.schema is not None:
logger.debug(f"Creating schema: {self.schema}")
sess.execute(text(f"create schema if not exists {self.schema};"))
logger.debug(f"Creating table: {self.collection}")
self.table.create(self.db_engine)
def doc_exists(self, document: Document) -> bool:
"""
Validating if the document exists or not
Args:
document (Document): Document to validate
"""
columns = [self.table.c.name, self.table.c.content_hash]
with self.Session() as sess:
with sess.begin():
cleaned_content = document.content.replace("\x00", "\ufffd")
stmt = select(*columns).where(self.table.c.content_hash == md5(cleaned_content.encode()).hexdigest())
result = sess.execute(stmt).first()
return result is not None
def name_exists(self, name: str) -> bool:
"""
Validate if a row with this name exists or not
Args:
name (str): Name to check
"""
with self.Session() as sess:
with sess.begin():
stmt = select(self.table.c.name).where(self.table.c.name == name)
result = sess.execute(stmt).first()
return result is not None
def id_exists(self, id: str) -> bool:
"""
Validate if a row with this id exists or not
Args:
id (str): Id to check
"""
with self.Session() as sess:
with sess.begin():
stmt = select(self.table.c.id).where(self.table.c.id == id)
result = sess.execute(stmt).first()
return result is not None
def insert(self, documents: List[Document], batch_size: int = 10) -> None:
with self.Session() as sess:
counter = 0
for document in documents:
document.embed(embedder=self.embedder)
cleaned_content = document.content.replace("\x00", "\ufffd")
content_hash = md5(cleaned_content.encode()).hexdigest()
_id = document.id or content_hash
stmt = postgresql.insert(self.table).values(
id=_id,
name=document.name,
meta_data=document.meta_data,
content=cleaned_content,
embedding=document.embedding,
usage=document.usage,
content_hash=content_hash,
)
sess.execute(stmt)
counter += 1
logger.debug(f"Inserted document: {document.name} ({document.meta_data})")
# Commit every `batch_size` documents
if counter >= batch_size:
sess.commit()
logger.info(f"Committed {counter} documents")
counter = 0
# Commit any remaining documents
if counter > 0:
sess.commit()
logger.info(f"Committed {counter} documents")
def upsert_available(self) -> bool:
return True
def upsert(self, documents: List[Document], batch_size: int = 20) -> None:
"""
Upsert documents into the database.
Args:
documents (List[Document]): List of documents to upsert
batch_size (int): Batch size for upserting documents
"""
with self.Session() as sess:
counter = 0
for document in documents:
document.embed(embedder=self.embedder)
cleaned_content = document.content.replace("\x00", "\ufffd")
content_hash = md5(cleaned_content.encode()).hexdigest()
_id = document.id or content_hash
stmt = postgresql.insert(self.table).values(
id=_id,
name=document.name,
meta_data=document.meta_data,
content=cleaned_content,
embedding=document.embedding,
usage=document.usage,
content_hash=content_hash,
)
# Update row when id matches but 'content_hash' is different
stmt = stmt.on_conflict_do_update(
index_elements=["id"],
set_=dict(
name=stmt.excluded.name,
meta_data=stmt.excluded.meta_data,
content=stmt.excluded.content,
embedding=stmt.excluded.embedding,
usage=stmt.excluded.usage,
content_hash=stmt.excluded.content_hash,
),
)
sess.execute(stmt)
counter += 1
logger.debug(f"Upserted document: {document.id} | {document.name} | {document.meta_data}")
# Commit every `batch_size` documents
if counter >= batch_size:
sess.commit()
logger.info(f"Committed {counter} documents")
counter = 0
# Commit any remaining documents
if counter > 0:
sess.commit()
logger.info(f"Committed {counter} documents")
def search(self, query: str, limit: int = 5, filters: Optional[Dict[str, Any]] = None) -> List[Document]:
query_embedding = self.embedder.get_embedding(query)
if query_embedding is None:
logger.error(f"Error getting embedding for Query: {query}")
return []
columns = [
self.table.c.name,
self.table.c.meta_data,
self.table.c.content,
self.table.c.embedding,
self.table.c.usage,
]
stmt = select(*columns)
if filters is not None:
for key, value in filters.items():
if hasattr(self.table.c, key):
stmt = stmt.where(getattr(self.table.c, key) == value)
if self.distance == Distance.l2:
stmt = stmt.order_by(self.table.c.embedding.max_inner_product(query_embedding))
if self.distance == Distance.cosine:
stmt = stmt.order_by(self.table.c.embedding.cosine_distance(query_embedding))
if self.distance == Distance.max_inner_product:
stmt = stmt.order_by(self.table.c.embedding.max_inner_product(query_embedding))
stmt = stmt.limit(limit=limit)
logger.debug(f"Query: {stmt}")
# Get neighbors
try:
with self.Session() as sess:
with sess.begin():
if self.index is not None:
if isinstance(self.index, Ivfflat):
sess.execute(text(f"SET LOCAL ivfflat.probes = {self.index.probes}"))
elif isinstance(self.index, HNSW):
sess.execute(text(f"SET LOCAL hnsw.ef_search = {self.index.ef_search}"))
neighbors = sess.execute(stmt).fetchall() or []
except Exception as e:
logger.error(f"Error searching for documents: {e}")
logger.error("Table might not exist, creating for future use")
self.create()
return []
# Build search results
search_results: List[Document] = []
for neighbor in neighbors:
search_results.append(
Document(
name=neighbor.name,
meta_data=neighbor.meta_data,
content=neighbor.content,
embedder=self.embedder,
embedding=neighbor.embedding,
usage=neighbor.usage,
)
)
return search_results
def delete(self) -> None:
if self.table_exists():
logger.debug(f"Deleting table: {self.collection}")
self.table.drop(self.db_engine)
def exists(self) -> bool:
return self.table_exists()
def get_count(self) -> int:
with self.Session() as sess:
with sess.begin():
stmt = select(func.count(self.table.c.name)).select_from(self.table)
result = sess.execute(stmt).scalar()
if result is not None:
return int(result)
return 0
def optimize(self) -> None:
from math import sqrt
logger.debug("==== Optimizing Vector DB ====")
if self.index is None:
return
if self.index.name is None:
_type = "ivfflat" if isinstance(self.index, Ivfflat) else "hnsw"
self.index.name = f"{self.collection}_{_type}_index"
index_distance = "vector_cosine_ops"
if self.distance == Distance.l2:
index_distance = "vector_l2_ops"
if self.distance == Distance.max_inner_product:
index_distance = "vector_ip_ops"
if isinstance(self.index, Ivfflat):
num_lists = self.index.lists
if self.index.dynamic_lists:
total_records = self.get_count()
logger.debug(f"Number of records: {total_records}")
if total_records < 1000000:
num_lists = int(total_records / 1000)
elif total_records > 1000000:
num_lists = int(sqrt(total_records))
with self.Session() as sess:
with sess.begin():
logger.debug(f"Setting configuration: {self.index.configuration}")
for key, value in self.index.configuration.items():
sess.execute(text(f"SET {key} = '{value}';"))
logger.debug(
f"Creating Ivfflat index with lists: {num_lists}, probes: {self.index.probes} "
f"and distance metric: {index_distance}"
)
sess.execute(text(f"SET ivfflat.probes = {self.index.probes};"))
sess.execute(
text(
f"CREATE INDEX IF NOT EXISTS {self.index.name} ON {self.table} "
f"USING ivfflat (embedding {index_distance}) "
f"WITH (lists = {num_lists});"
)
)
elif isinstance(self.index, HNSW):
with self.Session() as sess:
with sess.begin():
logger.debug(f"Setting configuration: {self.index.configuration}")
for key, value in self.index.configuration.items():
sess.execute(text(f"SET {key} = '{value}';"))
logger.debug(
f"Creating HNSW index with m: {self.index.m}, ef_construction: {self.index.ef_construction} "
f"and distance metric: {index_distance}"
)
sess.execute(
text(
f"CREATE INDEX IF NOT EXISTS {self.index.name} ON {self.table} "
f"USING hnsw (embedding {index_distance}) "
f"WITH (m = {self.index.m}, ef_construction = {self.index.ef_construction});"
)
)
logger.debug("==== Optimized Vector DB ====")
def clear(self) -> bool:
from sqlalchemy import delete
with self.Session() as sess:
with sess.begin():
stmt = delete(self.table)
sess.execute(stmt)
return True
|