llama-index-vector-stores-docarray 0.2.0__tar.gz → 0.3.0__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.
@@ -1,11 +1,11 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: llama-index-vector-stores-docarray
3
- Version: 0.2.0
3
+ Version: 0.3.0
4
4
  Summary: llama-index vector stores docarray integration
5
5
  License: MIT
6
6
  Author: Your Name
7
7
  Author-email: you@example.com
8
- Requires-Python: >=3.8.1,<4.0
8
+ Requires-Python: >=3.9,<4.0
9
9
  Classifier: License :: OSI Approved :: MIT License
10
10
  Classifier: Programming Language :: Python :: 3
11
11
  Classifier: Programming Language :: Python :: 3.9
@@ -13,7 +13,7 @@ Classifier: Programming Language :: Python :: 3.10
13
13
  Classifier: Programming Language :: Python :: 3.11
14
14
  Classifier: Programming Language :: Python :: 3.12
15
15
  Requires-Dist: docarray (>=0.40.0,<0.41.0)
16
- Requires-Dist: llama-index-core (>=0.11.0,<0.12.0)
16
+ Requires-Dist: llama-index-core (>=0.12.0,<0.13.0)
17
17
  Description-Content-Type: text/markdown
18
18
 
19
19
  # LlamaIndex Vector Stores Integration: Docarray
@@ -28,12 +28,12 @@ exclude = ["**/BUILD"]
28
28
  license = "MIT"
29
29
  name = "llama-index-vector-stores-docarray"
30
30
  readme = "README.md"
31
- version = "0.2.0"
31
+ version = "0.3.0"
32
32
 
33
33
  [tool.poetry.dependencies]
34
- python = ">=3.8.1,<4.0"
34
+ python = ">=3.9,<4.0"
35
35
  docarray = "^0.40.0"
36
- llama-index-core = "^0.11.0"
36
+ llama-index-core = "^0.12.0"
37
37
 
38
38
  [tool.poetry.group.dev.dependencies]
39
39
  ipython = "8.10.0"
@@ -1,231 +0,0 @@
1
- """txtai Vector store index.
2
-
3
- An index that is built on top of an existing vector store.
4
-
5
- """
6
-
7
- import json
8
- import logging
9
- import os
10
- import pickle
11
- from pathlib import Path
12
- from typing import Any, List, Optional, cast
13
-
14
- import fsspec
15
- import numpy as np
16
- from fsspec.implementations.local import LocalFileSystem
17
- from llama_index.bridge.pydantic import PrivateAttr
18
- from llama_index.schema import BaseNode
19
- from llama_index.vector_stores.simple import DEFAULT_VECTOR_STORE, NAMESPACE_SEP
20
- from llama_index.vector_stores.types import (
21
- DEFAULT_PERSIST_DIR,
22
- DEFAULT_PERSIST_FNAME,
23
- BasePydanticVectorStore,
24
- VectorStoreQuery,
25
- VectorStoreQueryResult,
26
- )
27
-
28
- logger = logging.getLogger()
29
-
30
- DEFAULT_PERSIST_PATH = os.path.join(
31
- DEFAULT_PERSIST_DIR, f"{DEFAULT_VECTOR_STORE}{NAMESPACE_SEP}{DEFAULT_PERSIST_FNAME}"
32
- )
33
- IMPORT_ERROR_MSG = """
34
- `txtai` package not found. For instructions on
35
- how to install `txtai` please visit
36
- https://neuml.github.io/txtai/install/
37
- """
38
-
39
-
40
- class TxtaiVectorStore(BasePydanticVectorStore):
41
- """txtai Vector Store.
42
-
43
- Embeddings are stored within a txtai index.
44
-
45
- During query time, the index uses txtai to query for the top
46
- k embeddings, and returns the corresponding indices.
47
-
48
- Args:
49
- txtai_index (txtai.ann.ANN): txtai index instance
50
-
51
- """
52
-
53
- stores_text: bool = False
54
-
55
- _txtai_index = PrivateAttr()
56
-
57
- def __init__(
58
- self,
59
- txtai_index: Any,
60
- ) -> None:
61
- """Initialize params."""
62
- try:
63
- import txtai
64
- except ImportError:
65
- raise ImportError(IMPORT_ERROR_MSG)
66
-
67
- self._txtai_index = cast(txtai.ann.ANN, txtai_index)
68
-
69
- super().__init__()
70
-
71
- @classmethod
72
- def from_persist_dir(
73
- cls,
74
- persist_dir: str = DEFAULT_PERSIST_DIR,
75
- fs: Optional[fsspec.AbstractFileSystem] = None,
76
- ) -> "TxtaiVectorStore":
77
- persist_path = os.path.join(
78
- persist_dir,
79
- f"{DEFAULT_VECTOR_STORE}{NAMESPACE_SEP}{DEFAULT_PERSIST_FNAME}",
80
- )
81
- # only support local storage for now
82
- if fs and not isinstance(fs, LocalFileSystem):
83
- raise NotImplementedError("txtai only supports local storage for now.")
84
- return cls.from_persist_path(persist_path=persist_path, fs=None)
85
-
86
- @classmethod
87
- def from_persist_path(
88
- cls,
89
- persist_path: str,
90
- fs: Optional[fsspec.AbstractFileSystem] = None,
91
- ) -> "TxtaiVectorStore":
92
- try:
93
- import txtai
94
- except ImportError:
95
- raise ImportError(IMPORT_ERROR_MSG)
96
-
97
- if fs and not isinstance(fs, LocalFileSystem):
98
- raise NotImplementedError("txtai only supports local storage for now.")
99
-
100
- if not os.path.exists(persist_path):
101
- raise ValueError(f"No existing {__name__} found at {persist_path}.")
102
-
103
- logger.info(f"Loading {__name__} config from {persist_path}.")
104
- parent_directory = Path(persist_path).parent
105
- config_path = parent_directory / "config.json"
106
- jsonconfig = config_path.exists()
107
- # Determine if config is json or pickle
108
- config_path = config_path if jsonconfig else parent_directory / "config"
109
- # Load configuration
110
- with open(config_path, "r" if jsonconfig else "rb") as f:
111
- config = json.load(f) if jsonconfig else pickle.load(f)
112
-
113
- logger.info(f"Loading {__name__} from {persist_path}.")
114
- txtai_index = txtai.ann.ANNFactory.create(config)
115
- txtai_index.load(persist_path)
116
- return cls(txtai_index=txtai_index)
117
-
118
- def add(
119
- self,
120
- nodes: List[BaseNode],
121
- **add_kwargs: Any,
122
- ) -> List[str]:
123
- """Add nodes to index.
124
-
125
- Args:
126
- nodes: List[BaseNode]: list of nodes with embeddings
127
-
128
- """
129
- text_embedding_np = np.array(
130
- [node.get_embedding() for node in nodes], dtype="float32"
131
- )
132
-
133
- # Check if the ann index is already created
134
- # If not create the index with node embeddings
135
- if self._txtai_index.backend is None:
136
- self._txtai_index.index(text_embedding_np)
137
- else:
138
- self._txtai_index.append(text_embedding_np)
139
-
140
- indx_size = self._txtai_index.count()
141
- return [str(idx) for idx in range(indx_size - len(nodes) + 1, indx_size + 1)]
142
-
143
- @property
144
- def client(self) -> Any:
145
- """Return the txtai index."""
146
- return self._txtai_index
147
-
148
- def persist(
149
- self,
150
- persist_path: str = DEFAULT_PERSIST_PATH,
151
- fs: Optional[fsspec.AbstractFileSystem] = None,
152
- ) -> None:
153
- """Save to file.
154
-
155
- This method saves the vector store to disk.
156
-
157
- Args:
158
- persist_path (str): The save_path of the file.
159
-
160
- """
161
- if fs and not isinstance(fs, LocalFileSystem):
162
- raise NotImplementedError("txtai only supports local storage for now.")
163
-
164
- dirpath = Path(persist_path).parent
165
- dirpath.mkdir(exist_ok=True)
166
-
167
- jsonconfig = self._txtai_index.config.get("format", "pickle") == "json"
168
- # Determine if config is json or pickle
169
- config_path = dirpath / "config.json" if jsonconfig else dirpath / "config"
170
-
171
- # Write configuration
172
- with open(
173
- config_path,
174
- "w" if jsonconfig else "wb",
175
- encoding="utf-8" if jsonconfig else None,
176
- ) as f:
177
- if jsonconfig:
178
- # Write config as JSON
179
- json.dump(self._txtai_index.config, f, default=str)
180
- else:
181
- from txtai.version import __pickle__
182
-
183
- # Write config as pickle format
184
- pickle.dump(self._txtai_index.config, f, protocol=__pickle__)
185
-
186
- self._txtai_index.save(persist_path)
187
-
188
- def delete(self, ref_doc_id: str, **delete_kwargs: Any) -> None:
189
- """
190
- Delete nodes using with ref_doc_id.
191
-
192
- Args:
193
- ref_doc_id (str): The doc_id of the document to delete.
194
-
195
- """
196
- self._txtai_index.delete([int(ref_doc_id)])
197
-
198
- def query(
199
- self,
200
- query: VectorStoreQuery,
201
- **kwargs: Any,
202
- ) -> VectorStoreQueryResult:
203
- """Query index for top k most similar nodes.
204
-
205
- Args:
206
- query (VectorStoreQuery): query to search for in the index
207
-
208
- """
209
- if query.filters is not None:
210
- raise ValueError("Metadata filters not implemented for txtai yet.")
211
-
212
- query_embedding = cast(List[float], query.query_embedding)
213
- query_embedding_np = np.array(query_embedding, dtype="float32")[np.newaxis, :]
214
- search_result = self._txtai_index.search(
215
- query_embedding_np, query.similarity_top_k
216
- )[0]
217
- # if empty, then return an empty response
218
- if len(search_result) == 0:
219
- return VectorStoreQueryResult(similarities=[], ids=[])
220
-
221
- filtered_dists = []
222
- filtered_node_idxs = []
223
- for dist, idx in search_result:
224
- if idx < 0:
225
- continue
226
- filtered_dists.append(dist)
227
- filtered_node_idxs.append(str(idx))
228
-
229
- return VectorStoreQueryResult(
230
- similarities=filtered_dists, ids=filtered_node_idxs
231
- )