Skip to main content

Workflow Hooks

Add lifecycle hooks to workflows for monitoring, logging, and custom logic.

Basic Usage

import { Workflow, WorkflowHooksConfig } from 'praisonai';

const hooks: WorkflowHooksConfig = {
  onWorkflowStart: (workflow, input) => {
    console.log(`Starting: ${workflow.name}`);
  },
  
  onStepStart: (stepName, context) => {
    console.log(`Step ${context.stepIndex + 1}/${context.totalSteps}: ${stepName}`);
  },
  
  onStepComplete: (stepName, result) => {
    console.log(`${stepName} completed`);
  },
  
  onWorkflowComplete: (workflow, result) => {
    console.log(`Workflow done!`);
  }
};

const workflow = new Workflow({
  name: 'my-workflow',
  hooks
});

All Hooks

interface WorkflowHooksConfig {
  // Workflow lifecycle
  onWorkflowStart?: (workflow, input) => void | Promise<void>;
  onWorkflowComplete?: (workflow, result) => void | Promise<void>;
  onWorkflowError?: (workflow, error) => void | Promise<void>;
  
  // Step lifecycle
  onStepStart?: (stepName, context) => void | Promise<void>;
  onStepComplete?: (stepName, result, context) => void | Promise<void>;
  onStepError?: (stepName, error, context) => void | Promise<void>;
}

Step Context

interface StepContext {
  stepName: string;
  stepIndex: number;      // 0-based
  totalSteps: number;
  input: any;             // Current step input
  previousResults: Record<string, any>;
}

Pre-built Hooks

Logging Hooks

import { createLoggingWorkflowHooks } from 'praisonai';

const hooks = createLoggingWorkflowHooks((msg, data) => {
  console.log(`[Workflow] ${msg}`, data);
});

// Output:
// [Workflow] Workflow "my-workflow" started { input: ... }
// [Workflow] Step "step1" started (1/3)
// [Workflow] Step "step1" completed { result: ... }
// ...

Timing Hooks

import { createTimingWorkflowHooks } from 'praisonai';

const { hooks, getTimings } = createTimingWorkflowHooks();

const workflow = new Workflow({ hooks });
await workflow.run(input);

const timings = getTimings();
console.log(timings);
// {
//   workflow_abc123: 5432,      // Total ms
//   step_research: 2100,
//   step_write: 3200
// }

WorkflowHooksExecutor

For programmatic hook execution:
import { WorkflowHooksExecutor, createWorkflowHooks } from 'praisonai';

const executor = createWorkflowHooks({
  onWorkflowStart: (wf, input) => console.log('Start'),
  onStepComplete: (name, result) => console.log(`${name} done`)
}, true); // logging = true

// Check if hooks configured
if (executor.hasHooks()) {
  console.log('Hooks:', executor.getConfiguredHooks());
}

// Execute manually
await executor.onWorkflowStart(workflowRef, input);
await executor.onStepComplete('step1', result, context);

Error Handling

const hooks: WorkflowHooksConfig = {
  onStepError: async (stepName, error, context) => {
    console.error(`Step ${stepName} failed:`, error.message);
    
    // Log to external service
    await logToSentry({
      step: stepName,
      error: error.message,
      context
    });
  },
  
  onWorkflowError: async (workflow, error) => {
    console.error(`Workflow ${workflow.name} failed`);
    
    // Send alert
    await sendAlert({
      workflow: workflow.id,
      error: error.message
    });
  }
};

Async Hooks

All hooks support async functions:
const hooks: WorkflowHooksConfig = {
  onStepComplete: async (stepName, result) => {
    // Save to database
    await db.insert('step_results', {
      step: stepName,
      result,
      timestamp: new Date()
    });
  }
};