xqo-flows 3.2.0__py3-none-any.whl
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.
- xqo_flows/__init__.py +322 -0
- xqo_flows/engine.py +272 -0
- xqo_flows/examples/draft-review-approve.json +37 -0
- xqo_flows/examples/hello.json +17 -0
- xqo_flows/model.py +336 -0
- xqo_flows/service.py +622 -0
- xqo_flows/static/editor.css +1 -0
- xqo_flows/static/editor.html +14 -0
- xqo_flows/static/editor.js +297 -0
- xqo_flows/static/ui.js +12 -0
- xqo_flows/steps.py +54 -0
- xqo_flows/triggers.py +164 -0
- xqo_flows/workers.py +411 -0
- xqo_flows-3.2.0.dist-info/METADATA +187 -0
- xqo_flows-3.2.0.dist-info/RECORD +19 -0
- xqo_flows-3.2.0.dist-info/WHEEL +5 -0
- xqo_flows-3.2.0.dist-info/entry_points.txt +2 -0
- xqo_flows-3.2.0.dist-info/licenses/LICENSE +21 -0
- xqo_flows-3.2.0.dist-info/top_level.txt +1 -0
xqo_flows/__init__.py
ADDED
|
@@ -0,0 +1,322 @@
|
|
|
1
|
+
"""Flows plugin: visual workflows of xqo agents, drawn in a FlowGram.AI editor and run by xqo.
|
|
2
|
+
|
|
3
|
+
Turn it on with "flows": {} in agents.json (see service.py for the keys, workers.py for remote workers). The
|
|
4
|
+
editor is at /plugins/flows/editor.html (the "flows" link in the dashboard header). Runs start from the editor,
|
|
5
|
+
the API (POST /api/flows/<name>/run), the CLI (xqo flows run <name>) or an agent's run_flow tool."""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import sys
|
|
9
|
+
import time
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
|
|
12
|
+
from fastapi import HTTPException, Query, Request
|
|
13
|
+
from pydantic import BaseModel, Field
|
|
14
|
+
|
|
15
|
+
from xqo.api import Plugin
|
|
16
|
+
from xqo.api import client_api as _api
|
|
17
|
+
|
|
18
|
+
from .engine import FINAL, Engine, Run, Steps
|
|
19
|
+
from .model import FlowError, validate
|
|
20
|
+
from .service import FlowService
|
|
21
|
+
from .steps import BusSteps, run_task
|
|
22
|
+
from .workers import Dispatcher, create_worker_app, hook_response
|
|
23
|
+
|
|
24
|
+
__all__ = ["FlowsPlugin", "FlowService", "Engine", "Run", "Steps", "BusSteps", "run_task", "validate",
|
|
25
|
+
"FlowError", "Dispatcher", "FINAL"]
|
|
26
|
+
|
|
27
|
+
STATIC = Path(__file__).parent / "static"
|
|
28
|
+
|
|
29
|
+
RUN_FLOW_TOOL = {
|
|
30
|
+
"name": "run_flow",
|
|
31
|
+
"description": "Start one of the HQ's saved visual flows (a fixed sequence of agent steps, conditions and "
|
|
32
|
+
"approvals) and wait for its result. Use it when the user asks for something a listed flow does.",
|
|
33
|
+
"input_schema": {"type": "object",
|
|
34
|
+
"properties": {"name": {"type": "string", "description": "the flow's name"},
|
|
35
|
+
"inputs": {"type": "object", "additionalProperties": {"type": "string"},
|
|
36
|
+
"description": "the flow's inputs by name"}},
|
|
37
|
+
"required": ["name"], "additionalProperties": False},
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class RunIn(BaseModel):
|
|
42
|
+
model_config = {"extra": "forbid"}
|
|
43
|
+
inputs: dict[str, str | int | float | bool | None] = Field(default_factory=dict)
|
|
44
|
+
labels: list[str] = Field(default_factory=list, max_length=20)
|
|
45
|
+
worker: str = Field(default="", max_length=100)
|
|
46
|
+
remote: bool = False
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class ApproveIn(BaseModel):
|
|
50
|
+
model_config = {"extra": "forbid"}
|
|
51
|
+
node: str = Field(max_length=64)
|
|
52
|
+
approve: bool = True
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _call(fn, *args):
|
|
56
|
+
try:
|
|
57
|
+
return fn(*args)
|
|
58
|
+
except KeyError as e:
|
|
59
|
+
raise HTTPException(404, str(e.args[0] if e.args else e))
|
|
60
|
+
except (FlowError, ValueError) as e:
|
|
61
|
+
raise HTTPException(422, str(e))
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _line(r: dict) -> str:
|
|
65
|
+
return (f"{r['id']:<16} {r['flow'][:24]:<24} {r['status']:<11} {r['started'][:19].replace('T', ' ')} "
|
|
66
|
+
f"{r.get('where', 'hq'):<16} {(r.get('error') or r.get('result') or '')[:60]!r}")
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _cli(a) -> None:
|
|
70
|
+
url = a.url
|
|
71
|
+
try:
|
|
72
|
+
c = a.flows_cmd or "list"
|
|
73
|
+
if c == "list":
|
|
74
|
+
rows = _api(url, "GET", "/api/flows")
|
|
75
|
+
for f in rows:
|
|
76
|
+
last = f.get("last_run") or {}
|
|
77
|
+
print(f"{f['name']:<24} {f['title'][:36]:<36} {f.get('nodes', 0):>3} nodes "
|
|
78
|
+
f"inputs: {', '.join(f.get('inputs') or []) or '-':<20} last: {last.get('status', '-')}")
|
|
79
|
+
if not rows:
|
|
80
|
+
print("no flows (draw one on the Flows page, or: xqo flows import FILE.json)")
|
|
81
|
+
elif c == "show":
|
|
82
|
+
import json
|
|
83
|
+
print(json.dumps(_api(url, "GET", f"/api/flows/{a.name}"), indent=2))
|
|
84
|
+
elif c == "import":
|
|
85
|
+
import json
|
|
86
|
+
doc = json.loads(Path(a.file).read_text(encoding="utf-8"))
|
|
87
|
+
name = a.name or doc.get("name") or Path(a.file).stem
|
|
88
|
+
_api(url, "PUT", f"/api/flows/{name}", doc)
|
|
89
|
+
print(f"saved flow {name}")
|
|
90
|
+
elif c == "rm":
|
|
91
|
+
_api(url, "DELETE", f"/api/flows/{a.name}")
|
|
92
|
+
print(f"deleted flow {a.name}")
|
|
93
|
+
elif c == "run":
|
|
94
|
+
inputs = {}
|
|
95
|
+
for kv in a.input:
|
|
96
|
+
k, sep, v = kv.partition("=")
|
|
97
|
+
if not sep:
|
|
98
|
+
sys.exit(f"--input takes NAME=VALUE, got {kv!r}")
|
|
99
|
+
inputs[k] = v
|
|
100
|
+
body = {"inputs": inputs, "labels": [x for x in (a.labels or "").split(",") if x],
|
|
101
|
+
"worker": a.worker or "", "remote": bool(a.remote)}
|
|
102
|
+
r = _api(url, "POST", f"/api/flows/{a.name}/run", body)
|
|
103
|
+
print(f"started {r['id']} ({r['flow']})")
|
|
104
|
+
if a.no_wait:
|
|
105
|
+
return
|
|
106
|
+
seen: dict[str, str] = {}
|
|
107
|
+
while True:
|
|
108
|
+
r = _api(url, "GET", f"/api/flows/runs/{r['id']}")
|
|
109
|
+
for nid, st in r["nodes"].items():
|
|
110
|
+
if seen.get(nid) != st["status"] and st.get("type") != "start" and st["status"] != "pending":
|
|
111
|
+
seen[nid] = st["status"]
|
|
112
|
+
print(f" {st.get('title', nid):<28} {st['status']}"
|
|
113
|
+
+ (f" ({st.get('question')}) -> xqo flows approve {r['id']} {nid} [--reject]"
|
|
114
|
+
if st["status"] == "waiting" else ""))
|
|
115
|
+
if r["status"] in FINAL:
|
|
116
|
+
break
|
|
117
|
+
time.sleep(1)
|
|
118
|
+
print(f"\n[{r['status']}] " + (r.get("result") or r.get("error") or ""))
|
|
119
|
+
elif c == "runs":
|
|
120
|
+
for r in _api(url, "GET", f"/api/flows/runs?limit={a.limit}" + (f"&flow={a.name}" if a.name else "")):
|
|
121
|
+
print(_line(r))
|
|
122
|
+
elif c == "cancel":
|
|
123
|
+
r = _api(url, "POST", f"/api/flows/runs/{a.run_id}/cancel")
|
|
124
|
+
print(f"{r['id']}: {r['status']}")
|
|
125
|
+
elif c == "resume":
|
|
126
|
+
r = _api(url, "POST", f"/api/flows/runs/{a.run_id}/resume")
|
|
127
|
+
print(f"resumed {r['id']} ({r['flow']}): {r['status']}")
|
|
128
|
+
elif c == "triggers":
|
|
129
|
+
rows = _api(url, "GET", "/api/flows/triggers" + (f"?flow={a.name}" if a.name else ""))
|
|
130
|
+
for t in rows:
|
|
131
|
+
when = t.get("when") or t.get("path") or ""
|
|
132
|
+
print(f"{t['flow'][:20]:<20} {t['id'][:16]:<16} {t['type']:<8} {'on ' if t.get('enabled') else 'off'} "
|
|
133
|
+
f"{when[:34]:<34} next: {(t.get('next_run') or '-')[:19]:<19} last: {t.get('last_status') or '-'}"
|
|
134
|
+
+ (f" ({t['warning']})" if t.get("warning") else ""))
|
|
135
|
+
if not rows:
|
|
136
|
+
print("no triggers (add them in the editor's Flow panel or a flow's \"triggers\" list)")
|
|
137
|
+
elif c == "approve":
|
|
138
|
+
r = _api(url, "POST", f"/api/flows/runs/{a.run_id}/approve", {"node": a.node, "approve": not a.reject})
|
|
139
|
+
print(f"{r['run_id']} {r['node']}: {r['answer']}")
|
|
140
|
+
elif c == "workers":
|
|
141
|
+
st = _api(url, "GET", "/api/flows/workers")
|
|
142
|
+
print(f"worker API: {st['listen'] or '(off: set flows.workers.listen)'} queued jobs: {st['queued']}")
|
|
143
|
+
for w in st["workers"]:
|
|
144
|
+
print(f" {w['name']:<16} {'online ' if w['online'] else 'offline'} labels: {', '.join(w['labels']) or '-':<20}"
|
|
145
|
+
f" running: {len(w['running'])}" + ("" if w["token_set"] else f" ({w['token_env']} not set)"))
|
|
146
|
+
elif c == "token":
|
|
147
|
+
import secrets
|
|
148
|
+
print(secrets.token_urlsafe(32))
|
|
149
|
+
except RuntimeError as e:
|
|
150
|
+
sys.exit(str(e))
|
|
151
|
+
except ConnectionError:
|
|
152
|
+
sys.exit(f"no server answering at {url}: flows are run by the running server (xqo serve)")
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
class FlowsPlugin(Plugin):
|
|
156
|
+
name = "flows"
|
|
157
|
+
description = "Visual workflows of agents (FlowGram.AI editor), with remote workers"
|
|
158
|
+
service = "flows"
|
|
159
|
+
config_keys = ("flows",)
|
|
160
|
+
state_dirs = ("flows",)
|
|
161
|
+
tool_names = frozenset({"run_flow"})
|
|
162
|
+
static = ("/plugins/flows", STATIC)
|
|
163
|
+
nav = {"id": "tflows", "label": "flows", "href": "/plugins/flows/editor.html", "title": "Visual flows"}
|
|
164
|
+
ui = ("ui.js",)
|
|
165
|
+
|
|
166
|
+
@classmethod
|
|
167
|
+
def add_cli(cls, sub, url) -> list[str]:
|
|
168
|
+
p = sub.add_parser("flows", help="visual flows: list, show, import, rm, run, runs, cancel, resume, "
|
|
169
|
+
"approve, triggers, workers, token")
|
|
170
|
+
p.add_argument("--url", default=url, help="server address (XQO_URL)")
|
|
171
|
+
s = p.add_subparsers(dest="flows_cmd")
|
|
172
|
+
s.add_parser("list", help="saved flows")
|
|
173
|
+
x = s.add_parser("show", help="print a flow as JSON")
|
|
174
|
+
x.add_argument("name")
|
|
175
|
+
x = s.add_parser("import", help="save a flow from a JSON file")
|
|
176
|
+
x.add_argument("file")
|
|
177
|
+
x.add_argument("--name", help="save under this name (default: the file's name field or file name)")
|
|
178
|
+
x = s.add_parser("rm", help="delete a flow")
|
|
179
|
+
x.add_argument("name")
|
|
180
|
+
x = s.add_parser("run", help="start a run and follow it")
|
|
181
|
+
x.add_argument("name")
|
|
182
|
+
x.add_argument("--input", "-i", action="append", default=[], metavar="NAME=VALUE")
|
|
183
|
+
x.add_argument("--remote", action="store_true", help="run the whole flow on a worker (any worker)")
|
|
184
|
+
x.add_argument("--labels", help="run the whole flow on a worker with these labels (comma-separated)")
|
|
185
|
+
x.add_argument("--worker", help="run the whole flow on this worker")
|
|
186
|
+
x.add_argument("--no-wait", action="store_true", help="print the run id and return")
|
|
187
|
+
x = s.add_parser("runs", help="recent runs")
|
|
188
|
+
x.add_argument("name", nargs="?")
|
|
189
|
+
x.add_argument("--limit", type=int, default=20)
|
|
190
|
+
x = s.add_parser("cancel", help="cancel a run")
|
|
191
|
+
x.add_argument("run_id")
|
|
192
|
+
x = s.add_parser("resume", help="continue an interrupted, failed or cancelled run (done steps are kept)")
|
|
193
|
+
x.add_argument("run_id")
|
|
194
|
+
x = s.add_parser("triggers", help="schedule and webhook triggers, with their next and last runs")
|
|
195
|
+
x.add_argument("name", nargs="?")
|
|
196
|
+
x = s.add_parser("approve", help="answer a run's approval step")
|
|
197
|
+
x.add_argument("run_id")
|
|
198
|
+
x.add_argument("node")
|
|
199
|
+
x.add_argument("--reject", action="store_true")
|
|
200
|
+
s.add_parser("workers", help="remote workers and the job queue")
|
|
201
|
+
s.add_parser("token", help="print a new random token for a worker")
|
|
202
|
+
return ["flows"]
|
|
203
|
+
|
|
204
|
+
@classmethod
|
|
205
|
+
def run_cli(cls, a) -> None:
|
|
206
|
+
_cli(a)
|
|
207
|
+
|
|
208
|
+
def configure(self, ctx, cfg):
|
|
209
|
+
if "flows" not in cfg:
|
|
210
|
+
return None
|
|
211
|
+
return FlowService(ctx.bus, cfg.get("flows"), ctx.data_root)
|
|
212
|
+
|
|
213
|
+
async def start(self) -> None:
|
|
214
|
+
await self.obj.start()
|
|
215
|
+
|
|
216
|
+
async def stop(self) -> None:
|
|
217
|
+
await self.obj.stop()
|
|
218
|
+
|
|
219
|
+
def status(self) -> dict:
|
|
220
|
+
return self.obj.status()
|
|
221
|
+
|
|
222
|
+
def banner(self) -> list[str]:
|
|
223
|
+
out = ["Flows: /plugins/flows/editor.html"]
|
|
224
|
+
d = self.obj.dispatcher
|
|
225
|
+
if d.listen:
|
|
226
|
+
out.append(f"Flows worker API and webhooks: http://{d.listen[0]}:{d.listen[1]}/flows/v1/ "
|
|
227
|
+
f"({len(d.workers)} worker{'s' if len(d.workers) != 1 else ''} listed)")
|
|
228
|
+
return out
|
|
229
|
+
|
|
230
|
+
def side_servers(self):
|
|
231
|
+
d = self.obj.dispatcher
|
|
232
|
+
if not d.listen:
|
|
233
|
+
return []
|
|
234
|
+
return [(create_worker_app(d, self.obj), d.listen[0], d.listen[1])]
|
|
235
|
+
|
|
236
|
+
def tool_defs(self, agent) -> list[dict]:
|
|
237
|
+
return [RUN_FLOW_TOOL] if self.obj.may_run(agent) else []
|
|
238
|
+
|
|
239
|
+
def prompt_note(self, agent) -> str:
|
|
240
|
+
return self.obj.describe_for_agent() if self.obj.may_run(agent) else ""
|
|
241
|
+
|
|
242
|
+
async def call_tool(self, task, agent, name: str, inp: dict) -> str:
|
|
243
|
+
return await self.obj.tool_run(task, agent, inp or {})
|
|
244
|
+
|
|
245
|
+
def routes(self, app, bus) -> None:
|
|
246
|
+
def svc() -> FlowService:
|
|
247
|
+
s = bus.plugins.service("flows")
|
|
248
|
+
if s is None:
|
|
249
|
+
raise HTTPException(404, "flows are off")
|
|
250
|
+
return s
|
|
251
|
+
|
|
252
|
+
@app.get("/api/flows")
|
|
253
|
+
async def flows():
|
|
254
|
+
return svc().list()
|
|
255
|
+
|
|
256
|
+
# runs and workers first: "runs" / "workers" are not flow names (model.RESERVED)
|
|
257
|
+
@app.get("/api/flows/runs")
|
|
258
|
+
async def runs(flow: str | None = None, limit: int = Query(50, ge=1, le=500)):
|
|
259
|
+
return svc().list_runs(flow, limit)
|
|
260
|
+
|
|
261
|
+
@app.get("/api/flows/runs/{run_id}")
|
|
262
|
+
async def run_get(run_id: str):
|
|
263
|
+
s = svc()
|
|
264
|
+
return _call(lambda: s.view(s.get_run(run_id)))
|
|
265
|
+
|
|
266
|
+
@app.post("/api/flows/runs/{run_id}/resume")
|
|
267
|
+
async def run_resume(run_id: str):
|
|
268
|
+
s = svc()
|
|
269
|
+
_call(s.get_run, run_id)
|
|
270
|
+
try:
|
|
271
|
+
return s.view(s.resume(run_id, "user"))
|
|
272
|
+
except ValueError as e:
|
|
273
|
+
raise HTTPException(409, str(e))
|
|
274
|
+
|
|
275
|
+
@app.post("/api/flows/runs/{run_id}/cancel")
|
|
276
|
+
async def run_cancel(run_id: str):
|
|
277
|
+
s = svc()
|
|
278
|
+
_call(s.get_run, run_id)
|
|
279
|
+
try:
|
|
280
|
+
return s.view(await s.cancel(run_id))
|
|
281
|
+
except ValueError as e:
|
|
282
|
+
raise HTTPException(409, str(e))
|
|
283
|
+
|
|
284
|
+
@app.post("/api/flows/runs/{run_id}/approve")
|
|
285
|
+
async def run_approve(run_id: str, body: ApproveIn):
|
|
286
|
+
return _call(svc().approve, run_id, body.node, body.approve, "user")
|
|
287
|
+
|
|
288
|
+
@app.get("/api/flows/approvals")
|
|
289
|
+
async def approvals():
|
|
290
|
+
return svc().pending_approvals()
|
|
291
|
+
|
|
292
|
+
@app.get("/api/flows/triggers")
|
|
293
|
+
async def triggers(flow: str | None = None):
|
|
294
|
+
return svc().trigger_rows(flow)
|
|
295
|
+
|
|
296
|
+
@app.post("/api/flows/hooks/{flow}/{tid}")
|
|
297
|
+
async def hook(flow: str, tid: str, request: Request):
|
|
298
|
+
return await hook_response(svc(), flow, tid, request)
|
|
299
|
+
|
|
300
|
+
@app.get("/api/flows/workers")
|
|
301
|
+
async def workers():
|
|
302
|
+
return svc().dispatcher.status()
|
|
303
|
+
|
|
304
|
+
@app.get("/api/flows/{name}")
|
|
305
|
+
async def flow_get(name: str):
|
|
306
|
+
return _call(svc().get, name)
|
|
307
|
+
|
|
308
|
+
@app.put("/api/flows/{name}")
|
|
309
|
+
async def flow_put(name: str, body: dict):
|
|
310
|
+
s = svc()
|
|
311
|
+
doc = _call(s.save, name, body)
|
|
312
|
+
return {**doc, "warnings": s.warnings(doc)}
|
|
313
|
+
|
|
314
|
+
@app.delete("/api/flows/{name}")
|
|
315
|
+
async def flow_delete(name: str):
|
|
316
|
+
return _call(svc().delete, name)
|
|
317
|
+
|
|
318
|
+
@app.post("/api/flows/{name}/run")
|
|
319
|
+
async def flow_run(name: str, body: RunIn):
|
|
320
|
+
s = svc()
|
|
321
|
+
run = _call(s.start_run, name, body.inputs, "user", body.labels, body.worker, body.remote)
|
|
322
|
+
return s.view(run)
|
xqo_flows/engine.py
ADDED
|
@@ -0,0 +1,272 @@
|
|
|
1
|
+
"""The flow runner: walks a validated flow (model.py) from its start node and runs each step.
|
|
2
|
+
|
|
3
|
+
Execution rules
|
|
4
|
+
- A node starts when every incoming edge is decided. It runs if at least one of them is alive, and is skipped
|
|
5
|
+
(with all its outgoing edges dead) if none is: so a join after a condition waits only for the branch taken.
|
|
6
|
+
- Edges leaving a node run their targets in parallel. A condition makes the edges of its chosen port alive and
|
|
7
|
+
the others dead; an approval does the same with its "approve" / "reject" ports.
|
|
8
|
+
- A failed step fails the run and cancels the steps still going, unless the node has ``continue_on_error``.
|
|
9
|
+
- The run's result is the rendered output of the end node(s) reached, or the last step's result without one.
|
|
10
|
+
|
|
11
|
+
The steps themselves (an xqo task, a remote job, waiting for a person) are done by a ``Steps`` object, so the
|
|
12
|
+
same engine runs on the HQ (service.py) and on a headless worker (xqo-flows-runner)."""
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import asyncio
|
|
16
|
+
import time
|
|
17
|
+
from dataclasses import asdict, dataclass, field
|
|
18
|
+
from typing import Any, Callable
|
|
19
|
+
|
|
20
|
+
from xqo.api import new_id, utcnow
|
|
21
|
+
|
|
22
|
+
from .model import FlowError, check, ports, render
|
|
23
|
+
|
|
24
|
+
FINAL = {"done", "error", "cancelled", "interrupted"}
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
@dataclass
|
|
28
|
+
class Run:
|
|
29
|
+
flow: str
|
|
30
|
+
title: str = ""
|
|
31
|
+
inputs: dict = field(default_factory=dict)
|
|
32
|
+
id: str = field(default_factory=lambda: new_id("frun"))
|
|
33
|
+
status: str = "running" # running | waiting | done | error | cancelled | interrupted
|
|
34
|
+
started: str = field(default_factory=utcnow)
|
|
35
|
+
ended: str | None = None
|
|
36
|
+
result: str = ""
|
|
37
|
+
error: str = ""
|
|
38
|
+
by: str = "user"
|
|
39
|
+
where: str = "hq" # hq | worker:<name> (a whole run sent to a worker) | worker-local
|
|
40
|
+
nodes: dict = field(default_factory=dict) # node id -> {status, title, type, started, ended, output, ...}
|
|
41
|
+
job_id: str | None = None
|
|
42
|
+
trigger: dict | None = None # {id, type} when a schedule or webhook started the run
|
|
43
|
+
resumed: int = 0 # how many times the run was resumed
|
|
44
|
+
remote: dict | None = None # {labels, worker} when the whole run went to a worker
|
|
45
|
+
doc: dict | None = None # the flow as it was when the run started (a resume runs the same version)
|
|
46
|
+
|
|
47
|
+
def to_dict(self) -> dict:
|
|
48
|
+
return asdict(self)
|
|
49
|
+
|
|
50
|
+
@classmethod
|
|
51
|
+
def from_dict(cls, d: dict) -> "Run":
|
|
52
|
+
return cls(**{k: v for k, v in d.items() if k in cls.__dataclass_fields__})
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class Steps:
|
|
56
|
+
"""What a node does. Subclasses implement the kinds they support; the rest fail with a clear message."""
|
|
57
|
+
|
|
58
|
+
where = "this machine"
|
|
59
|
+
|
|
60
|
+
async def agent(self, run: Run, node: dict, prompt: str) -> dict:
|
|
61
|
+
raise FlowError(f"agent steps cannot run on {self.where}")
|
|
62
|
+
|
|
63
|
+
async def remote(self, run: Run, node: dict, prompt: str) -> dict:
|
|
64
|
+
raise FlowError(f"remote steps cannot run on {self.where}")
|
|
65
|
+
|
|
66
|
+
async def approval(self, run: Run, node: dict, question: str) -> str:
|
|
67
|
+
raise FlowError(f"approval steps cannot run on {self.where}")
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
class Engine:
|
|
71
|
+
def __init__(self, steps: Steps, changed: Callable[[Run, str | None], None] = lambda run, node: None):
|
|
72
|
+
self.steps = steps
|
|
73
|
+
self.changed = changed # called after every state change: persist and emit events
|
|
74
|
+
|
|
75
|
+
def _set(self, run: Run, nid: str, **kw) -> None:
|
|
76
|
+
run.nodes[nid].update(kw)
|
|
77
|
+
self.changed(run, nid)
|
|
78
|
+
|
|
79
|
+
async def run(self, doc: dict, run: Run, resume: bool = False) -> Run:
|
|
80
|
+
"""Run a flow. resume=True continues a run record: steps already done keep their results, every other
|
|
81
|
+
step runs again (or is skipped again) as the finished steps decide."""
|
|
82
|
+
nodes = {n["id"]: n for n in doc["nodes"]}
|
|
83
|
+
out_edges: dict[str, list[int]] = {n: [] for n in nodes}
|
|
84
|
+
in_edges: dict[str, list[int]] = {n: [] for n in nodes}
|
|
85
|
+
for i, e in enumerate(doc["edges"]):
|
|
86
|
+
out_edges[e["sourceNodeID"]].append(i)
|
|
87
|
+
in_edges[e["targetNodeID"]].append(i)
|
|
88
|
+
alive: dict[int, bool] = {}
|
|
89
|
+
for nid, n in nodes.items():
|
|
90
|
+
run.nodes.setdefault(nid, {"status": "pending", "title": n["data"].get("title", nid), "type": n["type"]})
|
|
91
|
+
defaults = {i["name"]: i.get("default", "") for i in next(n for n in nodes.values()
|
|
92
|
+
if n["type"] == "start")["data"].get("inputs", [])}
|
|
93
|
+
inputs = {**defaults, **{k: ("" if v is None else str(v)) for k, v in (run.inputs or {}).items()}}
|
|
94
|
+
run.inputs = inputs
|
|
95
|
+
scope: dict[str, Any] = {"inputs": inputs}
|
|
96
|
+
ends: list[str] = []
|
|
97
|
+
last: list[str] = []
|
|
98
|
+
jobs: dict[asyncio.Task, str] = {}
|
|
99
|
+
failure: list[str] = []
|
|
100
|
+
|
|
101
|
+
def decide(nid: str, port: str | None) -> list[str]:
|
|
102
|
+
"""Mark the edges leaving nid alive/dead; return the targets that became ready."""
|
|
103
|
+
ready = []
|
|
104
|
+
for i in out_edges[nid]:
|
|
105
|
+
e = doc["edges"][i]
|
|
106
|
+
alive[i] = port is None or e.get("sourcePortID") == port
|
|
107
|
+
t = e["targetNodeID"]
|
|
108
|
+
if all(j in alive for j in in_edges[t]) and run.nodes[t]["status"] == "pending":
|
|
109
|
+
ready.append(t)
|
|
110
|
+
return ready
|
|
111
|
+
|
|
112
|
+
def skip(nid: str) -> list[str]:
|
|
113
|
+
self._set(run, nid, status="skipped")
|
|
114
|
+
ready = []
|
|
115
|
+
for i in out_edges[nid]:
|
|
116
|
+
alive[i] = False
|
|
117
|
+
t = doc["edges"][i]["targetNodeID"]
|
|
118
|
+
if all(j in alive for j in in_edges[t]) and run.nodes[t]["status"] == "pending":
|
|
119
|
+
ready.append(t)
|
|
120
|
+
return ready
|
|
121
|
+
|
|
122
|
+
def launch(nid: str) -> None:
|
|
123
|
+
if not any(alive.get(i) for i in in_edges[nid]):
|
|
124
|
+
for t in skip(nid):
|
|
125
|
+
launch(t)
|
|
126
|
+
return
|
|
127
|
+
self._set(run, nid, status="running", started=utcnow())
|
|
128
|
+
jobs[asyncio.ensure_future(self._step(run, nodes[nid], scope))] = nid
|
|
129
|
+
|
|
130
|
+
start = next(n for n in nodes.values() if n["type"] == "start")
|
|
131
|
+
scope[start["id"]] = {"result": "", "status": "done", **inputs}
|
|
132
|
+
if resume:
|
|
133
|
+
for nid, st in run.nodes.items():
|
|
134
|
+
if nid in nodes and nid != start["id"] and st.get("status") != "done":
|
|
135
|
+
for k in ("error", "port", "started", "ended", "output", "question", "answer", "answered_by",
|
|
136
|
+
"task_id", "job_id", "worker"):
|
|
137
|
+
st.pop(k, None)
|
|
138
|
+
st["status"] = "pending"
|
|
139
|
+
run.nodes[start["id"]]["status"] = "done"
|
|
140
|
+
ready: list[str] = []
|
|
141
|
+
for nid in topo_order(nodes, doc["edges"]):
|
|
142
|
+
st = run.nodes[nid]
|
|
143
|
+
if st["status"] != "done":
|
|
144
|
+
continue
|
|
145
|
+
if nid != start["id"]:
|
|
146
|
+
scope[nid] = st.get("output") or {"result": "", "status": "done"}
|
|
147
|
+
if nodes[nid]["type"] == "end":
|
|
148
|
+
ends.append(nid)
|
|
149
|
+
elif nodes[nid]["type"] in ("agent", "remote"):
|
|
150
|
+
last.append(nid)
|
|
151
|
+
ready += decide(nid, st.get("port"))
|
|
152
|
+
self.changed(run, None)
|
|
153
|
+
for t in dict.fromkeys(ready):
|
|
154
|
+
if run.nodes[t]["status"] == "pending":
|
|
155
|
+
launch(t)
|
|
156
|
+
else:
|
|
157
|
+
self._set(run, start["id"], status="done", started=run.started, ended=utcnow(), output={"inputs": inputs})
|
|
158
|
+
for t in decide(start["id"], None):
|
|
159
|
+
launch(t)
|
|
160
|
+
try:
|
|
161
|
+
while jobs:
|
|
162
|
+
done, _ = await asyncio.wait(set(jobs), return_when=asyncio.FIRST_COMPLETED)
|
|
163
|
+
for fut in done:
|
|
164
|
+
nid = jobs.pop(fut)
|
|
165
|
+
node = nodes[nid]
|
|
166
|
+
try:
|
|
167
|
+
output, port = fut.result()
|
|
168
|
+
status = output.get("status", "done")
|
|
169
|
+
except asyncio.CancelledError:
|
|
170
|
+
raise
|
|
171
|
+
except Exception as e:
|
|
172
|
+
msg = str(e) if isinstance(e, FlowError) else f"{type(e).__name__}: {e}"
|
|
173
|
+
output, port, status = {"result": "", "status": "error", "error": msg}, None, "error"
|
|
174
|
+
scope[nid] = output
|
|
175
|
+
ok = status == "done" or node["data"].get("continue_on_error")
|
|
176
|
+
self._set(run, nid, status="done" if status == "done" else "error", ended=utcnow(),
|
|
177
|
+
output=output, **({"port": port} if port else {}),
|
|
178
|
+
**({"error": output.get("error") or output.get("result", "")[:2000]}
|
|
179
|
+
if status != "done" else {}))
|
|
180
|
+
if not ok:
|
|
181
|
+
failure.append(f"{node['data'].get('title', nid)}: "
|
|
182
|
+
f"{output.get('error') or output.get('result') or status}"[:2000])
|
|
183
|
+
continue
|
|
184
|
+
if node["type"] == "end":
|
|
185
|
+
ends.append(nid)
|
|
186
|
+
elif node["type"] in ("agent", "remote"):
|
|
187
|
+
last.append(nid)
|
|
188
|
+
for t in decide(nid, port):
|
|
189
|
+
launch(t)
|
|
190
|
+
if failure:
|
|
191
|
+
break
|
|
192
|
+
if failure:
|
|
193
|
+
await self._cancel_all(jobs, run)
|
|
194
|
+
for nid, st in run.nodes.items(): # never reached: behind a failed step
|
|
195
|
+
if st["status"] == "pending":
|
|
196
|
+
st["status"] = "skipped"
|
|
197
|
+
if failure:
|
|
198
|
+
run.status, run.error = "error", failure[0]
|
|
199
|
+
else:
|
|
200
|
+
run.status = "done"
|
|
201
|
+
outs = [scope[n].get("result", "") for n in ends] or ([scope[last[-1]].get("result", "")] if last else [])
|
|
202
|
+
run.result = "\n\n".join(o for o in outs if o)
|
|
203
|
+
except asyncio.CancelledError:
|
|
204
|
+
await self._cancel_all(jobs, run)
|
|
205
|
+
run.status = "cancelled"
|
|
206
|
+
run.error = run.error or "cancelled"
|
|
207
|
+
raise
|
|
208
|
+
finally:
|
|
209
|
+
run.ended = utcnow()
|
|
210
|
+
self.changed(run, None)
|
|
211
|
+
return run
|
|
212
|
+
|
|
213
|
+
async def _cancel_all(self, jobs: dict, run: Run) -> None:
|
|
214
|
+
for fut, nid in jobs.items():
|
|
215
|
+
fut.cancel()
|
|
216
|
+
if jobs:
|
|
217
|
+
await asyncio.wait(set(jobs), timeout=30)
|
|
218
|
+
for nid in jobs.values():
|
|
219
|
+
if run.nodes[nid]["status"] in ("running", "waiting"):
|
|
220
|
+
run.nodes[nid].update(status="cancelled", ended=utcnow())
|
|
221
|
+
jobs.clear()
|
|
222
|
+
|
|
223
|
+
async def _step(self, run: Run, node: dict, scope: dict) -> tuple[dict, str | None]:
|
|
224
|
+
t, d = node["type"], node["data"]
|
|
225
|
+
if t == "agent":
|
|
226
|
+
return await self.steps.agent(run, node, render(d["prompt"], scope)), None
|
|
227
|
+
if t == "remote":
|
|
228
|
+
return await self.steps.remote(run, node, render(d["prompt"], scope)), None
|
|
229
|
+
if t == "condition":
|
|
230
|
+
for c in d["conditions"]:
|
|
231
|
+
if check(c, scope):
|
|
232
|
+
return {"result": c["key"], "status": "done"}, c["key"]
|
|
233
|
+
return {"result": "else", "status": "done"}, "else"
|
|
234
|
+
if t == "approval":
|
|
235
|
+
self._set(run, node["id"], status="waiting")
|
|
236
|
+
answer = await self.steps.approval(run, node, render(d["question"], scope))
|
|
237
|
+
if answer not in ports(node):
|
|
238
|
+
raise FlowError(f"approval answer must be approve or reject, got {answer!r}")
|
|
239
|
+
self._set(run, node["id"], status="running")
|
|
240
|
+
return {"result": answer, "status": "done"}, answer
|
|
241
|
+
if t == "end":
|
|
242
|
+
return {"result": render(d.get("output", ""), scope), "status": "done"}, None
|
|
243
|
+
raise FlowError(f"unknown node type {t}")
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
def topo_order(nodes: dict, edges: list[dict]) -> list[str]:
|
|
247
|
+
"""Node ids so that every edge goes forward (flows are acyclic; model.validate checks it)."""
|
|
248
|
+
indeg = {n: 0 for n in nodes}
|
|
249
|
+
for e in edges:
|
|
250
|
+
indeg[e["targetNodeID"]] += 1
|
|
251
|
+
queue = [n for n, d in indeg.items() if d == 0]
|
|
252
|
+
out = []
|
|
253
|
+
while queue:
|
|
254
|
+
n = queue.pop(0)
|
|
255
|
+
out.append(n)
|
|
256
|
+
for e in edges:
|
|
257
|
+
if e["sourceNodeID"] == n:
|
|
258
|
+
indeg[e["targetNodeID"]] -= 1
|
|
259
|
+
if indeg[e["targetNodeID"]] == 0:
|
|
260
|
+
queue.append(e["targetNodeID"])
|
|
261
|
+
return out
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
async def wait_for(fut: asyncio.Future, timeout: float | None):
|
|
265
|
+
"""asyncio.wait_for that leaves `fut` running when it times out (the caller decides what to do)."""
|
|
266
|
+
if timeout is None:
|
|
267
|
+
return await asyncio.shield(fut)
|
|
268
|
+
t0 = time.monotonic()
|
|
269
|
+
done, _ = await asyncio.wait({fut}, timeout=timeout)
|
|
270
|
+
if not done:
|
|
271
|
+
raise asyncio.TimeoutError(f"no answer after {time.monotonic() - t0:.0f}s")
|
|
272
|
+
return fut.result()
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "draft-review-approve",
|
|
3
|
+
"title": "Draft, review, approve",
|
|
4
|
+
"description": "Two drafts in parallel, a review that picks one, a check, and your approval before the final step.",
|
|
5
|
+
"nodes": [
|
|
6
|
+
{"id": "start_0", "type": "start", "meta": {"position": {"x": 0, "y": 160}},
|
|
7
|
+
"data": {"title": "Start", "inputs": [{"name": "topic", "default": "a release note for the next version"}]}},
|
|
8
|
+
{"id": "draft_a", "type": "agent", "meta": {"position": {"x": 360, "y": 0}},
|
|
9
|
+
"data": {"title": "Draft A", "agent": "", "prompt": "Write a short draft of {{inputs.topic}}. Plain and direct."}},
|
|
10
|
+
{"id": "draft_b", "type": "agent", "meta": {"position": {"x": 360, "y": 320}},
|
|
11
|
+
"data": {"title": "Draft B", "agent": "", "prompt": "Write a short draft of {{inputs.topic}}. Friendly tone."}},
|
|
12
|
+
{"id": "review", "type": "agent", "meta": {"position": {"x": 740, "y": 160}},
|
|
13
|
+
"data": {"title": "Review", "agent": "", "prompt": "Pick the better draft and improve it. Start your answer with OK if it is ready, or REDO if neither works.\n\nA:\n{{draft_a.result}}\n\nB:\n{{draft_b.result}}"}},
|
|
14
|
+
{"id": "check", "type": "condition", "meta": {"position": {"x": 1120, "y": 160}},
|
|
15
|
+
"data": {"title": "Ready?", "conditions": [{"key": "ok", "left": "{{review.result}}", "op": "matches", "right": "^\\s*OK"}]}},
|
|
16
|
+
{"id": "approve", "type": "approval", "meta": {"position": {"x": 1480, "y": 60}},
|
|
17
|
+
"data": {"title": "Your approval", "question": "Publish this?\n\n{{review.result}}", "default": "reject"}},
|
|
18
|
+
{"id": "publish", "type": "agent", "meta": {"position": {"x": 1840, "y": 0}},
|
|
19
|
+
"data": {"title": "Finalize", "agent": "", "prompt": "Turn this into the final text, without the OK marker:\n\n{{review.result}}"}},
|
|
20
|
+
{"id": "end_ok", "type": "end", "meta": {"position": {"x": 2200, "y": 0}},
|
|
21
|
+
"data": {"title": "Published", "output": "{{publish.result}}"}},
|
|
22
|
+
{"id": "end_no", "type": "end", "meta": {"position": {"x": 1840, "y": 300}},
|
|
23
|
+
"data": {"title": "Not published", "output": "Not published ({{check.result}} / {{approve.result}}):\n\n{{review.result}}"}}
|
|
24
|
+
],
|
|
25
|
+
"edges": [
|
|
26
|
+
{"sourceNodeID": "start_0", "targetNodeID": "draft_a"},
|
|
27
|
+
{"sourceNodeID": "start_0", "targetNodeID": "draft_b"},
|
|
28
|
+
{"sourceNodeID": "draft_a", "targetNodeID": "review"},
|
|
29
|
+
{"sourceNodeID": "draft_b", "targetNodeID": "review"},
|
|
30
|
+
{"sourceNodeID": "review", "targetNodeID": "check"},
|
|
31
|
+
{"sourceNodeID": "check", "targetNodeID": "approve", "sourcePortID": "ok"},
|
|
32
|
+
{"sourceNodeID": "check", "targetNodeID": "end_no", "sourcePortID": "else"},
|
|
33
|
+
{"sourceNodeID": "approve", "targetNodeID": "publish", "sourcePortID": "approve"},
|
|
34
|
+
{"sourceNodeID": "approve", "targetNodeID": "end_no", "sourcePortID": "reject"},
|
|
35
|
+
{"sourceNodeID": "publish", "targetNodeID": "end_ok"}
|
|
36
|
+
]
|
|
37
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "hello",
|
|
3
|
+
"title": "Hello flow",
|
|
4
|
+
"description": "One agent step: the default agent answers a question. Edit it, then press Run.",
|
|
5
|
+
"nodes": [
|
|
6
|
+
{"id": "start_0", "type": "start", "meta": {"position": {"x": 0, "y": 0}},
|
|
7
|
+
"data": {"title": "Start", "inputs": [{"name": "question", "default": "What can this HQ do?"}]}},
|
|
8
|
+
{"id": "answer", "type": "agent", "meta": {"position": {"x": 380, "y": 0}},
|
|
9
|
+
"data": {"title": "Answer", "agent": "", "prompt": "Answer briefly: {{inputs.question}}"}},
|
|
10
|
+
{"id": "end_0", "type": "end", "meta": {"position": {"x": 760, "y": 0}},
|
|
11
|
+
"data": {"title": "End", "output": "{{answer.result}}"}}
|
|
12
|
+
],
|
|
13
|
+
"edges": [
|
|
14
|
+
{"sourceNodeID": "start_0", "targetNodeID": "answer"},
|
|
15
|
+
{"sourceNodeID": "answer", "targetNodeID": "end_0"}
|
|
16
|
+
]
|
|
17
|
+
}
|