Workflow: Workflow

WorkflowR Documentation

Workflow

Description

An R6 class for building sequential multi-agent pipelines. A 'Workflow' is composed of **Stations** (processing units - an 'Agent', a 'WorkflowAgent', or any plain R function) connected by **Routes** (directed links, optionally gated by a condition function). Execution is always sequential: the output of one Station becomes the input of the next.

Stations whose results have already been computed can be retrieved from an internal cache instead of being re-executed, which is useful when iterating on later parts of the pipeline without paying the cost (or latency) of earlier LLM calls.

A finished 'Workflow' can be wrapped as a 'WorkflowAgent' via $as_agent(), making it composable with 'LeadAgent' or embeddable as a Station inside another 'Workflow'.

Public fields

name

Workflow identifier.

description

Optional human-readable description.

use_cache

Whether to cache and reuse Station results.

cache

Environment used as a hash-map for cached Station outputs.

run_history

List of records from every $run() call.

hitl_steps

Integer vector of step numbers at which execution pauses for human review. Set via $set_hitl().

hitl_mode

Either '"console"' (blocking readline() prompt, the default) or '"pause"' (non-blocking: $run() returns a 'mini007_pending' object instead of blocking). Set via $set_hitl().

n_daemons

Number of parallel daemons. Set via $set_daemons().

Methods

Public methods


Method new()

Create a new 'Workflow'.

Usage
Workflow$new(name, description = NULL, use_cache = TRUE)
Arguments
name

'[character(1)]' Workflow name.

description

'[character(1)]' Optional description.

use_cache

'[logical(1)]' Enable result caching (default 'TRUE').


Method add_station()

Add a Station to the workflow.

A Station is a named processing unit. Its 'handler' can be:

  • An 'Agent' or 'WorkflowAgent' - the Station calls handler$invoke(input).

  • A plain R function(input) - called directly; return value is coerced to 'character'.

Usage
Workflow$add_station(
  name,
  handler,
  description = NULL,
  max_retries = 0,
  retry_delay = 1,
  fallback = NULL
)
Arguments
name

'[character(1)]' Unique Station name within this workflow.

handler

An 'Agent', 'WorkflowAgent', or 'function'.

description

'[character(1)]' Optional human-readable description (shown in $visualize()).

max_retries

'[integerish(1)]' Number of additional attempts after the first failure (default '0', i.e. no retries).

retry_delay

'[numeric(1)]' Seconds to wait between retry attempts (default '1').

fallback

'[function | NULL]' A function(input, error) invoked when all retry attempts are exhausted. 'NULL' re-raises the last error.

Returns

Invisibly returns 'self' for method chaining.


Method add_route()

Add a Route between two Stations.

Routes define the execution order. An optional 'condition' function receives the output of the 'from' Station and must return 'TRUE' or 'FALSE'. Conditional routes are evaluated first (in insertion order); the first matching one is followed. If none match, the first unconditional route from that Station is used as a default.

Usage
Workflow$add_route(from, to, condition = NULL, label = NULL)
Arguments
from

'[character(1)]' Name of the source Station.

to

'[character(1)]' Name of the destination Station.

condition

'[function | NULL]' A function function(output) returning a single logical value. 'NULL' means "always follow this route" (i.e., unconditional).

label

'[character(1) | NULL]' Optional text shown on the Route in $visualize(). By default a conditional Route shows its condition's code.

Returns

Invisibly returns 'self' for method chaining.


Method set_entry()

Set the entry Station where execution begins.

If not called, $run() defaults to the first Station added.

Usage
Workflow$set_entry(station_name)
Arguments
station_name

'[character(1)]' Name of the entry Station.

Returns

Invisibly returns 'self' for method chaining.


Method validate()

Check the workflow before running it.

Looks at the Stations, Routes and parallel groups, without running anything or calling an LLM, and reports:

- **errors**: loops the run can never leave, where every Route leads back into the loop (the run would go on until the 500-step limit, calling its agents each time), and a workflow without Stations. $run() refuses to start when there is one. - **warnings**: Stations that never run because nothing leads to them; Routes that are never followed (a second unconditional Route from the same Station, the Routes of a Station that starts a parallel group or only runs inside one); and a Station that starts several parallel groups.

Workflows wrapped with $as_agent() and used as Stations are checked too. Conditions on Routes are not run: a conditional Route counts as one the run may follow.

Usage
Workflow$validate(quiet = FALSE)
Arguments
quiet

'[logical(1)]' If 'TRUE', nothing is printed.

Returns

Invisibly, a data frame with one row per issue and the columns 'level' ('"error"' or '"warning"'), 'check', 'stations' and 'message'. It has no rows when nothing was found.

Examples
wf <- Workflow$new("guide")
wf$add_station("draft", function(x) paste("Draft about", x))
wf$add_station("review", function(x) paste("Reviewed:", x))
wf$add_station("translate", function(x) x)
wf$add_route("draft", "review")
wf$add_route("review", "draft")
wf$validate()

Method run()

Execute the workflow sequentially.

The ‘input' string is passed to the entry Station. Each Station’s output becomes the next Station's input. Execution stops when a Station has no outgoing Route (or no Route whose condition evaluates to 'TRUE').

When use_cache = TRUE, a Station whose (name, input) pair has been seen before returns the cached output without re-invoking the handler. Use $clear_cache() to force re-execution.

With stream = TRUE (or an 'on_event' callback), progress is delivered as 'mini007_event' objects while the workflow executes: station start/completion, retries, fallbacks, HITL requests, the final output, and the token deltas of every Agent Station (see mini007_event).

Usage
Workflow$run(input, stream = FALSE, on_event = NULL, checkpoint = NULL)
Arguments
input

'[character(1)]' The initial prompt / payload.

stream

'[logical(1)]' Whether to stream progress. Without 'on_event', Agent token deltas are printed to the console.

on_event

'[function | NULL]' Callback receiving each 'mini007_event'. Supplying it implies stream = TRUE. Raising an error inside it cancels the run.

checkpoint

'[character(1) | NULL]' A file (eg. '"run.rds"') where the run is saved after every step, so that it can go on after a failure, an interruption or a restart of R instead of starting over. When the file holds an unfinished run of this workflow with the same 'input', $run() picks it up where it stopped: the Stations already done are not run again. See $resume_from(). 'NULL' (the default) saves nothing.

Returns

'[character(1)]' The output of the last Station executed, or - if execution reaches an HITL step while hitl_mode = "pause" - a 'mini007_pending' object. Use is_pending() to check.


Method resume_from()

Go on with a run saved in a checkpoint file.

A run started with $run(input, checkpoint = "run.rds") is saved after every step. If it failed, was interrupted or R was restarted, rebuild the workflow (with the same Stations), then call $resume_from("run.rds"): the run goes on from the first Station that did not finish, with the output of the last one that did. The Stations' agents start with the conversation they have in this session, not the one they had before the restart.

A run paused at an HITL step (hitl_mode = "pause") is saved too: give 'action' (and 'value') to answer it, as with $resume(); without 'action', the pending request is returned again.

Usage
Workflow$resume_from(
  checkpoint,
  action = NULL,
  value = NULL,
  stream = FALSE,
  on_event = NULL
)
Arguments
checkpoint

'[character(1)]' The checkpoint file.

action

'[character(1) | NULL]' For a run paused at an HITL step: '"continue"', '"edit"' or '"abort"', as in $resume().

value

'[character(1) | NULL]' With action = "edit": the replacement output.

stream

'[logical(1)]' Whether to stream the rest of the run.

on_event

'[function | NULL]' Callback receiving each 'mini007_event'. Supplying it implies stream = TRUE.

Returns

The output of the run (for a run that had already finished, the saved output), or a 'mini007_pending' object.

Examples
wf <- Workflow$new("guide")
wf$add_station("draft", function(x) paste("Draft about", x))
wf$add_station("polish", function(x) paste("Polished:", x))
wf$add_route("draft", "polish")
checkpoint <- tempfile(fileext = ".rds")
wf$run("Tlemcen", checkpoint = checkpoint)
wf$resume_from(checkpoint)

Method resume()

Resume a Workflow paused at an HITL step.

Only relevant when hitl_mode = "pause" (see $set_hitl()). $run() returns a 'mini007_pending' object when it reaches a paused HITL step; call $resume() with that object's 'request_id' and a chosen 'action' to continue execution from that point.

Usage
Workflow$resume(
  request_id,
  action = c("continue", "edit", "abort"),
  value = NULL,
  stream = FALSE,
  on_event = NULL
)
Arguments
request_id

'[character(1)]' The 'request_id' from the 'mini007_pending' object returned by $run().

action

'[character(1)]' One of '"continue"' (use the proposed output as-is), '"edit"' (replace it with 'value'), or '"abort"' (raise an error, stopping the workflow).

value

'[character(1) | NULL]' Required when action = "edit": the replacement output.

stream

'[logical(1)]' Whether to stream the remaining execution (see $run()).

on_event

'[function | NULL]' Callback receiving each 'mini007_event'. Supplying it implies stream = TRUE.

Returns

'[character(1)]' The final output, or another 'mini007_pending' object if a further HITL step is reached.


Method set_daemons()

Configure parallel execution daemons using mirai.

Sets up persistent daemon processes for parallel station execution. When 'n > 0', daemons are created via mirai::daemons(). Call with 'n = 0' to shut down all daemons.

The daemons belong to the R session: every 'Workflow' and 'LeadAgent' shares the same pool, and the last call sets its size. Each parallel station runs on a copy of its agents; once it finishes, their conversation, cost and traces are copied back to the original agents (also for agents that a function handler, a 'LeadAgent' or a wrapped 'Workflow' runs). A station that fails makes the workflow fail, with the errors of every failed station.

Usage
Workflow$set_daemons(n = 0L)
Arguments
n

'[integerish(1)]' Number of daemon processes (default '0'). Use number of cores for optimal CPU parallelism.

Returns

Invisibly returns 'self' for method chaining.


Method add_parallel_group()

Define a group of Stations to execute in parallel.

All specified Stations receive the same input and execute concurrently via mirai daemons. Their outputs are collected and merged by the 'merge_fn' before passing to the next Station(s).

Requires '$set_daemons(n > 0)' to be called first.

Usage
Workflow$add_parallel_group(from, stations, to = NULL, merge_fn = NULL)
Arguments
from

'[character(1)]' Name of the predecessor Station whose output feeds into the parallel group. It runs first, in the same step as the group (so a HITL pause at that step reviews the group's merged result), and its own Routes are not followed: the run goes on to 'to'.

stations

'[character]' Names of Stations to run in parallel. All must exist and not be the 'from' Station.

to

'[character(1)]' Name of the successor Station that receives the merged result (optional).

merge_fn

'[function]' A function function(results) that takes a named list of results (names are station names) and returns a single character string. Default concatenates results with newlines.

Returns

Invisibly returns 'self' for method chaining.


Method set_hitl()

Set Human-In-The-Loop (HITL) pause points.

When execution reaches a step whose number is listed in 'steps', it pauses and presents the human with three choices:

  1. Continue with the Station's original output.

  2. Edit the output manually before the next Station receives it.

  3. Stop the workflow immediately (raises an error).

HITL only fires on fresh Station executions - cache hits are skipped. Steps are numbered from 1 in execution order, matching the step counter shown in $run() output. You can set multiple steps at once: wf$set_hitl(c(1, 3)).

With mode = "console" (default), a paused step blocks on readline() right there in $run() - unchanged from previous behavior. With mode = "pause", $run() instead returns immediately with a 'mini007_pending' object describing the paused step; call $resume() with the chosen action to continue. This allows HITL to work outside an interactive console (e.g. Shiny, Plumber, or a batch job resuming later) and lets workflow state be inspected/persisted between steps.

Usage
Workflow$set_hitl(steps, mode = c("console", "pause"))
Arguments
steps

'[integerish]' One or more step numbers (>= 1).

mode

'[character(1)]' '"console"' (default) or '"pause"'.

Returns

Invisibly returns 'self' for method chaining.


Method clear_cache()

Remove all cached Station results.

Usage
Workflow$clear_cache()
Returns

Invisibly returns 'self'.


Method as_agent()

Wrap this Workflow as a 'WorkflowAgent'.

The returned 'WorkflowAgent' exposes $invoke(prompt) and holds an 'agent_id', making it compatible with 'LeadAgent$register_agents()' and usable as a Station handler inside another 'Workflow'.

Usage
Workflow$as_agent(name = NULL, instruction = NULL)
Arguments
name

'[character(1)]' Name for the 'WorkflowAgent'. Defaults to "\{workflow name\} (agent)".

instruction

'[character(1)]' Instruction string describing the agent's role. Used by 'LeadAgent' for task-agent matching.

Returns

A 'WorkflowAgent' object.


Method visualize()

Draw the workflow as a graph.

Each Station is a card showing its name, what runs it (an Agent and its model, a wrapped Workflow, or a function), its description, and its retries and fallback. The graph follows the rules of $run():

- **Start** leads to the entry Station, and **End** is reached from every Station where the run can stop. - Conditional Routes are dashed and labelled with the condition's code (or the 'label' given to $add_route()); the Route taken when no condition matches is labelled "otherwise". - Parallel groups are drawn in a box, and their results meet at a merge point before going on. - The issues $validate() reports are shown: Stations that never run are faded, loops the run can never leave are red, and Routes that are never followed are dotted and labelled "ignored".

Hover over a Station to see its description and, for an Agent, its instruction.

Usage
Workflow$visualize(direction = c("LR", "TB"))
Arguments
direction

'[character(1)]' '"LR"' (left to right, the default) or '"TB"' (top to bottom).

Returns

A 'grViz' htmlwidget. Its DOT code is in '$x$diagram'.

Examples
wf <- Workflow$new("casbah_guide")
wf$add_station("draft", function(x) paste("A guide to", x),
               description = "Draft a guide to the Casbah")
wf$add_station("review", function(x) x)
wf$add_station("translate", function(x) x)
wf$add_route("draft", "review")
wf$add_route("review", "draft", condition = function(x) grepl("TODO", x))
wf$add_route("review", "translate")
wf$visualize()

Examples


## ------------------------------------------------
## Method `Workflow$validate`
## ------------------------------------------------

wf <- Workflow$new("guide")
wf$add_station("draft", function(x) paste("Draft about", x))
wf$add_station("review", function(x) paste("Reviewed:", x))
wf$add_station("translate", function(x) x)
wf$add_route("draft", "review")
wf$add_route("review", "draft")
wf$validate()

## ------------------------------------------------
## Method `Workflow$resume_from`
## ------------------------------------------------

wf <- Workflow$new("guide")
wf$add_station("draft", function(x) paste("Draft about", x))
wf$add_station("polish", function(x) paste("Polished:", x))
wf$add_route("draft", "polish")
checkpoint <- tempfile(fileext = ".rds")
wf$run("Tlemcen", checkpoint = checkpoint)
wf$resume_from(checkpoint)

## ------------------------------------------------
## Method `Workflow$visualize`
## ------------------------------------------------

wf <- Workflow$new("casbah_guide")
wf$add_station("draft", function(x) paste("A guide to", x),
               description = "Draft a guide to the Casbah")
wf$add_station("review", function(x) x)
wf$add_station("translate", function(x) x)
wf$add_route("draft", "review")
wf$add_route("review", "draft", condition = function(x) grepl("TODO", x))
wf$add_route("review", "translate")
wf$visualize()

mini007 documentation built on Dec. 3, 2026, 5:10 p.m.