novastack-workflows 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (28) hide show
  1. novastack_workflows-0.1.0/.gitignore +85 -0
  2. novastack_workflows-0.1.0/LICENSE +176 -0
  3. novastack_workflows-0.1.0/PKG-INFO +136 -0
  4. novastack_workflows-0.1.0/README.md +109 -0
  5. novastack_workflows-0.1.0/novastack_workflows/__init__.py +14 -0
  6. novastack_workflows-0.1.0/novastack_workflows/context/__init__.py +3 -0
  7. novastack_workflows-0.1.0/novastack_workflows/context/context.py +133 -0
  8. novastack_workflows-0.1.0/novastack_workflows/context/state_store.py +193 -0
  9. novastack_workflows-0.1.0/novastack_workflows/decorators.py +182 -0
  10. novastack_workflows-0.1.0/novastack_workflows/enums.py +7 -0
  11. novastack_workflows-0.1.0/novastack_workflows/events.py +35 -0
  12. novastack_workflows-0.1.0/novastack_workflows/exceptions.py +18 -0
  13. novastack_workflows-0.1.0/novastack_workflows/prebuilt/__init__.py +13 -0
  14. novastack_workflows-0.1.0/novastack_workflows/prebuilt/document_ingestion.py +286 -0
  15. novastack_workflows-0.1.0/novastack_workflows/runtime/__init__.py +5 -0
  16. novastack_workflows-0.1.0/novastack_workflows/runtime/engine.py +558 -0
  17. novastack_workflows-0.1.0/novastack_workflows/runtime/event_buffer.py +192 -0
  18. novastack_workflows-0.1.0/novastack_workflows/runtime/execution_pool.py +142 -0
  19. novastack_workflows-0.1.0/novastack_workflows/schemas.py +93 -0
  20. novastack_workflows-0.1.0/novastack_workflows/server/__init__.py +7 -0
  21. novastack_workflows-0.1.0/novastack_workflows/server/_api/__init__.py +0 -0
  22. novastack_workflows-0.1.0/novastack_workflows/server/_api/models.py +66 -0
  23. novastack_workflows-0.1.0/novastack_workflows/server/_api/routes.py +108 -0
  24. novastack_workflows-0.1.0/novastack_workflows/server/_registry.py +98 -0
  25. novastack_workflows-0.1.0/novastack_workflows/server/exceptions.py +5 -0
  26. novastack_workflows-0.1.0/novastack_workflows/server/server.py +74 -0
  27. novastack_workflows-0.1.0/novastack_workflows/workflow.py +274 -0
  28. novastack_workflows-0.1.0/pyproject.toml +133 -0
@@ -0,0 +1,85 @@
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ #IDE
10
+ .DS_Store
11
+ .idea
12
+ .vscode
13
+
14
+ # Distribution / packaging
15
+ .Python
16
+ build/
17
+ develop-eggs/
18
+ dist/
19
+ downloads/
20
+ eggs/
21
+ .eggs/
22
+ lib/
23
+ lib64/
24
+ parts/
25
+ sdist/
26
+ var/
27
+ wheels/
28
+ share/python-wheels/
29
+ *.egg-info/
30
+ .installed.cfg
31
+ *.egg
32
+ MANIFEST
33
+
34
+ # PyInstaller
35
+ # Usually these files are written by a python script from a template
36
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
37
+ *.manifest
38
+ *.spec
39
+
40
+ # Installer logs
41
+ pip-log.txt
42
+ pip-delete-this-directory.txt
43
+
44
+ # Unit test / coverage reports
45
+ htmlcov/
46
+ .tox/
47
+ .nox/
48
+ .coverage
49
+ .coverage.*
50
+ .cache
51
+ nosetests.xml
52
+ coverage.xml
53
+ *.cover
54
+ *.py,cover
55
+ .hypothesis/
56
+ .pytest_cache/
57
+ cover/
58
+
59
+ # Mkdocs documentation
60
+ docs/_build/
61
+ docs/api_reference/site/
62
+
63
+ # Ruff
64
+ .ruff_cache/
65
+
66
+ # PyBuilder
67
+ .pybuilder/
68
+ target/
69
+
70
+ # Jupyter Notebook
71
+ .ipynb_checkpoints
72
+
73
+ # pyenv
74
+ # For a library or package, you might want to ignore these files since the code is
75
+ # intended to run in multiple environments; otherwise, check them in:
76
+ .python-version
77
+
78
+ # Environments
79
+ .env
80
+ .venv
81
+ env/
82
+ venv/
83
+ ENV/
84
+ env.bak/
85
+ venv.bak/
@@ -0,0 +1,176 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
@@ -0,0 +1,136 @@
1
+ Metadata-Version: 2.4
2
+ Name: novastack-workflows
3
+ Version: 0.1.0
4
+ Summary: A workflow engine to run AI applications with event-driven, stepwise control.
5
+ Project-URL: Repository, https://github.com/novastack-project/novastack/tree/main/novastack-workflows
6
+ Author-email: Leonardo Furnielis <leonardofurnielis@outlook.com>
7
+ License: Apache-2.0
8
+ License-File: LICENSE
9
+ Keywords: AI,LLM,QA,RAG,data,retrieval,semantic-search,workflows
10
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
11
+ Classifier: Topic :: Software Development :: Libraries :: Application Frameworks
12
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
13
+ Requires-Python: <3.14,>=3.11
14
+ Requires-Dist: novastack-instrumentation<0.2.0,>=0.1.0
15
+ Requires-Dist: novastack-utils<0.2.0,>=0.1.0
16
+ Requires-Dist: pydantic<3.0.0,>=2.12.5
17
+ Provides-Extra: dev
18
+ Requires-Dist: httpx<1,>=0.28.1; extra == 'dev'
19
+ Requires-Dist: pyright<1.2.0,>=1.1.409; extra == 'dev'
20
+ Requires-Dist: pytest-asyncio<2.0.0,>=1.3.0; extra == 'dev'
21
+ Requires-Dist: pytest<10.0.0,>=9.0.3; extra == 'dev'
22
+ Requires-Dist: ruff<1.0.0,>=0.15.8; extra == 'dev'
23
+ Provides-Extra: server
24
+ Requires-Dist: fastapi<1,>=0.136.3; extra == 'server'
25
+ Requires-Dist: uvicorn[standard]<1,>=0.49.0; extra == 'server'
26
+ Description-Content-Type: text/markdown
27
+
28
+ <div align="center">
29
+ <img alt="Novastack workflows Logo" src=".github/images/logo-light.png" width="65%">
30
+ </div>
31
+
32
+ <div align="center">
33
+ <h3>A powerful and flexible event-driven workflow engine for Python, designed to build complex asynchronous workflows with ease.</h3>
34
+ </div>
35
+
36
+ <div align="center">
37
+ <img src="https://img.shields.io/pypi/v/novastack-workflows" alt="PyPI - Version">
38
+ <img src="https://github.com/novastack-project/novastack-workflows/actions/workflows/test.yml/badge.svg" alt="Testing">
39
+ <img
40
+ src="https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json"
41
+ alt="Ruff">
42
+ <img src="https://img.shields.io/pepy/dt/novastack-workflows" alt="Pepy Total Downloads">
43
+ <img src="https://img.shields.io/pypi/l/novastack-workflows" alt="PyPI - License">
44
+ </div>
45
+
46
+ ## Installation
47
+
48
+ ```bash
49
+ pip install novastack-workflows
50
+ ```
51
+
52
+ ## Quick Start
53
+
54
+ Here's a simple example to get you started with Novastack Workflows:
55
+
56
+ ```python
57
+ from novastack_workflows import Workflow, Context, step
58
+ from novastack_workflows.events import Event, StartEvent, StopEvent
59
+
60
+
61
+ class MessageEvent(Event):
62
+ message: str
63
+
64
+ class MyWorkflow(Workflow):
65
+
66
+ @step(when=StartEvent)
67
+ async def start(self, ctx: Context, ev: StartEvent) -> MessageEvent:
68
+
69
+ input_msg = ev.get("message", "")
70
+ return MessageEvent(message=f"Processed: {input_msg}")
71
+
72
+ @step(when=MessageEvent)
73
+ async def process(self, ctx: Context, ev: MessageEvent) -> StopEvent:
74
+ return StopEvent(result=ev.message)
75
+
76
+
77
+ async def main():
78
+ workflow = MyWorkflow()
79
+ result = await workflow.run(input_msg="Hello, World!")
80
+
81
+ print(result)
82
+ ```
83
+
84
+ ## Core Concepts
85
+
86
+ ### Workflow
87
+
88
+ A workflow is a class that inherits from `Workflow` and contains one or more steps. It orchestrates the execution of steps based on events.
89
+
90
+ ### Steps
91
+
92
+ Steps are asynchronous methods decorated with `@step(when=EventType)` that define what happens when a specific event is received.
93
+
94
+ - Steps receive a `Context` and an `Event`.
95
+ - Steps can return new events to trigger subsequent steps.
96
+
97
+ ### Events
98
+
99
+ Events are the building blocks of workflows. They carry data between steps and trigger step execution.
100
+
101
+ - **StartEvent**: Automatically triggered when a workflow starts
102
+ - **StopEvent**: Signals the end of a workflow and carries the final result
103
+ - **Custom Events**: Define your own events by inheriting from `Event`
104
+
105
+ ### Context
106
+
107
+ The `Context` object provides access to workflow state and allows steps to share data throughout the workflow execution.
108
+
109
+ ```python
110
+ # Read-only access
111
+ current_value = ctx.state.count
112
+
113
+ # Edit state
114
+ async with ctx.store.edit_state() as state:
115
+ state.count = current_counter + 1
116
+
117
+ # Send events
118
+ ctx.send_event(MyEvent(...))
119
+ ```
120
+
121
+ ## Features
122
+
123
+ | Feature | Novastack Workflows |
124
+ | ---------------------- | ----------------------- |
125
+ | Event-driven execution | ✅ |
126
+ | Fan-out (parallelism) | ✅ |
127
+ | Async execution | ✅ |
128
+ | Shared state | ✅ |
129
+ | Event joins | ✅ |
130
+ | Internal buffer | ✅ |
131
+ | Declarative API | ✅ |
132
+ | Observability | ✅ |
133
+
134
+ ## License
135
+
136
+ Apache License 2.0
@@ -0,0 +1,109 @@
1
+ <div align="center">
2
+ <img alt="Novastack workflows Logo" src=".github/images/logo-light.png" width="65%">
3
+ </div>
4
+
5
+ <div align="center">
6
+ <h3>A powerful and flexible event-driven workflow engine for Python, designed to build complex asynchronous workflows with ease.</h3>
7
+ </div>
8
+
9
+ <div align="center">
10
+ <img src="https://img.shields.io/pypi/v/novastack-workflows" alt="PyPI - Version">
11
+ <img src="https://github.com/novastack-project/novastack-workflows/actions/workflows/test.yml/badge.svg" alt="Testing">
12
+ <img
13
+ src="https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json"
14
+ alt="Ruff">
15
+ <img src="https://img.shields.io/pepy/dt/novastack-workflows" alt="Pepy Total Downloads">
16
+ <img src="https://img.shields.io/pypi/l/novastack-workflows" alt="PyPI - License">
17
+ </div>
18
+
19
+ ## Installation
20
+
21
+ ```bash
22
+ pip install novastack-workflows
23
+ ```
24
+
25
+ ## Quick Start
26
+
27
+ Here's a simple example to get you started with Novastack Workflows:
28
+
29
+ ```python
30
+ from novastack_workflows import Workflow, Context, step
31
+ from novastack_workflows.events import Event, StartEvent, StopEvent
32
+
33
+
34
+ class MessageEvent(Event):
35
+ message: str
36
+
37
+ class MyWorkflow(Workflow):
38
+
39
+ @step(when=StartEvent)
40
+ async def start(self, ctx: Context, ev: StartEvent) -> MessageEvent:
41
+
42
+ input_msg = ev.get("message", "")
43
+ return MessageEvent(message=f"Processed: {input_msg}")
44
+
45
+ @step(when=MessageEvent)
46
+ async def process(self, ctx: Context, ev: MessageEvent) -> StopEvent:
47
+ return StopEvent(result=ev.message)
48
+
49
+
50
+ async def main():
51
+ workflow = MyWorkflow()
52
+ result = await workflow.run(input_msg="Hello, World!")
53
+
54
+ print(result)
55
+ ```
56
+
57
+ ## Core Concepts
58
+
59
+ ### Workflow
60
+
61
+ A workflow is a class that inherits from `Workflow` and contains one or more steps. It orchestrates the execution of steps based on events.
62
+
63
+ ### Steps
64
+
65
+ Steps are asynchronous methods decorated with `@step(when=EventType)` that define what happens when a specific event is received.
66
+
67
+ - Steps receive a `Context` and an `Event`.
68
+ - Steps can return new events to trigger subsequent steps.
69
+
70
+ ### Events
71
+
72
+ Events are the building blocks of workflows. They carry data between steps and trigger step execution.
73
+
74
+ - **StartEvent**: Automatically triggered when a workflow starts
75
+ - **StopEvent**: Signals the end of a workflow and carries the final result
76
+ - **Custom Events**: Define your own events by inheriting from `Event`
77
+
78
+ ### Context
79
+
80
+ The `Context` object provides access to workflow state and allows steps to share data throughout the workflow execution.
81
+
82
+ ```python
83
+ # Read-only access
84
+ current_value = ctx.state.count
85
+
86
+ # Edit state
87
+ async with ctx.store.edit_state() as state:
88
+ state.count = current_counter + 1
89
+
90
+ # Send events
91
+ ctx.send_event(MyEvent(...))
92
+ ```
93
+
94
+ ## Features
95
+
96
+ | Feature | Novastack Workflows |
97
+ | ---------------------- | ----------------------- |
98
+ | Event-driven execution | ✅ |
99
+ | Fan-out (parallelism) | ✅ |
100
+ | Async execution | ✅ |
101
+ | Shared state | ✅ |
102
+ | Event joins | ✅ |
103
+ | Internal buffer | ✅ |
104
+ | Declarative API | ✅ |
105
+ | Observability | ✅ |
106
+
107
+ ## License
108
+
109
+ Apache License 2.0
@@ -0,0 +1,14 @@
1
+ # Context management
2
+ from novastack_workflows.context import Context
3
+ from novastack_workflows.decorators import step
4
+ from novastack_workflows.events import Event, StartEvent, StopEvent
5
+ from novastack_workflows.workflow import Workflow
6
+
7
+ __all__ = [
8
+ "Workflow",
9
+ "Context",
10
+ "step",
11
+ "Event",
12
+ "StartEvent",
13
+ "StopEvent",
14
+ ]
@@ -0,0 +1,3 @@
1
+ from novastack_workflows.context.context import Context
2
+
3
+ __all__ = ["Context"]
@@ -0,0 +1,133 @@
1
+ import asyncio
2
+ from typing import TYPE_CHECKING, Any, Generic, TypeVar
3
+
4
+ from pydantic import BaseModel, Field
5
+
6
+ from novastack_workflows.context.state_store import InMemoryStateStore
7
+
8
+ if TYPE_CHECKING:
9
+ from novastack_workflows.events import Event
10
+
11
+ STATE_T = TypeVar("STATE_T", bound=BaseModel)
12
+
13
+ class SerializedContext(BaseModel):
14
+
15
+ version: str = "1.0.0"
16
+ kind: str = "Context"
17
+ state: dict = Field(default_factory=dict)
18
+
19
+ class Context(Generic[STATE_T]):
20
+ """
21
+ Workflow execution context with copy-on-write state management.
22
+
23
+ Provides robust, immutable state management through 'state_store'.
24
+
25
+ State is automatically initialized based on the type annotation.
26
+ If no type is provided, uses DictState.
27
+
28
+ Example:
29
+ ```python
30
+ class RunState(BaseModel):
31
+ counter: int = 0
32
+ items: list[str] = []
33
+
34
+
35
+ # With typed state - auto-initialized
36
+ @step
37
+ async def start(self, ctx: Context[RunState], ev: StartEvent):
38
+ async with ctx.store.edit_state() as state:
39
+ state.counter += 1 # RunState auto-initialized
40
+
41
+
42
+ @step
43
+ async def start(self, ctx: Context, ev: StartEvent):
44
+ async with ctx.store.edit_state() as state:
45
+ state.counter = 1
46
+ ```
47
+ """
48
+
49
+ def __init__(
50
+ self,
51
+ workflow: Any,
52
+ event_queue: asyncio.Queue["Event"] | Any | None = None,
53
+ ):
54
+ """
55
+ Initialize workflow context.
56
+
57
+ Each context is isolated and maintains its own state store.
58
+ State type is inferred from Context[StateType] annotation or defaults to DictState.
59
+
60
+ Args:
61
+ workflow: Workflow instance
62
+ event_queue: Event queue for emission
63
+ """
64
+ self._workflow = workflow
65
+
66
+ # Use provided queue or create asyncio.Queue
67
+ if event_queue is None:
68
+ self._event_queue: asyncio.Queue[Event] = asyncio.Queue()
69
+ else:
70
+ self._event_queue = event_queue
71
+
72
+ # Copy-on-write state store with auto-initialization
73
+ # Infer state type from workflow's _state_type if available
74
+ state_type = getattr(workflow, "_state_type", None)
75
+ self._store = InMemoryStateStore(state_type=state_type)
76
+
77
+ @property
78
+ def workflow(self) -> Any:
79
+ """Get workflow instance."""
80
+ return self._workflow
81
+
82
+ @property
83
+ def store(self): # type: ignore[return]
84
+ """
85
+ Copy-on-write state store.
86
+
87
+ Provides immutability guarantees and thread-safety through
88
+ explicit edit contexts.
89
+
90
+ Example:
91
+ ```python
92
+ # Edit state
93
+ async with ctx.store.edit_state() as state:
94
+ state.counter += 1
95
+ ```
96
+ """
97
+ return self._store
98
+
99
+ @property
100
+ def state(self) -> BaseModel | None:
101
+ """
102
+ Get current state (read-only).
103
+
104
+ Convenience property for accessing store state.
105
+ Equivalent to ctx.store.state.
106
+
107
+ Example:
108
+ ```python
109
+ # Read-only access
110
+ current_value = ctx.state.counter
111
+ ```
112
+ """
113
+ return self._store.state
114
+
115
+ async def send_event(self, event: "Event") -> None:
116
+ """
117
+ Send an event to the workflow queue.
118
+
119
+ Args:
120
+ event(Event): Event to send
121
+
122
+ Example:
123
+ ```python
124
+ await ctx.send_event(MyEvent(data="processed"))
125
+ ```
126
+ """
127
+ await self._event_queue.put(event)
128
+
129
+ def to_dict(self) -> dict[str, Any]:
130
+ """Serialize context to dictionary."""
131
+ return SerializedContext(
132
+ state=self._store.to_dict()
133
+ ).model_dump()