What are Hooks?
Hooks allow workflows to suspend execution and wait for external events. Unlikesleep() 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 with Pydantic (Recommended)
TypedHook combines hook suspension with Pydantic validation for type-safe payloads.Defining a Typed Hook
Using in a Workflow
CLI Interactive Resume
When you runpyworkflow 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 thehook() function directly.
Resuming Hooks
Using the CLI
Programmatically
Token Format
Tokens are composite identifiers in the formatrun_id:hook_id:
Configuration Options
Timeout Examples
on_created Callback
Theon_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
Use TypedHook for production workflows
Use TypedHook for production workflows
TypedHook provides validation, IDE support, and CLI interactive prompts:
Set appropriate timeouts
Set appropriate timeouts
Always set timeouts to prevent workflows from waiting indefinitely:Handle expiration gracefully in your workflow logic.
Use descriptive hook names
Use descriptive hook names
Hook names should clearly indicate their purpose:
Notify external systems via on_created
Notify external systems via on_created
Use the
on_created callback to trigger notifications:Handle hook errors gracefully
Handle hook errors gracefully
Catch and handle hook-related exceptions:
Testing Hooks
UseMockContext 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.