Repository navigation
Expand file tree
/
Copy pathworkflow.qmd
More file actions
903 lines (701 loc) · 27.7 KB
/
Copy pathworkflow.qmd
File metadata and controls
903 lines (701 loc) · 27.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
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
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
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
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
---
title: "Workflow"
format:
html:
toc: true
execute:
echo: true
warning: false
error: false
---
```{r}
library(mini007)
retrieve_open_ai_credential <- function() {
Sys.getenv("OPENAI_API_KEY")
}
openai_4_1_mini <- ellmer::chat(
name = "openai/gpt-4.1-mini",
credentials = retrieve_open_ai_credential,
echo = "none"
)
```
A `Workflow` is a predefined, sequential pipeline of processing units called **Stations**. Each Station receives the output of the previous one as its input, transforms it, and passes the result forward. **Routes** define which Station comes next and can be gated by optional condition functions that inspect the current output to decide the execution path.
Workflows complement `Agent` and `LeadAgent`:
- An `Agent` is LLM-driven and decides its own steps dynamically.
- A `LeadAgent` decomposes a prompt and delegates subtasks to agents automatically.
- A `Workflow` gives you **explicit control** over every step of the pipeline — you decide the order, the branching logic, and which handler runs where.
There are two main building blocks:
- `add_station(name, handler)` — registers a named processing unit. The handler can be an `Agent`, a `WorkflowAgent`, or a plain R `function`.
- `add_route(from, to)` — connects two Stations in sequence.
## A minimal linear pipeline
The simplest `Workflow` is a straight chain of Stations executed one after the other. Here we wire three specialised agents: a researcher that gathers facts, a writer that shapes them into a paragraph, and an editor that polishes the result.
```{r}
researcher <- Agent$new(
name = "researcher",
instruction = "You are a research assistant. Provide concise, accurate facts on the given topic in 3 max",
llm_object = openai_4_1_mini
)
writer <- Agent$new(
name = "writer",
instruction = "You are a skilled writer. Turn the research notes you receive into a single, engaging paragraph.",
llm_object = openai_4_1_mini
)
editor <- Agent$new(
name = "editor",
instruction = "You are a copy editor. Polish the paragraph you receive for grammar, clarity, and conciseness. Return only the final text.",
llm_object = openai_4_1_mini
)
translator <- Agent$new(
name = "translator",
instruction = "You're a English-German Translater, translate text from English to German",
llm_object = openai_4_1_mini
)
```
```{r}
article_pipeline <- Workflow$new(
name = "article pipeline",
description = "Research → Write → Edit -> Transalte",
use_cache = TRUE
)
article_pipeline$add_station(name = "research", handler = researcher, )
article_pipeline$add_station(name = "write", handler = writer)
article_pipeline$add_station(name = "edit", handler = editor)
article_pipeline$add_station(name = "translate", handler = translator)
article_pipeline$add_route(from = "research", to = "write")
article_pipeline$add_route(from = "write", to = "edit")
article_pipeline$add_route(from = "edit", to = "translate")
article_pipeline$set_entry(station_name = "research")
```
Calling `$run()` executes every Station in order. Each Station's output becomes the next Station's input automatically.
```{r}
result <- article_pipeline$run("The potential of Algeria when it comes to tourism in the Sahara")
result
```
The `run_history` attribute records every execution, including the full trace of inputs and outputs for each Station:
```{r}
article_pipeline$run_history
```
## Mixing agents with plain R functions
Stations do not have to be `Agent` objects. Any R function that accepts a single character argument and returns a character value is a valid handler. This makes it easy to add pre-processing or post-processing steps without an LLM call.
```{r}
# Plain R function stations, no LLM involved
normalise <- function(text) {
trimws(gsub("\\s+", " ", text))
}
add_markdown_header <- function(text) {
paste0("## Summary\n\n", text)
}
summariser <- Agent$new(
name = "summariser",
instruction = "Summarise the text you receive into exactly three concise bullet points.",
llm_object = openai_4_1_mini
)
```
```{r}
format_pipeline <- Workflow$new("format and summarise")
format_pipeline$add_station(
name = "normalise",
handler = normalise,
description = "Collapse whitespace"
)
format_pipeline$add_station(
name = "summarise",
handler = summariser,
description = "LLM bullet summary"
)
format_pipeline$add_station(
name = "add_header",
handler = add_markdown_header,
description = "Prepend markdown header"
)
format_pipeline$add_route(from = "normalise", to = "summarise")
format_pipeline$add_route(from = "summarise", to = "add_header")
```
```{r}
messy_text <- " The 2026 worldcup is approachine. Algeria's first game is against Argentina "
format_pipeline$run(messy_text)
```
## Caching station results
When `use_cache = TRUE` (the default), every Station's output is stored keyed by its name and the input it received. A subsequent `$run()` call with the same input skips re-invoking any handler and returns the cached result immediately — saving both time and LLM costs when you are iterating on later Stations.
```{r}
cached_pipeline <- Workflow$new(
name = "cached-pipeline",
use_cache = TRUE
)
drafter <- Agent$new(
name = "drafter",
instruction = "Write a two-sentence draft on the topic provided.",
llm_object = openai_4_1_mini
)
refiner <- Agent$new(
name = "refiner",
instruction = "Improve the draft you receive. Make it more vivid and precise.",
llm_object = openai_4_1_mini
)
cached_pipeline$add_station(name = "draft", handler = drafter)
cached_pipeline$add_station(name = "refine", handler = refiner)
cached_pipeline$add_route(from = "draft", to = "refine")
```
```{r}
# First run — both stations are executed
start <- Sys.time()
first_run <- cached_pipeline$run("Rare fish in the Algerian see")
first_run
end <- Sys.time()
print(end - start)
```
```{r}
# Second run with the same input — cache is served, no LLM calls are made
start <- Sys.time()
second_run <- cached_pipeline$run("Rare fish in the Algerian see")
second_run
end <- Sys.time()
print(end - start)
```
To force a fresh execution, call `$clear_cache()`:
```{r}
cached_pipeline$clear_cache()
# Fresh run after clearing the cache
start <- Sys.time()
fresh_run <- cached_pipeline$run("Rare fish in the Algerian see")
fresh_run
end <- Sys.time()
print(end - start)
```
## Conditional routing
Routes can carry a `condition`, a function that inspects the current Station's output and returns `TRUE` or `FALSE`. When a Station has multiple outgoing Routes, conditional ones are evaluated first (in the order they were added). The first condition that returns `TRUE` determines the next Station. If none match, the first unconditional Route is used as the default fallback.
This makes it possible to build branching pipelines where the path taken depends on what an earlier Station produces.
```{r}
classifier <- Agent$new(
name = "classifier",
instruction = 'Classify the sentiment of the text. Reply with exactly one word: "positive" or "negative".',
llm_object = openai_4_1_mini
)
positive_handler <- Agent$new(
name = "positive_handler",
instruction = "Write a warm, enthusiastic one-sentence reply to the following positive message.",
llm_object = openai_4_1_mini
)
negative_handler <- Agent$new(
name = "negative_handler",
instruction = "Write an empathetic, solution-focused one-sentence reply to the following negative message.",
llm_object = openai_4_1_mini
)
```
```{r}
sentiment_router <- Workflow$new("sentiment router")
sentiment_router$add_station(name = "classify", handler = classifier)
sentiment_router$add_station(name = "reply_pos", handler = positive_handler)
sentiment_router$add_station(name = "reply_neg", handler = negative_handler)
# Conditional routes — evaluated against the classifier's output
sentiment_router$add_route(
from = "classify",
to = "reply_pos",
condition = function(out) grepl("positive", tolower(out))
)
sentiment_router$add_route(
from = "classify",
to = "reply_neg",
condition = function(out) grepl("negative", tolower(out))
)
sentiment_router$set_entry(station_name = "classify")
```
```{r}
sentiment_router$run("I absolutely love this product, it changed my life!")
```
```{r}
sentiment_router$run("Very disappointed. The quality is nothing like advertised.")
```
A more structured example uses a plain function as the router so the branching logic is deterministic and free of LLM calls.
**Important pattern:** the router station must be a **passthrough** — it returns the original text unchanged so that downstream agents receive the real content. The routing classification belongs in the **route conditions**, which inspect the station output and decide where it goes next.
```{r}
brief_expander <- Agent$new(
name = "brief_expander",
instruction = "The input is short. Expand it into a well-rounded paragraph of 2 sentences.",
llm_object = openai_4_1_mini
)
long_summariser <- Agent$new(
name = "long_summariser",
instruction = "The input is long. Distill it into a single crisp sentence.",
llm_object = openai_4_1_mini
)
length_router <- Workflow$new("length router")
# The router station is a passthrough: it returns the text as-is.
# The length check lives in the route conditions below, not here.
length_router$add_station(name = "router", handler = function(text) text)
length_router$add_station(name = "short-to-long", handler = brief_expander)
length_router$add_station(name = "long-to-short", handler = long_summariser)
# Conditions receive the router's output (the original text) and decide the branch.
length_router$add_route(
from = "router",
to = "short-to-long",
condition = function(x) nchar(x) < 80
)
length_router$add_route(
from = "router",
to = "long-to-short",
condition = function(x) nchar(x) >= 80
)
length_router$set_entry(station_name = "router")
```
```{r}
# Short input — routed to the expander
length_router$run("Fennec Algeria football team")
```
```{r}
# Long input — routed to the summariser
long_input <- paste(
"Bees are among the most important pollinators on the planet.",
"They transfer pollen from one flower to another, enabling plants to reproduce.",
"Without bees, many of the fruits and vegetables we eat would disappear.",
"Colony collapse disorder has threatened bee populations worldwide,",
"raising serious concerns about food security and ecosystem stability."
)
length_router$run(long_input)
```
## Wrapping a workflow as an agent
`$as_agent()` converts any `Workflow` into a `WorkflowAgent`. The result exposes the same `$invoke()` interface as a regular `Agent`, which means it can be:
- **registered with a `LeadAgent`** as one of its sub-agents, or
- **used as a Station handler** inside another `Workflow`.
This lets you compose complex pipelines from simpler ones without rewriting any logic.
### Using a WorkflowAgent inside a LeadAgent
```{r}
# Inner workflow: research + summarise
research_wf <- Workflow$new("research workflow")
gatherer <- Agent$new(
name = "gatherer",
instruction = "Gather three key facts about the topic provided. Be concise.",
llm_object = openai_4_1_mini
)
condonser <- Agent$new(
name = "condenser",
instruction = "Condense the facts you receive into a single sentence.",
llm_object = openai_4_1_mini
)
research_wf$add_station(name = "gather", handler = gatherer)
research_wf$add_station(name = "condense", handler = condonser)
research_wf$add_route(from = "gather", to = "condense")
research_wf$set_entry(station_name = "gather")
# Wrap as a WorkflowAgent
research_agent <- research_wf$as_agent(
name = "research_agent",
instruction = "An agent that gathers and condenses facts on any topic into one sentence."
)
```
```{r}
# Use the WorkflowAgent directly
research_agent$invoke("The city of Bejaia in Algeria")
```
```{r}
# Register with a LeadAgent alongside regular agents
translator <- Agent$new(
name = "translator",
instruction = "Translate the text you receive from English into German",
llm_object = openai_4_1_mini
)
lead <- LeadAgent$new(
name = "Lead",
llm_object = openai_4_1_mini
)
lead$register_agents(c(research_agent, translator))
lead$invoke("Tell me about the city of Bejaia in one sentence, then translate it into German")
```
### Nesting a WorkflowAgent inside another Workflow
```{r}
# Outer workflow: use the wrapped inner workflow as a Station
presentation_wf <- Workflow$new("Presentation workflow")
presentation_wf$add_station(
name = "research",
handler = research_agent # WorkflowAgent used as a station handler
)
presenter <- Agent$new(
name = "presenter",
instruction = "Turn the one-sentence summary you receive into a polished three-sentence report.",
llm_object = openai_4_1_mini
)
presentation_wf$add_station(
name = "present",
handler = presenter
)
presentation_wf$add_route(from = "research", to = "present")
presentation_wf$set_entry(station_name = "research")
presentation_wf$run("Algeria and Coffee")
```
## Human In The Loop (HITL)
`$set_hitl(steps)` lets you pause the workflow at specific steps so a human
can inspect the Station's output before execution continues. Steps are
numbered from 1 in execution order — the same counter shown in the `run()`
console output.
When execution reaches a HITL step, it prints the Station name, the input it
received, and the output it produced, then offers three choices:
1. **Continue** — use the output as-is and move to the next Station.
2. **Edit** — type a replacement output; that value is forwarded to the next
Station (and cached, if caching is on).
3. **Stop** — abort the workflow immediately.
HITL only fires on fresh executions; cache hits are skipped since the result
has already been reviewed in a prior run.
```{r}
hitl_pipeline <- Workflow$new("hitl pipeline", use_cache = FALSE)
drafter <- Agent$new(
name = "drafter",
instruction = "Write a short two-sentence paragraph on the topic provided.",
llm_object = openai_4_1_mini
)
translator <- Agent$new(
name = "translator",
instruction = "Translate the text you receive from English into Spanish.",
llm_object = openai_4_1_mini
)
hitl_pipeline$add_station(name = "draft", handler = drafter)
hitl_pipeline$add_station(name = "translate", handler = translator)
hitl_pipeline$add_route(from = "draft", to = "translate")
# Pause after step 1 (the drafter) so a human can review the draft
# before it is sent to the translator
hitl_pipeline$set_hitl(steps = 1)
```
```{r}
#| eval: false
hitl_pipeline$run("The discovery of penicillin")
```
You can set HITL at multiple steps at once:
```{r}
#| eval: false
hitl_pipeline$set_hitl(steps = c(1, 2), mode = "interactive")
```
### Non-blocking HITL: pause and resume (Not yet on CRAN)
The `HITL` above with `mode="interactive"` (the default) only works in an interactive console. Pass `mode = "pause"` to `$set_hitl()` and `$run()` returns immediately instead of
blocking, handing you back a `mini007_pending` object that describes exactly
where execution stopped. This is what lets HITL work from a Shiny app, a
Plumber API, or any batch job: persist the pending object, resume it whenever
the human actually responds, even in a different R session.
Let's route a teaser about Tassili n'Ajjer, the Algerian Sahara's
prehistoric rock-art plateau through a drafter and a translator, pausing
after the draft for review:
```{r}
sahara_pipeline <- Workflow$new("sahara pipeline", use_cache = FALSE)
drafter <- Agent$new(
name = "sahara_drafter",
instruction = "Write a punchy two-sentence teaser about the Saharan destination provided.",
llm_object = openai_4_1_mini
)
translator <- Agent$new(
name = "translator",
instruction = "Translate the text you receive from English into German.",
llm_object = openai_4_1_mini
)
sahara_pipeline$add_station(name = "draft", handler = drafter)
sahara_pipeline$add_station(name = "translate", handler = translator)
sahara_pipeline$add_route(from = "draft", to = "translate")
# mode = "pause" instead of the default "console"
sahara_pipeline$set_hitl(steps = 1, mode = "pause")
```
```{r}
#| eval: true
pending <- sahara_pipeline$run("Tassili n'Ajjer, Algeria")
pending
```
```
── Pending HITL request - step 1 ──
Request id: "b3f1c2a0-..."
Station/Agent: draft
ℹ Input:
Tassili n'Ajjer, Algeria
ℹ Proposed output:
Deep in Algeria's Sahara, Tassili n'Ajjer hides 15,000 years of rock art
carved into sandstone cathedrals — a UNESCO World Heritage plateau most
travellers never set foot on.
! Call `$resume("b3f1c2a0-...", action = "continue"|"edit"|"abort")` to proceed.
```
`is_pending(pending)` returns `TRUE` for this object (and `FALSE` for a
normal completed result). Once the human has weighed in, call `$resume()` with one of three actions:
```{r}
#| eval: false
# 1. Accept the draft as-is — the translator receives it next
sahara_pipeline$resume(pending$request_id, action = "continue")
```
```{r}
#| eval: false
# 2. Or edit it first. The edited text is what the translator receives
sahara_pipeline$resume(
pending$request_id,
action = "edit",
value = "Tassili n'Ajjer: 15,000 years of rock art etched into Saharan sandstone, in Algeria's far southeast."
)
```
```{r}
#| eval: false
# 3. Or abort altogether — raises an error, nothing downstream runs
sahara_pipeline$resume(pending$request_id, action = "abort")
```
If the workflow has more HITL steps ahead, `$resume()` returns another
`mini007_pending` object instead of the final result — so a caller typically
loops `while (is_pending(result))`, persisting `result$request_id` between
iterations, until a plain character string comes back.
Note that a `Workflow` wrapped as a `WorkflowAgent` (via `$as_agent()`) must
keep `mode = "console"` (the default): a `WorkflowAgent` is invoked
synchronously from inside a `Workflow` Station or a `LeadAgent` step, and
neither knows how to hand a paused run back to you — `$invoke()` raises an
error if the wrapped workflow pauses.
## Visualising a workflow
Call `$visualize()` on any `Workflow` to render an interactive directed graph. Stations appear as rounded blue boxes, conditional Routes as dashed arrows labelled "cond", and the entry Station is reached via a green **START** node.
```{r, eval=TRUE}
article_pipeline$visualize()
```
```{r, eval=TRUE}
sentiment_router$visualize()
```
The graph updates automatically to reflect whatever Stations and Routes are currently registered, making it a convenient tool for checking that the pipeline is wired correctly before running it.
---
## Per-station retry (Not yet on CRAN)
Real-world pipelines talk to external services — LLM providers, APIs, databases — that can fail transiently: rate-limit errors, network blips, brief provider outages. Rather than letting a single transient failure abort the entire run, you can attach a **retry logic** to any Station via two parameters of `$add_station()`:
| Parameter | Default | Meaning |
|-----------|---------|---------|
| `max_retries` | `0` | Extra attempts after the first failure |
| `retry_delay` | `1` | Seconds to sleep between attempts |
The station is tried up to `max_retries + 1` times in total. If it succeeds on any attempt, execution continues normally. If all attempts fail, the error is either forwarded to a [fallback handler](#fallback-handlers) (see below) or re-raised.
### Simulating a flaky service
```{r}
# Factory that returns a handler which fails the first `fail_times` calls
make_flaky_service <- function(fail_times = 2L) {
attempts <- 0
function(text) {
attempts <<- attempts + 1L
if (attempts <= fail_times) {
stop(sprintf("HTTP 429: Rate limit (attempt %d of %d)", attempts, fail_times + 1L))
}
paste("Service result:", toupper(text))
}
}
```
```{r}
#| message: false
retry_wf <- Workflow$new("retry pipeline", use_cache = FALSE)
retry_wf$add_station(
name = "call_service",
handler = make_flaky_service(fail_times = 2L),
max_retries = 3,
retry_delay = 0 # set to a positive number (e.g. 2) in production
)
retry_wf$run("summarise this document")
```
The station fails on attempts 1 and 2, then succeeds on attempt 3. The workflow returns the successful result transparently.
### Attaching retries to an Agent station
`max_retries` works identically for Agent stations — the LLM call is retried the same way.
```{r}
#| eval: false
fragile_pipeline <- Workflow$new("fragile pipeline")
fragile_pipeline$add_station(
name = "analyse",
handler = some_agent, # any Agent or WorkflowAgent
max_retries = 2,
retry_delay = 3 # wait 3 s between retries
)
```
### Behaviour when all retries are exhausted
When every attempt fails and no [fallback](#fallback-handlers) is defined, the last error is re-raised and propagates up from `$run()`.
```{r}
always_fails_wf <- Workflow$new("always-fails pipeline", use_cache = FALSE)
always_fails_wf$add_station(
name = "broken_step",
handler = function(x) stop("Service permanently unavailable"),
max_retries = 1,
retry_delay = 0
)
tryCatch(
always_fails_wf$run("input"),
error = function(e) paste("Caught:", conditionMessage(e))
)
```
---
## Fallback handlers {#fallback-handlers} (not yet on CRAN)
A **fallback** is a `function(input, error)` attached to a specific Station. It is invoked only after all retry attempts for that Station have been exhausted, giving you a controlled degradation path instead of a hard failure.
```r
wf$add_station(
name = "step",
handler = primary_handler,
fallback = function(input, error) {
# `input` — the string the station received
# `error` — the condition object from the last failed attempt
"default output"
}
)
```
The fallback's return value is used as the station's output and the pipeline continues normally from there.
### Simple graceful degradation
```{r}
safe_wf <- Workflow$new("safe pipeline", use_cache = FALSE)
safe_wf$add_station(
name = "fetch_summary",
handler = function(x) stop("Connection refused"),
fallback = function(input, err) {
paste("(Summary unavailable — service error:", conditionMessage(err), ")\nOriginal:", input)
}
)
safe_wf$run("Analyse this quarterly report")
```
### Fallback fires only after all retries
The fallback is a last resort. With `max_retries > 0` the primary handler is tried repeatedly; the fallback only runs if every attempt fails.
```{r}
#| message: false
attempts <- 0L
resilient_wf <- Workflow$new("resilient pipeline", use_cache = FALSE)
resilient_wf$add_station(
name = "external_call",
handler = function(x) {
attempts <<- attempts + 1L
stop(sprintf("Attempt %d failed", attempts))
},
max_retries = 2,
retry_delay = 0,
fallback = function(input, err) {
paste0("[Fallback after ", attempts, " attempt(s)] ", input)
}
)
resilient_wf$run("Process this document")
```
### Routing continues after a fallback
The fallback's output flows into the next Station via the normal routing mechanism. The rest of the pipeline is unaware that a fallback fired.
```{r}
routed_fallback_wf <- Workflow$new("routed fallback", use_cache = FALSE)
routed_fallback_wf$add_station(
name = "fetch",
handler = function(x) stop("API down"),
fallback = function(input, err) paste("CACHED VERSION OF:", input)
)
routed_fallback_wf$add_station(
"format",
function(x) paste0("**", trimws(x), "**")
)
routed_fallback_wf$add_route("fetch", "format")
routed_fallback_wf$run("monthly sales figures")
```
### Using a backup LLM as the fallback
A common production pattern is to call a premium model as the primary handler and fall back to a cheaper or local model when the primary is unavailable.
```{r}
#| eval: false
primary_agent <- Agent$new("primary", "You are a senior analyst.", premium_llm)
fallback_agent <- Agent$new("fallback", "You are a concise analyst.", cheap_llm)
pipeline <- Workflow$new("model-with-backup")
pipeline$add_station(
name = "analyse",
handler = primary_agent,
max_retries = 1,
retry_delay = 2,
fallback = function(input, err) {
fallback_agent$invoke(input) # delegate to the backup model
}
)
```
---
## Parallel Stations (not yet on CRAN)
Multiple independent Stations can run concurrently using `$set_daemons()` and `$add_parallel_group()`.
### Multi-perspective parallel analysis
```{r}
# Create three specialized agents for different perspectives
technical_agent <- Agent$new(
name = "technical_analyst",
instruction = paste(
"You are a technical expert in AI and software engineering.",
"Analyze topics from a technical/engineering perspective.",
"Focus on: implementation details, technology stack, technical challenges.",
"Keep responses to 2-3 sentences."
),
llm_object = openai_4_1_mini
)
business_agent <- Agent$new(
name = "business_strategist",
instruction = paste(
"You are a business strategist and market analyst.",
"Analyze topics from a business/market perspective.",
"Focus on: market opportunities, ROI, competitive advantage, business models.",
"Keep responses to 2-3 sentences."
),
llm_object = openai_4_1_mini
)
ux_agent <- Agent$new(
name = "ux_specialist",
instruction = paste(
"You are a UX and product design specialist.",
"Analyze topics from a user experience perspective.",
"Focus on: user needs, design considerations, accessibility, user satisfaction.",
"Keep responses to 2-3 sentences."
),
llm_object = openai_4_1_mini
)
# Create workflow with parallel execution
wf <- Workflow$new(
name = "parallel_multi_agent_analysis",
description = "Multi-perspective analysis using parallel Agent invocations"
)
# Set up 3 parallel workers for concurrent API calls
wf$set_daemons(3)
# Add input station (passthrough)
wf$add_station(
"input",
handler = function(x) x,
description = "Input topic"
)
# Add three parallel Agent stations
wf$add_station(
"technical_analysis",
handler = technical_agent,
description = "Technical perspective"
)
wf$add_station(
"business_analysis",
handler = business_agent,
description = "Business perspective"
)
wf$add_station(
"ux_analysis",
handler = ux_agent,
description = "UX perspective"
)
# Add synthesis station
wf$add_station(
"synthesis",
handler = function(x) {
paste0(
"═══════════════════════════════════════════\n",
"MULTI-PERSPECTIVE ANALYSIS REPORT\n",
"═══════════════════════════════════════════\n\n",
x
)
},
description = "Synthesis"
)
# Define parallel group: input -> [technical, business, ux] -> synthesis
wf$add_parallel_group(
from = "input",
stations = c("technical_analysis", "business_analysis", "ux_analysis"),
to = "synthesis",
merge_fn = function(results) {
paste0(
"📱 TECHNICAL PERSPECTIVE:\n",
results$technical_analysis, "\n\n",
"💼 BUSINESS PERSPECTIVE:\n",
results$business_analysis, "\n\n",
"👤 UX PERSPECTIVE:\n",
results$ux_analysis
)
}
)
wf$visualize()
```
```{r}
# Execute workflow with parallel execution
topic <- "Artificial Intelligence in Healthcare"
result <- wf$run(topic)
<
43CD
/div># Clean up any existing daemons from previous runs
mirai::daemons(0)
result
```
### How it works
1. **`$set_daemons(n)`** Creates `n` parallel worker processes.
2. **`$add_parallel_group(from, stations, to, merge_fn)`** Defines which stations run in parallel:
- `from`: predecessor station (all parallel stations receive its output)
- `stations`: vector of station names to run concurrently
- `to`: successor station (receives merged results)
- `merge_fn`: function to combine results from all parallel stations
3. **Execution** All parallel stations run concurrently in separate daemons
4. **Visualization** `$visualize()` shows parallel routes in **red with ∥ symbol** to distinguish from sequential routes