-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path3_sectioning.ts
79 lines (65 loc) · 2.34 KB
/
3_sectioning.ts
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
import { createWorkflow, workflowEvent, getContext } from "@llama-flow/core";
import { until } from "@llama-flow/core/stream/until";
import { collect } from "@llama-flow/core/stream/consumer";
import { filter } from "@llama-flow/core/stream/filter";
import { pipeline } from "node:stream/promises";
////////// define the workflow
const startEvent = workflowEvent<string>();
const branchAEvent = workflowEvent<string>();
const branchBEvent = workflowEvent<string>();
const branchCEvent = workflowEvent<string>();
const branchCompleteEvent = workflowEvent<string>();
const allCompleteEvent = workflowEvent<string>();
const stopEvent = workflowEvent<string>();
const workflow = createWorkflow();
// handle the start event
workflow.handle([startEvent], async (start) => {
// emit 3 different events, handled separately
const { sendEvent, stream } = getContext();
sendEvent(branchAEvent.with("Branch A"));
sendEvent(branchBEvent.with("Branch B"));
sendEvent(branchCEvent.with("Branch C"));
let condition = 0;
const results = await collect(
until(
filter(stream, (ev) => branchCompleteEvent.include(ev)),
() => {
condition++;
return condition === 3;
},
),
);
console.log(`All branches completed`);
console.log(results[0].data)
return allCompleteEvent.with(results.join(", "));
});
// handle branch A
workflow.handle([branchAEvent], (branchA) => {
return branchCompleteEvent.with(branchA.data);
});
// handle branch B
workflow.handle([branchBEvent], (branchB) => {
return branchCompleteEvent.with(branchB.data);
});
// handle branch C
workflow.handle([branchCEvent], (branchC) => {
return branchCompleteEvent.with(branchC.data);
});
// handle the collected results
workflow.handle([allCompleteEvent], (allComplete) => {
return stopEvent.with(allComplete.data);
});
////////// run the workflow
// Create a workflow context and send the initial event
const { stream, sendEvent } = workflow.createContext();
sendEvent(startEvent.with("I am some data"));
// Process the stream to get the result
const result = await pipeline(stream, async function (source) {
for await (const event of source) {
console.log(`Event: ${event.data}`);
if (stopEvent.include(event)) {
return `Result: ${event.data}`;
}
}
});
console.log(result)