Execution Hooks
Attach custom behavior to workflow execution without changing logic. Add logging, metrics, or tracing at key lifecycle moments.
Overview
Hooks let you observe and extend workflow execution. They're perfect for:
- •Logging task starts, completions, and failures
- •Collecting metrics on execution time and costs
- •Distributed tracing for debugging
- •Custom error handling and recovery
Using the Default Hook
Mozaik provides a default hook that logs execution events:
1import { Workflow, Task, DEFAULT_CLUSTER_HOOK } from '@mozaik-ai/core'23const workflow = new Workflow("sequential", [4 new Task("Analyze data", "gpt-5"),5 new Task("Generate report", "gpt-5-mini")6])78// Execute with the default hook9await workflow.execute(DEFAULT_CLUSTER_HOOK)
Creating Custom Hooks
Create your own hooks to add custom behavior:
1import { Hook, TaskEvent } from '@mozaik-ai/core'23class MetricsHook implements Hook {4 private startTimes = new Map<string, number>()56 onTaskStart(event: TaskEvent) {7 this.startTimes.set(event.taskId, Date.now())8 console.log(`Starting: ${event.taskName}`)9 }1011 onTaskComplete(event: TaskEvent) {12 const startTime = this.startTimes.get(event.taskId)13 const duration = Date.now() - (startTime || 0)14 console.log(`Completed: ${event.taskName} in ${duration}ms`)1516 // Send to your metrics service17 sendMetric('task_duration', duration, { task: event.taskName })18 }1920 onTaskError(event: TaskEvent, error: Error) {21 console.error(`Failed: ${event.taskName}`, error)2223 // Send to your error tracking service24 trackError(error, { task: event.taskName })25 }26}
Combining Multiple Hooks
Use ClusterHook to combine multiple hooks:
1import { ClusterHook, DEFAULT_CLUSTER_HOOK } from '@mozaik-ai/core'2import { MetricsHook } from './metrics-hook'3import { TracingHook } from './tracing-hook'45// Combine multiple hooks6const extendedHook = new ClusterHook([7 DEFAULT_CLUSTER_HOOK, // Keep default logging8 new MetricsHook(), // Add metrics collection9 new TracingHook() // Add distributed tracing10])1112// All hooks fire on each event13await workflow.execute(extendedHook)
Tip
Hook Lifecycle Events
onWorkflowStart
Called when a workflow begins execution. Useful for initializing resources.
onTaskStart
Called before each task executes. Track task starts, set up context.
onTaskComplete
Called when a task completes successfully. Record metrics, log results.
onTaskError
Called when a task fails. Handle errors, trigger alerts, implement retry logic.
onWorkflowComplete
Called when the entire workflow finishes. Clean up resources, summarize results.
Complete Example: Logging Hook
1import { Hook, WorkflowEvent, TaskEvent } from '@mozaik-ai/core'23export class LoggingHook implements Hook {4 private indent = 056 private log(message: string) {7 console.log(' '.repeat(this.indent) + message)8 }910 onWorkflowStart(event: WorkflowEvent) {11 this.log(`Workflow started: ${event.workflowId}`)12 this.indent++13 }1415 onTaskStart(event: TaskEvent) {16 this.log(`Task started: ${event.taskName} (using ${event.model})`)17 this.indent++18 }1920 onTaskComplete(event: TaskEvent) {21 this.indent--22 this.log(`Task completed: ${event.taskName}`)23 }2425 onTaskError(event: TaskEvent, error: Error) {26 this.indent--27 this.log(`Task failed: ${event.taskName} - ${error.message}`)28 }2930 onWorkflowComplete(event: WorkflowEvent) {31 this.indent--32 this.log(`Workflow completed: ${event.workflowId}`)33 }34}