Message Hooks
Message hooks let you intercept, inspect, and modify messages as they flow through the agent - perfect for content filtering, PII redaction, validation, and audit logging.Overview
Message hooks provide 3 execution points:| Hook | Fires | Use Case |
|---|---|---|
on_user | User message received | Input validation, PII filtering, preprocessing |
on_provider | Provider response received | Output filtering, verification, postprocessing |
on_error | Message processing error | Error handling, logging, retry logic |
Hook Registration
Decorator Syntax
Subscribe API
Message Hook Context
Every message hook receives aMessageExecContext with:
Return Value Format
Message hooks that modify content must return a tuple:- Return
(modified_content, True)if content was changed - Return
(original_content, False)if no changes made - Returning only content without boolean will raise error
- Returning
Nonepasses message through unchanged
Execution Flow
On User Message Hook
Fires when user message is received - before sending to provider:On Provider Message Hook
Fires when provider response is received - before adding to context:On Error Hook
Fires when message processing fails:Usage Patterns
Pattern 1: PII Redaction
Remove sensitive information from user messages:Pattern 2: Content Validation
Enforce content policies before processing:Pattern 3: Response Formatting
Standardize provider response formatting:Pattern 4: Audit Logging
Log all message traffic for compliance:Pattern 5: Translation
Translate messages between languages:Pattern 6: Rate Limiting
Implement message rate limiting:Message Types
Message hooks handle different message types:User Messages
Provider Messages
System Messages
Integration with ProviderThread
Message hooks fire before messages enter the ProviderThread:Best Practices
Always return tuple from modification hooks
Always return tuple from modification hooks
Use on_user for input validation, on_provider for output verification
Use on_user for input validation, on_provider for output verification
Log modifications for debugging
Log modifications for debugging
Use agent.state for cross-hook communication
Use agent.state for cross-hook communication
Performance Considerations
- Hook overhead: Less than 2ms per message hook
- Modification impact: Only modified messages incur serialization cost
- Async support: Message hooks can be async functions
- Error handling: Errors in hooks propagate and cancel message processing

