Tools
lazyllm.tools.agent.code_interpreter
code_interpreter(code, language='python')
Interpret the code and return the code interpreter result (include stdout, stderr, returncode, etc.).
Parameters:
-
code(str) –The code to interpret.
-
language(str, default:'python') –The language of the code. Default is 'python'.
Source code in lazyllm/tools/agent/code_interpreter.py
lazyllm.tools.sandbox.LazyLLMSandboxBase
Bases: ModuleBase
Base class for sandbox execution with a unified call interface and language validation.
Parameters:
-
output_dir_path(str | None, default:None) –output directory for generated files, default is cwd.
-
return_trace(bool, default:False) –whether to return intermediate execution info (controlled by ModuleBase).
Notes
Subclasses must implement _is_available and _execute.
Source code in lazyllm/tools/sandbox/sandbox_base.py
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 | |
forward(code, language='python', input_files=None, output_files=None)
Unified execution entry that validates language and delegates to the implementation.
Parameters:
-
code(str) –code to execute.
-
language(str, default:'python') –code language, default 'python'.
-
input_files(list[str] | None, default:None) –optional list of input file paths.
-
output_files(list[str] | None, default:None) –optional list of output files to fetch.
Returns:
Result produced by the sandbox implementation (usually a dict or an error message string).
Source code in lazyllm/tools/sandbox/sandbox_base.py
lazyllm.tools.sandbox.DummySandbox
Bases: LazyLLMSandboxBase
Local sandbox implementation (python-only) for executing code in a restricted environment.
Features: - Basic safety checks with AST + SecurityVisitor. - Runs code in a temp directory and cleans up afterwards. - Returns a dict with stdout/stderr/returncode.
Parameters:
-
timeout(int, default:30) –timeout in seconds, default 30.
-
project_dir(str | None, default:None) –if provided, copies .py files into sandbox for imports.
-
return_trace(bool, default:False) –whether to return intermediate execution info.
Examples:
>>> from lazyllm.tools.sandbox import DummySandbox
>>> sandbox = DummySandbox(timeout=10)
>>> result = sandbox(code="print(1 + 1)")
>>> print(result['stdout'].strip())
2
Source code in lazyllm/tools/sandbox/dummy_sandbox.py
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 | |
execute_script(source_dir, rel_path, args=None, cwd='.', env=None)
Execute a materialized Skill script in a temporary working directory.
The method copies the complete source_dir tree into a temporary directory, verifies that the script path and working
directory remain inside it, and selects an interpreter by file extension. .py files use the current Python interpreter,
.sh and .bash files use Bash, and other extensions use sh. The temporary directory is removed after execution.
Parameters:
-
source_dir(str) –root directory of the materialized Skill package.
-
rel_path(str) –script path relative to
source_dir. -
args(list[str] | None, default:None) –arguments passed to the script.
-
cwd(str, default:'.') –working directory relative to
source_dir, default.. -
env(dict[str, str] | None, default:None) –extra environment variables merged into the subprocess environment; does not mutate the parent process
os.environ. DefaultNone.
Returns:
dict: contains `status`, `stdout`, `stderr`, `exit_code`, and `cwd`. A missing script returns `status='missing'`;
a non-zero exit code returns `status='failed'`.
Notes
DummySandbox provides only a temporary-directory and subprocess boundary, not strong security isolation. It does not
prevent scripts from reading host files, accessing the network, or inheriting the current process environment with
env overlaid. Do not use it to execute untrusted code.
Examples:
>>> import tempfile
>>> from pathlib import Path
>>> from lazyllm.tools.sandbox import DummySandbox
>>> with tempfile.TemporaryDirectory() as root:
... script = Path(root) / "scripts" / "check.py"
... script.parent.mkdir()
... _ = script.write_text("print('ok')\n", encoding="utf-8")
... result = DummySandbox(timeout=10).execute_script(
... source_dir=root,
... rel_path="scripts/check.py",
... args=[],
... )
... print(result['stdout'].strip())
ok
Source code in lazyllm/tools/sandbox/dummy_sandbox.py
lazyllm.tools.sandbox.SandboxFusion
Bases: LazyLLMSandboxBase
Remote sandbox implementation that executes code via HTTP API.
Supports python / bash. Configurable compile/run timeouts and memory limits. Can upload project files and fetch output files.
Parameters:
-
base_url(str, default:config['sandbox_fusion_base_url']) –remote sandbox base URL, defaults to config['sandbox_fusion_base_url'].
-
compile_timeout(int, default:10) –compile timeout in seconds, default 10.
-
run_timeout(int, default:10) –run timeout in seconds, default 10.
-
memory_limit_mb(int, default:-1) –memory limit in MB, -1 means no limit.
-
project_dir(str | None, default:None) –if provided, uploads .py files from the project directory.
Notes
Set LAZYLLM_SANDBOX_FUSION_BASE_URL or pass base_url explicitly.
Examples:
>>> from lazyllm import config
>>> from lazyllm.tools.sandbox import SandboxFusion
>>> config['sandbox_fusion_base_url'] = "http://localhost:8000"
>>> sandbox = SandboxFusion(run_timeout=5)
>>> result = sandbox(code="print('ok')")
>>> print(result['stdout'].strip())
ok
Source code in lazyllm/tools/sandbox/sandbox_fusion.py
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 | |
lazyllm.tools.IntentClassifier
Bases: ModuleBase
Intent classification module that classifies input text into a given intent list. Supports automatic selection of Chinese or English prompt templates, and allows enhancement through examples, prompt text, constraints, and attention notes.
Parameters:
-
llm–The large language model instance used for intent classification.
-
intent_list(list, default:None) –Optional, list of intent categories, e.g., ["chat", "weather", "QA"].
-
prompt(str, default:'') –Optional, custom prompt inserted into the system prompt template.
-
constrain(str, default:'') –Optional, classification constraint description.
-
attention(str, default:'') –Optional, attention notes for classification.
-
examples(list[list[str, str]], default:None) –Optional, classification examples, each element is [input text, label].
-
return_trace(bool, default:False) –Whether to return execution trace. Default is False.
Examples:
>>> import lazyllm
>>> from lazyllm.tools import IntentClassifier
>>> classifier_llm = lazyllm.OnlineChatModule(source="openai")
>>> chatflow_intent_list = ["Chat", "Financial Knowledge Q&A", "Employee Information Query", "Weather Query"]
>>> classifier = IntentClassifier(classifier_llm, intent_list=chatflow_intent_list)
>>> classifier.start()
>>> print(classifier('What is the weather today'))
Weather Query
>>>
>>> with IntentClassifier(classifier_llm) as ic:
>>> ic.case['Weather Query', lambda x: '38.5°C']
>>> ic.case['Chat', lambda x: 'permission denied']
>>> ic.case['Financial Knowledge Q&A', lambda x: 'Calling Financial RAG']
>>> ic.case['Employee Information Query', lambda x: 'Beijing']
...
>>> ic.start()
>>> print(ic('What is the weather today'))
38.5°C
Source code in lazyllm/tools/classifier/intent_classifier.py
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 | |
intent_promt_hook(input=None, history=[], tools=None, label=None)
Pre-processing hook for intent classification. Packages the input text and intent list into JSON and generates a string of conversation history.
Parameters:
-
input(str | List | Dict | None, default:None) –The input text, only string type is supported.
-
history(List, default:[]) –Conversation history, default empty list.
-
tools(List[Dict] | None, default:None) –Optional tool information.
-
label(str | None, default:None) –Optional label.
Returns:
- tuple: input data dict, history list, tools, label
Source code in lazyllm/tools/classifier/intent_classifier.py
post_process_result(input)
Post-processing of intent classification result. Returns the result directly if it is in the intent list, otherwise returns the first element of the intent list.
Parameters:
-
input(str) –Output result from the classification model.
Returns:
- str: The final classification label.
Source code in lazyllm/tools/classifier/intent_classifier.py
lazyllm.tools.rag.document.Document
Bases: ModuleBase, BuiltinGroups
Initialize a document management module with optional embedding, storage, and user interface.
The Document module provides a unified interface for managing document datasets, including support for local files, cloud-based files, or temporary document files. It can optionally run with a document manager service or a web UI, and supports multiple embedding models and custom storage backends.
Parameters:
-
dataset_path(Optional[str], default:None) –Path to the dataset directory. If not found, the system will attempt to locate it in
lazyllm.config["data_path"]. -
embed(Optional[Union[Callable, Dict[str, Callable]]], default:None) –Embedding function or mapping of embedding functions. When a dictionary is provided, keys are embedding names and values are embedding models.
-
create_ui(bool, default:False) –Whether to create the document-management UI. It requires an available
DocServerand can be combined withmanager=Trueormanager=DocServer(...). -
manager(Union[bool, str, DocServer, DocumentProcessor], default:False) –Document manager mode.
Truelaunches a localDocServertogether with a local parsing service.DocServer(...)connects an existing document-management service.DocumentProcessor(...)connects a parsing service only and requires a non-mapstore_conf.'ui'is accepted as a compatibility alias formanager=True, create_ui=True. -
server(Union[bool, int], default:False) –Whether to run a server interface for knowledge bases.
Trueenables a default server, an integer specifies a custom port, andFalsedisables it. Defaults toFalse. -
name(Optional[str], default:None) –Name identifier for this document collection. Defaults to the system default name.
-
launcher(Optional[LazyLLMLaunchersBase], default:None) –Launcher instance for managing server processes. Defaults to a remote asynchronous launcher.
-
doc_files(Optional[List[str]], default:None) –Temporary document files. When used,
dataset_pathmust beNone. Only MapStore is supported in this mode. -
doc_fields(Optional[Dict[str, GlobalMetadataDesc]], default:None) –Metadata field configuration for storing and retrieving document attributes.
-
store_conf(Optional[Dict], default:None) –Storage configuration. Defaults to in-memory MapStore.
-
display_name(Optional[str], default:'') –Human-readable display name for this document module. Defaults to the collection name.
-
description(Optional[str], default:'algorithm description') –Description of the document collection. Defaults to
"algorithm description". -
schema_extractor(Optional[Union[LLMBase, SchemaExtractor]], default:None) –Optional schema extractor used for metadata schema analysis and registration.
-
enable_path_monitoring(Optional[bool], default:None) –Whether to watch the local dataset path for file additions and removals. Defaults to enabled only for local documents without
DocServer/DocumentProcessormanager mode.
Examples:
>>> import lazyllm
>>> from lazyllm.tools import Document
>>> m = lazyllm.OnlineEmbeddingModule(source="glm")
>>> documents = Document(dataset_path='your_doc_path', embed=m, manager=False) # or documents = Document(dataset_path='your_doc_path', embed={"key": m}, manager=False)
>>> m1 = lazyllm.TrainableModule("bge-large-zh-v1.5").start()
>>> document1 = Document(dataset_path='your_doc_path', embed={"online": m, "local": m1}, manager=False)
>>> store_conf = {
>>> "segment_store": {
>>> "type": "map",
>>> "kwargs": {
>>> "uri": "/tmp/tmp_segments.db",
>>> },
>>> },
>>> "vector_store": {
>>> "type": "milvus",
>>> "kwargs": {
>>> "uri": "/tmp/tmp_milvus.db",
>>> "index_kwargs": {
>>> "index_type": "FLAT",
>>> "metric_type": "COSINE",
>>> },
>>> },
>>> },
>>> }
>>> doc_fields = {
>>> 'author': DocField(data_type=DataType.VARCHAR, max_size=128, default_value=' '),
>>> 'public_year': DocField(data_type=DataType.INT32),
>>> }
>>> document2 = Document(dataset_path='your_doc_path', embed={"online": m, "local": m1}, store_conf=store_conf, doc_fields=doc_fields)
Source code in lazyllm/tools/rag/document.py
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 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 | |
activate_group(group_name, embed_keys=None, enable_embed=True)
Activate the specified knowledge base group, optionally enabling specific embedding keys.
After activation, the document module will perform retrieval and storage operations within the given group. If no embedding keys are provided, all available embeddings will be enabled by default.
Parameters:
-
group_name(str) –Name of the knowledge base group to activate.
-
embed_keys(Optional[Union[str, List[str]]], default:None) –Embedding keys to enable, either as a string or a list of strings. Defaults to an empty list, enabling all embeddings.
Source code in lazyllm/tools/rag/document.py
activate_groups(groups, **kwargs)
Activate multiple knowledge base groups in batch.
This method iteratively calls activate_group to activate all the provided groups.
Parameters:
-
groups(Union[str, List[str]]) –A single group name or a list of group names to activate.
Source code in lazyllm/tools/rag/document.py
add_reader(pattern, func=None)
Used to specify the file reader for an instance. The scope of action is visible only to the registered Document object. The registered file reader must be a Callable object. It can only be registered by calling a function. The priority of the file reader registered by the instance is higher than that of the file reader registered by the class, and the priority of the file reader registered by the instance and class is higher than the system default file reader. That is, the order of priority is: instance file reader > class file reader > system default file reader.
Parameters:
-
pattern(str) –Matching rules applied by the file reader.
-
func(Callable, default:None) –File reader, must be a Callable object.
Examples:
>>> from lazyllm.tools.rag import Document, DocNode
>>> from lazyllm.tools.rag.readers import ReaderBase
>>> class YmlReader(ReaderBase):
... def _load_data(self, file, fs=None):
... try:
... import yaml
... except ImportError:
... raise ImportError("yaml is required to read YAML file: `pip install pyyaml`")
... with open(file, 'r') as f:
... data = yaml.safe_load(f)
... print("Call the class YmlReader.")
... return [DocNode(text=data)]
...
>>> def processYml(file):
... with open(file, 'r') as f:
... data = f.read()
... print("Call the function processYml.")
... return [DocNode(text=data)]
...
>>> doc1 = Document(dataset_path="your_files_path")
>>> doc2 = Document(dataset_path="your_files_path")
>>> doc1.add_reader("**/*.yml", YmlReader)
>>> print(doc1._impl._local_file_reader)
{'**/*.yml': <class '__main__.YmlReader'>}
>>> print(doc2._impl._local_file_reader)
{}
>>> files = ["your_yml_files"]
>>> Document.register_global_reader("**/*.yml", processYml)
>>> doc1._impl._reader.load_data(input_files=files)
Call the class YmlReader.
>>> doc2._impl._reader.load_data(input_files=files)
Call the function processYml.
Source code in lazyllm/tools/rag/document.py
analyze_schema_by_llm(kb_id=None, doc_ids=None)
Use an LLM to auto-infer a field schema for a specific knowledge base or document set in the Document manager, returning a generated Pydantic model. Supports narrowing the sample by kb_id and a list of doc_ids.
Parameters:
-
kb_id(Optional[str], default:None) –Target knowledge base id.
-
doc_ids(Optional[List[str]], default:None) –List of target document ids.
Source code in lazyllm/tools/rag/document.py
clear_cache(group_names=None)
Clear cache.
This method clears the cache of the document module. A list of group names can be specified to clear cache for specific groups. If no group names are provided, all group caches will be cleared.
Parameters:
-
group_names(Optional[List[str]], default:None) –List of group names whose cache should be cleared. Defaults to
None, meaning clear all caches.
Source code in lazyllm/tools/rag/document.py
connect_sql_manager(sql_manager, schma=None, force_refresh=True)
.. deprecated:: Use SchemaExtractor directly.
This method is removed. Use SchemaExtractor with register_schema_set instead.
Source code in lazyllm/tools/rag/document.py
create_kb_group(name, doc_fields=None, store_conf=None)
Create a new knowledge base group (KB Group) and return a document object bound to that group.
Knowledge base groups are used to partition different document collections within the same document module. Each group can have independent field definitions and storage configurations.
Parameters:
-
name(str) –Name of the knowledge base group.
-
doc_fields(Optional[Dict[str, GlobalMetadataDesc]], default:None) –Document field definitions, specifying field names, types, and descriptions.
-
store_conf(Optional[Dict], default:None) –Storage configuration, defining the backend and its parameters.
Returns:
- Document: A copy of the document object bound to the newly created knowledge base group.
Source code in lazyllm/tools/rag/document.py
create_node_group(name=None, *, transform, parent=LAZY_ROOT_NAME, trans_node=None, num_workers=0, display_name=None, ref=None, group_type=NodeGroupType.CHUNK, lazy_mode=None, **kwargs)
Generate a node group produced by the specified rule.
Parameters:
-
name(str, default:None) –The name of the node group.
-
transform(Callable) –The transformation rule that converts a node into a node group. The function prototype is
(DocNode, group_name, **kwargs) -> List[DocNode]. Currently built-in options include [SentenceSplitter][lazyllm.tools.SentenceSplitter], and users can define their own transformation rules. -
trans_node(bool, default:None) –Determines whether the input and output of transform are
DocNodeorstr, default is None. Can only be set to true whentransformisCallable. -
num_workers(int, default:0) –number of new threads used for transform. default: 0
-
parent(str, default:LAZY_ROOT_NAME) –The node that needs further transformation. The series of new nodes obtained after transformation will be child nodes of this parent node. If not specified, the transformation starts from the root node.
-
ref(str, default:None) –The name of another node group to reference. The referenced node group must be a descendant of the parent. During transformation, nodes from the referenced node group are passed to the transform function as the
refparameter (if the transform function supports it). -
kwargs–Parameters related to the specific implementation.
Examples:
>>> import lazyllm
>>> from lazyllm.tools import Document, SentenceSplitter
>>> m = lazyllm.OnlineEmbeddingModule(source="glm")
>>> documents = Document(dataset_path='your_doc_path', embed=m, manager=False)
>>> documents.create_node_group(name="sentences", transform=SentenceSplitter, chunk_size=1024, chunk_overlap=100)
>>> # Example with ref parameter: create a node group that references another group
>>> documents.create_node_group(name="fine_chunks", parent="sentences",
... transform=SentenceSplitter, chunk_size=128, chunk_overlap=12)
>>> def transform_with_ref(text, ref):
... # ref contains nodes from the referenced group
... return "
".join(ref)
>>> documents.create_node_group(name="summary_chunks", parent="sentences",
... transform=transform_with_ref, ref="fine_chunks")
Source code in lazyllm/tools/rag/document.py
drop_algorithm()
Delete the algorithm information registered in the document parsing service for the current document collection.
extract_db_schema(llm=None, print_schema=False)
Extract the database schema from the dataset using the SchemaExtractor's LLM and register it.
Parameters:
-
llm(Union[OnlineChatModule, TrainableModule], default:None) –LLM for schema analysis; defaults to the SchemaExtractor's built-in LLM.
-
print_schema(bool, default:False) –Whether to log the extracted schema. Defaults to
False.
Source code in lazyllm/tools/rag/document.py
find(target)
Find the target.
This method returns a callable object that performs a deferred lookup operation. It invokes the underlying implementation to retrieve the specified target.
Parameters:
-
target–The target to be found.
Returns:
- Callable: Callable object for performing the target lookup.
Source code in lazyllm/tools/rag/document.py
find_children(target)
Find the children nodes of the target.
This method returns a callable object that performs a deferred children lookup operation. It invokes the underlying implementation to retrieve all children nodes of the specified target.
Parameters:
-
target–The target for which to find the children.
Returns:
- Callable: Callable object for performing the children lookup.
Examples:
>>> import lazyllm
>>> from lazyllm.tools import Document, SentenceSplitter
>>> m = lazyllm.OnlineEmbeddingModule(source="glm")
>>> documents = Document(dataset_path='your_doc_path', embed=m, manager=False)
>>> documents.create_node_group(name="parent", transform=SentenceSplitter, chunk_size=1024, chunk_overlap=100)
>>> documents.create_node_group(name="children", transform=SentenceSplitter, parent="parent", chunk_size=1024, chunk_overlap=100)
>>> documents.find_children('parent')
Source code in lazyllm/tools/rag/document.py
find_parent(target)
Find the parent node of the target.
This method returns a callable object that performs a deferred parent lookup operation. It invokes the underlying implementation to retrieve the parent node of the specified target.
Parameters:
-
target–The target for which to find the parent.
Returns:
- Callable: Callable object for performing the parent lookup.
Examples:
>>> import lazyllm
>>> from lazyllm.tools import Document, SentenceSplitter
>>> m = lazyllm.OnlineEmbeddingModule(source="glm")
>>> documents = Document(dataset_path='your_doc_path', embed=m, manager=False)
>>> documents.create_node_group(name="parent", transform=SentenceSplitter, chunk_size=1024, chunk_overlap=100)
>>> documents.create_node_group(name="children", transform=SentenceSplitter, parent="parent", chunk_size=1024, chunk_overlap=100)
>>> documents.find_parent('children')
Source code in lazyllm/tools/rag/document.py
get_embed()
Get the embedding placeholder object.
This method returns a placeholder for the embedding layer, allowing deferred binding of the actual embedding implementation. The caller can use this object for embedding-related configuration or extension.
Returns:
- EmbedPlaceholder: Embedding placeholder object.
Source code in lazyllm/tools/rag/document.py
get_nodes(uids=None, doc_ids=None, group=None, kb_id=None, numbers=None, limit=None, offset=0, return_total=False, sort_by_number=False)
Get nodes by criteria.
Parameters:
-
uids(Optional[List[str]], default:None) –List of node uids to fetch.
-
doc_ids(Optional[Set], default:None) –Set of document ids to filter by.
-
group(Optional[str], default:None) –Node group name.
-
kb_id(Optional[str], default:None) –Knowledge base id.
-
numbers(Optional[Set], default:None) –Set of node numbers.
Returns:
- List[DocNode]: Matched nodes.
Examples:
>>> import lazyllm
>>> from lazyllm.tools import Document
>>> doc = Document()
>>> nodes = doc.get_nodes(doc_ids={'doc_1'}, group='CoarseChunk', kb_id='kb_1', numbers={1, 2})
Source code in lazyllm/tools/rag/document.py
get_sql_manager()
Get the NL2SQL manager instance from the SchemaExtractor bound to this document module. Can be used to construct a SqlCall.
Returns:\n - SqlManager: The SQL manager instance.
Source code in lazyllm/tools/rag/document.py
get_store()
Get the storage placeholder object.
This method returns a placeholder for the storage layer, allowing deferred binding of the actual storage implementation. The caller can use this object for storage-related configuration or extension.
Returns:
- StorePlaceholder: Storage placeholder object.
Source code in lazyllm/tools/rag/document.py
get_window_nodes(node, span=(-5, 5), merge=False)
Get window nodes around a target node within the same document.
Parameters:
-
node(DocNode) –Target node.
-
span(tuple[int, int], default:(-5, 5)) –Window range based on relative offsets of node.number.
-
merge(bool, default:False) –Whether to merge window nodes into a single node.
Returns:
- Union[List[DocNode], DocNode]: Window nodes list or a merged node.
Examples:
>>> import lazyllm
>>> from lazyllm.tools import Document
>>> doc = Document()
>>> node = doc.get_nodes(doc_ids={'doc_1'}, group='CoarseChunk', kb_id='kb_1', numbers={10})[0]
>>> window_nodes = doc.get_window_nodes(node, span=(-2, 2), merge=False)
Source code in lazyllm/tools/rag/document.py
keyword_search(group, keyword, doc_id='', kb_id=None, phrase=True, sort_by='score', size=10, file_name=None)
Perform exact keyword matching within a specific document, complementing the collection-wide retrieval of :meth:find.
Locate the target document via doc_id or file_name (mutually exclusive; file_name takes precedence). Supports exact phrase or word-level matching, with configurable sort order and result count.
Parameters:
-
group(str) –Node group name (e.g.,
"block"or"line"). -
keyword(str) –Keyword or phrase to match.
-
doc_id(str, default:'') –Target document ID, defaults to empty string. Mutually exclusive with
file_name; if both are given,file_nametakes priority. -
kb_id(Optional[str], default:None) –Optional knowledge-base filter.
-
phrase(bool, default:True) –True for exact substring match; False requires every word to appear.
-
sort_by(str, default:'score') –"score"sorts by relevance,"number"sorts by document order. -
size(int, default:10) –Maximum number of hits.
-
file_name(Optional[str], default:None) –Filter by file name. Mutually exclusive with
doc_id; when set,doc_idis ignored.
Returns:
-
–
List[dict]: Matched segment list.
Source code in lazyllm/tools/rag/document.py
list_all_files_in_directory(dataset_path, skip_hidden_path=True, recursive=True)
staticmethod
List all files in a given directory path.
This method recursively or non-recursively traverses a directory and collects all file paths. It can optionally skip hidden files and directories (those starting with '.'). If the provided path is a file instead of a directory, it returns a list containing only that file path.
Parameters:
-
dataset_path(str) –The path to the directory to list.
-
skip_hidden_path(bool, default:True) –Whether to skip hidden files and directories (those starting with '.'). Defaults to True.
-
recursive(bool, default:True) –Whether to recursively search subdirectories. If False, only files in the immediate directory are returned. Defaults to True.
Returns:
- List[str]: A list of absolute file paths. Returns an empty list if the path does not exist or is not a directory.
Source code in lazyllm/tools/rag/document.py
register_global_reader(pattern, func=None)
classmethod
Used to specify a file reader, which is visible to all Document objects. The registered file reader must be a Callable object. It can be registered using a decorator or by a function call.
Parameters:
-
pattern(str) –Matching rules applied by the file reader.
-
func(Callable, default:None) –File reader, must be a Callable object.
Examples:
>>> from lazyllm.tools.rag import Document, DocNode
>>> @Document.register_global_reader("**/*.yml")
>>> def processYml(file):
... with open(file, 'r') as f:
... data = f.read()
... return [DocNode(text=data)]
...
>>> doc1 = Document(dataset_path="your_files_path")
>>> doc2 = Document(dataset_path="your_files_path")
>>> files = ["your_yml_files"]
>>> docs1 = doc1._impl._reader.load_data(input_files=files)
>>> docs2 = doc2._impl._reader.load_data(input_files=files)
>>> print(docs1[0].text == docs2[0].text)
# True
Source code in lazyllm/tools/rag/document.py
register_index(index_type, index_cls, *args, **kwargs)
Register a new index type.
This method allows users to register a new index type for the document module, enabling extension of retrieval capabilities. Once registered, the index can be referenced by its type.
Parameters:
-
index_type(str) –Name of the index type.
-
index_cls(IndexBase) –Index class, must inherit from
IndexBase. -
*args–Variable arguments for index initialization.
-
**kwargs–Keyword arguments for index initialization.
Source code in lazyllm/tools/rag/document.py
register_schema_set(schema_set, kb_id=DEFAULT_KB_ID, force_refresh=False)
Manually register a Pydantic model as the schema for the current algorithm and bind it to a specific knowledge base.
If the KB is already bound to another schema, it raises by default; set force_refresh=True to replace the binding and clean old records.
Parameters:
-
schema_set(Type[BaseModel]) –Pydantic model that defines the schema to register.
-
kb_id(Optional[str], default:DEFAULT_KB_ID) –Target knowledge base ID. Defaults to
DEFAULT_KB_ID. -
force_refresh(bool, default:False) –Whether to force refresh when a binding already exists. Defaults to
False.
Returns:
-
str(str) –The generated
schema_set_id.
Source code in lazyllm/tools/rag/document.py
update_database(llm=None)
Update the database with information extracted from documents using the SchemaExtractor.
Parameters:
-
llm(Union[OnlineChatModule, TrainableModule], default:None) –LLM for extraction; defaults to the SchemaExtractor's built-in LLM.
Source code in lazyllm/tools/rag/document.py
lazyllm.tools.rag.store.ChromaStore
Bases: EmbedResolveMixin, LazyLLMStoreBase
ChromaStore is a vector-capable implementation of LazyLLMStoreBase, leveraging Chroma for persistence and vector search.
Parameters:
-
uri(Optional[str], default:None) –URI string for Chroma connection. Required if
diris not provided. -
dir(Optional[str], default:None) –Filesystem path for local persistent storage. If provided, PersistentClient mode is used.
-
index_kwargs(Optional[Union[Dict, List]], default:None) –Configuration for Chroma collections, e.g., index type and distance metrics.
-
client_kwargs(Optional[Dict], default:None) –Additional arguments passed to the Chroma client constructor.
-
**kwargs–Reserved for future extension.
Source code in lazyllm/tools/rag/store/vector/chroma_store.py
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 | |
dir
property
Directory property of the store.
Returns:
- Optional[str]: Normalized directory path ending with a slash, or None if not set.
connect(embed_dims=None, embed_datatypes=None, embed=None, global_metadata_desc=None, **kwargs)
Initialize the Chroma client and configure embedding and global metadata settings.
Parameters:
-
embed_dims(Optional[Dict[str, int]], default:None) –Dimensions for each embedding key. Defaults to empty dict if not provided.
-
embed_datatypes(Optional[Dict[str, DataType]], default:None) –Data types for each embedding key. Only FLOAT_VECTOR or SPARSE_FLOAT_VECTOR are supported.
-
global_metadata_desc(Optional[Dict[str, GlobalMetadataDesc]], default:None) –Descriptions for global metadata fields. Supported types: string, int, float, bool.
-
**kwargs–Reserved for future extension.
Source code in lazyllm/tools/rag/store/vector/chroma_store.py
delete(collection_name, criteria=None, **kwargs)
Delete an entire collection or specific records.
Parameters:
-
collection_name(str) –Name of the collection to delete from.
-
criteria(Optional[dict], default:None) –If None, delete the entire collection. Otherwise, a dictionary specifying conditions to delete matching records (e.g., by doc_id, uid, kb_id).
-
**kwargs–Reserved for future extension.
Returns:
- bool: True if deletion succeeds, False otherwise.
Source code in lazyllm/tools/rag/store/vector/chroma_store.py
get(collection_name, criteria=None, **kwargs)
Retrieve records matching criteria.
Parameters:
-
collection_name(str) –Name of the collection to query.
-
criteria(Optional[dict], default:None) –Filter conditions such as primary key or metadata (e.g., doc_id, kb_id). If None, retrieves all records.
Returns:
- List[dict]: A list of records, where each record contains:
- 'uid': The unique identifier of the record.
- 'global_meta': A dictionary of global metadata fields.
- 'embedding': A dictionary mapping embedding keys to their corresponding vectors.
Source code in lazyllm/tools/rag/store/vector/chroma_store.py
search(collection_name, query_embedding, embed_key, topk=10, filters=None, **kwargs)
Perform a vector similarity search.
Parameters:
-
collection_name(str) –Name of the collection to query.
-
query_embedding(List[float]) –The query vector for similarity search.
-
embed_key(str) –The embedding key specifying which embedding space to use.
-
topk(int, default:10) –Number of top results to return. Defaults to 10.
-
filters(Optional[Dict[str, Union[str, int, List, Set]]], default:None) –Optional metadata filter conditions to restrict search results.
Returns:
- List[dict]: A list of matched records, where each record contains:
- 'uid': The unique identifier of the matched record.
- 'score': The similarity score (1 - distance).
Source code in lazyllm/tools/rag/store/vector/chroma_store.py
upsert(collection_name, data)
Insert or update a batch of records(segment's uid and vectors) into Chroma.
Parameters:
-
collection_name(str) –Logical name for the collection.
-
data(List[dict]) –List of documents.
Returns:
- bool: True if operation succeeds, False otherwise.
Source code in lazyllm/tools/rag/store/vector/chroma_store.py
lazyllm.tools.rag.store.MilvusStore
Bases: EmbedResolveMixin, LazyLLMStoreBase
Vector store implementation based on Milvus, inheriting from StoreBase. Supports vector insertion, deletion, flexible querying (including scalar filtering).
Parameters:
-
uri(str, default:'') –Milvus connection URI (e.g., "tcp://localhost:19530"). If scheme is local file path, uses milvus-lite version; otherwise remote (need to set up a milvus service, e.x. standalone/distributed version).
-
db_name(str, default:'lazyllm') –Database name to use in Milvus. Defaults to "lazyllm".
-
index_kwargs(Optional[Union[Dict, List]], default:None) –Index creation parameters (e.g., {"index_type": "IVF_FLAT", "metric_type": "COSINE"} or a list of per-embed-key configs).
-
client_kwargs(Optional[Dict], default:None) –Additional keyword arguments for milvus client.
Source code in lazyllm/tools/rag/store/vector/milvus_store.py
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 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 | |
dir
property
Local storage directory derived from URI if running embedded. Returns None when using remote Milvus.
Returns:
- Optional[str]: Directory path for local milvus.db file, or None if remote.
connect(embed_dims=None, embed_datatypes=None, embed=None, global_metadata_desc=None, **kwargs)
Initialize Milvus client, pass in embedding model parameters and global metadata descriptions.
Parameters:
-
embed_dims(Dict[str, int], default:None) –Embedding dimensions per embed key.
-
embed_datatypes(Dict[str, DataType], default:None) –Data types for each embed key.
-
global_metadata_desc(Dict[str, GlobalMetadataDesc], default:None) –Descriptions for metadata fields.
-
kwargs–Other connection parameters
Source code in lazyllm/tools/rag/store/vector/milvus_store.py
delete(collection_name, criteria=None, **kwargs)
Delete entire collection or subset of records by criteria.
Parameters:
-
collection_name(str) –Target collection.
-
criteria(Optional[dict], default:None) –If None, drop the entire collection; otherwise a dict of filters (uid list or metadata conditions).
-
kwargs–Other delete parameters
Returns:
- bool: True if deletion succeeds, False otherwise.
Source code in lazyllm/tools/rag/store/vector/milvus_store.py
get(collection_name, criteria=None, **kwargs)
Retrieve records matching primary-key or metadata filters.
Parameters:
-
collection_name(str) –Collection to query.
-
criteria(Optional[dict], default:None) –Dict containing 'uid' list or metadata field filters.
-
kwargs–Other query parameters
Returns:
- List[dict]: Each entry contains 'uid' and 'embedding'.
Source code in lazyllm/tools/rag/store/vector/milvus_store.py
rebuild(uri, db_name, index_kwargs, client_kwargs)
classmethod
Rebuild a MilvusStore from serialized parameters without copying a live connection.
Parameters:
-
uri(str) –Milvus endpoint or local storage path.
-
db_name(str) –Database name.
-
index_kwargs(dict or list) –Index parameters.
-
client_kwargs(dict) –Client parameters.
Returns:
-
MilvusStore–Reconstructed store.
Source code in lazyllm/tools/rag/store/vector/milvus_store.py
search(collection_name, query_embedding, topk, filters=None, embed_key=None, filter_str='', **kwargs)
Perform vector similarity search with optional metadata filtering.
Parameters:
-
collection_name(str) –Collection to search.
-
query_embedding(List[float]) –Query vector.
-
topk(int) –Number of nearest neighbors.
-
filters(Optional[Dict[str, Union[List, Set]]], default:None) –Metadata filter map.
-
embed_key(str, default:None) –Which embedding field to use.
-
filter_str(Optional[str], default:'') –过滤表达式字符串。默认为空字符串
-
kwargs–其他搜索参数
Returns:
- List[dict]: Each dict has 'uid' and similarity 'score'.
Source code in lazyllm/tools/rag/store/vector/milvus_store.py
upsert(collection_name, data)
Insert or update a batch of segment data into the Milvus collection.
Parameters:
-
collection_name(str) –Collection name (per embed key grouping).
-
data(List[dict]) –List of segment data.
Returns:
- bool: True if successful, False otherwise.
Source code in lazyllm/tools/rag/store/vector/milvus_store.py
validate_milvus_embed_keys(index_kwargs)
Validate and preprocess the index_kwargs of milvus store_conf: 1. Auto fill the only one missing embed_key into the configuration without embed_key; 2. The embed_key in self._embed must be a subset of the embed_key in store_conf; 3. store_conf can contain additional embed_key; 4. Duplicate embed_key is forbidden; 5. If multiple embed_key are missing, raise an error.
Source code in lazyllm/tools/rag/store/vector/milvus_store.py
lazyllm.tools.rag.store.QdrantStore
Bases: EmbedResolveMixin, LazyLLMStoreBase
Vector store implementation based on Qdrant, inheriting from LazyLLMStoreBase. Supports vector insertion, deletion, retrieval (including scalar filtering), dense and sparse vectors.
Note: Qdrant stores dense vectors normalized to unit length when the distance is COSINE, so vectors read back via get() may differ from the inserted values.
Parameters:
-
uri(str) –Qdrant connection address. Must be a remote Qdrant server URL in the form http(s)://host:port.
-
api_key(Optional[str], default:None) –API key for remote Qdrant (e.g. Qdrant Cloud).
-
index_kwargs(Optional[Union[Dict, List]], default:None) –Index configuration, each entry is {"embed_key": ..., "distance": "COSINE|EUCLID|DOT|MANHATTAN"} and the per-key distance defaults to COSINE for dense and DOT for sparse vectors.
-
client_kwargs(Optional[Dict], default:None) –Additional keyword arguments passed to the Qdrant client constructor.
Examples:
>>> import lazyllm
>>> from lazyllm.tools.rag.data_type import DataType
>>> from lazyllm.tools.rag.store import QdrantStore
>>> store = QdrantStore(uri='http://localhost:6333')
>>> store.connect(
... embed_dims={'vec_dense': 3},
... embed_datatypes={'vec_dense': DataType.FLOAT_VECTOR},
... global_metadata_desc={})
>>> store.upsert('my_collection', [{'uid': '1', 'embedding': {'vec_dense': [0.1, 0.2, 0.3]}}])
>>> store.search('my_collection', query_embedding=[0.1, 0.2, 0.3], embed_key='vec_dense', topk=1)
Source code in lazyllm/tools/rag/store/vector/qdrant_store.py
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 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 | |
dir
property
Always returns None; Qdrant is a remote service with no embedded filesystem path.
Returns:
- None.
connect(embed_dims=None, embed_datatypes=None, embed=None, global_metadata_desc=None, collections=None, **kwargs)
Initialize the Qdrant client, validate embed specs, and (when collections are given) infer missing embed dims and datatypes from the existing Qdrant schema.
Parameters:
-
embed_dims(Optional[Dict[str, int]], default:None) –Embedding dimensions per embed key.
-
embed_datatypes(Optional[Dict[str, DataType]], default:None) –Data type per embed key (FLOAT_VECTOR or SPARSE_FLOAT_VECTOR).
-
embed(Optional[Dict[str, Callable]], default:None) –Optional embed callables keyed by embed_key, used to auto-resolve dims for FLOAT_VECTOR keys that have no dim provided.
-
global_metadata_desc(Optional[Dict], default:None) –Field descriptor mapping for metadata filters.
-
collections(Optional[List[str]], default:None) –Existing collection names whose schema should be introspected to fill in missing embed dims/datatypes.
Source code in lazyllm/tools/rag/store/vector/qdrant_store.py
delete(collection_name, criteria=None, **kwargs)
Delete the entire Qdrant collection, or a subset of records by criteria.
Parameters:
-
collection_name(str) –Target collection.
-
criteria(Optional[dict], default:None) –If None, drop the entire collection; otherwise filter by uid list or metadata conditions.
-
kwargs–Other parameters.
Returns:
- bool: True on success, False if any error occurred.
Source code in lazyllm/tools/rag/store/vector/qdrant_store.py
get(collection_name, criteria=None, **kwargs)
Retrieve records from a Qdrant collection, optionally filtered by uid or metadata.
Parameters:
-
collection_name(str) –Target collection.
-
criteria(Optional[dict], default:None) –Dict containing 'uid' list or metadata field filters.
-
kwargs–Other parameters.
Returns:
- List[dict]: Each entry contains 'uid' and 'embedding'.
Source code in lazyllm/tools/rag/store/vector/qdrant_store.py
rebuild(uri, api_key, index_kwargs, client_kwargs)
classmethod
Rebuild a QdrantStore from the constructor kwargs. Used by pickle __reduce__ to round-trip without the live client.
Parameters:
-
uri(str) –Qdrant connection address.
-
api_key(Optional[str]) –API key for remote Qdrant.
-
index_kwargs(Optional[Union[Dict, List]]) –Index configuration.
-
client_kwargs(Optional[Dict]) –Additional keyword arguments for the Qdrant client.
Returns:
- QdrantStore: A new instance with no active client (call
connectto initialize).
Source code in lazyllm/tools/rag/store/vector/qdrant_store.py
search(collection_name, query_embedding=None, topk=10, filters=None, embed_key=None, **kwargs)
Perform vector similarity search.
Parameters:
-
collection_name(str) –The collection to search in.
-
query_embedding(Union[dict, List[float]], default:None) –The query vector, a dict of {index: value} for sparse vectors.
-
embed_key(str, default:None) –The embedding key to search against.
-
topk(int, default:10) –Number of results to return. Defaults to 10.
-
filters(Optional[Dict[str, Union[str, int, List, Set]]], default:None) –Optional metadata filters to narrow the search.
Returns:
- List[dict]: Matching results, each containing:
- 'uid': The unique identifier of the matched record.
- 'score': Similarity score (larger is more similar; for EUCLID/MANHATTAN distances the raw distance is negated).
Source code in lazyllm/tools/rag/store/vector/qdrant_store.py
upsert(collection_name, data)
Insert or update a batch of segment data into a Qdrant collection, creating the collection on first use.
Parameters:
-
collection_name(str) –Target collection.
-
data(List[dict]) –List of segment data; rows missing required embeddings are dropped with a warning.
Returns:
- bool: True on success, False if any error occurred.
Source code in lazyllm/tools/rag/store/vector/qdrant_store.py
lazyllm.tools.rag.store.hybrid.hybrid_store.HybridStore
Bases: LazyLLMStoreBase
Hybrid storage class that combines segment storage and vector storage capabilities.
Parameters:
-
segment_store(LazyLLMStoreBase) –Segment storage instance for storing original document content.
-
vector_store(LazyLLMStoreBase) –Vector storage instance for storing document vector representations.
Source code in lazyllm/tools/rag/store/hybrid/hybrid_store.py
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 | |
connect(*args, **kwargs)
Connect to underlying segment and vector stores.
Parameters:
-
*args–Positional arguments passed to store connection methods.
-
**kwargs–Keyword arguments passed to store connection methods.
Source code in lazyllm/tools/rag/store/hybrid/hybrid_store.py
delete(collection_name, criteria=None, **kwargs)
Delete data from the stores.
Parameters:
-
collection_name(str) –Name of the collection.
-
criteria(Optional[dict], default:None) –Deletion criteria, defaults to None.
-
**kwargs–Additional arguments.
Returns:
- bool: Returns True if operation is successful, False otherwise.
Source code in lazyllm/tools/rag/store/hybrid/hybrid_store.py
drop_collection(collection_name)
Drop a collection from both the segment store and the vector store.
Parameters:
-
collection_name(str) –Name of the collection to drop.
Returns:
- bool:
Trueif both underlying stores dropped the collection successfully,Falseotherwise.
Source code in lazyllm/tools/rag/store/hybrid/hybrid_store.py
get(collection_name, criteria=None, **kwargs)
Retrieve data from the stores.
Parameters:
-
collection_name(str) –Name of the collection.
-
criteria(Optional[dict], default:None) –Query criteria, defaults to None.
-
**kwargs–Additional arguments.
Returns:
- List[dict]: List of matching data items.
Raises:
-
ValueError–When a uid found in vector store is not found in segment store.
Source code in lazyllm/tools/rag/store/hybrid/hybrid_store.py
search(collection_name, query, query_embedding=None, topk=10, filters=None, embed_key=None, **kwargs)
Search data in the stores.
Parameters:
-
collection_name(str) –Name of the collection.
-
query(str) –Search query string.
-
query_embedding(Optional[Union[dict, List[float]]], default:None) –Vector representation of the query, defaults to None.
-
topk(int, default:10) –Maximum number of results to return, defaults to 10.
-
filters(Optional[Dict[str, Union[str, int, List, Set]]], default:None) –Filter conditions, defaults to None.
-
embed_key(Optional[str], default:None) –Key name for embedding vector, defaults to None.
-
**kwargs–Additional arguments.
Returns:
- List[dict]: List of search results.
Source code in lazyllm/tools/rag/store/hybrid/hybrid_store.py
seg_connect(*args, **kwargs)
Connect to the underlying segment store only.
Unlike connect(), seg_connect() initialises only segment_store and does not
trigger vector-store connection logic. DocumentStore calls this method during _seg_init(),
typically passing global_metadata_desc to register global metadata fields.
Parameters:
-
*args–Positional arguments forwarded to
segment_store.connect(). -
**kwargs–Keyword arguments forwarded to
segment_store.connect(). Common keys includeglobal_metadata_desc(global metadata schema description).
Returns:
- None
Source code in lazyllm/tools/rag/store/hybrid/hybrid_store.py
upsert(collection_name, data)
Insert or update data in the stores.
Parameters:
-
collection_name(str) –Name of the collection.
-
data(List[dict]) –List of data items to insert or update, each item is a dictionary.
Returns:
- bool: Returns True if operation is successful, False otherwise.
Source code in lazyllm/tools/rag/store/hybrid/hybrid_store.py
vec_connect(*args, **kwargs)
Connect to the underlying vector store only.
Unlike connect(), vec_connect() initialises only vector_store and does not
trigger segment-store connection logic. DocumentStore calls this method during _vec_init(),
typically passing embed_dims, embed_datatypes, collections, and
global_metadata_desc so the vector backend can create or validate collection schemas.
Parameters:
-
*args–Positional arguments forwarded to
vector_store.connect(). -
**kwargs–Keyword arguments forwarded to
vector_store.connect(). Common keys includeembed_dims(vector dimension per embed key),embed_datatypes(data type per embed key),global_metadata_desc(global metadata schema description),collections(collection names to pre-create).
Returns:
- None
Source code in lazyllm/tools/rag/store/hybrid/hybrid_store.py
lazyllm.tools.rag.store.hybrid.oceanbase_store.OceanBaseStore
Bases: EmbedResolveMixin, LazyLLMStoreBase
OceanBase storage class for storing and retrieving document nodes.
Parameters:
-
uri(str, default:'127.0.0.1:2881') –URI of the OceanBase database.
-
user(str) –Username of the OceanBase database.
-
password(str) –Password of the OceanBase database.
-
db_name(str, default:'test') –Name of the OceanBase database.
-
drop_old(bool) –Whether to drop old tables.
-
index_kwargs(List[dict], default:None) –List of index configurations.
-
client_kwargs(Dict, default:None) –Dictionary of client configurations.
-
max_pool_size(int) –Maximum pool size.
-
normalize(bool) –Whether to normalize data.
-
enable_fulltext_index(bool) –Whether to enable fulltext index.
Source code in lazyllm/tools/rag/store/hybrid/oceanbase_store.py
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 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 | |
connect(embed_dims=None, embed_datatypes=None, embed=None, global_metadata_desc=None, **kwargs)
Connect to underlying OceanBase database.
Parameters:
-
embed_dims(Dict[str, int], default:None) –Dictionary of embedding dimensions.
-
embed_datatypes(Dict[str, DataType], default:None) –Dictionary of embedding data types.
-
global_metadata_desc(Dict[str, GlobalMetadataDesc], default:None) –Dictionary of global metadata descriptions.
-
**kwargs–Additional arguments.
Source code in lazyllm/tools/rag/store/hybrid/oceanbase_store.py
delete(collection_name, criteria=None, **kwargs)
Delete data from the stores.
Parameters:
-
collection_name(str) –Name of the collection.
-
criteria(Optional[dict], default:None) –Deletion criteria, defaults to None.
-
**kwargs–Additional arguments.
Returns:
- bool: Returns True if operation is successful, False otherwise.
Source code in lazyllm/tools/rag/store/hybrid/oceanbase_store.py
get(collection_name, criteria=None, **kwargs)
Retrieve data from the stores.
Parameters:
-
collection_name(str) –Name of the collection.
-
criteria(Optional[dict], default:None) –Query criteria, defaults to None.
-
**kwargs–Additional arguments.
Returns:
- List[dict]: List of matching data items.
Source code in lazyllm/tools/rag/store/hybrid/oceanbase_store.py
search(collection_name, query, query_embedding, topk, filters=None, embed_key=None, filter_str='', **kwargs)
Search data in the stores.
Parameters:
-
collection_name(str) –Name of the collection.
-
query_embedding(Union[dict, List[float]]) –Vector representation of the query.
-
topk(int) –Maximum number of results to return.
-
filters(Optional[Dict[str, Union[str, int, List, Set]]], default:None) –Filter conditions, defaults to None.
-
embed_key(Optional[str], default:None) –Key name for embedding vector, defaults to None.
-
filter_str(Optional[str], default:'') –Filter conditions string, defaults to None.
-
**kwargs–Additional arguments.
Returns:
- List[dict]: List of search results.
Source code in lazyllm/tools/rag/store/hybrid/oceanbase_store.py
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 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 | |
upsert(collection_name, data, range_part=None, **kwargs)
Insert or update data in the stores.
Parameters:
-
collection_name(str) –Name of the collection.
-
data(List[dict]) –List of data items to insert or update, each item is a dictionary.
-
range_part(Optional[RangeListPartInfo], default:None) –Range partition information, not implemented yet.
-
**kwargs–Additional arguments.
Returns:
- bool: Returns True if operation is successful, False otherwise.
Source code in lazyllm/tools/rag/store/hybrid/oceanbase_store.py
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 | |
lazyllm.tools.rag.store.ElasticSearchStore
Bases: LazyLLMStoreBase
Vector store implementation based on Elasticsearch, inheriting from StoreBase. Supports vector insertion, deletion, flexible querying (including scalar filtering). Args: uris (List[str]): Elasticsearch connection URIs (e.g., ["http://localhost:9200"]). client_kwargs (Optional[Dict]): Additional keyword arguments for Elasticsearch client. index_kwargs (Optional[Union[Dict, List]]): Index creation parameters (e.g., {"index_type": "IVF_FLAT", "metric_type": "COSINE"} or a list of per-embed-key configs). **kwargs: Additional keyword arguments.
Examples:
>>> import lazyllm
>>> from lazyllm.tools.rag.store import ElasticSearchStore
>>> store = ElasticSearchStore(uris=["localhost:9200"], client_kwargs={}, index_kwargs={})
>>> store.connect(embed_dims={"vec_dense": 128, "vec_sparse": 128}, embed_datatypes={"vec_dense": DataType.FLOAT32, "vec_sparse": DataType.FLOAT32}, global_metadata_desc={})
>>> store.upsert(collection_name="test", data=[{"uid": "1", "embedding": {"vec_dense": [0.1, 0.2, 0.3], "vec_sparse": {"1": 0.1, "2": 0.2, "3": 0.3}}, "metadata": {"key1": "value1", "key2": "value2"}}])
>>> store.get(collection_name="test", criteria={"uid": "1"})
>>> store.delete(collection_name="test", criteria={"uid": "1"})
Source code in lazyllm/tools/rag/store/segment/elasticsearch_store.py
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 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 | |
dir
property
Returns None when using remote Elasticsearch. Returns:
Optional[str]: None if remote.
connect(global_metadata_desc=None, **kwargs)
Initialize Elasticsearch client, pass in embedding model parameters and global metadata descriptions. Args: embed_dims (Dict[str, int]): Embedding dimensions per embed key. embed_datatypes (Dict[str, DataType]): Data types for each embed key. global_metadata_desc (Dict[str, GlobalMetadataDesc]): Descriptions for metadata fields. Returns:
bool: True if successful, False otherwise.
Source code in lazyllm/tools/rag/store/segment/elasticsearch_store.py
delete(collection_name=None, criteria=None, **kwargs)
Delete entire collection or subset of records by criteria. Args: collection_name (str): Target collection. criteria (Optional[dict]): If None, drop the entire collection; otherwise a dict of filters (uid list or metadata conditions). Returns:
bool: True if deletion succeeds, False otherwise.
Source code in lazyllm/tools/rag/store/segment/elasticsearch_store.py
get(collection_name, criteria=None, **kwargs)
Retrieve records matching primary-key or metadata filters. Args: collection_name (str): Collection to query. criteria (Optional[dict]): Dict containing 'uid' list or metadata field filters. Returns:
List[dict]: List of segments with 'uid' and 'embedding'.
Source code in lazyllm/tools/rag/store/segment/elasticsearch_store.py
search(collection_name, query, topk=10, filters=None, **kwargs)
Perform vector similarity search with optional metadata filtering. Args: collection_name (str): Collection to search. query (Optional[str]): Query string. topk (Optional[int]): Number of nearest neighbors. filters (Optional[dict]): Metadata filter map. kwargs: Other search parameters
Returns:
- List[dict]: Return matching results list and similarity 'score'.
Source code in lazyllm/tools/rag/store/segment/elasticsearch_store.py
upsert(collection_name=None, data=None)
Insert or update a batch of segment data into the Elasticsearch collection. Args: collection_name (str): Collection name (per embed key grouping). data (List[dict]): List of segment data. Returns:
bool: True if successful, False otherwise.
Source code in lazyllm/tools/rag/store/segment/elasticsearch_store.py
lazyllm.tools.rag.readers.ReaderBase
Bases: ModuleBase
Base document reader class that provides fundamental interfaces for document loading. Inherits from ModuleBase and uses LazyLLMRegisterMetaClass as metaclass.
All readers may enable algorithm-side content caching on reader(file, ...): parsed
List[DocNode] results are stored in ModuleCache. Subsequent calls with the same file
content and reader configuration return the cache directly, skipping _load_data and
downstream OCR requests.
Global switch: lazyllm.config['reader_use_cache'] (env LAZYLLM_READER_USE_CACHE, default False).
Algorithm-side cache and OCR service use_cache are two independent layers:
- Algorithm-side content cache (this class): caches
DocNodelists; controlled bylazyllm.config['reader_use_cache']. - OCR service cache (e.g. MineruPDFReader): OCR reader
_load_data(..., use_cache=...), defaultTrue.
Cache keys combine reader type, appendix_hash_key (subclass config such as OCR URL/backend),
file mtime and st_size, and call kwargs such as extra_info. File updates (mtime/size
change) cause a miss; stale entries are not evicted automatically.
Storage reuses ModuleCache and global settings:
LAZYLLM_CACHE_STRATEGY:memory(default) /file/sqlite/redisLAZYLLM_CACHE_MODE:RW/RO/WO/NONELAZYLLM_CACHE_DIR: cache root, default~/.lazyllm/cache; withsqlitestrategy the db file is{CACHE_DIR}/module/cache.db
Parameters:
-
*args–Positional arguments, reserved for parent or subclass use.
-
return_trace(bool, default:True) –Whether to return processing trace information. Defaults to True.
-
**kwargs–Keyword arguments, reserved for parent or subclass use.
Examples:
from lazyllm.tools.rag.readers.readerBase import LazyLLMReaderBase
from lazyllm.tools.rag.doc_node import DocNode
from typing import Iterable
class CustomReader(LazyLLMReaderBase):
def _lazy_load_data(self, file_paths: list, **kwargs) -> Iterable[DocNode]:
for file_path in file_paths:
# Process each file and yield DocNode
content = self._read_file(file_path)
yield DocNode(
text=content,
metadata={"source": file_path}
)
# Create reader instance
reader = CustomReader(return_trace=True)
# Load documents
documents = reader.forward(file_paths=["doc1.txt", "doc2.txt"])
Source code in lazyllm/tools/rag/readers/readerBase.py
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 | |
clear_encoding_cache()
classmethod
Clear the encoding cache.
Parameters:
-
file_path(str) –The path of the file.
-
fs(AbstractFileSystem) –The file system.
-
sample_size(int) –The sample size.
-
use_cache(bool) –Whether to use cache.
-
enable_chardet(bool) –Whether to enable chardet.
Examples:
>>> import lazyllm
>>> from lazyllm.tools.rag.readers import LazyLLMReaderBase
>>> reader = LazyLLMReaderBase()
>>> reader.clear_encoding_cache()
Source code in lazyllm/tools/rag/readers/readerBase.py
detect_encoding(file_path, fs=None, sample_size=10000, use_cache=True, enable_chardet=True)
classmethod
Detect the encoding of a file.
Parameters:
-
file_path(str) –The path of the file.
-
fs(AbstractFileSystem, default:None) –The file system.
-
sample_size(int, default:10000) –The sample size.
-
use_cache(bool, default:True) –Whether to use cache.
-
enable_chardet(bool, default:True) –Whether to enable chardet.
Returns:
- str: The encoding of the file.
Examples:
>>> import lazyllm
>>> from lazyllm.tools.rag.readers import LazyLLMReaderBase
>>> reader = LazyLLMReaderBase()
>>> encoding = reader.detect_encoding("path/to/file.txt")
>>> print(encoding)
Source code in lazyllm/tools/rag/readers/readerBase.py
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 | |
get_encoding_cache_stats()
classmethod
Get the encoding cache stats.
Returns:
- dict: The encoding cache stats.
Examples:
>>> import lazyllm
>>> from lazyllm.tools.rag.readers import LazyLLMReaderBase
>>> reader = LazyLLMReaderBase()
>>> stats = reader.get_encoding_cache_stats()
>>> print(stats)
Source code in lazyllm/tools/rag/readers/readerBase.py
lazyllm.tools.rag.readers.PandasCSVReader
Bases: LazyLLMReaderBase
Reader for parsing CSV files using pandas.
Parameters:
-
concat_rows(bool, default:True) –Whether to concatenate all rows into a single text block. Default is True.
-
col_joiner(str, default:', ') –String used to join column values.
-
row_joiner(str, default:'\n') –String used to join rows.
-
pandas_config(Optional[Dict], default:None) –Optional config for pandas.read_csv.
-
fill_method(Optional[str], default:'fillna') –Missing value fill strategy: 'fillna'(default) / 'ffill' / 'bfill'.
-
return_trace(bool, default:True) –Whether to return the processing trace.
Source code in lazyllm/tools/rag/readers/pandasReader.py
lazyllm.tools.rag.readers.PandasExcelReader
Bases: LazyLLMReaderBase
Reader for extracting text content from Excel (.xlsx) files.
Parameters:
-
concat_rows(bool, default:True) –Whether to concatenate all rows into a single block.
-
sheet_name(Optional[str], default:None) –Name of the sheet to read. If None, all sheets will be read.
-
pandas_config(Optional[Dict], default:None) –Optional config for pandas.read_excel.
-
fill_method(Optional[str], default:'fillna') –Missing value fill strategy: 'fillna'(default) / 'ffill' / 'bfill'.
-
return_trace(bool, default:True) –Whether to return the processing trace.
-
col_joiner(str, default:' ') –String used to join column values. Default is a single space.
Source code in lazyllm/tools/rag/readers/pandasReader.py
lazyllm.tools.rag.readers.PDFReader
Bases: _RichReader
Reader for extracting text content from PDF files.
Parameters:
-
split_doc(bool, default:True) –If True (default), parses into a
RichDocNodewhich can be used withRichTransformto extract nodes with page information; if False, parses into a plain textDocNode. -
post_func(Optional[Callable[[List[DocNode]], List[DocNode]]], default:None) –Post-processing function. Must return a
List[DocNode]and will writeextra_infointo each node'sglobal_metadata. -
return_trace(bool, default:True) –Whether to return the processing trace. Default is True.
-
return_full_document((bool, deprecated), default:None) –This parameter will be removed in a future version. Please use
split_docinstead.
Notes
When split_doc=True, returns a RichDocNode; otherwise returns a DocNode. Both cases return a single node.
When split_doc=True, it is strongly recommended to use it with RichTransform, which can extract nodes with page information and other metadata;
without RichTransform, the parsed nodes will fall back to plain text nodes.
Source code in lazyllm/tools/rag/readers/pdfReader.py
lazyllm.tools.rag.readers.PPTXReader
Bases: LazyLLMReaderBase
Reader for PPTX (PowerPoint) files. Extracts text from slides and generates captions for embedded images using a vision-language model.
Parameters:
-
return_trace(bool, default:True) –Whether to record the processing trace. Default is True.
Source code in lazyllm/tools/rag/readers/pptxReader.py
lazyllm.tools.rag.readers.VideoAudioReader
Bases: LazyLLMReaderBase
Reader for extracting speech content from video or audio files using OpenAI's Whisper model for transcription.
Parameters:
-
model_version(str, default:'base') –Whisper model version (e.g., "base", "small", "medium", "large"). Default is "base".
-
return_trace(bool, default:True) –Whether to return the processing trace. Default is True.
Source code in lazyllm/tools/rag/readers/videoAudioReader.py
lazyllm.tools.SqlManager
Bases: DBManager
SqlManager is a specialized tool for interacting with databases. It provides methods for creating tables, executing queries, and performing updates on databases.
Parameters:
-
db_type(str) –Database type, supports: postgresql, mysql, mssql, sqlite, mysql+pymysql
-
user(str) –Database username
-
password(str) –Database password
-
host(str) –Database host address
-
port(int) –Database port number
-
db_name(str) –Database name
-
options_str(str, default:None) –Connection options string, defaults to None
-
tables_info_dict(Dict, default:None) –Table structure information dictionary for initializing table structure, defaults to None
Source code in lazyllm/tools/sql/sql_manager.py
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 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 | |
check_connection()
Check database connection status.
Tests whether the connection to the database is successfully established.
Returns:
- DBResult: DBResult.status True if the connection is successful, False if it fails. DBResult.detail contains failure information.
Source code in lazyllm/tools/sql/sql_manager.py
create_table(table)
Create a table
Parameters:
-
table(str / Type[DeclarativeBase] / DeclarativeMeta) –table schema。Supports three types of parameters: SQL statements with type str, ORM classes that inherit from DeclarativeBase or declarative_base().
Source code in lazyllm/tools/sql/sql_manager.py
dispose()
Release the underlying engine's connection pool.
Needed so callers (e.g. DocServer._Impl.stop) can close sqlite file handles
before removing the containing directory; on Windows this is required, because
open handles block TemporaryDirectory cleanup.
Source code in lazyllm/tools/sql/sql_manager.py
drop_table(table)
Delete a table
Parameters:
-
table(str / Type[DeclarativeBase] / DeclarativeMeta) –table schema。Supports three types of parameters: Table name with type str, ORM classes that inherit from DeclarativeBase or declarative_base().
Source code in lazyllm/tools/sql/sql_manager.py
execute_commit(statement)
Execute SQL commit statements.
Executes DDL or DML statements and automatically commits transactions. Suitable for CREATE, ALTER, INSERT, UPDATE, DELETE operations.
Parameters:
-
statement(str) –SQL statement to execute
Source code in lazyllm/tools/sql/sql_manager.py
execute_query(statement)
Execute the SQL query script and return the result as a JSON string.
Source code in lazyllm/tools/sql/sql_manager.py
get_all_tables()
Get list of all tables in the database.
Refreshes metadata and returns all table names in the current database.
Returns:
- List[str]: List of all table names in the database
Source code in lazyllm/tools/sql/sql_manager.py
get_session(session=None)
A database session context manager.
When called with the default session=None it opens a new SQLAlchemy session, commits on success, rolls back on exception, and unconditionally closes the session on exit.
When an external session is passed in, this context manager is transparent: the session is yielded as-is without commit / rollback / close — ownership stays with whoever originally opened it. Exceptions raised inside the with block still propagate and trigger rollback at the owning get_session up the call chain. This allows helper methods to participate in a caller-driven transaction via an optional session=None parameter without having to know whether they own the session.
Parameters:
-
session(Optional[Session], default:None) –An already-open SQLAlchemy session from an outer scope. When
None, a new session is opened and managed by this context; otherwise the passed session is yielded as-is.
Source code in lazyllm/tools/sql/sql_manager.py
get_table_orm_class(table_name)
Get corresponding ORM class by table name.
Reflects and gets SQLAlchemy automapped ORM class through table name.
Parameters:
-
table_name(str) –Table name to retrieve
Returns:
- sqlalchemy.ext.automap.Class: Corresponding ORM class, returns None if table doesn't exist
Source code in lazyllm/tools/sql/sql_manager.py
insert_values(table_name, vals)
Bulk insert data
Parameters:
-
table_name(str) –Table name
-
vals(List[dict]) –data to be inserted, format as [{"col_name1": v01, "col_name2": v02, ...}, {"col_name1": v11, "col_name2": v12, ...}, ...]
Source code in lazyllm/tools/sql/sql_manager.py
paginate(query, *, page=1, page_size=20)
staticmethod
Apply page-based pagination to a SQLAlchemy Query.
Clamps page and page_size to at least 1, issues a COUNT against the unpaginated query to obtain the total row count, then fetches the current page using OFFSET / LIMIT. Returns a dict shaped {'items', 'total', 'page', 'page_size'}.
The returned items are raw SQLAlchemy row results — no business conversion is performed. Callers are responsible for converting rows to their desired shape (for example via _orm_to_dict), so this helper stays domain-agnostic and reusable across any listing endpoint.
Parameters:
-
query(Query) –A SQLAlchemy
Querywith the desiredfilter/order_byalready applied. -
page(int, default:1) –1-based page number; values below 1 are clamped to 1.
-
page_size(int, default:20) –Number of rows per page; values below 1 are clamped to 1.
Source code in lazyllm/tools/sql/sql_manager.py
set_desc(tables_desc_dict={})
When using SqlManager with LLM to query table entries in natural language, set descriptions for better results, especially when table names, column names, and values are not self-explanatory.
Parameters:
-
tables_desc_dict(dict, default:{}) –descriptive comment for tables
Source code in lazyllm/tools/sql/sql_manager.py
lazyllm.tools.rag.rerank.Reranker
Bases: ModuleBase, _PostProcess
Initializes a Rerank module for postprocessing and reranking of nodes (documents). This constructor initializes a Reranker module that configures a reranking process based on a specified reranking type. It allows for the dynamic selection and instantiation of reranking kernels (algorithms) based on the type and provided keyword arguments.
Parameters:
-
name(str, default:'ModuleReranker') –The type of reranker used for the postprocessing and reranking process. Defaults to 'ModuleReranker'.
-
target(str, default:None) –Deprecated parameter, only used to notify users.
-
output_format(Optional[str], default:None) –Specifies the output format. Defaults to None. Optional values include 'content' and 'dict'. - 'content' means the output is in string format. - 'dict' means the output is a dictionary.
-
join(Union[bool, str], default:False) –Determines whether to join the top-k output nodes. - When
output_formatis 'content': - If set to True, returns a single long string. - If set to False, returns a list of strings, each representing one node’s content. - Whenoutput_formatis 'dict': - Joining is not supported;joindefaults to False. - Returns a dictionary with three keys: 'content', 'embedding', and 'metadata'. -
kwargs–Additional keyword arguments passed to the reranker upon instantiation.
Detailed explanation of reranker types
-
Reranker: Instantiates a
SentenceTransformerRerankreranker with a list of document nodes and a query. -
KeywordFilter: This registered reranking function instantiates a KeywordNodePostprocessor with specified required and excluded keywords. It filters nodes based on the presence or absence of these keywords.
Examples:
>>> import lazyllm
>>> from lazyllm.tools import Document, Reranker, Retriever, DocNode
>>> m = lazyllm.OnlineEmbeddingModule()
>>> documents = Document(dataset_path='/path/to/user/data', embed=m, manager=False)
>>> retriever = Retriever(documents, group_name='CoarseChunk', similarity='bm25', similarity_cut_off=0.01, topk=6)
>>> reranker = Reranker(DocNode(text=user_data),query="user query")
>>> ppl = lazyllm.ActionModule(retriever, reranker)
>>> ppl.start()
>>> print(ppl("user query"))
Source code in lazyllm/tools/rag/rerank.py
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 | |
register_reranker(func=None, batch=False)
classmethod
A class decorator factory method that provides a flexible mechanism for registering custom reranking algorithms to the Reranker class.
Parameters:
-
func(Optional[Callable], default:None) –The reranking function or class to register. This can be omitted when using decorator syntax (@).
-
batch(bool, default:False) –Whether to process nodes in batches. Defaults to False, meaning nodes are processed individually.
Examples:
@Reranker.register_reranker
def my_reranker(node: DocNode, **kwargs):
return node.score * 0.8 # 自定义分数计算
Source code in lazyllm/tools/rag/rerank.py
lazyllm.tools.rag.readers.readerBase.LazyLLMReaderBase
Bases: ModuleBase
Base document reader class that provides fundamental interfaces for document loading. Inherits from ModuleBase and uses LazyLLMRegisterMetaClass as metaclass.
All readers may enable algorithm-side content caching on reader(file, ...): parsed
List[DocNode] results are stored in ModuleCache. Subsequent calls with the same file
content and reader configuration return the cache directly, skipping _load_data and
downstream OCR requests.
Global switch: lazyllm.config['reader_use_cache'] (env LAZYLLM_READER_USE_CACHE, default False).
Algorithm-side cache and OCR service use_cache are two independent layers:
- Algorithm-side content cache (this class): caches
DocNodelists; controlled bylazyllm.config['reader_use_cache']. - OCR service cache (e.g. MineruPDFReader): OCR reader
_load_data(..., use_cache=...), defaultTrue.
Cache keys combine reader type, appendix_hash_key (subclass config such as OCR URL/backend),
file mtime and st_size, and call kwargs such as extra_info. File updates (mtime/size
change) cause a miss; stale entries are not evicted automatically.
Storage reuses ModuleCache and global settings:
LAZYLLM_CACHE_STRATEGY:memory(default) /file/sqlite/redisLAZYLLM_CACHE_MODE:RW/RO/WO/NONELAZYLLM_CACHE_DIR: cache root, default~/.lazyllm/cache; withsqlitestrategy the db file is{CACHE_DIR}/module/cache.db
Parameters:
-
*args–Positional arguments, reserved for parent or subclass use.
-
return_trace(bool, default:True) –Whether to return processing trace information. Defaults to True.
-
**kwargs–Keyword arguments, reserved for parent or subclass use.
Examples:
from lazyllm.tools.rag.readers.readerBase import LazyLLMReaderBase
from lazyllm.tools.rag.doc_node import DocNode
from typing import Iterable
class CustomReader(LazyLLMReaderBase):
def _lazy_load_data(self, file_paths: list, **kwargs) -> Iterable[DocNode]:
for file_path in file_paths:
# Process each file and yield DocNode
content = self._read_file(file_path)
yield DocNode(
text=content,
metadata={"source": file_path}
)
# Create reader instance
reader = CustomReader(return_trace=True)
# Load documents
documents = reader.forward(file_paths=["doc1.txt", "doc2.txt"])
Source code in lazyllm/tools/rag/readers/readerBase.py
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 | |
clear_encoding_cache()
classmethod
Clear the encoding cache.
Parameters:
-
file_path(str) –The path of the file.
-
fs(AbstractFileSystem) –The file system.
-
sample_size(int) –The sample size.
-
use_cache(bool) –Whether to use cache.
-
enable_chardet(bool) –Whether to enable chardet.
Examples:
>>> import lazyllm
>>> from lazyllm.tools.rag.readers import LazyLLMReaderBase
>>> reader = LazyLLMReaderBase()
>>> reader.clear_encoding_cache()
Source code in lazyllm/tools/rag/readers/readerBase.py
detect_encoding(file_path, fs=None, sample_size=10000, use_cache=True, enable_chardet=True)
classmethod
Detect the encoding of a file.
Parameters:
-
file_path(str) –The path of the file.
-
fs(AbstractFileSystem, default:None) –The file system.
-
sample_size(int, default:10000) –The sample size.
-
use_cache(bool, default:True) –Whether to use cache.
-
enable_chardet(bool, default:True) –Whether to enable chardet.
Returns:
- str: The encoding of the file.
Examples:
>>> import lazyllm
>>> from lazyllm.tools.rag.readers import LazyLLMReaderBase
>>> reader = LazyLLMReaderBase()
>>> encoding = reader.detect_encoding("path/to/file.txt")
>>> print(encoding)
Source code in lazyllm/tools/rag/readers/readerBase.py
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 | |
get_encoding_cache_stats()
classmethod
Get the encoding cache stats.
Returns:
- dict: The encoding cache stats.
Examples:
>>> import lazyllm
>>> from lazyllm.tools.rag.readers import LazyLLMReaderBase
>>> reader = LazyLLMReaderBase()
>>> stats = reader.get_encoding_cache_stats()
>>> print(stats)
Source code in lazyllm/tools/rag/readers/readerBase.py
lazyllm.tools.rag.readers.readerBase.TxtReader
Bases: LazyLLMReaderBase
The TxtReader class loads content from text files and wraps it into a list of DocNode objects.
This class inherits from LazyLLMReaderBase and mainly provides:
- Support for reading files with a specified text encoding;
- Optional tracing information of the loading process;
- Inherited algorithm-side content cache (
lazyllm.config['reader_use_cache']).
Parameters:
-
encoding(str, default:None) –Text encoding for reading files, default is 'utf-8'.
-
return_trace(bool, default:True) –Whether to return trace information of the loading process, default is True.
-
auto_detect_encoding(bool, default:config['auto_detect_encoding']) –Whether to auto-detect encoding; defaults to
LAZYLLM_AUTO_DETECT_ENCODING. -
enable_chardet(bool, default:config['enable_chardet']) –Whether to use chardet when detecting encoding; defaults to
LAZYLLM_ENABLE_CHARDET. -
use_encoding_cache(bool, default:config['use_encoding_cache']) –Whether to cache encoding detection results (class-level; separate from content cache).
Source code in lazyllm/tools/rag/readers/readerBase.py
lazyllm.tools.rag.component.bm25.BM25
A BM25 retriever that uses the BM25 algorithm to retrieve nodes.
Source code in lazyllm/tools/rag/component/bm25.py
retrieve(query, topk=None)
Retrieve the most relevant document nodes for a query using BM25 algorithm.
Parameters:
-
query(str) –Query text.
Returns:
- List[Tuple[DocNode, float]]: Returns a list of tuples containing (document node, relevance score).
Source code in lazyllm/tools/rag/component/bm25.py
lazyllm.tools.rag.doc_to_db.SchemaExtractor
Bases: ModuleBase
Schema aware extractor that materializes BaseModel schemas into database tables.
Source code in lazyllm/tools/rag/doc_to_db/extractor.py
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 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 | |
analyze_schema_and_register(data, schema_set_id=None)
Infer a schema from sample data, register it, and return the registration info.
Source code in lazyllm/tools/rag/doc_to_db/extractor.py
extract_and_store(data, schema_set_id=None, schema_set=None)
Extract content according to the registered schema and persist it; will register the provided schema_set if given; repeated calls for the same doc return cached results.
Parameters:
-
data(Union[str, List[DocNode]]) –Text or list of DocNodes from a single document.
-
schema_set_id(str, default:None) –Schema set id to use.
-
schema_set(Type[BaseModel], default:None) –Schema to register and use if no id is provided.
Returns:
- ExtractResult: Result object where
datais the field/value dict andmetadatacontains schema_set_id, kb_id, doc_id, and field-level clues; or None if nothing persisted.
Source code in lazyllm/tools/rag/doc_to_db/extractor.py
has_schema_set(schema_set_id)
Check whether a schema_set_id is registered, recovering the model and ensuring the table if needed.
Parameters:
-
schema_set_id(str) –Target schema set id.
Returns:
- bool: True if it exists.
Source code in lazyllm/tools/rag/doc_to_db/extractor.py
register_schema_set(schema_set, schema_set_id=None, force_refresh=False)
schema set registration, idempotent
Source code in lazyllm/tools/rag/doc_to_db/extractor.py
sql_manager_for_nl2sql(kb_ids=None)
Create a SqlManager tailored for NL2SQL in SqlCall Module that only exposes the table for the active schema set, with descriptions of columns and visible tables.
Parameters:
-
kb_ids(Union[str, List[str]], default:None) –KB id or list to filter rows.
Returns:
- SqlManager: Manager instance with visible_tables and column metadata set for NL2SQL use.
Source code in lazyllm/tools/rag/doc_to_db/extractor.py
lazyllm.tools.rag.readers.DocxReader
Bases: _RichReader
A docx format file parser, reading text content from a .docx file and return a list of DocNode objects.
Parameters:
-
file(Path) –Path to the
.docxfile. -
fs(Optional[AbstractFileSystem]) –Optional file system object for custom reading.
Returns:
- List[DocNode]: A list containing the extracted text content as
DocNodeinstances.
Source code in lazyllm/tools/rag/readers/docxReader.py
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 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 | |
lazyllm.tools.rag.readers.EpubReader
Bases: LazyLLMReaderBase
A file reader for .epub format eBooks.
Inherits from LazyLLMReaderBase, and only needs to implement _load_data. The Document module can automatically use this class to load .epub files.
Note: Reading from fsspec file systems (e.g., remote paths) is not supported in this version. If fs is specified, it will fall back to reading from the local file system.
Returns:
- List[DocNode]: A single node containing all merged chapter content from the EPUB file.
Source code in lazyllm/tools/rag/readers/epubReader.py
lazyllm.tools.rag.readers.HWPReader
Bases: LazyLLMReaderBase
A HWP format file parser. It supports loading from the local filesystem. It extracts body text from the .hwp file and returns it as a list of DocNode objects.
HWP is a proprietary binary document format used primarily in Korea. This reader focuses on extracting the plain text from the body sections of the document.
Parameters:
-
return_trace(bool, default:True) –Whether to enable trace logging. Defaults to
True.
Source code in lazyllm/tools/rag/readers/hwpReader.py
lazyllm.tools.rag.readers.ImageReader
Bases: LazyLLMReaderBase
Module for reading content from image files. Supports keeping the image as base64, parsing text from images using OCR or pretrained vision models, and returns a list of nodes with text and image path.
Parameters:
-
parser_config(Optional[Dict], default:None) –Parser configuration containing the model and processor. Defaults to None. When parse_text=True and parser_config is None, relevant models will be auto-loaded based on text_type.
-
keep_image(bool, default:False) –Whether to keep the image as base64 string. Default is False.
-
parse_text(bool, default:False) –Whether to parse text from the image. Default is False.
-
text_type(str, default:'text') –Type of text parsing. Supports
text(default) andplain_text. Ifplain_text, pytesseract OCR is used; otherwise a pretrained vision encoder-decoder model is used. -
pytesseract_model_kwargs(Optional[Dict], default:None) –Optional arguments passed to pytesseract OCR. Defaults to empty dict.
-
return_trace(bool, default:True) –Whether to record the processing trace. Default is True.
Source code in lazyllm/tools/rag/readers/imageReader.py
lazyllm.tools.rag.readers.IPYNBReader
Bases: LazyLLMReaderBase
Module for reading and parsing Jupyter Notebook (.ipynb) files. Converts the notebook to script text, then splits it by code cells into multiple document nodes or concatenates into a single text node.
Parameters:
-
parser_config(Optional[Dict], default:None) –Reserved parser configuration parameter, currently unused. Defaults to None.
-
concatenate(bool, default:False) –Whether to concatenate all code cells into one text node. Defaults to False (split into multiple nodes).
-
return_trace(bool, default:True) –Whether to record processing trace. Default is True.
Source code in lazyllm/tools/rag/readers/ipynbReader.py
lazyllm.tools.rag.readers.MineruPDFReader
Bases: _OcrReaderBase
Reader for PDF files by calling the Mineru service's API.
Parameters:
-
url(str, default:None) –The complete API endpoint URL for the Mineru service.
-
backend(str, default:None) –Type of parsing engine. Available options: - 'pipeline': Standard processing pipeline - 'vlm-transformers': Vision-language model based on Transformers - 'vlm-vllm-async-engine': Vision-language model based on async VLLM engine Defaults to 'pipeline'.
-
extract_table(bool, default:True) –Whether to extract table content and convert to Markdown format. Defaults to True.
-
extract_formula(bool, default:True) –Whether to extract formula text. - True: Extract as text format (e.g., LaTeX) - False: Keep formulas as images Defaults to True.
-
split_doc(bool, default:True) –If True (default), parses into a
RichDocNodewhich can be used withRichTransformto extract nodes with structural information; if False, parses into a plain textDocNode. -
clean_content(bool, default:True) –Whether to clean redundant content (headers, footers, page numbers, etc.). Defaults to True.
-
post_func(Optional[Callable[[List[DocNode]], Any]], default:None) –Post-processing function that takes a list of DocNodes as input for custom result handling. Defaults to None.
-
api_key(str, default:None) –Static auth token used at initialization.
-
dynamic_auth(bool, default:False) –Whether to enable dynamic auth. When enabled, token is read from globals.config['dynamic_ocr_auth']['mineru'].
-
auth_strategy(AuthStrategy, default:None) –Custom auth injection strategy. Defaults to Bearer token strategy.
Notes
When split_doc=True, returns a RichDocNode; otherwise returns a DocNode. Both cases return a single node.
When split_doc=True, it is strongly recommended to use it with RichTransform, which can extract nodes with structural information and other metadata;
without RichTransform, the parsed nodes will fall back to plain text nodes.
Per-request token: inject via inject_reader_config(ocr_config={'ocr_auth': {'mineru': '...'}}) into
globals.config['dynamic_ocr_auth']; CredentialMixin reads it on each HTTP call.
Static default token: globals['config']['mineru_api_key'] (only when dynamic_auth=False).
OCR service cache is controlled separately via _load_data(..., use_cache=...) (default True).
Algorithm-side DocNode content cache is controlled globally via lazyllm.config['reader_use_cache'].
Examples:
from lazyllm.tools.rag.readers import MineruPDFReader reader = MineruPDFReader("http://0.0.0.0:8888") # Mineru server address nodes = reader("path/to/pdf")
Source code in lazyllm/tools/rag/readers/ocrReader/mineru_pdf_reader.py
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 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 | |
lazyllm.tools.rag.readers.MarkdownReader
Bases: LazyLLMReaderBase
Module for reading and parsing Markdown files. Supports removing hyperlinks and images, and splits Markdown into text segments by headers, returning document nodes.
Parameters:
-
remove_hyperlinks(bool, default:True) –Whether to remove hyperlinks, default is True.
-
remove_images(bool, default:True) –Whether to remove image tags, default is True.
-
return_trace(bool, default:True) –Whether to record processing trace, default is True.
Source code in lazyllm/tools/rag/readers/markdownReader.py
remove_hyperlinks(content)
Remove markdown hyperlinks, converting text to just text.
Parameters:
-
content(str) –Input markdown content.
Returns:
- str: Content with hyperlinks removed, only link text retained.
Source code in lazyllm/tools/rag/readers/markdownReader.py
remove_images(content)
Remove custom image tags of the form ![[...]] from the content.
Parameters:
-
content(str) –Input markdown content.
Returns:
- str: Content with image tags removed.
Source code in lazyllm/tools/rag/readers/markdownReader.py
lazyllm.tools.rag.readers.MboxReader
Bases: LazyLLMReaderBase
Module to parse Mbox email archive files. Reads email messages and formats them into text. Supports limiting the maximum number of messages and custom message formatting.
Parameters:
-
max_count(int, default:0) –Maximum number of emails to read. Default 0 means read all.
-
message_format(str, default:DEFAULT_MESSAGE_FORMAT) –Template string for formatting each message, supports placeholders
{_date},{_from},{_to},{_subject}, and{_content}. -
return_trace(bool, default:True) –Whether to record processing trace. Default is True.
Source code in lazyllm/tools/rag/readers/mboxreader.py
lazyllm.tools.SqlCall
Bases: ModuleBase
SqlCall is a class that extends ModuleBase and provides an interface for generating and executing SQL queries using a language model (LLM). It is designed to interact with a SQL database, extract SQL queries from LLM responses, execute those queries, and return results or explanations.
Parameters:
-
llm–A language model to be used for generating and interpreting SQL queries and explanations.
-
sql_manager(DBManager) –Database manager instance containing connection and description information
-
sql_examples(str, default:'') –SQL example strings for prompt engineering. Defaults to empty string
-
sql_post_func(Callable, default:None) –Function for post-processing generated SQL statements. Defaults to
None -
use_llm_for_sql_result(bool, default:True) –Whether to use LLM to explain SQL execution results. Defaults to
True -
return_trace(bool, default:False) –Whether to return execution trace information. Defaults to
False
Examples:
>>> # First, run SqlManager example
>>> import lazyllm
>>> from lazyllm.tools import SQLManger, SqlCall
>>> sql_tool = SQLManger("personal.db")
>>> sql_llm = lazyllm.OnlineChatModule(model="gpt-4o", source="openai", base_url="***")
>>> sql_call = SqlCall(sql_llm, sql_tool, use_llm_for_sql_result=True)
>>> print(sql_call("去年一整年销售额最多的员工是谁?"))
Source code in lazyllm/tools/sql_call/sql_call.py
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 | |
extract_sql_from_response(str_response)
Extract SQL (or MongoDB pipeline) statement from the raw LLM response.
Parameters:
-
str_response(str) –Raw text returned by the LLM which may contain code fences.
Returns:
- tuple[bool, str]: A tuple where the first element indicates whether extraction succeeded, and the second is the cleaned or original content. If sql_post_func is provided, it is applied to the extracted content.
Source code in lazyllm/tools/sql_call/sql_call.py
sql_explain_prompt_hook(input=None, history=[], tools=None, label=None)
Hook to prepare the prompt for explaining the execution result of a database query.
Parameters:
-
input(Union[str, List, Dict[str, str], None], default:None) –A list containing the query and its result.
-
history(List[Union[List[str], Dict[str, Any]]], default:[]) –Conversation history.
-
tools(Union[List[Dict[str, Any]], None], default:None) –Available tool descriptions.
-
label(Union[str, None], default:None) –Optional label for the prompt.
Returns:
- Tuple: A tuple containing the formatted prompt dict (history_info, desc, query, result, explain_query), history, tools, and label.
Source code in lazyllm/tools/sql_call/sql_call.py
sql_query_promt_hook(input=None, history=None, tools=None, label=None)
Hook to prepare the prompt inputs for generating a database query from user input.
Parameters:
-
input(Union[str, List, Dict[str, str], None], default:None) –The user's natural language query.
-
history(List[Union[List[str], Dict[str, Any]]], default:None) –Conversation history.
-
tools(Union[List[Dict[str, Any]], None], default:None) –Available tool descriptions.
-
label(Union[str, None], default:None) –Optional label for the prompt.
Returns:
- Tuple: A tuple containing the formatted prompt dict (with current_date, db_type, desc, user_query), history, tools, and label.
Source code in lazyllm/tools/sql_call/sql_call.py
lazyllm.tools.rag.default_index.DefaultIndex
Bases: IndexBase
Default index implementation responsible for querying, updating, and removing document nodes in the underlying store based on embedding or text similarity. Supports multiple similarity metrics and performs embedding computation and node updates when required.
Parameters:
-
embed(Dict[str, Callable]) –Mapping of embedding names to functions that generate vector representations from strings.
-
store(StoreBase) –Underlying storage to persist and retrieve
DocNodeobjects. -
**kwargs–Reserved for future extension.
Returns:
- DefaultIndex: The default index instance.
Source code in lazyllm/tools/rag/default_index.py
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 | |
query(query, group_name, similarity_name, similarity_cut_off, topk, embed_keys=None, filters=None, **kwargs)
Perform a query against the index, supporting both embedding-based and text-based similarity modes. Filters and ranks nodes according to similarity functions and cutoffs.
Parameters:
-
query(str) –The raw query string.
-
group_name(str) –The group name from which to retrieve nodes.
-
similarity_name(str) –Name of the similarity metric to use; must be registered in registered_similarities.
-
similarity_cut_off(Union[float, Dict[str, float]]) –Similarity threshold(s) used to filter results; can be a single float or a mapping per embedding.
-
topk(int) –Maximum number of candidates to keep per similarity channel before final filtering.
-
embed_keys(Optional[List[str]], default:None) –Specific embedding keys to use; defaults to all available if not provided.
-
filters(Optional[Dict[str, List]], default:None) –Additional pre-filters applied to nodes before similarity computation.
-
**kwargs–Extra keyword arguments forwarded to the similarity function.
Returns
- list: List[DocNode]: Deduplicated list of document nodes passing similarity and cutoff criteria.
Source code in lazyllm/tools/rag/default_index.py
remove(uids, group_name=None)
Remove nodes with specified UIDs from the index. Optionally scoped to a group. This is a no-op placeholder and should be implemented in concrete usage.
Parameters:
-
uids(List[str]) –List of unique IDs of nodes to remove.
-
group_name(Optional[str], default:None) –Optional group name to scope the removal.
Source code in lazyllm/tools/rag/default_index.py
update(nodes)
Update the index with the given list of document nodes. This is a placeholder implementation and should be provided/extended in concrete usage.
Parameters:
-
nodes(List[DocNode]) –Document nodes to add or update in the index.
Source code in lazyllm/tools/rag/default_index.py
lazyllm.tools.rag.rerank.Reranker
Bases: ModuleBase, _PostProcess
Initializes a Rerank module for postprocessing and reranking of nodes (documents). This constructor initializes a Reranker module that configures a reranking process based on a specified reranking type. It allows for the dynamic selection and instantiation of reranking kernels (algorithms) based on the type and provided keyword arguments.
Parameters:
-
name(str, default:'ModuleReranker') –The type of reranker used for the postprocessing and reranking process. Defaults to 'ModuleReranker'.
-
target(str, default:None) –Deprecated parameter, only used to notify users.
-
output_format(Optional[str], default:None) –Specifies the output format. Defaults to None. Optional values include 'content' and 'dict'. - 'content' means the output is in string format. - 'dict' means the output is a dictionary.
-
join(Union[bool, str], default:False) –Determines whether to join the top-k output nodes. - When
output_formatis 'content': - If set to True, returns a single long string. - If set to False, returns a list of strings, each representing one node’s content. - Whenoutput_formatis 'dict': - Joining is not supported;joindefaults to False. - Returns a dictionary with three keys: 'content', 'embedding', and 'metadata'. -
kwargs–Additional keyword arguments passed to the reranker upon instantiation.
Detailed explanation of reranker types
-
Reranker: Instantiates a
SentenceTransformerRerankreranker with a list of document nodes and a query. -
KeywordFilter: This registered reranking function instantiates a KeywordNodePostprocessor with specified required and excluded keywords. It filters nodes based on the presence or absence of these keywords.
Examples:
>>> import lazyllm
>>> from lazyllm.tools import Document, Reranker, Retriever, DocNode
>>> m = lazyllm.OnlineEmbeddingModule()
>>> documents = Document(dataset_path='/path/to/user/data', embed=m, manager=False)
>>> retriever = Retriever(documents, group_name='CoarseChunk', similarity='bm25', similarity_cut_off=0.01, topk=6)
>>> reranker = Reranker(DocNode(text=user_data),query="user query")
>>> ppl = lazyllm.ActionModule(retriever, reranker)
>>> ppl.start()
>>> print(ppl("user query"))
Source code in lazyllm/tools/rag/rerank.py
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 | |
register_reranker(func=None, batch=False)
classmethod
A class decorator factory method that provides a flexible mechanism for registering custom reranking algorithms to the Reranker class.
Parameters:
-
func(Optional[Callable], default:None) –The reranking function or class to register. This can be omitted when using decorator syntax (@).
-
batch(bool, default:False) –Whether to process nodes in batches. Defaults to False, meaning nodes are processed individually.
Examples:
@Reranker.register_reranker
def my_reranker(node: DocNode, **kwargs):
return node.score * 0.8 # 自定义分数计算
Source code in lazyllm/tools/rag/rerank.py
lazyllm.tools.rag.retriever.Retriever
Bases: _RetrieverBase, _PostProcess
Create a retrieval module for document querying and retrieval. This constructor initializes a retrieval module that configures the document retrieval process based on the specified similarity metric.
Parameters:
-
doc(object) –An instance of the document module. The document module can be a single instance or a list of instances. If it is a single instance, it means searching for a single Document, and if it is a list of instances, it means searching for multiple Documents.
-
group_name(str) –The name of the node group on which to perform the retrieval.
-
similarity(Optional[str], default:None) –The similarity function to use for setting up document retrieval. Defaults to 'dummy'. Candidates include ["bm25", "bm25_chinese", "cosine"].
-
similarity_cut_off(Union[float, Dict[str, float]], default:float('-inf')) –Discard the document when the similarity is below the specified value. In a multi-embedding scenario, if you need to specify different values for different embeddings, you need to specify them in a dictionary, where the key indicates which embedding is specified and the value indicates the corresponding threshold. If all embeddings use the same threshold, you only need to specify one value.
-
index(str, default:'default') –The type of index to use for document retrieval. Currently, only 'default' is supported.
-
topk(int, default:6) –The number of documents to retrieve with the highest similarity.
-
embed_keys(Optional[List[str]], default:None) –Indicates which embeddings are used for retrieval. If not specified, all embeddings are used for retrieval.
-
target(Optional[str], default:None) –The name of the target document group for result conversion
-
output_format(Optional[str], default:None) –Represents the output format, with a default value of None. Optional values include 'content' and 'dict', where 'content' corresponds to a string output format and 'dict' corresponds to a dictionary.
-
join(Union[bool, str], default:False) –Determines whether to concatenate the output of k nodes - when output format is 'content', setting True returns a single concatenated string while False returns a list of strings (each corresponding to a node's text content); when output format is 'dict', joining is unsupported (join defaults to False) and the output will be a dictionary containing 'content', 'embedding' and 'metadata' keys.
The group_name has three built-in splitting strategies, all of which use SentenceSplitter for splitting, with the difference being in the chunk size:
- CoarseChunk: Chunk size is 1024, with an overlap length of 100
- MediumChunk: Chunk size is 256, with an overlap length of 25
- FineChunk: Chunk size is 128, with an overlap length of 12
Also, Image is available for group_name since LazyLLM supports image embedding and retrieval.
Examples:
>>> import lazyllm
>>> from lazyllm.tools import Retriever, Document, SentenceSplitter
>>> m = lazyllm.OnlineEmbeddingModule()
>>> documents = Document(dataset_path='/path/to/user/data', embed=m, manager=False)
>>> rm = Retriever(documents, group_name='CoarseChunk', similarity='bm25', similarity_cut_off=0.01, topk=6)
>>> rm.start()
>>> print(rm("user query"))
>>> m1 = lazyllm.TrainableModule('bge-large-zh-v1.5').start()
>>> document1 = Document(dataset_path='/path/to/user/data', embed={'online':m , 'local': m1}, manager=False)
>>> document1.create_node_group(name='sentences', transform=SentenceSplitter, chunk_size=1024, chunk_overlap=100)
>>> retriever = Retriever(document1, group_name='sentences', similarity='cosine', similarity_cut_off=0.4, embed_keys=['local'], topk=3)
>>> print(retriever("user query"))
>>> document2 = Document(dataset_path='/path/to/user/data', embed={'online':m , 'local': m1}, manager=False)
>>> document2.create_node_group(name='sentences', transform=SentenceSplitter, chunk_size=512, chunk_overlap=50)
>>> retriever2 = Retriever([document1, document2], group_name='sentences', similarity='cosine', similarity_cut_off=0.4, embed_keys=['local'], topk=3)
>>> print(retriever2("user query"))
>>>
>>> filters = {
>>> "author": ["A", "B", "C"],
>>> "public_year": [2002, 2003, 2004],
>>> }
>>> document3 = Document(dataset_path='/path/to/user/data', embed={'online':m , 'local': m1}, manager=False)
>>> document3.create_node_group(name='sentences', transform=SentenceSplitter, chunk_size=512, chunk_overlap=50)
>>> retriever3 = Retriever([document1, document3], group_name='sentences', similarity='cosine', similarity_cut_off=0.4, embed_keys=['local'], topk=3)
>>> print(retriever3(query="user query", filters=filters))
>>> document4 = Document(dataset_path='/path/to/user/data', embed=lazyllm.TrainableModule('siglip'))
>>> retriever4 = Retriever(document4, group_name='Image', similarity='cosine')
>>> nodes = retriever4("user query")
>>> print([node.get_content() for node in nodes])
>>> document5 = Document(dataset_path='/path/to/user/data', embed=m, manager=False)
>>> rm = Retriever(document5, group_name='CoarseChunk', similarity='bm25_chinese', similarity_cut_off=0.01, topk=3, output_format='content')
>>> rm.start()
>>> print(rm("user query"))
>>> document6 = Document(dataset_path='/path/to/user/data', embed=m, manager=False)
>>> rm = Retriever(document6, group_name='CoarseChunk', similarity='bm25_chinese', similarity_cut_off=0.01, topk=3, output_format='content', join=True)
>>> rm.start()
>>> print(rm("user query"))
>>> document7 = Document(dataset_path='/path/to/user/data', embed=m, manager=False)
>>> rm = Retriever(document7, group_name='CoarseChunk', similarity='bm25_chinese', similarity_cut_off=0.01, topk=3, output_format='dict')
>>> rm.start()
>>> print(rm("user query"))
Source code in lazyllm/tools/rag/retriever.py
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 | |
lazyllm.tools.rag.retriever.TempDocRetriever
Bases: TempRetriever
A temporary document retriever that inherits from TempRetriever, used for quickly processing temporary files and performing retrieval tasks.
Parameters:
-
embed(Callable, default:None) –The embedding function.
-
output_format(Optional[str], default:None) –The format of the output result (e.g., JSON). Optional, defaults to None.
-
join(Union[bool, str], default:False) –Whether to merge multiple result segments (set to True or specify a separator like "
").
Examples:
>>> import lazyllm
>>> from lazyllm.tools import TempDocRetriever, Document, SentenceSplitter
>>> retriever = TempDocRetriever(output_format="text", join="
---------------
")
retriever.create_node_group(transform=lambda text: [s.strip() for s in text.split("。") if s] )
retriever.add_subretriever(group=Document.MediumChunk, topk=3)
files = ["/path/to/file.txt"]
results = retriever.forward(files, "什么是机器学习?")
print(results)
Source code in lazyllm/tools/rag/retriever.py
lazyllm.tools.rag.retriever.UrlDocument
Bases: ModuleBase
UrlDocument class inherits from ModuleBase, used to manage remote document resources by specifying a URL and a name. Internally delegates calls to lazyllm's UrlModule, supporting document find, retrieve, and querying active node groups.
Parameters:
-
url(str) –Access URL for the remote document resource.
-
name(str, default:None) –Current document group name used to identify the document group.
Source code in lazyllm/tools/rag/document.py
929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 | |
find(target)
Creates a partially applied function to find a specified target within the current document group.
Parameters:
-
target(str) –The target identifier to find.
Returns:
- Callable: A partially applied function that executes the find operation when called.
Source code in lazyllm/tools/rag/document.py
get_nodes(uids=None, doc_ids=None, group=None, kb_id=None, numbers=None, limit=None, offset=0, return_total=False, sort_by_number=False)
Get remote document nodes by criteria.
Parameters:
-
uids(Optional[List[str]], default:None) –List of node uids to fetch.
-
doc_ids(Optional[Set], default:None) –Set of document ids to filter by.
-
group(Optional[str], default:None) –Node group name.
-
kb_id(Optional[str], default:None) –Knowledge base id.
-
numbers(Optional[Set], default:None) –Set of node numbers.
Returns:
- List[DocNode]: Matched nodes.
Source code in lazyllm/tools/rag/document.py
get_window_nodes(node, span=(-5, 5), merge=False)
Get window nodes around a target node in a remote document.
Parameters:
-
node(DocNode) –Target node.
-
span(tuple[int, int], default:(-5, 5)) –Window range based on relative offsets of node.number.
-
merge(bool, default:False) –Whether to merge window nodes into a single node.
Returns:
- Union[List[DocNode], DocNode]: Window nodes list or a merged node.
Source code in lazyllm/tools/rag/document.py
keyword_search(group, keyword, doc_id='', kb_id=None, phrase=True, sort_by='score', size=10, file_name=None)
Perform exact keyword matching in a remote document.
Same interface as :meth:Document.keyword_search, proxied via RPC to the remote Document service.
Parameters:
-
group(str) –Node group name.
-
keyword(str) –Keyword to match.
-
doc_id(str, default:'') –Target document ID, defaults to empty string. Mutually exclusive with
file_name; if both are given,file_nametakes priority. -
kb_id(Optional[str], default:None) –Knowledge-base filter.
-
phrase(bool, default:True) –True for exact substring match, False for word-level match.
-
sort_by(str, default:'score') –"score"sorts by relevance,"number"sorts by document order. -
size(int, default:10) –Maximum number of hits.
-
file_name(Optional[str], default:None) –Filter by file name. Mutually exclusive with
doc_id; when set,doc_idis ignored.
Returns:
-
–
List[dict]: Matched segment list.
Source code in lazyllm/tools/rag/document.py
lazyllm.tools.rag.doc_service.DocServer
Bases: ModuleBase
Primary entry point of the document service.
DocServer manages document upload/add/reparse/delete flows, task tracking, knowledge-base management,
chunk inspection, and cross-kb transfer. It is the recommended replacement for the legacy DocManager /
DocListManager APIs.
Parameters:
-
port(Optional[int], default:None) –Local service port when starting an in-process server.
-
url(Optional[str], default:None) –Existing doc_service URL. When provided, the instance works as a remote client.
-
parser_url(Optional[str], default:None) –Parsing service URL used by the local doc_service instance.
-
db_config(Optional[Dict[str, Any]], default:None) –Metadata database configuration for doc_service.
-
parser_db_config(Optional[Dict[str, Any]], default:None) –Parsing task database configuration for the parsing service.
-
parser_poll_interval(float, default:0.05) –Poll interval used by local parser coordination.
-
storage_dir(Optional[str], default:None) –Local storage directory for uploaded files.
-
callback_url(Optional[str], default:None) –Callback URL used to receive parsing task updates.
-
launcher–Launcher used to start local services.
Source code in lazyllm/tools/rag/doc_service/doc_server.py
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 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 | |
add(request)
Add existing local files through the /v1/docs/add endpoint.
Use this method when the file paths are already accessible on the DocServer host. The request body is an
AddRequest containing kb_id and items. Each item can provide file_path,
optional doc_id, and optional metadata.
Returns:
Standard API response. data["items"] contains the accepted doc_id and asynchronous task_id.
Source code in lazyllm/tools/rag/doc_service/doc_server.py
build_openapi_app(title='LazyLLM DocService API', version='1.0.0')
classmethod
Build the FastAPI application used for OpenAPI export.
Source code in lazyllm/tools/rag/doc_service/doc_server.py
build_openapi_schema(title='LazyLLM DocService API', version='1.0.0')
classmethod
Generate the OpenAPI schema for doc_service.
Source code in lazyllm/tools/rag/doc_service/doc_server.py
cancel_task(task_id)
Cancel a waiting task through the /v1/tasks/cancel endpoint.
Parameters:
-
task_id(str) –Task ID to cancel.
Returns: Standard API response indicating whether the task was canceled successfully.
Source code in lazyllm/tools/rag/doc_service/doc_server.py
create_kb(kb_id, display_name=None, description=None, owner_id=None, meta=None, algo_id='__default__')
Create a new knowledge base.