Skip to main content

What are Hooks?

Hooks allow workflows to suspend execution and wait for external events. Unlike sleep() which resumes after a time duration, hooks wait for an external system or user to provide data before continuing.
Hooks can only be called from workflow-level code, not from within @step functions. Steps cannot suspend to wait for external events. If you need hook behavior triggered by a step, move the hook() call to the workflow and pass the result to the step.

How It Works

Choosing a Hook Type

PyWorkflow offers two ways to define hooks:
We recommend TypedHook for all production workflows. The Pydantic schema enables CLI interactive prompts, payload validation, and better IDE support.
TypedHook combines hook suspension with Pydantic validation for type-safe payloads.

Defining a Typed Hook

Using in a Workflow

CLI Interactive Resume

When you run pyworkflow hooks resume, the CLI uses the stored Pydantic schema to prompt for each field:

Simple Hook

For quick prototyping or when you don’t need typed payloads, use the hook() function directly.
Simple hooks don’t enable CLI interactive prompts. You must provide the full JSON payload when resuming.

Resuming Hooks

Using the CLI

Programmatically

Token Format

Tokens are composite identifiers in the format run_id:hook_id:
This self-describing format allows the system to route the resumption to the correct workflow run.

Configuration Options

Timeout Examples

on_created Callback

The on_created callback is called with the hook token when the hook is created. Use it to notify external systems:

Use Cases

Human Approval Workflows

Multi-Level Approval

Webhook Integration

User Confirmation

Best Practices

TypedHook provides validation, IDE support, and CLI interactive prompts:
Always set timeouts to prevent workflows from waiting indefinitely:
Handle expiration gracefully in your workflow logic.
Hook names should clearly indicate their purpose:
Use the on_created callback to trigger notifications:
Catch and handle hook-related exceptions:

Testing Hooks

Use MockContext to test workflows with hooks without actual suspension:

Testing Multiple Hooks

Hook Events

Hooks generate events that are stored in the event log: View hook events for a run:

Next Steps

Sleep

Pause workflows for time durations.

Workflows

Learn about workflow orchestration.

CLI Guide

Manage hooks with CLI commands.

Fault Tolerance

Auto-recovery from worker crashes.