This example demonstrates all available agent hooks in VoltAgent, including the new onPrepareMessages hook for message transformation.
onStart- Called when the agent starts processingonPrepareMessages- Called before messages are sent to the LLM (allows transformation)onToolStart- Called when a tool starts executingonToolEnd- Called when a tool finishes executingonEnd- Called when the agent finishes processingonHandoff- Called when an agent hands off to another agent
- Modify messages before they're sent to the LLM
- Add contextual information (timestamps, metadata)
- Filter or transform content
- Simple and practical example
- Track operation start/end times
- Monitor tool execution
- Log conversation and operation IDs
- Error handling and reporting
- Install dependencies:
pnpm install- Set up your OpenAI API key:
export OPENAI_API_KEY="your-api-key"- Run the example:
pnpm devonPrepareMessages: async ({ messages }) => {
// Add timestamps to user messages
const enhanced = messages.map((msg) => {
if (msg.role === "user") {
return {
...msg,
content: `[${new Date().toLocaleTimeString()}] ${msg.content}`,
};
}
return msg;
});
return { messages: enhanced };
};onPrepareMessages: async ({ messages }) => {
// Remove sensitive patterns
const filtered = messages.map((msg) => ({
...msg,
content: msg.content.replace(/password:\s*\S+/gi, "password: [REDACTED]"),
}));
return { messages: filtered };
};onPrepareMessages: async ({ messages, context }) => {
// Log messages for debugging
console.log(`Operation ${context.operationId}: ${messages.length} messages`);
return { messages }; // Return unchanged
};- Hooks are optional - only implement the ones you need
- Hooks can be async or sync
- The
onPrepareMessageshook receives a copy of messages to prevent accidental mutations - Return
{ messages: transformedMessages }fromonPrepareMessagesto use transformed messages - All hooks receive the operation context for tracking and correlation