worker¶
The Worker module defines the Worker concept and its related implementations in Automa.
This module provides the core abstractions and implementations of Worker, including:
- Worker: The base class for all workers, which is the basic execution unit in Automa, defining the execution interface (
arun()andrun()methods) for nodes - CallableWorker: A worker implementation for wrapping callable objects (functions or methods)
- WorkerCallback: A callback interface during worker execution, supporting validation, monitoring, and log collection before and after execution
- WorkerCallbackBuilder: A builder for constructing and configuring worker callbacks
T_WorkerCallback module-attribute ¶
Type variable for WorkerCallback subclasses.
Worker ¶
Bases: Serializable
This class is the base class for all workers.
Worker has two methods that may be overridden by the subclass:
-
arun(): This asynchronous method should be implemented when your worker does not require almost immediately scheduling after all its task dependencies are fulfilled, and when overall workflow is not sensitive to the fair sharing of CPU resources between workers. If workers can afford to retain and occupy execution resources for their entire execution duration, and there is no explicit need for fair CPU time-sharing or timely scheduling, you should implementarun()and allow workers to run to completion as cooperative tasks within the event loop. -
run(): This synchronous method should be implemented when either of the following holds:-
a. The automa includes other workers that require timely access to CPU resources (for example, workers that must respond quickly or are sensitive to scheduling latency).
-
b. The current worker itself should be scheduled as soon as all its task dependencies are met, to maintain overall workflow responsiveness. In these cases,
run()enables the framework to offload your worker to a thread pool, ensuring that CPU time is shared fairly among all such workers and the event loop remains responsive.
-
In summary, if you are unsure whether your task require quickly scheduling or not, it is recommended to implement the arun() method. Otherwise, implement the run() ONLY if you are certain that you agree to share CPU time slices with other workers.
Source code in bridgic/core/automa/worker/_worker.py
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 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 | |
arun ¶
async The asynchronous method to run the worker.
Source code in bridgic/core/automa/worker/_worker.py
run ¶
The synchronous method to run the worker.
is_top_level ¶
Check if the current worker is the top-level worker.
Returns:
| Type | Description |
|---|---|
bool | True if the current worker is the top-level worker (parent is self), False otherwise. |
Source code in bridgic/core/automa/worker/_worker.py
get_input_param_names ¶
Get the names of input parameters of the worker. Use cached result if available in order to improve performance.
This method intelligently detects whether the user has overridden the run method or is using the default arun method, and returns the appropriate parameter signature.
Returns:
| Type | Description |
|---|---|
Dict[_ParameterKind, List[str]] | A dictionary of input parameter names by the kind of the parameter. The key is the kind of the parameter, which is one of five possible values:
|
Source code in bridgic/core/automa/worker/_worker.py
ferry_to ¶
Handoff control flow to the specified worker, passing along any arguments as needed. The specified worker will always start to run asynchronously in the next event loop, regardless of its dependencies.
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. | {} |
Source code in bridgic/core/automa/worker/_worker.py
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 in a non-async method or 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/worker/_worker.py
request_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 post_event should only be called from within a non-async method running in the 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 |
Source code in bridgic/core/automa/worker/_worker.py
request_feedback_async ¶
async 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, in the main thread.
Note that post_event should only be called from within an asynchronous method running in the main event loop of the top-level Automa.
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 |
Source code in bridgic/core/automa/worker/_worker.py
CallableWorker ¶
Bases: Worker
This class is a worker that wraps a callable object, such as functions or methods.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
func_or_method | Optional[Callable] | The callable to be wrapped by the worker. If | None |
Source code in bridgic/core/automa/worker/_callable_worker.py
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 | |
get_input_param_names ¶
Get the names of input parameters of this callable worker. Use cached result if available in order to improve performance.
Returns:
| Type | Description |
|---|---|
Dict[_ParameterKind, List[str]] | A dictionary of input parameter names by the kind of the parameter. The key is the kind of the parameter, which is one of five possible values:
|
Source code in bridgic/core/automa/worker/_callable_worker.py
WorkerCallback ¶
Bases: Serializable
Callback for the execution of a worker instance during the running of a prebult automa.
This class defines the interfaces that will be called before or after the execution of the corresponding worker. Callbacks are typically used for validating input, monitoring execution, and collecting logs, etc.
Methods:
| Name | Description |
|---|---|
on_worker_start | Hook invoked before worker execution. |
on_worker_end | Hook invoked after worker execution. |
on_worker_error | Hook invoked when worker execution raises an exception. |
Source code in bridgic/core/automa/worker/_worker_callback.py
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 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 | |
on_worker_start ¶
async on_worker_start(
key: str,
is_top_level: bool = False,
parent: Optional[Automa] = None,
arguments: Dict[str, Any] = None,
) -> None
Hook invoked before worker execution.
Called immediately before the worker runs. Use for arguments validation, logging, or monitoring. Cannot modify execution arguments or logic.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key | str | Worker identifier. | required |
is_top_level | bool | Whether the worker is the top-level automa. When True, parent will be the automa itself (parent is self). | False |
parent | Optional[Automa] = None | Parent automa instance containing this worker. For top-level automa, parent is the automa itself. | None |
arguments | Dict[str, Any] = None | Execution parameters with keys "args" and "kwargs". | None |
Source code in bridgic/core/automa/worker/_worker_callback.py
on_worker_end ¶
async on_worker_end(
key: str,
is_top_level: bool = False,
parent: Optional[Automa] = None,
arguments: Dict[str, Any] = None,
result: Any = None,
) -> None
Hook invoked after worker execution.
Called immediately after the worker completes. Use for result monitoring, logging, event publishing, or validation. Cannot modify execution results or logic.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key | str | Worker identifier. | required |
is_top_level | bool | Whether the worker is the top-level automa. When True, parent will be the automa itself (parent is self). | False |
parent | Optional[Automa] = None | Parent automa instance containing this worker. For top-level automa, parent is the automa itself. | None |
arguments | Dict[str, Any] = None | Execution arguments with keys "args" and "kwargs". | None |
result | Any = None | Worker execution result. | None |
Source code in bridgic/core/automa/worker/_worker_callback.py
on_worker_error ¶
async on_worker_error(
key: str,
is_top_level: bool = False,
parent: Optional[Automa] = None,
arguments: Dict[str, Any] = None,
error: Exception = None,
) -> bool
Hook invoked when worker execution raises an exception.
Called when the worker execution raises an exception. Use for error handling, logging, or event publishing. Cannot modify execution logic or arguments.
Exception Matching Mechanism: How to Handle a Specific Exception
The framework enable your callback to handle a given exception based on the type annotation of the error parameter in your on_worker_error method. The matching follows these rules:
- The parameter name MUST be
errorand the type annotation is critical for the matching mechanism. - If you annotate
error: ValueError, it will matchValueErrorand all its subclasses (e.g.,UnicodeDecodeError). - If you annotate
error: Exception, it will match all exceptions (since all exceptions inherit from Exception). - If you want to match multiple exception types, you can use
Union[Type1, Type2, ...].
Return Value: Whether to Suppress the Exception
- If
on_worker_errorreturnsTrue, the framework will suppress the exception. The framework will then proceed as if there was no error, and the worker result will be set to None. - If
on_worker_errorreturnsFalse, the framework will simply observe the error; after all matching callbacks are called, the framework will re-raise the exception.
Special Case: Interaction Exceptions Cannot Be Suppressed
To ensure human-interaction mechanisms work correctly, exceptions of type _InteractionEventException or InteractionException (including their subclasses) CANNOT be suppressed by any callback. Even if your callback returns True, the framework will forcibly re-raise the exception. This ensures these exceptions always propagate correctly through the automa hierarchy to trigger necessary human interactions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key | str | Worker identifier. | required |
is_top_level | bool | Whether the worker is the top-level automa. When True, parent will be the automa itself (parent is self). | False |
parent | Optional[Automa] = None | Parent automa instance containing this worker. For top-level automa, parent is the automa itself. | None |
arguments | Dict[str, Any] = None | Execution arguments with keys "args" and "kwargs". | None |
error | Exception = None | The exception raised during worker execution. The type annotation of this parameter determines which exceptions this callback will handle. The matching is based on inheritance relationship (using isinstance), so a callback with | None |
Returns:
| Type | Description |
|---|---|
bool | True if the automa should suppress the exception (not re-raise it); False otherwise. |
Source code in bridgic/core/automa/worker/_worker_callback.py
WorkerCallbackBuilder ¶
Bases: Generic[T_WorkerCallback]
Builder class for creating instances of WorkerCallback subclasses.
This builder is designed to construct instances of subclasses of WorkerCallback. The _callback_type parameter should be a subclass of WorkerCallback, and build() will return an instance of that specific subclass. There is no need to call build() directly. Instead, the framework calls the build method automatically to create its own WorkerCallback instance for each worker instance.
Notes
Register a Callback in Different Scope
There are three ways to register a callback for three levels of customization:
- Case 1: Use in worker decorator to register the callback for a specific worker.
- Case 2: Use in RunningOptions to register the callback for a specific Automa instance.
- Case 3: Use in GlobalSetting to register the callback for all workers.
Notes
Shared Instance Mode
- When
is_shared=True(default), all workers within the same scope will share the same callback instance. This is useful for scenarios where a single callback instance is needed to maintain some state across workers within the same scope, such as the connection to an external service. The scope is determined by where the builder is declared: - If declared in GlobalSetting: shared across all workers globally
- If declared in RunningOptions: shared across all workers within that Automa instance
- When
is_shared=False, each worker will get its own callback instance. This is useful for scenarios where a independent callback instance is needed for each worker.
Examples:
There are three ways to use the builder, for different levels of customization:
Source code in bridgic/core/automa/worker/_worker_callback.py
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 | |
build ¶
build() -> T_WorkerCallback
Build and return an instance of the specified WorkerCallback subclass.
Returns:
| Type | Description |
|---|---|
T_WorkerCallback | An instance of the |