Common
Register
lazyllm.common.Register
Bases: object
LazyLLM provides a registration mechanism for Components, allowing any function to be registered as a Component of LazyLLM. The registered functions can be indexed at any location through the grouping mechanism provided by the registrar, without the need for explicit import.
lazyllm.components.register(cls, *, rewrite_func)→ Decorator
After the function is called, it returns a decorator which wraps the decorated function into a Component and registers it in a group named cls.
Parameters:
-
base(type) –Base class
-
fnames(Union[str, List[str]]) –Function name or function name list to rewrite
-
template(str, default:None) –Registration template string, defaults to standard registration template
-
default_group(str, default:None) –Default group name, defaults to 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
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 | |
new_group(group_name)
Creates a new ComponentGroup. The newly created group will be automatically added to builtin and can be accessed at any location without the need for import.
Parameters:
-
group_name(str) –The name of the group to be created.
Source code in lazyllm/common/registry.py
lazyllm.common.registry.LazyDict
Bases: dict
A special dictionary class designed for lazy programmers. Supports various convenient access and operation methods.
Features:
- Use dot notation instead of ['str'] to access dictionary elements
- Support lowercase first character to make statements more like function calls
- Support direct calls when dictionary has only one element
- Support dynamic default keys
- Allow omitting group name if it appears in the name
Parameters:
-
name(str, default:'') –Name of the dictionary, defaults to empty string.
-
base–Base class reference, defaults to None.
-
*args–Positional arguments passed to dict parent class.
-
**kw–Keyword arguments passed to dict parent class.
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 | |
remove(key)
Remove the specified key-value pair from the dictionary.
Parameters:
-
key(str) –The key to remove. Supports the same key matching rules as getattr, including lowercase first character and group name omission features.
Note
Raises AttributeError if no matching key is found.
Source code in lazyllm/common/registry.py
set_default(key)
Set the default key for the dictionary. After setting, the value can be accessed through the .default property.
Parameters:
-
key(str) –The key name to set as default.
Note
- key must be a string type
- After setting, can be accessed via .default, or called directly when dictionary has only one element
Source code in lazyllm/common/registry.py
lazyllm.common.common.ResultCollector
Bases: object
A result collector used to store and access results by name during the execution of a flow or task.
Calling the instance with a name returns a callable Impl object that collects results for that name.
Useful for scenarios where intermediate results need to be shared across steps.
Source code in lazyllm/common/common.py
items()
Get all stored (name, value) pairs.
Returns:
- ItemsView[str, Any]: A set-like object containing name-value pairs of results.
keys()
Get all stored result names.
Returns:
- KeysView[str]: A set-like object containing result names.
lazyllm.common.common.EnvVarContextManager
Environment variable context manager used to temporarily set environment variables during the execution of a code block, automatically restoring original environment variables upon exit.
Parameters:
-
env_vars_dict(dict) –Dictionary of environment variables to temporarily set; variables with None values are ignored.
Source code in lazyllm/common/common.py
Bind
lazyllm.common.bind
Bind
Bases: object
The Bind class provides function binding and deferred invocation capabilities, supporting dynamic argument passing and context-based argument resolution for flexible function composition and pipeline-style calls.
The bind function binds a callable with fixed positional and keyword arguments, supporting placeholders (e.g. _0, _1) to reference outputs of upstream nodes within the current pipeline, enabling flexible data jumps and function composition.
Notes
- Bound arguments can be concrete values or placeholders referring to upstream pipeline outputs.
- Bindings are local to the current pipeline context and do not support cross-pipeline or external variable binding.
Parameters:
-
__bind_func(Callable or type, default:_None) –The function or function type to bind. If a type is given, it will be instantiated automatically.
-
*args–Fixed positional arguments to bind, supporting placeholders.
-
**kw–Fixed keyword arguments to bind, supporting placeholders.
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
The package class is used to encapsulate the return values of pipeline or parallel modules, ensuring automatic unpacking when passing to the next module, thereby supporting flexible multi-value passing.
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
Identity module that directly returns the input as output.
This module serves as a no-op placeholder in composition pipelines. If multiple inputs are provided, they are packed together before returning.
Parameters:
-
*args–Optional positional arguments for placeholder compatibility.
-
**kw–Optional keyword arguments for placeholder compatibility.
Source code in lazyllm/common/common.py
Compilation
lazyllm.common.compile_func(func_code, global_env=None)
Compile a Python function string into an executable function and return it.
Parameters:
-
func_code(str) –A string containing Python function code
-
global_env(str, default:None) –Packages and global variables used in the Python function
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
Abstract base class for file system-based queues.
FileSystemQueue is an abstract base class that provides a file system-based queue operation interface. It supports multiple backend implementations (such as SQLite, Redis) for message passing and data flow control in distributed environments.
This class implements the singleton pattern, ensuring only one queue instance per class name, and provides thread-safe queue operations.
Parameters:
-
klass(str, default:'__default__') –Class name identifier for the queue. Defaults to
'__default__'.
Returns:
- FileSystemQueue: Queue instance (singleton pattern)
Source code in lazyllm/common/queue.py
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 | |
clear()
Clear the queue.
Removes all messages from the queue, resetting it to an empty state.
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)
Retrieve messages from the queue.
This method retrieves messages from the head of the queue and removes them, with the option to specify the number of messages to retrieve at once.
Parameters:
-
limit(int, default:None) –Maximum number of messages to retrieve at once. If None, retrieves all messages. Defaults to None.
Returns:
- list: List of retrieved messages.
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)
Add a message to the queue.
This method adds the specified message to the tail of the queue, following the First-In-First-Out (FIFO) principle.
Parameters:
-
message–The message content to be added to the queue.
Examples:
>>> import lazyllm
>>> queue = lazyllm.FileSystemQueue(klass='enqueue_test')
>>> queue.enqueue(123)
>>> queue.peek()
'123'
Source code in lazyllm/common/queue.py
get_instance(klass)
classmethod
Get the queue instance for the specified class name.
This method returns the queue object bound to the given class name. If the class name has not been registered, it will be initialized automatically.
Parameters:
-
klass(str) –Queue class name identifier, must not be
'__default__'.
Returns:
- FileSystemQueue: Queue instance bound to the specified class name.
Source code in lazyllm/common/queue.py
init()
Initialize the queue.
This method clears all messages in the current queue, equivalent to calling clear().
peek()
Retrieve the next message in the queue without removing it.
Returns:
- Any: The next available message in the queue, or
Noneif the queue is empty.
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
Set the default queue implementation.
This method specifies the default queue class, used as the backend implementation when klass is not provided.
Parameters:
-
queue(Type) –Default queue class.
Source code in lazyllm/common/queue.py
size()
Get the number of messages in the queue.
Returns:
- int: The current number of messages in the queue.
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()
Start the process using spawn method.
This method forces the use of spawn method when starting the process, which creates a brand new Python interpreter process. Spawn is safer than fork, especially in multi-threaded environments.
Notes: - Uses spawn method to start new process, avoiding potential issues with fork - Temporarily switches to spawn method and restores original method after execution - Inherits all functionality from 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
Persistent file system queue backed by SQLite. This class extends FileSystemQueue and stores queue data in an SQLite database. Messages are ordered by a position field to preserve FIFO behavior. The class supports concurrent-safe operations including enqueue, dequeue, peek, size checking, and clearing the queue. The queue database is saved at ~/.lazyllm_filesystem_queue.db, with a file lock mechanism ensuring safe access in multi-process environments.
Parameters:
-
klass(str, default:'__default__') –Name of the queue category used to logically separate queues. Default is 'default'.
Source code in lazyllm/common/queue.py
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 | |
lazyllm.common.ReadOnlyWrapper
Bases: object
A lightweight read-only wrapper that holds an arbitrary object and exposes its attributes. It supports swapping the internal object dynamically and provides utility for checking emptiness. Note: it does not enforce deep immutability, but deepcopy drops the wrapped object.
Parameters:
-
obj(Optional[Any], default:None) –The initial wrapped object, defaults to None.
Source code in lazyllm/common/common.py
isNone()
Check whether the wrapper currently holds no object.
Returns:
- bool: True if the internal object is None, otherwise False.
lazyllm.common.queue.RedisQueue
Bases: FileSystemQueue
Redis-backed file system queue (inherits from FileSystemQueue) for cross-process/node message passing and queue management. It initializes its underlying storage using a configured Redis URL and employs thread-safe setup logic.
Parameters:
-
klass(str, default:'__default__') –Classification name for the queue instance to distinguish different queues. Defaults to 'default'.
Source code in lazyllm/common/queue.py
Multiprocessing
lazyllm.common.ForkProcess
Bases: Process
Enhanced process class provided by LazyLLM, inheriting from Python's standard library multiprocessing.Process. This class specifically uses the fork start method to create child processes and provides support for synchronous/asynchronous execution modes.
Parameters:
-
group–Process group, default to
None -
target–Function to be executed in the process, default to
None -
name–Process name, default to
None -
args–Tuple of arguments to pass to the target function, default to
() -
kwargs–Dictionary of keyword arguments to pass to the target function, default to
{} -
daemon–Whether the process is a daemon process, default to
None -
sync–Whether to use synchronous mode, default to
True. In synchronous mode, the process automatically exits after executing the target function; in asynchronous mode, the process continues running until manually terminated.
Note: This class is primarily used for LazyLLM's internal process management, especially in long-running server processes.
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()
Start the ForkProcess. This method uses the fork start method to create a child process and begin executing the target function.
Features of this method:
- Fork Start: Uses fork method to create child processes, providing better performance on Unix/Linux systems
- Context Management: Automatically manages the context of process start methods, ensuring the correct start method is used
- Parent Inheritance: Inherits all functionality from
multiprocessing.Process.start()
Note: This method actually creates a new process and begins execution, the process starts running immediately after calling.
Source code in lazyllm/common/multiprocessing.py
work(f, sync)
staticmethod
Core working method of ForkProcess, responsible for wrapping the target function and handling synchronous/asynchronous execution logic.
Parameters:
-
f–Target function to execute
-
sync–Whether to use synchronous mode. In synchronous mode, the process exits after executing the target function; in asynchronous mode, the process continues running.
Source code in lazyllm/common/multiprocessing.py
Options
lazyllm.common.Option
Bases: object
Option management class provided by LazyLLM, used for managing multiple option values and iterating between them. This class is primarily used for parameter grid search and hyperparameter tuning scenarios.
Parameters:
-
*obj–One or more option values, which can be objects of any type. If a single list or tuple is passed, it will be automatically expanded. At least two options must be provided.
Key features:
- Multi-option Management: Can manage multiple different option values.
- Iteration Support: Supports standard Python iteration protocol, allowing traversal of all options.
- Current Value Access: Provides access to the currently selected option.
- Deep Copy: Supports obtaining a deep copy of the currently selected option.
- Cyclic Iteration: Options can be iterated over in a cyclic manner.
Note: This class is mainly used for LazyLLM's internal parameter search and trial management, especially in TrialModule for parameter grid search.
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
Dynamic descriptor class for creating descriptors that support both instance and class level calls.
Parameters:
-
func(callable) –Function or method to be wrapped
Source code in lazyllm/common/common.py
lazyllm.common.CaseInsensitiveDict
Bases: dict
Case-insensitive dictionary class.
CaseInsensitiveDict inherits from dict and provides case-insensitive key-value storage and retrieval. All keys are converted to lowercase when stored, ensuring that values can be accessed regardless of whether the key name is uppercase, lowercase, or mixed case.
Features
- All keys are automatically converted to lowercase when stored
- Supports standard dictionary operations (get, set, check containment)
- Maintains all original dict functionality, only differs in key name handling
Parameters:
-
*args–Positional arguments passed to the parent dict class
-
**kwargs–Keyword arguments passed to the parent dict class
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)
Submit a task to the process pool for execution.
This method serializes a function and its arguments, then submits them to the process pool for execution. It returns a Future object to track the task's status or result.
Parameters:
-
fn(Callable) –The function to execute.
-
*args–Positional arguments passed to the function.
-
**kwargs–Keyword arguments passed to the function.
Returns:
- concurrent.futures.Future: A
Futureobject representing the task's execution status.
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
Parameter dictionary class for managing and validating command line arguments.
Parameters:
-
*args–Positional arguments passed to parent dict class
-
**kwargs–Keyword arguments passed to parent dict class
Returns:
- ArgsDict instance providing parameter checking and formatting functionality
Source code in lazyllm/common/common.py
check_and_update(kw)
Check and update parameter dictionary.
Parameters:
-
kw(dict) –Parameter dictionary to update
Source code in lazyllm/common/common.py
parse_kwargs()
Parse parameter dictionary into command line argument string.
Source code in lazyllm/common/common.py
Threading
lazyllm.common.Thread
Bases: Thread
Enhanced thread class provided by LazyLLM, inheriting from Python's standard library threading.Thread. This class provides additional functionality including session ID management, pre-hook function support, and exception handling mechanisms.
Parameters:
-
group–Thread group, default to
None -
target–Function to be executed in the thread, default to
None -
name–Thread name, default to
None -
args–Tuple of arguments to pass to the target function, default to
() -
kwargs–Dictionary of keyword arguments to pass to the target function, default to
None -
prehook–Function or list of functions to call before thread execution, default to
None -
daemon–Whether the thread is a daemon thread, default to
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()
Method to retrieve the thread execution result. This method blocks until the thread execution is complete, then returns the execution result or re-raises the exception.
Returns:
- The result of thread execution. If the target function executes normally, returns its return value; if an exception occurs, re-raises that exception.
Note: This method should be used after calling thread.start() to retrieve the thread execution result.
Source code in lazyllm/common/threading.py
work(prehook, target, args, **kw)
Core working method of the thread, responsible for executing pre-hook functions, target function, and handling exceptions and results.
Parameters:
-
prehook–List of pre-hook functions to call before thread execution
-
target–Target function to execute
-
args–Arguments to pass to the target function
-
**kw–Keyword arguments to pass to the target function
Note: This method is called internally by the Thread class, users typically don't need to call this method directly.
Source code in lazyllm/common/threading.py
LazyLLMCMD
lazyllm.common.LazyLLMCMD
Bases: object
Command line operation wrapper class providing secure and flexible command management.
Parameters:
-
cmd(Union[str, List[str], Callable]) –Command input, supports three formats:String command,Command list,Callable object.
-
return_value(Any, default:None) –Preset return value.
-
checkf(Any, default:lambda *a: True) –Command validation function with signature.
-
no_displays(Any, default:None) –Sensitive parameter names to filter.
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)
Extracts specified argument value from command string.
Parameters:
-
key–Argument name
Source code in lazyllm/common/common.py
with_cmd(cmd)
Create new command object inheriting current configuration.
Parameters:
-
cmd–New command content (must be same type as original)
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
Finalizer class for managing resource cleanup and release operations. Can be used as a context manager or trigger cleanup automatically when object is destroyed.
Parameters:
-
func1(Callable) –Primary cleanup function. If func2 is provided, func1 is executed immediately and func2 becomes the cleanup function.
-
func2(Optional[Callable], default:None) –Optional cleanup function, defaults to None.
-
condition(Callable, default:lambda: True) –Condition function, cleanup is executed only when it returns True, defaults to always returning True.
Uses: 1. Can be used as a context manager (with statement) 2. Can trigger cleanup automatically when object is destroyed 3. Supports conditional cleanup 4. Supports two-phase initialization and cleanup
Note
- When func2 is provided, func1 is executed immediately during initialization
- Cleanup function is executed only once
- Cleanup occurs when object is destroyed or context is exited
Source code in lazyllm/common/common.py
lazyllm.common.FlatList.absorb(item)
Absorb elements into the list.
Parameters:
-
item–Element to add, can be a single element or a list