Tools
lazyllm.tools.Document
Bases: ModuleBase
初始化一个具有可选用户界面的文档模块。
此构造函数初始化一个可以有或没有用户界面的文档模块。如果启用了用户界面,它还会提供一个ui界面来管理文档操作接口,并提供一个用于用户界面交互的网页。
Parameters:
-
dataset_path
(str
) –数据集目录的路径。此目录应包含要由文档模块管理的文档。
-
embed
(Optional[Union[Callable, Dict[str, Callable]]]
, default:None
) –用于生成文档 embedding 的对象。如果需要对文本生成多个 embedding,此处需要通过字典的方式指定多个 embedding 模型,key 标识 embedding 对应的名字, value 为对应的 embedding 模型。
-
manager
(bool
, default:False
) –指示是否为文档模块创建用户界面的标志。默认为 False。
-
launcher
(optional
, default:None
) –负责启动服务器模块的对象或函数。如果未提供,则使用
lazyllm.launchers
中的默认异步启动器 (sync=False
)。 -
store_conf
(optional
, default:None
) –配置使用哪种存储后端和索引后端。
-
doc_fields
(optional
, default:None
) –配置需要存储和检索的字段继对应的类型(目前只有 Milvus 后端会用到)。
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 = {
>>> 'type': 'chroma',
>>> 'indices': {
>>> 'smart_embedding_index': {
>>> 'backend': 'milvus',
>>> 'kwargs': {
>>> 'uri': '/tmp/tmp.db',
>>> 'index_kwargs': {
>>> 'index_type': 'HNSW',
>>> '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
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 |
|
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, extra_info=None, 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, metadata=extra_info or {})]
...
>>> def processYml(file, extra_info=None):
... with open(file, 'r') as f:
... data = f.read()
... print("Call the function processYml.")
... return [DocNode(text=data, metadata=extra_info or {})]
...
>>> 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, **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, extra_info=None):
... with open(file, 'r') as f:
... data = f.read()
... return [DocNode(text=data, metadata=extra_info or {})]
...
>>> 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.readers.ReaderBase
Bases: ModuleBase
文件读取器的基类,它继承自 ModuleBase 基类,具有 Callable 的能力,继承自该类的子类只需要实现 _load_data 函数即可,它的返回参数类型为 List[DocNode]. 一般 _load_data 函数的入参为 file (Path), extra_info (Dict), fs(AbstractFileSystem) 三个参数。
Parameters:
-
args
(Any
, default:()
) –根据需要传输相应的位置参数
-
return_trace
(bool
, default:True
) –设置是否记录trace日志
-
kwargs
(Dict
, default:{}
) –根据需要传输相应的关键字参数
Examples:
>>> from lazyllm.tools.rag.readers import ReaderBase
>>> from lazyllm.tools.rag import DocNode, Document
>>> from typing import Dict, Optional, List
>>> from pathlib import Path
>>> from fsspec import AbstractFileSystem
>>> @Document.register_global_reader("**/*.yml")
>>> class YmlReader(ReaderBase):
... def _load_data(self, file: Path, extra_info: Optional[Dict] = None, fs: Optional[AbstractFileSystem] = None) -> List[DocNode]:
... 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, metadata=extra_info or {})]
...
>>> files = ["your_yml_files"]
>>> doc = Document(dataset_path="your_files_path", create_ui=False)
>>> reader = doc._impl._reader.load_data(input_files=files)
# Call the class YmlReader.
Source code in lazyllm/tools/rag/readers/readerBase.py
lazyllm.tools.Reranker
Bases: ModuleBase
, _PostProcess
用于创建节点(文档)后处理和重排序的模块。
Parameters:
-
name
(str
, default:'ModuleReranker'
) –用于后处理和重排序过程的排序器类型。默认为 'Reranker'。
-
kwargs
–传递给重新排序器实例化的其他关键字参数。
详细解释排序器类型
- Reranker: 实例化一个具有指定模型和 top_n 参数的 SentenceTransformerRerank 重排序器。
- KeywordFilter: 实例化一个具有指定必需和排除关键字的 KeywordNodePostprocessor。它根据这些关键字的存在或缺失来过滤节点。
Examples:
>>> import lazyllm
>>> from lazyllm.tools import Document, Reranker, Retriever
>>> 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(name='ModuleReranker', model='bge-reranker-large', topk=1)
>>> ppl = lazyllm.ActionModule(retriever, reranker)
>>> ppl.start()
>>> print(ppl("user query"))
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 进行检索。
-
similarity_kw
–传递给 similarity 计算函数的其它参数。
其中 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])
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 |
|
lazyllm.tools.rag.DocManager
Bases: ModuleBase
DocManager类管理文档列表及相关操作,并通过API提供文档上传、删除、分组等功能。
Parameters:
-
dlm
(DocListManager
) –文档列表管理器,用于处理具体的文档操作。
Source code in lazyllm/tools/rag/doc_manager.py
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 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 |
|
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
delete_files(request)
删除指定文件的接口。
Parameters:
-
request
(FileGroupRequest
) –包含文件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
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.SentenceSplitter
Bases: NodeTransform
将句子拆分成指定大小的块。可以指定相邻块之间重合部分的大小。
Parameters:
-
chunk_size
(int
, default:1024
) –拆分之后的块大小
-
chunk_overlap
(int
, default:200
) –相邻两个块之间重合的内容长度
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
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 |
|
_split(text, chunk_size)
Break text into splits that are smaller than chunk size.
The order of splitting is: 1. split by paragraph separator 2. split by chunking tokenizer 3. split by second chunking regex 4. split by default separator (' ') 5. split by character
Source code in lazyllm/tools/rag/transform.py
lazyllm.tools.LLMParser
Bases: NodeTransform
一个文本摘要和关键词提取器,负责分析用户输入的文本,并根据请求任务提供简洁的摘要或提取相关关键词。
Parameters:
-
llm
(TrainableModule
) –可训练的模块
-
language
(str
) –语言种类,目前只支持中文(zh)和英文(en)
-
task_type
(str
) –目前支持两种任务:摘要(summary)和关键词抽取(keywords)。
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.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 |
|
lazyllm.tools.ToolManager
Bases: ModuleBase
ToolManager是一个工具管理类,用于提供工具信息和工具调用给function call。
此管理类构造时需要传入工具名字符串列表。此处工具名可以是LazyLLM提供的,也可以是用户自定义的,如果是用户自定义的,首先需要注册进LazyLLM中才可以使用。在注册时直接使用 fc_register
注册器,该注册器已经建立 tool
group,所以使用该工具管理类时,所有函数都统一注册进 tool
分组即可。待注册的函数需要对函数参数进行注解,并且需要对函数增加功能描述,以及参数类型和作用描述。以方便工具管理类能对函数解析传给LLM使用。
Parameters:
-
tools
(List[str]
) –工具名称字符串列表。
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
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 |
|
_gen_args_info_from_moduletool_and_docstring(tool, parsed_docstring)
staticmethod
returns a dict of param names containing at least
1. type
2. description
of params
for example
args = { "foo": { "enum": ["baz", "bar"], "type": "string", "description": "a string", }, "bar": { "type": "integer", "description": "an integer", } }
Source code in lazyllm/tools/agent/toolsManager.py
lazyllm.tools.FunctionCall
Bases: ModuleBase
FunctionCall是单轮工具调用类,如果LLM中的信息不足以回答用户的问题,必需结合外部知识来回答用户问题,则调用该类。如果LLM输出需要工具调用,则进行工具调用,并输出工具调用结果,输出结果为List类型,包含当前轮的输入、模型输出、工具输出。如果不需要工具调用,则直接输出LLM结果,输出结果为string类型。
Parameters:
-
llm
(ModuleBase
) –要使用的LLM可以是TrainableModule或OnlineChatModule。
-
tools
(List[Union[str, Callable]]
) –LLM使用的工具名称或者 Callable 列表
注意: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
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 |
|
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
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 |
|
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。
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。
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。
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 |
|
lazyllm.tools.IntentClassifier
Bases: ModuleBase
IntentClassifier 是一个基于语言模型的意图识别器,用于根据用户提供的输入文本及对话上下文识别预定义的意图,并通过预处理和后处理步骤确保准确识别意图。
Parameters:
-
llm
–用于意图识别的语言模型对象,OnlineChatModule或TrainableModule类型
-
intent_list
(list
, default:None
) –包含所有可能意图的字符串列表。可以包含中文或英文的意图。
-
prompt
(str
, default:''
) –用户附加的提示词。
-
constrain
(str
, default:''
) –用户附加的限制。
-
examples
(list[list]
, default:[]
) –额外的示例,格式为
[[query, intent], [query, intent], ...]
。 -
return_trace
((bool, 可选)
, default:False
) –如果设置为 True,则将结果记录在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 |
|