Skip to main content
This example demonstrates how to create event-driven workflows for complex multi-step AI applications.

Overview

Workflows allow you to:
  • Create event-driven architectures
  • Manage state across multiple steps
  • Build iterative refinement loops
  • Compose complex AI pipelines
This example builds a joke refinement workflow that iteratively improves a joke based on LLM critique.

Complete Example

joke-workflow.ts

Step-by-Step Explanation

1. Define Events

Events represent data flowing through your workflow:
Each event carries typed data through the workflow.

2. Create Stateful Workflow

Add state management to track workflow progress:

3. Define Event Handlers

Handlers process events and emit new events:

4. Conditional Routing

Route to different events based on conditions:

5. Access State

Read and update workflow state:

6. Execute Workflow

Workflow Patterns

Linear Pipeline

Sequential processing steps:

Parallel Execution

Process multiple paths simultaneously:

Iterative Refinement

Loop until condition met:

Error Handling

Handle errors gracefully:

Running the Example

  1. Install dependencies:
  1. Set your API key:
  1. Run the workflow:

Expected Output

The workflow will:
  1. Generate an initial joke about pirates
  2. Critique the joke
  3. If needed, improve the joke up to 3 times
  4. Return the final joke and critique

Advanced Features

Timeout Handling

Workflow Composition

Combine multiple workflows:

Next Steps

Advanced Workflows

Explore the workflows-ts repository

Agents

Combine workflows with agents

RAG Pipeline

Build RAG ingestion workflows

Event Streaming

Stream workflow events to clients