Tools
lazyllm.tools.Document
Bases: ModuleBase
初始化一个具有可选用户界面的文档模块。
此构造函数初始化一个可以有或没有用户界面的文档模块。如果启用了用户界面,它还会提供一个ui界面来管理文档操作接口,并提供一个用于用户界面交互的网页。
Parameters:
-
dataset_path(str) –数据集目录的路径。此目录应包含要由文档模块管理的文档。
-
embed–用于生成文档embedding的对象。
-
create_ui(bool, default:True) –指示是否为文档模块创建用户界面的标志。默认为 True。
-
launcher(optional, default:None) –负责启动服务器模块的对象或函数。如果未提供,则使用
lazyllm.launchers中的默认异步启动器 (sync=False)。
Examples:
>>> import lazyllm
>>> from lazyllm.tools import Document
>>> m = lazyllm.OnlineEmbeddingModule(source="glm")
>>> documents = Document(dataset_path='your_doc_path', embed=m, create_ui=False)
Source code in lazyllm/tools/rag/document.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 | |
create_node_group(name, transform, parent=LAZY_ROOT_NAME, **kwargs)
创建一个由指定规则生成的 node group。
Parameters:
-
name(str) –node group 的名称。
-
transform(Callable) –将 node 转换成 node group 的转换规则,函数原型是
(DocNode, group_name, **kwargs) -> List[DocNode]。目前内置的有 SentenceSplitter。用户也可以自定义转换规则。 -
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, create_ui=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(group)
查找指定节点的子节点。
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, create_ui=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(group)
查找指定节点的父节点。
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, create_ui=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
lazyllm.tools.Reranker
Bases: ModuleBase
用于创建节点(文档)后处理和重排序的模块。
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='rag_master', embed=m, create_ui=False)
>>> retriever = Retriever(documents, group_name='CoarseChunk', similarity='bm25', similarity_cut_off=0.01, topk=6)
>>> reranker = Reranker(name='ModuleReranker', model='bg-reranker-large', topk=1)
>>> ppl = lazyllm.ActionModule(retriever, reranker)
>>> ppl.start()
>>> print(ppl("query"))
Source code in lazyllm/tools/rag/rerank.py
lazyllm.tools.Retriever
Bases: ModuleBase
创建一个用于文档查询和检索的检索模块。此构造函数初始化一个检索模块,该模块根据指定的相似度度量配置文档检索过程。
Parameters:
-
doc(object) –文档模块实例。
-
group_name(str) –在哪个 node group 上进行检索。
-
similarity(str, default:'dummy') –用于设置文档检索的相似度函数。默认为 'dummy'。候选集包括 ["bm25", "bm25_chinese", "cosine"]。
-
similarity_cut_off(float, default:float('-inf')) –当相似度低于指定值时丢弃该文档。
-
index(str, default:'default') –用于文档检索的索引类型。目前仅支持 'default'。
-
topk(int, default:6) –表示取相似度最高的多少篇文档。
-
similarity_kw–传递给 similarity 计算函数的其它参数。
其中 group_name 有三个内置的切分策略,都是使用 SentenceSplitter 做切分,区别在于块大小不同:
- CoarseChunk: 块大小为 1024,重合长度为 100
- MediumChunk: 块大小为 256,重合长度为 25
- FineChunk: 块大小为 128,重合长度为 12
Examples:
>>> import lazyllm
>>> from lazyllm.tools import Retriever
>>> from lazyllm.tools import Document
>>> m = lazyllm.OnlineEmbeddingModule()
>>> documents = Document(dataset_path='your_doc_path', embed=m, create_ui=False)
>>> rm = Retriever(documents, group_name='CoarseChunk', similarity='bm25', similarity_cut_off=0.01, topk=6)
>>> rm.start()
>>> print(rm("query"))
Source code in lazyllm/tools/rag/retriever.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, create_ui=False)
>>> documents.create_node_group(name="sentences", transform=SentenceSplitter, chunk_size=1024, chunk_overlap=100)
Source code in lazyllm/tools/rag/transform.py
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 | |
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, TrainableModule
>>> llm = TrainableModule("internlm2-chat-7b")
>>> m = lazyllm.TrainableModule("bge-large-zh-v1.5")
>>> summary_parser = LLMParser(llm, language="en", task_type="summary")
>>> keywords_parser = LLMParser(llm, language="en", task_type="keywords")
>>> documents = Document(dataset_path='your_doc_path', embed=m, create_ui=False)
>>> rm = Retriever(documents, group_name='CoarseChunk', similarity='bm25', similarity_cut_off=0.01, topk=6)
>>> summary_result = summary_parser.transform(rm[0])
>>> keywords_result = keywords_parser.transform(rm[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
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 | |
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
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 | |
lazyllm.tools.FunctionCall
Bases: ModuleBase
FunctionCall是单轮工具调用类,如果LLM中的信息不足以回答用户的问题,必需结合外部知识来回答用户问题,则调用该类。如果LLM输出需要工具调用,则进行工具调用,并输出工具调用结果,输出结果为List类型,包含当前轮的输入、模型输出、工具输出。如果不需要工具调用,则直接输出LLM结果,输出结果为string类型。
Parameters:
-
llm(ModuleBase) –要使用的LLM可以是TrainableModule或OnlineChatModule。
-
tools(List[str]) –LLM使用的工具名称列表。
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
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.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
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.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 | |
lazyllm.tools.SQLiteTool
Bases: SqlTool
SQLiteTool是与SQLite数据库进行交互的专用工具。它扩展了SqlTool类,提供了创建表、执行查询和对SQLite数据库进行更新的方法。
Parameters:
-
db_file(str) –SQLite 文件数据库的路径
Examples:
>>> from lazyllm.tools import SQLiteTool
>>> with open("personal.db", "w") as _: pass
>>> sql_tool = SQLiteTool("personal.db")
>>> tables_info = {
... "User": {
... "fields": {
... "id": {
... "type": "integer",
... "comment": "user id"
... },
... "name": {
... "type": "text",
... "comment": "user name"
... },
... "email": {
... "type": "text",
... "comment": "user email"
... }
... }
... }
... }
>>> sql_tool.create_tables(tables_info)
>>> sql_tool.sql_update("INSERT INTO User (id, name, email) VALUES (1, 'Alice', 'alice@example.com')")
>>> table_info = sql_tool.get_all_tables()
>>> print(table_info)
>>> result_json = sql_tool.get_query_result_in_json("SELECT * from User")
>>> print(result_json)
Source code in lazyllm/tools/sql/sql_tool.py
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 | |
create_tables(tables_info)
根据描述表结构的JSON字典在SQLite数据库中创建表。 JSON格式形如:{$TABLE_NAME:{"fields":{$COLUMN_NAME:{"type":("REAL"/"TEXT"/"INT"), "comment":"..."} } } }
Source code in lazyllm/tools/sql/sql_tool.py
get_all_tables()
检索并返回SQLite数据库中所有表的字符串表示形式。
Source code in lazyllm/tools/sql/sql_tool.py
get_query_result_in_json(sql_script)
执行SQL查询并返回JSON格式的结果。
Source code in lazyllm/tools/sql/sql_tool.py
sql_update(sql_script)
在SQLite数据库上执行SQL插入或更新脚本。
Source code in lazyllm/tools/sql/sql_tool.py
lazyllm.tools.SqlModule
Bases: ModuleBase
SqlModule 是一个扩展自 ModuleBase 的类,提供了使用语言模型(LLM)生成和执行 SQL 查询的接口。 它设计用于与 SQL 数据库交互,从语言模型的响应中提取 SQL 查询,执行这些查询,并返回结果或解释。
Parameters:
-
llm–用于生成和解释 SQL 查询及解释的大语言模型。
-
sql_tool(SqlTool) –一个 SqlTool 实例,用于处理与 SQL 数据库的交互。
-
use_llm_for_sql_result((bool, 可选), default:True) –默认值为True。如果设置为False, 则只输出JSON格式表示的sql执行结果;True则会使用LLM对sql执行结果进行解读并返回自然语言结果。
-
return_trace((bool, 可选), default:False) –如果设置为 True,则将结果记录在trace中。默认为 False。
Examples:
>>> # First, run SQLiteTool example
>>> import lazyllm
>>> from lazyllm.tools import SQLiteTool, SqlModule
>>> sql_tool = SQLiteTool("personal.db")
>>> sql_llm = lazyllm.OnlineChatModule(model="gpt-4o", source="openai", base_url="***")
>>> sql_module = SqlModule(sql_llm, sql_tool, use_llm_for_sql_result=True)
>>> print(sql_module("员工Alice的邮箱地址是什么?"))
Source code in lazyllm/tools/sql/sql_tool.py
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 | |
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 | |