Extending¶
See Hooks, commands and plugins for an overview.
Hooks¶
User-replaceable build and solve steps.
The orchestrator manages storage and runs; it never requires flex-pse to build
or solve a model. A run is build(spec, **overrides) followed by
solve(model, **options), and both steps are hooks: plain callables that
follow BuildFn and SolveFn. Two optional hooks change the
surrogate a unit uses, either in the spec before building
(ApplySurrogateFn) or on a live model (SwapSurrogateFn),
one sets a configuration option in a spec (ConfigureFn), and one
names a built model’s time Sets for the exporter (TimeSetsFn).
A hook can be given three ways, and a HookSet slot accepts any of them:
a callable;
a name registered with
HookRegistry.register()("my_model"), which picks that set’s hook of the same kind;an import string,
"package.module:function". Ray workers and the HTTP API need this form, because they can’t receive a callable.
The flex-pse defaults are DEFAULT_HOOKS. They are import strings, so
this module doesn’t import flex-pse (or pyomo) and works without it.
- flexorchestrator.hooks.SolveStatus¶
How a solve ended.
"ok"(optimal),"failed"(the solver finished without an optimal solution) or"error"(the solve raised).alias of
Literal[‘ok’, ‘failed’, ‘error’]
- class flexorchestrator.hooks.SolveOutcome(*, status, termination=None, message=None, wall_time=None, solver=None, log=None)[source]¶
Bases:
BaseModelThe result of one solve, as stored with its run.
- Parameters:
- status¶
"ok","failed"or"error"(seeSolveStatus).- Type:
Literal[‘ok’, ‘failed’, ‘error’]
- termination¶
The solver’s termination condition, e.g.
"optimal"or"infeasible";Nonewhen the solve raised.- Type:
str | None
- wall_time¶
Seconds the solve took.
run_solve()fills it in when the hook leaves it unset.- Type:
float | None
Example
>>> outcome = SolveOutcome(status="ok", termination="optimal") >>> outcome.ok True
- model_config = {'frozen': True}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- classmethod from_stored(stored)[source]¶
Return the outcome a run stored (its JSON), or
Noneif there is none.The stored
okis dropped: it is computed fromstatus.Example
>>> stored = SolveOutcome(status="ok").model_dump(mode="json") >>> SolveOutcome.from_stored(stored).ok True
- Parameters:
- Return type:
SolveOutcome | None
- class flexorchestrator.hooks.BuildFn(*args, **kwargs)[source]¶
Bases:
ProtocolBuilds a model from a stored spec.
Example
>>> def build(spec: dict, **overrides) -> dict: ... return {**spec, **overrides}
- class flexorchestrator.hooks.SolveFn(*args, **kwargs)[source]¶
Bases:
ProtocolSolves a built model.
Example
>>> def solve(model, **options) -> SolveOutcome: ... return SolveOutcome(status="ok", termination="optimal")
- class flexorchestrator.hooks.ApplySurrogateFn(*args, **kwargs)[source]¶
Bases:
ProtocolPuts a surrogate into a spec, so the next build uses it.
Example
>>> def apply_surrogate(spec, unit, surrogate_spec, relation=None) -> dict: ... return {**spec, "surrogates": {unit: surrogate_spec}}
- class flexorchestrator.hooks.SwapSurrogateFn(*args, **kwargs)[source]¶
Bases:
ProtocolSwaps a surrogate into a model that is already built.
Example
>>> def swap_surrogate(model, unit, surrogate_spec, relation=None) -> None: ... model.surrogates[unit] = surrogate_spec
- class flexorchestrator.hooks.ConfigureFn(*args, **kwargs)[source]¶
Bases:
ProtocolSets one configuration option in a spec, so the next build uses it.
Example
>>> def configure(spec, path, value) -> dict: ... return {**spec, path: value}
- class flexorchestrator.hooks.TimeSetsFn(*args, **kwargs)[source]¶
Bases:
ProtocolNames a built model’s time Sets, for the exporter.
Example
>>> def time_sets(model) -> list: ... return [model.t]
- class flexorchestrator.hooks.TimeGridFn(*args, **kwargs)[source]¶
Bases:
ProtocolGives a model’s time axis, so stored data can be aligned to it.
Example
>>> import pandas as pd >>> def time_grid(spec_or_model): ... return pd.date_range("2025-07-08", periods=24, freq="1h")
- class flexorchestrator.hooks.ApplyValuesFn(*args, **kwargs)[source]¶
Bases:
ProtocolFixes variables of a built model to values.
orch.apply_model_inputsuses it to set stored data on a model that is already built.Example
>>> def apply_values(model, values) -> None: ... for path, value in values.items(): ... model.find_component(path).fix(value)
- flexorchestrator.hooks.HookRef¶
A hook as given by a user: a callable, an import string or a registered name.
- class flexorchestrator.hooks.HookSet(build=None, solve=None, apply_surrogate=None, swap_surrogate=None, time_sets=None, configure=None, time_grid=None, apply_values=None)[source]¶
Bases:
objectThe hooks for a run, one slot per kind in
HOOK_KINDS.Each slot holds a callable, an import string, a registered name, or
None(not set).HookRegistry.resolve()turns every slot into a callable.- Parameters:
- apply_surrogate¶
The optional
ApplySurrogateFn.- Type:
Any
- swap_surrogate¶
The optional
SwapSurrogateFn.- Type:
Any
- time_sets¶
The optional
TimeSetsFn.- Type:
Any
- configure¶
The optional
ConfigureFn.- Type:
Any
- time_grid¶
The optional
TimeGridFn.- Type:
Any
- apply_values¶
The optional
ApplyValuesFn.- Type:
Any
Example
>>> hooks = DEFAULT_HOOKS.merged(HookSet(build="mypkg.models:build")) >>> hooks.build 'mypkg.models:build'
- merged(other)[source]¶
Return these hooks with every slot
othersets taking precedence.This is how the precedence call arguments > study config > orchestrator defaults is applied:
defaults.merged(config).merged(arguments).
- to_refs()[source]¶
Return every set slot as an import string.
For callers that need portable hooks, which a Ray worker or another process can import. Resolve registered names first, with
HookRegistry.resolve().- Returns:
{kind: "package.module:function"}for every slot that is set.- Raises:
HookError – If a slot holds a callable that can’t be imported back (a lambda, a closure, or a function defined in
__main__), or a registered name.- Return type:
Example
>>> DEFAULT_HOOKS.to_refs()["build"] 'flexorchestrator.flexpse:build'
- flexorchestrator.hooks.HOOK_KINDS = ('build', 'solve', 'apply_surrogate', 'swap_surrogate', 'time_sets', 'configure', 'time_grid', 'apply_values')¶
The hook slots a
HookSethas:build,solve,apply_surrogate,swap_surrogate,time_sets,configure,time_gridandapply_values.
- flexorchestrator.hooks.DEFAULT_HOOKS = HookSet(build='flexorchestrator.flexpse:build', solve='flexorchestrator.flexpse:solve', apply_surrogate='flexorchestrator.flexpse:apply_surrogate', swap_surrogate='flexorchestrator.flexpse:swap_surrogate', time_sets='flexorchestrator.flexpse:time_sets', configure='flexorchestrator.flexpse:configure', time_grid='flexorchestrator.flexpse:time_grid', apply_values='flexorchestrator.flexpse:apply_values')¶
The flex-pse hooks, used when nothing else is configured.
- Type:
- flexorchestrator.hooks.import_hook(ref)[source]¶
Import the callable an import string names.
- Parameters:
ref (str) –
"package.module:attribute"; the attribute may be dotted ("package.module:Class.method").- Returns:
The callable.
- Raises:
HookError – If
refis malformed, the module can’t be imported, the attribute doesn’t exist, or it isn’t callable.- Return type:
Example
>>> import_hook("flexorchestrator.testing:fake_build").__name__ 'fake_build'
- flexorchestrator.hooks.hook_ref(fn)[source]¶
Return the import string that resolves back to
fn, if there is one.- Parameters:
fn (Any) – A callable.
- Returns:
"module:qualname", orNonewhen importing that string wouldn’t give backfn(lambdas, closures, bound methods, functions defined in__main__).- Return type:
str | None
Example
>>> from flexorchestrator.testing import fake_build >>> hook_ref(fake_build) 'flexorchestrator.testing.hooks:fake_build'
- class flexorchestrator.hooks.HookRegistry[source]¶
Bases:
objectNamed hook sets, and resolution of any
HookSetto callables.Example
>>> registry = HookRegistry() >>> _ = registry.register( ... "fake", ... build="flexorchestrator.testing:fake_build", ... solve="flexorchestrator.testing:fake_solve", ... ) >>> registry.resolve(HookSet(build="fake")).build.__name__ 'fake_build'
- register(name, *, build=None, solve=None, apply_surrogate=None, swap_surrogate=None, time_sets=None, configure=None, time_grid=None, apply_values=None, replace=False)[source]¶
Register a named set of hooks.
- Parameters:
name (str) – The name a
HookSetslot or a study config uses to refer to this set. Must not contain":".build (Any) – A callable or import string.
solve (Any) – A callable or import string.
apply_surrogate (Any) – A callable or import string.
swap_surrogate (Any) – A callable or import string.
time_sets (Any) – A callable or import string.
configure (Any) – A callable or import string.
time_grid (Any) – A callable or import string.
apply_values (Any) – A callable or import string.
replace (bool) – Allow replacing a set already registered under
name.
- Returns:
The registered set.
- Raises:
HookError – If
nameis empty, contains":"or is already registered (withoutreplace), or a hook is neither a callable nor an import string.- Return type:
- resolve_ref(ref, kind)[source]¶
Resolve one hook to a callable.
- Parameters:
ref (Any) – A callable, an import string or a registered name.
kind (str) – Which slot this is for (one of
HOOK_KINDS); picks the hook out of a registered set.
- Returns:
The callable.
- Raises:
HookError – If
kindis unknown, the name isn’t registered, its set has no hook of this kind, or an import string fails.- Return type:
- flexorchestrator.hooks.run_solve(solve, model, **options)[source]¶
Call a solve hook and always come back with a
SolveOutcome.An exception from the hook becomes an
"error"outcome carrying the traceback, so one failed solve doesn’t end a sweep.wall_timeis filled in when the hook didn’t set it.- Parameters:
- Returns:
The hook’s outcome, or an
"error"outcome if it raised.- Raises:
HookError – If the hook returns something other than a
SolveOutcome(a bug in the hook, not a failed solve).- Return type:
Example
>>> from flexorchestrator.testing import fake_solve >>> run_solve(fake_solve, model=None).status 'ok'
The flex-pse hooks¶
The default hooks, built on flex-pse 0.3.
This is the only package that imports flex-pse. Nothing else imports it
directly: DEFAULT_HOOKS refers to these
functions by import string, so the rest of the library works without flex-pse
installed. Specs are flex-pse flowsheet specs (schema 0.1.1; older specs migrate on
load).
- flexorchestrator.flexpse.apply_surrogate(spec, unit, surrogate_spec, relation=None)[source]¶
Return a copy of
specin whichunitusessurrogate_spec.Adds a
surrogateelement, replacing any the spec already has for the same unit and relation. Storing the edited spec lets the run be replayed without the live model.- Parameters:
spec (dict) – A
FlowsheetSpecas JSON, or aDesignSpec, whosebaseis edited. Not modified.unit (str) – The unit’s element name, e.g.
"demo.digester".surrogate_spec (dict) – A
SurrogateSpecas JSON (surrogate_type,data, optionalprovenance).relation (str | None) – The unit’s relation to replace, e.g.
"biogas_relation".Nonemeans flex-pse’s default,DEFAULT_RELATION.
- Returns:
The new spec.
- Raises:
SpecError – If
unitisn’t a unit of the spec, orsurrogate_specis invalid.- Return type:
Example
>>> spec = apply_surrogate( ... spec, "demo.digester", arima_spec, relation="biogas_relation" ... )
- flexorchestrator.flexpse.apply_values(model, values)[source]¶
Fix variables of a built flex-pse model, as
fixelements would.The values are checked against the variables’ bounds and applied together, all or nothing (
flexops.apply_spec()). A later apply of a point replaces an earlier one.- Parameters:
model (Block) – The built model, changed in place.
values (Mapping[str, Any]) –
{variable path: value}, aswith_overrides()takes them. A costing field (a price) can’t be set on a built model; set it before building, as a configuration option.
- Raises:
flexcore.exceptions.FlexConfigError – If a path names no variable, or a value doesn’t fit it.
SpecError – If
modelis a merged design model, which has several time blocks; set values per horizon with the design’schanges.
- Return type:
None
- flexorchestrator.flexpse.build(spec, **overrides)[source]¶
Build a flex-pse model from a stored flowsheet spec.
The overrides are added to the spec as
fixelements (with_overrides()), thenflexops.build_model()validates and builds it, arcs expanded.Relative paths in the spec (
tariff_source,$sourcefiles) resolve against the working directory of the process that builds, which on Ray is the worker’s.- Parameters:
spec (dict) – A
FlowsheetSpecas JSON (schema0.1.1; older specs migrate on load), or aDesignSpec, whichbuild_design()builds.**overrides (Any) – Values to fix, keyed by variable path from the model root (see
with_overrides()).
- Returns:
The model, ready to solve.
- Raises:
flexcore.exceptions.FlexConfigError – If the spec is invalid or an override names no variable; the message names the offending field.
- Return type:
Example
>>> model = build(spec, **{"demo.pump.flow_in": 10.0})
- flexorchestrator.flexpse.build_design(spec, **overrides)[source]¶
Build the merged model of a design study.
- Parameters:
- Returns:
The merged model, ready to solve.
- Raises:
SpecError – If an override names a capacity’s variable, which the study decides (fix its size with the capacity’s
lowerandupper), or gives a value per time point.- Return type:
- flexorchestrator.flexpse.configure(spec, path, value)[source]¶
Return a copy of
specwith one configuration option set.pathis an element’s name followed by the option: the element is the one whose name is the longest leading part ofpath, so this works for any unit or block, however deeply named ("plant.train_1.ro.recovery"). A unit’s options are itsconstruction_options; any other element’s are its own fields ("costing.energy_prices.electrical","properties.options.default_temperature").Dict-valued options can be set whole or one key at a time: the value
{"value": 200, "units": "m^3/hr"}at"plant.feed.max_withdrawal"replaces the option, and200at"plant.feed.max_withdrawal.value"changes only its number. Missing dicts on the way are created, so an option the spec leaves at its default can be set too. The option isn’t checked here; flex-pse validates the spec when it’s stored or built.In a design study,
capacities.<name>.<field>sets a field of that capacity ("capacities.battery_energy.capital_cost"), and any other path is an option of thebaseflowsheet.- Parameters:
- Returns:
The new spec.
- Raises:
SpecError – If no element’s name starts
path,pathnames only an element, or a part of the path on the way isn’t a dict.- Return type:
Example
>>> configure(spec, "plant.feed.max_withdrawal.value", 200)
- flexorchestrator.flexpse.get_regressor(name)[source]¶
Return the flex-pse regressor class for a
SurrogateTypename.- Parameters:
name (str) – A flex-pse
SurrogateType, e.g."multilinear".- Returns:
The regressor class.
- Raises:
NotImplementedError – If the installed flex-pse reserves the type but doesn’t fit it yet; the message names the installed version.
FitError – If
nameisn’t a surrogate type.
- Return type:
Example
>>> get_regressor("multilinear").__name__ 'LinearRegressor'
- flexorchestrator.flexpse.predict_surrogate(spec, X)[source]¶
Evaluate a
multilinearorconstant_intensitysurrogate spec onX.multilinearis its intercept plus each coefficient times its term, a*-separated product of input columns;constant_intensityis its coefficient times the one input. Values are in the units the spec was fitted in, which areX’s.- Parameters:
- Returns:
One predicted value per row of
X.- Raises:
FitError – For another surrogate type, a term
Xdoesn’t have, or aconstant_intensityspec without exactly one coefficient and one input column.- Return type:
- flexorchestrator.flexpse.solve(model, *, prefer=None, **options)[source]¶
Solve a model with the best available solver.
- Parameters:
model (Block) – The built model.
prefer (str | None) – A solver name to try first (see
flexcore.solvers.get_solver()).Noneuses the spec’ssolverfield when the model was built from one.**options (Any) – Passed to
flexcore.solvers.SolverFacade.solve():tee,warmstart,mip_gap,time_limitandoptions.
- Returns:
"ok"when the termination is optimal,"failed"otherwise.- Raises:
flexcore.exceptions.FlexSolverError – If no installed solver can solve the model.
run_solve()records this as an"error"outcome.- Return type:
Example
>>> outcome = solve(model, prefer="highs")
- flexorchestrator.flexpse.swap_surrogate(model, unit, surrogate_spec, relation=None)[source]¶
Swap
surrogate_specinto a built model, in place.The old relation is deactivated, not deleted, and the surrogate reuses the unit’s variables, so arcs are kept.
- Parameters:
model (Block) – The built model.
unit (str) – The unit’s element name, e.g.
"demo.digester".surrogate_spec (dict) – A
SurrogateSpecas JSON.relation (str | None) – The relation to replace;
NonemeansDEFAULT_RELATION.
- Raises:
SpecError – If
surrogate_specis invalid, ormodelis a merged design model.flexcore.exceptions.FlexConfigError – If the model has no such unit or relation.
- Return type:
None
Example
>>> swap_surrogate( ... model, "demo.digester", arima_spec, relation="biogas_relation" ... )
- flexorchestrator.flexpse.time_grid(spec_or_model)[source]¶
Return the time points of a flex-pse spec’s
timeelement, or a model’s.For a spec, the points
flexopsbuilds the model’s time block on: fromstart_date(inclusive) toend_date(exclusive) everytime_step, in naive local time. For a built model, its time block’s.- Parameters:
spec_or_model (Any) – A
FlowsheetSpecas JSON, or a built model. Not modified.- Returns:
The points;
Noneif there’s no time axis.- Raises:
SpecError – If there are two time axes, or the dates or step don’t make a whole number of steps.
- Return type:
DatetimeIndex | None
Example
>>> time_grid(spec)[:2] DatetimeIndex(['2025-07-08 00:00:00', '2025-07-08 01:00:00'], ...)
- flexorchestrator.flexpse.time_sets(model)[source]¶
Return a flex-pse model’s time Sets, for the exporter.
The TimeBlock’s
time_indexcomes first. After it come the index Sets of every unit’sstartup/shutdownVars, found on the units themselves and so registered by identity. A Set that merely holds time-like integers, such as asetelement[0, 1, 2]indexing RO trains, is never included.A merged design model has one TimeBlock per horizon: each horizon’s Sets follow in turn, its
time_indexfirst.- Returns:
The time Sets, main one first, or
[]if the model doesn’t have exactly one TimeBlock (a user’s own model, say). The exporter then finds time itself, and reports several TimeBlocks as ambiguous.- Parameters:
model (Block)
- Return type:
Example
>>> export_model_data(model, time_sets=time_sets(model))
- flexorchestrator.flexpse.validate_design_spec(spec)[source]¶
Check a design spec with flex-pse, and normalise it.
- flexorchestrator.flexpse.validate_model_spec(spec)[source]¶
Check a flowsheet spec with flex-pse’s own loader, and normalise it.
- Parameters:
spec (dict) – A
FlowsheetSpecas JSON.- Returns:
The validated spec as JSON, with defaults written out and any older schema migrated by flex-pse. Fields are written under their aliases (
{"$source": ...}), the form flex-pse itself writes.- Raises:
SpecError – If flex-pse rejects it; the message names the bad field.
- Return type:
- flexorchestrator.flexpse.validate_surrogate_spec(spec)[source]¶
Check a surrogate spec against flex-pse’s
SurrogateSpecand normalise it.
- flexorchestrator.flexpse.with_overrides(spec, overrides)[source]¶
Return a copy of
specwith onefixelement per override.A path whose first part names a
costingelement and whose next part is one of its fields ("costing.energy_prices.electrical") edits that field instead: that’s how a price is swept.- Parameters:
spec (dict) – A
FlowsheetSpecas JSON. Not modified.overrides (Mapping[str, Any]) –
{variable path: value}. The path is a Pyomo ComponentUID path from the model root ("demo.pump.flow_in","demo.pump.flow_in[3]","demo.ro[*].status"). The value is anything afixelement takes: a number in the variable’s own units,{"value": ..., "units": ...}, a list with one number per time point, or a{time index: value}mapping.
- Returns:
The new spec. Its
fixelements are named"override:<path>".- Return type:
Example
>>> with_overrides(spec, {"demo.pump.flow_in": 10.0})
Commands, plugins and events¶
The extension API: commands, plugins and lifecycle events.
command()makes a function aCommand, callable from Python (orch.run_command), the CLI (flex-orch cmd) and a host app’s HTTP API.A
Pluginbundles commands, named hooks, listeners and an orchestrator subclass;create_orchestrator()builds an orchestrator with the enabled plugins.An
Orchestratorsubclass may override the stable methodsbuild_hooks,default_export_selection,before_store,after_store,on_task_resultandon_study_created.
- class flexorchestrator.ext.Command(name, fn, params_model, role='editor', long_running=False, description='')[source]¶
Bases:
objectA registered command.
- Parameters:
- fn¶
fn(orch, params, progress, **runtime) -> result.- Type:
collections.abc.Callable[[…], Any]
- params_model¶
The pydantic model its parameters are checked against.
- Type:
- role¶
The least role that may run it over HTTP.
- Type:
Literal[‘viewer’, ‘editor’, ‘owner’]
- description¶
One line for
--helpand the OpenAPI schema; the first line of the function’s docstring by default.- Type:
- class flexorchestrator.ext.CommandRegistry[source]¶
Bases:
objectCommands by name, with where each came from.
Example
>>> registry = CommandRegistry() >>> @command() ... def ping(orch) -> str: ... return "pong" >>> registry.register(ping).name 'ping'
- register(cmd, *, source='user')[source]¶
Register a command.
- Parameters:
- Raises:
CommandError – If the name is taken.
- Return type:
- get(name)[source]¶
Return a command by name.
- Raises:
CommandError – If there is none.
- Parameters:
name (str)
- Return type:
- class flexorchestrator.ext.EventBus[source]¶
Bases:
objectListeners per event.
Example
>>> bus = EventBus() >>> seen = [] >>> @bus.on("study_created") ... def remember(study): ... seen.append(study) >>> bus.emit("study_created", study="a") >>> seen ['a']
- class flexorchestrator.ext.NoParams[source]¶
Bases:
BaseModelThe params model of a command that takes no parameters.
- model_config = {}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class flexorchestrator.ext.Plugin(name, api_version='>=1, <2', commands=(), hooks=<factory>, orchestrator_cls=None, routers=(), on_startup=None, on_shutdown=None, on_events=<factory>)[source]¶
Bases:
objectWhat a plugin provides.
- Parameters:
- api_version¶
The
PLUGIN_API_VERSIONrange it supports, e.g.">=1,<2".- Type:
- commands¶
Commands it adds.
- hooks¶
Named hooks:
{name: import string}registers that hook for every slot,{name: {"build": ..., "solve": ...}}registers a set.- Type:
collections.abc.Mapping[str, str | collections.abc.Mapping[str, str]]
- orchestrator_cls¶
An
Orchestratorsubclass;create_orchestrator()builds it.- Type:
type | None
- routers¶
FastAPI routers, for a host app to mount at
/ext/<name>; the library keeps them and doesn’t import FastAPI.- Type:
- on_startup¶
Called with the orchestrator once it is set up.
- Type:
collections.abc.Callable[[Any], None] | None
- on_shutdown¶
Called with the orchestrator when it closes.
- Type:
collections.abc.Callable[[Any], None] | None
- on_events¶
{event: listener or [listeners]}(seeflexorchestrator.ext.events).- Type:
collections.abc.Mapping[str, collections.abc.Callable[[…], Any] | collections.abc.Sequence[collections.abc.Callable[[…], Any]]]
- class flexorchestrator.ext.Progress(callback=None)[source]¶
Bases:
objectProgress reports and cancellation for one command call.
A command calls
update()as it goes andcheck()between steps; whoever runs it (a caller, the CLI, a host app’s job queue) readssnapshot()and maycancel()it.- Parameters:
callback (Callable[[dict[str, Any]], None] | None) – Called with
snapshot()after every update.
Example
>>> progress = Progress() >>> progress.update(total=2, message="fitting") >>> progress.advance() >>> progress.snapshot()["done"] 1
- update(done=None, total=None, message=None)[source]¶
Set how much is done, of how much, and what is happening.
- child()[source]¶
Return a
Progresswith its own counts that shares this one’s cancel.For a step that reports its own progress, such as the fits a study runs first: cancelling either cancels both.
Example
>>> parent = Progress() >>> step = parent.child() >>> parent.cancel() >>> step.cancelled True
- Return type:
- check()[source]¶
Raise
CommandCancelledif cancelled.- Return type:
None
- flexorchestrator.ext.command(name=None, *, role='editor', long_running=False, params=None, description=None)[source]¶
Make a function a
Command.- Parameters:
name (str | None) – The command’s name; the function’s name by default.
role (Literal['viewer', 'editor', 'owner']) – The least role that may run it over HTTP.
long_running (bool) – Whether HTTP sends it through a job queue.
params (type[BaseModel] | None) – The params model; by default the annotation of the function’s second parameter, or
NoParamsif it has none.description (str | None) – One line of help; the docstring’s first line by default.
- Returns:
A decorator that returns the
Command.- Return type:
Example
>>> from pydantic import BaseModel >>> class Echo(BaseModel): ... text: str >>> @command() ... def echo(orch, params: Echo, progress) -> dict: ... return {"text": params.text} >>> echo.name, echo.params_model.__name__ ('echo', 'Echo')
- flexorchestrator.ext.create_orchestrator(*args, plugins=None, **kwargs)[source]¶
Build an orchestrator with the enabled plugins, as their subclass if one has it.
The plugins are the ones passed plus those in
FLEXORCH_PLUGINS. A plugin’sorchestrator_clsis the class built; otherwiseOrchestrator.- Parameters:
- Returns:
The orchestrator.
- Raises:
PluginError – If a plugin can’t be loaded (see
load_plugins()).- Return type:
- flexorchestrator.ext.installed_plugins()[source]¶
Return the names of the plugins installed, loaded or not, sorted.
- flexorchestrator.ext.load_plugins(plugins=None, *, environ=None, builtin_commands=())[source]¶
Return the plugins to load: those passed, plus those in the allowlist.
- Parameters:
- Returns:
The plugins, allowlisted ones first, each once.
- Raises:
PluginError – If a name isn’t installed, an entry point isn’t a
Plugin, anapi_versionexcludes this version, or two plugins collide.- Return type:
Commands: named, validated operations on an orchestrator.
A command is a function fn(orch, params, progress, **runtime) -> result whose
params argument is a pydantic model (a command that needs neither may take only
orch, or orch and params). command() turns it
into a Command, and one definition is then callable from Python
(orch.run_command("price_sweep", prices=[0.1])), from the CLI
(flex-orch cmd price_sweep --prices 0.1) and from a host app’s HTTP API, with the
same JSON parameters.
runtime carries what JSON can’t: callables such as a build hook passed
from Python. It is never recorded, apart from the hooks’ import strings.
Every call is recorded as a run of the flexorch::commands ledger: its
parameters as the params input, what it returned as the result output
(JSON), and who ran it on which study in the metadata. A call that raises ends
failed with the error.
- flexorchestrator.ext.commands.COMMANDS_LEDGER = 'flexorch::commands'¶
The backend study every command call is recorded in.
- Type:
Plugins: bundles of commands, hooks and an orchestrator subclass.
A plugin package exposes a Plugin through the
flexorchestrator.plugins entry-point group:
[project.entry-points."flexorchestrator.plugins"]
digester_tools = "digester_tools:plugin"
Being installed isn’t enough to load: a plugin loads only when its name is in
FLEXORCH_PLUGINS (comma-separated) or it is passed explicitly
(Orchestrator(plugins=[...])), so each deployment enables its own set. Loading
checks that the plugin’s api_version range includes
PLUGIN_API_VERSION, and that no two plugins (or a
plugin and a built-in) claim the same command or hook name, or both provide an
orchestrator subclass.
- flexorchestrator.ext.plugins.PLUGIN_API_VERSION = '1.0.0'¶
The plugin API’s version (semver, separate from the package version).
- Type:
- flexorchestrator.ext.plugins.ENTRY_POINT_GROUP = 'flexorchestrator.plugins'¶
The entry-point group installed plugins register under.
- Type:
- flexorchestrator.ext.plugins.ALLOWLIST_ENV = 'FLEXORCH_PLUGINS'¶
The environment variable listing the installed plugins to enable, comma-separated (installed plugins are off unless listed).
- Type:
Lifecycle events: a lighter alternative to subclassing.
@orch.on("result_stored") registers a listener; the orchestrator calls it
with keyword arguments after the event. A listener that raises propagates: the
item is already stored by then, so nothing is undone.
Event |
Keyword arguments |
|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|