Skip to content

automa

This module contains the core Automa classes and functions.

Automa

Bases: Worker

Base class for an Automa.

In Bridgic, an Automa is an entity that manages and orchestrates a group of workers. An Automa itself is also a Worker, which enables the nesting of Automa instances within each other.

Source code in bridgic/core/automa/_automa.py
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
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
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
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
class Automa(Worker):
    """
    Base class for an Automa.

    In Bridgic, an Automa is an entity that manages and orchestrates a group of workers. An Automa itself is also a Worker, which enables the nesting of Automa instances within each other.
    """
    _running_options: RunningOptions

    # For event handling.
    _event_handlers: Dict[str, EventHandlerType]
    _default_event_handler: EventHandlerType

    # For human interaction.
    _worker_interaction_indices: Dict[str, int]

    # Ongoing human interactions triggered by the `interact_with_human()` call from workers of the current Automa.
    # worker_key -> list of interactions.
    _ongoing_interactions: Dict[str, List[_InteractionAndFeedback]]

    _thread_pool: ThreadPoolExecutor
    _main_thread_id: int
    _main_loop: asyncio.AbstractEventLoop

    # Cached callbacks for top-level automa execution, which are built once and reused across multiple arun() calls.
    _cached_callbacks: Optional[List[WorkerCallback]] = None

    def __init__(
        self,
        name: str = None,
        thread_pool: Optional[ThreadPoolExecutor] = None,
        running_options: Optional[RunningOptions] = None,
    ):
        super().__init__()

        # Set parent to self for top-level Automa
        self.parent = self

        # Set the name of the Automa instance.
        self.name = name or f"{self.__class__.__name__}-{uuid.uuid4().hex[:8]}"

        # Initialize the shared running options.
        self._running_options = running_options or RunningOptions()

        # Initialize data structures for event handling and human interactions
        self._event_handlers = {}
        self._default_event_handler = None
        self._worker_interaction_indices = {}
        self._ongoing_interactions = {}

        self._thread_pool = thread_pool

    @override
    def dump_to_dict(self) -> Dict[str, Any]:
        state_dict = super().dump_to_dict()
        state_dict["name"] = self.name
        state_dict["running_options"] = self._running_options
        state_dict["ongoing_interactions"] = self._ongoing_interactions
        return state_dict

    @override
    def load_from_dict(self, state_dict: Dict[str, Any]) -> None:
        super().load_from_dict(state_dict)
        self.name = state_dict["name"]
        self._running_options = state_dict["running_options"]

        self._event_handlers = {}
        self._default_event_handler = None
        self._worker_interaction_indices = {}
        self._ongoing_interactions = state_dict["ongoing_interactions"]
        self._thread_pool = None

    @classmethod
    def load_from_snapshot(
        cls, 
        snapshot: Snapshot,
        thread_pool: Optional[ThreadPoolExecutor] = None,
    ) -> "Automa":
        """
        Load an Automa instance from a snapshot.

        Parameters
        ----------
        snapshot: Snapshot
            The snapshot to load the Automa instance from.
        thread_pool: Optional[ThreadPoolExecutor]
            The thread pool for parallel running of I/O-bound tasks. If not provided, a default thread pool will be used.

        Returns
        -------
        Automa
            The loaded Automa instance.
        """
        # Here you can compare snapshot.serialization_version with SERIALIZATION_VERSION, and handle any necessary version compatibility issues if needed.
        automa = load_bytes(snapshot.serialized_bytes)
        if thread_pool:
            automa.thread_pool = thread_pool
        return automa

    @property
    def thread_pool(self) -> Optional[ThreadPoolExecutor]:
        """
        Get/Set the thread pool for parallel running of I/O-bound tasks used by the current Automa instance and its nested Automa instances.

        Note: If an Automa is nested within another Automa, the thread pool of the top-level Automa will be used, rather than the thread pool of the nested Automa.

        Returns
        -------
        Optional[ThreadPoolExecutor]
            The thread pool.
        """
        return self._thread_pool

    @thread_pool.setter
    def thread_pool(self, executor: ThreadPoolExecutor) -> None:
        """
        Set the thread pool for parallel running of I/O-bound tasks.

        Note: If an Automa is nested within another Automa, the thread pool of the top-level Automa will be used, rather than the thread pool of the nested Automa.
        """
        self._thread_pool = executor

    @abstractmethod
    def _locate_interacting_worker(self) -> Optional[str]:
        """
        Locate the worker that is currently interacting with human.

        Returns
        -------
        Optional[str]
            The necessary identifier of the worker that is currently interacting with human.
        """
        ...

    @abstractmethod
    def _get_worker_key(self, worker: Worker) -> Optional[str]:
        """
        Identify the worker key by the worker instance.
        """
        ...

    @abstractmethod
    def _get_worker_instance(self, worker_key: str) -> Worker:
        """
        Get the worker instance by the worker key.
        """
        ...

    def set_running_options(
        self,
        debug: Optional[bool] = None,
    ):
        """
        Set runtime-configurable running options for this Automa instance.

        This method only supports fields that can be changed at runtime. Fields that must be set 
        during initialization (such as `callback_builders`) cannot be changed here and must be 
        provided via the `running_options` parameter in the Automa constructor.

        For fields that can be delayed to be set, some settings (like `debug`) from the outermost 
        (top-level) Automa will override the settings of all inner (nested) Automa instances.
        For example, if the top-level Automa instance sets `debug = True` and the nested instances 
        sets `debug = False`, then the nested Automa instance will run in debug mode when the 
        top-level Automa instance is executed. We call it the Setting Penetration Mechanism.

        Parameters
        ----------
        debug : bool, optional
            Whether to enable debug mode. If None, the current value is not changed.
            This field is subject to the Setting Penetration Mechanism.
        """
        if debug is not None:
            self._running_options.debug = debug

    def _get_top_running_options(self) -> RunningOptions:
        if self.is_top_level():
            # Here we are at the top-level automa.
            return self._running_options
        return self.parent._get_top_running_options()

    def _collect_ancestor_callback_builders(self) -> List[WorkerCallbackBuilder]:
        """
        Collect callback builders from all ancestor automas in the ancestor chain.

        This method traverses up the automa ancestor chain (from current to top-level)
        to collect all callback builders from ancestor automas' RunningOptions, ensuring
        that callbacks from all levels are propagated to nested workers. The current
        automa's callbacks are included as the last in the chain.

        The ancestor chain is the path from the current automa up to the top-level automa
        through the parent relationship. This method collects callbacks from all automas
        in this chain, ordered from top-level (first) to current level (last).

        Returns
        -------
        List[WorkerCallbackBuilder]
            A list of callback builders collected from all ancestor automas in the ancestor
            chain and the current automa, ordered from top-level (first) to current level (last).
        """
        # First, collect all callback builders by traversing up the ancestor chain
        # (from current to top-level, stored in reverse order)
        ancestor_callback_builders_reverse = []
        current: Optional[Automa] = self

        # Traverse up the ancestor chain to collect callback builders
        while True:
            ancestor_callback_builders_reverse.append(current._running_options.callback_builders)
            if current.is_top_level():
                break
            else:
                current = current.parent

        # Reverse to get order from top-level (first) to current (last)
        callback_builders = []
        for builders in reversed(ancestor_callback_builders_reverse):
            callback_builders.extend(builders)

        return callback_builders

    def _get_automa_callbacks(self) -> List[WorkerCallback]:
        """
        Get or build cached callback instances for top-level automa execution.

        This method ensures that callback instances are built once and reused across
        multiple arun() calls, respecting the is_shared setting of each builder.

        Returns
        -------
        List[WorkerCallback]
            List of callback instances for top-level automa execution.
        """
        if self._cached_callbacks is None:
            effective_builders = []
            effective_builders.extend(GlobalSetting.read().callback_builders)
            effective_builders.extend(self._running_options.callback_builders)
            self._cached_callbacks = [cb.build() for cb in effective_builders]
        return self._cached_callbacks

    ###############################################################
    ########## [Bridgic Event Handling Mechanism] starts ##########
    ###############################################################

    def register_event_handler(self, event_type: Optional[str], event_handler: EventHandlerType) -> None:
        """
        Register an event handler for the specified event type. If `event_type` is set to None, the event handler will be registered as the default handler that will handle all event types.

        Note: Only event handlers registered on the top-level Automa will be invoked to handle events.

        Parameters
        ----------
        event_type: Optional[str]
            The type of event to be handled. If set to None, the event handler will be registered as the default handler and will be used to handle all event types.
        event_handler: EventHandlerType
            The event handler to be registered.
        """
        if event_type is None:
            self._default_event_handler = event_handler
        else:
            self._event_handlers[event_type] = event_handler

    def unregister_event_handler(self, event_type: Optional[str]) -> None:
        """
        Unregister an event handler for the specified event type.

        Parameters
        ----------
        event_type: Optional[str]
            The type of event to be unregistered. If set to None, the default event handler will be unregistered.
        """
        if event_type in self._event_handlers:
            del self._event_handlers[event_type]
        if event_type is None:
            self._default_event_handler = None

    def unregister_all_event_handlers(self) -> None:
        """
        Unregister all event handlers.
        """
        self._event_handlers.clear()
        self._default_event_handler = None

    class _FeedbackSender(FeedbackSender):
        def __init__(
                self, 
                future: asyncio.Future[Feedback],
                post_loop: asyncio.AbstractEventLoop,
                ):
            self._future = future
            self._post_loop = post_loop

        def send(self, feedback: Feedback) -> None:
            try:
                current_loop = asyncio.get_running_loop()
            except Exception:
                current_loop = None
            try:
                if current_loop is self._post_loop:
                    self._future.set_result(feedback)
                else:
                    self._post_loop.call_soon_threadsafe(self._future.set_result, feedback)
            except asyncio.InvalidStateError:
                # Suppress the InvalidStateError to be raised, maybe due to timeout.
                import warnings
                warnings.warn(f"Feedback future already set. feedback: {feedback}", FutureWarning)

    @override
    def post_event(self, event: Event) -> None:
        """
        Post an event to the application layer outside the Automa.

        The event handler implemented by the application layer will be called in the same thread as the worker (maybe the main thread or a new thread from the thread pool).

        Note that `post_event` can be called either in a non-async method or in an async method.

        The event will be bubbled up to the top-level Automa, where it will be processed by the event handler registered with the event type.

        Parameters
        ----------
        event: Event
            The event to be posted.
        """
        def _handler_need_feedback_sender(handler: EventHandlerType):
            positional_param_names = get_param_names_by_kind(handler, Parameter.POSITIONAL_ONLY) + get_param_names_by_kind(handler, Parameter.POSITIONAL_OR_KEYWORD)
            var_positional_param_names = get_param_names_by_kind(handler, Parameter.VAR_POSITIONAL)
            return len(var_positional_param_names) > 0 or len(positional_param_names) > 1

        if not self.is_top_level():
            # Bubble up the event to the top-level Automa.
            return self.parent.post_event(event)

        # Here is the top-level Automa.
        # Call event handlers
        if event.event_type in self._event_handlers:
            if _handler_need_feedback_sender(self._event_handlers[event.event_type]):
                self._event_handlers[event.event_type](event, feedback_sender=None)
            else:
                self._event_handlers[event.event_type](event)
        if self._default_event_handler is not None:
            if _handler_need_feedback_sender(self._default_event_handler):
                self._default_event_handler(event, feedback_sender=None)
            else:
                self._default_event_handler(event)

    def request_feedback(
        self, 
        event: Event,
        timeout: Optional[float] = None
    ) -> Feedback:
        """
        Request feedback for the specified event from the application layer outside the Automa. This method blocks the caller until the feedback is received.

        Note that `request_feedback` should only be called from within a non-async method running in a new thread of the Automa thread pool.

        Parameters
        ----------
        event: Event
            The event to be posted to the event handler implemented by the application layer.
        timeout: Optional[float]
            A float or int number of seconds to wait for if the feedback is not received. If None, then there is no limit on the wait time.

        Returns
        -------
        Feedback
            The feedback received from the application layer.

        Raises
        ------
        TimeoutError
            If the feedback is not received before the timeout. Note that the raised exception is the built-in `TimeoutError` exception, instead of asyncio.TimeoutError or concurrent.futures.TimeoutError!
        """
        if threading.get_ident() == self._main_thread_id:
            raise AutomaRuntimeError(
                f"`request_feedback` should only be called in a different thread from the main thread of the {self.name}. "
            )
        return asyncio.run_coroutine_threadsafe(
            self.request_feedback_async(event, timeout),
            self._main_loop
        ).result()

    async def request_feedback_async(
        self, 
        event: Event,
        timeout: Optional[float] = None
    ) -> Feedback:
        """
        Request feedback for the specified event from the application layer outside the Automa. This method blocks the caller until the feedback is received.

        The event handler implemented by the application layer will be called in the next event loop iteration, in the main thread.

        Parameters
        ----------
        event: Event
            The event to be posted to the event handler implemented by the application layer.
        timeout: Optional[float]
            A float or int number of seconds to wait for if the feedback is not received. If None, then there is no limit on the wait time.

        Returns
        -------
        Feedback
            The feedback received from the application layer.

        Raises
        ------
        TimeoutError
            If the feedback is not received before the timeout. Note that the raised exception is the built-in `TimeoutError` exception, instead of asyncio.TimeoutError!
        """
        if not self.is_top_level():
            # Bubble up the event to the top-level Automa.
            return await self.parent.request_feedback_async(event, timeout)

        # Here is the top-level Automa.
        event_loop = asyncio.get_running_loop()
        future = event_loop.create_future()
        feedback_sender = self._FeedbackSender(future, event_loop)
        # Call event handlers
        if event.event_type in self._event_handlers:
            self._event_handlers[event.event_type](event, feedback_sender)
        if self._default_event_handler is not None:
            self._default_event_handler(event, feedback_sender)

        try:
            return await asyncio.wait_for(future, timeout)
        except TimeoutError as e:
            # When python >= 3.11 here.
            raise TimeoutError(f"No feedback is received before timeout in Automa[{self.name}]") from e
        except asyncio.TimeoutError as e:
            # Version compatibility resolution: asyncio.wait_for raises asyncio.TimeoutError before python 3.11.
            # https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for
            raise TimeoutError(f"No feedback is received before timeout in Automa[{self.name}]") from e

    ###############################################################
    ########### [Bridgic Event Handling Mechanism] ends ###########
    ###############################################################

    ###############################################################
    ######## [Bridgic Human Interaction Mechanism] starts #########
    ###############################################################

    def interact_with_human(
        self,
        event: Event,
        interacting_worker: Optional[Worker] = None,
    ) -> InteractionFeedback:
        """
        Trigger an interruption in the "human-in-the-loop interaction" during the execution of the Automa.

        Parameters
        ----------
        event: Event
            The event that triggered the interaction.
        interacting_worker: Optional[Worker]
            The worker instance that is currently interacting with human. If not provided, the worker will be located automatically.

        Returns
        -------
        InteractionFeedback
            The feedback received from the application layer.
        """
        if not interacting_worker:
            kickoff_worker_key: str = self._locate_interacting_worker()
        else:
            kickoff_worker_key = self._get_worker_key(interacting_worker)

        if kickoff_worker_key:
            return self.interact_with_human_from_worker_key(event, kickoff_worker_key)
        raise AutomaRuntimeError(
            f"Get kickoff worker failed in Automa[{self.name}] "
            f"when trying to interact with human with event: {event}"
        )

    def interact_with_human_from_worker_key(
        self,
        event: Event,
        worker_key: str
    ) -> InteractionFeedback:
        # Match the interaction and feedback to see if it matches
        matched_feedback: _InteractionAndFeedback = None
        cur_interact_index = self._get_and_increment_interaction_index(worker_key)
        if worker_key in self._ongoing_interactions:
            interaction_and_feedbacks = self._ongoing_interactions[worker_key]
            if cur_interact_index < len(interaction_and_feedbacks):
                matched_feedback = interaction_and_feedbacks[cur_interact_index]
                # Check the event type
                if event.event_type != matched_feedback.interaction.event.event_type:
                    raise AutomaRuntimeError(
                        f"Event type mismatch! Automa[{self.name}-worker[{worker_key}]]. "
                        f"interact_with_human passed-in event: {event}\n"
                        f"ongoing interaction && feedback: {matched_feedback}\n"
                    )
        if matched_feedback is None or matched_feedback.feedback is None:
            # Important: The interaction_id should be unique for each human interaction.
            interaction_id = uuid.uuid4().hex if matched_feedback is None else matched_feedback.interaction.interaction_id
            # Match failed, raise an exception to go into the human interactioin process.
            raise _InteractionEventException(Interaction(
                interaction_id=interaction_id,
                event=event,
            ))
        else:
            # Match the interaction and feedback succeeded, return it.
            return matched_feedback.feedback

    def _get_and_increment_interaction_index(self, worker_key: str) -> int:
        if worker_key not in self._worker_interaction_indices:
            cur_index = 0
            self._worker_interaction_indices[worker_key] = 0
        else:
            cur_index = self._worker_interaction_indices[worker_key]
        self._worker_interaction_indices[worker_key] += 1
        return cur_index

    ###############################################################
    ######### [Bridgic Human Interaction Mechanism] ends ##########
    ###############################################################

    def get_local_space(self, runtime_context: RuntimeContext) -> Dict[str, Any]:
        """
        Retrieve the local execution context (local space) associated with the current worker. 
        If you require the local space to be cleared after the completion of `automa.arun()`, 
        you may customize this behavior by overriding the `should_reset_local_space()` method.

        Parameters
        ----------
        runtime_context : RuntimeContext
            The runtime context.

        Returns
        -------
        Dict[str, Any]
            The local space.
        """
        worker_key = runtime_context.worker_key
        worker_obj = self._get_worker_instance(worker_key)
        return worker_obj.local_space

    def should_reset_local_space(self) -> bool:
        """
        This method indicates whether to reset the local space at the end of the arun method of Automa. 
        By default, it returns True, standing for resetting. Otherwise, it means doing nothing.

        Examples:
        --------
        ```python
        class MyAutoma(Automa):
            def should_reset_local_space(self) -> bool:
                return False
        ```
        """
        return True

thread_pool property writable

thread_pool: Optional[ThreadPoolExecutor]

Get/Set the thread pool for parallel running of I/O-bound tasks used by the current Automa instance and its nested Automa instances.

Note: If an Automa is nested within another Automa, the thread pool of the top-level Automa will be used, rather than the thread pool of the nested Automa.

Returns:

Type Description
Optional[ThreadPoolExecutor]

The thread pool.

load_from_snapshot

classmethod
load_from_snapshot(
    snapshot: Snapshot,
    thread_pool: Optional[ThreadPoolExecutor] = None,
) -> Automa

Load an Automa instance from a snapshot.

Parameters:

Name Type Description Default
snapshot Snapshot

The snapshot to load the Automa instance from.

required
thread_pool Optional[ThreadPoolExecutor]

The thread pool for parallel running of I/O-bound tasks. If not provided, a default thread pool will be used.

None

Returns:

Type Description
Automa

The loaded Automa instance.

Source code in bridgic/core/automa/_automa.py
@classmethod
def load_from_snapshot(
    cls, 
    snapshot: Snapshot,
    thread_pool: Optional[ThreadPoolExecutor] = None,
) -> "Automa":
    """
    Load an Automa instance from a snapshot.

    Parameters
    ----------
    snapshot: Snapshot
        The snapshot to load the Automa instance from.
    thread_pool: Optional[ThreadPoolExecutor]
        The thread pool for parallel running of I/O-bound tasks. If not provided, a default thread pool will be used.

    Returns
    -------
    Automa
        The loaded Automa instance.
    """
    # Here you can compare snapshot.serialization_version with SERIALIZATION_VERSION, and handle any necessary version compatibility issues if needed.
    automa = load_bytes(snapshot.serialized_bytes)
    if thread_pool:
        automa.thread_pool = thread_pool
    return automa

set_running_options

set_running_options(debug: Optional[bool] = None)

Set runtime-configurable running options for this Automa instance.

This method only supports fields that can be changed at runtime. Fields that must be set during initialization (such as callback_builders) cannot be changed here and must be provided via the running_options parameter in the Automa constructor.

For fields that can be delayed to be set, some settings (like debug) from the outermost (top-level) Automa will override the settings of all inner (nested) Automa instances. For example, if the top-level Automa instance sets debug = True and the nested instances sets debug = False, then the nested Automa instance will run in debug mode when the top-level Automa instance is executed. We call it the Setting Penetration Mechanism.

Parameters:

Name Type Description Default
debug bool

Whether to enable debug mode. If None, the current value is not changed. This field is subject to the Setting Penetration Mechanism.

None
Source code in bridgic/core/automa/_automa.py
def set_running_options(
    self,
    debug: Optional[bool] = None,
):
    """
    Set runtime-configurable running options for this Automa instance.

    This method only supports fields that can be changed at runtime. Fields that must be set 
    during initialization (such as `callback_builders`) cannot be changed here and must be 
    provided via the `running_options` parameter in the Automa constructor.

    For fields that can be delayed to be set, some settings (like `debug`) from the outermost 
    (top-level) Automa will override the settings of all inner (nested) Automa instances.
    For example, if the top-level Automa instance sets `debug = True` and the nested instances 
    sets `debug = False`, then the nested Automa instance will run in debug mode when the 
    top-level Automa instance is executed. We call it the Setting Penetration Mechanism.

    Parameters
    ----------
    debug : bool, optional
        Whether to enable debug mode. If None, the current value is not changed.
        This field is subject to the Setting Penetration Mechanism.
    """
    if debug is not None:
        self._running_options.debug = debug

register_event_handler

register_event_handler(
    event_type: Optional[str],
    event_handler: EventHandlerType,
) -> None

Register an event handler for the specified event type. If event_type is set to None, the event handler will be registered as the default handler that will handle all event types.

Note: Only event handlers registered on the top-level Automa will be invoked to handle events.

Parameters:

Name Type Description Default
event_type Optional[str]

The type of event to be handled. If set to None, the event handler will be registered as the default handler and will be used to handle all event types.

required
event_handler EventHandlerType

The event handler to be registered.

required
Source code in bridgic/core/automa/_automa.py
def register_event_handler(self, event_type: Optional[str], event_handler: EventHandlerType) -> None:
    """
    Register an event handler for the specified event type. If `event_type` is set to None, the event handler will be registered as the default handler that will handle all event types.

    Note: Only event handlers registered on the top-level Automa will be invoked to handle events.

    Parameters
    ----------
    event_type: Optional[str]
        The type of event to be handled. If set to None, the event handler will be registered as the default handler and will be used to handle all event types.
    event_handler: EventHandlerType
        The event handler to be registered.
    """
    if event_type is None:
        self._default_event_handler = event_handler
    else:
        self._event_handlers[event_type] = event_handler

unregister_event_handler

unregister_event_handler(event_type: Optional[str]) -> None

Unregister an event handler for the specified event type.

Parameters:

Name Type Description Default
event_type Optional[str]

The type of event to be unregistered. If set to None, the default event handler will be unregistered.

required
Source code in bridgic/core/automa/_automa.py
def unregister_event_handler(self, event_type: Optional[str]) -> None:
    """
    Unregister an event handler for the specified event type.

    Parameters
    ----------
    event_type: Optional[str]
        The type of event to be unregistered. If set to None, the default event handler will be unregistered.
    """
    if event_type in self._event_handlers:
        del self._event_handlers[event_type]
    if event_type is None:
        self._default_event_handler = None

unregister_all_event_handlers

unregister_all_event_handlers() -> None

Unregister all event handlers.

Source code in bridgic/core/automa/_automa.py
def unregister_all_event_handlers(self) -> None:
    """
    Unregister all event handlers.
    """
    self._event_handlers.clear()
    self._default_event_handler = None

post_event

post_event(event: Event) -> None

Post an event to the application layer outside the Automa.

The event handler implemented by the application layer will be called in the same thread as the worker (maybe the main thread or a new thread from the thread pool).

Note that post_event can be called either in a non-async method or in an async method.

The event will be bubbled up to the top-level Automa, where it will be processed by the event handler registered with the event type.

Parameters:

Name Type Description Default
event Event

The event to be posted.

required
Source code in bridgic/core/automa/_automa.py
@override
def post_event(self, event: Event) -> None:
    """
    Post an event to the application layer outside the Automa.

    The event handler implemented by the application layer will be called in the same thread as the worker (maybe the main thread or a new thread from the thread pool).

    Note that `post_event` can be called either in a non-async method or in an async method.

    The event will be bubbled up to the top-level Automa, where it will be processed by the event handler registered with the event type.

    Parameters
    ----------
    event: Event
        The event to be posted.
    """
    def _handler_need_feedback_sender(handler: EventHandlerType):
        positional_param_names = get_param_names_by_kind(handler, Parameter.POSITIONAL_ONLY) + get_param_names_by_kind(handler, Parameter.POSITIONAL_OR_KEYWORD)
        var_positional_param_names = get_param_names_by_kind(handler, Parameter.VAR_POSITIONAL)
        return len(var_positional_param_names) > 0 or len(positional_param_names) > 1

    if not self.is_top_level():
        # Bubble up the event to the top-level Automa.
        return self.parent.post_event(event)

    # Here is the top-level Automa.
    # Call event handlers
    if event.event_type in self._event_handlers:
        if _handler_need_feedback_sender(self._event_handlers[event.event_type]):
            self._event_handlers[event.event_type](event, feedback_sender=None)
        else:
            self._event_handlers[event.event_type](event)
    if self._default_event_handler is not None:
        if _handler_need_feedback_sender(self._default_event_handler):
            self._default_event_handler(event, feedback_sender=None)
        else:
            self._default_event_handler(event)

request_feedback

request_feedback(
    event: Event, timeout: Optional[float] = None
) -> Feedback

Request feedback for the specified event from the application layer outside the Automa. This method blocks the caller until the feedback is received.

Note that request_feedback should only be called from within a non-async method running in a new thread of the Automa thread pool.

Parameters:

Name Type Description Default
event Event

The event to be posted to the event handler implemented by the application layer.

required
timeout Optional[float]

A float or int number of seconds to wait for if the feedback is not received. If None, then there is no limit on the wait time.

None

Returns:

Type Description
Feedback

The feedback received from the application layer.

Raises:

Type Description
TimeoutError

If the feedback is not received before the timeout. Note that the raised exception is the built-in TimeoutError exception, instead of asyncio.TimeoutError or concurrent.futures.TimeoutError!

Source code in bridgic/core/automa/_automa.py
def request_feedback(
    self, 
    event: Event,
    timeout: Optional[float] = None
) -> Feedback:
    """
    Request feedback for the specified event from the application layer outside the Automa. This method blocks the caller until the feedback is received.

    Note that `request_feedback` should only be called from within a non-async method running in a new thread of the Automa thread pool.

    Parameters
    ----------
    event: Event
        The event to be posted to the event handler implemented by the application layer.
    timeout: Optional[float]
        A float or int number of seconds to wait for if the feedback is not received. If None, then there is no limit on the wait time.

    Returns
    -------
    Feedback
        The feedback received from the application layer.

    Raises
    ------
    TimeoutError
        If the feedback is not received before the timeout. Note that the raised exception is the built-in `TimeoutError` exception, instead of asyncio.TimeoutError or concurrent.futures.TimeoutError!
    """
    if threading.get_ident() == self._main_thread_id:
        raise AutomaRuntimeError(
            f"`request_feedback` should only be called in a different thread from the main thread of the {self.name}. "
        )
    return asyncio.run_coroutine_threadsafe(
        self.request_feedback_async(event, timeout),
        self._main_loop
    ).result()

request_feedback_async

async
request_feedback_async(
    event: Event, timeout: Optional[float] = None
) -> Feedback

Request feedback for the specified event from the application layer outside the Automa. This method blocks the caller until the feedback is received.

The event handler implemented by the application layer will be called in the next event loop iteration, in the main thread.

Parameters:

Name Type Description Default
event Event

The event to be posted to the event handler implemented by the application layer.

required
timeout Optional[float]

A float or int number of seconds to wait for if the feedback is not received. If None, then there is no limit on the wait time.

None

Returns:

Type Description
Feedback

The feedback received from the application layer.

Raises:

Type Description
TimeoutError

If the feedback is not received before the timeout. Note that the raised exception is the built-in TimeoutError exception, instead of asyncio.TimeoutError!

Source code in bridgic/core/automa/_automa.py
async def request_feedback_async(
    self, 
    event: Event,
    timeout: Optional[float] = None
) -> Feedback:
    """
    Request feedback for the specified event from the application layer outside the Automa. This method blocks the caller until the feedback is received.

    The event handler implemented by the application layer will be called in the next event loop iteration, in the main thread.

    Parameters
    ----------
    event: Event
        The event to be posted to the event handler implemented by the application layer.
    timeout: Optional[float]
        A float or int number of seconds to wait for if the feedback is not received. If None, then there is no limit on the wait time.

    Returns
    -------
    Feedback
        The feedback received from the application layer.

    Raises
    ------
    TimeoutError
        If the feedback is not received before the timeout. Note that the raised exception is the built-in `TimeoutError` exception, instead of asyncio.TimeoutError!
    """
    if not self.is_top_level():
        # Bubble up the event to the top-level Automa.
        return await self.parent.request_feedback_async(event, timeout)

    # Here is the top-level Automa.
    event_loop = asyncio.get_running_loop()
    future = event_loop.create_future()
    feedback_sender = self._FeedbackSender(future, event_loop)
    # Call event handlers
    if event.event_type in self._event_handlers:
        self._event_handlers[event.event_type](event, feedback_sender)
    if self._default_event_handler is not None:
        self._default_event_handler(event, feedback_sender)

    try:
        return await asyncio.wait_for(future, timeout)
    except TimeoutError as e:
        # When python >= 3.11 here.
        raise TimeoutError(f"No feedback is received before timeout in Automa[{self.name}]") from e
    except asyncio.TimeoutError as e:
        # Version compatibility resolution: asyncio.wait_for raises asyncio.TimeoutError before python 3.11.
        # https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for
        raise TimeoutError(f"No feedback is received before timeout in Automa[{self.name}]") from e

interact_with_human

interact_with_human(
    event: Event,
    interacting_worker: Optional[Worker] = None,
) -> InteractionFeedback

Trigger an interruption in the "human-in-the-loop interaction" during the execution of the Automa.

Parameters:

Name Type Description Default
event Event

The event that triggered the interaction.

required
interacting_worker Optional[Worker]

The worker instance that is currently interacting with human. If not provided, the worker will be located automatically.

None

Returns:

Type Description
InteractionFeedback

The feedback received from the application layer.

Source code in bridgic/core/automa/_automa.py
def interact_with_human(
    self,
    event: Event,
    interacting_worker: Optional[Worker] = None,
) -> InteractionFeedback:
    """
    Trigger an interruption in the "human-in-the-loop interaction" during the execution of the Automa.

    Parameters
    ----------
    event: Event
        The event that triggered the interaction.
    interacting_worker: Optional[Worker]
        The worker instance that is currently interacting with human. If not provided, the worker will be located automatically.

    Returns
    -------
    InteractionFeedback
        The feedback received from the application layer.
    """
    if not interacting_worker:
        kickoff_worker_key: str = self._locate_interacting_worker()
    else:
        kickoff_worker_key = self._get_worker_key(interacting_worker)

    if kickoff_worker_key:
        return self.interact_with_human_from_worker_key(event, kickoff_worker_key)
    raise AutomaRuntimeError(
        f"Get kickoff worker failed in Automa[{self.name}] "
        f"when trying to interact with human with event: {event}"
    )

get_local_space

get_local_space(
    runtime_context: RuntimeContext,
) -> Dict[str, Any]

Retrieve the local execution context (local space) associated with the current worker. If you require the local space to be cleared after the completion of automa.arun(), you may customize this behavior by overriding the should_reset_local_space() method.

Parameters:

Name Type Description Default
runtime_context RuntimeContext

The runtime context.

required

Returns:

Type Description
Dict[str, Any]

The local space.

Source code in bridgic/core/automa/_automa.py
def get_local_space(self, runtime_context: RuntimeContext) -> Dict[str, Any]:
    """
    Retrieve the local execution context (local space) associated with the current worker. 
    If you require the local space to be cleared after the completion of `automa.arun()`, 
    you may customize this behavior by overriding the `should_reset_local_space()` method.

    Parameters
    ----------
    runtime_context : RuntimeContext
        The runtime context.

    Returns
    -------
    Dict[str, Any]
        The local space.
    """
    worker_key = runtime_context.worker_key
    worker_obj = self._get_worker_instance(worker_key)
    return worker_obj.local_space

should_reset_local_space

should_reset_local_space() -> bool

This method indicates whether to reset the local space at the end of the arun method of Automa. By default, it returns True, standing for resetting. Otherwise, it means doing nothing.

Examples:
1
2
3
class MyAutoma(Automa):
    def should_reset_local_space(self) -> bool:
        return False
Source code in bridgic/core/automa/_automa.py
def should_reset_local_space(self) -> bool:
    """
    This method indicates whether to reset the local space at the end of the arun method of Automa. 
    By default, it returns True, standing for resetting. Otherwise, it means doing nothing.

    Examples:
    --------
    ```python
    class MyAutoma(Automa):
        def should_reset_local_space(self) -> bool:
            return False
    ```
    """
    return True

Snapshot

Bases: BaseModel

A snapshot that represents the current state of an Automa. It is used when an Automa resumes after a human interaction.

Source code in bridgic/core/automa/_automa.py
class Snapshot(BaseModel):
    """
    A snapshot that represents the current state of an Automa. It is used when an Automa resumes after a human interaction.
    """
    serialized_bytes: bytes
    """
    The serialized bytes that represents the snapshot of the Automa.
    """
    serialization_version: str
    """
    The serialization version.
    """

serialized_bytes instance-attribute

serialized_bytes: bytes

The serialized bytes that represents the snapshot of the Automa.

serialization_version instance-attribute

serialization_version: str

The serialization version.

RunningOptions

Bases: BaseModel

Running options for an Automa instance.

This class contains two types of fields:

  1. Runtime-configurable fields: Can be set at any time via set_running_options().
  2. debug: Whether to enable debug mode.

  3. Initialization-only fields: Must be set during Automa instantiation via the running_options parameter.

  4. callback_builders: Callback builders at the Automa instance level. These will be merged with global callback builders when workers are created during Automa initialization.
Source code in bridgic/core/automa/_automa.py
class RunningOptions(BaseModel):
    """
    Running options for an Automa instance.

    This class contains two types of fields:

    1. **Runtime-configurable fields**: Can be set at any time via `set_running_options()`.
       - `debug`: Whether to enable debug mode.

    2. **Initialization-only fields**: Must be set during Automa instantiation via the `running_options` parameter.
       - `callback_builders`: Callback builders at the Automa instance level. These will be merged with 
         global callback builders when workers are created during Automa initialization.
    """
    debug: bool = False
    """Whether to enable debug mode. Can be set at runtime via set_running_options()."""

    callback_builders: List[WorkerCallbackBuilder] = []
    """A list of callback builders specific to this Automa instance."""

    model_config = {"arbitrary_types_allowed": True}

debug class-attribute instance-attribute

debug: bool = False

Whether to enable debug mode. Can be set at runtime via set_running_options().

callback_builders class-attribute instance-attribute

callback_builders: List[WorkerCallbackBuilder] = []

A list of callback builders specific to this Automa instance.

GraphAutoma

Bases: Automa

Dynamic Directed Graph (abbreviated as DDG) implementation of Automa. GraphAutoma manages the running control flow between workers automatically, via dependencies and ferry_to. Outputs of workers can be mapped and passed to their successor workers in the runtime, following args_mapping_rule and result_dispatching_rule.

Parameters:

Name Type Description Default
name Optional[str]

The name of the automa.

None
thread_pool Optional[ThreadPoolExecutor]

The thread pool for parallel running of I/O-bound tasks.

  • If not provided, a default thread pool will be used. The maximum number of threads in the default thread pool dependends on the number of CPU cores. Please refer to the ThreadPoolExecutor for detail.

  • If provided, all workers (including all nested Automa instances) will be run in it. In this case, the application layer code is responsible to create it and shut it down.

None

Examples:

The following example shows how to use GraphAutoma to create a simple graph automa that prints "Hello, Bridgic".

import asyncio
from bridgic.core.automa import GraphAutoma, worker, ArgsMappingRule

class MyGraphAutoma(GraphAutoma):
    @worker(is_start=True)
    async def greet(self) -> list[str]:
        return ["Hello", "Bridgic"]

    @worker(dependencies=["greet"], args_mapping_rule=ArgsMappingRule.AS_IS, result_dispatching_rule=ResultDispatchingRule.AS_IS, is_output=True)
    async def output(self, message: list[str]):
        print("Echo: " + " ".join(message))

async def main():
    automa_obj = MyGraphAutoma(name="my_graph_automa")
    await automa_obj.arun()

asyncio.run(main())
Source code in bridgic/core/automa/_graph_automa.py
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 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
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 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
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 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
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
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
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
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
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
class GraphAutoma(Automa, metaclass=GraphMeta):
    """
    Dynamic Directed Graph (abbreviated as DDG) implementation of Automa. `GraphAutoma` manages 
    the running control flow between workers automatically, via `dependencies` and `ferry_to`.
    Outputs of workers can be mapped and passed to their successor workers in the runtime, 
    following `args_mapping_rule` and `result_dispatching_rule`.

    Parameters
    ----------
    name : Optional[str]
        The name of the automa.

    thread_pool : Optional[ThreadPoolExecutor]
        The thread pool for parallel running of I/O-bound tasks.

        - If not provided, a default thread pool will be used.
        The maximum number of threads in the default thread pool dependends on the number of CPU cores. Please refer to 
        the [ThreadPoolExecutor](https://docs.python.org/3/library/concurrent.futures.html#threadpoolexecutor) for detail.

        - If provided, all workers (including all nested Automa instances) will be run in it. In this case, the 
        application layer code is responsible to create it and shut it down.

    Examples
    --------

    The following example shows how to use `GraphAutoma` to create a simple graph automa that prints "Hello, Bridgic".

    ```python
    import asyncio
    from bridgic.core.automa import GraphAutoma, worker, ArgsMappingRule

    class MyGraphAutoma(GraphAutoma):
        @worker(is_start=True)
        async def greet(self) -> list[str]:
            return ["Hello", "Bridgic"]

        @worker(dependencies=["greet"], args_mapping_rule=ArgsMappingRule.AS_IS, result_dispatching_rule=ResultDispatchingRule.AS_IS, is_output=True)
        async def output(self, message: list[str]):
            print("Echo: " + " ".join(message))

    async def main():
        automa_obj = MyGraphAutoma(name="my_graph_automa")
        await automa_obj.arun()

    asyncio.run(main())
    ```
    """

    # Automa type.
    AUTOMA_TYPE: ClassVar[AutomaType] = AutomaType.Graph

    # The initial topology defined by @worker functions.
    _registered_worker_funcs: ClassVar[Dict[str, Callable]] = {}

    # IMPORTANT: The entire states of a GraphAutoma instance include 2 part:
    # 
    # Part-1 (for the states of topology structure):
    #   1. Inner worker instances: self._workers
    #   2. Relations between worker: self._worker_forwards
    #   3. Dynamic states that serve as trigger of execution of workers: self._workers_dynamic_states
    #   4. Execution result of inner workers: self._worker_output
    #   5. Configurations of this automa instance: self._output_worker_key
    # 
    # Part-2 (for the states of running states):
    #   1. Records of Workers that are going to be kicked off: self._current_kickoff_workers
    #   2. Records of running or deferred tasks:
    #      - self._running_tasks
    #      - self._topology_change_deferred_tasks
    #      - self._ferry_deferred_tasks
    #      - self._set_output_worker_deferred_task
    #   3. Buffers of automa inputs: self._input_buffer
    #   4. Ongoing human interactions: self._ongoing_interactions
    #   ...

    _workers: Dict[str, _GraphAdaptedWorker]
    _worker_output: Dict[str, Any]
    _worker_forwards: Dict[str, List[str]]

    _current_kickoff_workers: List[_KickoffInfo]
    _input_buffer: _AutomaInputBuffer
    _workers_dynamic_states: Dict[str, _WorkerDynamicState]

    # The whole running process of the DDG is divided into two main phases:
    # 1. [Initialization Phase] The first phase (when _automa_running is False): the initial topology of DDG was constructed.
    # 2. [Running Phase] The second phase (when _automa_running is True): the DDG is running, and the workers are executed in a dynamic step-by-step manner (DS loop).
    _automa_running: bool

    #########################################################
    #### The following fields need not to be serialized. ####
    #########################################################
    _running_tasks: List[_RunnningTask]

    # TODO: The following deferred task structures need to be thread-safe.
    # TODO: Need to be refactored when parallelization features are added.
    _topology_change_deferred_tasks: List[Union[_AddWorkerDeferredTask, _RemoveWorkerDeferredTask]]
    _ferry_deferred_tasks: List[_FerryDeferredTask]

    def __init__(
        self,
        name: Optional[str] = None,
        thread_pool: Optional[ThreadPoolExecutor] = None,
        running_options: Optional[RunningOptions] = None,
    ):
        """
        Parameters
        ----------
        name : Optional[str]
            The name of the automa.

        thread_pool : Optional[ThreadPoolExecutor]
            The thread pool for parallel running of I/O-bound tasks.

            - If not provided, a default thread pool will be used.
            The maximum number of threads in the default thread pool dependends on the number of CPU cores. Please refer to 
            the [ThreadPoolExecutor](https://docs.python.org/3/library/concurrent.futures.html#threadpoolexecutor) for detail.

            - If provided, all workers (including all nested Automa instances) will be run in it. In this case, the 
            application layer code is responsible to create it and shut it down.

        running_options : Optional[RunningOptions]
            Running options for this Automa instance, including callback_builders.
            If None, uses default RunningOptions.

        state_dict : Optional[Dict[str, Any]]
            A dictionary for initializing the automa's runtime states. This parameter is designed for framework use only.
        """
        super().__init__(name=name, thread_pool=thread_pool, running_options=running_options)

        self._workers = {}
        self._worker_outputs = {}
        self._automa_running = False

        # Initialize the states that need to be serialized.
        self._normal_init()

        # The list of the tasks that are currently being executed.
        self._running_tasks = []
        # deferred tasks
        self._topology_change_deferred_tasks = []
        self._ferry_deferred_tasks = []

    def _normal_init(self):
        ###############################################################################
        # Initialization of [Part One: Topology-Related Runtime States] #### Strat ####
        ###############################################################################

        cls = type(self)

        # _workers, _worker_forwards and _workers_dynamic_states will be initialized incrementally by add_worker()...
        self._worker_forwards = {}
        self._worker_output = {}
        self._workers_dynamic_states = {}

        if cls.AUTOMA_TYPE == AutomaType.Graph:
            # The _registered_worker_funcs data are from @worker decorators.
            for worker_key, worker_func in cls._registered_worker_funcs.items():
                # The decorator based mechanism (i.e. @worker) is based on the add_worker() interface.
                # Parameters check and other implementation details can be unified.
                self._add_func_as_worker_internal(
                    key=worker_key,
                    func=worker_func,
                    dependencies=worker_func.__dependencies__,
                    is_start=worker_func.__is_start__,
                    is_output=worker_func.__is_output__,
                    args_mapping_rule=worker_func.__args_mapping_rule__,
                    result_dispatching_rule=worker_func.__result_dispatching_rule__,
                    callback_builders=worker_func.__callback_builders__,
                )

        ###############################################################################
        # Initialization of [Part One: Topology-Related Runtime States] ##### End #####
        ###############################################################################

        ###############################################################################
        # Initialization of [Part Two: Task-Related Runtime States] ###### Strat ######
        ###############################################################################

        # -- Current kickoff workers list.
        # The key list of the workers that are ready to be immediately executed in the next DS (Dynamic Step). It will be lazily initialized in _compile_graph_and_detect_risks().
        self._current_kickoff_workers = []
        # -- Automa input buffer.
        self._input_buffer = _AutomaInputBuffer()

        ###############################################################################
        # Initialization of [Part Two: Task-Related Runtime States] ####### End #######
        ###############################################################################

    ###############################################################
    ########## [Bridgic Serialization Mechanism] starts ###########
    ###############################################################

    # The version of the serialization format.
    SERIALIZATION_VERSION: str = "1.0"

    @override
    def dump_to_dict(self) -> Dict[str, Any]:
        state_dict = super().dump_to_dict()

        state_dict["name"] = self.name
        state_dict["automa_running"] = self._automa_running

        # States related to workers.
        state_dict["workers"] = self._workers
        state_dict["worker_forwards"] = self._worker_forwards
        state_dict["workers_dynamic_states"] = self._workers_dynamic_states
        state_dict["worker_output"] = self._worker_output

        # States related to interruption recovery.
        state_dict["current_kickoff_workers"] = self._current_kickoff_workers
        state_dict["input_buffer"] = self._input_buffer

        return state_dict

    @override
    def load_from_dict(self, state_dict: Dict[str, Any]) -> None:
        super().load_from_dict(state_dict)

        self.name = state_dict["name"]
        self._automa_running = state_dict["automa_running"]

        # States related to workers.
        self._workers = state_dict["workers"]
        for worker in self._workers.values():
            worker.parent = self
        self._worker_forwards = state_dict["worker_forwards"]
        self._workers_dynamic_states = state_dict["workers_dynamic_states"]
        self._worker_output = state_dict["worker_output"]

        # States related to interruption recovery.
        self._current_kickoff_workers = state_dict["current_kickoff_workers"]
        self._input_buffer = state_dict["input_buffer"]

        # The list of the tasks that are currently being executed.
        self._running_tasks = []
        # Deferred tasks
        self._topology_change_deferred_tasks = []
        self._set_output_worker_deferred_task = None
        self._ferry_deferred_tasks = []

    ###############################################################
    ########### [Bridgic Serialization Mechanism] ends ############
    ###############################################################

    def _add_worker_incrementally(
        self,
        key: str,
        worker: Worker,
        *,
        dependencies: List[str] = [],
        is_start: bool = False,
        is_output: bool = False,
        args_mapping_rule: ArgsMappingRule = ArgsMappingRule.AS_IS,
        result_dispatching_rule: ResultDispatchingRule = ResultDispatchingRule.AS_IS,
        callback_builders: List[WorkerCallbackBuilder] = [],
    ) -> None:
        """
        Incrementally add a worker into the automa. For internal use only.
        This method is one of the very basic primitives of DDG for dynamic topology changes. 
        """
        if key in self._workers:
            raise AutomaRuntimeError(
                f"duplicate workers with the same key '{key}' are not allowed to be added!"
            )

        # Merge callback builders: Global -> Ancestor Automa(s) -> Current Automa -> Nested Automa (if worker is automa) -> Worker
        effective_callback_builders = []
        effective_callback_builders.extend(GlobalSetting.read().callback_builders)
        # Collect callback builders from all ancestor automas in the ancestor chain (from top-level to current)
        effective_callback_builders.extend(self._collect_ancestor_callback_builders())
        # If the worker itself is an automa, include its own RunningOptions callback builders
        if isinstance(worker, Automa):
            effective_callback_builders.extend(worker._running_options.callback_builders)
        # Include the callback builders from the worker itself.
        effective_callback_builders.extend(callback_builders)

        # Note: the dependencies argument must be a new copy of the list, created with list(dependencies).
        # Refer to the Python documentation for more details:
        # 1. https://docs.python.org/3/reference/compound_stmts.html#function-definitions
        # "Default parameter values are evaluated from left to right when the function definition is executed"
        # 2. https://docs.python.org/3/tutorial/controlflow.html#default-argument-values
        # "The default values are evaluated at the point of function definition in the defining scope"
        # "Important warning: The default value is evaluated only once."
        new_worker_obj = _GraphAdaptedWorker(
            key=key,
            worker=worker,
            dependencies=list(dependencies),
            is_start=is_start,
            is_output=is_output,
            args_mapping_rule=args_mapping_rule,
            result_dispatching_rule=result_dispatching_rule,
            callback_builders=effective_callback_builders,
        )

        # Register the worker_obj.
        new_worker_obj.parent = self
        self._workers[new_worker_obj.key] = new_worker_obj

        # Incrementally update the dynamic states of added workers.
        self._workers_dynamic_states[key] = _WorkerDynamicState(
            dependency_triggers=set(dependencies)
        )

        # Incrementally update the forwards table.
        for trigger in dependencies:
            if trigger not in self._worker_forwards:
                self._worker_forwards[trigger] = []
            self._worker_forwards[trigger].append(key)

        # If the added worker is an automa, recursively propagate callbacks to inner workers.
        if new_worker_obj.is_automa():
            nested_automa = new_worker_obj.get_decorated_worker()
            if isinstance(nested_automa, GraphAutoma):
                # Collect callback builders from all ancestor automas in the ancestor chain (from top-level to current)
                ancestor_callback_builders = self._collect_ancestor_callback_builders()
                # Append ancestor callbacks to the _cached_callbacks of the nested automa instance.
                nested_automa._cached_callbacks = nested_automa._get_automa_callbacks() + [cb.build() for cb in ancestor_callback_builders]
                # Recursively propagate ancestor callbacks to inner workers.
                self._propagate_callbacks_to_nested_automa(
                    nested_automa=nested_automa,
                    callback_builders=ancestor_callback_builders,
                )

    def _propagate_callbacks_to_nested_automa(
        self,
        nested_automa: "GraphAutoma",
        callback_builders: List[WorkerCallbackBuilder],
    ) -> None:
        """
        Recursively propagate callback builders to all workers in a nested automa.

        This method ensures that callbacks from all ancestor automas in the ancestor chain
        are applied to all workers in nested automa instances, including deeply nested ones.

        Parameters
        ----------
        nested_automa : GraphAutoma
            The nested automa instance to propagate callbacks to.
        callback_builders : List[WorkerCallbackBuilder]
            The callback builders from all ancestor automas in the ancestor chain 
            (from top-level to current) to propagate.
        """
        for worker_key in nested_automa.all_workers():
            nested_worker = nested_automa._workers[worker_key]

            # Add callback instances built from all ancestor automas' callback builders in the ancestor chain.
            new_callbacks = [cb.build() for cb in callback_builders]
            nested_worker._worker_callbacks += new_callbacks

            # Check if the nested worker is also an automa, and recursively propagate.
            if nested_worker.is_automa():
                deeper_nested_automa = nested_worker.get_decorated_worker()
                if isinstance(deeper_nested_automa, GraphAutoma):
                    # Recursively propagate to deeper nested automas.
                    # Include current nested automa's callbacks in the propagation chain,
                    # so that deeper nested workers get callbacks from all ancestor automas.
                    self._propagate_callbacks_to_nested_automa(
                        nested_automa=deeper_nested_automa,
                        callback_builders=callback_builders,
                    )

    def _remove_worker_incrementally(
        self,
        key: str
    ) -> None:
        """
        Incrementally remove a worker from the automa. For internal use only.
        This method is one of the very basic primitives of DDG for dynamic topology changes.
        """
        if key not in self._workers:
            raise AutomaRuntimeError(
                f"fail to remove worker '{key}' that does not exist!"
            )

        worker_to_remove = self._workers[key]

        # Remove the worker.
        del self._workers[key]
        # Incrementally update the dynamic states of removed workers.
        del self._workers_dynamic_states[key]

        if key in self._worker_forwards:
            # Update the dependencies of the successor workers, if needed.
            for successor in self._worker_forwards[key]:
                self._workers[successor].dependencies.remove(key)
                # Note this detail here: use discard() instead of remove() to avoid KeyError.
                # This case occurs when a worker call remove_worker() to remove its predecessor worker.
                self._workers_dynamic_states[successor].dependency_triggers.discard(key)
            # Incrementally update the forwards table.
            del self._worker_forwards[key]

        # Remove from the forwards list of all dependencies worker.
        for trigger in worker_to_remove.dependencies:
            self._worker_forwards[trigger].remove(key)
        if key in self._worker_interaction_indices:
            del self._worker_interaction_indices[key]
        if key in self._ongoing_interactions:
            del self._ongoing_interactions[key]

    def _add_dependency_incrementally(
        self,
        key: str,
        dependency: str,
    ) -> None:
        """
        Incrementally add a dependency from `key` to `depends`. For internal use only.
        This method is one of the very basic primitives of DDG for dynamic topology changes.
        """
        if key not in self._workers:
            raise AutomaRuntimeError(
                f"fail to add dependency from a worker that does not exist: `{key}`!"
            )
        if dependency not in self._workers:
            raise AutomaRuntimeError(
                f"fail to add dependency to a worker that does not exist: `{dependency}`!"
            )
        if dependency in self._workers[key].dependencies:
            raise AutomaRuntimeError(
                f"dependency from '{key}' to '{dependency}' already exists!"
            )

        self._workers[key].dependencies.append(dependency)
        # Note this detail here for dynamic states change:
        # The new dependency added here may be removed right away if the dependency is just the next kickoff worker. This is a valid behavior.
        self._workers_dynamic_states[key].dependency_triggers.add(dependency)

        if dependency not in self._worker_forwards:
            self._worker_forwards[dependency] = []
        self._worker_forwards[dependency].append(key)

    def _add_worker_internal(
        self,
        key: str,
        worker: Worker,
        *,
        dependencies: List[str] = [],
        is_start: bool = False,
        is_output: bool = False,
        args_mapping_rule: ArgsMappingRule = ArgsMappingRule.AS_IS,
        result_dispatching_rule: ResultDispatchingRule = ResultDispatchingRule.AS_IS,
        callback_builders: List[WorkerCallbackBuilder] = [],
    ) -> None:
        """
        The private version of the method `add_worker()`.
        """

        def _basic_worker_params_check(key: str, worker_obj: Worker):
            if not isinstance(worker_obj, Worker):
                raise TypeError(
                    f"worker_obj to be registered must be a Worker, "
                    f"but got {type(worker_obj)} for worker '{key}'"
                )

            if not asyncio.iscoroutinefunction(worker_obj.arun):
                raise WorkerSignatureError(
                    f"arun of Worker must be an async method, "
                    f"but got {type(worker_obj.arun)} for worker '{key}'"
                )

            if not isinstance(dependencies, list):
                raise TypeError(
                    f"dependencies must be a list, "
                    f"but got {type(dependencies)} for worker '{key}'"
                )
            if not all([isinstance(d, str) for d in dependencies]):
                raise ValueError(
                    f"dependencies must be a List of str, "
                    f"but got {dependencies} for worker {key}"
                )

            if args_mapping_rule not in ArgsMappingRule:
                raise ValueError(
                    f"args_mapping_rule must be one of the following: {[e for e in ArgsMappingRule]}, "
                    f"but got {args_mapping_rule} for worker {key}"
                )

            if result_dispatching_rule not in ResultDispatchingRule:
                raise ValueError(
                    f"result_dispatching_rule must be one of the following: {[e for e in ResultDispatchingRule]}, "
                    f"but got {result_dispatching_rule} for worker {key}"
                )

        # Ensure the parameters are valid.
        _basic_worker_params_check(key, worker)

        if not self._automa_running:
            # Add worker during the [Initialization Phase].
            self._add_worker_incrementally(
                key=key,
                worker=worker,
                dependencies=dependencies,
                is_start=is_start,
                is_output=is_output,
                args_mapping_rule=args_mapping_rule,
                result_dispatching_rule=result_dispatching_rule,
                callback_builders=callback_builders,
            )
        else:
            # Add worker during the [Running Phase].
            deferred_task = _AddWorkerDeferredTask(
                worker_key=key,
                worker_obj=worker,
                dependencies=dependencies,
                is_start=is_start,
                is_output=is_output,
                args_mapping_rule=args_mapping_rule,
                result_dispatching_rule=result_dispatching_rule,
                callback_builders=callback_builders,
            )
            # Note1: the execution order of topology change deferred tasks is important and is determined by the order of the calls of add_worker(), remove_worker() and add_dependency() in one DS.
            # Note2: add_worker() and remove_worker() may be called in a new thread. But _topology_change_deferred_tasks is not necessary to be thread-safe due to Visibility Guarantees of the Bridgic Concurrency Model.
            self._topology_change_deferred_tasks.append(deferred_task)

    def _add_func_as_worker_internal(
        self,
        key: str,
        func: Callable,
        *,
        dependencies: List[str] = [],
        is_start: bool = False,
        is_output: bool = False,
        args_mapping_rule: ArgsMappingRule = ArgsMappingRule.AS_IS,
        result_dispatching_rule: ResultDispatchingRule = ResultDispatchingRule.AS_IS,
        callback_builders: List[WorkerCallbackBuilder] = [],
    ) -> None:
        """
        The private version of the method `add_func_as_worker()`.
        """
        if not isinstance(func, MethodType) and key in self._registered_worker_funcs:
            func = MethodType(func, self)

        # Validate: if func is a method, its bounded __self__ must be self when add_func_as_worker() is called.
        if hasattr(func, "__self__") and func.__self__ is not self:
            raise AutomaRuntimeError(
                f"the bounded instance of `func` must be the same as the instance of the GraphAutoma, "
                f"but got {func.__self__}"
            )

        # Register func as an instance of CallableWorker.
        func_worker = CallableWorker(func)

        self._add_worker_internal(
            key=key,
            worker=func_worker,
            dependencies=dependencies,
            is_start=is_start,
            is_output=is_output,
            args_mapping_rule=args_mapping_rule,
            result_dispatching_rule=result_dispatching_rule,
            callback_builders=callback_builders,
        )

    def all_workers(self) -> List[str]:
        """
        Gets a list containing the keys of all workers registered in this Automa.

        Returns
        -------
        List[str]
            A list of worker keys.
        """
        return list(self._workers.keys())

    def add_worker(
        self,
        key: str,
        worker: Worker,
        *,
        dependencies: List[str] = [],
        is_start: bool = False,
        is_output: bool = False,
        args_mapping_rule: ArgsMappingRule = ArgsMappingRule.AS_IS,
        result_dispatching_rule: ResultDispatchingRule = ResultDispatchingRule.AS_IS,
        callback_builders: List[WorkerCallbackBuilder] = [],
    ) -> None:
        """
        This method is used to add a worker dynamically into the automa.

        If this method is called during the [Initialization Phase], the worker will be added immediately. If this method is called during the [Running Phase], the worker will be added as a deferred task which will be executed in the next DS.

        The dependencies can be added together with a worker. However, you can add a worker without any dependencies.

        Note: args_mapping_rule and result_dispatching_rule could only be set when using worker-adding API. Even if the worker has no any dependencies.

        Parameters
        ----------
        key : str
            The key of the worker.
        worker : Worker
            The worker instance to be registered.
        dependencies : List[str]
            A list of worker keys that the worker depends on.
        is_start : bool
            Whether the worker is a start worker.
        is_output : bool
            Whether the worker is an output worker.
        args_mapping_rule : ArgsMappingRule
            The rule of arguments mapping.
        result_dispatching_rule : ResultDispatchingRule
            The rule of result dispatch.
        callback_builders : List[WorkerCallbackBuilder]
            A list of worker callback builders to be registered.
            Callback instances will be created from builders when the worker is instantiated.
        """
        self._add_worker_internal(
            key=key,
            worker=worker,
            dependencies=dependencies,
            is_start=is_start,
            is_output=is_output,
            args_mapping_rule=args_mapping_rule,
            result_dispatching_rule=result_dispatching_rule,
            callback_builders=callback_builders,
        )

    def add_func_as_worker(
        self,
        key: str,
        func: Callable,
        *,
        dependencies: List[str] = [],
        is_start: bool = False,
        is_output: bool = False,
        args_mapping_rule: ArgsMappingRule = ArgsMappingRule.AS_IS,
        result_dispatching_rule: ResultDispatchingRule = ResultDispatchingRule.AS_IS,
        callback_builders: List[WorkerCallbackBuilder] = [],
    ) -> None:
        """
        This method is used to add a function as a worker into the automa.

        The format of the parameters will follow that of the decorator @worker(...), so that the 
        behavior of the decorated function is consistent with that of normal CallableLandableWorker objects.

        Parameters
        ----------
        key : str
            The key of the function worker.
        func : Callable
            The function to be added as a worker to the automa.
        dependencies : List[str]
            A list of worker names that the decorated callable depends on.
        is_start : bool
            Whether the decorated callable is a start worker. True means it is, while False means it is not.
        is_output : bool
            Whether the decorated callable is an output worker. True means it is, while False means it is not.
        args_mapping_rule : ArgsMappingRule
            The rule of arguments mapping.
        result_dispatching_rule : ResultDispatchingRule
            The rule of result dispatch.
        callback_builders : List[WorkerCallbackBuilder]
            A list of worker callback builders to be registered.
            Callback instances will be created from builders when the worker is instantiated.
        """
        self._add_func_as_worker_internal(
            key=key,
            func=func,
            dependencies=dependencies,
            is_start=is_start,
            is_output=is_output,
            args_mapping_rule=args_mapping_rule,
            result_dispatching_rule=result_dispatching_rule,
            callback_builders=callback_builders,
        )

    def worker(
        self,
        *,
        key: Optional[str] = None,
        dependencies: List[str] = [],
        is_start: bool = False,
        is_output: bool = False,
        args_mapping_rule: ArgsMappingRule = ArgsMappingRule.AS_IS,
        result_dispatching_rule: ResultDispatchingRule = ResultDispatchingRule.AS_IS,
        callback_builders: List[WorkerCallbackBuilder] = [],
    ) -> Callable:
        """
        This is a decorator used to mark a function as an GraphAutoma detectable Worker. Dislike the 
        global decorator @worker(...), it is usally used after an GraphAutoma instance is initialized.

        The format of the parameters will follow that of the decorator @worker(...), so that the 
        behavior of the decorated function is consistent with that of normal CallableLandableWorker objects.

        Parameters
        ----------
        key : str
            The key of the worker. If not provided, the name of the decorated callable will be used.
        dependencies : List[str]
            A list of worker names that the decorated callable depends on.
        is_start : bool
            Whether the decorated callable is a start worker. True means it is, while False means it is not.
        is_output : bool
            Whether the decorated callable is an output worker. True means it is, while False means it is not.
        args_mapping_rule : str
            The rule of arguments mapping. The options are: "auto", "as_list", "as_dict", "suppressed".
        result_dispatching_rule : ResultDispatchingRule
            The rule of result dispatch.
        callback_builders : List[WorkerCallbackBuilder]
            A list of worker callback builders to be registered.
            Callback instances will be created from builders when the worker is instantiated.
        """
        def wrapper(func: Callable):
            self._add_func_as_worker_internal(
                key=(key or func.__name__),
                func=func,
                dependencies=dependencies,
                is_start=is_start,
                is_output=is_output,
                args_mapping_rule=args_mapping_rule,
                result_dispatching_rule=result_dispatching_rule,
                callback_builders=callback_builders,
            )

        return wrapper

    def remove_worker(self, key: str) -> None:
        """
        Remove a worker from the Automa. This method can be called at any time to remove a worker from the Automa.

        When a worker is removed, all dependencies related to this worker, including all the dependencies of the worker itself and the dependencies between the worker and its successor workers, will be also removed.

        Parameters
        ----------
        key : str
            The key of the worker to be removed.

        Returns
        -------
        None

        Raises
        ------
        AutomaDeclarationError
            If the worker specified by key does not exist in the Automa, this exception will be raised.
        """
        if not self._automa_running:
            # remove immediately
            self._remove_worker_incrementally(key)
        else:
            deferred_task = _RemoveWorkerDeferredTask(
                worker_key=key,
            )
            # Note: the execution order of topology change deferred tasks is important and is determined by the order of the calls of add_worker(), remove_worker() and add_dependency() in one DS.
            self._topology_change_deferred_tasks.append(deferred_task)

    def add_dependency(
        self,
        key: str,
        dependency: str,
    ) -> None:
        """
        This method is used to dynamically add a dependency from `key` to `dependency`.

        Note: args_mapping_rule and result_dispatching_rule is not allowed to be set by this method, 
        instead they should be set together with add_worker() or add_func_as_worker() when adding the worker.

        Parameters
        ----------
        key : str
            The key of the worker that will depend on the worker with key `dependency`.
        dependency : str
            The key of the worker on which the worker with key `key` will depend.
        """
        ...
        if not self._automa_running:
            # add the dependency immediately
            self._add_dependency_incrementally(key, dependency)
        else:
            deferred_task = _AddDependencyDeferredTask(
                worker_key=key,
                dependency=dependency,
            )
            # Note: the execution order of topology change deferred tasks is important and is determined by the order of the calls of add_worker(), remove_worker() and add_dependency() in one DS.
            self._topology_change_deferred_tasks.append(deferred_task)

    def _validate_canonical_graph(self):
        """
        This method is used to validate that DDG graph is canonical.
        """
        for worker_key, worker_obj in self._workers.items():
            for dependency_key in worker_obj.dependencies:
                if dependency_key not in self._workers:
                    raise AutomaCompilationError(
                        f"the dependency `{dependency_key}` of worker `{worker_key}` does not exist"
                    )
        assert set(self._workers.keys()) == set(self._workers_dynamic_states.keys())
        for worker_key, worker_dynamic_state in self._workers_dynamic_states.items():
            for dependency_key in worker_dynamic_state.dependency_triggers:
                assert dependency_key in self._workers[worker_key].dependencies

        for worker_key, worker_obj in self._workers.items():
            for dependency_key in worker_obj.dependencies:
                assert worker_key in self._worker_forwards[dependency_key]
        for worker_key, successor_keys in self._worker_forwards.items():
            for successor_key in successor_keys:
                assert worker_key in self._workers[successor_key].dependencies

    def _compile_graph_and_detect_risks(self):
        """
        This method should be called at the very beginning of self.run() to ensure that:
        1. The whole graph is built out of all of the following worker sources:
            - Pre-defined workers, such as:
                - Methods decorated with @worker(...)
            - Post-added workers, such as:
                - Functions decorated with @automa_obj.worker(...)
                - Workers added via automa_obj.add_func_as_worker(...)
                - Workers added via automa_obj.add_worker(...)
        2. The dependencies of each worker are confirmed to satisfy the DAG constraints.
        """

        # Validate the canonical graph.
        self._validate_canonical_graph()
        # Validate the DAG constraints.
        GraphMeta.validate_dag_constraints(self._worker_forwards)
        # TODO: More validations can be added here...

        # Find all connected components of the whole automa graph.
        self._find_connected_components()

    def ferry_to(self, key: str, /, *args, **kwargs):
        """
        Defer the invocation to the specified worker, passing any provided arguments. This creates a 
        delayed call, ensuring the worker will be scheduled to run asynchronously in the next event loop, 
        independent of its dependencies.

        This primitive is commonly used for:

        1. Implementing dynamic branching based on runtime conditions.
        2. Creating logic that forms cyclic graphs.

        Parameters
        ----------
        key : str
            The key of the worker to run.
        args : optional
            Positional arguments to be passed.
        kwargs : optional
            Keyword arguments to be passed.

        Examples
        --------
        ```python
        class MyGraphAutoma(GraphAutoma):
            @worker(is_start=True)
            def start_worker(self):
                number = random.randint(0, 1)
                if number == 0:
                    self.ferry_to("cond_1_worker", number=number)
                else:
                    self.ferry_to("cond_2_worker")

            @worker()
            def cond_1_worker(self, number: int):
                print(f'Got {{number}}!')

            @worker()
            def cond_2_worker(self):
                self.ferry_to("start_worker")

        automa = MyGraphAutoma()
        await automa.arun()

        # Output: Got 0!
        ```
        """
        # TODO: check worker_key is valid, maybe deferred check...
        running_options = self._get_top_running_options()
        # if debug is enabled, trace back the kickoff worker key from stacktrace.
        kickoff_worker_key: str = self._trace_back_kickoff_worker_key_from_stack() if running_options.debug else None
        deferred_task = _FerryDeferredTask(
            ferry_to_worker_key=key,
            kickoff_worker_key=kickoff_worker_key,
            args=args,
            kwargs=kwargs,
        )
        # Note: ferry_to() may be called in a new thread.
        # But _ferry_deferred_tasks is not necessary to be thread-safe due to Visibility Guarantees of the Bridgic Concurrency Model.
        self._ferry_deferred_tasks.append(deferred_task)

    def _clean_all_worker_local_space(self):
        """
        Clean the local space of all workers.
        """
        for worker_obj in self._workers.values():
            worker_obj.local_space = {}

    async def arun(
        self,
        *args: Tuple[Any, ...],
        feedback_data: Optional[Union[InteractionFeedback, List[InteractionFeedback]]] = None,
        **kwargs: Dict[str, Any]
    ) -> Any:
        """
        The entry point for running the constructed `GraphAutoma` instance.

        This method serves as the entry point for both initial execution and resumption after 
        interruption of an automa instance. It automatically drives the execution of workers 
        based on their `dependencies` and explicit `ferry_to()` calls. Each execution will be 
        wrapped in an `asyncio.Task` to ensure context isolation.

        **Automatic Scheduling**

        The scheduling behavior in `GraphAutoma` is automatically driven by:

        - Worker dependencies: Workers are scheduled to run only after all their necessary 
          dependencies are satisfied. The dependencies automatically drive the execution order.

        - Calling ferry_to: During execution, a worker can explicitly trigger another worker 
          by calling `ferry_to()`, which enables dynamic flow control and conditional branching.

        - Dynamic topology changes: When the graph topology is modified at runtime (such as 
          adding or removing workers or dependencies), the scheduling system seamlessly updates 
          to reflect the latest structure, ensuring that worker execution always follows the 
          current graph.

        **Human Interaction Mechanism**

        Workers can request human input by calling `interact_with_human()` during execution. 
        When this occurs:

        - The execution will be paused after the running workers finish their execution.
        - The Automa's state will be serialized into a `Snapshot` object.
        - An `InteractionException` will be raised to the application layer. It contains both the 
          list of pending `Interaction` objects and the `Snapshot` object.
        - The application layer may persist the `Snapshot` properly to resume the execution later.
        - To resume execution, the application layer should reload the Automa state using 
          `load_from_snapshot()` with the saved `Snapshot` object and call `arun()` again with 
          `feedback_data` containing the user's feedback(s) to finish a complete interaction.

        Parameters
        ----------
        args : optional
            Positional arguments to be passed.
        feedback_data : Optional[Union[InteractionFeedback, List[InteractionFeedback]]]
            Feedbacks that are received from one or multiple human interactions occurred before the
            Automa was paused. This argument may be of type `InteractionFeedback` or 
            `List[InteractionFeedback]`. If only one interaction occurred, `feedback_data` should be
            of type `InteractionFeedback`. If multiple interactions occurred simultaneously, 
            `feedback_data` should be of type `List[InteractionFeedback]`.
        kwargs : optional
            Keyword arguments which may be further propagated to contained workers.

        Returns
        -------
        Any
            The execution result of the output-worker that has the setting `is_output=True`,
            otherwise None.

        Raises
        ------
        InteractionException
            If the Automa is the top-level Automa and the `interact_with_human()` method is called
            by one or more workers within the lastest event loop iteration, this exception will be
            raised to the application layer.
        """
        if self.is_top_level():
            # For top-level automa, wrap in a task to ensure context isolation
            task = asyncio.create_task(
                self._arun_internal(*args, feedback_data=feedback_data, **kwargs),
                name=f"GraphAutoma-{self.name}-arun"
            )
            return await task
        else:
            # For nested automa, directly call _arun_internal to avoid redundant task creation
            return await self._arun_internal(*args, feedback_data=feedback_data, **kwargs)

    async def _arun_internal(
        self,
        *args: Tuple[Any, ...],
        feedback_data: Optional[Union[InteractionFeedback, List[InteractionFeedback]]] = None,
        **kwargs: Dict[str, Any]
    ) -> Any:
        """
        Internal implementation of `arun()` for `GraphAutoma`.

        The scheduling behavior in `GraphAutoma` is automatically driven by:

        1. **Worker dependencies**: Workers are scheduled to run only after all their necessary 
        dependencies are satisfied. The dependencies automatically drives the execution order.

        2. **Calling ferry_to**: During execution, a worker can explicitly trigger another worker 
        with calling `ferry_to()`, which enables dynamic flow control and conditional branching.

        3. **Dynamic topology changes**: When the graph topology is modified at runtime (such as adding 
        or removing workers or dependencies), the scheduling system seamlessly updates to reflect 
        the latest structure, ensuring that worker execution always follows the current graph.
        """

        def _reinit_current_kickoff_workers_if_needed():
            # Note: After deserialization, the _current_kickoff_workers must not be empty!
            # Therefore, _current_kickoff_workers will only be reinitialized when the Automa is run for the first time or rerun.
            # It is guaranteed that _current_kickoff_workers will not be reinitialized when the Automa is resumed after deserialization.
            if not self._current_kickoff_workers:
                self._current_kickoff_workers = [
                    _KickoffInfo(
                        worker_key=worker_key,
                        last_kickoff="__automa__"
                    ) for worker_key, worker_obj in self._workers.items()
                    if getattr(worker_obj, "is_start", False)
                ]
                # Each time the Automa re-runs, buffer the input arguments here.
                self._input_buffer.args = args
                self._input_buffer.kwargs = kwargs

        def _execute_topology_change_deferred_tasks(tc_tasks: List[Union[_AddWorkerDeferredTask, _RemoveWorkerDeferredTask, _AddDependencyDeferredTask]]):
            # update the control flow topology
            for topology_task in tc_tasks:
                if topology_task.task_type == "add_worker":
                    self._add_worker_incrementally(
                        key=topology_task.worker_key,
                        worker=topology_task.worker_obj,
                        dependencies=topology_task.dependencies,
                        is_start=topology_task.is_start,
                        is_output=topology_task.is_output,
                        args_mapping_rule=topology_task.args_mapping_rule,
                        result_dispatching_rule=topology_task.result_dispatching_rule,
                        callback_builders=topology_task.callback_builders,
                    )
                elif topology_task.task_type == "remove_worker":
                    self._remove_worker_incrementally(topology_task.worker_key)
                elif topology_task.task_type == "add_dependency":
                    self._add_dependency_incrementally(topology_task.worker_key, topology_task.dependency)

            # update the data flow topology
            args_manager.update_data_flow_topology(dynamic_tasks=tc_tasks)

        def _set_worker_run_finished(worker_key: str):
            for kickoff_info in self._current_kickoff_workers:
                if kickoff_info.worker_key == worker_key:
                    kickoff_info.run_finished = True
                    break

        def _check_and_normalize_interaction_params(
            feedback_data: Optional[Union[InteractionFeedback, List[InteractionFeedback]]] = None,
            interaction_feedback: Optional[InteractionFeedback] = None,
            interaction_feedbacks: Optional[List[InteractionFeedback]] = None,
        ):
            if feedback_data:
                if isinstance(feedback_data, list):
                    rx_feedbacks = feedback_data
                else:
                    rx_feedbacks = [feedback_data]
                return rx_feedbacks
            # For backward compatibility with old parameter names. To be removed in the future.
            if interaction_feedback and interaction_feedbacks:
                raise AutomaRuntimeError(
                    f"Only one of interaction_feedback or interaction_feedbacks can be used. "
                    f"But received interaction_feedback={interaction_feedback} and \n"
                    f"interaction_feedbacks={interaction_feedbacks}"
                )
            if interaction_feedback:
                rx_feedbacks = [interaction_feedback]
            else:
                rx_feedbacks = interaction_feedbacks
            return rx_feedbacks

        def _match_ongoing_interaction_and_feedbacks(rx_feedbacks:List[InteractionFeedback]):
            match_left_feedbacks = []
            for feedback in rx_feedbacks:
                matched = False
                for interaction_and_feedbacks in self._ongoing_interactions.values():
                    for interaction_and_feedback in interaction_and_feedbacks:
                        if interaction_and_feedback.interaction.interaction_id == feedback.interaction_id:
                            matched = True
                            # Note: Only one feedback is allowed for each interaction. Here we assume that only the first feedback is valid, which is a choice of implementation.
                            if interaction_and_feedback.feedback is None:
                                # Set feedback to self._ongoing_interactions
                                interaction_and_feedback.feedback = feedback
                            break
                    if matched:
                        break
                if not matched:
                    match_left_feedbacks.append(feedback)
            return match_left_feedbacks

        running_options = self._get_top_running_options()

        self._main_loop = asyncio.get_running_loop()
        self._main_thread_id = threading.get_ident()

        if self.thread_pool is None:
            self.thread_pool = ThreadPoolExecutor(thread_name_prefix="bridgic-thread")

        if not self._automa_running:
            # Here is the last chance to compile and check the DDG in the end of the [Initialization Phase] (phase 1 just before the first DS).
            self._compile_graph_and_detect_risks()
            self._automa_running = True

        # An Automa needs to be re-run with _current_kickoff_workers reinitialized.
        _reinit_current_kickoff_workers_if_needed()

        is_top_level = self.is_top_level()

        # If this is the top-level automa, execute its callbacks separately.
        if is_top_level:
            automa_callbacks = self._get_automa_callbacks()

            for callback in automa_callbacks:
                await callback.on_worker_start(
                    key=self.name,
                    is_top_level=True,
                    parent=self.parent,
                    arguments={
                        "args": self._input_buffer.args,
                        "kwargs": self._input_buffer.kwargs,
                        "feedback_data": feedback_data,
                    },
                )

        # For backward compatibility with old parameter names. To be removed in the future.
        interaction_feedback = kwargs.get("interaction_feedback")
        interaction_feedbacks = kwargs.get("interaction_feedbacks")
        rx_feedbacks = _check_and_normalize_interaction_params(feedback_data, interaction_feedback, interaction_feedbacks)
        if rx_feedbacks:
            rx_feedbacks = _match_ongoing_interaction_and_feedbacks(rx_feedbacks)

        if running_options.debug:
            printer.print(f"\n{type(self).__name__}-[{self.name}] is getting started.", color="green")

        # Task loop divided into many dynamic steps (DS).
        args_manager = ArgsManager(
            input_args=self._input_buffer.args,
            input_kwargs=self._input_buffer.kwargs,
            worker_outputs=self._worker_output,
            worker_forwards=self._worker_forwards,
            worker_dict=self._workers
        )
        is_output_worker_keys = set()
        while self._current_kickoff_workers:
            # A new DS started.
            if running_options.debug:
                kickoff_worker_keys = [kickoff_info.worker_key for kickoff_info in self._current_kickoff_workers]
                printer.print(f"[DS][Before Tasks Started] kickoff workers: {kickoff_worker_keys}", color="purple")

            for kickoff_info in self._current_kickoff_workers:
                if kickoff_info.run_finished:
                    # Skip finished workers. Here is the case that the Automa is resumed after a human interaction.
                    if running_options.debug:
                        printer.print(f"[{kickoff_info.worker_key}] will be skipped - run finished", color="blue")
                    continue

                if running_options.debug:
                    kickoff_name = kickoff_info.last_kickoff
                    if kickoff_name == "__automa__":
                        kickoff_name = f"{kickoff_name}:({self.name})"
                    printer.print(f"[{kickoff_name}] will kick off [{kickoff_info.worker_key}]", color="cyan")

                # Arguments Mapping:
                binding_args, binding_kwargs = args_manager.args_binding(
                    last_worker_key=kickoff_info.last_kickoff,
                    current_worker_key=kickoff_info.worker_key
                ) if not kickoff_info.from_ferry else ((), {})
                # Inputs Propagation
                _, propagation_kwargs = args_manager.inputs_propagation(current_worker_key=kickoff_info.worker_key)
                # Data injection.
                _, injection_kwargs = args_manager.args_injection(
                    current_worker_key=kickoff_info.worker_key, 
                    current_automa=self
                )
                # Ferry arguments.
                ferry_args, ferry_kwargs = kickoff_info.args, kickoff_info.kwargs
                # combine the arguments from the three steps.
                # kwargs will cover priority follows: propagation_kwargs < binding_kwargs < injection_kwargs < ferry_kwargs
                next_args, next_kwargs = safely_map_args(
                    (*binding_args, *ferry_args), 
                    {**propagation_kwargs, **binding_kwargs, **injection_kwargs, **ferry_kwargs}, 
                    self._workers[kickoff_info.worker_key].get_input_param_names()
                )

                # Collect the output worker keys.
                if self._workers[kickoff_info.worker_key].is_output:
                    is_output_worker_keys.add(kickoff_info.worker_key)
                    if len(is_output_worker_keys) > 1:
                        raise AutomaRuntimeError(
                            f"It is not allowed to have more than one worker with `is_output=True` and "
                            f"they are all considered as output-worker when the automa terminates and returns."
                            f"The current output-worker keys are: {is_output_worker_keys}."
                            f"If you want to collect the results of multiple workers simultaneously, "
                            f"it is recommended that you add one worker to gather them."
                        )

                # Schedule task for each kickoff worker.
                worker_obj = self._workers[kickoff_info.worker_key]
                if worker_obj.is_automa():
                    coro = worker_obj.arun(
                        *next_args,
                        feedback_data=rx_feedbacks,
                        **next_kwargs,
                    )
                else:
                    coro = worker_obj.arun(*next_args, **next_kwargs)

                task = asyncio.create_task(
                    # TODO1: arun() may need to be wrapped to support better interrupt...
                    coro,
                    name=f"Task-{kickoff_info.worker_key}"
                )
                self._running_tasks.append(_RunnningTask(
                    worker_key=kickoff_info.worker_key,
                    task=task,
                ))

            # Wait until all of the tasks are finished.
            while True:
                undone_tasks = [t.task for t in self._running_tasks if not t.task.done()]
                if not undone_tasks:
                    break
                try:
                    await undone_tasks[0]
                except Exception as e:
                    ...
                    # The same exception will be raised again in the following task.result().
                    # Note: A Task is done when the wrapped coroutine either returned a value, raised an exception, or the Task was cancelled.
                    # Refer to: https://docs.python.org/3/library/asyncio-task.html#task-object

            # Process graph topology change deferred tasks triggered by add_worker() and remove_worker().
            _execute_topology_change_deferred_tasks(self._topology_change_deferred_tasks)

            # Handle exceptions raised by all running tasks.
            interaction_exceptions: List[_InteractionEventException] = []
            non_interaction_exceptions: List[Exception] = []

            for task in self._running_tasks:
                try:
                    # It will raise an exception if task failed.
                    task_result = task.task.result()
                    _set_worker_run_finished(task.worker_key)

                    if task.worker_key in self._workers:
                        # The current running worker may be removed.
                        worker_obj = self._workers[task.worker_key]
                        # Collect results of the finished tasks.
                        self._worker_output[task.worker_key] = task_result
                        # reset dynamic states of finished workers.
                        self._workers_dynamic_states[task.worker_key].dependency_triggers = set(getattr(worker_obj, "dependencies", []))
                        # Update the dynamic states of successor workers.
                        for successor_key in self._worker_forwards.get(task.worker_key, []):
                            self._workers_dynamic_states[successor_key].dependency_triggers.remove(task.worker_key)
                        # Each time a worker is finished running, the ongoing interaction states should be cleared. Once it is re-run, the human interactions in the worker can be triggered again.
                        if task.worker_key in self._worker_interaction_indices:
                            del self._worker_interaction_indices[task.worker_key]
                        if task.worker_key in self._ongoing_interactions:
                            del self._ongoing_interactions[task.worker_key]
                except Exception as e:
                    if isinstance(e, _InteractionEventException):
                        interaction_exceptions.append(e)
                        if task.worker_key in self._workers and not self._workers[task.worker_key].is_automa():
                            if task.worker_key not in self._ongoing_interactions:
                                self._ongoing_interactions[task.worker_key] = []
                            interaction=e.args[0]
                            # Make sure the interaction_id is unique for each human interaction.
                            found = False
                            for iaf in self._ongoing_interactions[task.worker_key]:
                                if iaf.interaction.interaction_id == interaction.interaction_id:
                                    found = True
                                    break
                            if not found:
                                self._ongoing_interactions[task.worker_key].append(_InteractionAndFeedback(
                                    interaction=interaction,
                                ))
                    else:
                        non_interaction_exceptions.append(e)

            if len(self._topology_change_deferred_tasks) > 0:
                # Graph topology validation and risk detection. Only needed when topology changes.
                # Guarantee the graph topology is valid and consistent after each DS.
                # 1. Validate the canonical graph.
                self._validate_canonical_graph()
                # 2. Validate the DAG constraints.
                GraphMeta.validate_dag_constraints(self._worker_forwards)
                # TODO: more validations can be added here...

            # TODO: Ferry-related risk detection may be added here...

            # Handle exceptions with callbacks at the top-level automa before re-raising them.
            if is_top_level:
                # Get cached callbacks for top-level automa
                automa_callbacks = self._get_automa_callbacks()

                # Process interaction exceptions with callbacks (they cannot be suppressed, but callbacks can observe them)
                for e in interaction_exceptions + non_interaction_exceptions:
                    await try_handle_error_with_callbacks(
                        callbacks=automa_callbacks,
                        key=self.name,
                        is_top_level=True,
                        parent=self.parent,
                        arguments={
                            "args": self._input_buffer.args,
                            "kwargs": self._input_buffer.kwargs,
                            "feedback_data": feedback_data,
                        },
                        error=e,
                    )

            # For inner interaction exceptions, collect them and throw an InteractionException as a whole.
            if len(interaction_exceptions) > 0:
                all_interactions: List[Interaction] = [interaction for e in interaction_exceptions for interaction in e.args]
                if self.is_top_level():
                    # This is the top-level Automa. Serialize the Automa and raise InteractionException to the application layer.
                    serialized_automa = dump_bytes(self)
                    snapshot = Snapshot(
                        serialized_bytes=serialized_automa,
                        serialization_version=GraphAutoma.SERIALIZATION_VERSION,
                    )
                    raise InteractionException(
                        interactions=all_interactions,
                        snapshot=snapshot,
                    )
                else:
                    # Continue raise exception to the upper level Automa.
                    raise _InteractionEventException(*all_interactions)

            # For non-interaction exceptions, immediately raise the first one directly, since none of them are meant to be suppressed.
            if len(non_interaction_exceptions) > 0:
                raise non_interaction_exceptions[0]

            # Find next kickoff workers and rebuild _current_kickoff_workers
            run_finished_worker_keys: List[str] = [kickoff_info.worker_key for kickoff_info in self._current_kickoff_workers if kickoff_info.run_finished]
            assert len(run_finished_worker_keys) == len(self._current_kickoff_workers)
            self._current_kickoff_workers = []
            # New kickoff workers can be triggered by two ways:
            # 1. The ferry_to() operation is called during current worker execution.
            # 2. The dependencies are eliminated after all predecessor workers are finished.
            # So,
            # First add kickoff workers triggered by ferry_to();
            for ferry_task in self._ferry_deferred_tasks:
                self._current_kickoff_workers.append(_KickoffInfo(
                    worker_key=ferry_task.ferry_to_worker_key,
                    last_kickoff=ferry_task.kickoff_worker_key,
                    from_ferry=True,
                    args=ferry_task.args,
                    kwargs=ferry_task.kwargs,
                ))
            # Then add kickoff workers triggered by dependencies elimination.
            # Merge successor keys of all finished tasks.
            successor_keys = set()
            for worker_key in run_finished_worker_keys:
                # Note: The `worker_key` worker may have been removed from the Automa.
                for successor_key in self._worker_forwards.get(worker_key, []):
                    if successor_key not in successor_keys:
                        dependency_triggers = self._workers_dynamic_states[successor_key].dependency_triggers
                        if not dependency_triggers:
                            self._current_kickoff_workers.append(_KickoffInfo(
                                worker_key=successor_key,
                                last_kickoff=worker_key,
                            ))
                        successor_keys.add(successor_key)
            if running_options.debug:
                deferred_ferrys = [ferry_task.ferry_to_worker_key for ferry_task in self._ferry_deferred_tasks]
                printer.print(f"[DS][After Tasks Finished] successor workers: {successor_keys}, deferred ferrys: {deferred_ferrys}", color="purple")

            # Clear running tasks after all finished.
            self._running_tasks.clear()
            self._ferry_deferred_tasks.clear()
            self._topology_change_deferred_tasks.clear()

        if running_options.debug:
            printer.print(f"{type(self).__name__}-[{self.name}] is finished.", color="green")

        # After a complete run, reset all necessary states to allow the automa to re-run.
        self._input_buffer = _AutomaInputBuffer()
        if self.should_reset_local_space():
            self._clean_all_worker_local_space()
        self._ongoing_interactions.clear()
        self._worker_interaction_indices.clear()
        self._automa_running = False

        # Get result before calling callbacks
        if is_output_worker_keys:
            result = self._worker_output.get(list(is_output_worker_keys)[0], None)
        else:
            result = None

        # If this is the top-level automa, execute its callbacks separately.
        if is_top_level:
            automa_callbacks = self._get_automa_callbacks()
            for callback in automa_callbacks:
                await callback.on_worker_end(
                    key=self.name,
                    is_top_level=True,
                    parent=self.parent,
                    arguments={
                        "args": self._input_buffer.args,
                        "kwargs": self._input_buffer.kwargs,
                        "feedback_data": feedback_data,
                    },
                    result=result,
                )

        return result

    def _get_worker_dependencies(self, worker_key: str) -> List[str]:
        """
        Get the worker keys of all dependencies of the worker.
        """
        deps = self._workers[worker_key].dependencies
        return [] if deps is None else deps

    def _find_connected_components(self):
        """
        Find all of the connected components in the whole automa graph described by self._workers.
        """
        visited = set()
        component_list = []
        component_idx = {}

        def dfs(worker: str, component: List[str]):
            visited.add(worker)
            component.append(worker)
            for target in self._worker_forwards.get(worker, []):
                if target not in visited:
                    dfs(target, component)

        for worker in self._workers.keys():
            if worker not in visited:
                component_list.append([])
                current_idx = len(component_list) - 1
                current_component = component_list[current_idx]

                dfs(worker, current_component)

                for worker in current_component:
                    component_idx[worker] = current_idx

        # self._component_list, self._component_idx = component_list, component_idx
        # TODO: check how to use _component_list and _component_idx...

    @override
    def _get_worker_key(self, worker: Worker) -> Optional[str]:
        for worker_key, worker_obj in self._workers.items():
            if worker_obj == worker:
                # Note: _GraphAdaptedWorker.__eq__() is overridden to support the '==' operator.
                return worker_key
        return None

    @override
    def _get_worker_instance(self, worker_key: str) -> Worker:
        return self._workers[worker_key]

    @override
    def _locate_interacting_worker(self) -> Optional[str]:
        return self._trace_back_kickoff_worker_key_from_stack()

    def _trace_back_kickoff_worker_key_from_stack(self) -> Optional[str]:
        worker = self._get_current_running_worker_instance_by_stacktrace()
        if worker:
            return self._get_worker_key(worker)
        return None

    def _get_current_running_worker_instance_by_stacktrace(self) -> Optional[Worker]:
        for frame_info in inspect.stack():
            frame = frame_info.frame
            if 'self' in frame.f_locals:
                self_obj = frame.f_locals['self']
                if isinstance(self_obj, Worker) and (not isinstance(self_obj, Automa)) and (frame_info.function == "arun" or frame_info.function == "run"):
                    return self_obj
        return None

    def __repr__(self) -> str:
        # TODO : It's good to make __repr__() of Automa compatible with eval().
        # This feature depends on the implementation of __repr__() of workers.
        class_name = self.__class__.__name__
        workers_str = self._workers.__repr__()
        return f"{class_name}(workers={workers_str})"

    def __str__(self) -> str:
        d = {}
        for k, v in self._workers.items():
            d[k] = f"{v} depends on {getattr(v, 'dependencies', [])}"
        return json.dumps(d, ensure_ascii=False, indent=4)

all_workers

all_workers() -> List[str]

Gets a list containing the keys of all workers registered in this Automa.

Returns:

Type Description
List[str]

A list of worker keys.

Source code in bridgic/core/automa/_graph_automa.py
def all_workers(self) -> List[str]:
    """
    Gets a list containing the keys of all workers registered in this Automa.

    Returns
    -------
    List[str]
        A list of worker keys.
    """
    return list(self._workers.keys())

add_worker

add_worker(
    key: str,
    worker: Worker,
    *,
    dependencies: List[str] = [],
    is_start: bool = False,
    is_output: bool = False,
    args_mapping_rule: ArgsMappingRule = AS_IS,
    result_dispatching_rule: ResultDispatchingRule = AS_IS,
    callback_builders: List[WorkerCallbackBuilder] = []
) -> None

This method is used to add a worker dynamically into the automa.

If this method is called during the [Initialization Phase], the worker will be added immediately. If this method is called during the [Running Phase], the worker will be added as a deferred task which will be executed in the next DS.

The dependencies can be added together with a worker. However, you can add a worker without any dependencies.

Note: args_mapping_rule and result_dispatching_rule could only be set when using worker-adding API. Even if the worker has no any dependencies.

Parameters:

Name Type Description Default
key str

The key of the worker.

required
worker Worker

The worker instance to be registered.

required
dependencies List[str]

A list of worker keys that the worker depends on.

[]
is_start bool

Whether the worker is a start worker.

False
is_output bool

Whether the worker is an output worker.

False
args_mapping_rule ArgsMappingRule

The rule of arguments mapping.

AS_IS
result_dispatching_rule ResultDispatchingRule

The rule of result dispatch.

AS_IS
callback_builders List[WorkerCallbackBuilder]

A list of worker callback builders to be registered. Callback instances will be created from builders when the worker is instantiated.

[]
Source code in bridgic/core/automa/_graph_automa.py
def add_worker(
    self,
    key: str,
    worker: Worker,
    *,
    dependencies: List[str] = [],
    is_start: bool = False,
    is_output: bool = False,
    args_mapping_rule: ArgsMappingRule = ArgsMappingRule.AS_IS,
    result_dispatching_rule: ResultDispatchingRule = ResultDispatchingRule.AS_IS,
    callback_builders: List[WorkerCallbackBuilder] = [],
) -> None:
    """
    This method is used to add a worker dynamically into the automa.

    If this method is called during the [Initialization Phase], the worker will be added immediately. If this method is called during the [Running Phase], the worker will be added as a deferred task which will be executed in the next DS.

    The dependencies can be added together with a worker. However, you can add a worker without any dependencies.

    Note: args_mapping_rule and result_dispatching_rule could only be set when using worker-adding API. Even if the worker has no any dependencies.

    Parameters
    ----------
    key : str
        The key of the worker.
    worker : Worker
        The worker instance to be registered.
    dependencies : List[str]
        A list of worker keys that the worker depends on.
    is_start : bool
        Whether the worker is a start worker.
    is_output : bool
        Whether the worker is an output worker.
    args_mapping_rule : ArgsMappingRule
        The rule of arguments mapping.
    result_dispatching_rule : ResultDispatchingRule
        The rule of result dispatch.
    callback_builders : List[WorkerCallbackBuilder]
        A list of worker callback builders to be registered.
        Callback instances will be created from builders when the worker is instantiated.
    """
    self._add_worker_internal(
        key=key,
        worker=worker,
        dependencies=dependencies,
        is_start=is_start,
        is_output=is_output,
        args_mapping_rule=args_mapping_rule,
        result_dispatching_rule=result_dispatching_rule,
        callback_builders=callback_builders,
    )

add_func_as_worker

add_func_as_worker(
    key: str,
    func: Callable,
    *,
    dependencies: List[str] = [],
    is_start: bool = False,
    is_output: bool = False,
    args_mapping_rule: ArgsMappingRule = AS_IS,
    result_dispatching_rule: ResultDispatchingRule = AS_IS,
    callback_builders: List[WorkerCallbackBuilder] = []
) -> None

This method is used to add a function as a worker into the automa.

The format of the parameters will follow that of the decorator @worker(...), so that the behavior of the decorated function is consistent with that of normal CallableLandableWorker objects.

Parameters:

Name Type Description Default
key str

The key of the function worker.

required
func Callable

The function to be added as a worker to the automa.

required
dependencies List[str]

A list of worker names that the decorated callable depends on.

[]
is_start bool

Whether the decorated callable is a start worker. True means it is, while False means it is not.

False
is_output bool

Whether the decorated callable is an output worker. True means it is, while False means it is not.

False
args_mapping_rule ArgsMappingRule

The rule of arguments mapping.

AS_IS
result_dispatching_rule ResultDispatchingRule

The rule of result dispatch.

AS_IS
callback_builders List[WorkerCallbackBuilder]

A list of worker callback builders to be registered. Callback instances will be created from builders when the worker is instantiated.

[]
Source code in bridgic/core/automa/_graph_automa.py
def add_func_as_worker(
    self,
    key: str,
    func: Callable,
    *,
    dependencies: List[str] = [],
    is_start: bool = False,
    is_output: bool = False,
    args_mapping_rule: ArgsMappingRule = ArgsMappingRule.AS_IS,
    result_dispatching_rule: ResultDispatchingRule = ResultDispatchingRule.AS_IS,
    callback_builders: List[WorkerCallbackBuilder] = [],
) -> None:
    """
    This method is used to add a function as a worker into the automa.

    The format of the parameters will follow that of the decorator @worker(...), so that the 
    behavior of the decorated function is consistent with that of normal CallableLandableWorker objects.

    Parameters
    ----------
    key : str
        The key of the function worker.
    func : Callable
        The function to be added as a worker to the automa.
    dependencies : List[str]
        A list of worker names that the decorated callable depends on.
    is_start : bool
        Whether the decorated callable is a start worker. True means it is, while False means it is not.
    is_output : bool
        Whether the decorated callable is an output worker. True means it is, while False means it is not.
    args_mapping_rule : ArgsMappingRule
        The rule of arguments mapping.
    result_dispatching_rule : ResultDispatchingRule
        The rule of result dispatch.
    callback_builders : List[WorkerCallbackBuilder]
        A list of worker callback builders to be registered.
        Callback instances will be created from builders when the worker is instantiated.
    """
    self._add_func_as_worker_internal(
        key=key,
        func=func,
        dependencies=dependencies,
        is_start=is_start,
        is_output=is_output,
        args_mapping_rule=args_mapping_rule,
        result_dispatching_rule=result_dispatching_rule,
        callback_builders=callback_builders,
    )

worker

worker(
    *,
    key: Optional[str] = None,
    dependencies: List[str] = [],
    is_start: bool = False,
    is_output: bool = False,
    args_mapping_rule: ArgsMappingRule = AS_IS,
    result_dispatching_rule: ResultDispatchingRule = AS_IS,
    callback_builders: List[WorkerCallbackBuilder] = []
) -> Callable

This is a decorator used to mark a function as an GraphAutoma detectable Worker. Dislike the global decorator @worker(...), it is usally used after an GraphAutoma instance is initialized.

The format of the parameters will follow that of the decorator @worker(...), so that the behavior of the decorated function is consistent with that of normal CallableLandableWorker objects.

Parameters:

Name Type Description Default
key str

The key of the worker. If not provided, the name of the decorated callable will be used.

None
dependencies List[str]

A list of worker names that the decorated callable depends on.

[]
is_start bool

Whether the decorated callable is a start worker. True means it is, while False means it is not.

False
is_output bool

Whether the decorated callable is an output worker. True means it is, while False means it is not.

False
args_mapping_rule str

The rule of arguments mapping. The options are: "auto", "as_list", "as_dict", "suppressed".

AS_IS
result_dispatching_rule ResultDispatchingRule

The rule of result dispatch.

AS_IS
callback_builders List[WorkerCallbackBuilder]

A list of worker callback builders to be registered. Callback instances will be created from builders when the worker is instantiated.

[]
Source code in bridgic/core/automa/_graph_automa.py
def worker(
    self,
    *,
    key: Optional[str] = None,
    dependencies: List[str] = [],
    is_start: bool = False,
    is_output: bool = False,
    args_mapping_rule: ArgsMappingRule = ArgsMappingRule.AS_IS,
    result_dispatching_rule: ResultDispatchingRule = ResultDispatchingRule.AS_IS,
    callback_builders: List[WorkerCallbackBuilder] = [],
) -> Callable:
    """
    This is a decorator used to mark a function as an GraphAutoma detectable Worker. Dislike the 
    global decorator @worker(...), it is usally used after an GraphAutoma instance is initialized.

    The format of the parameters will follow that of the decorator @worker(...), so that the 
    behavior of the decorated function is consistent with that of normal CallableLandableWorker objects.

    Parameters
    ----------
    key : str
        The key of the worker. If not provided, the name of the decorated callable will be used.
    dependencies : List[str]
        A list of worker names that the decorated callable depends on.
    is_start : bool
        Whether the decorated callable is a start worker. True means it is, while False means it is not.
    is_output : bool
        Whether the decorated callable is an output worker. True means it is, while False means it is not.
    args_mapping_rule : str
        The rule of arguments mapping. The options are: "auto", "as_list", "as_dict", "suppressed".
    result_dispatching_rule : ResultDispatchingRule
        The rule of result dispatch.
    callback_builders : List[WorkerCallbackBuilder]
        A list of worker callback builders to be registered.
        Callback instances will be created from builders when the worker is instantiated.
    """
    def wrapper(func: Callable):
        self._add_func_as_worker_internal(
            key=(key or func.__name__),
            func=func,
            dependencies=dependencies,
            is_start=is_start,
            is_output=is_output,
            args_mapping_rule=args_mapping_rule,
            result_dispatching_rule=result_dispatching_rule,
            callback_builders=callback_builders,
        )

    return wrapper

remove_worker

remove_worker(key: str) -> None

Remove a worker from the Automa. This method can be called at any time to remove a worker from the Automa.

When a worker is removed, all dependencies related to this worker, including all the dependencies of the worker itself and the dependencies between the worker and its successor workers, will be also removed.

Parameters:

Name Type Description Default
key str

The key of the worker to be removed.

required

Returns:

Type Description
None

Raises:

Type Description
AutomaDeclarationError

If the worker specified by key does not exist in the Automa, this exception will be raised.

Source code in bridgic/core/automa/_graph_automa.py
def remove_worker(self, key: str) -> None:
    """
    Remove a worker from the Automa. This method can be called at any time to remove a worker from the Automa.

    When a worker is removed, all dependencies related to this worker, including all the dependencies of the worker itself and the dependencies between the worker and its successor workers, will be also removed.

    Parameters
    ----------
    key : str
        The key of the worker to be removed.

    Returns
    -------
    None

    Raises
    ------
    AutomaDeclarationError
        If the worker specified by key does not exist in the Automa, this exception will be raised.
    """
    if not self._automa_running:
        # remove immediately
        self._remove_worker_incrementally(key)
    else:
        deferred_task = _RemoveWorkerDeferredTask(
            worker_key=key,
        )
        # Note: the execution order of topology change deferred tasks is important and is determined by the order of the calls of add_worker(), remove_worker() and add_dependency() in one DS.
        self._topology_change_deferred_tasks.append(deferred_task)

add_dependency

add_dependency(key: str, dependency: str) -> None

This method is used to dynamically add a dependency from key to dependency.

Note: args_mapping_rule and result_dispatching_rule is not allowed to be set by this method, instead they should be set together with add_worker() or add_func_as_worker() when adding the worker.

Parameters:

Name Type Description Default
key str

The key of the worker that will depend on the worker with key dependency.

required
dependency str

The key of the worker on which the worker with key key will depend.

required
Source code in bridgic/core/automa/_graph_automa.py
def add_dependency(
    self,
    key: str,
    dependency: str,
) -> None:
    """
    This method is used to dynamically add a dependency from `key` to `dependency`.

    Note: args_mapping_rule and result_dispatching_rule is not allowed to be set by this method, 
    instead they should be set together with add_worker() or add_func_as_worker() when adding the worker.

    Parameters
    ----------
    key : str
        The key of the worker that will depend on the worker with key `dependency`.
    dependency : str
        The key of the worker on which the worker with key `key` will depend.
    """
    ...
    if not self._automa_running:
        # add the dependency immediately
        self._add_dependency_incrementally(key, dependency)
    else:
        deferred_task = _AddDependencyDeferredTask(
            worker_key=key,
            dependency=dependency,
        )
        # Note: the execution order of topology change deferred tasks is important and is determined by the order of the calls of add_worker(), remove_worker() and add_dependency() in one DS.
        self._topology_change_deferred_tasks.append(deferred_task)

ferry_to

ferry_to(key: str, /, *args, **kwargs)

Defer the invocation to the specified worker, passing any provided arguments. This creates a delayed call, ensuring the worker will be scheduled to run asynchronously in the next event loop, independent of its dependencies.

This primitive is commonly used for:

  1. Implementing dynamic branching based on runtime conditions.
  2. Creating logic that forms cyclic graphs.

Parameters:

Name Type Description Default
key str

The key of the worker to run.

required
args optional

Positional arguments to be passed.

()
kwargs optional

Keyword arguments to be passed.

{}

Examples:

class MyGraphAutoma(GraphAutoma):
    @worker(is_start=True)
    def start_worker(self):
        number = random.randint(0, 1)
        if number == 0:
            self.ferry_to("cond_1_worker", number=number)
        else:
            self.ferry_to("cond_2_worker")

    @worker()
    def cond_1_worker(self, number: int):
        print(f'Got {{number}}!')

    @worker()
    def cond_2_worker(self):
        self.ferry_to("start_worker")

automa = MyGraphAutoma()
await automa.arun()

# Output: Got 0!
Source code in bridgic/core/automa/_graph_automa.py
def ferry_to(self, key: str, /, *args, **kwargs):
    """
    Defer the invocation to the specified worker, passing any provided arguments. This creates a 
    delayed call, ensuring the worker will be scheduled to run asynchronously in the next event loop, 
    independent of its dependencies.

    This primitive is commonly used for:

    1. Implementing dynamic branching based on runtime conditions.
    2. Creating logic that forms cyclic graphs.

    Parameters
    ----------
    key : str
        The key of the worker to run.
    args : optional
        Positional arguments to be passed.
    kwargs : optional
        Keyword arguments to be passed.

    Examples
    --------
    ```python
    class MyGraphAutoma(GraphAutoma):
        @worker(is_start=True)
        def start_worker(self):
            number = random.randint(0, 1)
            if number == 0:
                self.ferry_to("cond_1_worker", number=number)
            else:
                self.ferry_to("cond_2_worker")

        @worker()
        def cond_1_worker(self, number: int):
            print(f'Got {{number}}!')

        @worker()
        def cond_2_worker(self):
            self.ferry_to("start_worker")

    automa = MyGraphAutoma()
    await automa.arun()

    # Output: Got 0!
    ```
    """
    # TODO: check worker_key is valid, maybe deferred check...
    running_options = self._get_top_running_options()
    # if debug is enabled, trace back the kickoff worker key from stacktrace.
    kickoff_worker_key: str = self._trace_back_kickoff_worker_key_from_stack() if running_options.debug else None
    deferred_task = _FerryDeferredTask(
        ferry_to_worker_key=key,
        kickoff_worker_key=kickoff_worker_key,
        args=args,
        kwargs=kwargs,
    )
    # Note: ferry_to() may be called in a new thread.
    # But _ferry_deferred_tasks is not necessary to be thread-safe due to Visibility Guarantees of the Bridgic Concurrency Model.
    self._ferry_deferred_tasks.append(deferred_task)

arun

async
arun(
    *args: Tuple[Any, ...],
    feedback_data: Optional[
        Union[
            InteractionFeedback, List[InteractionFeedback]
        ]
    ] = None,
    **kwargs: Dict[str, Any]
) -> Any

The entry point for running the constructed GraphAutoma instance.

This method serves as the entry point for both initial execution and resumption after interruption of an automa instance. It automatically drives the execution of workers based on their dependencies and explicit ferry_to() calls. Each execution will be wrapped in an asyncio.Task to ensure context isolation.

Automatic Scheduling

The scheduling behavior in GraphAutoma is automatically driven by:

  • Worker dependencies: Workers are scheduled to run only after all their necessary dependencies are satisfied. The dependencies automatically drive the execution order.

  • Calling ferry_to: During execution, a worker can explicitly trigger another worker by calling ferry_to(), which enables dynamic flow control and conditional branching.

  • Dynamic topology changes: When the graph topology is modified at runtime (such as adding or removing workers or dependencies), the scheduling system seamlessly updates to reflect the latest structure, ensuring that worker execution always follows the current graph.

Human Interaction Mechanism

Workers can request human input by calling interact_with_human() during execution. When this occurs:

  • The execution will be paused after the running workers finish their execution.
  • The Automa's state will be serialized into a Snapshot object.
  • An InteractionException will be raised to the application layer. It contains both the list of pending Interaction objects and the Snapshot object.
  • The application layer may persist the Snapshot properly to resume the execution later.
  • To resume execution, the application layer should reload the Automa state using load_from_snapshot() with the saved Snapshot object and call arun() again with feedback_data containing the user's feedback(s) to finish a complete interaction.

Parameters:

Name Type Description Default
args optional

Positional arguments to be passed.

()
feedback_data Optional[Union[InteractionFeedback, List[InteractionFeedback]]]

Feedbacks that are received from one or multiple human interactions occurred before the Automa was paused. This argument may be of type InteractionFeedback or List[InteractionFeedback]. If only one interaction occurred, feedback_data should be of type InteractionFeedback. If multiple interactions occurred simultaneously, feedback_data should be of type List[InteractionFeedback].

None
kwargs optional

Keyword arguments which may be further propagated to contained workers.

{}

Returns:

Type Description
Any

The execution result of the output-worker that has the setting is_output=True, otherwise None.

Raises:

Type Description
InteractionException

If the Automa is the top-level Automa and the interact_with_human() method is called by one or more workers within the lastest event loop iteration, this exception will be raised to the application layer.

Source code in bridgic/core/automa/_graph_automa.py
async def arun(
    self,
    *args: Tuple[Any, ...],
    feedback_data: Optional[Union[InteractionFeedback, List[InteractionFeedback]]] = None,
    **kwargs: Dict[str, Any]
) -> Any:
    """
    The entry point for running the constructed `GraphAutoma` instance.

    This method serves as the entry point for both initial execution and resumption after 
    interruption of an automa instance. It automatically drives the execution of workers 
    based on their `dependencies` and explicit `ferry_to()` calls. Each execution will be 
    wrapped in an `asyncio.Task` to ensure context isolation.

    **Automatic Scheduling**

    The scheduling behavior in `GraphAutoma` is automatically driven by:

    - Worker dependencies: Workers are scheduled to run only after all their necessary 
      dependencies are satisfied. The dependencies automatically drive the execution order.

    - Calling ferry_to: During execution, a worker can explicitly trigger another worker 
      by calling `ferry_to()`, which enables dynamic flow control and conditional branching.

    - Dynamic topology changes: When the graph topology is modified at runtime (such as 
      adding or removing workers or dependencies), the scheduling system seamlessly updates 
      to reflect the latest structure, ensuring that worker execution always follows the 
      current graph.

    **Human Interaction Mechanism**

    Workers can request human input by calling `interact_with_human()` during execution. 
    When this occurs:

    - The execution will be paused after the running workers finish their execution.
    - The Automa's state will be serialized into a `Snapshot` object.
    - An `InteractionException` will be raised to the application layer. It contains both the 
      list of pending `Interaction` objects and the `Snapshot` object.
    - The application layer may persist the `Snapshot` properly to resume the execution later.
    - To resume execution, the application layer should reload the Automa state using 
      `load_from_snapshot()` with the saved `Snapshot` object and call `arun()` again with 
      `feedback_data` containing the user's feedback(s) to finish a complete interaction.

    Parameters
    ----------
    args : optional
        Positional arguments to be passed.
    feedback_data : Optional[Union[InteractionFeedback, List[InteractionFeedback]]]
        Feedbacks that are received from one or multiple human interactions occurred before the
        Automa was paused. This argument may be of type `InteractionFeedback` or 
        `List[InteractionFeedback]`. If only one interaction occurred, `feedback_data` should be
        of type `InteractionFeedback`. If multiple interactions occurred simultaneously, 
        `feedback_data` should be of type `List[InteractionFeedback]`.
    kwargs : optional
        Keyword arguments which may be further propagated to contained workers.

    Returns
    -------
    Any
        The execution result of the output-worker that has the setting `is_output=True`,
        otherwise None.

    Raises
    ------
    InteractionException
        If the Automa is the top-level Automa and the `interact_with_human()` method is called
        by one or more workers within the lastest event loop iteration, this exception will be
        raised to the application layer.
    """
    if self.is_top_level():
        # For top-level automa, wrap in a task to ensure context isolation
        task = asyncio.create_task(
            self._arun_internal(*args, feedback_data=feedback_data, **kwargs),
            name=f"GraphAutoma-{self.name}-arun"
        )
        return await task
    else:
        # For nested automa, directly call _arun_internal to avoid redundant task creation
        return await self._arun_internal(*args, feedback_data=feedback_data, **kwargs)

WorkerSignatureError

Bases: Exception

Raised when invalid signature is detected in the case of defining a worker.

Source code in bridgic/core/types/_error.py
5
6
7
8
9
class WorkerSignatureError(Exception):
    """
    Raised when invalid signature is detected in the case of defining a worker.
    """
    pass

WorkerArgsMappingError

Bases: Exception

Raised when the parameters declaration of a worker does not meet the requirements of the arguments mapping rule.

Source code in bridgic/core/types/_error.py
class WorkerArgsMappingError(Exception):
    """
    Raised when the parameters declaration of a worker does not meet the requirements of the arguments mapping rule.
    """
    pass

WorkerArgsInjectionError

Bases: Exception

Raised when the arguments injection mechanism encountered an error during operation.

Source code in bridgic/core/types/_error.py
class WorkerArgsInjectionError(Exception):
    """
    Raised when the arguments injection mechanism encountered an error during operation.
    """
    pass

WorkerRuntimeError

Bases: RuntimeError

Raised when the worker encounters an unexpected error during runtime.

Source code in bridgic/core/types/_error.py
class WorkerRuntimeError(RuntimeError):
    """
    Raised when the worker encounters an unexpected error during runtime.
    """
    pass

AutomaDeclarationError

Bases: Exception

Raised when the declaration of workers within an Automa is not valid.

Source code in bridgic/core/types/_error.py
class AutomaDeclarationError(Exception):
    """
    Raised when the declaration of workers within an Automa is not valid.
    """
    pass

AutomaCompilationError

Bases: Exception

Raised when the compilation or validation of an Automa fails.

Source code in bridgic/core/types/_error.py
class AutomaCompilationError(Exception):
    """
    Raised when the compilation or validation of an Automa fails.
    """
    pass

AutomaRuntimeError

Bases: RuntimeError

Raised when the execution of an Automa encounters an unexpected error.

Source code in bridgic/core/types/_error.py
class AutomaRuntimeError(RuntimeError):
    """
    Raised when the execution of an Automa encounters an unexpected error.
    """
    pass

worker

worker(**kwargs) -> Callable

Decorator for marking a method inside an Automa class as a worker.

To cover the need to declare workers in various Automa classes, this decorator actually accepts a variable kwargs parameter. Through overloading, it further supports specifying the parameters that need to be passed in when registering a worker under a specific Automa, such as ConcurrentAutoma, SequentialAutoma and so on.

Parameters:

Name Type Description Default
kwargs Dict[str, Any]

The keyword arguments for the worker decorator.

{}
Source code in bridgic/core/automa/worker/_worker_decorator.py
def worker(**kwargs) -> Callable:
    """
    Decorator for marking a method inside an Automa class as a worker.

    To cover the need to declare workers in various Automa classes, this decorator actually 
    accepts a variable kwargs parameter. Through overloading, it further supports specifying 
    the parameters that need to be passed in when registering a worker under a specific Automa, 
    such as `ConcurrentAutoma`, `SequentialAutoma` and so on.

    Parameters
    ----------
    kwargs : Dict[str, Any]
        The keyword arguments for the worker decorator.
    """
    def wrapper(func: Callable):
        setattr(func, "__worker_kwargs__", kwargs)
        return func
    return wrapper