langroid 0.33.6__py3-none-any.whl → 0.33.8__py3-none-any.whl

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 (129) hide show
  1. langroid/__init__.py +106 -0
  2. langroid/agent/__init__.py +41 -0
  3. langroid/agent/base.py +1983 -0
  4. langroid/agent/batch.py +398 -0
  5. langroid/agent/callbacks/__init__.py +0 -0
  6. langroid/agent/callbacks/chainlit.py +598 -0
  7. langroid/agent/chat_agent.py +1899 -0
  8. langroid/agent/chat_document.py +454 -0
  9. langroid/agent/openai_assistant.py +882 -0
  10. langroid/agent/special/__init__.py +59 -0
  11. langroid/agent/special/arangodb/__init__.py +0 -0
  12. langroid/agent/special/arangodb/arangodb_agent.py +656 -0
  13. langroid/agent/special/arangodb/system_messages.py +186 -0
  14. langroid/agent/special/arangodb/tools.py +107 -0
  15. langroid/agent/special/arangodb/utils.py +36 -0
  16. langroid/agent/special/doc_chat_agent.py +1466 -0
  17. langroid/agent/special/lance_doc_chat_agent.py +262 -0
  18. langroid/agent/special/lance_rag/__init__.py +9 -0
  19. langroid/agent/special/lance_rag/critic_agent.py +198 -0
  20. langroid/agent/special/lance_rag/lance_rag_task.py +82 -0
  21. langroid/agent/special/lance_rag/query_planner_agent.py +260 -0
  22. langroid/agent/special/lance_tools.py +61 -0
  23. langroid/agent/special/neo4j/__init__.py +0 -0
  24. langroid/agent/special/neo4j/csv_kg_chat.py +174 -0
  25. langroid/agent/special/neo4j/neo4j_chat_agent.py +433 -0
  26. langroid/agent/special/neo4j/system_messages.py +120 -0
  27. langroid/agent/special/neo4j/tools.py +32 -0
  28. langroid/agent/special/relevance_extractor_agent.py +127 -0
  29. langroid/agent/special/retriever_agent.py +56 -0
  30. langroid/agent/special/sql/__init__.py +17 -0
  31. langroid/agent/special/sql/sql_chat_agent.py +654 -0
  32. langroid/agent/special/sql/utils/__init__.py +21 -0
  33. langroid/agent/special/sql/utils/description_extractors.py +190 -0
  34. langroid/agent/special/sql/utils/populate_metadata.py +85 -0
  35. langroid/agent/special/sql/utils/system_message.py +35 -0
  36. langroid/agent/special/sql/utils/tools.py +64 -0
  37. langroid/agent/special/table_chat_agent.py +263 -0
  38. langroid/agent/task.py +2099 -0
  39. langroid/agent/tool_message.py +393 -0
  40. langroid/agent/tools/__init__.py +38 -0
  41. langroid/agent/tools/duckduckgo_search_tool.py +50 -0
  42. langroid/agent/tools/file_tools.py +234 -0
  43. langroid/agent/tools/google_search_tool.py +39 -0
  44. langroid/agent/tools/metaphor_search_tool.py +68 -0
  45. langroid/agent/tools/orchestration.py +303 -0
  46. langroid/agent/tools/recipient_tool.py +235 -0
  47. langroid/agent/tools/retrieval_tool.py +32 -0
  48. langroid/agent/tools/rewind_tool.py +137 -0
  49. langroid/agent/tools/segment_extract_tool.py +41 -0
  50. langroid/agent/xml_tool_message.py +382 -0
  51. langroid/cachedb/__init__.py +17 -0
  52. langroid/cachedb/base.py +58 -0
  53. langroid/cachedb/momento_cachedb.py +108 -0
  54. langroid/cachedb/redis_cachedb.py +153 -0
  55. langroid/embedding_models/__init__.py +39 -0
  56. langroid/embedding_models/base.py +74 -0
  57. langroid/embedding_models/models.py +461 -0
  58. langroid/embedding_models/protoc/__init__.py +0 -0
  59. langroid/embedding_models/protoc/embeddings.proto +19 -0
  60. langroid/embedding_models/protoc/embeddings_pb2.py +33 -0
  61. langroid/embedding_models/protoc/embeddings_pb2.pyi +50 -0
  62. langroid/embedding_models/protoc/embeddings_pb2_grpc.py +79 -0
  63. langroid/embedding_models/remote_embeds.py +153 -0
  64. langroid/exceptions.py +71 -0
  65. langroid/language_models/__init__.py +53 -0
  66. langroid/language_models/azure_openai.py +153 -0
  67. langroid/language_models/base.py +678 -0
  68. langroid/language_models/config.py +18 -0
  69. langroid/language_models/mock_lm.py +124 -0
  70. langroid/language_models/openai_gpt.py +1964 -0
  71. langroid/language_models/prompt_formatter/__init__.py +16 -0
  72. langroid/language_models/prompt_formatter/base.py +40 -0
  73. langroid/language_models/prompt_formatter/hf_formatter.py +132 -0
  74. langroid/language_models/prompt_formatter/llama2_formatter.py +75 -0
  75. langroid/language_models/utils.py +151 -0
  76. langroid/mytypes.py +84 -0
  77. langroid/parsing/__init__.py +52 -0
  78. langroid/parsing/agent_chats.py +38 -0
  79. langroid/parsing/code_parser.py +121 -0
  80. langroid/parsing/document_parser.py +718 -0
  81. langroid/parsing/para_sentence_split.py +62 -0
  82. langroid/parsing/parse_json.py +155 -0
  83. langroid/parsing/parser.py +313 -0
  84. langroid/parsing/repo_loader.py +790 -0
  85. langroid/parsing/routing.py +36 -0
  86. langroid/parsing/search.py +275 -0
  87. langroid/parsing/spider.py +102 -0
  88. langroid/parsing/table_loader.py +94 -0
  89. langroid/parsing/url_loader.py +115 -0
  90. langroid/parsing/urls.py +273 -0
  91. langroid/parsing/utils.py +373 -0
  92. langroid/parsing/web_search.py +156 -0
  93. langroid/prompts/__init__.py +9 -0
  94. langroid/prompts/dialog.py +17 -0
  95. langroid/prompts/prompts_config.py +5 -0
  96. langroid/prompts/templates.py +141 -0
  97. langroid/pydantic_v1/__init__.py +10 -0
  98. langroid/pydantic_v1/main.py +4 -0
  99. langroid/utils/__init__.py +19 -0
  100. langroid/utils/algorithms/__init__.py +3 -0
  101. langroid/utils/algorithms/graph.py +103 -0
  102. langroid/utils/configuration.py +98 -0
  103. langroid/utils/constants.py +30 -0
  104. langroid/utils/git_utils.py +252 -0
  105. langroid/utils/globals.py +49 -0
  106. langroid/utils/logging.py +135 -0
  107. langroid/utils/object_registry.py +66 -0
  108. langroid/utils/output/__init__.py +20 -0
  109. langroid/utils/output/citations.py +41 -0
  110. langroid/utils/output/printing.py +99 -0
  111. langroid/utils/output/status.py +40 -0
  112. langroid/utils/pandas_utils.py +30 -0
  113. langroid/utils/pydantic_utils.py +602 -0
  114. langroid/utils/system.py +286 -0
  115. langroid/utils/types.py +93 -0
  116. langroid/vector_store/__init__.py +50 -0
  117. langroid/vector_store/base.py +359 -0
  118. langroid/vector_store/chromadb.py +214 -0
  119. langroid/vector_store/lancedb.py +406 -0
  120. langroid/vector_store/meilisearch.py +299 -0
  121. langroid/vector_store/momento.py +278 -0
  122. langroid/vector_store/qdrantdb.py +468 -0
  123. {langroid-0.33.6.dist-info → langroid-0.33.8.dist-info}/METADATA +95 -94
  124. langroid-0.33.8.dist-info/RECORD +127 -0
  125. {langroid-0.33.6.dist-info → langroid-0.33.8.dist-info}/WHEEL +1 -1
  126. langroid-0.33.6.dist-info/RECORD +0 -7
  127. langroid-0.33.6.dist-info/entry_points.txt +0 -4
  128. pyproject.toml +0 -356
  129. {langroid-0.33.6.dist-info → langroid-0.33.8.dist-info}/licenses/LICENSE +0 -0
@@ -0,0 +1,406 @@
1
+ from __future__ import annotations
2
+
3
+ import logging
4
+ from typing import (
5
+ TYPE_CHECKING,
6
+ Any,
7
+ Dict,
8
+ Generator,
9
+ List,
10
+ Optional,
11
+ Sequence,
12
+ Tuple,
13
+ Type,
14
+ )
15
+
16
+ import pandas as pd
17
+ from dotenv import load_dotenv
18
+
19
+ from langroid.pydantic_v1 import BaseModel, ValidationError, create_model
20
+
21
+ if TYPE_CHECKING:
22
+ from lancedb.query import LanceVectorQueryBuilder
23
+
24
+ from langroid.embedding_models.base import (
25
+ EmbeddingModelsConfig,
26
+ )
27
+ from langroid.embedding_models.models import OpenAIEmbeddingsConfig
28
+ from langroid.exceptions import LangroidImportError
29
+ from langroid.mytypes import Document, EmbeddingFunction
30
+ from langroid.utils.configuration import settings
31
+ from langroid.utils.pydantic_utils import (
32
+ dataframe_to_document_model,
33
+ dataframe_to_documents,
34
+ )
35
+ from langroid.vector_store.base import VectorStore, VectorStoreConfig
36
+
37
+ try:
38
+ import lancedb
39
+ from lancedb.pydantic import LanceModel, Vector
40
+
41
+ has_lancedb = True
42
+ except ImportError:
43
+ has_lancedb = False
44
+
45
+ logger = logging.getLogger(__name__)
46
+
47
+
48
+ class LanceDBConfig(VectorStoreConfig):
49
+ cloud: bool = False
50
+ collection_name: str | None = "temp"
51
+ storage_path: str = ".lancedb/data"
52
+ embedding: EmbeddingModelsConfig = OpenAIEmbeddingsConfig()
53
+ distance: str = "cosine"
54
+
55
+
56
+ class LanceDB(VectorStore):
57
+ def __init__(self, config: LanceDBConfig = LanceDBConfig()):
58
+ super().__init__(config)
59
+ if not has_lancedb:
60
+ raise LangroidImportError("lancedb", "lancedb")
61
+
62
+ self.config: LanceDBConfig = config
63
+ self.embedding_fn: EmbeddingFunction = self.embedding_model.embedding_fn()
64
+ self.embedding_dim = self.embedding_model.embedding_dims
65
+ self.host = config.host
66
+ self.port = config.port
67
+ self.is_from_dataframe = False # were docs ingested from a dataframe?
68
+ self.df_metadata_columns: List[str] = [] # metadata columns from dataframe
69
+
70
+ load_dotenv()
71
+ if self.config.cloud:
72
+ logger.warning(
73
+ "LanceDB Cloud is not available yet. Switching to local storage."
74
+ )
75
+ config.cloud = False
76
+ else:
77
+ try:
78
+ self.client = lancedb.connect(
79
+ uri=config.storage_path,
80
+ )
81
+ except Exception as e:
82
+ new_storage_path = config.storage_path + ".new"
83
+ logger.warning(
84
+ f"""
85
+ Error connecting to local LanceDB at {config.storage_path}:
86
+ {e}
87
+ Switching to {new_storage_path}
88
+ """
89
+ )
90
+ self.client = lancedb.connect(
91
+ uri=new_storage_path,
92
+ )
93
+
94
+ def clear_empty_collections(self) -> int:
95
+ coll_names = self.list_collections()
96
+ n_deletes = 0
97
+ for name in coll_names:
98
+ nr = self.client.open_table(name).head(1).shape[0]
99
+ if nr == 0:
100
+ n_deletes += 1
101
+ self.client.drop_table(name)
102
+ return n_deletes
103
+
104
+ def clear_all_collections(self, really: bool = False, prefix: str = "") -> int:
105
+ """Clear all collections with the given prefix."""
106
+ if not really:
107
+ logger.warning("Not deleting all collections, set really=True to confirm")
108
+ return 0
109
+ coll_names = [
110
+ c for c in self.list_collections(empty=True) if c.startswith(prefix)
111
+ ]
112
+ if len(coll_names) == 0:
113
+ logger.warning(f"No collections found with prefix {prefix}")
114
+ return 0
115
+ n_empty_deletes = 0
116
+ n_non_empty_deletes = 0
117
+ for name in coll_names:
118
+ nr = self.client.open_table(name).head(1).shape[0]
119
+ n_empty_deletes += nr == 0
120
+ n_non_empty_deletes += nr > 0
121
+ self.client.drop_table(name)
122
+ logger.warning(
123
+ f"""
124
+ Deleted {n_empty_deletes} empty collections and
125
+ {n_non_empty_deletes} non-empty collections.
126
+ """
127
+ )
128
+ return n_empty_deletes + n_non_empty_deletes
129
+
130
+ def list_collections(self, empty: bool = False) -> List[str]:
131
+ """
132
+ Returns:
133
+ List of collection names that have at least one vector.
134
+
135
+ Args:
136
+ empty (bool, optional): Whether to include empty collections.
137
+ """
138
+ colls = self.client.table_names(limit=None)
139
+ if len(colls) == 0:
140
+ return []
141
+ if empty: # include empty tbls
142
+ return colls # type: ignore
143
+ counts = [self.client.open_table(coll).head(1).shape[0] for coll in colls]
144
+ return [coll for coll, count in zip(colls, counts) if count > 0]
145
+
146
+ def _create_lance_schema(self, doc_cls: Type[Document]) -> Type[BaseModel]:
147
+ """
148
+ NOTE: NOT USED, but leaving it here as it may be useful.
149
+
150
+ Create a subclass of LanceModel with fields:
151
+ - id (str)
152
+ - Vector field that has dims equal to
153
+ the embedding dimension of the embedding model, and a data field of type
154
+ DocClass.
155
+ - other fields from doc_cls
156
+
157
+ Args:
158
+ doc_cls (Type[Document]): A Pydantic model which should be a subclass of
159
+ Document, to be used as the type for the data field.
160
+
161
+ Returns:
162
+ Type[BaseModel]: A new Pydantic model subclassing from LanceModel.
163
+
164
+ Raises:
165
+ ValueError: If `n` is not a non-negative integer or if `DocClass` is not a
166
+ subclass of Document.
167
+ """
168
+ if not issubclass(doc_cls, Document):
169
+ raise ValueError("DocClass must be a subclass of Document")
170
+
171
+ if not has_lancedb:
172
+ raise LangroidImportError("lancedb", "lancedb")
173
+
174
+ n = self.embedding_dim
175
+
176
+ # Prepare fields for the new model
177
+ fields = {"id": (str, ...), "vector": (Vector(n), ...)}
178
+
179
+ sorted_fields = dict(
180
+ sorted(doc_cls.__fields__.items(), key=lambda item: item[0])
181
+ )
182
+ # Add both statically and dynamically defined fields from doc_cls
183
+ for field_name, field in sorted_fields.items():
184
+ fields[field_name] = (field.outer_type_, field.default)
185
+
186
+ # Create the new model with dynamic fields
187
+ NewModel = create_model(
188
+ "NewModel", __base__=LanceModel, **fields
189
+ ) # type: ignore
190
+ return NewModel # type: ignore
191
+
192
+ def create_collection(self, collection_name: str, replace: bool = False) -> None:
193
+ self.config.replace_collection = replace
194
+ self.config.collection_name = collection_name
195
+ if replace:
196
+ self.delete_collection(collection_name)
197
+
198
+ def add_documents(self, documents: Sequence[Document]) -> None:
199
+ super().maybe_add_ids(documents)
200
+ colls = self.list_collections(empty=True)
201
+ if len(documents) == 0:
202
+ return
203
+ embedding_vecs = self.embedding_fn([doc.content for doc in documents])
204
+ coll_name = self.config.collection_name
205
+ if coll_name is None:
206
+ raise ValueError("No collection name set, cannot ingest docs")
207
+ # self._maybe_set_doc_class_schema(documents[0])
208
+ table_exists = False
209
+ if (
210
+ coll_name in colls
211
+ and self.client.open_table(coll_name).head(1).shape[0] > 0
212
+ ):
213
+ # collection exists and is not empty:
214
+ # if replace_collection is True, we'll overwrite the existing collection,
215
+ # else we'll append to it.
216
+ if self.config.replace_collection:
217
+ self.client.drop_table(coll_name)
218
+ else:
219
+ table_exists = True
220
+
221
+ ids = [str(d.id()) for d in documents]
222
+ # don't insert all at once, batch in chunks of b,
223
+ # else we get an API error
224
+ b = self.config.batch_size
225
+
226
+ def make_batches() -> Generator[List[Dict[str, Any]], None, None]:
227
+ for i in range(0, len(ids), b):
228
+ batch = [
229
+ dict(
230
+ id=ids[i + j],
231
+ vector=embedding_vecs[i + j],
232
+ **doc.dict(),
233
+ )
234
+ for j, doc in enumerate(documents[i : i + b])
235
+ ]
236
+ yield batch
237
+
238
+ try:
239
+ if table_exists:
240
+ tbl = self.client.open_table(coll_name)
241
+ tbl.add(make_batches())
242
+ else:
243
+ batch_gen = make_batches()
244
+ batch = next(batch_gen)
245
+ # use first batch to create table...
246
+ tbl = self.client.create_table(
247
+ coll_name,
248
+ data=batch,
249
+ mode="create",
250
+ )
251
+ # ... and add the rest
252
+ tbl.add(batch_gen)
253
+ except Exception as e:
254
+ logger.error(
255
+ f"""
256
+ Error adding documents to LanceDB: {e}
257
+ POSSIBLE REMEDY: Delete the LancdDB storage directory
258
+ {self.config.storage_path} and try again.
259
+ """
260
+ )
261
+
262
+ def add_dataframe(
263
+ self,
264
+ df: pd.DataFrame,
265
+ content: str = "content",
266
+ metadata: List[str] = [],
267
+ ) -> None:
268
+ """
269
+ Add a dataframe to the collection.
270
+ Args:
271
+ df (pd.DataFrame): A dataframe
272
+ content (str): The name of the column in the dataframe that contains the
273
+ text content to be embedded using the embedding model.
274
+ metadata (List[str]): A list of column names in the dataframe that contain
275
+ metadata to be stored in the database. Defaults to [].
276
+ """
277
+ self.is_from_dataframe = True
278
+ actual_metadata = metadata.copy()
279
+ self.df_metadata_columns = actual_metadata # could be updated below
280
+ # get content column
281
+ content_values = df[content].values.tolist()
282
+ embedding_vecs = self.embedding_fn(content_values)
283
+
284
+ # add vector column
285
+ df["vector"] = embedding_vecs
286
+ if content != "content":
287
+ # rename content column to "content", leave existing column intact
288
+ df = df.rename(columns={content: "content"}, inplace=False)
289
+
290
+ if "id" not in df.columns:
291
+ docs = dataframe_to_documents(df, content="content", metadata=metadata)
292
+ ids = [str(d.id()) for d in docs]
293
+ df["id"] = ids
294
+
295
+ if "id" not in actual_metadata:
296
+ actual_metadata += ["id"]
297
+
298
+ colls = self.list_collections(empty=True)
299
+ coll_name = self.config.collection_name
300
+ if (
301
+ coll_name not in colls
302
+ or self.client.open_table(coll_name).head(1).shape[0] == 0
303
+ ):
304
+ # collection either doesn't exist or is empty, so replace it
305
+ # and set new schema from df
306
+ self.client.create_table(
307
+ self.config.collection_name,
308
+ data=df,
309
+ mode="overwrite",
310
+ )
311
+ doc_cls = dataframe_to_document_model(
312
+ df,
313
+ content=content,
314
+ metadata=actual_metadata,
315
+ exclude=["vector"],
316
+ )
317
+ self.config.document_class = doc_cls # type: ignore
318
+ else:
319
+ # collection exists and is not empty, so append to it
320
+ tbl = self.client.open_table(self.config.collection_name)
321
+ tbl.add(df)
322
+
323
+ def delete_collection(self, collection_name: str) -> None:
324
+ self.client.drop_table(collection_name, ignore_missing=True)
325
+
326
+ def _lance_result_to_docs(
327
+ self, result: "LanceVectorQueryBuilder"
328
+ ) -> List[Document]:
329
+ if self.is_from_dataframe:
330
+ df = result.to_pandas()
331
+ return dataframe_to_documents(
332
+ df,
333
+ content="content",
334
+ metadata=self.df_metadata_columns,
335
+ doc_cls=self.config.document_class,
336
+ )
337
+ else:
338
+ records = result.to_arrow().to_pylist()
339
+ return self._records_to_docs(records)
340
+
341
+ def _records_to_docs(self, records: List[Dict[str, Any]]) -> List[Document]:
342
+ try:
343
+ docs = [self.config.document_class(**rec) for rec in records]
344
+ except ValidationError as e:
345
+ raise ValueError(
346
+ f"""
347
+ Error validating LanceDB result: {e}
348
+ HINT: This could happen when you're re-using an
349
+ existing LanceDB store with a different schema.
350
+ Try deleting your local lancedb storage at `{self.config.storage_path}`
351
+ re-ingesting your documents and/or replacing the collections.
352
+ """
353
+ )
354
+ return docs
355
+
356
+ def get_all_documents(self, where: str = "") -> List[Document]:
357
+ if self.config.collection_name is None:
358
+ raise ValueError("No collection name set, cannot retrieve docs")
359
+ if self.config.collection_name not in self.list_collections(empty=True):
360
+ return []
361
+ tbl = self.client.open_table(self.config.collection_name)
362
+ pre_result = tbl.search(None).where(where or None).limit(None)
363
+ return self._lance_result_to_docs(pre_result)
364
+
365
+ def get_documents_by_ids(self, ids: List[str]) -> List[Document]:
366
+ if self.config.collection_name is None:
367
+ raise ValueError("No collection name set, cannot retrieve docs")
368
+ _ids = [str(id) for id in ids]
369
+ tbl = self.client.open_table(self.config.collection_name)
370
+ docs = []
371
+ for _id in _ids:
372
+ results = self._lance_result_to_docs(tbl.search().where(f"id == '{_id}'"))
373
+ if len(results) > 0:
374
+ docs.append(results[0])
375
+ return docs
376
+
377
+ def similar_texts_with_scores(
378
+ self,
379
+ text: str,
380
+ k: int = 1,
381
+ where: Optional[str] = None,
382
+ ) -> List[Tuple[Document, float]]:
383
+ embedding = self.embedding_fn([text])[0]
384
+ tbl = self.client.open_table(self.config.collection_name)
385
+ result = (
386
+ tbl.search(embedding)
387
+ .metric(self.config.distance)
388
+ .where(where, prefilter=True)
389
+ .limit(k)
390
+ )
391
+ docs = self._lance_result_to_docs(result)
392
+ # note _distance is 1 - cosine
393
+ if self.is_from_dataframe:
394
+ scores = [
395
+ 1 - rec["_distance"] for rec in result.to_pandas().to_dict("records")
396
+ ]
397
+ else:
398
+ scores = [1 - rec["_distance"] for rec in result.to_arrow().to_pylist()]
399
+ if len(docs) == 0:
400
+ logger.warning(f"No matches found for {text}")
401
+ return []
402
+ if settings.debug:
403
+ logger.info(f"Found {len(docs)} matches, max score: {max(scores)}")
404
+ doc_score_pairs = list(zip(docs, scores))
405
+ self.show_if_debug(doc_score_pairs)
406
+ return doc_score_pairs
@@ -0,0 +1,299 @@
1
+ """
2
+ MeiliSearch as a pure document store, without its
3
+ (experimental) vector-store functionality.
4
+ We aim to use MeiliSearch for fast lexical search.
5
+ Note that what we call "Collection" in Langroid is referred to as
6
+ "Index" in MeiliSearch. Each data-store has its own terminology,
7
+ but for uniformity we use the Langroid terminology here.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import asyncio
13
+ import logging
14
+ import os
15
+ from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Sequence, Tuple
16
+
17
+ from dotenv import load_dotenv
18
+
19
+ if TYPE_CHECKING:
20
+ from meilisearch_python_sdk.index import AsyncIndex
21
+ from meilisearch_python_sdk.models.documents import DocumentsInfo
22
+
23
+
24
+ from langroid.exceptions import LangroidImportError
25
+ from langroid.mytypes import DocMetaData, Document
26
+ from langroid.utils.configuration import settings
27
+ from langroid.vector_store.base import VectorStore, VectorStoreConfig
28
+
29
+ logger = logging.getLogger(__name__)
30
+
31
+
32
+ class MeiliSearchConfig(VectorStoreConfig):
33
+ cloud: bool = False
34
+ collection_name: str | None = None
35
+ primary_key: str = "id"
36
+ port = 7700
37
+
38
+
39
+ class MeiliSearch(VectorStore):
40
+ def __init__(self, config: MeiliSearchConfig = MeiliSearchConfig()):
41
+ super().__init__(config)
42
+ try:
43
+ import meilisearch_python_sdk as meilisearch
44
+ except ImportError:
45
+ raise LangroidImportError("meilisearch", "meilisearch")
46
+
47
+ self.config: MeiliSearchConfig = config
48
+ self.host = config.host
49
+ self.port = config.port
50
+ load_dotenv()
51
+ self.key = os.getenv("MEILISEARCH_API_KEY") or "masterKey"
52
+ self.url = os.getenv("MEILISEARCH_API_URL") or f"http://{self.host}:{self.port}"
53
+ if config.cloud and None in [self.key, self.url]:
54
+ logger.warning(
55
+ f"""MEILISEARCH_API_KEY, MEILISEARCH_API_URL env variable must be set
56
+ to use MeiliSearch in cloud mode. Please set these values
57
+ in your .env file. Switching to local MeiliSearch at
58
+ {self.url}
59
+ """
60
+ )
61
+ config.cloud = False
62
+
63
+ self.client: Callable[[], meilisearch.AsyncClient] = lambda: (
64
+ meilisearch.AsyncClient(url=self.url, api_key=self.key)
65
+ )
66
+
67
+ # Note: Only create collection if a non-null collection name is provided.
68
+ # This is useful to delay creation of db until we have a suitable
69
+ # collection name (e.g. we could get it from the url or folder path).
70
+ if config.collection_name is not None:
71
+ self.create_collection(
72
+ config.collection_name, replace=config.replace_collection
73
+ )
74
+
75
+ def clear_empty_collections(self) -> int:
76
+ """All collections are treated as non-empty in MeiliSearch, so this is a
77
+ no-op"""
78
+ return 0
79
+
80
+ async def _async_delete_indices(self, uids: List[str]) -> List[bool]:
81
+ """Delete any indicecs in `uids` that exist.
82
+ Returns list of bools indicating whether the index has been deleted"""
83
+ async with self.client() as client:
84
+ result = await asyncio.gather(
85
+ *[client.delete_index_if_exists(uid=uid) for uid in uids]
86
+ )
87
+ return result
88
+
89
+ def clear_all_collections(self, really: bool = False, prefix: str = "") -> int:
90
+ """Delete all indices whose names start with `prefix`"""
91
+ if not really:
92
+ logger.warning("Not deleting all collections, set really=True to confirm")
93
+ return 0
94
+ coll_names = [c for c in self.list_collections() if c.startswith(prefix)]
95
+ deletes = asyncio.run(self._async_delete_indices(coll_names))
96
+ n_deletes = sum(deletes)
97
+ logger.warning(f"Deleted {n_deletes} indices in MeiliSearch")
98
+ return n_deletes
99
+
100
+ def _list_all_collections(self) -> List[str]:
101
+ """
102
+ List all collections, including empty ones.
103
+ Returns:
104
+ List of collection names.
105
+ """
106
+ return self.list_collections()
107
+
108
+ async def _async_get_indexes(self) -> List[AsyncIndex]:
109
+ async with self.client() as client:
110
+ indexes = await client.get_indexes(limit=10_000)
111
+ return [] if indexes is None else indexes # type: ignore
112
+
113
+ async def _async_get_index(self, index_uid: str) -> "AsyncIndex":
114
+ async with self.client() as client:
115
+ index = await client.get_index(index_uid)
116
+ return index # type: ignore
117
+
118
+ def list_collections(self, empty: bool = False) -> List[str]:
119
+ """
120
+ Returns:
121
+ List of index names stored. We treat any existing index as non-empty.
122
+ """
123
+ indexes = asyncio.run(self._async_get_indexes())
124
+ if len(indexes) == 0:
125
+ return []
126
+ else:
127
+ return [ind.uid for ind in indexes]
128
+
129
+ async def _async_create_index(self, collection_name: str) -> "AsyncIndex":
130
+ async with self.client() as client:
131
+ index = await client.create_index(
132
+ uid=collection_name,
133
+ primary_key=self.config.primary_key,
134
+ )
135
+ return index
136
+
137
+ async def _async_delete_index(self, collection_name: str) -> bool:
138
+ """Delete index if it exists. Returns True iff index was deleted"""
139
+ async with self.client() as client:
140
+ result = await client.delete_index_if_exists(uid=collection_name)
141
+ return result # type: ignore
142
+
143
+ def create_collection(self, collection_name: str, replace: bool = False) -> None:
144
+ """
145
+ Create a collection with the given name, optionally replacing an existing
146
+ collection if `replace` is True.
147
+ Args:
148
+ collection_name (str): Name of the collection to create.
149
+ replace (bool): Whether to replace an existing collection
150
+ with the same name. Defaults to False.
151
+ """
152
+ self.config.collection_name = collection_name
153
+ collections = self.list_collections()
154
+ if collection_name in collections:
155
+ logger.warning(
156
+ f"MeiliSearch Non-empty Index {collection_name} already exists"
157
+ )
158
+ if not replace:
159
+ logger.warning("Not replacing collection")
160
+ return
161
+ else:
162
+ logger.warning("Recreating fresh collection")
163
+ asyncio.run(self._async_delete_index(collection_name))
164
+ asyncio.run(self._async_create_index(collection_name))
165
+ collection_info = asyncio.run(self._async_get_index(collection_name))
166
+ if settings.debug:
167
+ level = logger.getEffectiveLevel()
168
+ logger.setLevel(logging.INFO)
169
+ logger.info(collection_info)
170
+ logger.setLevel(level)
171
+
172
+ async def _async_add_documents(
173
+ self, collection_name: str, documents: Sequence[Dict[str, Any]]
174
+ ) -> None:
175
+ async with self.client() as client:
176
+ index = client.index(collection_name)
177
+ await index.add_documents_in_batches(
178
+ documents=documents,
179
+ batch_size=self.config.batch_size,
180
+ primary_key=self.config.primary_key,
181
+ )
182
+
183
+ def add_documents(self, documents: Sequence[Document]) -> None:
184
+ super().maybe_add_ids(documents)
185
+ if len(documents) == 0:
186
+ return
187
+ colls = self._list_all_collections()
188
+ if self.config.collection_name is None:
189
+ raise ValueError("No collection name set, cannot ingest docs")
190
+ if self.config.collection_name not in colls:
191
+ self.create_collection(self.config.collection_name, replace=True)
192
+ docs = [
193
+ dict(
194
+ id=d.id(),
195
+ content=d.content,
196
+ metadata=d.metadata.dict(),
197
+ )
198
+ for d in documents
199
+ ]
200
+ asyncio.run(self._async_add_documents(self.config.collection_name, docs))
201
+
202
+ def delete_collection(self, collection_name: str) -> None:
203
+ asyncio.run(self._async_delete_index(collection_name))
204
+
205
+ def _to_int_or_uuid(self, id: str) -> int | str:
206
+ try:
207
+ return int(id)
208
+ except ValueError:
209
+ return id
210
+
211
+ async def _async_get_documents(self, where: str = "") -> "DocumentsInfo":
212
+ if self.config.collection_name is None:
213
+ raise ValueError("No collection name set, cannot retrieve docs")
214
+ filter = [] if where is None else where
215
+ async with self.client() as client:
216
+ index = client.index(self.config.collection_name)
217
+ documents = await index.get_documents(limit=10_000, filter=filter)
218
+ return documents
219
+
220
+ def get_all_documents(self, where: str = "") -> List[Document]:
221
+ if self.config.collection_name is None:
222
+ raise ValueError("No collection name set, cannot retrieve docs")
223
+ docs = asyncio.run(self._async_get_documents(where))
224
+ if docs is None:
225
+ return []
226
+ doc_results = docs.results
227
+ return [
228
+ Document(
229
+ content=d["content"],
230
+ metadata=DocMetaData(**d["metadata"]),
231
+ )
232
+ for d in doc_results
233
+ ]
234
+
235
+ async def _async_get_documents_by_ids(self, ids: List[str]) -> List[Dict[str, Any]]:
236
+ if self.config.collection_name is None:
237
+ raise ValueError("No collection name set, cannot retrieve docs")
238
+ async with self.client() as client:
239
+ index = client.index(self.config.collection_name)
240
+ documents = await asyncio.gather(*[index.get_document(id) for id in ids])
241
+ return documents
242
+
243
+ def get_documents_by_ids(self, ids: List[str]) -> List[Document]:
244
+ if self.config.collection_name is None:
245
+ raise ValueError("No collection name set, cannot retrieve docs")
246
+ docs = asyncio.run(self._async_get_documents_by_ids(ids))
247
+ return [
248
+ Document(
249
+ content=d["content"],
250
+ metadata=DocMetaData(**d["metadata"]),
251
+ )
252
+ for d in docs
253
+ ]
254
+
255
+ async def _async_search(
256
+ self,
257
+ query: str,
258
+ k: int = 20,
259
+ filter: str | list[str | list[str]] | None = None,
260
+ ) -> List[Dict[str, Any]]:
261
+ if self.config.collection_name is None:
262
+ raise ValueError("No collection name set, cannot search")
263
+ async with self.client() as client:
264
+ index = client.index(self.config.collection_name)
265
+ results = await index.search(
266
+ query,
267
+ limit=k,
268
+ show_ranking_score=True,
269
+ filter=filter,
270
+ )
271
+ return results.hits # type: ignore
272
+
273
+ def similar_texts_with_scores(
274
+ self,
275
+ text: str,
276
+ k: int = 20,
277
+ where: Optional[str] = None,
278
+ neighbors: int = 0, # ignored
279
+ ) -> List[Tuple[Document, float]]:
280
+ filter = [] if where is None else where
281
+ if self.config.collection_name is None:
282
+ raise ValueError("No collection name set, cannot search")
283
+ _docs = asyncio.run(self._async_search(text, k, filter)) # type: ignore
284
+ if len(_docs) == 0:
285
+ logger.warning(f"No matches found for {text}")
286
+ return []
287
+ scores = [h["_rankingScore"] for h in _docs]
288
+ if settings.debug:
289
+ logger.info(f"Found {len(_docs)} matches, max score: {max(scores)}")
290
+ docs = [
291
+ Document(
292
+ content=d["content"],
293
+ metadata=DocMetaData(**d["metadata"]),
294
+ )
295
+ for d in _docs
296
+ ]
297
+ doc_score_pairs = list(zip(docs, scores))
298
+ self.show_if_debug(doc_score_pairs)
299
+ return doc_score_pairs