operonx.core¶
Engine, op decorators, graph composition, state markers, and middleware. This page is the primary public surface — everything you need to build and run a workflow without touching providers or telemetry.
Engine¶
Operon
¶
Operon(
graph: Union[GraphOp, Callable[..., GraphOp]],
*,
params: Optional[Dict[str, Any]] = None,
trace: Optional[Union[str, Consumer, List[Union[str, Consumer]]]] = None,
errors: str = "record",
max_concurrency: Optional[int] = None,
journal: Any = None,
durability: str = "async",
on_resume: str = "restart",
carry: Sequence[str] = (),
)
Workflow execution engine.
Operon takes a GraphOp and provides execution capabilities: - Builds and validates the graph structure - Creates state schema for data flow - Executes workflows with fresh state per run - Integrates with tracers for observability
Attributes:
| Name | Type | Description |
|---|---|---|
graph |
The GraphOp to execute |
|
name |
Workflow name (from graph) |
|
schema |
StateSchema
|
State schema for the workflow |
Example
# Define graph
with GraphOp(name="chatbot") as graph:
llm = LLMOp(name="llm", resource="gpt-4o", inputs={"prompt": ...})
START >> llm >> END
# Create engine (builds automatically)
engine = Operon(graph)
# Run multiple times with fresh state
result = await engine.run(inputs={"query": "Hello!"})
print(result["response"]) # workflow output
print(result["$state"]) # MemoryState for debugging
# Or use callable syntax
result = await engine({"query": "Goodbye!"})
Initialize Operon engine with a GraphOp or a graph factory.
Pure orchestrator — does not load .env or resources.yaml.
Call :func:operonx.bootstrap (or :meth:ResourceHub.from_yaml directly)
before constructing the engine if your graph uses provider ops.
Pure-compute graphs need no setup.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
graph
|
Union[GraphOp, Callable[..., GraphOp]]
|
A GraphOp workflow, or a callable that returns one.
When a callable is passed, it is invoked with |
required |
params
|
Optional[Dict[str, Any]]
|
Keyword arguments passed to the graph factory. Ignored
when graph is already a GraphOp. Defaults to |
None
|
trace
|
Optional[Union[str, Consumer, List[Union[str, Consumer]]]]
|
V3 tracing. Accepts a ResourceHub key (str),
a :class: |
None
|
errors
|
str
|
What a run does when an op fails. |
'record'
|
max_concurrency
|
Optional[int]
|
The most ops of one run that may be running at
once, counted across every nested graph. A graph's own
|
None
|
journal
|
Any
|
Makes runs durable: a :class: |
None
|
durability
|
str
|
With a journal, when steps are written: |
'async'
|
carry
|
Sequence[str]
|
Declared cells ( |
()
|
on_resume
|
str
|
An execution that had yielded and not ended when the
run stopped: |
'restart'
|
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If a provider op needs the hub but none has been
installed. The message points at |
TypeError
|
If a |
Source code in operonx/core/engine.py
574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 | |
Attributes¶
trace_consumers
property
¶
The consumers every run of this engine feeds, resolved from
trace= — for a caller that runs another graph beside this one
and wants it traced to the same places (an eval's judges).
fingerprint
property
¶
The compiled graph's structural fingerprint (what :meth:resume
checks): its ops, their code and their wiring.
Methods:¶
start
¶
start(
inputs: Dict[str, Any],
*,
user_id: Optional[str] = None,
session_id: Optional[str] = None,
request_id: Optional[str] = None,
trace_id: Optional[str] = None,
scratch: Optional[Dict[str, Any]] = None,
checkpointer=None,
context: Any = None,
run_id: Optional[str] = None,
thread_id: Optional[str] = None,
) -> ExecutionHandle
Start workflow execution and return a streaming handle immediately.
Does not block — the graph runs in the background. Use the handle to stream frames, await specific outputs, or collect the final result.
V3 trace consumers (declared via Operon(..., trace=...)) fire
automatically once the scheduler completes — no explicit finalize
needed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
inputs
|
Dict[str, Any]
|
Input data for the workflow |
required |
user_id
|
Optional[str]
|
Optional user identifier (auto-generated if not provided) |
None
|
session_id
|
Optional[str]
|
Optional session identifier (auto-generated if not provided) |
None
|
request_id
|
Optional[str]
|
Optional request identifier (auto-generated if not provided) |
None
|
scratch
|
Optional[Dict[str, Any]]
|
Optional initial values for per-call scratch space. Applied
synchronously before the scheduler task is created — race-free.
Equivalent to writing |
None
|
context
|
Any
|
Any object the run's ops may read as
|
None
|
run_id
|
Optional[str]
|
The run's id — its trace id, and with a |
None
|
thread_id
|
Optional[str]
|
The thread the run belongs to ( |
None
|
The run's run_context().run_id is its trace id (trace_id,
else request_id), and thread_id is session_id as given
(None when not given).
Returns:
| Type | Description |
|---|---|
ExecutionHandle
|
ExecutionHandle — async-iterable, supports |
ExecutionHandle
|
and |
Source code in operonx/core/engine.py
846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 | |
resume
async
¶
resume(
run_id: str,
*,
answers: Optional[Dict[str, Any]] = None,
allow_graph_change: bool = False,
checkpointer=None,
context: Any = None,
) -> ExecutionHandle
Continue the journalled run run_id and return its handle::
handle = await engine.resume("order-42")
out = await handle.result()
Every cell is put back as the journal last had it; an execution that ended is not run again — its yields are replayed, so what came after it is dispatched as before — and the rest runs. The result is the one the run would have had. Any process with the same graph and a journal holding the run can resume it.
A run parked on interrupts (its result's "$interrupted") takes
their responses as answers={interrupt_id: value}; one left
unanswered parks the run again. A drained run resumes as it is.
Raises:
| Type | Description |
|---|---|
RuntimeError
|
The engine has no |
JournalError
|
The journal has no such run, the graph changed
since the run started ( |
Source code in operonx/core/engine.py
984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 | |
runs
¶
The journalled runs (their headers), optionally only status
("running": stopped or still going, the ones to resume).
Source code in operonx/core/engine.py
run
async
¶
run(
inputs: Dict[str, Any],
*,
user_id: Optional[str] = None,
session_id: Optional[str] = None,
request_id: Optional[str] = None,
trace_id: Optional[str] = None,
scratch: Optional[Dict[str, Any]] = None,
checkpointer=None,
context: Any = None,
run_id: Optional[str] = None,
thread_id: Optional[str] = None,
) -> Dict[str, Any]
Execute the workflow with given inputs.
Each call creates a fresh state, so the same engine can be used for multiple independent executions. Equivalent to::
handle = engine.start(inputs, ...)
result = await handle.collect(unwrap=True)
V3 trace consumers (declared via Operon(..., trace=...))
fire automatically inside start() when the scheduler
completes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
inputs
|
Dict[str, Any]
|
Input data for the workflow |
required |
user_id
|
Optional[str]
|
Optional user identifier (auto-generated if not provided) |
None
|
session_id
|
Optional[str]
|
Optional session identifier (auto-generated if not provided) |
None
|
request_id
|
Optional[str]
|
Optional request identifier (auto-generated if not provided) |
None
|
scratch
|
Optional[Dict[str, Any]]
|
Optional initial values for per-call scratch space. |
None
|
context
|
Any
|
What the run's ops read as |
None
|
run_id
|
Optional[str]
|
The run's id (see :meth: |
None
|
thread_id
|
Optional[str]
|
The run's thread (see :meth: |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
Dict[str, Any]
|
Dictionary containing workflow outputs plus "$state" key |
|
Dict[str, Any]
|
with the MemoryState for debugging/tracing access, plus |
|
Dict[str, Any]
|
"$errors" — |
|
Dict[str, Any]
|
op raised. An op that raises does not raise out of the run; |
|
Dict[str, Any]
|
its outputs, and those of every op after it, are missing — |
|
Dict[str, Any]
|
unless the engine was built with |
|
raises |
Dict[str, Any]
|
class: |
Dict[str, Any]
|
( |
|
Dict[str, Any]
|
raise. |
Source code in operonx/core/engine.py
1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 | |
invoke
async
¶
stream
async
¶
stream(
inputs: Dict[str, Any],
*,
mode: Union[str, List[str], tuple] = "updates",
channels: Optional[List[str]] = None,
checkpointer: Optional[Any] = None,
**kwargs: Any,
) -> asyncio.AsyncGenerator[Any, None]
LangGraph-familiar streaming iterator.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
inputs
|
Dict[str, Any]
|
workflow inputs (same as |
required |
mode
|
Union[str, List[str], tuple]
|
one mode, or a list of them. A string yields that mode's
chunks; a list yields
|
'updates'
|
channels
|
Optional[List[str]]
|
for |
None
|
checkpointer
|
Optional[Any]
|
for |
None
|
**kwargs
|
Any
|
forwarded to |
{}
|
Yields:
| Type | Description |
|---|---|
AsyncGenerator[Any, None]
|
mode-specific chunks, or |
Raises:
| Type | Description |
|---|---|
ValueError
|
an unknown mode, one given twice, or an empty list — before anything runs. |
BaseException
|
whatever |
Source code in operonx/core/engine.py
1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 | |
serve
¶
serve(
*,
path: str = "/",
host: str = "0.0.0.0",
port: int = 8000,
websocket: bool = False,
**kwargs: Any,
) -> None
Serve this workflow over HTTP or a WebSocket.
The one-endpoint convenience form. It builds the same ServeSpec
an operonx.toml would and serves that, so a project outgrowing
it moves to the manifest without changing how anything runs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
URL path for the endpoint (default: "/"). |
'/'
|
host
|
str
|
Bind address. |
'0.0.0.0'
|
port
|
int
|
Bind port. |
8000
|
websocket
|
bool
|
Serve a WebSocket endpoint instead of HTTP. |
False
|
**kwargs
|
Any
|
Extra arguments forwarded to |
{}
|
Source code in operonx/core/engine.py
batch
async
¶
batch(
inputs_list: List[Dict[str, Any]], *, concurrency: int = 10, **kwargs: Any
) -> List[Dict[str, Any]]
Run the workflow concurrently on multiple inputs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
inputs_list
|
List[Dict[str, Any]]
|
List of input dicts to process. |
required |
concurrency
|
int
|
Max concurrent executions (default: 10). |
10
|
**kwargs
|
Any
|
Extra arguments forwarded to |
{}
|
Returns:
| Type | Description |
|---|---|
List[Dict[str, Any]]
|
List of result dicts in the same order as inputs. |
Source code in operonx/core/engine.py
cli
¶
Interactive CLI mode — read JSON from stdin, print result to stdout.
Source code in operonx/core/engine.py
input_schema
¶
Return JSON Schema describing the workflow's expected inputs.
output_schema
¶
Decorators¶
The two decorators that turn ordinary Python into Operonx ops:
op
¶
op(
func: Optional[Callable] = None,
*,
bound: Optional[str] = None,
cache: Optional[Any] = None,
delay: float = 0,
exclude: Optional[Any] = None,
include: Optional[Any] = None,
observe_max: Optional[int] = None,
transient: bool = False,
show_keys: Optional[Any] = None,
door: Optional[str] = None,
retry: Optional[Retry] = None,
timeout: Optional[Timeout] = None,
) -> Any
Decorator that turns a plain function into a FuncOp factory.
Can be used bare or with keyword arguments::
@op
def double(x: int):
return {"result": x * 2}
@op(bound="cpu")
def heavy_compute(data: list):
return {"result": process(data)}
@op(bound="io")
async def call_api(url: str):
return {"data": await fetch(url)}
# Phase 2 observability filter (Checkpointer + Tracer both respect these):
@op(exclude=["tokens"]) # skip these vars in both observers
@op(include=[]) # silence entire op (allowlist of nothing)
@op(exclude={"trace": ["pii"]}) # per-observer split (dict form)
@op(observe_max=10_000) # circuit breaker: raise if op emits > N events
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bound
|
Optional[str]
|
Execution bound hint for the scheduler.
|
None
|
exclude
|
Optional[Any]
|
Vars to hide from observers. |
None
|
include
|
Optional[Any]
|
Vars to expose to observers (allowlist). Same shapes as |
None
|
transient
|
bool
|
This op's per-item outputs are stored, delivered, then evicted when the consuming context finishes, instead of being kept for the life of the run. For high-rate streams — a socket reader, an audio chunker — where retaining every item is the difference between a flat run and one that grows without bound. Transience propagates along pull refs: a cell that caches a pull
from a transient port is itself transient, so declaring it once on
the producer stops the whole chain from retaining. Incompatible
with |
False
|
observe_max
|
Optional[int]
|
Per-op circuit breaker. If the op emits more than this many
events in a single run, :class: |
None
|
show_keys
|
Optional[Any]
|
The output key (or keys) that stand for this op — what a viewer
prints for it when it has room for one line instead of a port
list. |
None
|
door
|
Optional[str]
|
|
None
|
retry
|
Optional[Retry]
|
|
None
|
timeout
|
Optional[Timeout]
|
|
None
|
Source code in operonx/core/ops/transform/func_op.py
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 | |
graph
¶
GraphOp — container op that manages a graph of child ops.
Classes¶
GraphOp
¶
Bases: BaseOp
Container op that holds and executes a directed graph of child ops.
Lifecycle::
1. DEFINE with GraphOp(name="wf") as g:
a = double(x=PARENT["x"])
b = add(a=a["result"], b=PARENT["y"])
START >> a >> b >> END
Ops auto-register via context manager. Edges via >> operator.
Inputs/outputs auto-discovered from PARENT refs.
2. BUILD g.build() (or auto on first run)
_setup_schema scan PARENT refs → graph inputs/outputs
_setup_endpoints find entry/exit ops from topology
_build() adj list + ready counts + stream ready counts
validate branch targets, cycles, reachability, refs
3. EXECUTE g.run(state, context_id) — async generator
→ run_task_scheduler() drives ops via Frame/EOF events
→ yields (ctx, outputs) per batch or per stream frame
→ loop iteration handled inside scheduler EOF handler
4. EXPORT serialize() the graph as a config dict
validate() graph structure validation
show() debug display
Source code in operonx/core/ops/graph/graph_op.py
Methods:¶
get_current_graph
staticmethod
¶
add_op
¶
Add an op to the graph.
Source code in operonx/core/ops/graph/graph_op.py
add_edge
¶
add_edge(
source: str,
target: str,
type: EdgeType = "normal",
soft: bool = False,
hard: bool = False,
)
Add an edge between two ops.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
str
|
Source op name. |
required |
target
|
str
|
Target op name. |
required |
type
|
EdgeType
|
Edge type (normal, lookback, condition). |
'normal'
|
soft
|
bool
|
If True, edge does not count toward ready_count. Used for branch outputs when only one branch executes. |
False
|
hard
|
bool
|
If True, opt this edge out of auto-softening at build time. Use for the rare case where a branch-descended pred must still be waited on as a hard dependency. |
False
|
Source code in operonx/core/ops/graph/graph_op.py
build
¶
Build graph: cycle-rewrite → children → schema → endpoints → validation → topology.
The cycle-rewrite pass (Phase 3 Level-2) runs FIRST so that any
synthetic hidden GraphOp.loop children it creates are then built
alongside the user's own children. Ordering matters — validate() and
auto_soft assume a DAG and would produce wrong results on cyclic input.
Source code in operonx/core/ops/graph/graph_op.py
store_result
¶
Store the graph's outputs — except its declared cells.
A declared cell already holds the graph's value: every write inside
the graph went into it. Storing the graph's output there again hands
the cell's reducer its own accumulated value as a fresh delta — an
add_messages cell came out with every message twice.
Source code in operonx/core/ops/graph/graph_op.py
run
async
¶
run(
state: MemoryState, context_id: Optional[tuple] = None
) -> AsyncGenerator[Tuple[tuple, Dict[str, Any]], None]
Execute graph: get inputs → schedule ops → loop if needed → store results.
Source code in operonx/core/ops/graph/graph_op.py
931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 | |
serialize
¶
The whole graph as a config dict: ops, edges, entries and exits.
A graph's canonical description; an eval's fingerprint hashes it.
It was written for the dropped Rust runtime, and some keys are
still that runtime's (initial_ready_count, compiled_adj,
stream_initial_ready): kept so the output, and every hash
taken of it, stays the same.
Source code in operonx/core/ops/graph/graph_op.py
1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 | |
validate
¶
Run all validations and return result.
Source code in operonx/core/ops/graph/graph_op.py
show
¶
Display graph structure (debug).
Source code in operonx/core/ops/graph/graph_op.py
GraphValidationError
¶
Bases: Exception
Exception raised when graph validation fails.
Source code in operonx/core/ops/graph/validation.py
ValidationIssue
dataclass
¶
ValidationIssue(
level: ValidationLevel,
category: str,
message: str,
op_name: Optional[str] = None,
target_name: Optional[str] = None,
available_nodes: List[str] = list(),
suggestions: List[str] = list(),
)
A single validation issue found in the graph.
ValidationLevel
¶
Bases: Enum
Severity level for validation issues.
ValidationResult
dataclass
¶
Result of graph validation.
Methods:¶
raise_if_errors
¶
Raise exception if there are any errors.
Source code in operonx/core/ops/graph/validation.py
Inside a run¶
What an op body can read about its run, the steps it records, and the
events engine.stream(mode="tasks") yields:
run_context
¶
The :class:RunContext of the op body calling it, or None
outside one (module level, a plain function call).
Source code in operonx/core/runtime.py
RunContext
dataclass
¶
RunContext(
run_id: Optional[str],
thread_id: Optional[str],
op_path: str,
ctx: Tuple[str, ...],
attempt: int = 1,
deadline: Optional[float] = None,
context: Any = None,
)
The run and the invocation an op body is executing in.
Attributes:
| Name | Type | Description |
|---|---|---|
run_id |
Optional[str]
|
The run's trace id ( |
thread_id |
Optional[str]
|
The |
op_path |
str
|
The execution's full name ( |
ctx |
Tuple[str, ...]
|
The execution's ctx tuple ( |
attempt |
int
|
The attempt running, 1-based ( |
deadline |
Optional[float]
|
When the attempt's |
context |
Any
|
The object passed as |
Attributes¶
idempotency_key
property
¶
:func:invocation_key of this execution — the same on every
attempt, different in every other run, op or ctx. Pass it to an
external API that deduplicates (a payment, an email). None
without a run_id.
remaining
property
¶
Seconds until :attr:deadline (negative once it passed), or None.
child
¶
child(
name: str,
inputs: Optional[Dict[str, Any]] = None,
*,
op_type: str = "",
current: bool = True,
) -> "_ChildScope"
Record the block as a child execution of the op running it::
@op
async def agent(messages: list) -> dict:
async with child("model", inputs={"messages": messages}, op_type="llm") as call:
reply = await model(messages)
call.outputs = reply
call.attrs["gen_ai.operation.name"] = "chat"
...
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
What a trace viewer prints ( |
required |
inputs
|
Optional[Dict[str, Any]]
|
What the step was given, recorded as its inputs. |
None
|
op_type
|
str
|
The step's kind ( |
''
|
current
|
bool
|
Whether the code inside the block runs as the child:
its own |
True
|
The record's ctx is its parent's plus "<name>[<n>]" — the n-th
child of that name under that parent — and its full name the parent's
plus ".<name>", so the parent is derived, never stored. The parent
is the op's record; for a generator, the record of the yield being
produced when the block opens; inside another child, that child. The
op's @op(exclude=/include=) trace filter applies to the child's
inputs and outputs.
An exception inside the block is recorded as error and re-raised;
a cancellation as cancelled. Inside the block, :func:run_context
describes the child, so each step has its own idempotency_key.
Outside a traced run it records nothing.
Async only: a plain def op cannot use it, and a bound="cpu"
body runs in a thread, where records could interleave.
Source code in operonx/core/runtime.py
ChildExecution
¶
The handle :func:child yields. Set :attr:outputs (a dict; any
other value is recorded as {"_": value}), :attr:attrs (semantic
attributes such as gen_ai.operation.name) and :attr:redact before
the block ends.
redact is (values: dict) -> dict: every exporter (the run
stores, the Local and Langfuse consumers) writes the record's inputs
and outputs through it; the record in memory keeps them as recorded.
For a credential a step saw that must not leave the process, scrubbed
where the trace is written instead of on the run's event loop.
Source code in operonx/core/runtime.py
TaskStarted
dataclass
¶
An op invocation, or a child execution, began an attempt.
op is its full name (a child's is its op's plus .<name>),
ctx its ctx tuple, attempt 1-based (@op(retry=)).
TaskFinished
dataclass
¶
It ended without an error — a generator once, after its last item.
TaskFailed
dataclass
¶
TaskFailed(
op: str,
ctx: Tuple[str, ...],
attempt: int = 1,
duration_ms: float = 0.0,
error: str = "",
cancelled: bool = False,
retrying: bool = False,
)
It ended with an error (error is "TypeName: message"), or was
cancelled (cancelled, no error). retrying means retry=
runs another attempt, which starts with its own :class:TaskStarted.
Op types¶
The base classes that compose into a workflow. Most users only touch
GraphOp directly (via with GraphOp(...) as g:) — the others are
constructed by decorators or factory helpers.
GraphOp
¶
Bases: BaseOp
Container op that holds and executes a directed graph of child ops.
Lifecycle::
1. DEFINE with GraphOp(name="wf") as g:
a = double(x=PARENT["x"])
b = add(a=a["result"], b=PARENT["y"])
START >> a >> b >> END
Ops auto-register via context manager. Edges via >> operator.
Inputs/outputs auto-discovered from PARENT refs.
2. BUILD g.build() (or auto on first run)
_setup_schema scan PARENT refs → graph inputs/outputs
_setup_endpoints find entry/exit ops from topology
_build() adj list + ready counts + stream ready counts
validate branch targets, cycles, reachability, refs
3. EXECUTE g.run(state, context_id) — async generator
→ run_task_scheduler() drives ops via Frame/EOF events
→ yields (ctx, outputs) per batch or per stream frame
→ loop iteration handled inside scheduler EOF handler
4. EXPORT serialize() the graph as a config dict
validate() graph structure validation
show() debug display
Source code in operonx/core/ops/graph/graph_op.py
Methods:¶
get_current_graph
staticmethod
¶
add_op
¶
Add an op to the graph.
Source code in operonx/core/ops/graph/graph_op.py
add_edge
¶
add_edge(
source: str,
target: str,
type: EdgeType = "normal",
soft: bool = False,
hard: bool = False,
)
Add an edge between two ops.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
str
|
Source op name. |
required |
target
|
str
|
Target op name. |
required |
type
|
EdgeType
|
Edge type (normal, lookback, condition). |
'normal'
|
soft
|
bool
|
If True, edge does not count toward ready_count. Used for branch outputs when only one branch executes. |
False
|
hard
|
bool
|
If True, opt this edge out of auto-softening at build time. Use for the rare case where a branch-descended pred must still be waited on as a hard dependency. |
False
|
Source code in operonx/core/ops/graph/graph_op.py
build
¶
Build graph: cycle-rewrite → children → schema → endpoints → validation → topology.
The cycle-rewrite pass (Phase 3 Level-2) runs FIRST so that any
synthetic hidden GraphOp.loop children it creates are then built
alongside the user's own children. Ordering matters — validate() and
auto_soft assume a DAG and would produce wrong results on cyclic input.
Source code in operonx/core/ops/graph/graph_op.py
store_result
¶
Store the graph's outputs — except its declared cells.
A declared cell already holds the graph's value: every write inside
the graph went into it. Storing the graph's output there again hands
the cell's reducer its own accumulated value as a fresh delta — an
add_messages cell came out with every message twice.
Source code in operonx/core/ops/graph/graph_op.py
run
async
¶
run(
state: MemoryState, context_id: Optional[tuple] = None
) -> AsyncGenerator[Tuple[tuple, Dict[str, Any]], None]
Execute graph: get inputs → schedule ops → loop if needed → store results.
Source code in operonx/core/ops/graph/graph_op.py
931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 | |
serialize
¶
The whole graph as a config dict: ops, edges, entries and exits.
A graph's canonical description; an eval's fingerprint hashes it.
It was written for the dropped Rust runtime, and some keys are
still that runtime's (initial_ready_count, compiled_adj,
stream_initial_ready): kept so the output, and every hash
taken of it, stays the same.
Source code in operonx/core/ops/graph/graph_op.py
1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 | |
validate
¶
Run all validations and return result.
Source code in operonx/core/ops/graph/graph_op.py
show
¶
Display graph structure (debug).
Source code in operonx/core/ops/graph/graph_op.py
BranchOp
¶
BranchOp(
cases: Optional[List[Tuple[Ref, str]]] = None,
candidates: Optional[List[str]] = None,
default: Optional[str] = None,
inputs: Dict[str, Any] = None,
outputs: Dict[str, Any] = None,
max_iterations: Optional[int] = None,
**kwargs,
)
Bases: BaseOp
Op that evaluates conditions and routes execution to different targets.
Conditions are Ref objects with comparison operators. The first matching
condition determines the target. An optional anchor input overrides all
conditions. Use soft edges (>>~) to connect branch targets to a merge op.
Inputs
anchor (str, optional): Hard-coded target name that overrides conditions. (any): Variables referenced in condition Refs (auto-extracted).
Outputs
target (str): Name of the selected target op. matched (str): Description of which condition matched.
Example::
router = if_(PARENT["score"] >= 90, "excellent").else_("fail")
START >> router >> ~excellent >> merge >> END
router >> ~fail >> merge
Source code in operonx/core/ops/flow/branch_op.py
FuncOp
¶
FuncOp(
code_fn: Optional[Callable] = None,
return_keys: Optional[List[str]] = None,
inputs: Dict[str, Any] = None,
outputs: Dict[str, Any] = None,
_mappings: Dict[str, Any] = None,
**kwargs,
)
Bases: BaseOp
Op that executes a Python function.
Inputs and outputs are auto-extracted from the function's signature and
return-statement AST. Both sync and async functions are supported.
Prefer the @op decorator over instantiating FuncOp directly.
Inputs
Auto-parsed from the function's parameter list.
Outputs
Auto-parsed from return {"key": ...} via AST, or from
explicit return_keys.
Example::
@op
def add(a: int, b: int):
return {"sum": a + b}
with GraphOp(name="main") as graph:
result = add(a=PARENT["x"], b=PARENT["y"])
START >> result >> END
Source code in operonx/core/ops/transform/func_op.py
Note (1.0.0): the standalone ParserOp was removed. Text parsing lives
inline in LLMOp(fields=..., parser=..., validators=...); pure text
helpers (no LLM) are in operonx.providers.parsing.
Branch helpers¶
Branch
¶
Fluent builder for creating a BranchOp.
Two usage flavors — both supported, both idiomatic:
Inline form (recommended for common if/else) — pass op instances as
targets. The Branch auto-wires branch >> target edges at build time
so you never write them yourself, and the branch can drop right into a
>> chain::
START >> source >> if_(source["kind"] == "audio", asr).else_(skip_stt)
asr >> denoise >> picker
skip_stt >> picker
Auto-name resolves to the LHS if there is one (stt_route = if_(...));
inline, to a per-graph counter, route_1, route_2.
Named form (for forward refs or a shared branch node) — pass op
names as strings. No auto-wiring; you wire branch >> target
yourself as before::
router = (if_(PARENT["score"] >= 90, "excellent")
.if_(PARENT["score"] >= 70, "good")
.else_("fail"))
# ...
router >> excellent >> merge
router >> good >> merge
router >> fail >> merge
Mixed is allowed — string targets skip auto-wiring, op-instance targets get auto-wired.
Initialise the builder.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
Optional[str]
|
Op name. If None, auto-inferred from the variable name. |
None
|
Source code in operonx/core/ops/flow/branch_op.py
Methods:¶
if_
¶
Add a condition–target case.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
condition
|
Union[Ref, BaseOp]
|
Ref with comparison (e.g., |
required |
target
|
Union[str, BaseOp]
|
Target op instance (enables auto-wiring) or op name string. |
required |
Returns:
| Type | Description |
|---|---|
Branch
|
self for chaining. |
Source code in operonx/core/ops/flow/branch_op.py
else_
¶
if_
¶
if_(
condition: Union[Ref, BaseOp],
target: Union[str, BaseOp],
*,
max_iterations: Optional[int] = None,
) -> Branch
Start a branch declaration with the first condition.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
condition
|
Union[Ref, BaseOp]
|
What to test — a Ref comparison or a single-output op. |
required |
target
|
Union[str, BaseOp]
|
The op (or op name) to route to when it holds. |
required |
max_iterations
|
Optional[int]
|
When one of this branch's arms loops back to an
earlier op, the most iterations that loop may run (default
1000). A loop that reaches it stops, records
|
None
|
Example (inline, auto-wired)::
START >> source >> if_(cond, asr).else_(skip_stt)
Example (named, string targets, wire manually)::
router = if_(PARENT["score"] >= 90, "excellent").else_("fail")
router >> excellent >> merge
router >> fail >> merge
Example (a loop capped at 50 iterations)::
START >> s >> if_(s["done"] == True, END, max_iterations=50).else_(s)
Source code in operonx/core/ops/flow/branch_op.py
State markers¶
Constants used inside with GraphOp(...) blocks to wire edges and
references. None of these are real instances you'd construct — they're
sentinels the graph builder recognises.
| Marker | Meaning |
|---|---|
START |
Entry node. Every graph's first hard edge goes from START. |
END |
Exit node. op >> END auto-forwards op's outputs as the graph result. |
PARENT |
Reference root for inputs from engine.run(inputs={...}) or the parent graph in nested contexts. Used as PARENT["key"]. |
PENDING |
Sentinel returned by ops that absorb input without producing output. |
Top-level convenience¶
bootstrap
¶
bootstrap(
*, resources: Optional[Union[str, Path]] = None, env: bool = True
) -> Optional[ResourceHub]
One-line setup for .env and :class:ResourceHub.
- When
envisTrue(default), load./.envfrom CWD usingpython-dotenv(non-override; existing env wins). The path is recorded inBOOTSTRAP_ENV_PATHSfor later diagnostic messages. - When
resourcesis a path, install the hub via :meth:ResourceHub.from_yaml. - When
resourcesisNone, call :meth:ResourceHub.auto— which checks./resources.yamland warns on miss. - Idempotent: if a hub is already installed, return it unchanged.
Returns the installed hub, or None if no resources.yaml was
found and none was provided. Pure-compute graphs that don't need a
hub can ignore the return value.
Source code in operonx/__init__.py
Provider-neutral types¶
The v0.7 LLMOp converter layer will translate provider-specific types to/from these at the provider boundary.
ChatMessage
¶
Bases: TypedDict
A single message in a chat conversation.
Provider-neutral shape; backends translate to / from this at the LLMOp boundary.
Required fields
role: One of "system", "user", "assistant",
"tool".
content: The message body. str for plain text;
providers may accept richer structured shapes (tool calls,
multi-modal parts) via opt-in fields below.
Optional fields
name: Speaker identifier (for tool replies and named system
prompts).
tool_call_id: When role == "tool", the id of the tool call
this message responds to.
tool_calls: When role == "assistant", the list of tool
calls the model is requesting. Shape is
provider-specific; converter layers normalise this in v0.7.