Tools
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.Document
Bases: ModuleBase, BuiltinGroups
Initialize a document module with an optional user interface.
This constructor initializes a document module that can have an optional user interface. If the user interface is enabled, it also provides a UI to manage the document operation interface and offers a web page for user interface interaction.
Parameters:
-
dataset_path(str, default:None) –The path to the dataset directory. This directory should contain the documents to be managed by the document module.
-
embed(Optional[Union[Callable, Dict[str, Callable]]], default:None) –The object used to generate document embeddings. If you need to generate multiple embeddings for the text, you need to specify multiple embedding models in a dictionary format. The key identifies the name corresponding to the embedding, and the value is the corresponding embedding model.
-
create_ui(bool, default:False) –[Deprecated] Whether to create a user interface. Use 'manager' parameter instead.
-
manager(bool, default:False) –A flag indicating whether to create a user interface for the document module. Defaults to False.
-
server(Union[bool, int], default:False) –Server configuration. True for default server, False for no server, or an integer port number for custom server.
-
name(Optional[str], default:None) –Name identifier for this document collection. Required for cloud services.
-
launcher(optional, default:None) –An object or function responsible for launching the server module. If not provided, the default asynchronous launcher from
lazyllm.launchersis used (sync=False). -
doc_fields(optional, default:None) –Configure the fields that need to be stored and retrieved along with their corresponding types (currently only used by the Milvus backend).
-
doc_files(Optional[List[str]], default:None) –List of temporary document files (alternative to dataset_path).When used, dataset_path must be None and only map store is supported.
-
store_conf(optional, default:None) –Configure which storage backend, MapStore is the default choice.
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
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 | |
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", create_ui=False)
>>> doc2 = Document(dataset_path="your_files_path", create_ui=False)
>>> 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
create_node_group(name=None, *, transform, parent=LAZY_ROOT_NAME, trans_node=None, num_workers=0, display_name=None, group_type=NodeGroupType.CHUNK, **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, 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.
-
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)
Source code in lazyllm/tools/rag/document.py
find_children(target)
Find the child nodes of the specified node.
Parameters:
-
group(str) –The name of the node group for which to find the children.
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 specified node.
Parameters:
-
group(str) –The name of the node group for which to find the parent.
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
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", create_ui=False)
>>> doc2 = Document(dataset_path="your_files_path", create_ui=False)
>>> 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
lazyllm.tools.rag.store.ChromadbStore
Bases: LazyLLMStoreBase
Source code in lazyllm/tools/rag/store/vector/chroma_store.py
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 | |
lazyllm.tools.rag.store.MilvusStore
Bases: LazyLLMStoreBase
Source code in lazyllm/tools/rag/store/vector/milvus_store.py
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 | |
lazyllm.tools.rag.readers.ReaderBase
Bases: ModuleBase
Base document reader class that provides basic interfaces for document loading. Inherits from ModuleBase and uses LazyLLMRegisterMetaClass as metaclass.
Parameters:
-
return_trace(bool, default:True) –Whether to return processing trace information. Defaults to True.
Notes: - Provides both lazy loading and regular loading methods - Subclasses need to implement _lazy_load_data method - Supports batch document processing - Automatically converts to standardized DocNode format
Examples:
```python
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
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.
-
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.
-
return_trace(bool, default:True) –Whether to return the processing trace.
Source code in lazyllm/tools/rag/readers/pandasReader.py
lazyllm.tools.rag.readers.PDFReader
Bases: LazyLLMReaderBase
Reader for extracting text content from PDF files.
Parameters:
-
return_full_document(bool, default:False) –Whether to merge the entire PDF into a single document node. If False, each page becomes a separate node.
-
return_trace(bool, default:True) –Whether to return the processing trace. Default is True.
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) –"PostgreSQL","SQLite", "MySQL", "MSSQL". Note that when the type is "SQLite", db_name is a file path or ":memory:"
-
user(str) –Username for connection
-
password(str) –Password for connection
-
host(str) –Hostname or IP
-
port(int) –Port number
-
db_name(str) –Name of the database
-
**options_str(str, default:None) –Options represented in the format k1=v1&k2=v2
Source code in lazyllm/tools/sql/sql_manager.py
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 | |
check_connection()
Check the current connection status of the SqlManagerBase.
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
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 the SQL script without return and submit changes.
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_session()
This is a context manager that creates and returns a database session, yields it for use, and then automatically commits or rolls back changes and closes the session when done.
Returns:
- sqlalchemy.orm.Session: sqlalchemy database session
Source code in lazyllm/tools/sql/sql_manager.py
get_table_orm_class(table_name)
Return the sqlalchemy orm class corresponding to the given table name. Combine with get_session to perform orm operations.
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
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.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
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.
Args:
func (Optional[Callable]): The reranking function or class to register. This can be omitted when using decorator syntax (@).
batch (bool): 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 basic interfaces for document loading. Inherits from ModuleBase and uses LazyLLMRegisterMetaClass as metaclass.
Parameters:
-
return_trace(bool, default:True) –Whether to return processing trace information. Defaults to True.
Notes: - Provides both lazy loading and regular loading methods - Subclasses need to implement _lazy_load_data method - Supports batch document processing - Automatically converts to standardized DocNode format
Examples:
```python
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
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
lazyllm.tools.rag.doc_to_db.DocInfoSchemaItem
Bases: TypedDict
Definition of a single field in the document information schema.
Parameters:
-
key(str) –The name of the field.
-
desc(str) –The description of the field's meaning.
-
type(str) –The data type of the field.
Source code in lazyllm/tools/rag/doc_to_db/doc_analysis.py
lazyllm.tools.rag.doc_to_db.DocGenreAnalyser
Used to analyze the genre/type of documents, such as contracts, resumes, invoices, etc. It reads the document content and uses a language model to classify its type.
Parameters:
-
maximum_doc_num(int, default:3) –Maximum number of documents to analyze, default is 3.
Examples:
>>> import lazyllm
>>> from lazyllm.components.doc_info_extractor import DocGenreAnalyser
>>> from lazyllm import OnlineChatModule
>>> m = OnlineChatModule(source="openai")
>>> analyser = DocGenreAnalyser()
>>> genre = analyser.analyse_doc_genre(m, "path/to/document.txt")
>>> print(genre)
contract
Source code in lazyllm/tools/rag/doc_to_db/doc_analysis.py
lazyllm.tools.rag.doc_to_db.DocInfoSchemaAnalyser
Used to extract key-value schema from documents, such as field names, descriptions, and data types. Useful for building structured information extraction templates.
Parameters:
-
maximum_doc_num(int, default:3) –Maximum number of documents to be used for generating schema, default is 3.
Examples:
>>> from lazyllm.components.doc_info_extractor import DocInfoSchemaAnalyser
>>> from lazyllm import OnlineChatModule
>>> analyser = DocInfoSchemaAnalyser()
>>> m = OnlineChatModule(source="openai")
>>> schema = analyser.analyse_info_schema(m, "contract", ["doc1.txt", "doc2.txt"])
>>> print(schema)
[{'key': 'party_a', 'desc': 'The first party', 'type': 'str'}, ...]
Source code in lazyllm/tools/rag/doc_to_db/doc_analysis.py
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 | |
analyse_info_schema(llm, doc_type, doc_paths)
Method for analyzing document information schema, used to extract structural definitions of key information fields from documents of a specified type.
Parameters:
-
llm(Union[OnlineChatModule, TrainableModule]) –LLM model used to generate information schema
-
doc_type(str) –Document type, used to guide the LLM in generating corresponding information schema
-
doc_paths(list[str]) –List of document paths, used as information sources for analysis
Returns:
- DocInfoSchema: List of schema containing key information field definitions, each field includes key, desc, and type attributes
Source code in lazyllm/tools/rag/doc_to_db/doc_analysis.py
lazyllm.tools.rag.doc_to_db.DocInfoExtractor
Extracts specific values for key fields from a document according to a provided schema. Returns a dictionary of key-value pairs.
Examples:
>>> from lazyllm.components.doc_info_extractor import DocInfoExtractor
>>> from lazyllm import OnlineChatModule
>>> extractor = DocInfoExtractor()
>>> m = OnlineChatModule(source="openai")
>>> schema = [{"key": "party_a", "desc": "Party A name", "type": "str"}]
>>> info = extractor.extract_doc_info(m, "contract.txt", schema)
>>> print(info)
{'party_a': 'ABC Corp'}
Source code in lazyllm/tools/rag/doc_to_db/doc_analysis.py
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 | |
extract_doc_info(llm, doc_path, info_schema, extra_desc='')
Extracts specific key information values from a document according to a provided schema.
This method uses a large language model to analyze document content and extract corresponding information values based on predefined field structure, returning a key-value dictionary.
Parameters:
-
llm(Union[OnlineChatModule, TrainableModule]) –The large language model used for document information extraction.
-
doc_path(str) –Path to the document to be analyzed.
-
info_schema(DocInfoSchema) –Field structure definition containing the information to be extracted.
-
extra_desc(str, default:'') –Additional description information to guide the extraction process. Defaults to empty string.
Returns:
-
dict(dict) –Extracted key information dictionary with field names as keys and corresponding information values as values.
Source code in lazyllm/tools/rag/doc_to_db/doc_analysis.py
lazyllm.tools.rag.doc_to_db.DocInfoExtractor
Extracts specific values for key fields from a document according to a provided schema. Returns a dictionary of key-value pairs.
Examples:
>>> from lazyllm.components.doc_info_extractor import DocInfoExtractor
>>> from lazyllm import OnlineChatModule
>>> extractor = DocInfoExtractor()
>>> m = OnlineChatModule(source="openai")
>>> schema = [{"key": "party_a", "desc": "Party A name", "type": "str"}]
>>> info = extractor.extract_doc_info(m, "contract.txt", schema)
>>> print(info)
{'party_a': 'ABC Corp'}
Source code in lazyllm/tools/rag/doc_to_db/doc_analysis.py
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 | |
extract_doc_info(llm, doc_path, info_schema, extra_desc='')
Extracts specific key information values from a document according to a provided schema.
This method uses a large language model to analyze document content and extract corresponding information values based on predefined field structure, returning a key-value dictionary.
Parameters:
-
llm(Union[OnlineChatModule, TrainableModule]) –The large language model used for document information extraction.
-
doc_path(str) –Path to the document to be analyzed.
-
info_schema(DocInfoSchema) –Field structure definition containing the information to be extracted.
-
extra_desc(str, default:'') –Additional description information to guide the extraction process. Defaults to empty string.
Returns:
-
dict(dict) –Extracted key information dictionary with field names as keys and corresponding information values as values.
Source code in lazyllm/tools/rag/doc_to_db/doc_analysis.py
lazyllm.tools.rag.doc_to_db.DocToDbProcessor
Used to extract information from documents and export it to a database.
This class analyzes document topics, extracts schema structure, pulls out key information, and saves it into a database table.
Parameters:
-
sql_manager(SqlManager) –The SQL management module.
-
doc_table_name(str, default:'lazyllm_doc_elements') –The table name to store document fields. Default is
lazyllm_doc_elements.
Note
- If the table already exists, it checks and avoids redundant creation.
- Use
reset_doc_info_schemato reset the schema if necessary.
Source code in lazyllm/tools/rag/doc_to_db/doc_processor.py
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 | |
analyze_info_schema_by_llm(llm, doc_paths, doc_topic='')
Infer structured database information using a large language model from document nodes.
Parameters:
-
nodes(list[DocNode]) –List of document nodes.
Returns:
-
dict(DocInfoSchema) –The inferred database schema, including table names, fields, and relationships.
Source code in lazyllm/tools/rag/doc_to_db/doc_processor.py
extract_info_from_docs(llm, doc_paths, extra_desc='')
Extract structured database-related information from documents.
This function uses embedding and retrieval techniques to identify relevant text fragments in the provided documents for schema generation.
Parameters:
-
docs(list[DocNode]) –List of input documents.
-
num_nodes(int) –Number of text fragments to retrieve. Default is 10.
Returns:
-
List[dict]–list[DocNode]: The relevant extracted document nodes.
Source code in lazyllm/tools/rag/doc_to_db/doc_processor.py
lazyllm.tools.rag.doc_to_db.extract_db_schema_from_files(file_paths, llm)
Extract the schema information from documents using a given LLM.
Parameters:
-
file_paths(List[str]) –Paths of the documents to analyze.
-
llm(Union[OnlineChatModule, TrainableModule]) –A chat-supported LLM module.
Returns:
-
DocInfoSchema(DocInfoSchema) –The extracted field structure schema.
Examples:
>>> import lazyllm
>>> from lazyllm.components.document_to_db import extract_db_schema_from_files
>>> llm = lazyllm.OnlineChatModule()
>>> file_paths = ["doc1.pdf", "doc2.pdf"]
>>> schema = extract_db_schema_from_files(file_paths, llm)
>>> print(schema)
Source code in lazyllm/tools/rag/doc_to_db/doc_processor.py
lazyllm.tools.rag.readers.DocxReader
Bases: LazyLLMReaderBase
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
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.MagicPDFReader
Module to parse PDF content via the MagicPDF service. Supports file upload or URL-based parsing, with a callback to process the parsed elements into document nodes.
Parameters:
-
magic_url(str) –The MagicPDF service API URL.
-
callback(Optional[Callable[[List[dict], Path, dict], List[DocNode]]], default:None) –A callback function that takes parsed element list, file path, and extra info, returns a list of DocNode. Defaults to merging all text into a single node.
-
upload_mode(bool, default:False) –Whether to use file upload mode for the API call. Default is False, meaning JSON request with file path.
Source code in lazyllm/tools/rag/readers/magic_pdf_reader.py
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 | |
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(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(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(SqlManager) –An instance of SqlManager that handles interaction with the SQL database.
-
sql_examples(str, default:'') –An example of converting natural language represented by a JSON string into an SQL statement, formatted as: [{"Question": "Find the names of people in the same department as Smith", "Answer": "SELECT...;"}]
-
use_llm_for_sql_result(bool, default:True) –Default is True. If set to False, the module will only output raw SQL results in JSON without further processing.
-
return_trace(bool, default:False) –If set to True, the results will be recorded in the trace. 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 | |
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]–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 using embedding or text similarity. Supports multiple similarity metrics and performs embedding computation and node updates when needed.
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 DocNode objects.
-
**kwargs–Reserved for future extension.
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 | |
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.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
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.
Args:
func (Optional[Callable]): The reranking function or class to register. This can be omitted when using decorator syntax (@).
batch (bool): 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.Retriever
Bases: ModuleBase, _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
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 | |
lazyllm.tools.rag.retriever.TempDocRetriever
Bases: ModuleBase, _PostProcess
A temporary document retriever that inherits from ModuleBase and _PostProcess, 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 = ["机器学习是AI的核心领域。深度学习是其重要分支。"]
results = retriever.forward(files, "什么是机器学习?")
print(results)
Source code in lazyllm/tools/rag/retriever.py
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 | |
add_subretriever(group, **kwargs)
Add a sub-retriever with search configuration.
Parameters:
-
group(str) –Target node group name.
-
**kwargs–Retriever parameters (e.g., similarity='cosine').
Returns:
- self: For method chaining.
Source code in lazyllm/tools/rag/retriever.py
create_node_group(name=None, *, transform, parent=LAZY_ROOT_NAME, trans_node=None, num_workers=0, **kwargs)
Create a node group with specific processing pipeline.
Parameters:
-
name(str, default:None) –Name of the node group. Auto-generated if None.
-
transform(Callable) –Function to process documents in this group.
-
parent(str, default:LAZY_ROOT_NAME) –Parent group name. Defaults to root group.
-
trans_node(bool, default:None) –Whether to transform nodes. Inherits from parent if None.
-
num_workers(int, default:0) –Parallel workers for processing. Default 0 (sequential).
-
**kwargs–Additional group parameters.
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
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
lazyllm.tools.rag.DocManager
Bases: ModuleBase
The DocManager class manages document lists and related operations, providing APIs for uploading, deleting, and grouping documents.
Parameters:
-
dlm(DocListManager) –Document list manager responsible for handling document-related operations.
Source code in lazyllm/tools/rag/doc_manager.py
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 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 | |
add_files(request)
Batch add files.
Parameters:
-
files(List[UploadFile]) –List of uploaded files.
-
group_name(str) –Target knowledge base group name; if empty, files are not added to any group.
-
metadatas(Optional[str]) –Metadata of the files in JSON format.
Returns:
- BaseResponse: Returns a list of unique file IDs corresponding to all input files, including newly added and existing ones. In case of exceptions, returns error codes and exception information.
Source code in lazyllm/tools/rag/doc_manager.py
add_files_to_group(files, group_name, override=False, metadatas=None, user_path=None)
An endpoint to upload files and directly add them to a specified group.
Parameters:
-
files(List[UploadFile]) –List of files to upload.
-
group_name(str) –Name of the group to add the files to.
-
override(bool, default:False) –Whether to overwrite existing files. Default is False.
-
metadatas(Optional[str], default:None) –Metadata for the files in JSON format.
-
user_path(Optional[str], default:None) –User-defined path for file uploads.
Returns:
- BaseResponse: Operation result and file IDs.
Source code in lazyllm/tools/rag/doc_manager.py
add_files_to_group_by_id(request)
An endpoint to add files to a specific group by file IDs.
Parameters:
-
request(FileGroupRequest) –Request containing file IDs and group name.
Returns:
- BaseResponse: Operation result.
Source code in lazyllm/tools/rag/doc_manager.py
add_metadata(add_metadata_request)
An endpoint to add or update metadata for specified documents.
Parameters:
-
add_metadata_request(AddMetadataRequest) –Request containing list of document IDs and key-value metadata.
Returns:
- BaseResponse: Operation result information.
Source code in lazyllm/tools/rag/doc_manager.py
delete_files(request)
An endpoint to delete specified files.
Parameters:
-
request(FileGroupRequest) –Request containing file IDs and group name.
Returns:
- BaseResponse: Deletion operation result.
Source code in lazyllm/tools/rag/doc_manager.py
delete_files_from_group(request)
An endpoint to delete specified files in a group.
Parameters:
-
request(FileGroupRequest) –Request containing a list of file IDs and the group name.
Returns:
- BaseResponse: Deletion operation result.
Source code in lazyllm/tools/rag/doc_manager.py
delete_metadata_item(del_metadata_request)
An endpoint to delete metadata fields or field values from specified documents.
Parameters:
-
del_metadata_request(DeleteMetadataRequest) –Request containing list of document IDs, field names, and/or deletion rules.
Returns:
- BaseResponse: Deletion operation result.
Source code in lazyllm/tools/rag/doc_manager.py
document()
An endpoint to redirect to the default documentation page.
Returns:
- RedirectResponse: Redirects to the
/docspage.
Source code in lazyllm/tools/rag/doc_manager.py
list_files(limit=None, details=True, alive=None)
An endpoint to list uploaded files.
Parameters:
-
limit(Optional[int], default:None) –Limit on the number of files returned. Default is None.
-
details(bool, default:True) –Whether to return detailed information. Default is True.
-
alive(Optional[bool], default:None) –If True, only returns non-deleted files. Default is None.
Returns:
- BaseResponse: File list data.
Source code in lazyllm/tools/rag/doc_manager.py
list_files_in_group(group_name=None, limit=None, alive=None)
An endpoint to list files in a specific group.
Parameters:
-
group_name(Optional[str], default:None) –The name of the file group.
-
limit(Optional[int], default:None) –Limit on the number of files returned. Default is None.
-
alive(Optional[bool], default:None) –Whether to return only non-deleted files.
Returns:
- BaseResponse: List of files in the group.
Source code in lazyllm/tools/rag/doc_manager.py
list_kb_groups()
An endpoint to list all document groups.
Returns:
- BaseResponse: Contains the data of all document groups.
Source code in lazyllm/tools/rag/doc_manager.py
query_metadata(query_metadata_request)
An endpoint to query metadata of a specific document.
Parameters:
-
query_metadata_request(QueryMetadataRequest) –Request containing the document ID and an optional metadata field name.
Returns:
- BaseResponse: Returns the field value if key is specified and exists; otherwise returns full metadata. If the key does not exist, returns an error.
Source code in lazyllm/tools/rag/doc_manager.py
reset_metadata(reset_metadata_request)
An endpoint to reset all metadata fields of specified documents.
Parameters:
-
reset_metadata_request(ResetMetadataRequest) –Request containing a list of document IDs and the new metadata dictionary to apply.
Returns:
- BaseResponse: Deletion operation result.
Source code in lazyllm/tools/rag/doc_manager.py
update_or_create_metadata_keys(update_metadata_request)
An endpoint to update or create metadata fields for specified documents.
Parameters:
-
update_metadata_request(UpdateMetadataRequest) –Request containing a list of document IDs and metadata key-value pairs to update or create.
Returns:
- BaseResponse: Deletion operation result.
Source code in lazyllm/tools/rag/doc_manager.py
upload_files(files, override=False, metadatas=None, user_path=None)
An endpoint to upload files and update their status. Multiple files can be uploaded at once.
Parameters:
-
files(List[UploadFile]) –List of files to upload.
-
override(bool, default:False) –Whether to overwrite existing files. Default is False.
-
metadatas(Optional[str], default:None) –Metadata for the files in JSON format.
-
user_path(Optional[str], default:None) –User-defined path for file uploads.
Returns:
- BaseResponse: Upload results and file IDs.
Source code in lazyllm/tools/rag/doc_manager.py
lazyllm.tools.rag.utils.SqliteDocListManager
Bases: DocListManager
SQLite-based document manager for persistent local file storage, status tracking, and metadata management.
This class inherits from DocListManager and uses a SQLite backend to store document records. It is suitable for managing locally identified documents with support for inserting, querying, updating, and filtering based on status. Optional file path monitoring is also supported.
Parameters:
-
path(str) –Directory path to store the database.
-
name(str) –Name of the SQLite database file (without path).
-
enable_path_monitoring(bool, default:True) –Whether to enable path monitoring. Defaults to True.
Examples:
>>> from lazyllm.tools.rag.utils import SqliteDocListManager
>>> manager = SqliteDocListManager(path="./data", name="docs.sqlite")
>>> manager.insert({"uid": "doc_001", "name": "example.txt", "status": "ready"})
>>> print(manager.get("doc_001"))
>>> files = manager.list_files(limit=5, details=True)
>>> print(files)
Source code in lazyllm/tools/rag/utils.py
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 | |
add_files_to_kb_group(file_ids, group)
Adds multiple files to the specified knowledge base group.
This method sets the file status to waiting. If successfully added, increments the document's count.
Parameters:
-
file_ids(List[str]) –List of file IDs to add.
-
group(str) –Name of the knowledge base group.
Source code in lazyllm/tools/rag/utils.py
add_kb_group(name)
Adds a new knowledge base group name to the database; ignores if the group already exists.
Parameters:
-
name(str) –The name of the knowledge base group to add.
Source code in lazyllm/tools/rag/utils.py
delete_files_from_kb_group(file_ids, group)
Deletes multiple files from the specified knowledge base group.
After deletion, decrements the document's count but not below zero. If the document is not found, logs a warning.
Parameters:
-
file_ids(List[str]) –List of file IDs to delete.
-
group(str) –Name of the knowledge base group.
Source code in lazyllm/tools/rag/utils.py
delete_unreferenced_doc()
Deletes documents from the database that are marked for deletion and are no longer referenced by any knowledge base group.
This method queries documents with status "deleting" and a reference count of zero, deletes them from the database, and adds operation logs for these deletions.
Source code in lazyllm/tools/rag/utils.py
fetch_docs_changed_meta(group)
Fetches the list of documents within a specified knowledge base group that have updated metadata, and resets the new_meta field for those documents.
Parameters:
-
group(str) –Name of the knowledge base group.
Returns:
- List[DocMetaChangedRow]: A list containing document IDs and their updated metadata.
Source code in lazyllm/tools/rag/utils.py
get_docs(doc_ids)
Fetches document objects from the database corresponding to the given list of document IDs.
Parameters:
-
doc_ids(List[str]) –A list of document IDs to query.
Returns:
- List[KBDocument]: A list of matching document objects. Returns an empty list if no matches found.
Source code in lazyllm/tools/rag/utils.py
get_docs_need_reparse(group)
Retrieves the list of documents that require re-parsing within a specified knowledge base group.
Only documents with status "success" or "failed" and marked as needing reparse in the group are returned.
Parameters:
-
group(str) –Name of the knowledge base group.
Returns:
- List[KBDocument]: List of documents that need to be re-parsed.
Source code in lazyllm/tools/rag/utils.py
get_existing_paths_by_pattern(pattern)
Retrieves a list of existing document paths that match a given pattern.
Parameters:
-
pattern(str) –Path matching pattern, supports SQL LIKE wildcards.
Returns:
- List[str]: List of existing document paths matching the pattern.
Source code in lazyllm/tools/rag/utils.py
get_file_status(fileid)
Gets the status of a specified file.
Parameters:
-
fileid(str) –Unique identifier of the file.
Returns:
- Optional[Tuple]: A tuple containing the status, or None if the file does not exist.
Source code in lazyllm/tools/rag/utils.py
list_all_kb_group()
Lists all knowledge base group names stored in the database.
Returns:
- List[str]: A list of knowledge base group names.
Source code in lazyllm/tools/rag/utils.py
list_files(limit=None, details=False, status=DocListManager.Status.all, exclude_status=None)
Lists files in the document database based on status filters and returns either full records or file paths.
Parameters:
-
limit(Optional[int], default:None) –The maximum number of records to return. If None, all matching records are returned.
-
details(bool, default:False) –Whether to return full database rows or just file paths (document IDs).
-
status(Union[str, List[str]], default:all) –Status values to include in the result. Defaults to including all.
-
exclude_status(Optional[Union[str, List[str]]], default:None) –Status values to exclude from the result.
Returns:
- list: A list of file records or document paths depending on the
detailsflag.
Source code in lazyllm/tools/rag/utils.py
list_kb_group_files(group=None, limit=None, details=False, status=DocListManager.Status.all, exclude_status=None, upload_status=DocListManager.Status.all, exclude_upload_status=None, need_reparse=None)
Lists files in a specified knowledge base group, with support for multiple filters.
Parameters:
-
group(str, default:None) –Knowledge base group name to filter by. If None, no group filtering is applied.
-
limit(int, default:None) –Limit on the number of files to return.
-
details(bool, default:False) –Whether to return detailed file information.
-
status(str or List[str], default:all) –Filter files by group document status.
-
exclude_status(str or List[str], default:None) –Exclude files with these group document statuses.
-
upload_status(str or List[str], default:all) –Filter files by upload document status.
-
exclude_upload_status(str or List[str], default:None) –Exclude files with these upload document statuses.
-
need_reparse(bool, default:None) –If set, only returns files marked as needing reparse.
Returns:
- list:
- If details is False, returns a list of tuples (doc_id, path).
- If details is True, returns a list of tuples containing detailed file information: document ID, path, status, metadata, group name, group status, and group log.
Source code in lazyllm/tools/rag/utils.py
release()
Clears all documents, groups, and operation logs from the database.
This operation deletes all records from documents, document_groups, kb_group_documents, and operation_logs tables.
Source code in lazyllm/tools/rag/utils.py
set_docs_new_meta(doc_meta)
Batch updates the metadata (meta) of documents, and simultaneously updates the new_meta field of documents in knowledge base groups for documents that are not in waiting status.
Parameters:
-
doc_meta(Dict[str, dict]) –A dictionary mapping document IDs to their new metadata dictionaries.
Source code in lazyllm/tools/rag/utils.py
table_inited()
Checks whether the "documents" table has been initialized in the database.
The method queries the sqlite_master metadata table to verify if the "documents" table exists.
Returns:
- bool: True if the "documents" table exists, False otherwise.
Source code in lazyllm/tools/rag/utils.py
update_file_message(fileid, **kw)
Updates fields of the specified file record.
Parameters:
-
fileid(str) –Unique identifier of the file (doc_id).
-
**kw–Key-value pairs of fields to update and their new values.
Source code in lazyllm/tools/rag/utils.py
update_file_status(file_ids, status, cond_status_list=None)
Updates the status of multiple files, optionally filtered by current status.
Parameters:
-
file_ids(List[str]) –List of file IDs to update.
-
status(str) –New status to set.
-
cond_status_list(Union[None, List[str]], default:None) –List of statuses to filter files that can be updated. Defaults to None.
Returns:
- List[DocPartRow]: List of updated file IDs and their paths.
Source code in lazyllm/tools/rag/utils.py
update_kb_group(cond_file_ids, cond_group=None, cond_status_list=None, new_status=None, new_need_reparse=None)
Updates the status and reparse need flag of specified files in a knowledge base group.
Batch updates files' status and need_reparse flag within a knowledge base group based on file IDs, group name, and optional status filter.
Parameters:
-
cond_file_ids(List[str]) –List of file IDs to update.
-
cond_group(Optional[str], default:None) –Group name to filter files, if specified only updates files in this group.
-
cond_status_list(Optional[List[str]], default:None) –Only update files whose status is in this list.
-
new_status(Optional[str], default:None) –New status to set.
-
new_need_reparse(Optional[bool], default:None) –New flag indicating if reparse is needed.
Returns:
- List[Tuple]: List of tuples of updated files containing doc_id, group_name, and status.
Source code in lazyllm/tools/rag/utils.py
update_need_reparsing(doc_id, need_reparse, group_name=None)
Updates the re-parsing flag for a specific document.
This method sets whether a document should be re-parsed. If a group name is provided, the update is scoped to that group only.
Parameters:
-
doc_id(str) –The unique identifier of the document.
-
need_reparse(bool) –Whether the document needs to be re-parsed.
-
group_name(Optional[str], default:None) –Optional. The knowledge base group name to filter by. If provided, only documents in the specified group will be updated.
Source code in lazyllm/tools/rag/utils.py
validate_paths(paths)
Validates whether the documents corresponding to the given paths can be safely added to the database.
The method checks if the document already exists. If it exists, it verifies whether the document is currently being parsed, waiting to be parsed, or was not successfully re-parsed last time.
Parameters:
-
paths(List[str]) –A list of file paths to validate.
Returns:
- Tuple[bool, str, List[bool]]:
- bool: Whether all paths passed validation.
- str: Description message of the validation result.
- List[bool]: A boolean list corresponding to input paths, indicating whether each path is new (True) or already exists (False). If validation fails, this value is None.
Source code in lazyllm/tools/rag/utils.py
lazyllm.tools.rag.data_loaders.DirectoryReader
A directory reader class for loading and processing documents from file directories.
This class provides functionality to read documents from specified directories and convert them into document nodes. It supports both local and global file readers, and can handle different types of documents including images.
Parameters:
-
input_files(Optional[List[str]]) –A list of file paths to read. If None, files will be loaded when calling load_data method.
-
local_readers(Optional[Dict], default:None) –A dictionary of local file readers specific to this instance. Keys are file patterns, values are reader functions.
-
global_readers(Optional[Dict], default:None) –A dictionary of global file readers shared across all instances. Keys are file patterns, values are reader functions.
Examples:
>>> from lazyllm.tools.rag.data_loaders import DirectoryReader
>>> from lazyllm.tools.rag.readers import DocxReader, PDFReader
>>> local_readers = {
... "**/*.docx": DocxReader,
... "**/*.pdf": PDFReader
>>> }
>>> reader = DirectoryReader(
... input_files=["path/to/documents"],
... local_readers=local_readers,
... global_readers={}
>>> )
>>> documents = reader.load_data()
>>> print(f"加载了 {len(documents)} 个文档")
Source code in lazyllm/tools/rag/data_loaders.py
load_data(input_files=None, metadatas=None, *, split_image_nodes=False)
Load and process documents from the specified input files.
This method reads documents from the input files using the configured file readers (both local and global), processes them into document nodes, and optionally separates image nodes from text nodes.
Parameters:
-
input_files(Optional[List[str]], default:None) –A list of file paths to read. If None, uses the files specified during initialization.
-
metadatas(Optional[Dict], default:None) –Additional metadata to associate with the loaded documents.
-
split_image_nodes(bool, default:False) –Whether to separate image nodes from text nodes. If True, returns a tuple of (text_nodes, image_nodes). If False, returns all nodes together.
Returns: - Union[List[DocNode], Tuple[List[DocNode], List[ImageDocNode]]]: If split_image_nodes is False, returns a list of all document nodes. If True, returns a tuple containing text nodes and image nodes separately.
Source code in lazyllm/tools/rag/data_loaders.py
lazyllm.tools.SentenceSplitter
Bases: NodeTransform
Split sentences into chunks of a specified size. You can specify the size of the overlap between adjacent chunks.
Parameters:
-
chunk_size(int, default:1024) –The size of the chunk after splitting.
-
chunk_overlap(int, default:200) –The length of the overlapping content between two adjacent chunks.
-
num_workers(int, default:0) –Controls the number of threads or processes used for parallel processing.
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)
Source code in lazyllm/tools/rag/transform.py
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 | |
lazyllm.tools.LLMParser
Bases: NodeTransform
A text summarizer and keyword extractor that is responsible for analyzing the text input by the user and providing concise summaries or extracting relevant keywords based on the requested task.
Parameters:
-
llm(TrainableModule) –A trainable module.
-
language(str) –The language type, currently only supports Chinese (zh) and English (en).
-
task_type(str) –Currently supports two types of tasks: summary and keyword extraction.
-
num_workers(int, default:30) –Controls the number of threads or processes used for parallel processing.
Examples:
>>> from lazyllm import TrainableModule
>>> from lazyllm.tools.rag import LLMParser
>>> llm = TrainableModule("internlm2-chat-7b")
>>> summary_parser = LLMParser(llm, language="en", task_type="summary")
Source code in lazyllm/tools/rag/transform.py
transform(node, **kwargs)
Perform the set task on the specified document.
Parameters:
-
node(DocNode) –The document on which the extraction task needs to be performed.
Examples:
>>> import lazyllm
>>> from lazyllm.tools import LLMParser
>>> llm = lazyllm.TrainableModule("internlm2-chat-7b").start()
>>> m = lazyllm.TrainableModule("bge-large-zh-v1.5").start()
>>> summary_parser = LLMParser(llm, language="en", task_type="summary")
>>> keywords_parser = LLMParser(llm, language="en", task_type="keywords")
>>> documents = lazyllm.Document(dataset_path="/path/to/your/data", embed=m, manager=False)
>>> rm = lazyllm.Retriever(documents, group_name='CoarseChunk', similarity='bm25', topk=6)
>>> doc_nodes = rm("test")
>>> summary_result = summary_parser.transform(doc_nodes[0])
>>> keywords_result = keywords_parser.transform(doc_nodes[0])
Source code in lazyllm/tools/rag/transform.py
lazyllm.tools.rag.transform.NodeTransform members: exclude-members:
lazyllm.tools.rag.transform.TransformArgs
dataclass
A document transformation parameter container for centralized management of processing configurations. Args: f (Union[str, Callable]): Transformation function or registered function name.Can be either a callable function or a string identifier for registered functions. trans_node (bool): Whether to transform node types.When True, modifies the document node structure during processing. num_workers (int):Controls parallel processing threads.Values >0. kwargs (Dict):Additional parameters passed to the transformation function. pattern (Union[str, Callable[[str], bool]]):File name/content matching pattern.
Examples:
>>> from lazyllm.tools import TransformArgs
>>> args = TransformArgs(f=lambda text: text.lower(),num_workers=4,pattern=r'.*\.md$')
>>>config = {'f': 'parse_pdf','kwargs': {'engine': 'pdfminer'},'trans_node': True}
>>>args = TransformArgs.from_dict(config)
print(args['f'])
print(args.get('unknown'))
Source code in lazyllm/tools/rag/transform.py
lazyllm.tools.rag.similarity.register_similarity(func=None, mode=None, descend=True, batch=False)
Similarity computation registration decorator, used for unified registration and management of different types of similarity computation methods. Args: func (Callable): The name of the similarity computation function. mode (Literal['text', 'embedding']): 'text' indicates direct text matching, while 'embedding' indicates vector-based similarity computation. descend (bool): Controls whether multithreading is enabled (enabled when > 0). kwargs (Dict): Whether the results are sorted in descending order of similarity. batch (bool): Whether to process nodes in batch.
Source code in lazyllm/tools/rag/similarity.py
lazyllm.tools.rag.doc_node.DocNode
Execute assigned tasks on the specified document. Args: uid (str): Unique identifier. content (Union[str, List[Any]]): Node content. group (str): Document group name. embedding (Dict[str, List[float]]): Dictionary of embedding vectors. parent (Union[str, "DocNode"]): Reference to the parent node. store: Storage representation. node_groups (Dict[str, Dict]): Node storage groups. metadata (Dict[str, Any]): Node-level metadata. global_metadata (Dict[str, Any]): Document-level metadata. text (str): Node content, mutually exclusive with content.
Source code in lazyllm/tools/rag/doc_node.py
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 | |
check_embedding_state(embed_key)
Block to check the embedding status and ensure that asynchronous embedding computation is completed. Args: embed_key (str): List of target keys.
Source code in lazyllm/tools/rag/doc_node.py
do_embedding(embed)
Execute embedding computation. Args: embed (Dict[str, Callable]): Target embedding objects.
Source code in lazyllm/tools/rag/doc_node.py
get_metadata_str(mode=MetadataMode.ALL)
Metadata info string.
Source code in lazyllm/tools/rag/doc_node.py
get_text(metadata_mode=MetadataMode.NONE)
Combine metadata and content. Args: metadata_mode: Same as the parameter in get_metadata_str.
Source code in lazyllm/tools/rag/doc_node.py
has_missing_embedding(embed_keys)
Check for missing embedding vectors. Args: embed_keys (Union[str, List[str]]): List of target keys.
Source code in lazyllm/tools/rag/doc_node.py
to_dict()
with_score(score)
Shallow copy the original node and add a semantic relevance score. Args: score: Relevance score.
with_sim_score(score)
Shallow copy the original node and add a similarity score. Args: score: Similarity score.
lazyllm.tools.rag.doc_processor.DocumentProcessor
Bases: ModuleBase
Document processor class for managing document addition, deletion and update operations.
Parameters:
-
server(bool, default:True) –Whether to run in server mode. Defaults to True.
-
port(Optional[int], default:None) –Server port number. Defaults to None.
-
url(Optional[str], default:None) –Remote service URL. Defaults to None.
Notes: - Supports asynchronous document task processing - Provides document metadata update functionality - Supports task status callback notifications - Configurable database storage
Examples:
```python
# Create local document processor
processor = DocumentProcessor(server=False)
# Create server mode document processor
processor = DocumentProcessor(server=True, port=8080)
# Create remote document processor
processor = DocumentProcessor(url="http://remote-server:8080")
```
Source code in lazyllm/tools/rag/doc_processor.py
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 | |
drop_algorithm(name, clean_db=False)
Remove specified algorithm from document processor.
Parameters:
-
name(str) –Name of the algorithm to remove.
-
clean_db(bool, default:False) –Whether to clean related database data. Defaults to False.
Notes: - If algorithm name does not exist, a warning message will be output - After removal, the algorithm will no longer be available
Examples:
```python
# Remove algorithm
processor.drop_algorithm("pdf_processor")
# Remove algorithm and clean database
processor.drop_algorithm("pdf_processor", clean_db=True)
```
Source code in lazyllm/tools/rag/doc_processor.py
register_algorithm(name, store, reader, node_groups, display_name=None, description=None, force_refresh=False, **kwargs)
Register an algorithm to the document processor.
Parameters:
-
name(str) –Algorithm name as unique identifier.
-
store(StoreBase) –Storage instance for managing document data.
-
reader(ReaderBase) –Reader instance for parsing document content.
-
node_groups(Dict[str, Dict]) –Node group configuration information.
-
force_refresh(bool, default:False) –Whether to force refresh existing algorithm. Defaults to False.
Notes: - If algorithm name exists and force_refresh is False, registration will be skipped - After successful registration, the algorithm can be used to process documents
Examples:
```python
from lazyllm.rag import DocumentProcessor, FileStore, PDFReader
# Create storage and reader instances
store = FileStore(path="./data")
reader = PDFReader()
# Define node group configuration
node_groups = {
"text": {"transform": "text", "parent": "root"},
"summary": {"transform": "summary", "parent": "text"}
}
# Register algorithm
processor = DocumentProcessor()
processor.register_algorithm(
name="pdf_processor",
store=store,
reader=reader,
node_groups=node_groups
)
```
Source code in lazyllm/tools/rag/doc_processor.py
lazyllm.tools.rag.doc_node.QADocNode
Bases: DocNode
Question-Answer document node class for storing QA pair data.
Parameters:
-
query(str) –The question text.
-
answer(str) –The answer text.
-
uid(str, default:None) –Unique identifier.
-
group(str, default:None) –Document group name.
-
embedding(Dict[str, List[float]], default:None) –Dictionary of embedding vectors.
-
parent(DocNode, default:None) –Reference to the parent node.
-
metadata(Dict[str, Any], default:None) –Node-level metadata.
-
global_metadata(Dict[str, Any], default:None) –Document-level metadata.
-
text(str, default:None) –Node content, mutually exclusive with query.
Source code in lazyllm/tools/rag/doc_node.py
get_text(metadata_mode=MetadataMode.NONE)
Get the text content of the node.
Parameters:
-
metadata_mode(MetadataMode, default:NONE) –Metadata mode, defaults to MetadataMode.NONE. When set to MetadataMode.LLM, returns formatted QA pair. For other modes, returns base class text format.
Returns:
-
str(str) –The formatted text content.
Source code in lazyllm/tools/rag/doc_node.py
lazyllm.tools.rag.dataReader.SimpleDirectoryReader
Bases: ModuleBase
A modular document directory reader that inherits from ModuleBase, supporting reading various document formats from the file system and converting them into standardized DocNode objects. Args: input_dir (Optional[str]): Input directory path. Mutually exclusive with input_files. input_files (Optional[List]): Directly specified list of files. Mutually exclusive with input_dir. exclude (Optional[List]): List of file patterns to exclude. exclude_hidden (bool): Whether to exclude hidden files. recursive (bool): Whether to recursively read subdirectories. encoding (str): Encoding format of text files. required_exts (Optional[List[str]]): Whitelist of file extensions to process. file_extractor (Optional[Dict[str, Callable]]): Dictionary of custom file readers. fs (Optional[AbstractFileSystem]): Custom file system. metadata_genf (Optional[Callable[[str], Dict]]): Metadata generation function that takes a file path and returns a metadata dictionary. num_files_limit (Optional[int]): Maximum number of files to read. return_trace (bool): Whether to return processing trace information. metadatas (Optional[Dict]): Predefined global metadata dictionary.
Examples:
>>> import lazyllm
>>> from lazyllm.tools.dataReader import SimpleDirectoryReader
>>> reader = SimpleDirectoryReader(input_dir="yourpath/",recursive=True,exclude=["*.tmp"],required_exts=[".pdf", ".docx"])
>>> documents = reader.load_data()
Source code in lazyllm/tools/rag/dataReader.py
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 | |
lazyllm.tools.rag.dataReader.FileReader
Bases: object
File content reader whose main function is to convert various input file formats into concatenated plain text content. Args: input_files (Optional[List]): Directly specified list of input files.
Examples:
>>> import lazyllm
>>> from lazyllm.tools.dataReader import FileReader
>>> reader = FileReader()
>>> content = reader("yourpath/")
Source code in lazyllm/tools/rag/dataReader.py
lazyllm.tools.rag.transform.FuncNodeTransform
Bases: NodeTransform
Used for user defined function.
Wrapped the transform to: List[Docnode] -> List[Docnode]
This wrapper supports when trans_node is False:
1. str -> list: transform=lambda t: t.split('
') 2. str -> str: transform=lambda t: t[:3]
This wrapper supports when trans_node is True:
1. DocNode -> list: pipeline(lambda x:x, SentenceSplitter)
2. DocNode -> DocNode: pipeline(LLMParser)
Source code in lazyllm/tools/rag/transform.py
transform(node, **kwargs)
Transform a document node using the wrapped user-defined function.
This method applies the user-defined function to either the text content of the node (when trans_node=False) or the node itself (when trans_node=True).
Parameters:
-
node(DocNode) –The document node to be transformed.
-
**kwargs–Additional keyword arguments passed to the transformation function.
Returns:
-
List[Union[str, DocNode]]–List[Union[str, DocNode]]: The transformed results, which can be either strings or DocNode objects depending on the function implementation.
Source code in lazyllm/tools/rag/transform.py
lazyllm.tools.rag.web.DocWebModule
Bases: ModuleBase
Document Web Interface Module, inherits from ModuleBase, provides web-based document management interface.
Parameters:
-
doc_server(ServerModule) –Document server module instance providing backend API support
-
title(str, default:'文档管理演示终端') –Interface title, defaults to "文档管理演示终端"
-
port(int / range / list, default:None) –Service port number or range, defaults to 20800-20999
-
history(list, default:None) –Initial chat history, defaults to empty list
-
text_mode(Mode, default:None) –Text processing mode, defaults to Mode.Dynamic
-
trace_mode(Mode, default:None) –Trace mode, defaults to Mode.Refresh
Class Attributes
Mode: Mode enumeration class containing: - Dynamic: Dynamic mode - Refresh: Refresh mode - Appendix: Appendix mode
Notes
- Requires a valid doc_server instance to work with
- Automatically tries other ports in range when port conflict occurs
- Releases resources when service is stopped
Examples:
>>> import lazyllm
>>> from lazyllm.tools.rag.web import DocWebModule
>>> from lazyllm import
>>> doc_server = ServerModule(url="your_url")
>>> doc_web = DocWebModule(
>>> doc_server=doc_server,
>>> title="文档管理演示终端",
>>> port=range(20800, 20805) # 自动寻找可用端口)
>>> deploy_task = doc_web._get_deploy_tasks()
>>> deploy_task()
>>> print(doc_web.url)
>>> doc_web.stop()
Source code in lazyllm/tools/rag/web.py
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 | |
stop()
lazyllm.tools.WebModule
Bases: ModuleBase
WebModule is a web-based interactive interface provided by LazyLLM for developers. After initializing and starting a WebModule, developers can see structure of the module they provides behind the WebModule, and transmit the input of the Chatbot component to their modules. The results and logs returned by the module will be displayed on the “Processing Logs” and Chatbot component on the web page. In addition, Checkbox or Text components can be added programmatically to the web page for additional parameters to the background module. Meanwhile, The WebModule page provides Checkboxes of “Use Context,” “Stream Output,” and “Append Output,” which can be used to adjust the interaction between the page and the module behind.
WebModule.init_web(component_descs) -> gradio.Blocks
Generate a demonstration web page based on gradio. The function initializes session-related data to save chat history and logs for different pages, then dynamically add Checkbox and Text components to the page according to component_descs parameter, and set the corresponding functions for the buttons and text boxes on the page at last. WebModule’s init function calls this method to generate the page.
Parameters:
-
component_descs(list) –A list used to add components to the page. Each element in the list is also a list containing
Examples:
>>> import lazyllm
>>> def func2(in_str, do_sample=True, temperature=0.0, *args, **kwargs):
... return f"func2:{in_str}|do_sample:{str(do_sample)}|temp:{temperature}"
...
>>> m1=lazyllm.ActionModule(func2)
>>> m1.name="Module1"
>>> w = lazyllm.WebModule(m1, port=[20570, 20571, 20572], components={
... m1:[('do_sample', 'Checkbox', True), ('temperature', 'Text', 0.1)]},
... text_mode=lazyllm.tools.WebModule.Mode.Refresh)
>>> w.start()
193703: 2024-06-07 10:26:00 lazyllm SUCCESS: ...
Source code in lazyllm/tools/webpages/webmodule.py
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 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 | |
init_web(component_descs)
Initialize the Web UI page.
This method uses Gradio to build the interactive chat interface and binds all components to the appropriate logic. It supports session selection, streaming output, context toggling, multimodal input, and control tools. The method returns the constructed Gradio Blocks object.
Args:
component_descs (List[Tuple]): A list of component descriptors. Each element is a 5-tuple
(module, group_name, name, component_type, value), e.g. ('MyModule', 'GroupA', 'use_cache', 'Checkbox', True).
Returns:
gr.Blocks: The constructed Gradio UI object, which can be launched via .launch().
Source code in lazyllm/tools/webpages/webmodule.py
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 | |
stop()
Stop the web interface and clean up resources.
If the web demo has been initialized, this method closes the Gradio demo, frees related resources, and resets demo and url attributes.
Source code in lazyllm/tools/webpages/webmodule.py
wait()
Block the main thread until the web interface is closed. This method blocks the current thread until the Gradio demo is closed. Useful in deployment scenarios to prevent premature program exit.
Source code in lazyllm/tools/webpages/webmodule.py
lazyllm.tools.CodeGenerator
Bases: ModuleBase
Code Generation Module.
This module generates code based on a user-defined prompt. It automatically selects a Chinese or English system prompt based on the input, and extracts Python code snippets from the output.
__init__(self, base_model, prompt="")
Initializes the code generator with a base model and prompt.
Parameters:
-
base_model(Union[str, TrainableModule, OnlineChatModuleBase]) –A path string to load the model, or an initialized model instance.
-
prompt(str, default:'') –A user-defined prompt to guide the code generation. May contain Chinese or English.
Examples:
>>> from lazyllm.components import CodeGenerator
>>> generator = CodeGenerator(base_model="deepseek-coder", prompt="写一个Python函数,计算斐波那契数列。")
>>> result = generator("请给出实现代码")
>>> print(result)
... def fibonacci(n):
... if n <= 1:
... return n
... return fibonacci(n-1) + fibonacci(n-2)
Source code in lazyllm/tools/actors/code_generator.py
choose_prompt(prompt)
Selects an appropriate code generation prompt template based on the content of the input prompt.
Returns the Chinese prompt template if Chinese characters are detected; otherwise returns the English prompt template.
Parameters:
-
prompt(str) –Input prompt text.
Returns:
- str: The selected code generation prompt template string.
Source code in lazyllm/tools/actors/code_generator.py
lazyllm.tools.ParameterExtractor
Bases: ModuleBase
Parameter Extraction Module.
This module extracts structured parameters from a given text using a language model, based on the parameter names, types, descriptions, and whether they are required.
__init__(self, base_model, param, type, description, require)
Initializes the parameter extractor with the parameter specification and base model.
Parameters:
-
base_model(Union[str, TrainableModule, OnlineChatModuleBase]) –A model path or model instance used for extraction.
-
param(list[str]) –List of parameter names to extract.
-
type(list[str]) –List of parameter types (e.g., "int", "str", "bool").
-
description(list[str]) –List of descriptions for each parameter.
-
require(list[bool]) –List indicating whether each parameter is required.
Examples:
>>> from lazyllm.components import ParameterExtractor
>>> extractor = ParameterExtractor(
... base_model="deepseek-chat",
... param=["name", "age"],
... type=["str", "int"],
... description=["The user's name", "The user's age"],
... require=[True, True]
... )
>>> result = extractor("My name is Alice and I am 25 years old.")
>>> print(result)
... ['Alice', 25]
Source code in lazyllm/tools/actors/parameter_extractor.py
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 | |
lazyllm.tools.QustionRewrite
Bases: ModuleBase
Question Rewrite Module.
This module rewrites or reformulates a user query using a language model. It supports both string and list output formats based on the formatter.
__init__(self, base_model, rewrite_prompt="", formatter="str")
Initializes the question rewrite module with a prompt and model.
Parameters:
-
base_model(Union[str, TrainableModule, OnlineChatModuleBase]) –A path string or initialized model for question rewriting.
-
rewrite_prompt(str, default:'') –Custom prompt to guide the rewrite behavior.
-
formatter(str, default:'str') –Output format type; either "str" or "list".
Examples:
>>> from lazyllm.components import QustionRewrite
>>> rewriter = QustionRewrite(base_model="chatglm", rewrite_prompt="请将问题改写为更适合检索的形式", formatter="list")
>>> result = rewriter("中国的最高山峰是什么?")
>>> print(result)
... ['中国的最高山峰是哪一座?', '中国海拔最高的山是什么?']
Source code in lazyllm/tools/actors/qustion_rewrite.py
choose_prompt(prompt)
Choose the appropriate prompt template based on the language of the input prompt.
This method analyzes the input prompt string and determines whether to use the Chinese or English prompt template. It checks each character in the prompt string and if any character falls within the Chinese Unicode range (一-鿿), it returns the Chinese prompt template; otherwise, it returns the English prompt template.
Parameters:
-
prompt(str) –The input prompt string to be analyzed for language detection.
Returns:
-
str–The selected prompt template string (either Chinese or English version).
Examples:
>>> from lazyllm.tools.actors.qustion_rewrite import QustionRewrite
# Example 1: English prompt (no Chinese characters)
>>> rewriter = QustionRewrite("gpt-3.5-turbo")
>>> prompt_template = rewriter.choose_prompt("How to implement machine learning?")
>>> print("Template contains Chinese:", "中文" in prompt_template)
Template contains Chinese: False
# Example 2: Chinese prompt (contains Chinese characters)
>>> prompt_template = rewriter.choose_prompt("如何实现机器学习?")
>>> print("Template contains Chinese:", "中文" in prompt_template)
Template contains Chinese: True
# Example 3: Mixed language prompt (contains Chinese characters)
>>> prompt_template = rewriter.choose_prompt("What is 机器学习?")
>>> print("Template contains Chinese:", "中文" in prompt_template)
Template contains Chinese: True
Source code in lazyllm/tools/actors/qustion_rewrite.py
lazyllm.tools.agent.toolsManager.ToolManager
Bases: ModuleBase
ToolManager is a tool management class used to provide tool information and tool calls to function call.
When constructing this management class, you need to pass in a list of tool name strings. The tool name here can be provided by LazyLLM or user-defined. If it is user-defined, it must first be registered in LazyLLM before it can be used. When registering, directly use the fc_register registrar, which has established the tool group, so when using the tool management class, all functions can be uniformly registered in the tool group. The function to be registered needs to annotate the function parameters, and add a functional description to the function, as well as the parameter type and function description. This is to facilitate the tool management class to parse the function and pass it to LLM for use.
Parameters:
-
tools(List[str]) –A list of tool name strings.
-
return_trace(bool, default:False) –If True, return intermediate steps and tool calls.
-
stream(bool) –Whether to stream the planning and solving process.
Examples:
>>> from lazyllm.tools import ToolManager, fc_register
>>> import json
>>> from typing import Literal
>>> @fc_register("tool")
>>> def get_current_weather(location: str, unit: Literal["fahrenheit", "celsius"]="fahrenheit"):
... '''
... Get the current weather in a given location
...
... Args:
... location (str): The city and state, e.g. San Francisco, CA.
... unit (str): The temperature unit to use. Infer this from the users location.
... '''
... if 'tokyo' in location.lower():
... return json.dumps({'location': 'Tokyo', 'temperature': '10', 'unit': 'celsius'})
... elif 'san francisco' in location.lower():
... return json.dumps({'location': 'San Francisco', 'temperature': '72', 'unit': 'fahrenheit'})
... elif 'paris' in location.lower():
... return json.dumps({'location': 'Paris', 'temperature': '22', 'unit': 'celsius'})
... elif 'beijing' in location.lower():
... return json.dumps({'location': 'Beijing', 'temperature': '90', 'unit': 'fahrenheit'})
... else:
... return json.dumps({'location': location, 'temperature': 'unknown'})
...
>>> @fc_register("tool")
>>> def get_n_day_weather_forecast(location: str, num_days: int, unit: Literal["celsius", "fahrenheit"]='fahrenheit'):
... '''
... Get an N-day weather forecast
...
... Args:
... location (str): The city and state, e.g. San Francisco, CA.
... num_days (int): The number of days to forecast.
... unit (Literal['celsius', 'fahrenheit']): The temperature unit to use. Infer this from the users location.
... '''
... if 'tokyo' in location.lower():
... return json.dumps({'location': 'Tokyo', 'temperature': '10', 'unit': 'celsius', "num_days": num_days})
... elif 'san francisco' in location.lower():
... return json.dumps({'location': 'San Francisco', 'temperature': '75', 'unit': 'fahrenheit', "num_days": num_days})
... elif 'paris' in location.lower():
... return json.dumps({'location': 'Paris', 'temperature': '25', 'unit': 'celsius', "num_days": num_days})
... elif 'beijing' in location.lower():
... return json.dumps({'location': 'Beijing', 'temperature': '85', 'unit': 'fahrenheit', "num_days": num_days})
... else:
... return json.dumps({'location': location, 'temperature': 'unknown'})
...
>>> tools = ["get_current_weather", "get_n_day_weather_forecast"]
>>> tm = ToolManager(tools)
>>> print(tm([{'name': 'get_n_day_weather_forecast', 'arguments': {'location': 'Beijing', 'num_days': 3}}])[0])
'{"location": "Beijing", "temperature": "85", "unit": "fahrenheit", "num_days": 3}'
Source code in lazyllm/tools/agent/toolsManager.py
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 | |
lazyllm.tools.ModuleTool
Bases: ModuleBase
Base class for defining tools using callable Python functions.
This class automatically parses function signatures and docstrings to build a parameter schema using pydantic. It also performs input validation and handles standardized tool execution.
__init__(self, verbose=False, return_trace=True)
Initializes a tool wrapper module.
Parameters:
-
verbose(bool, default:False) –Whether to print verbose logs during execution.
-
return_trace(bool, default:True) –Whether to keep intermediate execution trace in the result.
Examples:
>>> from lazyllm.components import ModuleTool
>>> class AddTool(ModuleTool):
... def apply(self, a: int, b: int) -> int:
... '''Add two integers.
...
... Args:
... a (int): First number.
... b (int): Second number.
...
... Returns:
... int: The sum of a and b.
... '''
... return a + b
>>> tool = AddTool()
>>> result = tool({'a': 3, 'b': 5})
>>> print(result)
8
Source code in lazyllm/tools/agent/toolsManager.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 217 218 219 220 221 222 223 224 | |
apply(*args, **kwargs)
Abstract method to be implemented in subclasses.
This method should perform a specific task based on the provided arguments.
Raises:
-
NotImplementedError–If the method is not overridden in a subclass.
Source code in lazyllm/tools/agent/toolsManager.py
validate_parameters(arguments)
Validate whether the provided arguments meet the required criteria.
This method checks if all required keys are present in the input dictionary and attempts format validation.
Parameters:
-
arguments(Dict[str, Any]) –Dictionary of input arguments.
Returns:
-
bool(bool) –True if valid and complete; False otherwise.
Source code in lazyllm/tools/agent/toolsManager.py
lazyllm.tools.FunctionCall
Bases: ModuleBase
FunctionCall is a single-turn tool invocation class. It is used when the LLM alone cannot answer user queries and requires external knowledge through tool calls.
If the LLM output requires tool calls, the tools are invoked and the combined results (input, model output, tool output) are returned as a list.
If no tool calls are needed, the LLM output is returned directly as a string.
Parameters:
-
llm(ModuleBase) –The LLM instance to use, which can be either a TrainableModule or OnlineChatModule.
-
tools(List[Union[str, Callable]]) –A list of tool names or callable objects that the LLM can use.
-
return_trace(Optional[bool], default:False) –Whether to return the invocation trace, defaults to False.
-
stream(Optional[bool], default:False) –Whether to enable streaming output, defaults to False.
-
_prompt(Optional[str], default:None) –Custom prompt for function call, defaults to automatic selection based on llm type.
Note: Tools in tools must include a __doc__ attribute and describe their purpose and parameters according to the Google Python Style.
Examples:
>>> import lazyllm
>>> from lazyllm.tools import fc_register, FunctionCall
>>> import json
>>> from typing import Literal
>>> @fc_register("tool")
>>> def get_current_weather(location: str, unit: Literal["fahrenheit", "celsius"] = 'fahrenheit'):
... '''
... Get the current weather in a given location
...
... Args:
... location (str): The city and state, e.g. San Francisco, CA.
... unit (str): The temperature unit to use. Infer this from the users location.
... '''
... if 'tokyo' in location.lower():
... return json.dumps({'location': 'Tokyo', 'temperature': '10', 'unit': 'celsius'})
... elif 'san francisco' in location.lower():
... return json.dumps({'location': 'San Francisco', 'temperature': '72', 'unit': 'fahrenheit'})
... elif 'paris' in location.lower():
... return json.dumps({'location': 'Paris', 'temperature': '22', 'unit': 'celsius'})
... else:
... return json.dumps({'location': location, 'temperature': 'unknown'})
...
>>> @fc_register("tool")
>>> def get_n_day_weather_forecast(location: str, num_days: int, unit: Literal["celsius", "fahrenheit"] = 'fahrenheit'):
... '''
... Get an N-day weather forecast
...
... Args:
... location (str): The city and state, e.g. San Francisco, CA.
... num_days (int): The number of days to forecast.
... unit (Literal['celsius', 'fahrenheit']): The temperature unit to use. Infer this from the users location.
... '''
... if 'tokyo' in location.lower():
... return json.dumps({'location': 'Tokyo', 'temperature': '10', 'unit': 'celsius', "num_days": num_days})
... elif 'san francisco' in location.lower():
... return json.dumps({'location': 'San Francisco', 'temperature': '72', 'unit': 'fahrenheit', "num_days": num_days})
... elif 'paris' in location.lower():
... return json.dumps({'location': 'Paris', 'temperature': '22', 'unit': 'celsius', "num_days": num_days})
... else:
... return json.dumps({'location': location, 'temperature': 'unknown'})
...
>>> tools=["get_current_weather", "get_n_day_weather_forecast"]
>>> llm = lazyllm.TrainableModule("internlm2-chat-20b").start() # or llm = lazyllm.OnlineChatModule("openai", stream=False)
>>> query = "What's the weather like today in celsius in Tokyo."
>>> fc = FunctionCall(llm, tools)
>>> ret = fc(query)
>>> print(ret)
["What's the weather like today in celsius in Tokyo.", {'role': 'assistant', 'content': '
', 'tool_calls': [{'id': 'da19cddac0584869879deb1315356d2a', 'type': 'function', 'function': {'name': 'get_current_weather', 'arguments': {'location': 'Tokyo', 'unit': 'celsius'}}}]}, [{'role': 'tool', 'content': '{"location": "Tokyo", "temperature": "10", "unit": "celsius"}', 'tool_call_id': 'da19cddac0584869879deb1315356d2a', 'name': 'get_current_weather'}]]
>>> query = "Hello"
>>> ret = fc(query)
>>> print(ret)
'Hello! How can I assist you today?'
Source code in lazyllm/tools/agent/functionCall.py
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 | |
lazyllm.tools.FunctionCallFormatter
Bases: JsonFormatter
Formatter for parsing structured function call messages.
This class extends JsonFormatter and is responsible for extracting JSON-based tool call structures from a mixed message string, optionally separating them using a global delimiter.
Private Method
_load(msg) Parses the input message string and extracts JSON-formatted tool calls, if present.
Examples:
>>> from lazyllm.components import FunctionCallFormatter
>>> formatter = FunctionCallFormatter()
>>> msg = "Please call this tool. <TOOL> [{"name": "search", "args": {"query": "weather"}}]"
>>> result = formatter._load(msg)
>>> print(result)
... [{'name': 'search', 'args': {'query': 'weather'}}, 'Please call this tool. ']
Source code in lazyllm/tools/agent/functionCallFormatter.py
lazyllm.tools.FunctionCallAgent
Bases: ModuleBase
FunctionCallAgent is an agent that uses the tool calling method to perform complete tool calls. That is, when answering uesr questions, if LLM needs to obtain external knowledge through the tool, it will call the tool and feed back the return results of the tool to LLM, which will finally summarize and output them.
Parameters:
-
llm(ModuleBase) –The LLM to be used can be either TrainableModule or OnlineChatModule.
-
tools(List[str]) –A list of tool names for LLM to use.
-
max_retries(int, default:5) –The maximum number of tool call iterations. The default value is 5.
Examples:
>>> import lazyllm
>>> from lazyllm.tools import fc_register, FunctionCallAgent
>>> import json
>>> from typing import Literal
>>> @fc_register("tool")
>>> def get_current_weather(location: str, unit: Literal["fahrenheit", "celsius"]='fahrenheit'):
... '''
... Get the current weather in a given location
...
... Args:
... location (str): The city and state, e.g. San Francisco, CA.
... unit (str): The temperature unit to use. Infer this from the users location.
... '''
... if 'tokyo' in location.lower():
... return json.dumps({'location': 'Tokyo', 'temperature': '10', 'unit': 'celsius'})
... elif 'san francisco' in location.lower():
... return json.dumps({'location': 'San Francisco', 'temperature': '72', 'unit': 'fahrenheit'})
... elif 'paris' in location.lower():
... return json.dumps({'location': 'Paris', 'temperature': '22', 'unit': 'celsius'})
... elif 'beijing' in location.lower():
... return json.dumps({'location': 'Beijing', 'temperature': '90', 'unit': 'Fahrenheit'})
... else:
... return json.dumps({'location': location, 'temperature': 'unknown'})
...
>>> @fc_register("tool")
>>> def get_n_day_weather_forecast(location: str, num_days: int, unit: Literal["celsius", "fahrenheit"]='fahrenheit'):
... '''
... Get an N-day weather forecast
...
... Args:
... location (str): The city and state, e.g. San Francisco, CA.
... num_days (int): The number of days to forecast.
... unit (Literal['celsius', 'fahrenheit']): The temperature unit to use. Infer this from the users location.
... '''
... if 'tokyo' in location.lower():
... return json.dumps({'location': 'Tokyo', 'temperature': '10', 'unit': 'celsius', "num_days": num_days})
... elif 'san francisco' in location.lower():
... return json.dumps({'location': 'San Francisco', 'temperature': '75', 'unit': 'fahrenheit', "num_days": num_days})
... elif 'paris' in location.lower():
... return json.dumps({'location': 'Paris', 'temperature': '25', 'unit': 'celsius', "num_days": num_days})
... elif 'beijing' in location.lower():
... return json.dumps({'location': 'Beijing', 'temperature': '85', 'unit': 'fahrenheit', "num_days": num_days})
... else:
... return json.dumps({'location': location, 'temperature': 'unknown'})
...
>>> tools = ['get_current_weather', 'get_n_day_weather_forecast']
>>> llm = lazyllm.TrainableModule("internlm2-chat-20b").start() # or llm = lazyllm.OnlineChatModule(source="sensenova")
>>> agent = FunctionCallAgent(llm, tools)
>>> query = "What's the weather like today in celsius in Tokyo and Paris."
>>> res = agent(query)
>>> print(res)
'The current weather in Tokyo is 10 degrees Celsius, and in Paris, it is 22 degrees Celsius.'
>>> query = "Hello"
>>> res = agent(query)
>>> print(res)
'Hello! How can I assist you today?'
Source code in lazyllm/tools/agent/functionCall.py
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 | |
lazyllm.tools.ReactAgent
Bases: ModuleBase
ReactAgent follows the process of Thought->Action->Observation->Thought...->Finish step by step through LLM and tool calls to display the steps to solve user questions and the final answer to the user.
Parameters:
-
llm(ModuleBase) –The LLM to be used can be either TrainableModule or OnlineChatModule.
-
tools(List[str]) –A list of tool names for LLM to use.
-
max_retries(int, default:5) –The maximum number of tool call iterations. The default value is 5.
-
return_trace(bool, default:False) –If True, return intermediate steps and tool calls.
-
stream(bool, default:False) –Whether to stream the planning and solving process.
Examples:
>>> import lazyllm
>>> from lazyllm.tools import fc_register, ReactAgent
>>> @fc_register("tool")
>>> def multiply_tool(a: int, b: int) -> int:
... '''
... Multiply two integers and return the result integer
...
... Args:
... a (int): multiplier
... b (int): multiplier
... '''
... return a * b
...
>>> @fc_register("tool")
>>> def add_tool(a: int, b: int):
... '''
... Add two integers and returns the result integer
...
... Args:
... a (int): addend
... b (int): addend
... '''
... return a + b
...
>>> tools = ["multiply_tool", "add_tool"]
>>> llm = lazyllm.TrainableModule("internlm2-chat-20b").start() # or llm = lazyllm.OnlineChatModule(source="sensenova")
>>> agent = ReactAgent(llm, tools)
>>> query = "What is 20+(2*4)? Calculate step by step."
>>> res = agent(query)
>>> print(res)
'Answer: The result of 20+(2*4) is 28.'
Source code in lazyllm/tools/agent/reactAgent.py
lazyllm.tools.PlanAndSolveAgent
Bases: ModuleBase
PlanAndSolveAgent consists of two components. First, the planner breaks down the entire task into smaller subtasks, then the solver executes these subtasks according to the plan, which may involve tool calls, and finally returns the answer to the user.
Parameters:
-
llm(ModuleBase, default:None) –The LLM to be used can be TrainableModule or OnlineChatModule. It is mutually exclusive with plan_llm and solve_llm. Either set llm(the planner and sovler share the same LLM), or set plan_llm and solve_llm,or only specify llm(to set the planner) and solve_llm. Other cases are considered invalid.
-
tools(List[str], default:[]) –A list of tool names for LLM to use.
-
plan_llm(ModuleBase, default:None) –The LLM to be used by the planner, which can be either TrainableModule or OnlineChatModule.
-
solve_llm(ModuleBase, default:None) –The LLM to be used by the solver, which can be either TrainableModule or OnlineChatModule.
-
max_retries(int, default:5) –The maximum number of tool call iterations. The default value is 5.
-
return_trace(bool, default:False) –If True, return intermediate steps and tool calls.
-
stream(bool, default:False) –Whether to stream the planning and solving process.
Examples:
>>> import lazyllm
>>> from lazyllm.tools import fc_register, PlanAndSolveAgent
>>> @fc_register("tool")
>>> def multiply(a: int, b: int) -> int:
... '''
... Multiply two integers and return the result integer
...
... Args:
... a (int): multiplier
... b (int): multiplier
... '''
... return a * b
...
>>> @fc_register("tool")
>>> def add(a: int, b: int):
... '''
... Add two integers and returns the result integer
...
... Args:
... a (int): addend
... b (int): addend
... '''
... return a + b
...
>>> tools = ["multiply", "add"]
>>> llm = lazyllm.TrainableModule("internlm2-chat-20b").start() # or llm = lazyllm.OnlineChatModule(source="sensenova")
>>> agent = PlanAndSolveAgent(llm, tools)
>>> query = "What is 20+(2*4)? Calculate step by step."
>>> res = agent(query)
>>> print(res)
'The final answer is 28.'
Source code in lazyllm/tools/agent/planAndSolveAgent.py
lazyllm.tools.ReWOOAgent
Bases: ModuleBase
ReWOOAgent consists of three parts: Planer, Worker and Solver. The Planner uses predictive reasoning capabilities to create a solution blueprint for a complex task; the Worker interacts with the environment through tool calls and fills in actual evidence or observations into instructions; the Solver processes all plans and evidence to develop a solution to the original task or problem.
Parameters:
-
llm(ModuleBase, default:None) –The LLM to be used can be TrainableModule or OnlineChatModule. It is mutually exclusive with plan_llm and solve_llm. Either set llm(the planner and sovler share the same LLM), or set plan_llm and solve_llm,or only specify llm(to set the planner) and solve_llm. Other cases are considered invalid.
-
tools(List[str], default:[]) –A list of tool names for LLM to use.
-
plan_llm(ModuleBase, default:None) –The LLM to be used by the planner, which can be either TrainableModule or OnlineChatModule.
-
solve_llm(ModuleBase, default:None) –The LLM to be used by the solver, which can be either TrainableModule or OnlineChatModule.
-
max_retries(int) –The maximum number of tool call iterations. The default value is 5.
-
return_trace(bool, default:False) –If True, return intermediate steps and tool calls.
-
stream(bool, default:False) –Whether to stream the planning and solving process.
Examples:
>>> import lazyllm
>>> import wikipedia
>>> from lazyllm.tools import fc_register, ReWOOAgent
>>> @fc_register("tool")
>>> def WikipediaWorker(input: str):
... '''
... Worker that search for similar page contents from Wikipedia. Useful when you need to get holistic knowledge about people, places, companies, historical events, or other subjects. The response are long and might contain some irrelevant information. Input should be a search query.
...
... Args:
... input (str): search query.
... '''
... try:
... evidence = wikipedia.page(input).content
... evidence = evidence.split("\n\n")[0]
... except wikipedia.PageError:
... evidence = f"Could not find [{input}]. Similar: {wikipedia.search(input)}"
... except wikipedia.DisambiguationError:
... evidence = f"Could not find [{input}]. Similar: {wikipedia.search(input)}"
... return evidence
...
>>> @fc_register("tool")
>>> def LLMWorker(input: str):
... '''
... A pretrained LLM like yourself. Useful when you need to act with general world knowledge and common sense. Prioritize it when you are confident in solving the problem yourself. Input can be any instruction.
...
... Args:
... input (str): instruction
... '''
... llm = lazyllm.OnlineChatModule(source="glm")
... query = f"Respond in short directly with no extra words.\n\n{input}"
... response = llm(query, llm_chat_history=[])
... return response
...
>>> tools = ["WikipediaWorker", "LLMWorker"]
>>> llm = lazyllm.TrainableModule("GLM-4-9B-Chat").deploy_method(lazyllm.deploy.vllm).start() # or llm = lazyllm.OnlineChatModule(source="sensenova")
>>> agent = ReWOOAgent(llm, tools)
>>> query = "What is the name of the cognac house that makes the main ingredient in The Hennchata?"
>>> res = agent(query)
>>> print(res)
'
Hennessy '
Source code in lazyllm/tools/agent/rewooAgent.py
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 | |
lazyllm.tools.rag.smart_embedding_index.SmartEmbeddingIndex
Bases: IndexBase
Source code in lazyllm/tools/rag/smart_embedding_index.py
lazyllm.tools.rag.doc_node.ImageDocNode
Bases: DocNode
A specialized document node for handling image content in RAG systems.
ImageDocNode extends DocNode to provide specialized functionality for image processing and embedding generation. It automatically handles image loading, base64 encoding for embedding, and PIL Image objects for LLM processing.
Parameters:
-
image_path(str) –The file path to the image file. This should be a valid path to an image file (e.g., .jpg, .png, .jpeg).
-
uid(Optional[str], default:None) –Unique identifier for the document node. If not provided, a UUID will be automatically generated.
-
group(Optional[str], default:None) –The group name this node belongs to. Used for organizing and filtering nodes.
-
embedding(Optional[Dict[str, List[float]]], default:None) –Pre-computed embeddings for the image. Keys are embedding model names, values are embedding vectors.
-
parent(Optional[DocNode], default:None) –Parent node in the document hierarchy. Used for building document trees.
-
metadata(Optional[Dict[str, Any]], default:None) –Additional metadata associated with the image node.
-
global_metadata(Optional[Dict[str, Any]], default:None) –Global metadata that applies to all nodes in the document.
-
text(Optional[str], default:None) –Optional text description or caption for the image.
Examples:
>>> from lazyllm.tools.rag.doc_node import ImageDocNode, MetadataMode
>>> import numpy as np
>>> image_node = ImageDocNode(
... image_path="/home/mnt/yehongfei/Code/Test/framework.jpg",
... text="这是一张照片"
)
>>> def clip_emb(content, modality="image"):
... if modality == "image":
... return [np.random.rand(512).tolist()]
... return [np.random.rand(256).tolist()]
>>> embed_functions = {"clip": clip_emb}
>>> image_node.do_embedding(embed_functions)
>>> print(f"嵌入维度: {len(image_node.embedding['clip'])}")
>>> text_representation = image_node.get_text()
>>> content_representation = image_node.get_content(MetadataMode.EMBED)
>>> print(f"text属性: {text_representation}")
>>> print(f"content属性: {content_representation}")
Source code in lazyllm/tools/rag/doc_node.py
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 | |
do_embedding(embed)
Generate embeddings for the image using the provided embedding functions.
This method overrides the parent class method to handle image-specific embedding generation. It automatically converts the image to the appropriate format (base64 for embedding) and calls the embedding functions with the image modality.
Parameters:
-
embed(Dict[str, Callable]) –Dictionary of embedding functions. Keys are embedding model names, values are callable functions that accept (content, modality) and return embedding vectors.
Source code in lazyllm/tools/rag/doc_node.py
get_content(metadata_mode=MetadataMode.LLM)
Get the image content in different formats based on the metadata mode.
This method returns the image content in different formats depending on the intended use case. For LLM processing, it returns a PIL Image object. For embedding generation, it returns a base64-encoded image string.
Parameters:
-
metadata_mode(MetadataMode, default:LLM) –The mode for content retrieval. Defaults to MetadataMode.LLM. - MetadataMode.LLM: Returns PIL Image object for LLM processing - MetadataMode.EMBED: Returns base64-encoded image for embedding generation - Other modes: Returns the image path as text
Returns:
- Union[PIL.Image.Image, List[str], str]: The image content in the requested format.
Source code in lazyllm/tools/rag/doc_node.py
get_text()
Get the image path as text representation.
This method overrides the parent class method to return the image path instead of the content field, since ImageDocNode doesn't use the content field for storing text.
Returns:
- str: The image file path.
Source code in lazyllm/tools/rag/doc_node.py
lazyllm.tools.rag.transform.AdaptiveTransform
Bases: NodeTransform
A flexible document transformation system that applies different transforms based on document patterns.
AdaptiveTransform allows you to define multiple transformation strategies and automatically selects the appropriate one based on the document's file path or custom pattern matching. This is particularly useful when you have different types of documents that require different processing approaches.
Parameters:
-
transforms(Union[List[Union[TransformArgs, Dict]], Union[TransformArgs, Dict]]) –A list of transform configurations or a single transform configuration.
-
num_workers(int, default:0) –Number of worker threads for parallel processing. Defaults to 0.
Examples:
>>> from lazyllm.tools.rag.transform import AdaptiveTransform, DocNode, SentenceSplitter
>>> doc1 = DocNode(text="这是第一个文档的内容。它包含多个句子。")
>>> doc2 = DocNode(text="这是第二个文档的内容。")
>>> transforms = [
... {
... 'f': SentenceSplitter,
... 'pattern': '*.txt',
... 'kwargs': {'chunk_size': 50, 'chunk_overlap': 10}
... },
... {
... 'f': SentenceSplitter,
... 'pattern': '*.pdf',
... 'kwargs': {'chunk_size': 100, 'chunk_overlap': 20}
... }
... ]
>>> adaptive = AdaptiveTransform(transforms)
>>> results1 = adaptive.transform(doc1)
>>> print(f"文档1转换结果: {len(results1)} 个块")
>>> for i, result in enumerate(results1):
... print(f" 块 {i+1}: {result.text}")
>>> results2 = adaptive.transform(doc2)
>>> print(f"文档2转换结果: {len(results2)} 个块")
>>> for i, result in enumerate(results2):
... print(f" 块 {i+1}: {result.text}")
Source code in lazyllm/tools/rag/transform.py
transform(document, **kwargs)
Transform a document using the appropriate transformation strategy based on pattern matching.
This method evaluates each transform configuration in order and applies the first one that matches the document's path pattern. The matching logic supports both glob patterns and custom callable functions.
Parameters:
-
document(DocNode) –The document node to be transformed.
-
**kwargs–Additional keyword arguments passed to the transform function.
Returns:
- List[Union[str, DocNode]]: A list of transformed results (strings or DocNode objects).
Source code in lazyllm/tools/rag/transform.py
lazyllm.tools.rag.rerank.ModuleReranker
Bases: Reranker
A reranker that uses trainable modules to reorder documents based on relevance to a query.
ModuleReranker is a specialized reranker that leverages trainable models (such as BGE-reranker, Cohere rerank, etc.) to improve the relevance of retrieved documents. It takes a list of documents and a query, then returns the documents reordered by their relevance scores.
Parameters:
-
name(str, default:'ModuleReranker') –The name of the reranker. Defaults to "ModuleReranker".
-
model(Union[Callable, str], default:None) –The reranking model. Can be either a model name (string) or a callable function.
-
target(Optional[str], default:None) –Defaults to None.
-
output_format(Optional[str], default:None) –The format for output processing. Defaults to None.
-
join(Union[bool, str], default:False) –Whether to join the results. Defaults to False.
-
**kwargs–Additional keyword arguments passed to the reranker model.
Examples:
>>> from lazyllm.tools.rag.rerank import ModuleReranker, DocNode
>>> def simple_reranker(query, documents, top_n):
... query_lower = query.lower()
... scores = []
... for i, doc in enumerate(documents):
... score = sum(1 for word in query_lower.split() if word in doc)
... scores.append((i, score))
... scores.sort(key=lambda x: x[1], reverse=True)
... return scores[:top_n]
>>> reranker = ModuleReranker(
... model=simple_reranker,
... topk=2
... )
>>> docs = [
... DocNode(text="机器学习算法在数据分析中应用广泛"),
... DocNode(text="深度学习模型需要大量训练数据"),
... DocNode(text="自然语言处理技术发展迅速"),
... DocNode(text="计算机视觉在自动驾驶中的应用")
... ]
>>> query = "机器学习"
>>> results = reranker.forward(docs, query)
>>> for i, doc in enumerate(results):
... print(f" {i+1}. : {doc.text}")
... print(f" 相关性分数: {doc.relevance_score:.4f}")
Source code in lazyllm/tools/rag/rerank.py
forward(nodes, query='')
Forward pass of the reranker that reorders documents based on relevance to the query.
This method takes a list of documents and a query, then uses the underlying reranking model to score and reorder the documents by relevance. The documents are processed in MetadataMode.EMBED format to ensure compatibility with the reranking model.
Parameters:
-
nodes(List[DocNode]) –List of document nodes to be reranked.
-
query(str, default:'') –The query string to rank documents against. Defaults to "".
Returns:
- List[DocNode]: List of document nodes reordered by relevance score, with relevance_score attribute added.
Source code in lazyllm/tools/rag/rerank.py
lazyllm.tools.rag.utils.DocListManager
Bases: ABC
Abstract base class for managing document lists and monitoring changes in a document directory.
Parameters:
-
path–Path of the document directory to monitor.
-
name–Name of the manager.
-
enable_path_monitoring–Whether to enable path monitoring.
Examples:
>>> import lazyllm
>>> from lazyllm.rag.utils import DocListManager
>>> manager = DocListManager(path='your_file_path/', name="test_manager", enable_path_monitoring=False)
>>> added_docs = manager.add_files([test_file_list])
>>> manager.enable_path_monitoring(True)
>>> deleted = manager.delete_files([delete_file_list])
Source code in lazyllm/tools/rag/utils.py
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 | |
enable_path_monitoring
property
writable
Enable or disable path monitoring for the document manager.
This method enables or disables the path monitoring functionality in the document manager. When enabled, a monitoring thread starts to handle path-related operations. When disabled, the thread stops and joins (waits for it to terminate).
Args:
val (bool): Whether to enable or disable path monitoring.
Notes:
- If val is True, path monitoring is enabled by setting _monitor_continue to True and starting the _monitor_thread.
- If val is False, path monitoring is disabled by setting _monitor_continue to False and joining the _monitor_thread if it is running.
- This method ensures thread-safe operation when managing the monitoring thread.
add_files(files, metadatas=None, status=Status.waiting, batch_size=64)
Add multiple files to the document list with optional metadata, status, and batch processing.
This method adds a list of files to the database and sets optional metadata and initial status for each file. The files are processed in batches for efficiency. After the files are added, they are automatically associated with the default knowledge base (KB) group.
Args:
files (List[str]): A list of file paths to add to the database.
metadatas (Optional[List[Dict[str, Any]]]): A list of metadata dictionaries corresponding to the files. If None, no metadata will be associated. Defaults to None.
status (Optional[str]): The initial status for the added files. Defaults to Status.waiting.
batch_size (int): The number of files to process in each batch. Defaults to 64.
Returns::
List[DocPartRow]: A list of DocPartRow objects representing the added files and their associated information.
Notes:
- The method first creates document records using the helper function _add_doc_records.
- After the files are added, they are automatically linked to the default knowledge base group (DocListManager.DEFAULT_GROUP_NAME).
- Batch processing ensures good scalability when adding a large number of files.
Source code in lazyllm/tools/rag/utils.py
add_files_to_kb_group(file_ids, group)
abstractmethod
Adds files to the specified knowledge base group.
Parameters:
-
file_ids(list of str) –List of file IDs to add.
-
group(str) –Name of the group to add the files to.
Source code in lazyllm/tools/rag/utils.py
add_kb_group(name)
abstractmethod
delete_files(file_ids)
Set the knowledge base entries associated with the document to "deleting," and have each knowledge base asynchronously delete parsed results and associated records.
Parameters:
-
file_ids(list of str) –List of file IDs to delete.
Source code in lazyllm/tools/rag/utils.py
delete_files_from_kb_group(file_ids, group)
abstractmethod
Deletes files from the specified knowledge base group.
Parameters:
-
file_ids(list of str) –List of file IDs to delete.
-
group(str) –Name of the group.
Source code in lazyllm/tools/rag/utils.py
delete_unreferenced_doc()
abstractmethod
Delete documents marked as "deleting" and no longer referenced in the database.
This method removes documents from the database that meet the following conditions:
1. Their status is set to DocListManager.Status.deleting.
2. Their reference count (count) is 0.
Source code in lazyllm/tools/rag/utils.py
fetch_docs_changed_meta(group)
abstractmethod
List files in a specific knowledge base (KB) group with optional filters, limiting, and details.
This method retrieves files from the kb_group_documents table, optionally filtering by group, document status, upload status, and whether reparsing is needed.
Args:
group (str): The name of the group to filter documents by.
Returns:
List[DocMetaChangedRow]: A list of rows, where each row contains the doc_id and the new_meta field of documents with changed metadata.
Notes:
- This method constructs a SQL query dynamically based on the provided filters.
- Uses a thread-safe lock (self._db_lock) to ensure safe database access.
- If status or upload_status are provided as lists, they are processed with SQL IN clauses.
Source code in lazyllm/tools/rag/utils.py
get_docs(doc_ids)
abstractmethod
This method retrieves document objects of type KBDocument from the database for the provided list of document IDs.
Args:
doc_ids (List[str]): A list of document IDs to fetch.
Returns:
List[KBDocument]: A list of KBDocument objects corresponding to the provided document IDs. If no documents are found, an empty list is returned.
Notes:
- The method uses a thread-safe lock (self._db_lock) to ensure safe database access.
- It performs a SQL join between KBDocument and KBGroupDocuments to retrieve the relevant rows.
- After fetching, it updates the new_meta field of the affected rows to None and commits the changes to the database.
Source code in lazyllm/tools/rag/utils.py
get_docs_need_reparse(group=None)
abstractmethod
Retrieve documents that require reparsing for a specific group.
This method fetches documents that are marked as needing reparsing (need_reparse=True) for the given group. Only documents with a status of success or failed are included in the results.
Args:
group (str): The name of the group to filter documents by.
Returns::
List[KBDocument]: A list of KBDocument objects that need reparsing.
Notes:
- The method uses a thread-safe lock (self._db_lock) to ensure safe database access.
- The query performs a SQL JOIN between KBDocument and KBGroupDocuments to filter by group and reparse status.
- Documents with need_reparse=True and a status of success or failed are considered for reparsing.
Source code in lazyllm/tools/rag/utils.py
get_existing_paths_by_pattern(file_path)
abstractmethod
Retrieve existing document paths that match a given pattern.
This method fetches all document paths from the database that match the provided SQL LIKE pattern.
Args:
pattern (str): The SQL LIKE pattern to filter document paths. For example, %example% matches paths containing the word "example".
Returns::
List[str]: A list of document paths that match the given pattern. If no paths match, an empty list is returned.
Notes:
- The method uses a thread-safe lock (self._db_lock) to ensure safe database access.
- The LIKE operator in the SQL query is used to perform pattern matching on document paths.
Source code in lazyllm/tools/rag/utils.py
get_file_status(fileid)
abstractmethod
Retrieves the status of a specified file.
Parameters:
-
fileid(str) –File ID.
Returns: - str: The current status of the file.
init_tables()
Ensure that the default group exists in the database tables.
Source code in lazyllm/tools/rag/utils.py
list_all_kb_group()
abstractmethod
Lists all the knowledge base group names.
Returns: - list: List of knowledge base group names.
list_files(limit=None, details=False, status=Status.all, exclude_status=None)
abstractmethod
Lists files from the documents table with optional filtering, limiting, and returning details.
This method retrieves file IDs or detailed file information from the database, based on the specified filtering conditions.
Args:
limit (Optional[int]): Maximum number of files to return. If None, all matching files will be returned.
details (bool): Whether to return detailed file information (True) or just file IDs (False).
status (Union[str, List[str]]): The status or list of statuses to include in the results. Defaults to all statuses.
exclude_status (Optional[Union[str, List[str]]]): The status or list of statuses to exclude from the results. Defaults to None.
Returns:
List: A list of file IDs if details=False, or a list of detailed file rows if details=True.
Notes:
- The method constructs a query dynamically based on the provided status and exclude_status conditions.
- A thread-safe lock (self._db_lock) ensures safe database access.
- The LIMIT clause is applied if limit is specified.
Source code in lazyllm/tools/rag/utils.py
list_kb_group_files(group=None, limit=None, details=False, status=Status.all, exclude_status=None, upload_status=Status.all, exclude_upload_status=None, need_reparse=False)
abstractmethod
List files in a specific knowledge base group .
Parameters:
-
group(str, default:None) –The name of the KB group to filter files by. Defaults to
None. -
limit(Optional[int], default:None) –Maximum number of files to return. If
None, returns all matching files. -
details(bool, default:False) –Whether to return detailed file information or only file IDs and paths.
-
status(Union[str, List[str]], default:all) –The KB group status or list of statuses to include in the results. Defaults to all statuses.
-
exclude_status(Optional[Union[str, List[str]], default:None) –The KB group status or list of statuses to exclude from the results. Defaults to
None. -
upload_status(Union[str, List[str]], default:all) –The document upload status or list of statuses to include in the results. Defaults to all statuses.
-
exclude_upload_status(Optional[Union[str, List[str]], default:None) –The document upload status or list of statuses to exclude from the results. Defaults to
None. -
need_reparse(Optional[bool], default:False) –Whether to filter files that need reparsing or not . Defaults to
None.
Returns::
List: If details=False, returns a list of tuples containing (doc_id, path).
If details=True, returns a list of detailed rows with additional metadata.
Notes:
- The method first creates document records using the _add_doc_records helper function.
- After the files are added, they are automatically linked to the default KB group (DocListManager.DEFAULT_GROUP_NAME).
- Batch processing ensures scalability when adding a large number of files.
Source code in lazyllm/tools/rag/utils.py
release()
abstractmethod
set_docs_new_meta(doc_meta)
abstractmethod
Batch update metadata for documents.
Parameters:
-
doc_meta(Dict[str, dict]) –A dictionary mapping document IDs to their new metadata.
table_inited()
abstractmethod
Checks if the database table documents is initialized. This method ensures thread-safety when accessing the database.
Determines whether the documents table exists in the database.
Returns:
bool: True if the documents table exists, False otherwise.
Notes:
- Uses a thread-safe lock (self._db_lock) to ensure safe access to the database.
- Establishes a connection to the SQLite database at self._db_path with the check_same_thread option.
- Executes the SQL query: SELECT name FROM sqlite_master WHERE type='table' AND name='documents' to check for the table.
Source code in lazyllm/tools/rag/utils.py
update_file_message(fileid, **kw)
abstractmethod
Updates the message for a specified file.
Parameters:
-
fileid(str) –File ID.
-
**kw–Additional key-value pairs to update.
update_file_status(file_ids, status, cond_status_list=None)
abstractmethod
Update the status of specified files.
Parameters:
-
file_ids(list of str) –List of file IDs whose status needs to be updated.
-
status(str) –Target status to set.
-
cond_status_list(Union[None, List[str]], default:None) –Optional. Only update files currently in these statuses.
Source code in lazyllm/tools/rag/utils.py
update_kb_group(cond_file_ids, cond_group=None, cond_status_list=None, new_status=None, new_need_reparse=None)
abstractmethod
Updates the record of kb_group_document.
Parameters:
-
cond_file_ids(list of str) –a list of file IDs to filter by, default None.
-
cond_group(str, default:None) –a kb_group name to filter by, default None.
-
cond_status_list(list of str, default:None) –a list of statuses to filter by, default None.
-
new_status(str, default:None) –the new status to update to, default None
-
new_need_reparse((bool, optinoal), default:None) –the new need_reparse flag to update to, default None
Returns: - list: updated records, list of (doc_id, group_name)
Source code in lazyllm/tools/rag/utils.py
update_need_reparsing(doc_id, need_reparse)
abstractmethod
Updates the need_reparse status of a document in the KBGroupDocuments table.
This method sets the need_reparse flag for a specific document, optionally scoped to a given group.
Args:
doc_id (str): The ID of the document to update.
need_reparse (bool): The new value for the need_reparse flag.
group_name (Optional[str]): If provided, the update will be applied only to the specified group.
Notes:
- Uses a thread-safe lock (self._db_lock) to ensure safe database access.
- The group_name parameter allows scoping the update to a specific group; if not provided, the update applies to all groups containing the document.
- The method commits the change to the database immediately.
Source code in lazyllm/tools/rag/utils.py
validate_paths(paths)
abstractmethod
Validates a list of file paths to ensure they are ready for processing.
This method checks whether the provided paths are new, already processed, or currently being processed. It ensures there are no conflicts in processing the documents.
Args
paths (List[str]): A list of file paths to validate.
Returns:
Tuple[bool, str, List[bool]]: A tuple containing:
- bool: True if all paths are valid, False otherwise.
- str: A message indicating success or the reason for failure.
- List[bool]: A list where each element corresponds to whether a path is new (True) or already exists (False).
Notes:
- If any document is still being processed or needs reparsing, the method returns False with an appropriate error message.
- The method uses a database session and thread-safe lock (self._db_lock) to retrieve document status information.
- Unsafe statuses include working and waiting.
Source code in lazyllm/tools/rag/utils.py
lazyllm.tools.rag.global_metadata.GlobalMetadataDesc
A descriptor for global metadata, defining its type, optional element type, default value, and size constraints.
class GlobalMetadataDesc
This class is used to describe metadata properties such as type, optional constraints, and default values. It supports scalar and array data types, with specific size limitations for certain types.
Args:
data_type (int): The type of the metadata as an integer, representing various data types (e.g., VARCHAR, ARRAY, etc.).
element_type (Optional[int]): The type of individual elements if data_type is an array. Defaults to None.
default_value (Optional[Any]): The default value for the metadata. If not provided, the default will be None.
max_size (Optional[int]): The maximum size or length for the metadata. Required if data_type is VARCHAR or ARRAY.
Source code in lazyllm/tools/rag/global_metadata.py
lazyllm.tools.rag.IndexBase.update(nodes)
abstractmethod
Update index contents.
This method receives a list of document nodes and updates or inserts them into the index structure. Typically used for incremental indexing or refreshing data.
Parameters:
-
nodes(List[DocNode]) –A list of document nodes to update or insert.
Source code in lazyllm/tools/rag/index_base.py
lazyllm.tools.rag.IndexBase.remove(uids, group_name=None)
abstractmethod
Remove specific document nodes from the index.
Removes document nodes based on their unique identifiers, optionally scoped by group name.
Parameters:
-
uids(List[str]) –List of unique IDs corresponding to the document nodes to remove.
-
group_name(Optional[str], default:None) –Optional group name to scope the removal operation.
Source code in lazyllm/tools/rag/index_base.py
lazyllm.tools.rag.IndexBase.query(*args, **kwargs)
abstractmethod
Execute a query over the index.
Performs a query based on the given arguments and returns matching document nodes. The logic depends on the specific implementation.
Returns:
-
List[DocNode]–List[DocNode]: A list of matched document nodes from the index.
Source code in lazyllm/tools/rag/index_base.py
lazyllm.tools.rag.index_base.IndexBase
Bases: ABC
An abstract base class for implementing indexing systems that support updating, removing, and querying document nodes.
class IndexBase(ABC)
This abstract base class defines the interface for an indexing system. It requires subclasses to implement methods for updating, removing, and querying document nodes.
Examples:
>>> from mymodule import IndexBase, DocNode
>>> class MyIndex(IndexBase):
... def __init__(self):
... self.nodes = []
... def update(self, nodes):
... self.nodes.extend(nodes)
... print(f"Updated nodes: {nodes}")
... def remove(self, uids, group_name=None):
... self.nodes = [node for node in self.nodes if node.uid not in uids]
... print(f"Removed nodes with uids: {uids}")
... def query(self, *args, **kwargs):
... print("Querying nodes...")
... return self.nodes
>>> index = MyIndex()
>>> doc1 = DocNode(uid="1", content="Document 1")
>>> doc2 = DocNode(uid="2", content="Document 2")
>>> index.update([doc1, doc2])
Updated nodes: [DocNode(uid="1", content="Document 1"), DocNode(uid="2", content="Document 2")]
>>> index.query()
Querying nodes...
[DocNode(uid="1", content="Document 1"), DocNode(uid="2", content="Document 2")]
>>> index.remove(["1"])
Removed nodes with uids: ['1']
>>> index.query()
Querying nodes...
[DocNode(uid="2", content="Document 2")]
Source code in lazyllm/tools/rag/index_base.py
query(*args, **kwargs)
abstractmethod
Execute a query over the index.
Performs a query based on the given arguments and returns matching document nodes. The logic depends on the specific implementation.
Returns:
-
List[DocNode]–List[DocNode]: A list of matched document nodes from the index.
Source code in lazyllm/tools/rag/index_base.py
remove(uids, group_name=None)
abstractmethod
Remove specific document nodes from the index.
Removes document nodes based on their unique identifiers, optionally scoped by group name.
Parameters:
-
uids(List[str]) –List of unique IDs corresponding to the document nodes to remove.
-
group_name(Optional[str], default:None) –Optional group name to scope the removal operation.
Source code in lazyllm/tools/rag/index_base.py
update(nodes)
abstractmethod
Update index contents.
This method receives a list of document nodes and updates or inserts them into the index structure. Typically used for incremental indexing or refreshing data.
Parameters:
-
nodes(List[DocNode]) –A list of document nodes to update or insert.
Source code in lazyllm/tools/rag/index_base.py
lazyllm.tools.BaseEvaluator
Bases: ModuleBase
Abstract base class for evaluation modules.
This class defines the standard interface and retry logic for evaluating model outputs. It supports concurrent processing, input validation, and automatic result saving.
Parameters:
-
concurrency(int, default:1) –Number of concurrent threads used during evaluation.
-
retry(int, default:3) –Number of retry attempts for each evaluation item.
-
log_base_name(Optional[str], default:None) –Optional log file name prefix for saving results.
Examples:
>>> from lazyllm.components import BaseEvaluator
>>> class SimpleAccuracyEvaluator(BaseEvaluator):
... def _process_one_data_impl(self, data):
... return {
... "final_score": float(data["pred"] == data["label"])
... }
>>> evaluator = SimpleAccuracyEvaluator()
>>> score = evaluator([
... {"pred": "yes", "label": "yes"},
... {"pred": "no", "label": "yes"}
... ])
>>> print(score)
... 0.5
Source code in lazyllm/tools/eval/eval_base.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 | |
lazyllm.tools.ResponseRelevancy
Bases: BaseEvaluator
Evaluator for measuring the semantic relevancy between a user-generated question and a model-generated one.
This evaluator uses a language model to generate possible questions from an answer, and measures their semantic similarity to the original question using embeddings and cosine similarity.
Parameters:
-
llm(ModuleBase) –A language model used to generate inferred questions from the given answer.
-
embedding(ModuleBase) –An embedding module to encode questions for similarity comparison.
-
prompt(str, default:None) –Custom prompt to guide the question generation. If not provided, a default will be used.
-
prompt_lang(str, default:'en') –Language for the default prompt. Options:
'en'(default) or'zh'. -
num_infer_questions(int, default:3) –Number of questions to generate and evaluate for each answer.
-
retry(int, default:3) –Number of retry attempts if generation fails.
-
concurrency(int, default:1) –Number of concurrent evaluations.
Examples:
>>> from lazyllm.components import ResponseRelevancy
>>> relevancy = ResponseRelevancy(
... llm=YourLLM(),
... embedding=YourEmbedding(),
... prompt_lang="en",
... num_infer_questions=3
... )
>>> result = relevancy([
... {"question": "What is the capital of France?", "answer": "Paris is the capital city of France."}
... ])
>>> print(result)
... 0.95 # (a float score between 0 and 1)
Source code in lazyllm/tools/eval/rag_generator_metrics.py
lazyllm.tools.Faithfulness
Bases: BaseEvaluator
Evaluator that measures the factual consistency of an answer with the given context.
This evaluator splits the answer into atomic factual statements using a generation model, then verifies each against the context using binary (1/0) scoring. It computes a final score as the average of the individual statement scores.
Parameters:
-
llm(ModuleBase) –A language model capable of both generating statements and evaluating them.
-
generate_prompt(str, default:None) –Custom prompt to generate factual statements from the answer.
-
eval_prompt(str, default:None) –Custom prompt to evaluate statement support within the context.
-
prompt_lang(str, default:'en') –Language of the default prompt, either 'en' or 'zh'.
-
retry(int, default:3) –Number of retry attempts when generation or evaluation fails.
-
concurrency(int, default:1) –Number of concurrent evaluations to run in parallel.
Examples:
>>> from lazyllm.components import Faithfulness
>>> evaluator = Faithfulness(llm=YourLLM(), prompt_lang="en")
>>> data = {
... "question": "What is the role of ATP in cells?",
... "answer": "ATP stores energy and transfers it within cells.",
... "context": "ATP is the energy currency of the cell. It provides energy for many biochemical reactions."
... }
>>> result = evaluator([data])
>>> print(result)
... 1.0 # Average binary score of all factual statements
Source code in lazyllm/tools/eval/rag_generator_metrics.py
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 | |
lazyllm.tools.LLMContextRecall
Bases: BaseEvaluator
Source code in lazyllm/tools/eval/rag_retriever_metrics.py
lazyllm.tools.NonLLMContextRecall
Bases: BaseEvaluator
Source code in lazyllm/tools/eval/rag_retriever_metrics.py
lazyllm.tools.ContextRelevance
Bases: BaseEvaluator
Source code in lazyllm/tools/eval/rag_retriever_metrics.py
lazyllm.tools.HttpRequest
Bases: ModuleBase
General HTTP request executor.
This class builds and sends HTTP requests with support for dynamic variable substitution, API key injection, JSON or form data encoding, and file-aware response parsing.
Parameters:
-
method(str) –HTTP method, such as 'GET', 'POST', etc.
-
url(str) –The target URL for the HTTP request.
-
api_key(str) –Optional API key, inserted into query parameters.
-
headers(dict) –HTTP request headers.
-
params(dict) –URL query parameters.
-
body(Union[str, dict]) –HTTP request body (raw string or JSON-formatted dict).
-
timeout(int, default:10) –Timeout duration for the request (in seconds).
-
proxies(dict, default:None) –Proxy settings for the request, if needed.
Examples:
>>> from lazyllm.components import HttpRequest
>>> request = HttpRequest(
... method="GET",
... url="https://api.github.com/repos/openai/openai-python",
... api_key="",
... headers={"Accept": "application/json"},
... params={},
... body=None
... )
>>> result = request()
>>> print(result["status_code"])
... 200
>>> print(result["content"][:100])
... '{"id":123456,"name":"openai-python", ...}'
Source code in lazyllm/tools/http_request/http_request.py
7 8 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 | |
lazyllm.tools.JobDescription
Bases: BaseModel
Model deployment job description schema.
Used to specify the configuration for creating a model inference job, including model name and GPU requirements.
Parameters:
-
deploy_model(str) –The model to be deployed. Default is "qwen1.5-0.5b-chat".
-
num_gpus(int) –Number of GPUs required for deployment. Default is 1.
Examples:
>>> from lazyllm.components import JobDescription
>>> job = JobDescription(deploy_model="deepseek-coder", num_gpus=2)
>>> print(job.dict())
... {'deploy_model': 'deepseek-coder', 'num_gpus': 2}
Source code in lazyllm/tools/infer_service/serve.py
lazyllm.tools.DBManager
Bases: ABC, ModuleBase
Abstract base class for database managers.
This class defines the standard interface and helpers for building database connectors, including a required execute_query method and description property.
Parameters:
-
db_type(str) –Type identifier of the database (e.g., 'mysql', 'mongodb').
Examples:
>>> from lazyllm.components import DBManager
>>> class DummyDB(DBManager):
... def __init__(self):
... super().__init__(db_type="dummy")
... def execute_query(self, statement):
... return f"Executed: {statement}"
... @property
... def desc(self):
... return "Dummy database for testing."
>>> db = DummyDB()
>>> print(db("SELECT * FROM test"))
... Executed: SELECT * FROM test
Source code in lazyllm/tools/sql/db_manager.py
execute_query(statement)
abstractmethod
Abstract method for executing database query statements. This method needs to be implemented by specific database manager subclasses to execute various database operations.
Parameters:
-
statement–The database query statement to execute, which can be SQL statements or other database-specific query languages
Features of this method:
- Abstract Method: Requires implementation of specific database operation logic in subclasses
- Unified Interface: Provides a unified query interface for different database types
- Error Handling: Subclass implementations should include appropriate error handling and status reporting
- Result Formatting: Returns formatted string results for subsequent processing
Note: This method is the core method of the database manager, and all specific database operations are executed through this method.
Source code in lazyllm/tools/sql/db_manager.py
lazyllm.tools.MongoDBManager
Bases: DBManager
Source code in lazyllm/tools/sql/mongodb_manager.py
lazyllm.tools.HttpTool
Bases: HttpRequest
Module for accessing third-party services and executing custom code. The values in params and headers, as well as in body, can include template variables marked with double curly braces like {{variable}}, which are then replaced with actual values through parameters when called. Refer to the usage instructions in [[lazyllm.tools.HttpTool.forward]].
Parameters:
-
method(str, default:None) –Specifies the HTTP request method, refer to
https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods. -
url(str, default:None) –The URL to access. If this field is empty, it indicates that the module does not need to access third-party services.
-
params(Dict[str, str], default:None) –Params fields to be filled when requesting the URL. If the URL is empty, this field will be ignored.
-
headers(Dict[str, str], default:None) –Header fields to be filled when accessing the URL. If the URL is empty, this field will be ignored.
-
body(Dict[str, str], default:None) –Body fields to be filled when requesting the URL. If the URL is empty, this field will be ignored.
-
timeout(int, default:10) –Request timeout in seconds, default value is 10.
-
proxies(Dict[str, str], default:None) –Specifies the proxies to be used when requesting the URL. Proxy format refer to
https://www.python-httpx.org/advanced/proxies. -
code_str(str, default:None) –A string containing a user-defined function. If the parameter url is empty, execute this function directly, forwarding all arguments to it; if url is not empty, the parameters of this function are the results returned from the URL request, and in this case, the function serves as a post-processing function for the URL response.
-
vars_for_code(Dict[str, Any], default:None) –A dictionary that includes dependencies and variables required for running the code.
-
outputs(Optional[List[str]], default:None) –Names of expected output fields.
-
extract_from_result(Optional[bool], default:None) –Whether to extract fields directly from response dict using
outputs.
Examples:
from lazyllm.tools import HttpTool
code_str = "def identity(content): return content"
tool = HttpTool(method='GET', url='http://www.sensetime.com/', code_str=code_str)
ret = tool()
Source code in lazyllm/tools/tools/http_tool.py
forward(*args, **kwargs)
Used to perform operations specified during initialization: request the specified URL or execute the passed function. Generally not called directly, but through the base class's __call__. If the url parameter in the constructor is not empty, all passed parameters will be used as variables to replace template parameters marked with {{}} in the constructor; if the url parameter in the constructor is empty and code_str is not empty, all passed parameters will be used as arguments for the function defined in code_str.
Examples:
from lazyllm.tools import HttpTool
code_str = "def exp(v, n): return v ** n"
tool = HttpTool(code_str=code_str)
assert tool(v=10, n=2) == 100
Source code in lazyllm/tools/tools/http_tool.py
lazyllm.tools.agent.functionCall.StreamResponse
StreamResponse class encapsulates streaming output behavior with configurable prefix and colors.
When streaming is enabled, calling the instance enqueues colored text to a filesystem queue for asynchronous processing or display.
Parameters:
-
prefix(str) –Prefix text before the output, typically used to indicate the source or category.
-
prefix_color(Optional[str], default:None) –Color of the prefix text, supports terminal color codes, defaults to None.
-
color(Optional[str], default:None) –Color of the main content text, supports terminal color codes, defaults to None.
-
stream(bool, default:False) –Whether to enable streaming output mode, which enqueues text to the filesystem queue, defaults to False.
Examples:
>>> from lazyllm.tools.agent.functionCall import StreamResponse
>>> resp = StreamResponse(prefix="[INFO]", prefix_color="green", color="white", stream=True)
>>> resp("Hello, world!")
Hello, world!
Source code in lazyllm/tools/agent/functionCall.py
lazyllm.tools.MCPClient
Bases: object
Source code in lazyllm/tools/mcp/client.py
lazyllm.tools.tools.GoogleSearch
Bases: HttpTool
Search for specified keywords through Google.
Parameters:
-
custom_search_api_key(str) –The Google API key applied by the user.
-
search_engine_id(str) –The ID of the search engine created by the user for retrieval.
-
timeout(int, default:10) –The timeout for the search request, in seconds, default is 10.
-
proxies(Dict[str, str], default:None) –The proxy services used during the request. Format reference
https://www.python-httpx.org/advanced/proxies.
Examples:
from lazyllm.tools.tools import GoogleSearch
key = '<your_google_search_api_key>'
cx = '<your_search_engine_id>'
google = GoogleSearch(custom_search_api_key=key, search_engine_id=cx)
Source code in lazyllm/tools/tools/google_search.py
forward(query, date_restrict='m1', search_engine_id=None)
Execute search request.
Parameters:
-
query(str) –Keywords to retrieve.
-
date_restrict(str, default:'m1') –Timeliness of the content to retrieve. Defaults to web pages within one month (m1). Refer to
https://developers.google.com/custom-search/v1/reference/rest/v1/cse/list?hl=zh-cnfor parameter format. -
search_engine_id(str, default:None) –Search engine ID for retrieval. If this value is empty, the value passed in the constructor is used.
Examples:
from lazyllm.tools.tools import GoogleSearch
key = '<your_google_search_api_key>'
cx = '<your_search_engine_id>'
google = GoogleSearch(key, cx)
res = google(query='商汤科技', date_restrict='m1')
Source code in lazyllm/tools/tools/google_search.py
lazyllm.tools.tools.tencent_search.TencentSearch
Bases: ModuleBase
This is a search enhancement tool.
Examples:
from lazyllm.tools.tools import TencentSearch
secret_id = '<your_secret_id>'
secret_key = '<your_secret_key>'
searcher = TencentSearch(secret_id, secret_key)
Source code in lazyllm/tools/tools/tencent_search.py
forward(query)
Searches for the query entered by the user.
Parameters:
-
query(str) –The content that the user wants to query.
Examples:
from lazyllm.tools.tools import TencentSearch
secret_id = '<your_secret_id>'
secret_key = '<your_secret_key>'
searcher = TencentSearch(secret_id, secret_key)
res = searcher('calculus')
Source code in lazyllm/tools/tools/tencent_search.py
lazyllm.tools.rag.web.WebUi
A Gradio-based web UI for managing knowledge base files.
This class provides an interactive UI to create/delete groups, upload files, list files, and perform deletion operations via RESTful APIs. It is designed for rapid integration of file and group management.
Parameters:
-
base_url(str) –Base URL of the backend API service.
Source code in lazyllm/tools/rag/web.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 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 | |
basic_headers(content_type=True)
Generate standard HTTP headers.
Parameters:
-
content_type(bool, default:True) –Whether to include Content-Type in the headers (default: True).
Returns:
-
dict–Dictionary of HTTP headers.
Source code in lazyllm/tools/rag/web.py
create_ui()
Build a Gradio-based file management UI, including tabs for group listing, file uploading, viewing, and deletion.
Returns:
-
–
gr.Blocks: A complete Gradio application instance.
Source code in lazyllm/tools/rag/web.py
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 | |
delete_file(group_name, file_ids)
Delete specific files from a group.
Parameters:
-
group_name(str) –Name of the group.
-
file_ids(List[str]) –IDs of files to delete.
Returns:
-
str–Deletion result message.
Source code in lazyllm/tools/rag/web.py
delete_group(group_name)
Delete a specific file group.
Parameters:
-
group_name(str) –Name of the group to delete.
Returns:
-
str–Server message about the deletion.
Source code in lazyllm/tools/rag/web.py
get_request(url)
Send a GET request.
Parameters:
-
url(str) –Target request URL.
Returns:
-
dict–JSON response from the server.
Source code in lazyllm/tools/rag/web.py
gr_show_list(str_list, list_name)
Display a list of strings as a Gradio DataFrame.
Parameters:
-
str_list(List) –List of strings or rows.
-
list_name(Union[str, List]) –Column name(s) for the table.
Returns:
-
–
gr.DataFrame: Gradio DataFrame component.
Source code in lazyllm/tools/rag/web.py
list_files_in_group(group_name)
List all files within a specific group.
Parameters:
-
group_name(str) –Name of the group.
Returns:
-
List–List of file information.
Source code in lazyllm/tools/rag/web.py
list_groups()
List all available file groups.
Returns:
-
–
List[str]: List of group names.
Source code in lazyllm/tools/rag/web.py
muti_headers()
Generate HTTP headers for file upload.
Returns:
-
dict–Dictionary of HTTP headers.
new_group(group_name)
Create a new file group.
Parameters:
-
group_name(str) –Name of the new group.
Returns:
-
str–Server message about the creation result.
Source code in lazyllm/tools/rag/web.py
post_request(url, data)
Send a POST request.
Parameters:
-
url(str) –Target request URL.
-
data(dict) –Request data (will be serialized as JSON).
Returns:
-
dict–JSON response from the server.
Source code in lazyllm/tools/rag/web.py
upload_files(group_name, override=True)
Upload files to a specified group.
Parameters:
-
group_name(str) –Name of the group.
-
override(bool, default:True) –Whether to override existing files (default: True).
Returns:
-
Any–Data returned by the backend.
Source code in lazyllm/tools/rag/web.py
lazyllm.tools.http_request.http_executor_response.HttpExecutorResponse
Source code in lazyllm/tools/http_request/http_executor_response.py
is_file
property
check if response is file
extract_file()
extract file from response if content type is file related
get_content_type()
Get the content type of the HTTP response.
Extracts the 'content-type' field value from the response headers to determine the type of response content.
Returns:
-
str(str) –The content type of the response, or empty string if not found.
Examples:
>>> from lazyllm.tools.http_request.http_executor_response import HttpExecutorResponse
>>> import httpx
>>> response = httpx.Response(200, headers={'content-type': 'application/json'})
>>> http_response = HttpExecutorResponse(response)
>>> content_type = http_response.get_content_type()
>>> print(content_type)
... 'application/json'