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:

hooks-default.ts
1import { Workflow, Task, DEFAULT_CLUSTER_HOOK } from '@mozaik-ai/core'
2
3const workflow = new Workflow("sequential", [
4 new Task("Analyze data", "gpt-5"),
5 new Task("Generate report", "gpt-5-mini")
6])
7
8// Execute with the default hook
9await workflow.execute(DEFAULT_CLUSTER_HOOK)

Creating Custom Hooks

Create your own hooks to add custom behavior:

hooks-custom.ts
1import { Hook, TaskEvent } from '@mozaik-ai/core'
2
3class MetricsHook implements Hook {
4 private startTimes = new Map<string, number>()
5
6 onTaskStart(event: TaskEvent) {
7 this.startTimes.set(event.taskId, Date.now())
8 console.log(`Starting: ${event.taskName}`)
9 }
10
11 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`)
15
16 // Send to your metrics service
17 sendMetric('task_duration', duration, { task: event.taskName })
18 }
19
20 onTaskError(event: TaskEvent, error: Error) {
21 console.error(`Failed: ${event.taskName}`, error)
22
23 // Send to your error tracking service
24 trackError(error, { task: event.taskName })
25 }
26}

Combining Multiple Hooks

Use ClusterHook to combine multiple hooks:

hooks-cluster.ts
1import { ClusterHook, DEFAULT_CLUSTER_HOOK } from '@mozaik-ai/core'
2import { MetricsHook } from './metrics-hook'
3import { TracingHook } from './tracing-hook'
4
5// Combine multiple hooks
6const extendedHook = new ClusterHook([
7 DEFAULT_CLUSTER_HOOK, // Keep default logging
8 new MetricsHook(), // Add metrics collection
9 new TracingHook() // Add distributed tracing
10])
11
12// All hooks fire on each event
13await workflow.execute(extendedHook)

Tip

Hooks execute in order. Place logging hooks first so you can see events even if later hooks throw errors.

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

logging-hook.ts
1import { Hook, WorkflowEvent, TaskEvent } from '@mozaik-ai/core'
2
3export class LoggingHook implements Hook {
4 private indent = 0
5
6 private log(message: string) {
7 console.log(' '.repeat(this.indent) + message)
8 }
9
10 onWorkflowStart(event: WorkflowEvent) {
11 this.log(`Workflow started: ${event.workflowId}`)
12 this.indent++
13 }
14
15 onTaskStart(event: TaskEvent) {
16 this.log(`Task started: ${event.taskName} (using ${event.model})`)
17 this.indent++
18 }
19
20 onTaskComplete(event: TaskEvent) {
21 this.indent--
22 this.log(`Task completed: ${event.taskName}`)
23 }
24
25 onTaskError(event: TaskEvent, error: Error) {
26 this.indent--
27 this.log(`Task failed: ${event.taskName} - ${error.message}`)
28 }
29
30 onWorkflowComplete(event: WorkflowEvent) {
31 this.indent--
32 this.log(`Workflow completed: ${event.workflowId}`)
33 }
34}

Continue Learning