通用
Register
lazyllm.common.Register
Bases: object
LazyLLM提供了一套组件注册机制,允许将任意函数注册为LazyLLM的Component。通过注册器提供的分组机制,注册后的函数可在任意位置通过分组索引进行调用,无需显式导入。
lazyllm.components.register(cls, *, rewrite_func)→ 装饰器
该函数调用后返回一个装饰器,将被装饰函数包装为Component并注册到名为cls的分组中。
Parameters:
-
base(type) –基类
-
fnames(Union[str, List[str]]) –要重写的函数名或函数名列表
-
template(str, default:None) –注册模板字符串,默认为标准注册模板
-
default_group(str, default:None) –默认组名,默认为None
Examples:
>>> import lazyllm
>>> @lazyllm.component_register('mygroup')
... def myfunc(input):
... return input
...
>>> lazyllm.mygroup.myfunc()(1)
1
>>> @lazyllm.component_register.cmd('mygroup')
... def mycmdfunc(input):
... return f'echo {input}'
...
>>> lazyllm.mygroup.mycmdfunc()(1)
PID: 2024-06-01 00:00:00 lazyllm INFO: (lazyllm.launcher) Command: echo 1
PID: 2024-06-01 00:00:00 lazyllm INFO: (lazyllm.launcher) PID: 1
Source code in lazyllm/common/registry.py
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 | |
new_group(group_name)
创建一个新的ComponentGroup。新建的group会自动加入到__builtin__中,无需import即可在任一位置访问到该group。
Parameters:
-
group_name(str) –待创建的group的名字
lazyllm.common.registry.LazyDict
Bases: dict
一个为懒惰的程序员设计的特殊字典类。支持多种便捷的访问和操作方式。
特性:
- 使用点号代替['str']访问字典元素
- 支持首字母小写来使语句更像函数调用
- 当字典只有一个元素时支持直接调用
- 支持动态默认键
- 如果组名出现在名称中,允许省略组名
Parameters:
-
name(str, default:'') –字典的名称,默认为空字符串。
-
base–基类引用,默认为None。
-
*args–位置参数,传递给dict父类。
-
**kw–关键字参数,传递给dict父类。
Source code in lazyllm/common/registry.py
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 | |
remove(key)
从字典中移除指定的键值对。
Parameters:
-
key(str) –要移除的键。支持与__getattr__相同的键匹配规则,包括首字母小写和组名省略等特性。
注意
如果找不到匹配的键,将抛出AttributeError异常。
set_default(key)
设置字典的默认键。设置后可以通过.default属性访问该键对应的值。
Parameters:
-
key(str) –要设置为默认的键名。
注意
- key必须是字符串类型
- 设置后可以通过.default访问,或在字典只有一个元素时直接调用
Source code in lazyllm/common/registry.py
lazyllm.common.common.ResultCollector
Bases: object
结果收集器,用于在流程或任务执行过程中按名称存储和访问结果。
它通过调用自身(传入 name)返回一个可调用的 Impl 对象来收集指定名称的结果。
适用于需要跨步骤共享中间结果的场景。
Source code in lazyllm/common/common.py
items()
lazyllm.common.common.EnvVarContextManager
环境变量上下文管理器,用于 在代码块执行期间临时设置环境变量,退出时自动恢复原始环境变量。
Parameters:
-
env_vars_dict(dict) –需要临时设置的环境变量字典,值为 None 的变量将被忽略。
Source code in lazyllm/common/common.py
Bind
lazyllm.common.bind
Bind
Bases: object
Bind 类用于函数绑定与延迟调用,支持动态参数传入和上下文参数解析,实现灵活的函数组合与流水线式调用。
bind 函数能够将一个函数与固定的位置参数和关键字参数绑定,支持使用占位符(如 _0, _1)引用当前数据流中上游节点的输出,实现数据在流水线中的跳跃传递和灵活组合。
注意事项: - 绑定的参数可以是具体值,也可以是当前数据流中上游节点的输出占位符。 - 参数绑定仅在当前数据流上下文内生效,不能跨数据流绑定或绑定外部变量。
Parameters:
-
__bind_func(Callable 或 type, default:_None) –要绑定的函数或函数类型,传入类型时会自动实例化。
-
*args–绑定时固定的位置参数,可以包含占位符。
-
**kw–绑定时固定的关键字参数,可以包含占位符。
Examples:
>>> from lazyllm import bind, _0, _1
>>> def f1(x):
... return x ** 2
>>> def f21(input1, input2=0):
... return input1 + input2 + 1
>>> def f22(input1, input2=0):
... return input1 + input2 - 1
>>> def f3(in1='placeholder1', in2='placeholder2', in3='placeholder3'):
... return f"get [input:{in1}], [f21:{in2}], [f22:{in3}]"
>>> with pipeline() as ppl:
... ppl.f1 = f1
... with parallel() as ppl.subprl2:
... ppl.subprl2.path1 = f21
... ppl.subprl2.path2 = f22
... ppl.f3 = bind(f3, ppl.input, _0, _1)
...
>>> print(ppl(2))
get [input:2], [f21:5], [f22:3]
>>> # Demonstrate operator '|' overloading for bind
>>> with pipeline() as ppl2:
... ppl2.f1 = f1
... with parallel().bind(ppl2.input, _0) as ppl2.subprl2:
... ppl2.subprl2.path1 = f21
... ppl2.subprl2.path2 = f22
... ppl2.f3 = f3 | bind(ppl2.input, _0, _1)
...
>>> print(ppl2(2))
get [input:2], [f21:7], [f22:5]
Source code in lazyllm/common/bind.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 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 | |
Package
lazyllm.common.package
Bases: tuple
package类用于封装流水线或并行模块的返回值,保证传递给下游模块时自动拆包,从而支持多个值的灵活传递。
Examples:
>>> from lazyllm.common import package
>>> p = package(1, 2, 3)
>>> p
(1, 2, 3)
>>> p[1]
2
>>> p_slice = p[1:]
>>> isinstance(p_slice, package)
True
>>> p2 = package([4, 5])
>>> p + p2
(1, 2, 3, 4, 5)
Source code in lazyllm/common/common.py
Identity
lazyllm.common.Identity
恒等模块,用于直接返回输入值。
该模块常用于模块拼接结构中占位,无实际处理逻辑。若输入为多个参数,将自动打包为一个整体结构输出。
Parameters:
-
*args–可选的位置参数,占位用。
-
**kw–可选的关键字参数,占位用。
Source code in lazyllm/common/common.py
Compilation
lazyllm.common.compile_func(func_code, global_env=None)
将一段 python 函数字符串编译成一个可执行函数并返回。
Parameters:
-
func_code(str) –包含 python 函数代码的字符串
-
global_env(str, default:None) –在 python 函数中用到的包和全局变量
Examples:
from lazyllm.common import compile_func
code_str = 'def Identity(v): return v'
identity = compile_func(code_str)
assert identity('hello') == 'hello'
Source code in lazyllm/common/utils.py
Queue
lazyllm.common.FileSystemQueue
Bases: ABC
基于文件系统的队列抽象基类。
FileSystemQueue是一个抽象基类,提供了基于文件系统的队列操作接口。它支持多种后端实现(如SQLite、Redis),用于在分布式环境中进行消息传递和数据流控制。
该类实现了单例模式,确保每个类名只有一个队列实例,并提供了线程安全的队列操作。
Parameters:
-
klass(str, default:'__default__') –队列的类名标识符。默认为
'__default__'。
Returns:
- FileSystemQueue: 队列实例(单例模式)
Source code in lazyllm/common/queue.py
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 | |
clear()
清空队列。
移除队列中的所有消息,使其恢复为空状态。
Examples:
>>> import lazyllm
>>> queue = lazyllm.FileSystemQueue(klass='clear_test')
>>> for i in range(10):
... queue.enqueue(f"Message{i}")
>>> queue.size()
10
>>> queue.clear()
>>> queue.size()
0
>>> queue.peek() is None
True
Source code in lazyllm/common/queue.py
dequeue(limit=None)
从队列中取出消息。
此方法从队列头部取出消息并移除它们,可以指定一次取出的消息数量。
Parameters:
-
limit(int, default:None) –一次取出的最大消息数量。如果为None,则取出所有消息。默认为None。
Returns:
- list: 取出的消息列表。
Examples:
>>> import lazyllm
>>> queue = lazyllm.FileSystemQueue(klass='dequeue_test')
>>> for i in range(5):
... queue.enqueue(f"Message{i}")
>>> all_messages = queue.dequeue()
>>> all_messages
['Message0', 'Message1', 'Message2', 'Message3', 'Message4']
Source code in lazyllm/common/queue.py
enqueue(message)
get_instance(klass)
classmethod
获取指定类名对应的队列实例。
此方法会根据类名标识符返回对应的队列对象。如果该类名尚未注册,会触发自动初始化。
Parameters:
-
klass(str) –队列类名标识符,不能为
'__default__'。
Returns:
- FileSystemQueue: 与指定类名绑定的队列实例。
Source code in lazyllm/common/queue.py
init()
peek()
获取队列中的下一个消息,但不移除。
Returns:
- Any: 队列中下一个可用的消息;如果队列为空,返回
None。
Examples:
>>> import lazyllm
>>> queue = lazyllm.FileSystemQueue(klass='peek_test')
>>> queue.enqueue("First message")
>>> queue.enqueue("Second message")
>>> first_message = queue.peek()
>>> first_message
'First message'
>>> queue.peek()
'First message'
Source code in lazyllm/common/queue.py
set_default(queue)
classmethod
设置默认的队列实现。
此方法用于指定默认的队列类,作为未传入 klass 参数时的后端实现。
Parameters:
-
queue(Type) –默认队列类。
size()
获取队列中的消息数量。
Returns:
- int: 队列中当前消息的数量。
Examples:
>>> import lazyllm
>>> queue = lazyllm.FileSystemQueue(klass='size_test')
>>> queue.size()
0
>>> queue.enqueue("Message1")
>>> queue.size()
1
>>> queue.enqueue("Message2")
>>> queue.size()
2
>>> queue.dequeue()
['Message1', 'Message2']
>>> queue.size()
0
Source code in lazyllm/common/queue.py
lazyllm.common.multiprocessing.SpawnProcess
Bases: Process
Source code in lazyllm/common/multiprocessing.py
start()
使用spawn方式启动进程。
此方法在启动进程时强制使用spawn方式,这种方式会创建一个全新的Python解释器进程。spawn方式相比fork更安全,特别是在多线程环境下。
说明: - 使用spawn方式启动新进程,避免了fork可能带来的问题 - 会临时切换启动方式为spawn,执行完后恢复原有启动方式 - 继承自multiprocessing.Process.start()的所有功能
Examples:
```python
from lazyllm.common.multiprocessing import SpawnProcess
def worker():
print("Worker process running")
# Create and start a process using spawn method
process = SpawnProcess(target=worker)
process.start()
process.join()
```
Source code in lazyllm/common/multiprocessing.py
lazyllm.common.queue.SQLiteQueue
Bases: FileSystemQueue
基于 SQLite 的持久化文件系统队列。 该类扩展自 FileSystemQueue,使用 SQLite 数据库存储队列数据,通过 position 字段保证先进先出顺序,并支持并发安全的消息入队、出队、查看队头、队列大小查询和清空操作。 队列数据库默认存储在 ~/.lazyllm_filesystem_queue.db,通过文件锁机制确保多进程安全访问。
Parameters:
-
klass(str, default:'__default__') –队列分类名,用于逻辑隔离不同的队列,默认为 'default'。
Source code in lazyllm/common/queue.py
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 | |
lazyllm.common.ReadOnlyWrapper
Bases: object
一个轻量级只读包装器,用于包裹任意对象并对外提供只读访问(实际并未完全禁止修改,但复制时不会携带原始对象)。包装器可以动态替换内部对象,并提供判断对象是否为空的辅助方法。
Parameters:
-
obj(Optional[Any], default:None) –初始被包装的对象,默认为 None。
Source code in lazyllm/common/common.py
isNone()
lazyllm.common.queue.RedisQueue
Bases: FileSystemQueue
基于 Redis 实现的文件系统队列(继承自 FileSystemQueue),用于跨进程/节点的消息传递与队列管理。内部使用指定的 redis_url 初始化并管理底层存储,同时提供线程安全的初始化逻辑。
Parameters:
-
klass(str, default:'__default__') –队列的分类名称,用于区分不同队列实例,默认值为 'default'。
Source code in lazyllm/common/queue.py
Multiprocessing
lazyllm.common.ForkProcess
Bases: Process
LazyLLM 提供的增强进程类,继承自 Python 标准库的 multiprocessing.Process。此类专门使用 fork 启动方法来创建子进程,并提供了同步/异步执行模式的支持。
Parameters:
-
group–进程组,默认为
None -
target–要在进程中执行的函数,默认为
None -
name–进程名称,默认为
None -
args–传递给目标函数的参数元组,默认为
() -
kwargs–传递给目标函数的关键字参数字典,默认为
{} -
daemon–是否为守护进程,默认为
None -
sync–是否为同步模式,默认为
True。在同步模式下,进程执行完目标函数后会自动退出;在异步模式下,进程会持续运行直到被手动终止。
注意: 此类主要用于 LazyLLM 内部的进程管理,特别是在需要长期运行的服务器进程中。
Examples:
>>> import lazyllm
>>> from lazyllm.common import ForkProcess
>>> import time
>>> import os
>>> def simple_task(task_id):
... print(f"Process {os.getpid()} executing task {task_id}")
... time.sleep(0.1)
... return f"Task {task_id} completed by process {os.getpid()}"
>>> process = ForkProcess(target=simple_task, args=(1,), sync=True)
>>> process.start()
Process 12345 executing task 1
Source code in lazyllm/common/multiprocessing.py
start()
启动 ForkProcess 进程。此方法会使用 fork 启动方法来创建子进程,并开始执行目标函数。
此方法的特点:
- Fork 启动: 使用 fork 方法创建子进程,在 Unix/Linux 系统上提供更好的性能
- 上下文管理: 自动管理进程启动方法的上下文,确保使用正确的启动方式
- 继承父类: 继承自
multiprocessing.Process.start()的所有功能
注意: 此方法会实际创建新的进程并开始执行,调用后进程会立即开始运行。
Source code in lazyllm/common/multiprocessing.py
work(f, sync)
staticmethod
ForkProcess 的核心工作方法,负责包装目标函数并处理同步/异步执行逻辑。
Parameters:
-
f–要执行的目标函数
-
sync–是否为同步模式。在同步模式下,执行完目标函数后进程会退出;在异步模式下,进程会持续运行。
Source code in lazyllm/common/multiprocessing.py
Options
lazyllm.common.Option
Bases: object
LazyLLM 提供的选项管理类,用于管理多个选项值并在它们之间进行迭代。此类主要用于参数网格搜索和超参数调优场景。
Parameters:
-
*obj–一个或多个选项值,可以是任意类型的对象。如果传入单个列表或元组,会自动展开。至少需要提供两个选项。
主要特性:
- 多选项管理: 可以管理多个不同的选项值。
- 迭代支持: 支持标准 Python 迭代协议,可以遍历所有选项。
- 当前值访问: 可直接访问当前选中的选项值。
- 深度复制: 支持获取当前选中选项值的深拷贝。
- 循环迭代: 可在所有选项之间循环迭代。
注意: 此类主要用于 LazyLLM 内部的参数搜索和实验管理,尤其在 TrialModule 中进行参数网格搜索时。
Examples:
>>> import lazyllm
>>> from lazyllm.common.option import Option
>>> learning_rates = Option(0.001, 0.01, 0.1)
>>> print(f"当前学习率: {learning_rates}")
当前学习率: <Option options="(0.001, 0.01, 0.1)" curr="0.001">
>>> print(f"所有选项: {list(learning_rates)}")
所有选项: [0.001, 0.01, 0.1]
Source code in lazyllm/common/option.py
DynamicDescriptor
lazyllm.common.DynamicDescriptor
动态描述符类,用于创建支持实例和类级别调用的描述符。
Parameters:
-
func(callable) –要包装的函数或方法
Source code in lazyllm/common/common.py
lazyllm.common.CaseInsensitiveDict
Bases: dict
大小写不敏感的字典类。
CaseInsensitiveDict 继承自 dict,提供大小写不敏感的键值存储和检索功能。所有的键都会被转换为小写形式存储,确保无论使用大写、小写或混合大小写的键名都能访问到相同的值。
特点: - 所有键在存储时自动转换为小写 - 支持标准的字典操作(获取、设置、检查包含关系) - 保持字典的原有功能,只是键名处理方式不同
Parameters:
-
*args–传递给父类 dict 的位置参数
-
**kwargs–传递给父类 dict 的关键字参数
Examples:
>>> from lazyllm.common import CaseInsensitiveDict
>>> # 创建大小写不敏感的字典
>>> d = CaseInsensitiveDict({'Name': 'John', 'AGE': 25, 'City': 'New York'})
>>>
>>> # 使用不同大小写访问相同的键
>>> print(d['name']) # 使用小写
... 'John'
>>> print(d['NAME']) # 使用大写
... 'John'
>>> print(d['Name']) # 使用首字母大写
... 'John'
>>>
>>> # 设置值时也会转换为小写
>>> d['EMAIL'] = 'john@example.com'
>>> print(d['email']) # 使用小写访问
... 'john@example.com'
>>>
>>> # 检查键是否存在(大小写不敏感)
>>> 'AGE' in d
True
>>> 'age' in d
True
>>> 'Age' in d
True
>>>
>>> # 支持标准字典操作
>>> d['PHONE'] = '123-456-7890'
>>> print(d.get('phone'))
... '123-456-7890'
>>> print(len(d))
... 5
Source code in lazyllm/common/common.py
lazyllm.common.ProcessPoolExecutor
Bases: ProcessPoolExecutor
Source code in lazyllm/common/multiprocessing.py
submit(fn, /, *args, **kwargs)
将任务提交到进程池中执行。
此方法将一个函数及其参数序列化后提交到进程池中执行,返回一个 Future 对象,用于获取任务执行结果或状态。
Parameters:
-
fn(Callable) –要执行的函数。
-
*args–传递给函数的位置参数。
-
**kwargs–传递给函数的关键字参数。
Returns:
- concurrent.futures.Future: 表示任务执行状态的
Future对象。
Examples:
>>> from lazyllm.common.multiprocessing import ProcessPoolExecutor
>>> import time
>>>
>>> def task(x):
... time.sleep(1)
... return x * 2
...
>>> with ProcessPoolExecutor(max_workers=2) as executor:
... future = executor.submit(task, 5)
... result = future.result()
... print(result)
10
Source code in lazyllm/common/multiprocessing.py
lazyllm.common.ArgsDict
Bases: dict
参数字典类,用于管理和验证命令行参数。
Parameters:
-
*args–传递给父类dict的 positional arguments
-
**kwargs–传递给父类dict的 keyword arguments
Returns:
- ArgsDict实例,提供参数检查和格式化功能
Source code in lazyllm/common/common.py
check_and_update(kw)
检查并更新参数字典。
Parameters:
-
kw(dict) –要更新的参数字典
Source code in lazyllm/common/common.py
parse_kwargs()
将参数字典解析为命令行参数字符串。
Source code in lazyllm/common/common.py
Threading
lazyllm.common.Thread
Bases: Thread
LazyLLM 提供的增强线程类,继承自 Python 标准库的 threading.Thread。此类提供了额外的功能,包括会话ID管理、预钩子函数支持和异常处理机制。
Parameters:
-
group–线程组,默认为
None -
target–要在线程中执行的函数,默认为
None -
name–线程名称,默认为
None -
args–传递给目标函数的参数元组,默认为
() -
kwargs–传递给目标函数的关键字参数字典,默认为
None -
prehook–在线程执行前要调用的函数或函数列表,默认为
None -
daemon–是否为守护线程,默认为
None
Examples:
>>> import lazyllm
>>> from lazyllm.common.threading import Thread
>>> import time
>>> def simple_task(name):
... time.sleep(0.1)
... return f"Hello from {name}"
>>> thread = Thread(target=simple_task, args=("Worker",))
>>> thread.start()
>>> result = thread.get_result()
>>> print(result)
Hello from Worker
>>> def setup_environment():
... print("Setting up environment...")
... return "environment_ready"
>>> def validate_input(data):
... print(f"Validating input: {data}")
... if not isinstance(data, (int, float)):
... raise ValueError("Input must be numeric")
>>> def process_data(data):
... print(f"Processing data: {data}")
... time.sleep(0.1)
... return data * 2
>>> thread = Thread(
... target=process_data,
... args=(42,),
... prehook=[setup_environment, lambda: validate_input(42)]
... )
>>> thread.start()
Setting up environment...
Validating input: 42
Processing data: 42
>>> result = thread.get_result()
>>> print(f"Final result: {result}")
Final result: 84
Source code in lazyllm/common/threading.py
get_result()
获取线程执行结果的方法。此方法会阻塞直到线程执行完成,然后返回执行结果或重新抛出异常。
Returns:
- 线程执行的结果。如果目标函数正常执行,返回其返回值;如果发生异常,会重新抛出该异常。
注意: 此方法应该在调用 thread.start() 之后使用,用于获取线程的执行结果。
Source code in lazyllm/common/threading.py
work(prehook, target, args, **kw)
线程的核心工作方法,负责执行预钩子函数、目标函数,并处理异常和结果。
Parameters:
-
prehook–预钩子函数列表,在线程执行前调用
-
target–要执行的目标函数
-
args–传递给目标函数的参数
-
**kw–传递给目标函数的关键字参数
注意: 此方法由 Thread 类内部调用,用户通常不需要直接调用此方法。
Source code in lazyllm/common/threading.py
LazyLLMCMD
lazyllm.common.LazyLLMCMD
Bases: object
命令行操作封装类,提供安全、灵活的命令行管理功能。
Parameters:
-
cmd(Union[str, List[str], Callable]) –命令行指令,支持三种形式:字符串命令,命令列表,可调用对象。
-
return_value(Any, default:None) –预设返回值。
-
checkf(Any, default:lambda *a: True) –命令验证函数。
-
no_displays(Any, default:None) –需要过滤的敏感参数名。
Examples:
>>> from lazyllm.common import LazyLLMCMD
>>> cmd = LazyLLMCMD("run --epochs=50 --batch-size=32")
>>> print(cmd.get_args("epochs"))
50
>>> print(cmd.get_args("batch-size"))
32
>>> base = LazyLLMCMD("python train.py", checkf=lambda x: True)
>>> new = base.with_cmd("python predict.py")
Source code in lazyllm/common/common.py
get_args(key)
从命令字符串中提取指定参数的值。
Parameters:
-
key–要提取的参数名
Source code in lazyllm/common/common.py
with_cmd(cmd)
创建新命令对象并继承当前配置。
Parameters:
-
cmd–新的命令内容(类型需与原始命令一致)
Source code in lazyllm/common/common.py
lazyllm.common.utils.SecurityVisitor
Bases: NodeVisitor
AST-based security analyzer to detect unsafe operations in Python code.
IMPORTANT: Method names within this class (e.g., visit_Call, visit_Import) should not
be renamed to lowercase. These method names are part of the NodeVisitor pattern from the ast
module and must remain consistant with this naming convention to function correctly.
Source code in lazyllm/common/utils.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 | |
visit_Attribute(node)
Check os.environ and tempfile usage
Source code in lazyllm/common/utils.py
visit_Call(node)
Check function calls
Source code in lazyllm/common/utils.py
visit_FunctionDef(node)
Check function definitions that might return import
Source code in lazyllm/common/utils.py
visit_Import(node)
visit_ImportFrom(node)
visit_Lambda(node)
Check lambda functions that might return import
Source code in lazyllm/common/utils.py
visit_ListComp(node)
Check list comprehensions that might contain import
Source code in lazyllm/common/utils.py
lazyllm.common.common.Finalizer
Bases: object
终结器类,用于管理资源的清理和释放操作。可以作为上下文管理器使用,或通过对象销毁时自动触发清理。
Parameters:
-
func1(Callable) –主要的清理函数。如果提供了func2,则func1会立即执行,func2作为清理函数。
-
func2(Optional[Callable], default:None) –可选的清理函数,默认为None。
-
condition(Callable, default:lambda: True) –条件函数,返回True时才执行清理函数,默认总是返回True。
用途: 1. 可以作为上下文管理器使用(with语句) 2. 可以通过对象销毁时自动触发清理 3. 支持条件性清理 4. 支持两阶段初始化和清理
注意: - 当提供func2时,func1会在初始化时立即执行 - 清理函数只会执行一次 - 清理操作会在对象销毁或退出上下文时执行