Flow
lazyllm.flow.FlowBase
Bases: SessionConfigableBase
Base class for constructing flow-like structures that can hold multiple items and organize them hierarchically.
This class allows combining different objects (including FlowBase instances or other types)
into a structured flow, with optional names for each item, enabling both name-based and index-based access.
Items in the structure can be added or traversed dynamically.
Parameters:
-
*items–Items to be included in the flow, which can be instances of
FlowBaseor other objects. -
item_names(list of str, default:None) –A list of names corresponding to the items, paired with
itemsin order. If not provided, all items will be assignedNoneas their name. -
auto_capture(bool, default:False) –Whether to enable automatic variable capture. If
True, when used as a context manager, newly defined variables in the current scope will be automatically added to the flow. Defaults toFalse.
Source code in lazyllm/flow/flow.py
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 | |
ancestor
property
is_root
property
A property that indicates whether the current flow item is the root of the flow structure.
Returns:
- bool: True if the current item has no parent (
_fatheris None), otherwise False.
Examples:
for_each(filter, action)
Performs an action on each item in the flow that matches a given filter.
The method recursively traverses the flow structure, applying the action to each item that passes the filter.
Parameters:
-
filter(callable) –A function that takes an item as input and returns True if the item should have the action applied.
-
action(callable) –A function that takes an item as input and performs some operation on it.
Returns:
- None
Examples:
>>> import lazyllm
>>> def test1(): print('1')
...
>>> def test2(): print('2')
...
>>> def test3(): print('3')
...
>>> flow = lazyllm.pipeline(test1, lazyllm.pipeline(test2, test3))
>>> flow.for_each(lambda x: callable(x), lambda x: print(x))
<Function type=test1>
<Function type=test2>
<Function type=test3>
Source code in lazyllm/flow/flow.py
id(module=None)
Get the identifier for a module or the flow itself. If a string is provided, it is returned as-is. If a bound module is provided, returns its associated item_id. If no argument is given, returns the unique id of the entire flow.
Parameters:
-
module(Optional[Union[str, Any]], default:None) –Target module or string identifier.
Returns:
- str: Corresponding identifier string.
Source code in lazyllm/flow/flow.py
lazyllm.flow.LazyLLMFlowsBase
Bases: FlowBase
A base class for flow structures with hook support and unified execution logic.
LazyLLMFlowsBase is the base class for all LazyLLM flow types. It organizes a sequence of callable modules into a flow and provides support for pre/post hooks, synchronization control, post-processing, and error-safe invocation. It is not intended for direct use but instead serves as a foundational class for concrete flow types like Pipeline, Parallel, etc.
Parameters:
-
args–A sequence of callables representing the flow modules.
-
post_action–An optional callable applied to the output after main flow execution. Defaults to
None。 -
auto_capture–If True, variables newly defined within the
withblock will be automatically added to the flow. Defaults toFalse. -
**kw–Key-value pairs for named components.
Source code in lazyllm/flow/flow.py
317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 | |
bind(*args, **kw)
Bind arguments to the current flow, producing a bind object.
Parameters:
-
*args–Positional arguments.
-
**kw–Keyword arguments.
Returns:
- bind: The bound bind object.
Source code in lazyllm/flow/flow.py
clear_hooks()
invoke(it, __input, *, bind_args_source=None, **kw)
Invoke a target (function, module, or bind object) with the given input.
Supports root/pipeline output replacement for bind objects.
Parameters:
-
it(Callable | bind) –The target to invoke.
-
__input(Any) –Input data.
-
bind_args_source(Any, default:None) –Source of bind arguments.
-
**kw–Additional keyword arguments.
Source code in lazyllm/flow/flow.py
register_hook(hook_type)
Register a hook type for additional processing before and after the flow execution.
Parameters:
-
hook_type(LazyLLMHook) –The hook type or instance to register.
Source code in lazyllm/flow/flow.py
set_sync(sync=True)
Set whether the flow executes synchronously.
Parameters:
-
sync(bool, default:True) –Whether to execute synchronously. Default is True.
Returns:
- LazyLLMFlowsBase: The current instance.
Source code in lazyllm/flow/flow.py
start(*args, **kw)
Start flow processing execution (deprecated).
This method is deprecated, it is recommended to directly call the flow instance as a function. Executes the flow processing and returns the result.
Parameters:
-
*args–Variable positional arguments passed to the flow processing.
-
**kw–Named arguments passed to the flow processing.
Returns:
- The result of flow processing.
Note:
- This method is marked as deprecated, please use direct invocation of the flow instance instead.
Source code in lazyllm/flow/flow.py
unregister_hook(hook_type)
Unregister a previously registered hook.
Parameters:
-
hook_type(LazyLLMHook) –The hook type or instance to remove.
wait()
Wait for all asynchronous tasks in the flow to complete.
Returns:
- LazyLLMFlowsBase: The current instance.
Source code in lazyllm/flow/flow.py
lazyllm.flow.Pipeline
Bases: LazyLLMFlowsBase
A sequential execution model that forms a pipeline of processing stages.
The Pipeline class is a linear sequence of processing stages, where the output of one stage becomes the input to the next. It supports the addition of post-actions that can be performed after the last stage. It is a subclass of LazyLLMFlowsBase which provides a lazy execution model and allows for functions to be wrapped and registered in a lazy manner.
Parameters:
-
args(list of callables or single callable, default:()) –The processing stages of the pipeline. Each element can be a callable function or an instance of
LazyLLMFlowsBase.FuncWrap. If a single list or tuple is provided, it is unpacked as the stages of the pipeline. -
post_action(callable, default:None) –An optional action to perform after the last stage of the pipeline. Defaults to None.
-
auto_capture(bool, default:False) –If True, variables newly defined within the
withblock will be automatically added to the flow. Defaults toFalse. -
kwargs(dict of callables) –Named processing stages of the pipeline. Each key-value pair represents a named stage, where the key is the name and the value is the callable stage.
Returns:
- The output of the last stage of the pipeline.
Examples:
>>> import lazyllm
>>> ppl = lazyllm.pipeline(
... stage1=lambda x: x+1,
... stage2=lambda x: f'get {x}'
... )
>>> ppl(1)
'get 2'
>>> ppl.stage2
<Function type=lambda>
Source code in lazyllm/flow/flow.py
536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 | |
output(module, unpack=False)
Get the output result of a specified module in the pipeline.
Parameters:
-
module–The module to get output from. Can be a module object or module name.
-
unpack(bool, default:False) –Whether to unpack the output result. Defaults to False.
Returns:
- bind.Args: A bound argument object for data passing in the pipeline.
Source code in lazyllm/flow/flow.py
lazyllm.flow.save_pipeline_result(flag=True)
A context manager that temporarily sets whether to save intermediate results during pipeline execution.
When entering the context, Pipeline.g_save_flow_result is set to the given value. After exiting, it restores the previous value. Useful for debugging or recording intermediate outputs.
Parameters:
-
flag(bool, default:True) –Whether to enable result saving. Defaults to True.
Returns:
- ContextManager: A context manager.
Examples:
>>> import lazyllm
>>> pipe = lazyllm.pipeline(lambda x: x + 1, lambda x: x * 2)
>>> with lazyllm.save_pipeline_result(True):
... result = pipe(1)
>>> result
4
Source code in lazyllm/flow/flow.py
lazyllm.flow.Parallel
Bases: LazyLLMFlowsBase
A class for managing parallel flows in LazyLLMFlows.
This class inherits from LazyLLMFlowsBase and provides an interface for running operations in parallel or sequentially. It supports concurrent execution using threads and allows for the return of results as a dictionary.
The Parallel class can be visualized as follows:
# /> module11 -> ... -> module1N -> out1 \
# input -> module21 -> ... -> module2N -> out2 -> (out1, out2, out3)
# \> module31 -> ... -> module3N -> out3 /
The Parallel.sequential method can be visualized as follows:
Parameters:
-
args–Variable length argument list for the base class.
-
_scatter(bool, default:False) –If
True, the input is split across the items. IfFalse, the same input is passed to all items. Defaults toFalse. -
_concurrent(Union[bool, int], default:True) –If
True, operations will be executed concurrently using threading. If an integer, specifies the maximum number of concurrent executions. IfFalse, operations will be executed sequentially. Defaults toTrue. -
multiprocessing(bool, default:False) –If
True, multiprocessing will be used instead of multithreading for parallel execution. This can provide true parallelism but adds overhead for inter-process communication. Defaults toFalse. -
auto_capture(bool, default:False) –If True, variables newly defined within the
withblock will be automatically added to the flow. Defaults toFalse. -
kwargs–Arbitrary keyword arguments for the base class.
asdict property
Tag Parallel so that the return value of each call to Parallel is changed from a tuple to a dict. When using asdict, make sure that the elements of parallel are named, for example: parallel(name=value).
astuple property
Mark Parallel so that the return value of Parallel changes from package to tuple each time it is called.
aslist property
Mark Parallel so that the return value of Parallel changes from package to list each time it is called.
sum property
Mark Parallel so that the return value of Parallel is accumulated each time it is called.
join(self, string)
Mark Parallel so that the return value of Parallel is joined by string each time it is called.
Examples:
>>> import lazyllm
>>> test1 = lambda a: a + 1
>>> test2 = lambda a: a * 4
>>> test3 = lambda a: a / 2
>>> ppl = lazyllm.parallel(test1, test2, test3)
>>> ppl(1)
(2, 4, 0.5)
>>> ppl = lazyllm.parallel(a=test1, b=test2, c=test3)
>>> ppl(1)
{2, 4, 0.5}
>>> ppl = lazyllm.parallel(a=test1, b=test2, c=test3).asdict
>>> ppl(2)
{'a': 3, 'b': 8, 'c': 1.0}
>>> ppl = lazyllm.parallel(a=test1, b=test2, c=test3).astuple
>>> ppl(-1)
(0, -4, -0.5)
>>> ppl = lazyllm.parallel(a=test1, b=test2, c=test3).aslist
>>> ppl(0)
[1, 0, 0.0]
>>> ppl = lazyllm.parallel(a=test1, b=test2, c=test3).join('\n')
>>> ppl(1)
'2\n4\n0.5'
Source code in lazyllm/flow/flow.py
660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 | |
join(string='')
Marks the Parallel instance to join its results with the specified string on each call.
Parameters:
-
string(str, default:'') –The string to use for joining results. Defaults to an empty string.
Returns:
- Parallel: Returns the current Parallel instance configured to join results with the specified string.
Example:
Source code in lazyllm/flow/flow.py
sequential(*args, **kw)
classmethod
Creates a Parallel instance that executes sequentially.
This class method sets _concurrent to False, causing all operations to be executed in sequence rather than in parallel.
The Parallel.sequential method can be visualized as follows:
Parameters:
-
args–Variable length argument list passed to the Parallel constructor.
-
kwargs–Keyword arguments passed to the Parallel constructor.
-
_scatter(bool) –If
True, the input is split across the items. IfFalse, the same input is passed to all items. Defaults toFalse. -
_concurrent(bool) –If
True, operations will be executed concurrently using threading. IfFalse, operations will be executed sequentially. Defaults toTrue. -
multiprocessing(bool) –If
True, multiprocessing will be used instead of multithreading for parallel execution. This can provide true parallelism but adds overhead for inter-process communication. Defaults toFalse. -
auto_capture(bool) –If True, variables newly defined within the
withblock will be automatically added to the flow. Defaults toFalse. -
args–Variable length argument list for the base class.
-
kwargs–Arbitrary keyword arguments for the base class.
Returns:
- Parallel: A new Parallel instance configured for sequential execution.
Source code in lazyllm/flow/flow.py
lazyllm.flow.Diverter
Bases: Parallel
A flow diverter that routes inputs through different modules in parallel.
The Diverter class is a specialized form of parallel processing where multiple inputs are each processed by a separate sequence of modules in parallel. The outputs are then aggregated and returned as a tuple.
This class is useful when you have distinct data processing pipelines that can be executed concurrently, and you want to manage them within a single flow construct.
# /> in1 -> module11 -> ... -> module1N -> out1 \
# (in1, in2, in3) -> in2 -> module21 -> ... -> module2N -> out2 -> (out1, out2, out3)
# \> in3 -> module31 -> ... -> module3N -> out3 /
Parameters:
-
args–Variable length argument list representing the modules to be executed in parallel.
-
_concurrent(bool, default:True) –A flag to control whether the modules should be run concurrently. Defaults to
True. You can useDiverter.sequentialinstead ofDiverterto set this variable. -
auto_capture(bool, default:False) –If True, variables newly defined within the
withblock will be automatically added to the flow. Defaults toFalse. -
kwargs–Arbitrary keyword arguments representing additional modules, where the key is the name of the module.
Examples:
>>> import lazyllm
>>> div = lazyllm.diverter(lambda x: x+1, lambda x: x*2, lambda x: -x)
>>> div(1, 2, 3)
(2, 4, -3)
>>> div = lazyllm.diverter(a=lambda x: x+1, b=lambda x: x*2, c=lambda x: -x).asdict
>>> div(1, 2, 3)
{'a': 2, 'b': 4, 'c': -3}
>>> div(dict(c=3, b=2, a=1))
{'a': 2, 'b': 4, 'c': -3}
Source code in lazyllm/flow/flow.py
lazyllm.flow.Warp
Bases: Parallel
A flow warp that applies a single module to multiple inputs in parallel.
The Warp class is designed to apply the same processing module to a set of inputs. It effectively 'warps' the single module around the inputs so that each input is processed in parallel. The outputs are collected and returned as a tuple. It is important to note that this class cannot be used for asynchronous tasks, such as training and deployment.
# /> in1 \ /> out1 \
# (in1, in2, in3) -> in2 -> module1 -> ... -> moduleN -> out2 -> (out1, out2, out3)
# \> in3 / \> out3 /
Parameters:
-
args–Variable length argument list representing the single module to be applied to all inputs.
-
_scatter(bool) –Whether to scatter inputs into parts before processing. Defaults to False.
-
_concurrent(bool | int, default:True) –Whether to execute in parallel. Can be a boolean or a max concurrency limit. Defaults to True.
-
auto_capture(bool, default:False) –If True, variables newly defined within the
withblock will be automatically added to the flow. Defaults toFalse. -
kwargs–Arbitrary keyword arguments for future extensions.
Note
- Only one function is allowed in warp.
- The Warp flow should not be used for asynchronous tasks such as training and deployment.
Examples:
>>> import lazyllm
>>> warp = lazyllm.warp(lambda x: x * 2)
>>> warp(1, 2, 3, 4)
(2, 4, 6, 8)
>>> warp = lazyllm.warp(lazyllm.pipeline(lambda x: x * 2, lambda x: f'get {x}'))
>>> warp(1, 2, 3, 4)
('get 2', 'get 4', 'get 6', 'get 8')
>>> from lazyllm import package
>>> warp1 = lazyllm.warp(lambda x, y: x * 2 + y)
>>> print(warp1([package(1,2), package(10, 20)]))
(4, 40)
Source code in lazyllm/flow/flow.py
lazyllm.flow.IFS
Bases: LazyLLMFlowsBase
Implements an If-Else functionality within the LazyLLMFlows framework.
The IFS (If-Else Flow Structure) class is designed to conditionally execute one of two provided paths (true path or false path) based on the evaluation of a given condition. After the execution of the selected path, an optional post-action can be applied, and the input can be returned alongside the output if specified.
Parameters:
-
cond(callable) –A callable that takes the input and returns a boolean. It determines which path to execute. If
cond(input)evaluates to True,tpathis executed; otherwise,fpathis executed. -
tpath(callable) –The path to be executed if the condition is True.
-
fpath(callable) –The path to be executed if the condition is False.
-
post_action(callable, default:None) –An optional callable that is executed after the selected path. It can be used to perform cleanup or further processing. Defaults to None.
Returns:
- The output of the executed path.
Examples:
>>> import lazyllm
>>> cond = lambda x: x > 0
>>> tpath = lambda x: x * 2
>>> fpath = lambda x: -x
>>> ifs_flow = lazyllm.ifs(cond, tpath, fpath)
>>> ifs_flow(10)
20
>>> ifs_flow(-5)
5
Source code in lazyllm/flow/flow.py
lazyllm.flow.Switch
Bases: LazyLLMFlowsBase
A control flow mechanism that selects and executes a flow based on a condition.
The Switch class provides a way to choose between different flows depending on the value of an expression or the truthiness of conditions. It is similar to a switch-case statement found in other programming languages.
# switch(exp):
# case cond1: input -> module11 -> ... -> module1N -> out; break
# case cond2: input -> module21 -> ... -> module2N -> out; break
# case cond3: input -> module31 -> ... -> module3N -> out; break
Parameters:
-
args–A variable length argument list, alternating between conditions and corresponding flows or functions. Conditions are either callables returning a boolean or values to be compared with the input expression.
-
conversion(callable, default:None) –A function used to transform or preprocess the evaluation expression
expbefore performing condition matching. Defaults toNone. -
post_action(callable, default:None) –A function to be called on the output after the selected flow is executed. Defaults to
None. -
judge_on_full_input(bool, default:True) –If set to
True, the conditional judgment will be performed through the input ofswitch, otherwise the input will be split into two parts: the judgment condition and the actual input, and only the judgment condition will be judged.
Raises:
-
TypeError–If an odd number of arguments are provided, or if the first argument is not a dictionary and the conditions are not provided in pairs.
Examples:
>>> import lazyllm
>>> def is_positive(x): return x > 0
...
>>> def is_negative(x): return x < 0
...
>>> switch = lazyllm.switch(is_positive, lambda x: 2 * x, is_negative, lambda x : -x, 'default', lambda x : '000', judge_on_full_input=True)
>>>
>>> switch(1)
2
>>> switch(0)
'000'
>>> switch(-4)
4
>>>
>>> def is_1(x): return True if x == 1 else False
...
>>> def is_2(x): return True if x == 2 else False
...
>>> def is_3(x): return True if x == 3 else False
...
>>> def t1(x): return 2 * x
...
>>> def t2(x): return 3 * x
...
>>> def t3(x): return x
...
>>> with lazyllm.switch(judge_on_full_input=True) as sw:
... sw.case[is_1::t1]
... sw.case(is_2, t2)
... sw.case[is_3, t3]
...
>>> sw(1)
2
>>> sw(2)
6
>>> sw(3)
3
Source code in lazyllm/flow/flow.py
1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 | |
lazyllm.flow.Loop
Bases: Pipeline
Initializes a Loop flow structure which repeatedly applies a sequence of functions to an input until a stop condition is met or a specified count of iterations is reached.
The Loop structure allows for the definition of a simple control flow where a series of steps are applied in a loop, with an optional stop condition that can be used to exit the loop early based on the output of the steps.
Parameters:
-
*item(callable or list of callables, default:()) –The function(s) or callable object(s) that will be applied in the loop.
-
stop_condition(callable, default:None) –A function that takes the output of the last item in the loop as input and returns a boolean. If it returns
True, the loop will stop. IfNone, the loop will continue untilcountis reached. Defaults toNone. -
count(int, default:maxsize) –The maximum number of iterations to run the loop for. Defaults to
sys.maxsize. -
post_action(callable, default:None) –A function to be called with the final output after the loop ends. Defaults to
None. -
auto_capture(bool, default:False) –If True, variables newly defined within the
withblock will be automatically added to the flow. Defaults toFalse. -
judge_on_full_input(bool, default:True) –If set to
True, the conditional judgment will be performed through the input ofstop_condition; otherwise, the input will be split into two parts: the judgment condition and the actual input, and only the judgment condition will be judged.
Raises:
-
AssertionError–If the provided
stop_conditionis neither callable norNone.
Examples:
>>> import lazyllm
>>> loop = lazyllm.loop(lambda x: x * 2, stop_condition=lambda x: x > 10, judge_on_full_input=True)
>>> loop(1)
16
>>> loop(3)
12
>>>
>>> with lazyllm.loop(stop_condition=lambda x: x > 10, judge_on_full_input=True) as lp:
... lp.f1 = lambda x: x + 1
... lp.f2 = lambda x: x * 2
...
>>> lp(0)
14
Source code in lazyllm/flow/flow.py
lazyllm.flow.Graph
Bases: LazyLLMFlowsBase
A complex flow control structure based on Directed Acyclic Graph (DAG).
The Graph class allows you to create complex processing graphs where nodes represent processing functions and edges represent data flow. It supports topological sorting to ensure correct execution order and can handle complex dependencies with multiple inputs and outputs.
The Graph class is particularly suitable for scenarios requiring complex data flow and dependency management, such as machine learning pipelines, data processing workflows, etc.
Parameters:
-
post_action(callable, default:None) –A function to be called after the graph execution is complete. Defaults to
None. -
auto_capture(bool, default:False) –Whether to automatically capture variables from context. Defaults to
False. -
kwargs–Arbitrary keyword arguments representing named nodes and corresponding functions.
Returns:
- The final output result of the graph.
Source code in lazyllm/flow/flow.py
1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 | |
end_node
property
start_node
property
add_const_edge(constant, to_node)
Add a constant edge that passes a fixed value to a specified node.
This method is used to pass constant values as input to nodes in the graph without needing to get data from other nodes.
Parameters:
-
constant–The constant value to pass.
-
to_node(str or Node) –The name or Node object of the target node.
Examples:
>>> import lazyllm
>>> with lazyllm.graph() as g:
... g.add = lambda x, y: x + y
>>> g.add_const_edge(10, 'add')
>>> g._constants
[10]
Source code in lazyllm/flow/flow.py
add_edge(from_node, to_node, formatter=None)
Add an edge to the graph, defining data flow between nodes.
This method is used to define connection relationships between nodes in the graph, specifying how data flows from one node to another.
Parameters:
-
from_node(str or Node) –The name or Node object of the source node.
-
to_node(str or Node) –The name or Node object of the target node.
-
formatter(callable, default:None) –Optional formatting function for data transformation during transfer. Defaults to
None.
Examples:
>>> import lazyllm
>>> with lazyllm.graph() as g:
... g.node1 = lambda x: x * 2
... g.node2 = lambda x: x + 1
... g.node3 = lambda x, y: x + y
>>> g.add_edge('__start__', 'node1')
>>> g.add_edge('node1', 'node2')
>>> g.add_edge('node3', '__end__')
>>> g._nodes['node1'].outputs
[<Flow type=Node name=node2>]
>>> def double_input(data):
... return data * 2
>>> g.add_edge('node1', 'node3', formatter=double_input)
>>> g._nodes['node3'].inputs
{'node1': <function double_input at ...>}
Source code in lazyllm/flow/flow.py
compute_node(sid, node, intermediate_results, futures)
Compute the output result of a single node.
This is an internal method of the graph, used to execute the computation of a single node, including getting input data, applying formatter functions, calling node functions, etc.
Parameters:
-
sid–Session ID.
-
node(Node) –The node to compute.
-
intermediate_results(dict) –Intermediate result storage.
-
futures(dict) –Async task dictionary.
Returns:
- The computation result of the node.
Examples:
>>> import lazyllm
>>> with lazyllm.graph() as g:
... g.add = lambda x, y: x + y
... g.multiply = lambda x: x * 2
>>> g.add_edge('__start__', 'add')
>>> g.add_const_edge(5, 'add')
>>> g.add_edge('add', 'multiply')
>>> g.add_edge('multiply', '__end__')
>>> result = g(3) # x=3, y=5 (常量)
>>> result
16
Source code in lazyllm/flow/flow.py
set_node_arg_name(arg_names)
Set the argument names for nodes.
This method is used to set the names of function arguments for nodes in the graph, which is important for correct invocation of multi-parameter functions.
Parameters:
-
arg_names(list) –List of argument names, corresponding to the order when nodes were created.
Examples:
>>> import lazyllm
>>> with lazyllm.graph() as g:
... g.add = lambda a, b: a + b
... g.multiply = lambda x, y: x * y
>>> g.set_node_arg_name([['x', 'y'], ['a', 'b']])
>>> g._nodes['add'].arg_names
['x', 'y']
>>> g._nodes['multiply'].arg_names
['a', 'b']
Source code in lazyllm/flow/flow.py
topological_sort()
Perform topological sorting to return the correct node execution order.
This method uses Kahn's algorithm to perform topological sorting on the directed acyclic graph, ensuring all dependencies are satisfied.
Returns:
- List[Node]: List of nodes arranged in topological order.
Raises: - ValueError: If there are circular dependencies in the graph.
Examples:
>>> import lazyllm
>>> with lazyllm.graph() as g:
... g.node1 = lambda x: x * 2
... g.node2 = lambda x: x + 1
... g.node3 = lambda x, y: x + y
>>> g.add_edge('__start__', 'node1')
>>> g.add_edge('node1', 'node2')
>>> g.add_edge('node1', 'node3')
>>> g.add_edge('node2', 'node3')
>>> g.add_edge('node3', '__end__')
>>> sorted_nodes = g.topological_sort()
>>> [node.name for node in sorted_nodes]
['__start__', 'node1', 'node2', 'node3', '__end__']
>>> g.add_edge('node3', 'node1')
>>> try:
... g.topological_sort()
... except ValueError as e:
... print("检测到循环依赖")
检测到循环依赖