loom-workflow 0.3.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.
- loom_workflow-0.3.0/PKG-INFO +221 -0
- loom_workflow-0.3.0/README.md +212 -0
- loom_workflow-0.3.0/loom/__init__.py +25 -0
- loom_workflow-0.3.0/loom/agent/__init__.py +17 -0
- loom_workflow-0.3.0/loom/agent/loop.py +129 -0
- loom_workflow-0.3.0/loom/agent/provider.py +70 -0
- loom_workflow-0.3.0/loom/agent/task_gen.py +101 -0
- loom_workflow-0.3.0/loom/core/__init__.py +18 -0
- loom_workflow-0.3.0/loom/core/contract.py +103 -0
- loom_workflow-0.3.0/loom/core/pipeline.py +111 -0
- loom_workflow-0.3.0/loom/core/result.py +40 -0
- loom_workflow-0.3.0/loom/core/task.py +34 -0
- loom_workflow-0.3.0/loom/graphite/__init__.py +18 -0
- loom_workflow-0.3.0/loom/graphite/match_strategy.py +110 -0
- loom_workflow-0.3.0/loom/graphite/processor.py +343 -0
- loom_workflow-0.3.0/loom/graphite/schema.py +201 -0
- loom_workflow-0.3.0/loom/graphite/schema_constraints.py +34 -0
- loom_workflow-0.3.0/loom/graphite/schema_contract.py +21 -0
- loom_workflow-0.3.0/loom_workflow.egg-info/PKG-INFO +221 -0
- loom_workflow-0.3.0/loom_workflow.egg-info/SOURCES.txt +23 -0
- loom_workflow-0.3.0/loom_workflow.egg-info/dependency_links.txt +1 -0
- loom_workflow-0.3.0/loom_workflow.egg-info/requires.txt +2 -0
- loom_workflow-0.3.0/loom_workflow.egg-info/top_level.txt +1 -0
- loom_workflow-0.3.0/pyproject.toml +17 -0
- loom_workflow-0.3.0/setup.cfg +4 -0
|
@@ -0,0 +1,221 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: loom-workflow
|
|
3
|
+
Version: 0.3.0
|
|
4
|
+
Summary: Task orchestration, contracts
|
|
5
|
+
Requires-Python: >=3.10
|
|
6
|
+
Description-Content-Type: text/markdown
|
|
7
|
+
Requires-Dist: pydantic>=2
|
|
8
|
+
Requires-Dist: pydantic-ai>=1
|
|
9
|
+
|
|
10
|
+
# Loom
|
|
11
|
+
|
|
12
|
+
Loom provides small, domain-neutral building blocks for executing Tasks,
|
|
13
|
+
composing them in Pipelines, and verifying their results with Contracts. It is
|
|
14
|
+
designed to keep an AI-generated Task bounded and independently verifiable.
|
|
15
|
+
|
|
16
|
+
Graph-IR support currently lives in `loom.graphite`. It is intentionally
|
|
17
|
+
separate from the orchestration core and can later move to Graphite without
|
|
18
|
+
affecting users of `loom.core`, such as Artisan.
|
|
19
|
+
|
|
20
|
+
## Architecture
|
|
21
|
+
|
|
22
|
+
```text
|
|
23
|
+
AI-generated or human-written Task
|
|
24
|
+
|
|
|
25
|
+
v
|
|
26
|
+
TaskResult
|
|
27
|
+
|
|
|
28
|
+
v
|
|
29
|
+
Pipeline composes Tasks and returns PipelineResult
|
|
30
|
+
|
|
|
31
|
+
v
|
|
32
|
+
Verifier evaluates Contracts for the selected result
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
`TaskResult` and `PipelineResult` both extend `Result`. A Contract evaluates
|
|
36
|
+
the explicit result supplied to it; it does not own or run a Pipeline.
|
|
37
|
+
|
|
38
|
+
## Core API
|
|
39
|
+
|
|
40
|
+
```python
|
|
41
|
+
from loom.core import (
|
|
42
|
+
Contract,
|
|
43
|
+
ContractResult,
|
|
44
|
+
Pipeline,
|
|
45
|
+
PipelineResult,
|
|
46
|
+
Result,
|
|
47
|
+
Task,
|
|
48
|
+
TaskResult,
|
|
49
|
+
Verifier,
|
|
50
|
+
)
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
A Task is the smallest executable unit of domain work:
|
|
54
|
+
|
|
55
|
+
```python
|
|
56
|
+
class NormalizeTask(Task):
|
|
57
|
+
def __init__(self):
|
|
58
|
+
super().__init__(name="normalize")
|
|
59
|
+
|
|
60
|
+
def execute(self, artifact) -> TaskResult:
|
|
61
|
+
changed = normalize(artifact)
|
|
62
|
+
return TaskResult(output=artifact, modified=changed)
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
A Pipeline owns sequencing, branching, and fixed-point repetition. The default
|
|
66
|
+
iteration limit is configured in its constructor and can be overridden for one
|
|
67
|
+
call to `repeat()`.
|
|
68
|
+
|
|
69
|
+
```python
|
|
70
|
+
class CompilerPipeline(Pipeline):
|
|
71
|
+
def __init__(self, lower_task):
|
|
72
|
+
super().__init__(name="compile", max_iterations=1000)
|
|
73
|
+
self.lower_task = lower_task
|
|
74
|
+
|
|
75
|
+
def execute(self, graph) -> PipelineResult:
|
|
76
|
+
lower_result = self.repeat(self.lower_task, graph)
|
|
77
|
+
return PipelineResult(
|
|
78
|
+
output=graph,
|
|
79
|
+
modified=lower_result.modified,
|
|
80
|
+
task_results={"lower": lower_result},
|
|
81
|
+
)
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
`repeat()` stops when its Task returns `modified=False`. Its result metadata
|
|
85
|
+
records the iteration count and whether it converged.
|
|
86
|
+
|
|
87
|
+
## Contracts and verification
|
|
88
|
+
|
|
89
|
+
Contracts judge a result after a Task or Pipeline has executed. A caller can
|
|
90
|
+
invoke a Verifier explicitly, or a domain-specific Pipeline can do so as part
|
|
91
|
+
of its own orchestration. Contracts can validate an AI-generated Task directly,
|
|
92
|
+
a whole Pipeline result, or a selected Task result from a Pipeline result.
|
|
93
|
+
|
|
94
|
+
```python
|
|
95
|
+
task_result = candidate_task.execute(input)
|
|
96
|
+
checks = Verifier([candidate_contract]).verify(task_result)
|
|
97
|
+
|
|
98
|
+
pipeline_result = pipeline.execute(input)
|
|
99
|
+
checks = Verifier([end_to_end_contract]).verify(pipeline_result)
|
|
100
|
+
checks = Verifier([candidate_contract]).verify(
|
|
101
|
+
pipeline_result.task_results["candidate"]
|
|
102
|
+
)
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
A Contract implements `evaluate(result: Result) -> ContractResult`. The
|
|
106
|
+
Verifier keeps all normal failures so they can be used as feedback for the next
|
|
107
|
+
agent revision.
|
|
108
|
+
|
|
109
|
+
## Graphite support
|
|
110
|
+
|
|
111
|
+
`loom.graphite` provides the current Heterograph-specific implementation:
|
|
112
|
+
|
|
113
|
+
```python
|
|
114
|
+
from loom.graphite import (
|
|
115
|
+
DfsMatchStrategy,
|
|
116
|
+
GraphProcessor,
|
|
117
|
+
GraphSchema,
|
|
118
|
+
GraphSchemaContract,
|
|
119
|
+
IsoMatchStrategy,
|
|
120
|
+
)
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
- `GraphProcessor` matches AQL patterns and performs in-place graph rewrites.
|
|
124
|
+
- `GraphSchema` defines and validates typed Heterograph IRs.
|
|
125
|
+
- `GraphSchemaContract` validates the output of any `Result` against a graph
|
|
126
|
+
schema.
|
|
127
|
+
|
|
128
|
+
For example:
|
|
129
|
+
|
|
130
|
+
```python
|
|
131
|
+
processor = GraphProcessor(snapshot=False)
|
|
132
|
+
result = processor.run(
|
|
133
|
+
graph,
|
|
134
|
+
select="a => b => c",
|
|
135
|
+
rewrite="a => c",
|
|
136
|
+
)
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
Graphite Tasks call `GraphProcessor` directly. Loom core does not define an
|
|
140
|
+
Action abstraction and does not require a graph or an IR.
|
|
141
|
+
|
|
142
|
+
## Agent workflow
|
|
143
|
+
|
|
144
|
+
`loom.agent` provides a restricted interface for an external agent to develop
|
|
145
|
+
and revise selected Task implementations. The agent receives an
|
|
146
|
+
`AgentContext`, which exposes the pipeline runner, the names of editable tasks,
|
|
147
|
+
and their forge locations. It does not receive the pipeline implementation or
|
|
148
|
+
the human-written contracts.
|
|
149
|
+
|
|
150
|
+
```python
|
|
151
|
+
from pathlib import Path
|
|
152
|
+
|
|
153
|
+
from loom.agent import AgentLoop, PipelineRunner
|
|
154
|
+
|
|
155
|
+
runner = PipelineRunner(
|
|
156
|
+
LoweringPipeline,
|
|
157
|
+
editable_tasks={"lower-dense"},
|
|
158
|
+
forge={
|
|
159
|
+
"lower-dense": Path("examples/agent/forge/lower_dense_task.py"),
|
|
160
|
+
},
|
|
161
|
+
)
|
|
162
|
+
result = AgentLoop(runner).run(input_value, agent)
|
|
163
|
+
```
|
|
164
|
+
|
|
165
|
+
The pipeline merges its builtin task factories with the agent-provided
|
|
166
|
+
factories. Only the explicitly editable task slots can be replaced. Each
|
|
167
|
+
attempt loads the candidate task from the forge and executes the unchanged
|
|
168
|
+
pipeline and contracts.
|
|
169
|
+
|
|
170
|
+
Task exceptions are passed to the agent as normal exceptions. Contract
|
|
171
|
+
failures are raised by `Verifier` as `ContractException`, carrying the
|
|
172
|
+
execution result and contract results. An agent can use this feedback to
|
|
173
|
+
revise the forged task and retry until the contracts pass or the loop reaches
|
|
174
|
+
its attempt limit.
|
|
175
|
+
|
|
176
|
+
The lowering integration example is in `examples/agent`. Its forge currently
|
|
177
|
+
contains an intentionally disabled OP-IR update so the contract-failure path
|
|
178
|
+
can be exercised; uncomment those lines to restore the successful task.
|
|
179
|
+
|
|
180
|
+
### Pydantic AI task generation
|
|
181
|
+
|
|
182
|
+
Select a provider, model, and the task names that `TaskGen` may revise:
|
|
183
|
+
|
|
184
|
+
```bash
|
|
185
|
+
pip install loom-workflow
|
|
186
|
+
```
|
|
187
|
+
|
|
188
|
+
```python
|
|
189
|
+
from loom.agent import PydanticAIProvider, TaskGen
|
|
190
|
+
|
|
191
|
+
agent = TaskGen(
|
|
192
|
+
provider=PydanticAIProvider(provider="openai", model="gpt-5.6-sol"),
|
|
193
|
+
tasks={"lower-dense"},
|
|
194
|
+
)
|
|
195
|
+
result = AgentLoop(runner).run(input_value, agent)
|
|
196
|
+
```
|
|
197
|
+
|
|
198
|
+
`TaskGen` sends only the selected forge module and execution feedback to its
|
|
199
|
+
provider. It writes the returned replacement module into that forge path and
|
|
200
|
+
returns a factory for the next pipeline attempt. `PydanticAIProvider` owns the
|
|
201
|
+
provider-specific model routing; another backend can implement `Provider`
|
|
202
|
+
without changing `TaskGen`.
|
|
203
|
+
|
|
204
|
+
## Examples
|
|
205
|
+
|
|
206
|
+
Loom requires Python 3.10+ and Heterograph for the Graphite examples. Create
|
|
207
|
+
the supplied environment:
|
|
208
|
+
|
|
209
|
+
```bash
|
|
210
|
+
conda env create -f examples/environment.yml
|
|
211
|
+
conda activate loom-examples
|
|
212
|
+
```
|
|
213
|
+
|
|
214
|
+
Run the examples from the repository root:
|
|
215
|
+
|
|
216
|
+
```bash
|
|
217
|
+
python examples/validation/main.py
|
|
218
|
+
python examples/processor_tests/main.py
|
|
219
|
+
python examples/lowering/main.py
|
|
220
|
+
python examples/agent/main.py
|
|
221
|
+
```
|
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
# Loom
|
|
2
|
+
|
|
3
|
+
Loom provides small, domain-neutral building blocks for executing Tasks,
|
|
4
|
+
composing them in Pipelines, and verifying their results with Contracts. It is
|
|
5
|
+
designed to keep an AI-generated Task bounded and independently verifiable.
|
|
6
|
+
|
|
7
|
+
Graph-IR support currently lives in `loom.graphite`. It is intentionally
|
|
8
|
+
separate from the orchestration core and can later move to Graphite without
|
|
9
|
+
affecting users of `loom.core`, such as Artisan.
|
|
10
|
+
|
|
11
|
+
## Architecture
|
|
12
|
+
|
|
13
|
+
```text
|
|
14
|
+
AI-generated or human-written Task
|
|
15
|
+
|
|
|
16
|
+
v
|
|
17
|
+
TaskResult
|
|
18
|
+
|
|
|
19
|
+
v
|
|
20
|
+
Pipeline composes Tasks and returns PipelineResult
|
|
21
|
+
|
|
|
22
|
+
v
|
|
23
|
+
Verifier evaluates Contracts for the selected result
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
`TaskResult` and `PipelineResult` both extend `Result`. A Contract evaluates
|
|
27
|
+
the explicit result supplied to it; it does not own or run a Pipeline.
|
|
28
|
+
|
|
29
|
+
## Core API
|
|
30
|
+
|
|
31
|
+
```python
|
|
32
|
+
from loom.core import (
|
|
33
|
+
Contract,
|
|
34
|
+
ContractResult,
|
|
35
|
+
Pipeline,
|
|
36
|
+
PipelineResult,
|
|
37
|
+
Result,
|
|
38
|
+
Task,
|
|
39
|
+
TaskResult,
|
|
40
|
+
Verifier,
|
|
41
|
+
)
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
A Task is the smallest executable unit of domain work:
|
|
45
|
+
|
|
46
|
+
```python
|
|
47
|
+
class NormalizeTask(Task):
|
|
48
|
+
def __init__(self):
|
|
49
|
+
super().__init__(name="normalize")
|
|
50
|
+
|
|
51
|
+
def execute(self, artifact) -> TaskResult:
|
|
52
|
+
changed = normalize(artifact)
|
|
53
|
+
return TaskResult(output=artifact, modified=changed)
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
A Pipeline owns sequencing, branching, and fixed-point repetition. The default
|
|
57
|
+
iteration limit is configured in its constructor and can be overridden for one
|
|
58
|
+
call to `repeat()`.
|
|
59
|
+
|
|
60
|
+
```python
|
|
61
|
+
class CompilerPipeline(Pipeline):
|
|
62
|
+
def __init__(self, lower_task):
|
|
63
|
+
super().__init__(name="compile", max_iterations=1000)
|
|
64
|
+
self.lower_task = lower_task
|
|
65
|
+
|
|
66
|
+
def execute(self, graph) -> PipelineResult:
|
|
67
|
+
lower_result = self.repeat(self.lower_task, graph)
|
|
68
|
+
return PipelineResult(
|
|
69
|
+
output=graph,
|
|
70
|
+
modified=lower_result.modified,
|
|
71
|
+
task_results={"lower": lower_result},
|
|
72
|
+
)
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
`repeat()` stops when its Task returns `modified=False`. Its result metadata
|
|
76
|
+
records the iteration count and whether it converged.
|
|
77
|
+
|
|
78
|
+
## Contracts and verification
|
|
79
|
+
|
|
80
|
+
Contracts judge a result after a Task or Pipeline has executed. A caller can
|
|
81
|
+
invoke a Verifier explicitly, or a domain-specific Pipeline can do so as part
|
|
82
|
+
of its own orchestration. Contracts can validate an AI-generated Task directly,
|
|
83
|
+
a whole Pipeline result, or a selected Task result from a Pipeline result.
|
|
84
|
+
|
|
85
|
+
```python
|
|
86
|
+
task_result = candidate_task.execute(input)
|
|
87
|
+
checks = Verifier([candidate_contract]).verify(task_result)
|
|
88
|
+
|
|
89
|
+
pipeline_result = pipeline.execute(input)
|
|
90
|
+
checks = Verifier([end_to_end_contract]).verify(pipeline_result)
|
|
91
|
+
checks = Verifier([candidate_contract]).verify(
|
|
92
|
+
pipeline_result.task_results["candidate"]
|
|
93
|
+
)
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
A Contract implements `evaluate(result: Result) -> ContractResult`. The
|
|
97
|
+
Verifier keeps all normal failures so they can be used as feedback for the next
|
|
98
|
+
agent revision.
|
|
99
|
+
|
|
100
|
+
## Graphite support
|
|
101
|
+
|
|
102
|
+
`loom.graphite` provides the current Heterograph-specific implementation:
|
|
103
|
+
|
|
104
|
+
```python
|
|
105
|
+
from loom.graphite import (
|
|
106
|
+
DfsMatchStrategy,
|
|
107
|
+
GraphProcessor,
|
|
108
|
+
GraphSchema,
|
|
109
|
+
GraphSchemaContract,
|
|
110
|
+
IsoMatchStrategy,
|
|
111
|
+
)
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
- `GraphProcessor` matches AQL patterns and performs in-place graph rewrites.
|
|
115
|
+
- `GraphSchema` defines and validates typed Heterograph IRs.
|
|
116
|
+
- `GraphSchemaContract` validates the output of any `Result` against a graph
|
|
117
|
+
schema.
|
|
118
|
+
|
|
119
|
+
For example:
|
|
120
|
+
|
|
121
|
+
```python
|
|
122
|
+
processor = GraphProcessor(snapshot=False)
|
|
123
|
+
result = processor.run(
|
|
124
|
+
graph,
|
|
125
|
+
select="a => b => c",
|
|
126
|
+
rewrite="a => c",
|
|
127
|
+
)
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
Graphite Tasks call `GraphProcessor` directly. Loom core does not define an
|
|
131
|
+
Action abstraction and does not require a graph or an IR.
|
|
132
|
+
|
|
133
|
+
## Agent workflow
|
|
134
|
+
|
|
135
|
+
`loom.agent` provides a restricted interface for an external agent to develop
|
|
136
|
+
and revise selected Task implementations. The agent receives an
|
|
137
|
+
`AgentContext`, which exposes the pipeline runner, the names of editable tasks,
|
|
138
|
+
and their forge locations. It does not receive the pipeline implementation or
|
|
139
|
+
the human-written contracts.
|
|
140
|
+
|
|
141
|
+
```python
|
|
142
|
+
from pathlib import Path
|
|
143
|
+
|
|
144
|
+
from loom.agent import AgentLoop, PipelineRunner
|
|
145
|
+
|
|
146
|
+
runner = PipelineRunner(
|
|
147
|
+
LoweringPipeline,
|
|
148
|
+
editable_tasks={"lower-dense"},
|
|
149
|
+
forge={
|
|
150
|
+
"lower-dense": Path("examples/agent/forge/lower_dense_task.py"),
|
|
151
|
+
},
|
|
152
|
+
)
|
|
153
|
+
result = AgentLoop(runner).run(input_value, agent)
|
|
154
|
+
```
|
|
155
|
+
|
|
156
|
+
The pipeline merges its builtin task factories with the agent-provided
|
|
157
|
+
factories. Only the explicitly editable task slots can be replaced. Each
|
|
158
|
+
attempt loads the candidate task from the forge and executes the unchanged
|
|
159
|
+
pipeline and contracts.
|
|
160
|
+
|
|
161
|
+
Task exceptions are passed to the agent as normal exceptions. Contract
|
|
162
|
+
failures are raised by `Verifier` as `ContractException`, carrying the
|
|
163
|
+
execution result and contract results. An agent can use this feedback to
|
|
164
|
+
revise the forged task and retry until the contracts pass or the loop reaches
|
|
165
|
+
its attempt limit.
|
|
166
|
+
|
|
167
|
+
The lowering integration example is in `examples/agent`. Its forge currently
|
|
168
|
+
contains an intentionally disabled OP-IR update so the contract-failure path
|
|
169
|
+
can be exercised; uncomment those lines to restore the successful task.
|
|
170
|
+
|
|
171
|
+
### Pydantic AI task generation
|
|
172
|
+
|
|
173
|
+
Select a provider, model, and the task names that `TaskGen` may revise:
|
|
174
|
+
|
|
175
|
+
```bash
|
|
176
|
+
pip install loom-workflow
|
|
177
|
+
```
|
|
178
|
+
|
|
179
|
+
```python
|
|
180
|
+
from loom.agent import PydanticAIProvider, TaskGen
|
|
181
|
+
|
|
182
|
+
agent = TaskGen(
|
|
183
|
+
provider=PydanticAIProvider(provider="openai", model="gpt-5.6-sol"),
|
|
184
|
+
tasks={"lower-dense"},
|
|
185
|
+
)
|
|
186
|
+
result = AgentLoop(runner).run(input_value, agent)
|
|
187
|
+
```
|
|
188
|
+
|
|
189
|
+
`TaskGen` sends only the selected forge module and execution feedback to its
|
|
190
|
+
provider. It writes the returned replacement module into that forge path and
|
|
191
|
+
returns a factory for the next pipeline attempt. `PydanticAIProvider` owns the
|
|
192
|
+
provider-specific model routing; another backend can implement `Provider`
|
|
193
|
+
without changing `TaskGen`.
|
|
194
|
+
|
|
195
|
+
## Examples
|
|
196
|
+
|
|
197
|
+
Loom requires Python 3.10+ and Heterograph for the Graphite examples. Create
|
|
198
|
+
the supplied environment:
|
|
199
|
+
|
|
200
|
+
```bash
|
|
201
|
+
conda env create -f examples/environment.yml
|
|
202
|
+
conda activate loom-examples
|
|
203
|
+
```
|
|
204
|
+
|
|
205
|
+
Run the examples from the repository root:
|
|
206
|
+
|
|
207
|
+
```bash
|
|
208
|
+
python examples/validation/main.py
|
|
209
|
+
python examples/processor_tests/main.py
|
|
210
|
+
python examples/lowering/main.py
|
|
211
|
+
python examples/agent/main.py
|
|
212
|
+
```
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
"""Loom: domain-neutral orchestration and optional graph-IR support."""
|
|
2
|
+
|
|
3
|
+
from .core import (
|
|
4
|
+
Contract,
|
|
5
|
+
ContractException,
|
|
6
|
+
ContractResult,
|
|
7
|
+
Pipeline,
|
|
8
|
+
PipelineResult,
|
|
9
|
+
Result,
|
|
10
|
+
Task,
|
|
11
|
+
TaskResult,
|
|
12
|
+
Verifier,
|
|
13
|
+
)
|
|
14
|
+
|
|
15
|
+
__all__ = [
|
|
16
|
+
"Result",
|
|
17
|
+
"Task",
|
|
18
|
+
"TaskResult",
|
|
19
|
+
"Pipeline",
|
|
20
|
+
"PipelineResult",
|
|
21
|
+
"Contract",
|
|
22
|
+
"ContractException",
|
|
23
|
+
"ContractResult",
|
|
24
|
+
"Verifier",
|
|
25
|
+
]
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
"""Restricted agent orchestration for revisable Loom tasks."""
|
|
2
|
+
|
|
3
|
+
from .provider import Provider, PydanticAIProvider
|
|
4
|
+
from .task_gen import TaskGen, TaskSource
|
|
5
|
+
from .loop import Agent, AgentContext, AgentLoop, PipelineRunner, TaskFactories
|
|
6
|
+
|
|
7
|
+
__all__ = [
|
|
8
|
+
"Agent",
|
|
9
|
+
"AgentContext",
|
|
10
|
+
"AgentLoop",
|
|
11
|
+
"PipelineRunner",
|
|
12
|
+
"Provider",
|
|
13
|
+
"PydanticAIProvider",
|
|
14
|
+
"TaskGen",
|
|
15
|
+
"TaskFactories",
|
|
16
|
+
"TaskSource",
|
|
17
|
+
]
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
"""Agent-facing pipeline execution boundaries.
|
|
2
|
+
|
|
3
|
+
This module deliberately contains no model-provider integration. An adapter
|
|
4
|
+
such as Pydantic AI can implement :class:`Agent` and use :class:`AgentContext`
|
|
5
|
+
as its dependency object.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from dataclasses import dataclass
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
from types import MappingProxyType
|
|
13
|
+
from typing import Any, Callable, Mapping, Protocol, Type
|
|
14
|
+
|
|
15
|
+
from ..core import Pipeline, PipelineResult, Task
|
|
16
|
+
|
|
17
|
+
TaskFactory = Callable[[Pipeline], Task]
|
|
18
|
+
TaskFactories = Mapping[str, TaskFactory]
|
|
19
|
+
class PipelineRunner:
|
|
20
|
+
"""Capability for executing a human-owned pipeline.
|
|
21
|
+
|
|
22
|
+
The pipeline factory and input factory remain private. Callers can submit
|
|
23
|
+
implementations only for the explicitly editable task names.
|
|
24
|
+
"""
|
|
25
|
+
|
|
26
|
+
def __init__(self, pipeline_class: Type[Pipeline], *,
|
|
27
|
+
editable_tasks: set[str] | frozenset[str],
|
|
28
|
+
pipeline_kwargs: Mapping[str, Any] | None = None,
|
|
29
|
+
forge: Mapping[str, str | Path] | None = None,
|
|
30
|
+
input_factory: Callable[[Any], Any] | None = None):
|
|
31
|
+
if not isinstance(pipeline_class, type) or not issubclass(pipeline_class, Pipeline):
|
|
32
|
+
raise TypeError("pipeline_class must be a Pipeline subclass.")
|
|
33
|
+
self._pipeline_class = pipeline_class
|
|
34
|
+
self._pipeline_kwargs = dict(pipeline_kwargs or {})
|
|
35
|
+
self._editable_tasks = frozenset(editable_tasks)
|
|
36
|
+
paths = {
|
|
37
|
+
name: Path(path) for name, path in (forge or {}).items()
|
|
38
|
+
}
|
|
39
|
+
unknown_paths = set(paths) - self._editable_tasks
|
|
40
|
+
if unknown_paths:
|
|
41
|
+
raise ValueError(
|
|
42
|
+
f"Task paths are not editable: {sorted(unknown_paths)!r}"
|
|
43
|
+
)
|
|
44
|
+
self._forge = MappingProxyType(paths)
|
|
45
|
+
self._input_factory = input_factory or (lambda value: value)
|
|
46
|
+
|
|
47
|
+
@property
|
|
48
|
+
def editable_tasks(self) -> frozenset[str]:
|
|
49
|
+
return self._editable_tasks
|
|
50
|
+
|
|
51
|
+
@property
|
|
52
|
+
def forge(self) -> Mapping[str, Path]:
|
|
53
|
+
return self._forge
|
|
54
|
+
|
|
55
|
+
def run(self, input: Any, task_factories: TaskFactories) -> PipelineResult:
|
|
56
|
+
"""Execute with candidate implementations for editable task slots."""
|
|
57
|
+
unknown = set(task_factories) - self._editable_tasks
|
|
58
|
+
if unknown:
|
|
59
|
+
raise ValueError(f"Tasks are not editable: {sorted(unknown)!r}")
|
|
60
|
+
pipeline = self._pipeline_class(
|
|
61
|
+
task_factories=task_factories,
|
|
62
|
+
**self._pipeline_kwargs,
|
|
63
|
+
)
|
|
64
|
+
result = pipeline.execute(self._input_factory(input))
|
|
65
|
+
if not isinstance(result, PipelineResult):
|
|
66
|
+
raise TypeError("pipeline must return PipelineResult")
|
|
67
|
+
return result
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
@dataclass(frozen=True)
|
|
71
|
+
class AgentContext:
|
|
72
|
+
"""Dependencies exposed to an agent implementation."""
|
|
73
|
+
|
|
74
|
+
runner: PipelineRunner
|
|
75
|
+
input: Any
|
|
76
|
+
|
|
77
|
+
@property
|
|
78
|
+
def editable_tasks(self) -> frozenset[str]:
|
|
79
|
+
return self.runner.editable_tasks
|
|
80
|
+
|
|
81
|
+
@property
|
|
82
|
+
def forge(self) -> Mapping[str, Path]:
|
|
83
|
+
return self.runner.forge
|
|
84
|
+
|
|
85
|
+
def run(self, task_factories: TaskFactories) -> PipelineResult:
|
|
86
|
+
return self.runner.run(self.input, task_factories)
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
class Agent(Protocol):
|
|
90
|
+
"""Protocol suitable for a Pydantic AI-backed task reviser."""
|
|
91
|
+
|
|
92
|
+
def initial_tasks(self, context: AgentContext) -> TaskFactories:
|
|
93
|
+
...
|
|
94
|
+
|
|
95
|
+
def revise_tasks(self, context: AgentContext, *,
|
|
96
|
+
failure: Exception) -> TaskFactories:
|
|
97
|
+
...
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
class AgentLoop:
|
|
101
|
+
"""Run candidate task implementations until the pipeline succeeds."""
|
|
102
|
+
|
|
103
|
+
def __init__(self, runner: PipelineRunner, *, max_attempts: int = 10):
|
|
104
|
+
if not isinstance(max_attempts, int) or isinstance(max_attempts, bool) \
|
|
105
|
+
or max_attempts <= 0:
|
|
106
|
+
raise ValueError("max_attempts must be a positive integer.")
|
|
107
|
+
self.runner = runner
|
|
108
|
+
self.max_attempts = max_attempts
|
|
109
|
+
|
|
110
|
+
def run(self, input: Any, agent: Agent) -> PipelineResult:
|
|
111
|
+
context = AgentContext(self.runner, input)
|
|
112
|
+
task_factories = agent.initial_tasks(context)
|
|
113
|
+
last_failure: Exception | None = None
|
|
114
|
+
|
|
115
|
+
for _ in range(self.max_attempts):
|
|
116
|
+
try:
|
|
117
|
+
return context.run(task_factories)
|
|
118
|
+
except Exception as failure:
|
|
119
|
+
# ContractException carries the PipelineResult and contract
|
|
120
|
+
# results; other exceptions are task/runtime errors.
|
|
121
|
+
last_failure = failure
|
|
122
|
+
task_factories = agent.revise_tasks(
|
|
123
|
+
context, failure=failure
|
|
124
|
+
)
|
|
125
|
+
|
|
126
|
+
raise RuntimeError(
|
|
127
|
+
f"agent loop exceeded max_attempts ({self.max_attempts}); "
|
|
128
|
+
f"last failure: {last_failure}"
|
|
129
|
+
) from last_failure
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
"""Provider abstractions for model-backed Loom agents."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from abc import ABC, abstractmethod
|
|
6
|
+
from typing import Type
|
|
7
|
+
|
|
8
|
+
from pydantic import BaseModel
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class Provider(ABC):
|
|
12
|
+
"""Generic interface for communicating with a language model."""
|
|
13
|
+
|
|
14
|
+
@abstractmethod
|
|
15
|
+
def generate(self, prompt: str, output_type: Type[BaseModel]) -> BaseModel:
|
|
16
|
+
"""Generate one structured response for ``prompt``."""
|
|
17
|
+
pass
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class PydanticAIProvider(Provider):
|
|
21
|
+
"""Provider backed by Pydantic AI.
|
|
22
|
+
|
|
23
|
+
Model identifiers and provider-specific routing are kept here so callers
|
|
24
|
+
such as :class:`~loom.agent.task_gen.TaskGen` need only use ``generate``.
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
def __init__(self, *, provider: str, model: str):
|
|
28
|
+
if not isinstance(provider, str) or not provider.strip():
|
|
29
|
+
raise ValueError("provider must be a non-empty string.")
|
|
30
|
+
if not isinstance(model, str) or not model.strip():
|
|
31
|
+
raise ValueError("model must be a non-empty string.")
|
|
32
|
+
self.provider = provider.strip().lower()
|
|
33
|
+
self.model = model.strip()
|
|
34
|
+
|
|
35
|
+
@property
|
|
36
|
+
def model_name(self) -> str:
|
|
37
|
+
"""Return the Pydantic AI model identifier for this configuration."""
|
|
38
|
+
prefixes = {
|
|
39
|
+
"openai": "openai-responses",
|
|
40
|
+
"claude": "anthropic",
|
|
41
|
+
"anthropic": "anthropic",
|
|
42
|
+
}
|
|
43
|
+
try:
|
|
44
|
+
prefix = prefixes[self.provider]
|
|
45
|
+
except KeyError as error:
|
|
46
|
+
raise ValueError(
|
|
47
|
+
f"Unsupported Pydantic AI provider {self.provider!r}."
|
|
48
|
+
) from error
|
|
49
|
+
return f"{prefix}:{self.model}"
|
|
50
|
+
|
|
51
|
+
def generate(self, prompt: str, output_type: Type[BaseModel]) -> BaseModel:
|
|
52
|
+
try:
|
|
53
|
+
from pydantic_ai import Agent
|
|
54
|
+
except ImportError as error:
|
|
55
|
+
raise ImportError(
|
|
56
|
+
"PydanticAIProvider requires Pydantic AI. Install it with "
|
|
57
|
+
"`pip install loom[agent]`."
|
|
58
|
+
) from error
|
|
59
|
+
|
|
60
|
+
agent = Agent(
|
|
61
|
+
self.model_name,
|
|
62
|
+
output_type=output_type,
|
|
63
|
+
system_prompt=(
|
|
64
|
+
"You write one complete Python Task module for Loom. "
|
|
65
|
+
"Return only the structured response. The task must use its "
|
|
66
|
+
"supplied pipeline constructor argument, preserve its assigned "
|
|
67
|
+
"task name, and modify no files itself."
|
|
68
|
+
),
|
|
69
|
+
)
|
|
70
|
+
return agent.run_sync(prompt).output
|