Files
workflows-ts/demo/node/basic.ts
T
Thuc Pham 26d0ea4270 chore: clean up demo (#185)
Co-authored-by: Marcus Schiesser <mail@marcusschiesser.de>
2025-09-17 11:27:11 +08:00

62 lines
1.8 KiB
TypeScript

import { pipeline } from "node:stream/promises";
import {
createWorkflow,
getContext,
workflowEvent,
} from "@llamaindex/workflow-core";
//#region define workflow events
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>();
//#endregion
//#region defines workflow
const workflow = createWorkflow();
workflow.handle([startEvent], async () => {
// 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"));
const results = await stream.filter(branchCompleteEvent).take(3).toArray();
return allCompleteEvent.with(results.map((e) => e.data).join(", "));
});
workflow.handle([branchAEvent], (_context, branchA) => {
return branchCompleteEvent.with(branchA.data);
});
workflow.handle([branchBEvent], (_context, branchB) => {
return branchCompleteEvent.with(branchB.data);
});
workflow.handle([branchCEvent], (_context, branchC) => {
return branchCompleteEvent.with(branchC.data);
});
workflow.handle([allCompleteEvent], (_context, allComplete) => {
return stopEvent.with(allComplete.data);
});
//#endregion
const { stream, sendEvent } = workflow.createContext();
sendEvent(startEvent.with("initial data"));
const result = await pipeline(stream, async (source) => {
for await (const event of source) {
if (stopEvent.include(event)) {
return `Result: ${event.data}`;
}
}
});
console.log(result); // Result: Branch A, Branch B, Branch C