工具
lazyllm.tools.IntentClassifier
Bases: ModuleBase
意图分类模块,用于根据输入文本在给定的意图列表中进行分类。
支持中英文自动选择提示模板,并可通过示例、提示、约束和注意事项增强分类效果。
Parameters:
-
llm–用于意图分类的大语言模型实例。
-
intent_list(list, default:None) –可选,意图类别列表,例如 ["聊天", "天气", "问答"]。
-
prompt(str, default:'') –可选,自定义提示语,插入到系统提示模板中。
-
constrain(str, default:'') –可选,分类约束条件说明。
-
attention(str, default:'') –可选,提示注意事项。
-
examples(list[list[str, str]], default:None) –可选,分类示例列表,每个元素为 [输入文本, 标签]。
-
return_trace(bool, default:False) –是否返回执行过程的 trace,默认为 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)
意图分类的预处理 Hook。
将输入文本与意图列表打包为 JSON,并生成历史对话信息字符串。
Parameters:
-
input(str | List | Dict | None, default:None) –输入文本,仅支持字符串类型。
-
history(List, default:[]) –历史对话记录,默认为空列表。
-
tools(List[Dict] | None, default:None) –工具信息,可选。
-
label(str | None, default:None) –标签,可选。
Returns
- tuple: (输入数据字典, 历史记录列表, 工具信息, 标签)
Source code in lazyllm/tools/classifier/intent_classifier.py
post_process_result(input)
意图分类结果的后处理。
如果结果在意图列表中则直接返回,否则返回意图列表的第一个元素。
Parameters:
-
input(str) –分类模型输出结果。
Returns
- str: 最终的分类标签。
Source code in lazyllm/tools/classifier/intent_classifier.py
lazyllm.tools.Document
Bases: ModuleBase, BuiltinGroups
初始化一个具有可选用户界面的文档模块。
此构造函数初始化一个可以有或没有用户界面的文档模块。如果启用了用户界面,它还会提供一个ui界面来管理文档操作接口,并提供一个用于用户界面交互的网页。
Parameters:
-
dataset_path(str, default:None) –数据集目录的路径。此目录应包含要由文档模块管理的文档。
-
embed(Optional[Union[Callable, Dict[str, Callable]]], default:None) –用于生成文档 embedding 的对象。如果需要对文本生成多个 embedding,此处需要通过字典的方式指定多个 embedding 模型,key 标识 embedding 对应的名字, value 为对应的 embedding 模型。
-
create_ui(bool, default:False) –[已弃用] 是否创建用户界面。请改用'manager'参数
-
manager(bool, default:False) –指示是否为文档模块创建用户界面的标志。默认为 False。
-
server(Union[bool, int], default:False) –服务器配置。True表示默认服务器,False表示已指定端口号作为自定义服务器
-
name(Optional[str], default:None) –文档集合的名称标识符。云服务模式下必须提供
-
launcher(optional, default:None) –负责启动服务器模块的对象或函数。如果未提供,则使用
lazyllm.launchers中的默认异步启动器 (sync=False)。 -
doc_files(Optional[List[str]], default:None) –临时文档文件列表(dataset_path的替代方案)。使用时dataset_path必须为None且仅支持map存储类型
-
store_conf(optional, default:None) –配置使用哪种存储后端, 默认使用MapStore将切片数据存于内存中。
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 | |
add_reader(pattern, func=None)
用于实例指定文件读取器,作用范围仅对注册的 Document 对象可见。注册的文件读取器必须是 Callable 对象。只能通过函数调用的方式进行注册。并且通过实例注册的文件读取器的优先级高于通过类注册的文件读取器,并且实例和类注册的文件读取器的优先级高于系统默认的文件读取器。即优先级的顺序是:实例文件读取器 > 类文件读取器 > 系统默认文件读取器。
Parameters:
-
pattern(str) –文件读取器适用的匹配规则
-
func(Callable, default:None) –文件读取器,必须是Callable的对象
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)
创建一个由指定规则生成的 node group。
Parameters:
-
name(str, default:None) –node group 的名称。
-
transform(Callable) –将 node 转换成 node group 的转换规则,函数原型是
(DocNode, group_name, **kwargs) -> List[DocNode]。目前内置的有 SentenceSplitter。用户也可以自定义转换规则。 -
trans_node(bool, default:None) –决定了transform的输入和输出是
DocNode还是str,默认为None。只有在transform为Callable时才可以设置为true。 -
num_workers(int, default:0) –Transform时所用的新线程数量,默认为0
-
parent(str, default:LAZY_ROOT_NAME) –需要进一步转换的节点。转换之后得到的一系列新的节点将会作为该父节点的子节点。如果不指定则从根节点开始转换。
-
kwargs–和具体实现相关的参数。
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)
查找指定节点的子节点。
Parameters:
-
group(str) –需要查找的节点组名称
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)
查找指定节点的父节点。
Parameters:
-
group(str) –需要查找的节点组名称
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
用于指定文件读取器,作用范围对于所有的 Document 对象都可见。注册的文件读取器必须是 Callable 对象。可以使用装饰器的方式进行注册,也可以通过函数调用的方式进行注册。
Parameters:
-
pattern(str) –文件读取器适用的匹配规则
-
func(Callable, default:None) –文件读取器,必须是Callable的对象
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
基础文档读取器类,提供了文档加载的基本接口。继承自ModuleBase,使用LazyLLMRegisterMetaClass作为元类。
Parameters:
-
return_trace(bool, default:True) –是否返回处理过程的追踪信息。默认为True。
说明: - 提供了惰性加载和普通加载两种方式 - 子类需要实现_lazy_load_data方法 - 支持批量处理文档 - 自动转换为标准化的DocNode格式
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.readerBase.LazyLLMReaderBase
Bases: ModuleBase
基础文档读取器类,提供了文档加载的基本接口。继承自ModuleBase,使用LazyLLMRegisterMetaClass作为元类。
Parameters:
-
return_trace(bool, default:True) –是否返回处理过程的追踪信息。默认为True。
说明: - 提供了惰性加载和普通加载两种方式 - 子类需要实现_lazy_load_data方法 - 支持批量处理文档 - 自动转换为标准化的DocNode格式
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.PandasExcelReader
Bases: LazyLLMReaderBase
用于读取 Excel 文件(.xlsx),并将内容提取为文本。
Parameters:
-
concat_rows(bool, default:True) –是否将所有行拼接为一个文本块。
-
sheet_name(Optional[str], default:None) –要读取的工作表名称。若为 None,则读取所有工作表。
-
pandas_config(Optional[Dict], default:None) –pandas.read_excel 的可选配置项。
-
return_trace(bool, default:True) –是否返回处理过程的 trace。
Source code in lazyllm/tools/rag/readers/pandasReader.py
lazyllm.tools.rag.readers.PDFReader
Bases: LazyLLMReaderBase
用于读取 PDF 文件并提取其中的文本内容。
Parameters:
-
return_full_document(bool, default:False) –是否将整份 PDF 合并为一个文档节点。若为 False,则每页作为一个节点。
-
return_trace(bool, default:True) –是否返回处理过程的 trace,默认为 True。
Source code in lazyllm/tools/rag/readers/pdfReader.py
lazyllm.tools.rag.readers.PPTXReader
Bases: LazyLLMReaderBase
用于解析 PPTX(PowerPoint)文件的读取器,能够提取幻灯片中的文本,并对嵌入图像进行视觉描述生成。
Parameters:
-
return_trace(bool, default:True) –是否记录处理过程的 trace,默认为 True。
Source code in lazyllm/tools/rag/readers/pptxReader.py
lazyllm.tools.rag.readers.VideoAudioReader
Bases: LazyLLMReaderBase
用于从视频或音频文件中提取语音内容的读取器,依赖 OpenAI 的 Whisper 模型进行语音识别。
Parameters:
-
model_version(str, default:'base') –Whisper 模型的版本(如 "base", "small", "medium", "large"),默认为 "base"。
-
return_trace(bool, default:True) –是否返回处理过程的 trace,默认为 True。
Source code in lazyllm/tools/rag/readers/videoAudioReader.py
lazyllm.tools.SqlManager
Bases: DBManager
SqlManager是与数据库进行交互的专用工具。它提供了连接数据库,设置、创建、检查数据表,插入数据,执行查询的方法。
Parameters:
-
db_type(str) –"PostgreSQL","SQLite", "MySQL", "MSSQL"。注意当类型为"SQLite"时,db_name为文件路径或者":memory:"
-
user(str) –用户名
-
password(str) –密码
-
host(str) –主机名或IP
-
port(int) –端口号
-
db_name(str) –数据仓库名
-
**options_str(str, default:None) –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 340 | |
check_connection()
检查当前SqlManager的连接状态。
Returns:
- DBResult: DBResult.status 连接成功(True), 连接失败(False)。DBResult.detail 包含失败信息
Source code in lazyllm/tools/sql/sql_manager.py
create_table(table)
创建数据表
Parameters:
-
table(str / Type[DeclarativeBase] / DeclarativeMeta) –数据表schema。支持三种参数类型:类型为str的sql语句,继承自DeclarativeBase或继承自declarative_base()的ORM类
Source code in lazyllm/tools/sql/sql_manager.py
drop_table(table)
删除数据表
Parameters:
-
table(str / Type[DeclarativeBase] / DeclarativeMeta) –数据表schema。支持三种参数类型:类型为str的数据表名,继承自DeclarativeBase或继承自declarative_base()的ORM类
Source code in lazyllm/tools/sql/sql_manager.py
execute_commit(statement)
execute_query(statement)
执行sql查询脚本并以JSON字符串返回结果。
Source code in lazyllm/tools/sql/sql_manager.py
get_all_tables()
get_session()
这是一个上下文管理器,它创建并返回一个数据库连接Session,并在完成时自动提交或回滚更改并在使用完成后自动关闭会话。
Returns:
- sqlalchemy.orm.Session: sqlalchemy 数据库会话
Source code in lazyllm/tools/sql/sql_manager.py
get_table_orm_class(table_name)
返回数据表名对应的sqlalchemy orm类。结合get_session,进行orm操作
Source code in lazyllm/tools/sql/sql_manager.py
insert_values(table_name, vals)
批量数据插入
Parameters:
-
table_name(str) –数据表名
-
vals(List[dict]) –待插入数据,格式为[{"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={})
对于SqlManager搭配LLM使用自然语言查询的表项设置其描述,尤其当其表名、列名及取值不具有自解释能力时。 例如: 数据表Document的status列取值包括: "waiting", "working", "success", "failed",tables_desc_dict参数应为 {"Document": "status列取值包括: waiting, working, success, failed"}
Parameters:
-
tables_desc_dict(dict, default:{}) –表项的补充说明
Source code in lazyllm/tools/sql/sql_manager.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
文档信息结构中单个字段的定义。
Parameters:
-
key(str) –字段名
-
desc(str) –字段含义描述
-
type(str) –字段的数据类型
Source code in lazyllm/tools/rag/doc_to_db/doc_analysis.py
lazyllm.tools.rag.doc_to_db.DocGenreAnalyser
用于分析文档所属的类别,例如合同、简历、发票等。通过读取文档内容,并结合大模型判断其类型。
Parameters:
-
maximum_doc_num(int, default:3) –最多分析的文档数量,默认是 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
用于从文档中抽取出关键信息字段的结构,如字段名、描述、字段类型。可用于构建信息提取模板。
Parameters:
-
maximum_doc_num(int, default:3) –用于生成schema的最大文档数量,默认是 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)
分析文档信息模式的方法,用于从指定类型的文档中提取关键信息字段的结构定义。
Parameters:
-
llm(Union[OnlineChatModule, TrainableModule]) –用于生成信息模式的LLM模型
-
doc_type(str) –文档类型,用于指导LLM生成相应的信息模式
-
doc_paths(list[str]) –文档路径列表,用于分析的信息来源
Returns:
- DocInfoSchema: 包含关键信息字段定义的模式列表,每个字段包含key、desc、type三个属性
Source code in lazyllm/tools/rag/doc_to_db/doc_analysis.py
lazyllm.tools.rag.doc_to_db.DocInfoExtractor
根据给定的字段结构(schema)从文档中抽取具体的关键信息值,返回格式为 key-value 字典。
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='')
根据提供的字段结构(schema)从指定文档中抽取具体的关键信息值。
该方法使用大语言模型分析文档内容,根据预定义的字段结构提取相应的信息值,返回格式为 key-value 字典。
Parameters:
-
llm(Union[OnlineChatModule, TrainableModule]) –用于文档信息抽取的大语言模型。
-
doc_path(str) –要分析的文档路径。
-
info_schema(DocInfoSchema) –字段结构定义,包含需要提取的字段信息。
-
extra_desc(str, default:'') –额外的描述信息,用于指导信息抽取。默认为空字符串。
Returns:
-
dict(dict) –提取出的关键信息字典,键为字段名,值为对应的信息值。
Source code in lazyllm/tools/rag/doc_to_db/doc_analysis.py
lazyllm.tools.rag.doc_to_db.DocToDbProcessor
用于将文档信息抽取并导出到数据库中。
该类通过分析文档主题、抽取字段结构、从文档中提取关键信息,并将其保存至数据库表中。
Parameters:
-
sql_manager(SqlManager) –数据库管理模块。
-
doc_table_name(str, default:'lazyllm_doc_elements') –存储文档字段的数据库表名,默认为
lazyllm_doc_elements。
Note
- 如果表已存在,会自动检测并避免重复创建。
- 如果你希望重置字段结构,使用
reset_doc_info_schema方法。
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='')
使用大语言模型从文档节点中推断数据库信息结构。
Parameters:
-
nodes(list[DocNode]) –文档节点列表。
Returns:
-
dict(DocInfoSchema) –结构化信息模式,包含表名、字段、关系等信息。
Source code in lazyllm/tools/rag/doc_to_db/doc_processor.py
extract_info_from_docs(llm, doc_paths, extra_desc='')
从文档中提取结构化数据库信息。
该函数使用嵌入和检索技术,在提供的文档中获取数据库相关的文本片段,用于后续模式生成。
Parameters:
-
docs(list[DocNode]) –输入文档列表。
-
num_nodes(int) –要提取的片段数量,默认为10。
Returns:
-
List[dict]–list[DocNode]: 提取出的相关文档片段。
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)
给定文档路径和LLM模型,提取文档结构信息。
Parameters:
-
file_paths(List[str]) –要分析的文档路径。
-
llm(Union[OnlineChatModule, TrainableModule]) –支持聊天的模型模块。
Returns:
-
DocInfoSchema(DocInfoSchema) –提取出的字段结构描述。
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
docx格式文件解析器,从 .docx 文件中读取文本内容并封装为文档节点(DocNode)列表。
Parameters:
-
file(Path) –.docx文件路径。 -
fs(Optional[AbstractFileSystem]) –可选的文件系统对象,支持自定义读取方式。
Returns:
-
–
List[DocNode]: 包含文档中所有文本内容的节点列表。
Source code in lazyllm/tools/rag/readers/docxReader.py
lazyllm.tools.rag.readers.EpubReader
Bases: LazyLLMReaderBase
用于读取 .epub 格式电子书的文件读取器。
继承自 LazyLLMReaderBase,只需实现 _load_data 方法,即可通过 Document 组件自动加载 .epub 文件中的内容。
注意:当前版本不支持通过 fsspec 文件系统(如远程路径)加载 epub 文件,若提供 fs 参数,将回退到本地文件读取。
Returns:
-
–
List[DocNode]: 所有章节内容合并后的文本节点列表。
Source code in lazyllm/tools/rag/readers/epubReader.py
lazyllm.tools.rag.readers.HWPReader
Bases: LazyLLMReaderBase
HWP文件解析器,支持从本地文件系统读取 HWP 文件。它会从文档中提取正文部分的文本内容,返回 DocNode 列表。
HWP 是一种专有的二进制格式,主要在韩国使用。由于格式封闭,因此只能解析部分内容(如文本段落),但对常规文本提取已经足够使用。
Parameters:
-
return_trace(bool, default:True) –是否启用 trace 日志记录,默认为
True。
Source code in lazyllm/tools/rag/readers/hwpReader.py
lazyllm.tools.rag.readers.ImageReader
Bases: LazyLLMReaderBase
用于从图片文件中读取内容的模块。支持保留图片、解析图片中的文本(基于OCR或预训练视觉模型),并返回文本和图片路径的节点列表。
Parameters:
-
parser_config(Optional[Dict], default:None) –解析器配置,包含模型和处理器,默认为 None。当设置 parse_text=True 且 parser_config=None 时,会自动根据 text_type 加载相应模型。
-
keep_image(bool, default:False) –是否保留图片的 base64 编码,默认为 False。
-
parse_text(bool, default:False) –是否解析图片中的文本,默认为 False。
-
text_type(str, default:'text') –解析文本的类型,支持
text(默认)和plain_text。当为plain_text时,使用 pytesseract 进行OCR;否则使用预训练视觉编码解码模型。 -
pytesseract_model_kwargs(Optional[Dict], default:None) –传递给 pytesseract OCR 的可选参数,默认为空字典。
-
return_trace(bool, default:True) –是否记录处理过程的 trace,默认为 True。
Source code in lazyllm/tools/rag/readers/imageReader.py
lazyllm.tools.rag.readers.IPYNBReader
Bases: LazyLLMReaderBase
用于读取和解析 Jupyter Notebook (.ipynb) 文件的模块。将 notebook 转换成脚本文本后,按代码单元划分为多个文档节点,或合并为单一文本节点。
Parameters:
-
parser_config(Optional[Dict], default:None) –预留的解析器配置参数,当前未使用,默认为 None。
-
concatenate(bool, default:False) –是否将所有代码单元合并成一个整体文本节点,默认为 False,即分割为多个节点。
-
return_trace(bool, default:True) –是否记录处理过程的 trace,默认为 True。
Source code in lazyllm/tools/rag/readers/ipynbReader.py
lazyllm.tools.rag.readers.MagicPDFReader
用于通过 MagicPDF 服务解析 PDF 文件内容的模块。支持上传文件或通过 URL 方式调用解析接口,解析结果经过回调函数处理成文档节点列表。
Parameters:
-
magic_url(str) –MagicPDF 服务的接口 URL。
-
callback(Optional[Callable[[List[dict], Path, dict], List[DocNode]]], default:None) –解析结果回调函数,接收解析元素列表、文件路径及额外信息,返回文档节点列表。默认将所有文本合并为一个节点。
-
upload_mode(bool, default:False) –是否采用文件上传模式调用接口,默认为 False,即通过 JSON 请求文件路径。
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
用于读取和解析 Markdown 文件的模块。支持去除超链接和图片,按标题和内容将 Markdown 划分成若干文本段落节点。
Parameters:
-
remove_hyperlinks(bool, default:True) –是否移除超链接,默认 True。
-
remove_images(bool, default:True) –是否移除图片标记,默认 True。
-
return_trace(bool, default:True) –是否记录处理过程的 trace,默认为 True。
Source code in lazyllm/tools/rag/readers/markdownReader.py
remove_hyperlinks(content)
移除 Markdown 超链接,将 文本 转换为纯文本。
Parameters:
-
content(str) –输入的 markdown 内容。
Returns:
-
str(str) –移除超链接后的内容,仅保留链接文本。
Source code in lazyllm/tools/rag/readers/markdownReader.py
remove_images(content)
移除内容中形如 ![[...]] 的自定义图片标签。
Parameters:
-
content(str) –输入的 markdown 内容。
Returns:
-
str(str) –移除图片标签后的内容。
Source code in lazyllm/tools/rag/readers/markdownReader.py
lazyllm.tools.rag.readers.MboxReader
Bases: LazyLLMReaderBase
用于解析 Mbox 邮件存档文件的模块。读取邮件内容并格式化为文本,支持限制最大邮件数和自定义消息格式。
Parameters:
-
max_count(int, default:0) –最大读取的邮件数量,默认 0 表示读取全部邮件。
-
message_format(str, default:DEFAULT_MESSAGE_FORMAT) –邮件文本格式模板,支持使用
{_date}、{_from}、{_to}、{_subject}和{_content}占位符。 -
return_trace(bool, default:True) –是否记录处理过程的 trace,默认为 True。
Source code in lazyllm/tools/rag/readers/mboxreader.py
lazyllm.tools.rag.default_index.DefaultIndex
Bases: IndexBase
\ 默认的索引实现,负责通过 embedding 和文本相似度在底层存储中查询、更新和删除文档节点。支持多种相似度度量方式,并在必要时对查询和节点进行 embedding 计算与更新。
Parameters:
-
embed(Dict[str, Callable]) –用于生成查询和节点 embedding 的字典,key 是 embedding 名称,value 是接收字符串返回向量的函数。
-
store(StoreBase) –底层存储,用于持久化和检索 DocNode 节点。
-
**kwargs–预留扩展参数。
Source code in lazyllm/tools/rag/default_index.py
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 | |
query(query, group_name, similarity_name, similarity_cut_off, topk, embed_keys=None, filters=None, **kwargs)
\ 执行一次查询,支持 embedding 和文本两种模式,依据相似度函数过滤并返回符合条件的 DocNode 结果。
Parameters:
-
query(str) –原始查询文本。
-
group_name(str) –要检索的节点组名称。
-
similarity_name(str) –使用的相似度度量名称,必须在 registered_similarities 中注册。
-
similarity_cut_off(Union[float, Dict[str, float]]) –相似度阈值或每个 embedding 对应的阈值字典,用于过滤结果。
-
topk(int) –每个相似度渠道最多保留的候选数量。
-
embed_keys(Optional[List[str]], default:None) –指定用于 embedding 的 key 列表,若为空则使用所有可用 embedding。
-
filters(Optional[Dict[str, List]], default:None) –额外的节点过滤器,应用在计算相似度前。
-
**kwargs–传递给相似度函数的额外参数。
Returns
- list: List[DocNode]: 经过相似度计算与阈值过滤后去重的文档节点列表。
Source code in lazyllm/tools/rag/default_index.py
remove(uids, group_name=None)
\ 从索引中删除指定 UID 的节点,可选指定分组名称以限定作用域。当前为空实现,使用时需要补全逻辑。
Parameters:
-
uids(List[str]) –要删除的节点唯一标识列表。
-
group_name(Optional[str], default:None) –可选的分组名称,用于限定删除范围。
Source code in lazyllm/tools/rag/default_index.py
update(nodes)
\ 根据提供的节点列表更新索引中的内容。具体行为由子类或外部实现填充(此处为空实现,需在实际使用中覆盖/扩展)。
Parameters:
-
nodes(List[DocNode]) –需要更新(新增或替换)的文档节点列表。
lazyllm.tools.Reranker
Bases: ModuleBase, _PostProcess
用于创建节点(文档)后处理和重排序的模块。
Parameters:
-
name(str, default:'ModuleReranker') –用于后处理和重排序过程的排序器类型。默认为 'ModuleReranker'。
-
target(str)–已废弃参数,仅用于提示用户。
-
output_format(Optional[str], default:None) –代表输出格式,默认为None,可选值有 'content' 和 'dict',其中 content 对应输出格式为字符串,dict 对应字典。
-
join(Union[bool, str], default:False) –是否联合输出的 k 个节点,当输出格式为 content 时,如果设置该值为 True,则输出一个长字符串,如果设置为 False 则输出一个字符串列表,其中每个字符串对应每个节点的文本内容。当输出格式是 dict 时,不能联合输出,此时join默认为False,,将输出一个字典,包括'content、'embedding'、'metadata'三个key。
-
kwargs–传递给重新排序器实例化的其他关键字参数。
详细解释排序器类型
- Reranker: 实例化一个具有待排序的文档节点node列表和 query的 SentenceTransformerRerank 重排序器。
- KeywordFilter: 实例化一个具有指定必需和排除关键字的 KeywordNodePostprocessor。它根据这些关键字的存在或缺失来过滤节点。
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
是一个类装饰器工厂方法,它的核心作用是为 Reranker 类提供灵活的排序算法注册机制 Args: func (Optional[Callable]): 要注册的排序函数或排序器类。当使用装饰器语法(@)时可省略。 batch (bool):是否批量处理节点。默认为False,表示逐节点处理。
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
创建一个用于文档查询和检索的检索模块。此构造函数初始化一个检索模块,该模块根据指定的相似度度量配置文档检索过程。
Parameters:
-
doc(object) –文档模块实例。该文档模块可以是单个实例,也可以是一个实例的列表。如果是单个实例,表示对单个Document进行检索,如果是实例的列表,则表示对多个Document进行检索。
-
group_name(str) –在哪个 node group 上进行检索。
-
similarity(Optional[str], default:None) –用于设置文档检索的相似度函数。默认为 'dummy'。候选集包括 ["bm25", "bm25_chinese", "cosine"]。
-
similarity_cut_off(Union[float, Dict[str, float]], default:float('-inf')) –当相似度低于指定值时丢弃该文档。在多 embedding 场景下,如果需要对不同的 embedding 指定不同的值,则需要使用字典的方式指定,key 表示指定的是哪个 embedding,value 表示相应的阈值。如果所有的 embedding 使用同一个阈值,则只指定一个数值即可。
-
index(str, default:'default') –用于文档检索的索引类型。目前仅支持 'default'。
-
topk(int, default:6) –表示取相似度最高的多少篇文档。
-
embed_keys(Optional[List[str]], default:None) –表示通过哪些 embedding 做检索,不指定表示用全部 embedding 进行检索。
-
output_format(Optional[str], default:None) –代表输出格式,默认为None,可选值有 'content' 和 'dict',其中 content 对应输出格式为字符串,dict 对应字典。
-
join(Union[bool, str], default:False) –是否联合输出的 k 个节点,当输出格式为 content 时,如果设置该值为 True,则输出一个长字符串,如果设置为 False 则输出一个字符串列表,其中每个字符串对应每个节点的文本内容。当输出格式是 dict 时,不能联合输出,此时join默认为False,,将输出一个字典,包括'content、'embedding'、'metadata'三个key。
其中 group_name 有三个内置的切分策略,都是使用 SentenceSplitter 做切分,区别在于块大小不同:
- CoarseChunk: 块大小为 1024,重合长度为 100
- MediumChunk: 块大小为 256,重合长度为 25
- FineChunk: 块大小为 128,重合长度为 12
此外,LazyLLM提供了内置的Image节点组存储了所有图像节点,支持图像嵌入和检索。
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
临时文档检索器,继承自 ModuleBase 和 _PostProcess,用于快速处理临时文件并执行检索任务。
Parameters:
-
embed(Callable, default:None) –嵌入函数。
-
output_format(Optional[str], default:None) –结果输出格式(如json),可选默认为None
-
join(Union[bool, str], default:False) –是否合并多段结果(True或用分隔符如"
")
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)
添加带搜索配置的子检索器。
Parameters:
-
group(str) –目标节点组名称。
-
**kwargs–检索器参数(如similarity='cosine')。
Returns:
- self: 支持链式调用。
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)
创建具有特定处理流程的节点组。
Parameters:
-
name(str, default:None) –节点组名称,None时自动生成。
-
transform(Callable) –该组文档的处理函数。
-
parent(str, default:LAZY_ROOT_NAME) –父组名称,默认为根组。
-
trans_node(bool, default:None) –是否转换节点,None时继承父组设置。
-
num_workers(int, default:0) –并行处理worker数,0表示串行。
-
**kwargs–其他组参数。
Source code in lazyllm/tools/rag/retriever.py
lazyllm.tools.rag.retriever.UrlDocument
Bases: ModuleBase
UrlDocument类继承自ModuleBase,用于通过指定的URL和名称管理远程文档资源。
内部通过lazyllm的UrlModule代理实际调用,支持文档查找、检索和活跃节点分组查询。
Parameters:
-
url(str) –远程文档资源的访问URL。
-
name(str, default:None) –当前文档分组名称,用于标识文档分组。
Source code in lazyllm/tools/rag/document.py
find(target)
生成一个部分应用函数,用于在当前文档组中查找指定目标。
Parameters:
-
target(str) –需要查找的目标标识。
Returns:
- Callable: 调用时会执行查找操作的部分应用函数。
lazyllm.tools.rag.DocManager
Bases: ModuleBase
DocManager类管理文档列表及相关操作,并通过API提供文档上传、删除、分组等功能。
Parameters:
-
dlm(DocListManager) –文档列表管理器,用于处理具体的文档操作。
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 | |
add_files(request)
批量添加文件。 Args: files (List[UploadFile]): 上传的文件列表。 group_name (str): 目标知识库分组名称,为空时不添加到分组。 metadatas (Optional[str]): 文件的元数据,JSON格式。 Returns:
- BaseResponse:返回所有输入文件对应的唯一文件ID列表,包括新增和已存在的文件。若出现异常,则返回错误码和异常信息。
Source code in lazyllm/tools/rag/doc_manager.py
add_files_to_group(files, group_name, override=False, metadatas=None, user_path=None)
将文件上传后直接添加到指定分组的接口。
Parameters:
-
files(List[UploadFile]) –上传的文件列表。
-
group_name(str) –要添加到的分组名称。
-
override(bool, default:False) –是否覆盖已存在的文件。默认为False。
-
metadatas(Optional[str], default:None) –文件元数据,JSON格式。
-
user_path(Optional[str], default:None) –用户自定义的文件上传路径。
Returns:
- BaseResponse: 操作结果和文件ID。
Source code in lazyllm/tools/rag/doc_manager.py
add_files_to_group_by_id(request)
通过文件ID将文件添加到指定分组的接口。
Parameters:
-
request(FileGroupRequest) –包含文件ID和分组名称的请求。
Returns:
- BaseResponse: 操作结果。
Source code in lazyllm/tools/rag/doc_manager.py
add_metadata(add_metadata_request)
为指定文档添加或更新元数据的接口。
Parameters:
-
add_metadata_request(AddMetadataRequest) –包含文档ID列表和键值对元数据的请求。
Returns:
- BaseResponse: 操作结果信息。
Source code in lazyllm/tools/rag/doc_manager.py
delete_files(request)
删除指定文件的接口。
Parameters:
-
request(FileGroupRequest) –包含文件ID和分组名称的请求。
Returns:
- BaseResponse: 删除操作结果。
Source code in lazyllm/tools/rag/doc_manager.py
delete_files_from_group(request)
删除指定分组中的文件的接口。
Parameters:
-
request(FileGroupRequest) –包含文件ID列表和分组名称的请求参数。
Returns:
- BaseResponse: 删除操作结果。
Source code in lazyllm/tools/rag/doc_manager.py
delete_metadata_item(del_metadata_request)
删除指定文档的元数据字段或字段值的接口。
Parameters:
-
del_metadata_request(DeleteMetadataRequest) –包含文档ID列表、字段名和键值对删除条件的请求。
Returns:
- BaseResponse: 操作结果信息。
Source code in lazyllm/tools/rag/doc_manager.py
document()
提供默认文档页面的重定向接口。
Returns:
- RedirectResponse: 重定向到
/docs页面。
list_files(limit=None, details=True, alive=None)
列出已上传文件的接口。
Parameters:
-
limit(Optional[int], default:None) –返回的文件数量限制。默认为None。
-
details(bool, default:True) –是否返回详细信息。默认为True。
-
alive(Optional[bool], default:None) –如果为True,只返回未删除的文件。默认为None。
Returns:
- BaseResponse: 文件列表数据。
Source code in lazyllm/tools/rag/doc_manager.py
list_files_in_group(group_name=None, limit=None, alive=None)
列出指定分组中文件的接口。
Parameters:
-
group_name(Optional[str], default:None) –文件分组名称。
-
limit(Optional[int], default:None) –返回的文件数量限制。默认为None。
-
alive(Optional[bool], default:None) –是否只返回未删除的文件。
Returns:
- BaseResponse: 分组文件列表。
Source code in lazyllm/tools/rag/doc_manager.py
list_kb_groups()
列出所有文档分组的接口。
Returns:
- BaseResponse: 包含所有文档分组的数据。
Source code in lazyllm/tools/rag/doc_manager.py
query_metadata(query_metadata_request)
查询指定文档的元数据。
Parameters:
-
query_metadata_request(QueryMetadataRequest) –请求参数,包含文档ID和可选的字段名。
Returns:
- BaseResponse: 若指定了 key 且存在,返回对应字段值;否则返回整个 metadata;key 不存在时报错。
Source code in lazyllm/tools/rag/doc_manager.py
reset_metadata(reset_metadata_request)
重置指定文档的所有元数据字段。
Parameters:
-
reset_metadata_request(ResetMetadataRequest) –包含文档ID列表和新的元数据字典。
Returns:
- BaseResponse: 操作结果信息。
Source code in lazyllm/tools/rag/doc_manager.py
update_or_create_metadata_keys(update_metadata_request)
更新或创建文档元数据字段的接口。 Args: update_metadata_request (UpdateMetadataRequest): 包含文档ID列表和需更新或新增的键值对元数据。
Returns:
- BaseResponse: 操作结果信息。
Source code in lazyllm/tools/rag/doc_manager.py
upload_files(files, override=False, metadatas=None, user_path=None)
上传文件并更新其状态的接口。可以同时上传多个文件。
Parameters:
-
files(List[UploadFile]) –上传的文件列表。
-
override(bool, default:False) –是否覆盖已存在的文件。默认为False。
-
metadatas(Optional[str], default:None) –文件的元数据,JSON格式。
-
user_path(Optional[str], default:None) –用户自定义的文件上传路径。
Returns:
- BaseResponse: 上传结果和文件ID。
Source code in lazyllm/tools/rag/doc_manager.py
lazyllm.tools.rag.utils.SqliteDocListManager
Bases: DocListManager
基于 SQLite 的文档管理器,用于本地文件的持久化存储、状态管理与元信息追踪。
该类继承自 DocListManager,利用 SQLite 数据库存储文档记录。适用于管理具有唯一标识符的本地文档资源,并提供便捷的插入、查询、更新与状态过滤接口,支持可选的路径监控功能。
Parameters:
-
path(str) –数据库存储路径。
-
name(str) –数据库文件名(不包含路径)。
-
enable_path_monitoring(bool, default:True) –是否启用对文件路径的变动监控,默认为 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
592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 | |
add_files_to_kb_group(file_ids, group)
将多个文件添加到指定的知识库分组中。
该方法会将文件状态设置为等待处理(waiting), 若添加成功,则对应文档的计数(count)加一。
Parameters:
-
file_ids(List[str]) –需要添加的文件ID列表。
-
group(str) –知识库分组名称。
Source code in lazyllm/tools/rag/utils.py
add_kb_group(name)
向数据库中添加一个新的知识库分组名称,若已存在则忽略。
Parameters:
-
name(str) –要添加的知识库分组名称。
Source code in lazyllm/tools/rag/utils.py
delete_files_from_kb_group(file_ids, group)
从指定的知识库分组中删除多个文件。
删除成功后,对应文档的计数(count)减少,但不会低于0。 若文档不存在,会记录警告日志。
Parameters:
-
file_ids(List[str]) –需要删除的文件ID列表。
-
group(str) –知识库分组名称。
Source code in lazyllm/tools/rag/utils.py
delete_unreferenced_doc()
删除数据库中标记为删除且未被任何知识库分组引用的文档记录。
该方法会查找状态为“deleting”且引用计数为0的文档,删除这些文档记录,并记录删除操作日志。
Source code in lazyllm/tools/rag/utils.py
fetch_docs_changed_meta(group)
获取指定知识库分组中元数据发生变化的文档列表,并将对应的 new_meta 字段清空。
Parameters:
-
group(str) –知识库分组名称。
Returns:
- List[DocMetaChangedRow]: 包含文档ID及其对应新元数据的列表。
Source code in lazyllm/tools/rag/utils.py
get_docs(doc_ids)
根据给定的文档ID列表,从数据库中获取对应的文档对象列表。
Parameters:
-
doc_ids(List[str]) –需要查询的文档ID列表。
Returns:
- List[KBDocument]: 匹配的文档对象列表。如果没有匹配项,返回空列表。
Source code in lazyllm/tools/rag/utils.py
get_docs_need_reparse(group)
获取指定知识库分组中需要重新解析的文档列表。
仅返回状态为“success”或“failed”的文档,且其对应的知识库分组记录标记为需要重新解析。
Parameters:
-
group(str) –知识库分组名称。
Returns:
- List[KBDocument]: 需要重新解析的文档列表。
Source code in lazyllm/tools/rag/utils.py
get_existing_paths_by_pattern(pattern)
根据路径匹配模式获取已存在的文档路径列表。
Parameters:
-
pattern(str) –路径匹配模式,支持SQL的LIKE通配符。
Returns:
- List[str]: 匹配到的已存在文档路径列表。
Source code in lazyllm/tools/rag/utils.py
get_file_status(fileid)
获取指定文件的状态。
Parameters:
-
fileid(str) –文件的唯一标识符。
Returns:
- Optional[Tuple]: 返回包含状态的元组,若文件不存在则返回 None。
Source code in lazyllm/tools/rag/utils.py
list_all_kb_group()
列出数据库中所有的知识库分组名称。
Returns:
- List[str]: 知识库分组名称列表。
Source code in lazyllm/tools/rag/utils.py
list_files(limit=None, details=False, status=DocListManager.Status.all, exclude_status=None)
列出文档数据库中符合状态条件的文件,并根据参数选择返回完整记录或仅返回文件路径。
Parameters:
-
limit(Optional[int], default:None) –要返回的记录数上限,若为 None 则返回所有符合条件的记录。
-
details(bool, default:False) –是否返回完整的数据库行信息,若为 False 则仅返回文档路径(ID)。
-
status(Union[str, List[str]], default:all) –要包含在结果中的状态值,默认为包含所有状态。
-
exclude_status(Optional[Union[str, List[str]]], default:None) –要从结果中排除的状态值。
Returns:
- list: 文件记录列表或文档路径列表,具体取决于
details参数。
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)
列出指定知识库分组中的文件信息,可根据多种条件进行过滤。
Parameters:
-
group(str, default:None) –知识库分组名称,若为 None 则不按分组过滤。
-
limit(int, default:None) –限制返回的文件数量。
-
details(bool, default:False) –是否返回详细的文件信息。
-
status(str or List[str], default:all) –过滤知识库分组中文件的状态。
-
exclude_status(str or List[str], default:None) –排除指定状态的文件。
-
upload_status(str or List[str], default:all) –过滤文件上传状态。
-
exclude_upload_status(str or List[str], default:None) –排除指定的上传状态。
-
need_reparse(bool, default:None) –是否只返回需要重新解析的文件。
Returns:
- list:
- 如果 details 为 False,返回列表,每个元素为 (doc_id, path) 元组。
- 如果 details 为 True,返回包含文件详细信息的元组列表,包括文档ID、路径、状态、元数据, 知识库分组名、分组内状态及日志。
Source code in lazyllm/tools/rag/utils.py
release()
清空数据库中的所有文档、分组及相关操作日志数据。
该操作会删除 documents、document_groups、kb_group_documents 和 operation_logs 表中的所有记录。
Source code in lazyllm/tools/rag/utils.py
set_docs_new_meta(doc_meta)
批量更新文档的元数据(meta),同时更新对应知识库分组中文档的 new_meta 字段(非等待状态的文档)。
Parameters:
-
doc_meta(Dict[str, dict]) –字典,键为文档ID,值为对应的新元数据字典。
Source code in lazyllm/tools/rag/utils.py
table_inited()
检查数据库中是否已存在名为 "documents" 的表。
该方法通过查询 sqlite_master 元信息表,判断数据表是否已初始化。
Returns:
- bool: 如果 "documents" 表存在,返回 True;否则返回 False。
Source code in lazyllm/tools/rag/utils.py
update_file_message(fileid, **kw)
更新指定文件的字段信息。
Parameters:
-
fileid(str) –文件的唯一标识符(doc_id)。
-
**kw–需要更新的字段及其对应的值,键值对形式传入。
Source code in lazyllm/tools/rag/utils.py
update_file_status(file_ids, status, cond_status_list=None)
更新多个文件的状态,支持根据当前状态进行条件过滤。
Parameters:
-
file_ids(List[str]) –需要更新状态的文件ID列表。
-
status(str) –要设置的新状态。
-
cond_status_list(Union[None, List[str]], default:None) –仅更新当前状态在此列表中的文件,默认为 None,表示不筛选。
Returns:
- List[DocPartRow]: 返回更新后的文件ID和路径列表。
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)
更新知识库分组中指定文件的状态和重解析需求。
根据给定的文件ID列表、分组名及状态列表,批量更新对应文件在知识库分组中的状态及是否需要重解析标志。
Parameters:
-
cond_file_ids(List[str]) –需要更新的文件ID列表。
-
cond_group(Optional[str], default:None) –分组名称,若指定则只更新该分组内的文件。
-
cond_status_list(Optional[List[str]], default:None) –仅更新状态匹配此列表的文件。
-
new_status(Optional[str], default:None) –新的文件状态。
-
new_need_reparse(Optional[bool], default:None) –新的重解析需求标志。
Returns:
- List[Tuple]: 返回更新后文件的doc_id、group_name及状态列表。
Source code in lazyllm/tools/rag/utils.py
update_need_reparsing(doc_id, need_reparse, group_name=None)
更新指定文档的重解析标志位。
该方法用于设置某个文档是否需要重新解析。可以选择性地指定知识库分组进行精确匹配。
Parameters:
-
doc_id(str) –文档的唯一标识符。
-
need_reparse(bool) –是否需要重新解析文档。
-
group_name(Optional[str], default:None) –可选,所属的知识库分组名称。如果提供,将仅更新指定分组中的文档。
Source code in lazyllm/tools/rag/utils.py
validate_paths(paths)
验证输入路径所对应的文档是否可以安全添加到数据库。
该方法会检查每个路径是否对应已有文档,若已存在,需判断其状态是否允许重解析。 若文档正在解析或等待解析,或上次重解析未完成,则视为不可用。
Parameters:
-
paths(List[str]) –文件路径列表。
Returns:
- Tuple[bool, str, List[bool]]:
- bool: 是否所有路径都验证通过。
- str: 成功或失败的描述信息。
- List[bool]: 与输入路径一一对应的布尔列表,表示该路径是否为新文档(True 为新文档,False 为已存在)。 若验证失败,返回值为 None。
Source code in lazyllm/tools/rag/utils.py
lazyllm.tools.rag.data_loaders.DirectoryReader
用于从文件目录加载和处理文档的目录读取器类。
此类提供从指定目录读取文档并将其转换为文档节点的功能。它支持本地和全局文件读取器,并且可以处理不同类型的文档,包括图像。
Parameters:
-
input_files(Optional[List[str]]) –要读取的文件路径列表。如果为None,文件将在调用load_data方法时加载。
-
local_readers(Optional[Dict], default:None) –特定于此实例的本地文件读取器字典。键是文件模式,值是读取器函数。
-
global_readers(Optional[Dict], default:None) –在所有实例间共享的全局文件读取器字典。键是文件模式,值是读取器函数。
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)
从指定的输入文件加载和处理文档。
此方法使用配置的文件读取器(本地和全局)从输入文件读取文档,将它们处理成文档节点,并可选地将图像节点与文本节点分离。
Parameters:
-
input_files(Optional[List[str]], default:None) –要读取的文件路径列表。如果为None,使用初始化时指定的文件。
-
metadatas(Optional[Dict], default:None) –与加载文档关联的额外元数据。
-
split_image_nodes(bool, default:False) –是否将图像节点与文本节点分离。如果为True,返回(text_nodes, image_nodes)的元组。如果为False,一起返回所有节点。
Returns: - Union[List[DocNode], Tuple[List[DocNode], List[ImageDocNode]]]: 如果split_image_nodes为False,返回所有文档节点的列表。如果为True,返回包含文本节点和图像节点的元组。
Source code in lazyllm/tools/rag/data_loaders.py
lazyllm.tools.SentenceSplitter
Bases: NodeTransform
将句子拆分成指定大小的块。可以指定相邻块之间重合部分的大小。
Parameters:
-
chunk_size(int, default:1024) –拆分之后的块大小
-
chunk_overlap(int, default:200) –相邻两个块之间重合的内容长度
-
num_workers(int)–控制并行处理的线程/进程数量
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
一个文本摘要和关键词提取器,负责分析用户输入的文本,并根据请求任务提供简洁的摘要或提取相关关键词。
Parameters:
-
llm(TrainableModule) –可训练的模块
-
language(str) –语言种类,目前只支持中文(zh)和英文(en)
-
task_type(str) –目前支持两种任务:摘要(summary)和关键词抽取(keywords)。
-
num_workers(int)–控制并行处理的线程/进程数量。
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)
在指定的文档上执行设定的任务。
Parameters:
-
node(DocNode) –需要执行抽取任务的文档。
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
文档转换参数容器,用于统一管理文档处理中的各类配置参数。 Args: f(Union[str, Callable]):转换函数或注册的函数名。 trans_node(bool):是否转换节点类型。 num_workers(int):控制是否启用多线程(>0 时启用)。 kwargs(Dict):传递给转换函数的额外参数。 pattern(Union[str, Callable[[str], bool]]):文件名/内容匹配模式。
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)
相似度计算注册装饰器,用于统一注册和管理不同类型的相似度计算方法。 Args: func(Callable):相似度计算函数名。 mode(Literal['text', 'embedding']):text为文本直接匹配,embedding为向量相似度计算。 descend(bool):控制是否启用多线程(>0 时启用)。 kwargs(Dict):结果是否按相似度降序排列。 batch(bool):是否批量处理节点。
Source code in lazyllm/tools/rag/similarity.py
lazyllm.tools.rag.doc_node.DocNode
在指定的文档上执行设定的任务。 Args: uid(str): 唯一标识符。 content(Union[str, List[Any]]):节点内容 group(str):文档组名 embedding(Dict[str, List[float]]):嵌入向量字典 parent(Union[str, "DocNode"]):父节点引用 store:存储表示 node_groups(Dict[str, Dict]):节点存储组 metadata(Dict[str, Any]):节点级元数据 global_metadata(Dict[str, Any]):文档级元数据 text(str):节点内容与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)
阻塞检查嵌入状态,确保异步嵌入计算完成 Args: embed_key(str): 目标键列表
Source code in lazyllm/tools/rag/doc_node.py
do_embedding(embed)
执行嵌入计算 Args: embed(Dict[str, Callable]): 目标嵌入对象
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)
组合元数据和内容 Args: metadata_mode: 与get_metadata_str中参数一致
Source code in lazyllm/tools/rag/doc_node.py
has_missing_embedding(embed_keys)
检查缺失的嵌入向量 Args: embed_keys(Union[str, List[str]]): 目标键列表
Source code in lazyllm/tools/rag/doc_node.py
to_dict()
with_score(score)
lazyllm.tools.rag.doc_node.QADocNode
Bases: DocNode
问答文档节点类,用于存储问答对数据。
参数
query (str): 问题文本。 answer (str): 答案文本。 uid (str): 唯一标识符。 group (str): 文档组名。 embedding (Dict[str, List[float]]): 嵌入向量字典。 parent (DocNode): 父节点引用。 metadata (Dict[str, Any]): 节点级元数据。 global_metadata (Dict[str, Any]): 文档级元数据。 text (str): 节点内容,与query互斥。
Source code in lazyllm/tools/rag/doc_node.py
get_text(metadata_mode=MetadataMode.NONE)
获取节点的文本内容。
参数
metadata_mode (MetadataMode): 元数据模式,默认为MetadataMode.NONE。 当设置为MetadataMode.LLM时,返回格式化的问答对。 其他模式下返回基类的文本格式。
返回值
str: 格式化后的文本内容。
Source code in lazyllm/tools/rag/doc_node.py
lazyllm.tools.rag.doc_processor.DocumentProcessor
Bases: ModuleBase
文档处理器类,用于管理文档的添加、删除和更新操作。
Parameters:
-
server(bool, default:True) –是否以服务器模式运行。默认为True。
-
port(Optional[int], default:None) –服务器端口号。默认为None。
-
url(Optional[str], default:None) –远程服务URL。默认为None。
说明: - 支持异步处理文档任务 - 提供文档元数据更新功能 - 支持任务状态回调通知 - 可配置数据库存储
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)
从文档处理器中移除指定算法。
Parameters:
-
name(str) –要移除的算法名称。
-
clean_db(bool, default:False) –是否清理相关数据库数据。默认为False。
说明: - 如果算法名称不存在,将输出警告信息 - 移除后该算法将无法继续使用
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)
注册算法到文档处理器。
Parameters:
-
name(str) –算法名称,作为唯一标识符。
-
store(StoreBase) –存储实例,用于管理文档数据。
-
reader(ReaderBase) –读取器实例,用于解析文档内容。
-
node_groups(Dict[str, Dict]) –节点组配置信息。
-
force_refresh(bool, default:False) –是否强制刷新已存在的算法。默认为False。
说明: - 如果算法名称已存在且force_refresh为False,将跳过注册 - 注册成功后可以使用该算法处理文档
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.dataReader.SimpleDirectoryReader
Bases: ModuleBase
模块化的文档目录读取器,继承自 ModuleBase,支持从文件系统读取多种格式的文档并转换为标准化的 DocNode 。 Args: input_dir (Optional[str]): 输入目录路径。与input_files二选一,不可同时指定。 input_files (Optional[List]):直接指定的文件列表。与input_dir二选一。 exclude (Optional[List]):需要排除的文件模式列表。 exclude_hidden (bool): 是否排除隐藏文件。 recursive (bool):是否递归读取子目录。 encoding (str):文本文件的编码格式。 required_exts (Optional[List[str]]):需要处理的文件扩展名白名单。 file_extractor (Optional[Dict[str, Callable]]):自定义文件阅读器字典。 fs (Optional[AbstractFileSystem]):自定义文件系统。 metadata_genf (Optional[Callable[[str], Dict]]):元数据生成函数,接收文件路径返回元数据字典。 num_files_limit (Optional[int]):最大读取文件数量限制。 return_trace (bool):是否返回处理过程追踪信息。 metadatas (Optional[Dict]):预定义的全局元数据字典。
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
文件内容读取器,主要功能是将多种格式的输入文件转换为拼接后的纯文本内容。 Args: input_files (Optional[List]):直接指定的文件列表。
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.web.DocWebModule
Bases: ModuleBase
文档Web界面模块,继承自ModuleBase,提供基于Web的文档管理交互界面。
Parameters:
-
doc_server(ServerModule) –文档服务模块实例,提供后端API支持
-
title(str, default:'文档管理演示终端') –界面标题,默认为"文档管理演示终端"
-
port(int / range / list, default:None) –服务端口号或端口范围,默认为20800-20999
-
history(list, default:None) –初始聊天历史记录,默认为空列表
-
text_mode(Mode, default:None) –文本处理模式,默认为Mode.Dynamic(动态模式)
-
trace_mode(Mode, default:None) –追踪模式,默认为Mode.Refresh(刷新模式)
类属性
Mode: 模式枚举类,包含: - Dynamic: 动态模式 - Refresh: 刷新模式 - Appendix: 附录模式
注意事项
- 需要配合有效的doc_server实例使用
- 端口冲突时会自动尝试范围内其他端口
- 服务停止后会释放相关资源
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是LazyLLM为开发者提供的基于Web的交互界面。在初始化并启动一个WebModule之后,开发者可以从页面上看到WebModule背后的模块结构,并将Chatbot组件的输入传输给自己开发的模块进行处理。 模块返回的结果和日志会直接显示在网页的“处理日志”和Chatbot组件上。除此之外,WebModule支持在网页上动态加入Checkbox或Text组件用于向模块发送额外的参数。 WebModule页面还提供“使用上下文”,“流式输出”和“追加输出”的Checkbox,可以用来改变页面和后台模块的交互方式。
WebModule.init_web(component_descs) -> gradio.Blocks
使用gradio库生成演示web页面,初始化session相关数据以便在不同的页面保存各自的对话和日志,然后使用传入的component_descs参数为页面动态添加Checkbox和Text组件,最后设置页面上的按钮和文本框的相应函数
之后返回整个页面。WebModule的__init__函数调用此方法生成页面。
Parameters:
-
component_descs(list) –用于动态向页面添加组件的列表。列表中的每个元素也是一个列表,其中包含5个元素,分别是组件对应的模块ID,模块名,组件名,组件类型(目前仅支持Checkbox和Text),组件默认值。
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 | |
init_web(component_descs)
初始化 Web UI 页面。 该方法使用 Gradio 构建对话界面,并将组件绑定到事件,支持会话选择、流式输出、上下文控制、多模态输入等功能。该方法返回构建完成的 Gradio Blocks 对象。 Args: component_descs (List[Tuple]): 组件描述列表,每项为五元组 (module, group_name, name, component_type, value), 例如:('MyModule', 'GroupA', 'use_cache', 'Checkbox', True)。 Returns: gr.Blocks: 构建好的 Gradio 页面对象,可用于 launch 启动 Web 服务。
Source code in lazyllm/tools/webpages/webmodule.py
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 | |
stop()
关闭 Web 页面并清理资源。
如果 Web 页面已初始化,则关闭 Gradio demo,释放资源并重置 demo 与 url 属性。
lazyllm.tools.CodeGenerator
Bases: ModuleBase
代码生成模块。
该模块基于用户提供的提示词生成代码,会根据提示内容自动选择中文或英文的系统提示词,并从输出中提取 Python 代码片段。
__init__(self, base_model, prompt="")
初始化代码生成器。
Parameters:
-
base_model(Union[str, TrainableModule, OnlineChatModuleBase]) –模型路径字符串,或已初始化的模型实例。
-
prompt(str, default:'') –用户自定义的代码生成提示词,可为中文或英文。
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)
根据输入的提示文本内容选择合适的代码生成提示模板。
如果提示中包含中文字符,则返回中文提示模板;否则返回英文提示模板。
Parameters:
-
prompt(str) –输入的提示文本。
Returns:
- str: 选择的代码生成提示模板字符串。
Source code in lazyllm/tools/actors/code_generator.py
lazyllm.tools.ParameterExtractor
Bases: ModuleBase
参数提取模块。
该模块根据参数名称、类型、描述和是否必填,从文本中提取结构化参数,底层依赖语言模型实现。
__init__(self, base_model, param, type, description, require)
使用参数定义和模型初始化参数提取器。
Parameters:
-
base_model(Union[str, TrainableModule, OnlineChatModuleBase]) –用于参数提取的模型路径或模型实例。
-
param(list[str]) –需要提取的参数名称列表。
-
type(list[str]) –参数类型列表,如 "int"、"str"、"bool" 等。
-
description(list[str]) –每个参数的描述信息。
-
require(list[bool]) –每个参数是否为必填项的布尔列表。
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
问题改写模块。
该模块使用语言模型对用户输入的问题进行改写,可根据输出格式选择返回字符串或列表。
__init__(self, base_model, rewrite_prompt="", formatter="str")
使用提示词和模型初始化问题改写模块。
Parameters:
-
base_model(Union[str, TrainableModule, OnlineChatModuleBase]) –问题改写所使用的模型路径或已初始化模型。
-
rewrite_prompt(str, default:'') –用户自定义的改写提示词。
-
formatter(str, default:'str') –输出格式,可选 "str"(字符串)或 "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)
根据输入提示的语言选择合适的提示模板。
此方法分析输入提示字符串并确定使用中文还是英文提示模板。它检查提示字符串中的每个字符,如果任何字符落在中文字符Unicode范围内(一-鿿),则返回中文提示模板;否则返回英文提示模板。
Parameters:
-
prompt(str) –要分析语言检测的输入提示字符串。
Returns:
-
str–选定的提示模板字符串(中文或英文版本)。
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是一个工具管理类,用于提供工具信息和工具调用给function call。
此管理类构造时需要传入工具名字符串列表。此处工具名可以是LazyLLM提供的,也可以是用户自定义的,如果是用户自定义的,首先需要注册进LazyLLM中才可以使用。在注册时直接使用 fc_register 注册器,该注册器已经建立 tool group,所以使用该工具管理类时,所有函数都统一注册进 tool 分组即可。待注册的函数需要对函数参数进行注解,并且需要对函数增加功能描述,以及参数类型和作用描述。以方便工具管理类能对函数解析传给LLM使用。
Parameters:
-
tools(List[str]) –工具名称字符串列表。
-
return_trace(bool, default:False) –是否返回中间步骤和工具调用信息。
-
stream(bool) –是否以流式方式输出规划和解决过程。
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
用于构建工具模块的基类。
该类封装了函数签名和文档字符串的自动解析逻辑,可生成标准化的参数模式(基于 pydantic),并对输入进行校验和工具调用的标准封装。
__init__(self, verbose=False, return_trace=True)
初始化工具模块。
Parameters:
-
verbose(bool, default:False) –是否在执行过程中输出详细日志。
-
return_trace(bool, default:True) –是否在结果中保留中间执行痕迹。
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)
抽象方法,需在子类中实现具体逻辑。
此方法应根据传入的参数执行特定任务。
Raises:
-
NotImplementedError–如果未在子类中重写该方法。
validate_parameters(arguments)
验证参数是否满足所需条件。
此方法会检查参数字典是否包含所有必须字段,并尝试进一步进行格式验证。
Parameters:
-
arguments(Dict[str, Any]) –传入的参数字典。
Returns:
-
bool(bool) –若参数合法且完整,返回 True;否则返回 False。
Source code in lazyllm/tools/agent/toolsManager.py
lazyllm.tools.FunctionCall
Bases: ModuleBase
FunctionCall是单轮工具调用类。当LLM自身信息不足以回答用户问题,需要结合外部工具获取辅助信息时,调用此类。
若LLM输出需要调用工具,则执行工具调用并返回调用结果;输出结果为List类型,包含当前轮的输入、模型输出和工具输出。
若不需工具调用,则直接返回LLM输出结果,输出为字符串类型。
Parameters:
-
llm(ModuleBase) –使用的LLM实例,支持TrainableModule或OnlineChatModule。
-
tools(List[Union[str, Callable]]) –LLM可调用的工具名称或Callable对象列表。
-
return_trace(Optional[bool], default:False) –是否返回调用轨迹,默认为False。
-
stream(Optional[bool], default:False) –是否启用流式输出,默认为False。
-
_prompt(Optional[str], default:None) –自定义工具调用提示语,默认根据llm类型自动设置。
注意:tools中的工具需包含__doc__字段,且须遵循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
用于解析函数调用结构消息的格式化器。
该类继承自 JsonFormatter,用于从包含工具调用信息的消息字符串中提取 JSON 结构,并在需要时通过全局分隔符拆分内容。
私有方法
_load(msg) 解析输入的消息字符串,提取其中的 JSON 格式的工具调用结构(如果存在)。
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是一个使用工具调用方式进行完整工具调用的代理,即回答用户问题时,LLM如果需要通过工具获取外部知识,就会调用工具,并将工具的返回结果反馈给LLM,最后由LLM进行汇总输出。
Parameters:
-
llm(ModuleBase) –要使用的LLM,可以是TrainableModule或OnlineChatModule。
-
tools(List[str]) –LLM 使用的工具名称列表。
-
max_retries(int, default:5) –工具调用迭代的最大次数。默认值为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是按照 Thought->Action->Observation->Thought...->Finish 的流程一步一步的通过LLM和工具调用来显示解决用户问题的步骤,以及最后给用户的答案。
Parameters:
-
llm(ModuleBase) –要使用的LLM,可以是TrainableModule或OnlineChatModule。
-
tools(List[str]) –LLM 使用的工具名称列表。
-
max_retries(int, default:5) –工具调用迭代的最大次数。默认值为5。
-
return_trace(bool, default:False) –是否返回中间步骤和工具调用信息。
-
stream(bool, default:False) –是否以流式方式输出规划和解决过程。
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由两个组件组成,首先,由planner将整个任务分解为更小的子任务,然后由solver根据计划执行这些子任务,其中可能会涉及到工具调用,最后将答案返回给用户。
Parameters:
-
llm(ModuleBase, default:None) –要使用的LLM,可以是TrainableModule或OnlineChatModule。和plan_llm、solve_llm互斥,要么设置llm(planner和solver公用一个LLM),要么设置plan_llm和solve_llm,或者只指定llm(用来设置planner)和solve_llm,其它情况均认为是无效的。
-
tools(List[str], default:[]) –LLM使用的工具名称列表。
-
plan_llm(ModuleBase, default:None) –planner要使用的LLM,可以是TrainableModule或OnlineChatModule。
-
solve_llm(ModuleBase, default:None) –solver要使用的LLM,可以是TrainableModule或OnlineChatModule。
-
max_retries(int, default:5) –工具调用迭代的最大次数。默认值为5。
-
return_trace(bool, default:False) –是否返回中间步骤和工具调用信息。
-
stream(bool, default:False) –是否以流式方式输出规划和解决过程。
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包含三个部分:Planner、Worker和Solver。其中,Planner使用可预见推理能力为复杂任务创建解决方案蓝图;Worker通过工具调用来与环境交互,并将实际证据或观察结果填充到指令中;Solver处理所有计划和证据以制定原始任务或问题的解决方案。
Parameters:
-
llm(ModuleBase, default:None) –要使用的LLM,可以是TrainableModule或OnlineChatModule。和plan_llm、solve_llm互斥,要么设置llm(planner和solver公用一个LLM),要么设置plan_llm和solve_llm,或者只指定llm(用来设置planner)和solve_llm,其它情况均认为是无效的。
-
tools(List[str], default:[]) –LLM使用的工具名称列表。
-
plan_llm(ModuleBase, default:None) –planner要使用的LLM,可以是TrainableModule或OnlineChatModule。
-
solve_llm(ModuleBase, default:None) –solver要使用的LLM,可以是TrainableModule或OnlineChatModule。
-
max_retries(int) –工具调用迭代的最大次数。默认值为5。
-
return_trace(bool, default:False) –是否返回中间步骤和工具调用信息。
-
stream(bool, default:False) –是否以流式方式输出规划和解决过程。
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 166 | |
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
专门用于处理RAG系统中图像内容的文档节点。
ImageDocNode继承自DocNode,为图像处理和嵌入生成提供专门的功能。它自动处理图像加载、用于嵌入的base64编码,以及用于LLM处理的PIL图像对象。
Parameters:
-
image_path(str) –图像文件的文件路径。这应该是一个有效的图像文件路径(例如.jpg、.png、.jpeg)。
-
uid(Optional[str], default:None) –文档节点的唯一标识符。如果未提供,将自动生成UUID。
-
group(Optional[str], default:None) –此节点所属的组名。用于组织和过滤节点。
-
embedding(Optional[Dict[str, List[float]]], default:None) –图像的预计算嵌入。键是嵌入模型名称,值是嵌入向量。
-
parent(Optional[DocNode], default:None) –文档层次结构中的父节点。用于构建文档树。
-
metadata(Optional[Dict[str, Any]], default:None) –与图像节点关联的附加元数据。
-
global_metadata(Optional[Dict[str, Any]], default:None) –适用于文档中所有节点的全局元数据。
-
text(Optional[str], default:None) –图像的可选文本描述或标题。
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)
使用提供的嵌入函数为图像生成嵌入。
此方法重写父类方法以处理图像特定的嵌入生成。它自动将图像转换为适当的格式(用于嵌入的base64),并使用图像模态调用嵌入函数。
Parameters:
-
embed(Dict[str, Callable]) –嵌入函数字典。键是嵌入模型名称,值是接受(content, modality)并返回嵌入向量的可调用函数。
Source code in lazyllm/tools/rag/doc_node.py
get_content(metadata_mode=MetadataMode.LLM)
根据元数据模式获取不同格式的图像内容。
此方法根据预期用例返回不同格式的图像内容。对于LLM处理,它返回PIL图像对象。对于嵌入生成,它返回base64编码的图像字符串。
Parameters:
-
metadata_mode(MetadataMode, default:LLM) –内容检索模式。默认为MetadataMode.LLM。 - MetadataMode.LLM: 返回用于LLM处理的PIL图像对象 - MetadataMode.EMBED: 返回用于嵌入生成的base64编码图像 - 其他模式: 返回图像路径作为文本
Returns:
- Union[PIL.Image.Image, List[str], str]: 请求格式的图像内容。
Source code in lazyllm/tools/rag/doc_node.py
get_text()
获取图像路径作为文本表示。
此方法重写父类方法以返回图像路径而不是内容字段,因为ImageDocNode不使用内容字段存储文本。
Returns:
- str: 图像文件路径。
lazyllm.tools.rag.transform.AdaptiveTransform
Bases: NodeTransform
一个灵活的文档转换系统,根据文档模式应用不同的转换策略。
AdaptiveTransform允许您定义多种转换策略,并根据文档的文件路径或自定义模式匹配自动选择适当的转换方法。当您有不同类型的文档需要不同处理方法时,这特别有用。
Parameters:
-
transforms(Union[List[Union[TransformArgs, Dict]], Union[TransformArgs, Dict]]) –转换配置列表或单个转换配置。
-
num_workers(int, default:0) –并行处理的工作线程数。默认为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)
根据模式匹配使用适当的转换策略转换文档。
此方法按顺序评估每个转换配置,并应用第一个匹配文档路径模式的转换。匹配逻辑支持glob模式和自定义可调用函数。
Parameters:
-
document(DocNode) –要转换的文档节点。
-
**kwargs–传递给转换函数的附加关键字参数。
Returns:
- List[Union[str, DocNode]]: 转换结果列表(字符串或DocNode对象)。
Source code in lazyllm/tools/rag/transform.py
lazyllm.tools.rag.rerank.ModuleReranker
Bases: Reranker
使用可训练模块根据查询相关性重新排序文档的重排序器。
ModuleReranker是一个专门的重排序器,利用可训练模型(如BGE-reranker、Cohere rerank等)来提高检索文档的相关性。它接收文档列表和查询,然后返回按相关性分数重新排序的文档。
Parameters:
-
name(str, default:'ModuleReranker') –重排序器的名称。默认为"ModuleReranker"。
-
model(Union[Callable, str], default:None) –重排序模型。可以是模型名称(字符串)或可调用函数。
-
target(Optional[str], default:None) –默认为None。
-
output_format(Optional[str], default:None) –输出处理格式。默认为None。
-
join(Union[bool, str], default:False) –是否连接结果。默认为False。
-
**kwargs–传递给重排序模型模型的附加关键字参数。
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='')
重排序器的前向传播,根据与查询的相关性重新排序文档。
此方法接收文档列表和查询,然后使用底层重排序模型对文档进行评分和重新排序。文档以MetadataMode.EMBED格式处理,以确保与重排序模型的兼容性。
Parameters:
-
nodes(List[DocNode]) –要重排序的文档节点列表。
-
query(str, default:'') –用于排序文档的查询字符串。默认为""。
Returns:
- List[DocNode]: 按相关性分数重新排序的文档节点列表,添加了relevance_score属性。
Source code in lazyllm/tools/rag/rerank.py
lazyllm.tools.rag.utils.DocListManager
Bases: ABC
抽象基类,用于管理文档列表和监控文档目录变化。
Parameters:
-
path–要监控的文档目录路径。
-
name–管理器名称。
-
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 587 588 589 | |
enable_path_monitoring
property
writable
启用或禁用文档管理器的路径监控功能。
此方法用于启用或禁用文档管理器的路径监控功能。当启用时,会启动一个监控线程处理与路径相关的操作;当禁用时,会停止该线程并等待它终止。
Args:
val (bool): 启用或禁用路径监控。
说明:
- 如果 val 为 True,路径监控功能会通过将 _monitor_continue 设置为 True 并启动 _monitor_thread 来启用。
- 如果 val 为 False,路径监控功能会通过将 _monitor_continue 设置为 False 并等待 _monitor_thread 终止来禁用。
- 方法在管理监控线程时确保线程操作是安全的。
add_files(files, metadatas=None, status=Status.waiting, batch_size=64)
批量向文档列表中添加文件,可选附加元数据、状态,并支持分批处理。
此方法将文件列表添加到数据库中,并为每个文件设置可选的元数据和初始状态。文件会以批量方式处理以提高效率。在文件添加完成后,它们会自动关联到默认的知识库 (KB) 组。
Args:
files (List[str]): 添加的文件路径列表。
metadatas (Optional[List[Dict[str, Any]]]): 与文件对应的元数据字典列表。默认为 None。
status (Optional[str]): 添加文件的初始状态。默认为 Status.waiting。
batch_size (int): 每批处理的文件数量。默认为 64。
Returns::
List[DocPartRow]: 包含已添加文件及其相关信息的 DocPartRow 对象列表。
说明:
- 方法首先通过辅助函数 _add_doc_records 创建文档记录。
- 文件添加后,会自动关联到默认的知识库组 (DocListManager.DEFAULT_GROUP_NAME)。
- 批量处理确保在添加大量文件时具有良好的可扩展性。
Source code in lazyllm/tools/rag/utils.py
add_files_to_kb_group(file_ids, group)
abstractmethod
将文件添加到指定的知识库分组中。
Parameters:
-
file_ids(list of str) –要添加的文件ID列表。
-
group(str) –要添加的分组名称。
add_kb_group(name)
abstractmethod
delete_files(file_ids)
将与文件关联的知识库条目设为删除中,并由各知识库进行异步删除解析结果及关联记录。
Parameters:
-
file_ids(list of str) –要删除的文件ID列表
Source code in lazyllm/tools/rag/utils.py
delete_files_from_kb_group(file_ids, group)
abstractmethod
从指定的知识库分组中删除文件。
Parameters:
-
file_ids(list of str) –要删除的文件ID列表。
-
group(str) –分组名称。
delete_unreferenced_doc()
abstractmethod
删除数据库中标记为 "删除中" 且不再被引用的文档。
此方法从数据库中删除满足以下条件的文档:
1. 文档状态为 DocListManager.Status.deleting。
2. 文档的引用计数 (count) 为 0。
fetch_docs_changed_meta(group)
abstractmethod
获取指定组中元数据已更改的文档,并将其 new_meta 字段重置为 None。
此方法检索元数据已更改(即 new_meta 不为 None)的所有文档,基于提供的组名。检索后,会将这些文档的 new_meta 字段重置为 None。
Parameters:
-
group(str) –用于过滤文档的组名。
Returns:
List[DocMetaChangedRow]: 包含文档 doc_id 和 new_meta 字段的行列表,表示元数据已更改的文档。
说明:
- 使用线程安全锁 (self._db_lock) 确保数据库访问安全。
- 方法通过 SQL JOIN 操作连接 KBDocument 和 KBGroupDocuments 表以检索相关行。
- 在获取数据后,将受影响行的 new_meta 字段更新为 None,并将更改提交到数据库。
Source code in lazyllm/tools/rag/utils.py
get_docs(doc_ids)
abstractmethod
从数据库中检索类型为 KBDocument 的文档对象,基于提供的文档 ID 列表。
Parameters:
-
doc_ids(List[str]) –要获取的文档 ID 列表。
Returns:
List[KBDocument]: 与提供的文档 ID 对应的 KBDocument 对象列表。如果没有找到文档,将返回空列表。
说明:
- 使用线程安全锁 (self._db_lock) 确保数据库访问的安全性。
- 查询使用 SQL 的 IN 子句,通过 doc_id 字段进行过滤。
- 如果 doc_ids 为空,函数将直接返回空列表,而不会查询数据库。
Source code in lazyllm/tools/rag/utils.py
get_docs_need_reparse(group=None)
abstractmethod
获取需要重新解析 (need_reparse=True)的指定组中的文档。
此方法检索标记为需要重新解析 (need_reparse=True) 的文档,基于提供的组名。仅包含状态为 success 或 failed 的文档。
Args:
group (str): 用于过滤文档的组名。
Returns::
List[KBDocument]: 需要重新解析的 KBDocument 对象列表。
说明:
- 使用线程安全锁 (self._db_lock) 确保多线程环境下的数据库访问安全。
- 查询通过 SQL JOIN 操作连接 KBDocument 和 KBGroupDocuments 表,并基于组名和重新解析状态进行过滤。
- 仅状态为 success 或 failed 且 need_reparse=True 的文档会被检索出来。
Source code in lazyllm/tools/rag/utils.py
get_existing_paths_by_pattern(file_path)
abstractmethod
根据给定的模式,检索符合条件的文档路径。
此方法从数据库中获取所有符合提供的 SQL LIKE 模式的文档路径。
Args:
pattern (str): 用于过滤文档路径的 SQL LIKE 模式。例如,%example% 匹配包含单词 "example" 的路径。
Returns::
List[str]: 符合给定模式的文档路径列表。如果没有匹配的路径,则返回空列表。
说明:
- 使用线程安全锁 (self._db_lock) 确保多线程环境下的数据库访问安全。
- SQL 查询中的 LIKE 操作符用于对文档路径进行模式匹配。
Source code in lazyllm/tools/rag/utils.py
get_file_status(fileid)
abstractmethod
init_tables()
list_all_kb_group()
abstractmethod
list_files(limit=None, details=False, status=Status.all, exclude_status=None)
abstractmethod
从 documents 表中列出文件,并支持过滤、限制返回结果以及返回详细信息。
此方法根据指定的条件,从数据库中检索文件ID或详细文件信息。
参数:
limit (Optional[int]): 返回的最大文件数量。如果为 None,则返回所有匹配的文件。
details (bool): 是否返回详细的文件信息(True)或仅返回文件ID(False)。
status (Union[str, List[str]]): 要包含的状态或状态列表,默认为所有状态。
exclude_status (Optional[Union[str, List[str]]]): 要排除的状态或状态列表,默认为 None。
返回值:
List: 如果 details=False,则返回文件ID列表;如果 details=True,则返回详细文件行的列表。
说明:
- 该方法根据 status 和 exclude_status 条件动态构造查询。
- 使用线程安全锁 (self._db_lock) 确保数据库访问安全。
- 如果指定了 limit,查询会附加 LIMIT 子句。
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
列出指定知识库组中的文件。
Parameters:
-
group(str, default:None) –用于过滤文件的 KB 组名。默认为
None。 -
limit(Optional[int], default:None) –返回的最大文件数量。如果为
None,则返回所有匹配的文件。 -
details(bool, default:False) –返回详细的文件信息或仅返回文件 ID 和路径。
-
status(Union[str, List[str]], default:all) –包含在结果中的 KB 组状态或状态列表。默认为所有状态。
-
exclude_status(Optional[Union[str, List[str]], default:None) –从结果中排除的 KB 组状态或状态列表。默认为
None。 -
upload_status(Union[str, List[str]], default:all) –包含在结果中的文档上传状态或状态列表。默认为所有状态。
-
exclude_upload_status(Optional[Union[str, List[str]], default:None) –从结果中排除的文档上传状态或状态列表。默认为
None。 -
need_reparse(Optional[bool], default:False) –过滤需要重新解析的文件或不需要重新解析的文件。默认为
None。
Returns::
List: 如果 details=False,返回包含 (doc_id, path) 的元组列表。
如果 details=True,返回包含附加元数据的详细行列表。
说明:
- 方法根据提供的过滤条件动态构建 SQL 查询。
- 使用线程安全锁 (self._db_lock) 确保多线程环境下的数据库访问安全。
- 如果 status 或 upload_status 参数为列表,则会使用 SQL 的 IN 子句进行处理。
Source code in lazyllm/tools/rag/utils.py
release()
abstractmethod
set_docs_new_meta(doc_meta)
abstractmethod
table_inited()
abstractmethod
检查数据库中的 documents 表是否已初始化。此方法在访问数据库时确保线程安全。
判断数据库中是否存在 documents 表。
返回值:
bool: 如果 documents 表存在,返回 True;否则返回 False。
说明:
- 使用线程安全锁 (self._db_lock) 确保对数据库的安全访问。
- 通过 self._db_path 连接 SQLite 数据库,并使用 check_same_thread 配置选项。
- 执行 SQL 查询:SELECT name FROM sqlite_master WHERE type='table' AND name='documents' 来检查表是否存在。
Source code in lazyllm/tools/rag/utils.py
update_file_message(fileid, **kw)
abstractmethod
update_file_status(file_ids, status, cond_status_list=None)
abstractmethod
更新指定文件的状态。
Parameters:
-
file_ids(list of str) –更新状态的文件ID列表。
-
status(str) –目标状态。
-
cond_status_list(Union[None,(List[str]]) –限制只更新处于这些状态的文档
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
更新指定知识库分组中的内容。
Parameters:
-
cond_file_ids(list of str) –过滤使用的文件ID列表,默认为None。
-
cond_group(str, default:None) –过滤使用的知识库分组名称,默认为None。
-
cond_status_list(list of str, default:None) –过滤使用的状态列表,默认为None。
-
new_status(str, default:None) –新状态, 默认为None。
-
new_need_reparse((bool, optinoal), default:None) –新的是否需重解析标志。
Returns: - list: 得到更新的列表list of (doc_id, group_name)
Source code in lazyllm/tools/rag/utils.py
update_need_reparsing(doc_id, need_reparse)
abstractmethod
更新 KBGroupDocuments 表中某个文档的 need_reparse 状态。
此方法设置指定文档的 need_reparse 标志,并可选限定到特定分组。
参数:
doc_id (str): 要更新的文档ID。
need_reparse (bool): need_reparse 标志的新值。
group_name (Optional[str]): 如果提供,仅对指定分组应用更新;如果未提供,则对包含该文档的所有分组应用更新。
说明:
- 使用线程安全锁 (self._db_lock) 确保数据库访问安全。
- group_name 参数允许将更新限定到特定分组;如果未提供,则更新应用于包含该文档的所有分组。
- 方法会立刻将更改提交到数据库。
Source code in lazyllm/tools/rag/utils.py
validate_paths(paths)
abstractmethod
验证一组文件路径,以确保它们可以被正常处理。
此方法检查提供的路径是否是新的、已处理的或当前正在处理的,并确保处理文档时不会发生冲突。
参数:
paths (List[str]): 要验证的文件路径列表。
返回值:
Tuple[bool, str, List[bool]]: 返回一个元组,包括:
- bool: 如果所有路径有效,则返回 True;否则返回 False。
- str: 表示成功或失败原因的消息。
- List[bool]: 一个布尔值列表,每个元素对应一个路径是否为新路径(True 表示新路径,False 表示已存在)。
说明:
- 如果任何文档仍在处理中或需要重新解析,该方法会返回 False,并附带相应的错误消息。
- 方法通过数据库会话和线程安全锁 (self._db_lock) 检索文档状态信息。
- 不安全状态包括 working 和 waiting。
Source code in lazyllm/tools/rag/utils.py
lazyllm.tools.rag.global_metadata.GlobalMetadataDesc
用于描述全局元数据的说明符,包括其类型、可选的元素类型、默认值和大小限制。
class GlobalMetadataDesc
此类用于描述元数据的属性,例如类型、可选约束和默认值。支持标量和数组数据类型,并对某些类型指定特定的大小限制。
Args:
data_type (int): 元数据的类型,以整数表示,代表不同的数据类型(例如 VARCHAR、ARRAY 等)。
element_type (Optional[int]): 如果 data_type 是数组,则表示数组中每个元素的类型。默认为 None。
default_value (Optional[Any]): 元数据的默认值。如果未提供,默认值为 None。
max_size (Optional[int]): 元数据的最大大小或长度。如果 data_type 为 VARCHAR 或 ARRAY,则此属性为必填项。
Source code in lazyllm/tools/rag/global_metadata.py
lazyllm.tools.rag.index_base.IndexBase
Bases: ABC
用于实现索引系统的抽象基类,支持更新、删除和查询文档节点。
class IndexBase(ABC)
此抽象基类定义了索引系统的接口,要求子类实现更新、删除和查询文档节点的方法。
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
执行索引查询。
根据传入的参数执行查询操作,返回匹配的文档节点列表。具体查询逻辑由实现类定义。
Returns:
-
List[DocNode]–List[DocNode]: 查询结果的文档节点列表。
remove(uids, group_name=None)
abstractmethod
从索引中移除指定文档节点。
可根据唯一标识符列表删除索引中的文档节点,可选地指定组名称以限定范围。
Parameters:
-
uids(List[str]) –需要移除的文档节点的唯一标识符列表。
-
group_name(Optional[str], default:None) –可选的组名称,用于限定要删除的范围。
Source code in lazyllm/tools/rag/index_base.py
update(nodes)
abstractmethod
更新索引内容。
该方法接收一组文档节点对象,并将其添加或更新到索引结构中。通常用于增量构建或刷新索引。
Parameters:
-
nodes(List[DocNode]) –需要更新的文档节点列表。
lazyllm.tools.rag.IndexBase.update(nodes)
abstractmethod
更新索引内容。
该方法接收一组文档节点对象,并将其添加或更新到索引结构中。通常用于增量构建或刷新索引。
Parameters:
-
nodes(List[DocNode]) –需要更新的文档节点列表。
lazyllm.tools.rag.IndexBase.remove(uids, group_name=None)
abstractmethod
从索引中移除指定文档节点。
可根据唯一标识符列表删除索引中的文档节点,可选地指定组名称以限定范围。
Parameters:
-
uids(List[str]) –需要移除的文档节点的唯一标识符列表。
-
group_name(Optional[str], default:None) –可选的组名称,用于限定要删除的范围。
Source code in lazyllm/tools/rag/index_base.py
lazyllm.tools.rag.IndexBase.query(*args, **kwargs)
abstractmethod
执行索引查询。
根据传入的参数执行查询操作,返回匹配的文档节点列表。具体查询逻辑由实现类定义。
Returns:
-
List[DocNode]–List[DocNode]: 查询结果的文档节点列表。
lazyllm.tools.BaseEvaluator
Bases: ModuleBase
评估模块的抽象基类。
该类定义了模型评估的标准接口,支持并发处理、输入校验和评估结果的自动保存,同时内置了重试机制。
Parameters:
-
concurrency(int, default:1) –评估过程中使用的并发线程数。
-
retry(int, default:3) –每个样本的最大重试次数。
-
log_base_name(Optional[str], default:None) –用于保存结果文件的日志文件名前缀(可选)。
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
用于评估用户问题与模型生成问题之间语义相关性的指标类。
该评估器使用语言模型根据回答生成问题,并通过 Embedding 与余弦相似度度量其与原始问题之间的相关性。
Parameters:
-
llm(ModuleBase) –用于根据回答生成问题的语言模型模块。
-
embedding(ModuleBase) –用于编码问题向量的嵌入模块。
-
prompt((str, 可选), default:None) –自定义的生成提示词,若不提供将使用默认提示。
-
prompt_lang(str, default:'en') –默认提示词的语言,可选
'en'(默认)或'zh'。 -
num_infer_questions(int, default:3) –每条数据生成和评估的问题数量。
-
retry(int, default:3) –失败时的重试次数。
-
concurrency(int, default:1) –并发评估的数量。
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
评估回答与上下文之间事实一致性的指标类。
该评估器首先使用语言模型将答案拆分为独立事实句,然后基于上下文对每条句子进行支持性判断(0或1分),最终取平均值作为总体一致性分数。
Parameters:
-
llm(ModuleBase) –同时用于生成句子与进行评估的语言模型模块。
-
generate_prompt((str, 可选), default:None) –用于将答案转换为事实句的自定义提示词。
-
eval_prompt((str, 可选), default:None) –用于评估句子与上下文匹配度的提示词。
-
prompt_lang(str, default:'en') –默认提示词的语言,可选 'en' 或 'zh'。
-
retry(int, default:3) –生成或评估失败时的最大重试次数。
-
concurrency(int, default:1) –并发评估的数据条数。
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
通用 HTTP 请求执行器。
该类用于构建并发送 HTTP 请求,支持变量替换、API Key 注入、JSON 或表单编码、文件类型响应识别等功能。
Parameters:
-
method(str) –HTTP 方法,如 'GET'、'POST' 等。
-
url(str) –请求目标的 URL。
-
api_key(str) –可选的 API Key,会被加入请求参数。
-
headers(dict) –HTTP 请求头。
-
params(dict) –URL 查询参数。
-
body(Union[str, dict]) –请求体,支持字符串或 JSON 字典格式。
-
timeout(int, default:10) –请求超时时间(秒)。
-
proxies(dict, default:None) –可选的代理设置。
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
模型部署任务描述的数据结构。
用于创建模型推理任务时指定部署配置,包括模型名称与所需 GPU 数量。
Parameters:
-
deploy_model(str) –要部署的模型名称,默认为 "qwen1.5-0.5b-chat"。
-
num_gpus(int) –所需的 GPU 数量,默认为 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
数据库管理器的抽象基类。
该类定义了构建数据库连接器的通用接口,包括 execute_query 抽象方法和 desc 描述属性。
Parameters:
-
db_type(str) –数据库类型标识符,例如 '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
执行数据库查询语句的抽象方法。此方法需要由具体的数据库管理器子类实现,用于执行各种数据库操作。
Parameters:
-
statement–要执行的数据库查询语句,可以是 SQL 语句或其他数据库特定的查询语言
此方法的特点:
- 抽象方法: 需要在子类中实现具体的数据库操作逻辑
- 统一接口: 为不同的数据库类型提供统一的查询接口
- 错误处理: 子类实现应该包含适当的错误处理和状态报告
- 结果格式化: 返回格式化的字符串结果,便于后续处理
注意: 此方法是数据库管理器的核心方法,所有具体的数据库操作都通过此方法执行。
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
用于访问第三方服务和执行自定义代码的模块。参数中的 params 和 headers 的 value,以及 body 中可以包含形如 {{variable}} 这样用两个花括号标记的模板变量,然后在调用的时候通过参数来替换模板中的值。参考 [[lazyllm.tools.HttpTool.forward]] 中的使用说明。
Parameters:
-
method(str, default:None) –指定 http 请求方法,参考
https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods。 -
url(str, default:None) –要访问的 url。如果该字段为空,则表示该模块不需要访问第三方服务。
-
params(Dict[str, str], default:None) –请求 url 需要填充的 params 字段。如果 url 为空,该字段会被忽略。
-
headers(Dict[str, str], default:None) –访问 url 需要填充的 header 字段。如果 url 为空,该字段会被忽略。
-
body(Dict[str, str], default:None) –请求 url 需要填充的 body 字段。如果 url 为空,该字段会被忽略。
-
timeout(int, default:10) –请求超时时间,单位是秒,默认值是 10。
-
proxies(Dict[str, str], default:None) –指定请求 url 时所使用的代理。代理格式参考
https://www.python-httpx.org/advanced/proxies。 -
code_str(str, default:None) –一个字符串,包含用户定义的函数。如果参数
url为空,则直接执行该函数,执行时所有的参数都会转发给该函数;如果url不为空,该函数的参数为请求 url 返回的结果,此时该函数作为 url 返回后的后处理函数。 -
vars_for_code(Dict[str, Any], default:None) –一个字典,传入运行 code 所需的依赖及变量。
-
outputs(Optional[List[str]], default:None) –期望提取的输出字段名。
-
extract_from_result(Optional[bool], default:None) –是否从响应字典中直接提取指定字段。
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)
用于执行初始化时指定的操作:请求指定的 url 或者执行传入的函数。一般不直接调用,而是通过基类的 __call__ 来调用。如果构造函数的 url 参数不为空,则传入的所有参数都会作为变量,用于替换在构造函数中使用 {{}} 标记的模板参数;如果构造函数的参数 url 为空,并且 code_str 不为空,则传入的所有参数都会作为 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类用于封装带有前缀和颜色配置的流式输出行为。
当启用流式模式时,调用实例会将带颜色的文本推送到文件系统队列中,用于异步处理或显示。
Parameters:
-
prefix(str) –输出内容前的前缀文本,通常用于标识信息来源或类别。
-
prefix_color(Optional[str], default:None) –前缀文本的颜色,支持终端颜色代码,默认无颜色。
-
color(Optional[str], default:None) –主体内容文本颜色,支持终端颜色代码,默认无颜色。
-
stream(bool, default: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
通过 Google 搜索指定的关键词。
Parameters:
-
custom_search_api_key(str) –用户申请的 Google API key。
-
search_engine_id(str) –用户创建的用于检索的搜索引擎 id。
-
timeout(int, default:10) –搜索请求的超时时间,单位是秒,默认是 10。
-
proxies(Dict[str, str], default:None) –请求时所用的代理服务。格式参考
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)
执行搜索请求。
Parameters:
-
query(str) –要检索的关键词。
-
date_restrict(str, default:'m1') –要检索内容的时效性。默认检索一个月内的网页(
m1)。参数格式可以参考https://developers.google.com/custom-search/v1/reference/rest/v1/cse/list?hl=zh-cn。 -
search_engine_id(str, default:None) –用于检索的搜索引擎 id。如果该值为空,则使用构造函数中传入的值。
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
这是一个搜索增强工具。
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)
搜索用户输入的查询。
Parameters:
-
query(str) –用户待查询的内容。
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
基于 Gradio 的知识库文件管理 Web UI 工具类。
该类用于构建一个简单的 Web 界面,支持创建分组、上传文件、列出/删除分组或文件,并通过 RESTful API 与后端交互。支持快速集成与展示文件管理能力。
Parameters:
-
base_url(str) –后端 API 服务的基础地址。
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)
生成通用的 HTTP 请求头。
Parameters:
-
content_type(bool, default:True) –是否包含 Content-Type 头信息(默认为 True)。
Returns:
-
dict–HTTP 请求头字典。
Source code in lazyllm/tools/rag/web.py
create_ui()
构建基于 Gradio 的文件管理图形界面,包含分组列表、上传、查看、删除等功能标签页。
Returns:
-
–
gr.Blocks: 完整的 Gradio UI 应用实例。
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)
从指定分组中删除文件。
Parameters:
-
group_name(str) –分组名称。
-
file_ids(List[str]) –要删除的文件 ID 列表。
Returns:
-
str–删除结果提示。
Source code in lazyllm/tools/rag/web.py
delete_group(group_name)
删除指定的文件分组。
Parameters:
-
group_name(str) –分组名称。
Returns:
-
str–删除结果信息。
Source code in lazyllm/tools/rag/web.py
get_request(url)
发送 GET 请求。
Parameters:
-
url(str) –请求地址。
Returns:
-
dict–响应结果的 JSON。
gr_show_list(str_list, list_name)
以 Gradio 表格的形式展示字符串列表。
Parameters:
-
str_list(List) –字符串或子项列表。
-
list_name(Union[str, List]) –表头名称或列名列表。
Returns:
-
–
gr.DataFrame: Gradio 表格组件。
Source code in lazyllm/tools/rag/web.py
list_files_in_group(group_name)
列出指定分组下的所有文件。
Parameters:
-
group_name(str) –分组名称。
Returns:
-
List–文件信息列表。
Source code in lazyllm/tools/rag/web.py
list_groups()
列出所有文件分组。
Returns:
-
–
List[str]: 分组名称列表。
muti_headers()
new_group(group_name)
创建新的文件分组。
Parameters:
-
group_name(str) –分组名称。
Returns:
-
str–创建结果的提示信息。
Source code in lazyllm/tools/rag/web.py
post_request(url, data)
发送 POST 请求。
Parameters:
-
url(str) –请求地址。
-
data(dict) –请求数据,将被转为 JSON。
Returns:
-
dict–响应结果的 JSON。
Source code in lazyllm/tools/rag/web.py
upload_files(group_name, override=True)
向指定分组上传文件。
Parameters:
-
group_name(str) –分组名称。
-
override(bool, default:True) –是否覆盖已存在的文件(默认 True)。
Returns:
-
Any–后端返回的上传结果数据。
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()
获取HTTP响应的内容类型。
从响应头中提取 'content-type' 字段的值,用于判断响应内容的类型。
Returns:
-
str(str) –响应的内容类型,如果未找到则返回空字符串。
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'