crewplus 0.2.89__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.
@@ -0,0 +1,586 @@
1
+ from typing import List, Optional
2
+ import logging
3
+ import json
4
+ import asyncio
5
+
6
+ from pymilvus import DataType
7
+ from langchain_milvus import Milvus
8
+ from langchain_core.documents import Document
9
+ from ...utils.schema_document_updater import SchemaDocumentUpdater
10
+ from ...utils.schema_action import Action
11
+ from .milvus_schema_manager import MilvusSchemaManager
12
+
13
+ DEFAULT_SCHEMA = """
14
+ {
15
+ "node_types": {
16
+ "Document": {
17
+ "properties": {
18
+ "pk": {
19
+ "type": "INT64",
20
+ "is_primary": true,
21
+ "auto_id": true
22
+ },
23
+ "vector": {
24
+ "type": "FLOAT_VECTOR",
25
+ "dim": 1536
26
+ },
27
+ "text": {
28
+ "type": "VARCHAR",
29
+ "max_length": 65535,
30
+ "description": "The core text of the memory. This could be a user query, a documented fact, a procedural step, or a log of an event."
31
+ }
32
+ }
33
+ }
34
+ }
35
+ }
36
+ """
37
+
38
+ class SchemaMilvus(Milvus):
39
+ """
40
+ SchemaMilvus is a subclass of the Milvus class from langchain_milvus. This class is responsible for updating metadata of documents in a Milvus vector store.
41
+
42
+ Attributes:
43
+ embedding_function: Embedding function used by the Milvus vector store.
44
+ collection_name: Name of the collection in the Milvus vector store.
45
+ connection_args: Connection arguments for the Milvus vector store.
46
+ index_params: Index parameters for the Milvus vector store.
47
+ auto_id: Flag to specify if auto ID generation is enabled.
48
+ primary_field: The primary field of the collection.
49
+ vector_field: The vector field of the collection.
50
+ consistency_level: The consistency level for the Milvus vector store.
51
+ collection_schema: Schema JSON string associated with the Milvus existing collection name.
52
+ """
53
+ def __init__(
54
+ self,
55
+ embedding_function,
56
+ collection_name,
57
+ connection_args,
58
+ index_params=None,
59
+ auto_id=True,
60
+ primary_field="pk",
61
+ text_field: str = "text",
62
+ vector_field=["vector"],
63
+ consistency_level="Session",
64
+ logger: Optional[logging.Logger] = None
65
+ ):
66
+ """
67
+ Initializes the SchemaMilvus class with the provided parameters.
68
+
69
+ Args:
70
+ embedding_function: Embedding function used by the Milvus vector store.
71
+ collection_name: Name of the collection in the Milvus vector store.
72
+ connection_args: Connection arguments for the Milvus vector store.
73
+ index_params: Index parameters for the Milvus vector store.
74
+ auto_id: Flag to specify if auto ID generation is enabled.
75
+ primary_field: The primary field of the collection.
76
+ text_field: The text field of the collection.
77
+ vector_field: The vector field of the collection.
78
+ consistency_level: The consistency level for the Milvus vector store.
79
+ logger: Optional logger instance. If not provided, a default logger is created.
80
+ """
81
+ super().__init__(
82
+ embedding_function=embedding_function,
83
+ collection_name=collection_name,
84
+ connection_args=connection_args,
85
+ index_params=index_params,
86
+ auto_id=auto_id,
87
+ primary_field=primary_field,
88
+ text_field=text_field,
89
+ vector_field=vector_field,
90
+ consistency_level=consistency_level
91
+ )
92
+ self.logger = logger or logging.getLogger(__name__)
93
+ self.collection_schema = None
94
+ self.schema_manager = MilvusSchemaManager(client=self.client, async_client=self.aclient)
95
+
96
+ def set_schema(self, schema: str):
97
+ """
98
+ Sets the collection schema.
99
+
100
+ Args:
101
+ schema: The schema JSON string.
102
+ """
103
+ self.collection_schema = schema
104
+
105
+ def get_fields(self, collection_name: Optional[str] = None) -> Optional[List[str]]:
106
+ """
107
+ Retrieves and returns the fields from the collection schema.
108
+
109
+ Args:
110
+ collection_name: The name of the collection to describe. If None, use self.collection_name.
111
+
112
+ Returns:
113
+ List[str] | None: The list of field names from the collection schema (excluding vector and text fields), or None if collection_name is not provided or an error occurs.
114
+ """
115
+ if collection_name is None:
116
+ collection_name = self.collection_name
117
+ if collection_name is None:
118
+ return None
119
+
120
+ try:
121
+ schema = self.client.describe_collection(collection_name)
122
+ fields = [field["name"] for field in schema["fields"] if field["type"] != DataType.FLOAT_VECTOR ]
123
+ return fields
124
+ except Exception as e:
125
+ self.logger.warning(f"Failed to retrieve schema fields: {e}")
126
+ return None
127
+
128
+ def create_collection(self) -> bool:
129
+ """
130
+ Validates the schema and creates the collection using the MilvusSchemaManager.
131
+
132
+ Returns:
133
+ bool: True if the collection is successfully created, False otherwise.
134
+ """
135
+ if self.collection_schema is None:
136
+ self.logger.error("Collection schema is not set. Please set a schema using set_schema().")
137
+ return False
138
+
139
+ self.schema_manager.bind_client(self.client)
140
+ if not self.schema_manager.validate_schema(self.collection_schema):
141
+ self.logger.error("Failed to validate schema")
142
+ return False
143
+ try:
144
+ self.schema_manager.create_collection(self.collection_name, self.collection_schema)
145
+ self.logger.info(f"Collection {self.collection_name} created successfully")
146
+
147
+ return True
148
+ except Exception as e:
149
+ self.logger.error(f"Failed to create collection: {e}")
150
+ return False
151
+
152
+ async def acreate_collection(self) -> bool:
153
+ """
154
+ Asynchronously validates the schema and creates the collection using the MilvusSchemaManager.
155
+
156
+ Returns:
157
+ bool: True if the collection is successfully created, False otherwise.
158
+ """
159
+ if self.collection_schema is None:
160
+ self.logger.error("Collection schema is not set. Please set a schema using set_schema().")
161
+ return False
162
+
163
+ self.schema_manager.bind_async_client(self.aclient)
164
+ if not self.schema_manager.validate_schema(self.collection_schema):
165
+ self.logger.error("Failed to validate schema")
166
+ return False
167
+ try:
168
+ await self.schema_manager.acreate_collection(self.collection_name, self.collection_schema)
169
+ self.logger.info(f"Collection {self.collection_name} created successfully")
170
+ return True
171
+ except Exception as e:
172
+ self.logger.error(f"Failed to create collection asynchronously: {e}")
173
+ return False
174
+
175
+ def drop_collection(self, collection_name: Optional[str] = None) -> bool:
176
+ """
177
+ Drops the collection using the Milvus client.
178
+
179
+ Returns:
180
+ bool: True if the collection is successfully dropped, False otherwise.
181
+ """
182
+ if collection_name is None:
183
+ collection_name = self.collection_name
184
+
185
+ try:
186
+ self.client.drop_collection(collection_name)
187
+ self.logger.info(f"Collection {collection_name} dropped successfully")
188
+ return True
189
+ except Exception as e:
190
+ self.logger.error(f"Failed to drop collection {self.collection_name}: {e}")
191
+ return False
192
+
193
+ def _handle_upsert(self, doc: Document, metadata_dict: dict) -> Document:
194
+ """
195
+ Handles the UPSERT action for a single document by merging metadata.
196
+ """
197
+ existing_metadata = doc.metadata
198
+ for key, value in metadata_dict.items():
199
+ # Skip primary key and text fields to prevent modification.
200
+ if key in [self.primary_field, self.text_field]:
201
+ continue
202
+
203
+ if isinstance(value, dict):
204
+ # If it's a JSON object field (e.g., plant_metadata)
205
+ # Check if the existing value is a string, and if so, try to parse it as a dictionary
206
+ if key in existing_metadata and isinstance(existing_metadata[key], str):
207
+ try:
208
+ existing_metadata[key] = json.loads(existing_metadata[key])
209
+ except json.JSONDecodeError:
210
+ # If the parsing fails, it may not be a valid JSON string, treat it as a regular string
211
+ self.logger.warning(f"Field '{key}' could not be parsed as JSON. Overwriting as a new dict.")
212
+ existing_metadata[key] = {}
213
+
214
+ if key not in existing_metadata:
215
+ # If the field does not exist, add it
216
+ existing_metadata[key] = value
217
+ elif isinstance(existing_metadata[key], dict):
218
+ # If the field exists and is a dictionary, recursively update the sub-fields
219
+ for sub_key, sub_value in value.items():
220
+ if isinstance(sub_value, dict):
221
+ # If the sub-field is also a dictionary, recursively process it
222
+ if sub_key not in existing_metadata[key]:
223
+ existing_metadata[key][sub_key] = sub_value
224
+ else:
225
+ existing_metadata[key][sub_key].update(sub_value)
226
+ else:
227
+ # If the sub-field is a regular value, update it
228
+ existing_metadata[key][sub_key] = sub_value
229
+ else:
230
+ # If the field exists but is not a dictionary (e.g., a number or string), overwrite with the new dictionary
231
+ existing_metadata[key] = value
232
+ else:
233
+ # If it's a regular field, update the value
234
+ existing_metadata[key] = value
235
+
236
+ # Update the document's metadata
237
+ doc.metadata = existing_metadata
238
+
239
+ return doc
240
+
241
+ def _process_document_update(self, doc: Document, metadata_dict: dict, action: Action) -> Document:
242
+ """
243
+ Applies the specified update operation to a single document.
244
+
245
+ Args:
246
+ doc: The Document object to be updated.
247
+ metadata_dict: A dictionary containing the new data.
248
+ action: The type of operation to perform (UPSERT, DELETE, UPDATE, INSERT).
249
+
250
+ Returns:
251
+ The updated Document object.
252
+ """
253
+ pk_value = doc.metadata.get(self.primary_field)
254
+ text_value = doc.metadata.get(self.text_field)
255
+
256
+ if action == Action.UPSERT:
257
+ doc = self._handle_upsert(doc, metadata_dict)
258
+ elif action == Action.DELETE:
259
+ keys_to_delete = metadata_dict.keys()
260
+ doc = SchemaDocumentUpdater.delete_document_metadata(doc, list(keys_to_delete))
261
+ elif action == Action.UPDATE:
262
+ existing_metadata = doc.metadata
263
+ update_dict = {}
264
+ for key, value in metadata_dict.items():
265
+ if key in existing_metadata:
266
+ if isinstance(value, dict) and isinstance(existing_metadata.get(key), dict):
267
+ merged = existing_metadata[key].copy()
268
+ for sub_key, sub_value in value.items():
269
+ if sub_key in merged:
270
+ merged[sub_key] = sub_value
271
+ update_dict[key] = merged
272
+ else:
273
+ update_dict[key] = value
274
+ doc = SchemaDocumentUpdater.update_document_metadata(doc, update_dict)
275
+ elif action == Action.INSERT:
276
+ existing_metadata = doc.metadata
277
+ for key, value in metadata_dict.items():
278
+ if key in ['pk', 'text']:
279
+ continue
280
+
281
+ if isinstance(value, dict) and key in existing_metadata and isinstance(existing_metadata.get(key), dict):
282
+ existing_metadata[key] = {}
283
+ existing_metadata[key] = value
284
+ else:
285
+ existing_metadata[key] = value
286
+ doc.metadata = existing_metadata
287
+
288
+ if pk_value is not None:
289
+ doc.metadata[self.primary_field] = pk_value
290
+ if text_value is not None:
291
+ doc.metadata[self.text_field] = text_value
292
+
293
+ return doc
294
+
295
+ def update_documents_metadata(self, expr: str, metadata: str, action: Action = Action.UPSERT) -> List[Document]:
296
+ """
297
+ Updates the metadata of documents in the Milvus vector store based on the provided expression.
298
+ This method uses a direct client upsert to avoid re-embedding vectors.
299
+
300
+ Args:
301
+ expr: Expression to filter the target documents.
302
+ metadata: New metadata to update the documents with.
303
+ action: The action to perform on the document metadata.
304
+
305
+ Returns:
306
+ List of updated documents.
307
+ """
308
+ try:
309
+ metadata_dict = json.loads(metadata)
310
+ except json.JSONDecodeError:
311
+ raise ValueError("Invalid JSON string for metadata")
312
+
313
+ fields = self.get_fields()
314
+ if not fields:
315
+ fields = []
316
+
317
+ if isinstance(self._vector_field, list):
318
+ fields.extend(self._vector_field)
319
+ else:
320
+ fields.append(self._vector_field)
321
+
322
+ documents = self.search_by_metadata(expr, fields=fields, limit=5000)
323
+
324
+ updated_documents = [self._process_document_update(doc, metadata_dict, action) for doc in documents]
325
+
326
+ if updated_documents:
327
+ self.logger.debug(f"Upserting {len(updated_documents)} documents using direct client upsert.")
328
+ upsert_data = [doc.metadata for doc in updated_documents]
329
+ self.client.upsert(
330
+ collection_name=self.collection_name,
331
+ data=upsert_data
332
+ )
333
+
334
+ return updated_documents
335
+
336
+ async def aupdate_documents_metadata(self, expr: str, metadata: str, action: Action = Action.UPSERT) -> List[Document]:
337
+ """
338
+ Asynchronously updates the metadata of documents in the Milvus vector store.
339
+ This method uses a direct client upsert to avoid re-embedding vectors.
340
+
341
+ Args:
342
+ expr: Expression to filter the target documents.
343
+ metadata: New metadata to update the documents with.
344
+ action: The action to perform on the document metadata.
345
+
346
+ Returns:
347
+ List of updated documents.
348
+ """
349
+ try:
350
+ metadata_dict = json.loads(metadata)
351
+ except json.JSONDecodeError:
352
+ raise ValueError("Invalid JSON string for metadata")
353
+
354
+ fields = self.get_fields()
355
+ if not fields:
356
+ fields = []
357
+
358
+ if isinstance(self._vector_field, list):
359
+ fields.extend(self._vector_field)
360
+ else:
361
+ fields.append(self._vector_field)
362
+
363
+ documents = self.search_by_metadata(expr, fields=fields, limit=5000)
364
+
365
+ updated_documents = [self._process_document_update(doc, metadata_dict, action) for doc in documents]
366
+
367
+ if updated_documents:
368
+ self.logger.debug(f"Upserting {len(updated_documents)} documents using direct client upsert.")
369
+ upsert_data = [doc.metadata for doc in updated_documents]
370
+
371
+ await asyncio.to_thread(
372
+ self.client.upsert,
373
+ collection_name=self.collection_name,
374
+ data=upsert_data
375
+ )
376
+
377
+ return updated_documents
378
+
379
+ def update_documents_metadata_by_iterator(self, expr: str, metadata: str, action:Action=Action.UPSERT) -> List[Document]:
380
+ """
381
+ 【官方推荐版】
382
+ 使用 pymilvus.Collection.query_iterator 官方推荐的迭代方式更新元数据。
383
+ 本方法的业务逻辑(UPSERT/DELETE等)与 update_documents_metadata 方法完全一致,
384
+ 仅数据获取方式遵循官方标准迭代器模式。
385
+ """
386
+ try:
387
+ metadata_dict = json.loads(metadata)
388
+ except json.JSONDecodeError:
389
+ raise ValueError("Invalid JSON string for metadata")
390
+
391
+ fields = self.get_fields() or []
392
+ # 确保主键和文本字段在输出字段中
393
+ if 'pk' not in fields:
394
+ fields.append('pk')
395
+ text_field = getattr(self, "_text_field", "text")
396
+ if text_field not in fields:
397
+ fields.append(text_field)
398
+
399
+ # 【关键修正】: 确保在查询时也获取向量字段。
400
+ # self.client.upsert 操作要求提供所有非 nullable 字段,包括 vector。
401
+ # 因此,我们必须在迭代查询时获取它,以便在更新时能够一并传回。
402
+ vector_fields_to_add = self._vector_field if isinstance(self._vector_field, list) else [self._vector_field]
403
+ for vf in vector_fields_to_add:
404
+ if vf not in fields:
405
+ fields.append(vf)
406
+
407
+ total_updated_documents = []
408
+ batch_size = 1000 # 您可以根据需要调整批次大小
409
+
410
+ self.logger.info(f"Starting metadata update using 'collection.query_iterator' with batch size {batch_size}.")
411
+
412
+ # # 1. 【关键保险】: 在查询前,显式地确保集合已被加载。
413
+ # logger.info(f"Ensuring collection '{self.collection_name}' is loaded before querying.")
414
+ # self.col.load()
415
+
416
+ # 2. 【官方用法】: 创建官方推荐的迭代器
417
+ iterator = self.col.query_iterator(
418
+ batch_size=batch_size,
419
+ expr=expr,
420
+ output_fields=fields
421
+ )
422
+
423
+ batch_i = 0
424
+ try:
425
+ while True:
426
+ # 3. 【官方用法】: 获取下一批次
427
+ batch_results = iterator.next()
428
+ if not batch_results:
429
+ break # 迭代完成,正常退出
430
+
431
+ batch_i += 1
432
+ self.logger.info(f"Processing batch {batch_i} of {len(batch_results)} documents.")
433
+
434
+ # 4. 将 Milvus 返回的 dict 列表转换为 Langchain Document 对象
435
+ documents = [
436
+ Document(page_content=result.get(text_field, ""), metadata=result)
437
+ for result in batch_results
438
+ ]
439
+
440
+ # 5. 【核心业务逻辑】: 使用公共方法处理批次中的每个文档
441
+ updated_documents_in_batch = [self._process_document_update(doc, metadata_dict, action) for doc in documents]
442
+
443
+ # 6. 【Upsert逻辑】:
444
+ if updated_documents_in_batch:
445
+ self.logger.debug(f"Upserting batch of {len(updated_documents_in_batch)} documents using direct client upsert.")
446
+ # 从更新后的 Document 对象中提取元数据字典列表
447
+ upsert_data = [doc.metadata for doc in updated_documents_in_batch]
448
+ self.client.upsert(
449
+ collection_name=self.collection_name,
450
+ data=upsert_data
451
+ )
452
+ total_updated_documents.extend(updated_documents_in_batch)
453
+
454
+ finally:
455
+ # 7. 【官方用法】: 确保迭代器被关闭
456
+ self.logger.info("Closing iterator.")
457
+ iterator.close()
458
+
459
+ self.logger.info(f"Iterator processing complete. Total batches processed: {batch_i}.")
460
+ return total_updated_documents
461
+
462
+
463
+ def update_documents_metadata_folder_path(self, old_expr: str, metadata: str, action:Action=Action.UPSERT) -> List[Document]:
464
+ """
465
+ 专门用于更新 version_metadata.folder_path 字段的方法。
466
+
467
+ 它执行一个“目录移动”逻辑:
468
+ 1. 使用 old_expr 找出所有路径匹配的文档。
469
+ 2. 从 metadata 中获取新的基础路径。
470
+ 3. 将文档中 folder_path 的 old_expr 前缀替换为新的基础路径,并保留后续的子路径。
471
+ """
472
+ # 1. 根据 old_expr 构造一个 "starts with" 查询
473
+ # Milvus JSON 'like' 操作符需要转义内部的双引号
474
+ # 但由于我们这里是变量,直接用 f-string 插入是安全的
475
+ expr = f"version_metadata[\"folder_path\"] like \"{old_expr}%\""
476
+
477
+ try:
478
+ metadata_dict = json.loads(metadata)
479
+ except json.JSONDecodeError:
480
+ raise ValueError("Invalid JSON string for metadata")
481
+
482
+ fields = self.get_fields() or []
483
+ # 确保关键字段都被查询出来
484
+ required_fields = ['pk', getattr(self, "_text_field", "text")]
485
+ vector_fields = self._vector_field if isinstance(self._vector_field, list) else [self._vector_field]
486
+ required_fields.extend(vector_fields)
487
+
488
+ for f in required_fields:
489
+ if f not in fields:
490
+ fields.append(f)
491
+
492
+ total_updated_documents = []
493
+ batch_size = 1000
494
+
495
+ self.logger.info(f"Starting folder path update using 'collection.query_iterator' with expr: {expr}")
496
+
497
+ # self.col.load() # 确保集合已加载
498
+
499
+ iterator = self.col.query_iterator(
500
+ batch_size=batch_size,
501
+ expr=expr,
502
+ output_fields=fields
503
+ )
504
+
505
+ batch_i = 0
506
+ try:
507
+ while True:
508
+ batch_results = iterator.next()
509
+ if not batch_results:
510
+ break
511
+
512
+ batch_i += 1
513
+ self.logger.info(f"Processing batch {batch_i} of {len(batch_results)} documents for folder path update.")
514
+
515
+ documents = [
516
+ Document(page_content=result.get(getattr(self, "_text_field", "text"), ""), metadata=result)
517
+ for result in batch_results
518
+ ]
519
+
520
+ updated_documents_in_batch = []
521
+ for doc in documents:
522
+ # 沿用标准的 UPSERT 逻辑,但在处理 folder_path 时应用特殊规则
523
+ if action == Action.UPSERT:
524
+ existing_metadata = doc.metadata
525
+ for key, value in metadata_dict.items():
526
+ # ... (此处省略了标准的深层合并逻辑,与您已有的 update_documents_metadata 方法一致)
527
+ # 仅展示与 folder_path 相关的特殊处理部分
528
+ if isinstance(value, dict):
529
+ # ... (处理从数据库读出的可能是字符串的JSON)
530
+ if key in existing_metadata and isinstance(existing_metadata[key], str):
531
+ try:
532
+ existing_metadata[key] = json.loads(existing_metadata[key])
533
+ except json.JSONDecodeError:
534
+ existing_metadata[key] = {}
535
+
536
+ if key not in existing_metadata or not isinstance(existing_metadata[key], dict):
537
+ existing_metadata[key] = value
538
+ else:
539
+ # 递归更新,在这里注入我们的特殊逻辑
540
+ for sub_key, sub_value in value.items():
541
+ # 【核心特殊逻辑】
542
+ if key == 'version_metadata' and sub_key == 'folder_path':
543
+ new_folder_path_base = sub_value
544
+ current_folder_path = existing_metadata.get(key, {}).get(sub_key)
545
+
546
+ if current_folder_path and current_folder_path.startswith(old_expr):
547
+ # 移除旧前缀,保留子路径
548
+ sub_path = current_folder_path[len(old_expr):]
549
+ # 拼接新路径(确保斜杠正确)
550
+ new_full_path = f"{new_folder_path_base.rstrip('/')}/{sub_path.lstrip('/')}"
551
+ existing_metadata[key][sub_key] = new_full_path
552
+ self.logger.debug(f"Rewrote folder path from '{current_folder_path}' to '{new_full_path}'")
553
+ else:
554
+ # 如果不匹配,则按普通逻辑直接覆盖
555
+ existing_metadata[key][sub_key] = new_folder_path_base
556
+
557
+ # 其他所有字段按原逻辑递归更新
558
+ elif isinstance(sub_value, dict):
559
+ if sub_key not in existing_metadata[key]:
560
+ existing_metadata[key][sub_key] = sub_value
561
+ else:
562
+ existing_metadata[key][sub_key].update(sub_value)
563
+ else:
564
+ existing_metadata[key][sub_key] = sub_value
565
+ else:
566
+ existing_metadata[key] = value
567
+ doc.metadata = existing_metadata
568
+
569
+ # (此处可以添加对 DELETE, UPDATE, INSERT 的处理,如果需要的话)
570
+
571
+ updated_documents_in_batch.append(doc)
572
+
573
+ if updated_documents_in_batch:
574
+ self.logger.debug(f"Upserting batch of {len(updated_documents_in_batch)} documents with updated folder paths.")
575
+ upsert_data = [d.metadata for d in updated_documents_in_batch]
576
+ self.client.upsert(
577
+ collection_name=self.collection_name,
578
+ data=upsert_data
579
+ )
580
+ total_updated_documents.extend(updated_documents_in_batch)
581
+ finally:
582
+ self.logger.info("Closing folder path update iterator.")
583
+ iterator.close()
584
+
585
+ self.logger.info(f"Folder path update complete. Total batches processed: {batch_i}.")
586
+ return total_updated_documents