dap-engine 0.3.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.
- dap_engine/__init__.py +3 -0
- dap_engine/__main__.py +80 -0
- dap_engine/api/__init__.py +0 -0
- dap_engine/api/agents.py +546 -0
- dap_engine/api/deps.py +60 -0
- dap_engine/api/health.py +20 -0
- dap_engine/api/pipelines.py +428 -0
- dap_engine/api/projects.py +191 -0
- dap_engine/api/runs.py +694 -0
- dap_engine/api/runtimes.py +29 -0
- dap_engine/api/schemas.py +331 -0
- dap_engine/api/settings.py +288 -0
- dap_engine/app.py +438 -0
- dap_engine/auth/__init__.py +23 -0
- dap_engine/auth/admin_users_routes.py +134 -0
- dap_engine/auth/api_token_routes.py +345 -0
- dap_engine/auth/api_tokens.py +147 -0
- dap_engine/auth/audit.py +91 -0
- dap_engine/auth/audit_routes.py +125 -0
- dap_engine/auth/db.py +135 -0
- dap_engine/auth/oauth.py +41 -0
- dap_engine/auth/policies.py +64 -0
- dap_engine/auth/schemas.py +37 -0
- dap_engine/auth/users.py +400 -0
- dap_engine/contracts.py +205 -0
- dap_engine/execution/__init__.py +30 -0
- dap_engine/execution/conditions.py +87 -0
- dap_engine/execution/node_executor.py +363 -0
- dap_engine/execution/output_parser.py +162 -0
- dap_engine/execution/run_orchestrator.py +213 -0
- dap_engine/execution/run_registry.py +158 -0
- dap_engine/execution/runner.py +422 -0
- dap_engine/execution/validator.py +580 -0
- dap_engine/persistence/__init__.py +0 -0
- dap_engine/persistence/_common.py +24 -0
- dap_engine/persistence/agents.py +410 -0
- dap_engine/persistence/db.py +179 -0
- dap_engine/persistence/migrations.py +739 -0
- dap_engine/persistence/models.py +569 -0
- dap_engine/persistence/pipelines.py +328 -0
- dap_engine/persistence/projects.py +256 -0
- dap_engine/persistence/repository.py +101 -0
- dap_engine/persistence/runs.py +482 -0
- dap_engine/py.typed +0 -0
- dap_engine-0.3.0.dist-info/METADATA +49 -0
- dap_engine-0.3.0.dist-info/RECORD +48 -0
- dap_engine-0.3.0.dist-info/WHEEL +4 -0
- dap_engine-0.3.0.dist-info/entry_points.txt +2 -0
|
@@ -0,0 +1,422 @@
|
|
|
1
|
+
"""PipelineRunner — converts a Pipeline JSON into a LangGraph StateGraph and runs it.
|
|
2
|
+
|
|
3
|
+
Optional `checkpointer` enables LangGraph state persistence — required for
|
|
4
|
+
pause/resume. When supplied, `run_id` doubles as the LangGraph thread_id.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import dataclasses
|
|
10
|
+
import logging
|
|
11
|
+
from typing import TYPE_CHECKING, Any
|
|
12
|
+
|
|
13
|
+
from dap_runtimes import RuntimeRegistry
|
|
14
|
+
from dap_types import Pipeline, PipelineState
|
|
15
|
+
from dap_types.pipeline import PipelineEdge
|
|
16
|
+
from langgraph.graph import END, START, StateGraph
|
|
17
|
+
from sqlalchemy import select
|
|
18
|
+
from sqlalchemy.orm import Session
|
|
19
|
+
|
|
20
|
+
from dap_engine.execution.conditions import evaluate_condition
|
|
21
|
+
from dap_engine.execution.node_executor import NodeContext, make_node_fn
|
|
22
|
+
from dap_engine.persistence.models import (
|
|
23
|
+
AgentORM,
|
|
24
|
+
AgentVersionORM,
|
|
25
|
+
PipelineORM,
|
|
26
|
+
PipelineVersionORM,
|
|
27
|
+
ProjectORM,
|
|
28
|
+
RunORM,
|
|
29
|
+
)
|
|
30
|
+
|
|
31
|
+
if TYPE_CHECKING:
|
|
32
|
+
from langgraph.checkpoint.base import BaseCheckpointSaver
|
|
33
|
+
|
|
34
|
+
logger = logging.getLogger("dap.engine.execution.runner")
|
|
35
|
+
|
|
36
|
+
DEFAULT_RECURSION_LIMIT = 50
|
|
37
|
+
|
|
38
|
+
# Mode for rewind_and_run() — see method docstring.
|
|
39
|
+
REWIND_RETRY = "retry"
|
|
40
|
+
REWIND_SKIP = "skip"
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class RunnerError(Exception):
|
|
44
|
+
"""Raised when pipeline cannot be built or executed."""
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class CheckpointNotFoundError(RunnerError):
|
|
48
|
+
"""Raised when no checkpoint matches the requested rewind target."""
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class RunnerInterrupt(Exception):
|
|
52
|
+
"""Raised when the graph pauses at an approval-required node (interrupt_before).
|
|
53
|
+
|
|
54
|
+
This is a *normal* stop, not an error — the run should be marked as
|
|
55
|
+
``paused`` and resumed later via ``POST /runs/{id}/resume`` or the
|
|
56
|
+
semantically clearer ``POST /runs/{id}/nodes/{node_id}/approve``.
|
|
57
|
+
|
|
58
|
+
Attributes:
|
|
59
|
+
next_nodes: LangGraph nodes staged as next when the interrupt fired.
|
|
60
|
+
"""
|
|
61
|
+
|
|
62
|
+
def __init__(self, next_nodes: list[str]) -> None:
|
|
63
|
+
self.next_nodes = next_nodes
|
|
64
|
+
super().__init__(f"Pipeline paused before: {next_nodes}")
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
@dataclasses.dataclass(frozen=True)
|
|
68
|
+
class _ProjectContext:
|
|
69
|
+
"""Project context propagated into NodeContext (#65).
|
|
70
|
+
|
|
71
|
+
Captured once at run start so the same values flow through every
|
|
72
|
+
node — avoids re-querying the project for each node and keeps
|
|
73
|
+
behaviour stable if the project is edited mid-run.
|
|
74
|
+
"""
|
|
75
|
+
|
|
76
|
+
working_directory: str | None
|
|
77
|
+
env_vars: dict[str, str]
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
class PipelineRunner:
|
|
81
|
+
"""Build a LangGraph StateGraph from a pipeline JSON and execute it."""
|
|
82
|
+
|
|
83
|
+
def __init__(
|
|
84
|
+
self,
|
|
85
|
+
*,
|
|
86
|
+
session: Session,
|
|
87
|
+
registry: RuntimeRegistry,
|
|
88
|
+
checkpointer: BaseCheckpointSaver[Any] | None = None,
|
|
89
|
+
recursion_limit: int = DEFAULT_RECURSION_LIMIT,
|
|
90
|
+
) -> None:
|
|
91
|
+
self.session = session
|
|
92
|
+
self.registry = registry
|
|
93
|
+
self.checkpointer = checkpointer
|
|
94
|
+
self.recursion_limit = recursion_limit
|
|
95
|
+
|
|
96
|
+
async def run(
|
|
97
|
+
self,
|
|
98
|
+
*,
|
|
99
|
+
run_id: str,
|
|
100
|
+
pipeline_orm: PipelineORM,
|
|
101
|
+
pipeline_version_orm: PipelineVersionORM,
|
|
102
|
+
initial_state: PipelineState | None,
|
|
103
|
+
resume: bool = False,
|
|
104
|
+
) -> PipelineState:
|
|
105
|
+
"""Build graph for the given pipeline version + run end-to-end.
|
|
106
|
+
|
|
107
|
+
Returns the final PipelineState. Persists snapshots + node logs along
|
|
108
|
+
the way via the bound Session (caller commits).
|
|
109
|
+
|
|
110
|
+
When `resume=True`, `initial_state` is ignored and LangGraph resumes
|
|
111
|
+
from the checkpointed state for the given `run_id` (used as thread_id).
|
|
112
|
+
Requires a checkpointer to be configured.
|
|
113
|
+
"""
|
|
114
|
+
if resume and self.checkpointer is None:
|
|
115
|
+
msg = "Cannot resume without a checkpointer"
|
|
116
|
+
raise RunnerError(msg)
|
|
117
|
+
if not resume and initial_state is None:
|
|
118
|
+
msg = "initial_state required when resume=False"
|
|
119
|
+
raise RunnerError(msg)
|
|
120
|
+
|
|
121
|
+
pipeline = self._pipeline_from_orm(pipeline_orm, pipeline_version_orm)
|
|
122
|
+
|
|
123
|
+
# Pre-load agents referenced by the pipeline + verify they exist.
|
|
124
|
+
agent_lookup = self._load_agents(pipeline)
|
|
125
|
+
|
|
126
|
+
# Project context (#65) — working_directory + env_vars overlay.
|
|
127
|
+
# Bails out with a descriptive RunnerError when the bound project
|
|
128
|
+
# has been archived between trigger and execution (e.g. resumed
|
|
129
|
+
# paused run after the user archived the project).
|
|
130
|
+
project_context = self._load_project_context(run_id)
|
|
131
|
+
|
|
132
|
+
graph = self._build_graph(
|
|
133
|
+
run_id=run_id,
|
|
134
|
+
pipeline=pipeline,
|
|
135
|
+
agent_lookup=agent_lookup,
|
|
136
|
+
project_context=project_context,
|
|
137
|
+
)
|
|
138
|
+
|
|
139
|
+
config: dict[str, Any] = {"recursion_limit": self.recursion_limit}
|
|
140
|
+
if self.checkpointer is not None:
|
|
141
|
+
config["configurable"] = {"thread_id": run_id}
|
|
142
|
+
|
|
143
|
+
invoke_input: PipelineState | None = None if resume else initial_state
|
|
144
|
+
|
|
145
|
+
approval_nodes = set(pipeline.defaults.approval_required_nodes)
|
|
146
|
+
|
|
147
|
+
try:
|
|
148
|
+
result = await graph.ainvoke(invoke_input, config=config)
|
|
149
|
+
except Exception as exc:
|
|
150
|
+
logger.exception("pipeline execution failed for run %s", run_id)
|
|
151
|
+
msg = f"Execution failed: {type(exc).__name__}: {exc}"
|
|
152
|
+
raise RunnerError(msg) from exc
|
|
153
|
+
|
|
154
|
+
# Detect interrupt_before pause: when approval_required_nodes is configured
|
|
155
|
+
# and the graph stopped early, aget_state().next contains the gated node.
|
|
156
|
+
# This is a normal stop — raise RunnerInterrupt so the caller marks the
|
|
157
|
+
# run as paused rather than finalized (#164).
|
|
158
|
+
if approval_nodes and self.checkpointer is not None:
|
|
159
|
+
checkpoint_config: dict[str, Any] = {"configurable": {"thread_id": run_id}}
|
|
160
|
+
snap = await graph.aget_state(checkpoint_config)
|
|
161
|
+
pending = list(snap.next) if snap.next else []
|
|
162
|
+
if pending and any(n in approval_nodes for n in pending):
|
|
163
|
+
logger.info("run %s interrupted before approval node(s): %s", run_id, pending)
|
|
164
|
+
raise RunnerInterrupt(next_nodes=pending)
|
|
165
|
+
|
|
166
|
+
return PipelineState.model_validate(result)
|
|
167
|
+
|
|
168
|
+
async def rewind_and_run(
|
|
169
|
+
self,
|
|
170
|
+
*,
|
|
171
|
+
run_id: str,
|
|
172
|
+
pipeline_orm: PipelineORM,
|
|
173
|
+
pipeline_version_orm: PipelineVersionORM,
|
|
174
|
+
target_node: str,
|
|
175
|
+
mode: str,
|
|
176
|
+
) -> PipelineState:
|
|
177
|
+
"""Rewind the graph to just before `target_node`, then resume.
|
|
178
|
+
|
|
179
|
+
- ``mode="retry"``: rewind so the next step is `target_node`; resume
|
|
180
|
+
re-executes that node.
|
|
181
|
+
- ``mode="skip"``: pretend `target_node` ran with no state changes;
|
|
182
|
+
resume proceeds to its downstream successors.
|
|
183
|
+
|
|
184
|
+
Both modes require a checkpointer and a prior execution that reached
|
|
185
|
+
the target node. Raises ``CheckpointNotFoundError`` when no historical
|
|
186
|
+
checkpoint has the target node staged as next.
|
|
187
|
+
"""
|
|
188
|
+
if self.checkpointer is None:
|
|
189
|
+
msg = "Cannot rewind without a checkpointer"
|
|
190
|
+
raise RunnerError(msg)
|
|
191
|
+
if mode not in {REWIND_RETRY, REWIND_SKIP}:
|
|
192
|
+
msg = f"Unknown rewind mode: {mode}"
|
|
193
|
+
raise RunnerError(msg)
|
|
194
|
+
|
|
195
|
+
pipeline = self._pipeline_from_orm(pipeline_orm, pipeline_version_orm)
|
|
196
|
+
agent_lookup = self._load_agents(pipeline)
|
|
197
|
+
project_context = self._load_project_context(run_id)
|
|
198
|
+
graph = self._build_graph(
|
|
199
|
+
run_id=run_id,
|
|
200
|
+
pipeline=pipeline,
|
|
201
|
+
agent_lookup=agent_lookup,
|
|
202
|
+
project_context=project_context,
|
|
203
|
+
)
|
|
204
|
+
|
|
205
|
+
base_config: dict[str, Any] = {"configurable": {"thread_id": run_id}}
|
|
206
|
+
|
|
207
|
+
# Find the most recent checkpoint where `target_node` is the next
|
|
208
|
+
# step to execute. aget_state_history yields newest-first.
|
|
209
|
+
target_config: dict[str, Any] | None = None
|
|
210
|
+
async for snapshot in graph.aget_state_history(base_config):
|
|
211
|
+
if target_node in (snapshot.next or ()):
|
|
212
|
+
target_config = snapshot.config
|
|
213
|
+
break
|
|
214
|
+
|
|
215
|
+
if target_config is None:
|
|
216
|
+
msg = (
|
|
217
|
+
f"No checkpoint found where '{target_node}' is staged as next. "
|
|
218
|
+
f"The node may not have been reached during prior execution."
|
|
219
|
+
)
|
|
220
|
+
raise CheckpointNotFoundError(msg)
|
|
221
|
+
|
|
222
|
+
# Branch from the historical checkpoint: aupdate_state writes a new
|
|
223
|
+
# checkpoint and returns its config; subsequent ainvoke runs from it.
|
|
224
|
+
if mode == REWIND_SKIP:
|
|
225
|
+
new_config = await graph.aupdate_state(target_config, values={}, as_node=target_node)
|
|
226
|
+
else: # retry
|
|
227
|
+
# values=None + no as_node → no logical change, but we still get
|
|
228
|
+
# a new branch tip from which the target node will run again.
|
|
229
|
+
new_config = await graph.aupdate_state(target_config, values=None)
|
|
230
|
+
|
|
231
|
+
invoke_config: dict[str, Any] = {"recursion_limit": self.recursion_limit}
|
|
232
|
+
invoke_config["configurable"] = new_config["configurable"]
|
|
233
|
+
|
|
234
|
+
try:
|
|
235
|
+
result = await graph.ainvoke(None, config=invoke_config)
|
|
236
|
+
except Exception as exc:
|
|
237
|
+
logger.exception("pipeline rewind/run failed for run %s", run_id)
|
|
238
|
+
msg = f"Execution failed: {type(exc).__name__}: {exc}"
|
|
239
|
+
raise RunnerError(msg) from exc
|
|
240
|
+
|
|
241
|
+
return PipelineState.model_validate(result)
|
|
242
|
+
|
|
243
|
+
# -----------------------------------------------------------------------
|
|
244
|
+
# Graph construction
|
|
245
|
+
# -----------------------------------------------------------------------
|
|
246
|
+
|
|
247
|
+
def _build_graph(
|
|
248
|
+
self,
|
|
249
|
+
*,
|
|
250
|
+
run_id: str,
|
|
251
|
+
pipeline: Pipeline,
|
|
252
|
+
agent_lookup: dict[str, tuple[AgentORM, AgentVersionORM]],
|
|
253
|
+
project_context: _ProjectContext | None = None,
|
|
254
|
+
) -> Any:
|
|
255
|
+
builder = StateGraph(PipelineState)
|
|
256
|
+
|
|
257
|
+
for node in pipeline.nodes:
|
|
258
|
+
agent, version = agent_lookup[node.agent_id]
|
|
259
|
+
ctx = NodeContext(
|
|
260
|
+
run_id=run_id,
|
|
261
|
+
node_id=node.id,
|
|
262
|
+
agent=agent,
|
|
263
|
+
agent_version=version,
|
|
264
|
+
registry=self.registry,
|
|
265
|
+
session=self.session,
|
|
266
|
+
runtime_overrides=(node.overrides.runtime_config if node.overrides else None),
|
|
267
|
+
timeout_override_ms=(node.overrides.timeout_ms if node.overrides else None),
|
|
268
|
+
project_working_directory=(
|
|
269
|
+
project_context.working_directory if project_context else None
|
|
270
|
+
),
|
|
271
|
+
project_env_vars=(dict(project_context.env_vars) if project_context else None),
|
|
272
|
+
)
|
|
273
|
+
builder.add_node(node.id, make_node_fn(ctx)) # type: ignore[call-overload]
|
|
274
|
+
|
|
275
|
+
# Entry edge
|
|
276
|
+
if pipeline.entry_point not in {n.id for n in pipeline.nodes}:
|
|
277
|
+
msg = f"entry_point '{pipeline.entry_point}' not in pipeline.nodes"
|
|
278
|
+
raise RunnerError(msg)
|
|
279
|
+
builder.add_edge(START, pipeline.entry_point)
|
|
280
|
+
|
|
281
|
+
# Group edges by source node, then add either unconditional or conditional.
|
|
282
|
+
edges_by_source: dict[str, list[PipelineEdge]] = {}
|
|
283
|
+
for edge in pipeline.edges:
|
|
284
|
+
edges_by_source.setdefault(edge.source, []).append(edge)
|
|
285
|
+
|
|
286
|
+
for source, edges in edges_by_source.items():
|
|
287
|
+
if source in (START, "__start__"):
|
|
288
|
+
continue # entry edge already handled above
|
|
289
|
+
if all(e.condition is None for e in edges):
|
|
290
|
+
# Single straight edge per source. Multiple unconditional edges
|
|
291
|
+
# would be ambiguous — pick the first.
|
|
292
|
+
target = _resolve_target(edges[0].target)
|
|
293
|
+
builder.add_edge(source, target)
|
|
294
|
+
else:
|
|
295
|
+
_add_conditional_edges(builder, source, edges)
|
|
296
|
+
|
|
297
|
+
# approval_required_nodes drives interrupt_before so LangGraph pauses
|
|
298
|
+
# automatically before those nodes. RunnerInterrupt is raised in run()
|
|
299
|
+
# when the graph stops early at one of these gates (#164).
|
|
300
|
+
interrupt_nodes = list(pipeline.defaults.approval_required_nodes)
|
|
301
|
+
return builder.compile(
|
|
302
|
+
checkpointer=self.checkpointer,
|
|
303
|
+
interrupt_before=interrupt_nodes or [],
|
|
304
|
+
)
|
|
305
|
+
|
|
306
|
+
def _load_project_context(self, run_id: str) -> _ProjectContext | None:
|
|
307
|
+
"""Resolve the run's project, if any, into a ``_ProjectContext``.
|
|
308
|
+
|
|
309
|
+
- Returns ``None`` for ad-hoc runs (no ``project_id``) — keeps
|
|
310
|
+
legacy behaviour with ``working_directory="."`` and no env
|
|
311
|
+
overlay.
|
|
312
|
+
- Raises ``RunnerError`` if the bound project has been
|
|
313
|
+
archived between trigger and execution. The trigger
|
|
314
|
+
endpoint already 422s archived projects (#64), but a paused
|
|
315
|
+
run resumed after the project was archived would still
|
|
316
|
+
land here.
|
|
317
|
+
"""
|
|
318
|
+
run = self.session.get(RunORM, run_id)
|
|
319
|
+
if run is None or run.project_id is None:
|
|
320
|
+
return None
|
|
321
|
+
project = self.session.get(ProjectORM, run.project_id)
|
|
322
|
+
if project is None:
|
|
323
|
+
msg = f"Project not found: {run.project_id}"
|
|
324
|
+
raise RunnerError(msg)
|
|
325
|
+
if project.archived_at is not None:
|
|
326
|
+
msg = f"Project is archived: {run.project_id}"
|
|
327
|
+
raise RunnerError(msg)
|
|
328
|
+
return _ProjectContext(
|
|
329
|
+
working_directory=project.working_directory,
|
|
330
|
+
env_vars=dict(project.env_vars),
|
|
331
|
+
)
|
|
332
|
+
|
|
333
|
+
# -----------------------------------------------------------------------
|
|
334
|
+
# ORM helpers
|
|
335
|
+
# -----------------------------------------------------------------------
|
|
336
|
+
|
|
337
|
+
def _pipeline_from_orm(
|
|
338
|
+
self,
|
|
339
|
+
pipeline_orm: PipelineORM,
|
|
340
|
+
version_orm: PipelineVersionORM,
|
|
341
|
+
) -> Pipeline:
|
|
342
|
+
from dap_types.pipeline import ( # noqa: PLC0415 — break circular pretty-fmt
|
|
343
|
+
PipelineDefaults,
|
|
344
|
+
PipelineEdge,
|
|
345
|
+
PipelineNode,
|
|
346
|
+
)
|
|
347
|
+
|
|
348
|
+
return Pipeline(
|
|
349
|
+
id=pipeline_orm.id,
|
|
350
|
+
name=pipeline_orm.name,
|
|
351
|
+
description=pipeline_orm.description,
|
|
352
|
+
version=version_orm.version,
|
|
353
|
+
schema_version=version_orm.schema_version, # type: ignore[arg-type]
|
|
354
|
+
state_schema_ref=version_orm.state_schema_ref,
|
|
355
|
+
entry_point=version_orm.entry_point,
|
|
356
|
+
nodes=[PipelineNode.model_validate(n) for n in version_orm.nodes],
|
|
357
|
+
edges=[PipelineEdge.model_validate(e) for e in version_orm.edges],
|
|
358
|
+
defaults=PipelineDefaults.model_validate(version_orm.defaults),
|
|
359
|
+
created_at=pipeline_orm.created_at,
|
|
360
|
+
updated_at=pipeline_orm.updated_at,
|
|
361
|
+
is_active=pipeline_orm.archived_at is None,
|
|
362
|
+
)
|
|
363
|
+
|
|
364
|
+
def _load_agents(
|
|
365
|
+
self,
|
|
366
|
+
pipeline: Pipeline,
|
|
367
|
+
) -> dict[str, tuple[AgentORM, AgentVersionORM]]:
|
|
368
|
+
lookup: dict[str, tuple[AgentORM, AgentVersionORM]] = {}
|
|
369
|
+
for node in pipeline.nodes:
|
|
370
|
+
agent_id = node.agent_id
|
|
371
|
+
if agent_id in lookup:
|
|
372
|
+
continue
|
|
373
|
+
agent = self.session.get(AgentORM, agent_id)
|
|
374
|
+
if agent is None:
|
|
375
|
+
msg = f"Pipeline references unknown agent: {agent_id}"
|
|
376
|
+
raise RunnerError(msg)
|
|
377
|
+
version_orm = self.session.scalar(
|
|
378
|
+
select(AgentVersionORM)
|
|
379
|
+
.where(AgentVersionORM.agent_id == agent_id)
|
|
380
|
+
.where(AgentVersionORM.version == agent.current_version)
|
|
381
|
+
)
|
|
382
|
+
if version_orm is None:
|
|
383
|
+
msg = (
|
|
384
|
+
f"Agent {agent_id} has current_version={agent.current_version} "
|
|
385
|
+
f"but no version row found"
|
|
386
|
+
)
|
|
387
|
+
raise RunnerError(msg)
|
|
388
|
+
lookup[agent_id] = (agent, version_orm)
|
|
389
|
+
return lookup
|
|
390
|
+
|
|
391
|
+
|
|
392
|
+
def _resolve_target(target: str) -> Any:
|
|
393
|
+
"""Map sentinel '__end__' / END to LangGraph END constant."""
|
|
394
|
+
if target in (END, "__end__"):
|
|
395
|
+
return END
|
|
396
|
+
return target
|
|
397
|
+
|
|
398
|
+
|
|
399
|
+
def _add_conditional_edges(
|
|
400
|
+
builder: StateGraph[PipelineState, None, PipelineState, PipelineState],
|
|
401
|
+
source: str,
|
|
402
|
+
edges: list[PipelineEdge],
|
|
403
|
+
) -> None:
|
|
404
|
+
"""Wire conditional edges from `source` based on EdgeCondition matching."""
|
|
405
|
+
|
|
406
|
+
# Pre-extract for closure capture.
|
|
407
|
+
edge_specs = [(e.condition, _resolve_target(e.target)) for e in edges]
|
|
408
|
+
|
|
409
|
+
def chooser(state: PipelineState) -> str:
|
|
410
|
+
"""Return target node id (or END sentinel) for current state."""
|
|
411
|
+
for cond, target in edge_specs:
|
|
412
|
+
if cond is None or evaluate_condition(cond, state):
|
|
413
|
+
return str(target)
|
|
414
|
+
return str(END)
|
|
415
|
+
|
|
416
|
+
# LangGraph's add_conditional_edges needs a path_map. Build the union of
|
|
417
|
+
# possible targets so the framework knows the node graph topology.
|
|
418
|
+
targets = {target for _, target in edge_specs}
|
|
419
|
+
targets.add(END)
|
|
420
|
+
path_map = {t: t for t in targets}
|
|
421
|
+
|
|
422
|
+
builder.add_conditional_edges(source, chooser, path_map)
|