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,
retry: Any = 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
|
retry
|
Any
|
The default |
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
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 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 | |
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
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 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 | |
resume
async
¶
resume(
run_id: str,
*,
answers: Optional[Dict[str, Any]] = None,
allow_graph_change: bool = False,
retry_failed: 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.
retry_failed=True runs a failed run again from its first failed
op: the steps journalled before that failure are kept (what had
ended is not run again), the failed op's and every later step are
dropped, so the failed op and what follows it run. After fixing the
op's code, pass allow_graph_change=True as well.
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
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 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 | |
fork
async
¶
fork(
run_id: str,
*,
at: str,
outputs: Dict[str, Any],
ctx: Tuple[str, ...] = ("main",),
occurrence: int = 0,
allow_graph_change: bool = False,
) -> ExecutionHandle
Run run_id again from op at, as if at had answered outputs, and return the new run's handle::
handle = await engine.fork("order-42", at="quote", outputs={"price": 90})
out = await handle.result() # what follows `quote`, with price 90
The journal's steps up to at's end are copied into a new run
(<run_id>~<8 hex>), at's outputs replaced; the new run then
resumes, so nothing that ended before at runs again and what came
after it runs with the new value. The original run is not changed.
at is an op that yields once (not a generator or a graph), named
as in the graph; ctx and occurrence pick one execution of it
(an op in a loop runs at the same ctx once per iteration).
Raises:
| Type | Description |
|---|---|
JournalError
|
no such run or execution, at yields more than
once, an output at does not have, or the graph changed
( |
Source code in operonx/core/engine.py
1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 | |
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
1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 | |
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
1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 | |
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.
Source code in operonx/core/engine.py
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,
reads: Optional[Any] = None,
writes: Optional[Any] = 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
|
reads
|
Optional[Any]
|
the project's stores this op reads, by name (a table, a
queue, a folder): |
None
|
writes
|
Optional[Any]
|
the stores this op writes, the same way:
|
None
|
retry
|
Optional[Retry]
|
|
None
|
timeout
|
Optional[Timeout]
|
|
None
|
Source code in operonx/core/ops/transform/func_op.py
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 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 | |
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
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 1082 1083 1084 1085 1086 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 | |
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
1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 | |
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 latency it measures, 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
measure
¶
Record one latency sample of name, in milliseconds, on the run
whose op body calls it. When the run ends its trace carries
metadata["latency_ms"][name] = {"n", "p50", "p95", "max"}, and the
studio's Monitor charts it over time.
For the latency a user feels that no single op's time shows: a reply that starts in one op and is heard in another. A no-op outside a traced run. Call it on the event loop (in the op body, not in a thread the op hands work to)::
measure("reply", (first_sent - speech_ended) * 1000)
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
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 1082 1083 1084 1085 1086 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 | |
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
1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 | |
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, bool]
|
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, bool],
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, bool]
|
What to test — a Ref comparison, a single-output op, or
a bool: a parameter a variant bound is a plain value, so
|
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.