pgvector-template 0.2.0__tar.gz → 0.2.2__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (23) hide show
  1. {pgvector_template-0.2.0 → pgvector_template-0.2.2}/PKG-INFO +1 -1
  2. {pgvector_template-0.2.0 → pgvector_template-0.2.2}/pgvector_template/core/document.py +45 -5
  3. {pgvector_template-0.2.0 → pgvector_template-0.2.2}/pgvector_template/core/search.py +8 -10
  4. {pgvector_template-0.2.0 → pgvector_template-0.2.2}/pgvector_template/service/document_service.py +6 -0
  5. {pgvector_template-0.2.0 → pgvector_template-0.2.2}/pgvector_template.egg-info/PKG-INFO +1 -1
  6. {pgvector_template-0.2.0 → pgvector_template-0.2.2}/pyproject.toml +1 -1
  7. {pgvector_template-0.2.0 → pgvector_template-0.2.2}/LICENSE +0 -0
  8. {pgvector_template-0.2.0 → pgvector_template-0.2.2}/README.md +0 -0
  9. {pgvector_template-0.2.0 → pgvector_template-0.2.2}/pgvector_template/__init__.py +0 -0
  10. {pgvector_template-0.2.0 → pgvector_template-0.2.2}/pgvector_template/core/__init__.py +0 -0
  11. {pgvector_template-0.2.0 → pgvector_template-0.2.2}/pgvector_template/core/embedder.py +0 -0
  12. {pgvector_template-0.2.0 → pgvector_template-0.2.2}/pgvector_template/core/manager.py +0 -0
  13. {pgvector_template-0.2.0 → pgvector_template-0.2.2}/pgvector_template/db/__init__.py +0 -0
  14. {pgvector_template-0.2.0 → pgvector_template-0.2.2}/pgvector_template/db/connection.py +0 -0
  15. {pgvector_template-0.2.0 → pgvector_template-0.2.2}/pgvector_template/db/document_db.py +0 -0
  16. {pgvector_template-0.2.0 → pgvector_template-0.2.2}/pgvector_template/service/__init__.py +0 -0
  17. {pgvector_template-0.2.0 → pgvector_template-0.2.2}/pgvector_template/types.py +0 -0
  18. {pgvector_template-0.2.0 → pgvector_template-0.2.2}/pgvector_template/utils/__init__.py +0 -0
  19. {pgvector_template-0.2.0 → pgvector_template-0.2.2}/pgvector_template.egg-info/SOURCES.txt +0 -0
  20. {pgvector_template-0.2.0 → pgvector_template-0.2.2}/pgvector_template.egg-info/dependency_links.txt +0 -0
  21. {pgvector_template-0.2.0 → pgvector_template-0.2.2}/pgvector_template.egg-info/requires.txt +0 -0
  22. {pgvector_template-0.2.0 → pgvector_template-0.2.2}/pgvector_template.egg-info/top_level.txt +0 -0
  23. {pgvector_template-0.2.0 → pgvector_template-0.2.2}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: pgvector-template
3
- Version: 0.2.0
3
+ Version: 0.2.2
4
4
  Summary: Template library for flexible PGVector RAG implementations
5
5
  Author-email: DL <v49t9zpqd@mozmail.com>
6
6
  License: MIT
@@ -12,6 +12,7 @@ from sqlalchemy import (
12
12
  Integer,
13
13
  Float,
14
14
  Index,
15
+ UniqueConstraint,
15
16
  )
16
17
  from sqlalchemy.orm import declarative_base
17
18
  from sqlalchemy.dialects.postgresql import UUID, JSONB
@@ -63,6 +64,7 @@ class BaseDocument(Base):
63
64
  """
64
65
 
65
66
  __abstract__ = True
67
+ __tablename__ = "base_document"
66
68
 
67
69
  id = Column(UUID(as_uuid=True), primary_key=True, default=uuid4)
68
70
  """Primary key of the Document table. Represents unique ID of a Document"""
@@ -98,9 +100,39 @@ class BaseDocument(Base):
98
100
  # Audit fields
99
101
  created_at = Column(DateTime, default=datetime.utcnow)
100
102
  updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
101
- is_deleted = Column(Boolean, default=False)
103
+ is_deleted = Column(Boolean, default=False, index=True)
102
104
  """Entries can be logically marked for deletion before they are permanently deleted."""
103
105
 
106
+ def __init_subclass__(cls, **kwargs):
107
+ """Simply declare `__table_args__` to add more args in child classes."""
108
+ super().__init_subclass__(**kwargs)
109
+
110
+ if hasattr(cls, "__tablename__"):
111
+ table_name = cls.__tablename__
112
+
113
+ base_table_args = (
114
+ Index(
115
+ f"{table_name}_metadata_gin_idx", "document_metadata", postgresql_using="gin"
116
+ ),
117
+ cls.get_embedding_index(table_name),
118
+ Index(f"{table_name}_tags_gin_idx", "tags", postgresql_using="gin"),
119
+ Index(f"{table_name}_collection_corpus_idx", "collection", "corpus_id"),
120
+ UniqueConstraint(
121
+ "collection",
122
+ "corpus_id",
123
+ "chunk_index",
124
+ name=f"{table_name}_collection_corpus_chunk_unique",
125
+ ),
126
+ )
127
+
128
+ subclass_args = getattr(cls, "__table_args__", ())
129
+ if isinstance(subclass_args, dict):
130
+ cls.__table_args__ = base_table_args + (subclass_args,)
131
+ else:
132
+ if not isinstance(subclass_args, tuple):
133
+ subclass_args = (subclass_args,) if subclass_args else ()
134
+ cls.__table_args__ = base_table_args + subclass_args
135
+
104
136
  @classmethod
105
137
  def from_props(
106
138
  cls: Type[T],
@@ -142,9 +174,15 @@ class BaseDocument(Base):
142
174
  tags=optional_props.tags,
143
175
  )
144
176
 
145
- # Index("ix_corpus_chunk", "corpus_id", "chunk_index")
146
- # Index("ix_content_trgm", text("content gin_trgm_ops"), postgresql_using="gin") # For fuzzy text search
147
- # Index("ix_metadata_gin", "metadata", postgresql_using="gin")
177
+ @classmethod
178
+ def get_embedding_index(cls, table_name: str) -> Index:
179
+ """Override this method to customize the embedding index."""
180
+ return Index(
181
+ f"{table_name}_embedding_hnsw_idx",
182
+ "embedding",
183
+ postgresql_using="hnsw",
184
+ postgresql_ops={"embedding": "vector_cosine_ops"},
185
+ )
148
186
 
149
187
 
150
188
  class BaseDocumentMetadata(BaseModel):
@@ -154,7 +192,9 @@ class BaseDocumentMetadata(BaseModel):
154
192
  without any extraneous properties, or any missing properties, to avoid ambiguity.
155
193
  """
156
194
 
157
- document_type: str = Field(..., description="Description for type of document, e.g. markdown, pdf, etc")
195
+ document_type: str = Field(
196
+ ..., description="Description for type of document, e.g. markdown, pdf, etc"
197
+ )
158
198
  schema_version: str = Field(default="1.0", description="Schema version for the metadata")
159
199
 
160
200
  def to_dict(self) -> dict[str, Any]:
@@ -109,22 +109,21 @@ class BaseSearchClient:
109
109
  """
110
110
  db_query = select(self.config.document_cls)
111
111
 
112
- # if query.text:
113
- # db_query = self._apply_semantic_search(db_query, query)
112
+ if query.text:
113
+ db_query = self._apply_semantic_search(db_query, query)
114
114
  db_query = self._apply_keyword_search(db_query, query)
115
115
  # if query.metadata_filters:
116
116
  # db_query = self._apply_metadata_filters(db_query, query)
117
117
  db_query = db_query.limit(query.limit)
118
118
 
119
- # Execute the query
119
+ # execute query and return results
120
120
  results = self.session.scalars(db_query).all()
121
-
122
- # Convert to RetrievalResult objects
123
121
  return self._convert_to_retrieval_results(results)
124
122
 
125
123
  def _apply_semantic_search(self, query: Select, search_query: SearchQuery) -> Select:
126
124
  """Apply semantic (vector) search criteria to the query.
127
125
  `embedding_provider` must be provided at instantiation, or an `ValueError` will be raised.
126
+ In PGVector, `<=>` operator is used to compare cosine distance. Lower = more similar.
128
127
 
129
128
  Args:
130
129
  query: The base SQLAlchemy query.
@@ -133,11 +132,10 @@ class BaseSearchClient:
133
132
  Returns:
134
133
  Updated SQLAlchemy query with semantic search applied.
135
134
  """
136
- if not self.config.embedding_provider:
137
- raise ValueError(
138
- "EmbeddingProvider not provided in config. Vector (semantic) search is unavailable."
139
- )
140
- raise NotImplementedError
135
+ if not search_query.text:
136
+ return query
137
+ query_embedding = self.embedding_provider.embed_text(search_query.text)
138
+ return query.order_by(self.config.document_cls.embedding.cosine_distance(query_embedding))
141
139
 
142
140
  def _apply_keyword_search(self, db_query: Select, search_query: SearchQuery) -> Select:
143
141
  """Apply keyword (full-text) search criteria to the query.
@@ -53,6 +53,12 @@ class DocumentServiceConfig(BaseModel):
53
53
  if type(self.search_client_cfg) is BaseSearchClientConfig:
54
54
  self.search_client_cfg.document_cls = self.document_cls
55
55
 
56
+ # assign embedding_provider to CorpusManager & SearchClient configs
57
+ if not self.corpus_manager_cfg.embedding_provider:
58
+ self.corpus_manager_cfg.embedding_provider = self.embedding_provider
59
+ if not self.search_client_cfg.embedding_provider:
60
+ self.search_client_cfg.embedding_provider = self.embedding_provider
61
+
56
62
  model_config = {"arbitrary_types_allowed": True}
57
63
 
58
64
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: pgvector-template
3
- Version: 0.2.0
3
+ Version: 0.2.2
4
4
  Summary: Template library for flexible PGVector RAG implementations
5
5
  Author-email: DL <v49t9zpqd@mozmail.com>
6
6
  License: MIT
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "pgvector-template"
7
- version = "0.2.0"
7
+ version = "0.2.2"
8
8
  description = "Template library for flexible PGVector RAG implementations"
9
9
  authors = [{ name="DL", email="v49t9zpqd@mozmail.com" }]
10
10
  license = { text = "MIT" }