LarAgent provides a comprehensive hook system that allows you to intercept and customize behavior at various stages of the agentβs lifecycle and conversation flow.Documentation Index
Fetch the complete documentation index at: https://docs.laragent.ai/llms.txt
Use this file to discover all available pages before exploring further.
LarAgent also dispatches Laravel events for all hook points, providing more flexibility for cross-cutting concerns like logging and analytics. See the Event Setup Guide and Agent Events for details.
Lifecycle Hooks
Lifecycle hooks focus on the agentβs initialization, conversation flow, and termination. They are perfect for setting up agent-specific configurations, handling conversation state, and managing cleanup operations.onInitialize
Called when the agent is fully initialized. Use this to set up initial state or configurations.onConversationStart
Triggered at the beginning of eachrespond method call. Use this to prepare conversation-specific resources or logging.
onConversationEnd
Called at the end of eachrespond method. For streaming, it runs when the last chunk is received.
onToolChange
Triggered when a tool is added to or removed from the agent.onClear
Triggered before the agentβs chat history is cleared.onTerminate
Called when the agent is being terminated. Ideal for final cleanup or saving state.onEngineError
Called when the provider fails to process a request, before trying the fallback provider.Engine Hooks
Engine hooks provide fine-grained control over the conversation processing pipeline, allowing you to intercept and modify behavior at crucial points.Each engine hook returns a boolean value where
true allows the operation to proceed and false prevents it. Prefer throwing exceptions with clear messages instead of returning false, since returning false silently stops execution.beforeReinjectingInstructions
Called before the engine reinjects system instructions into the chat history.Instructions are always injected at the beginning of the chat history. The
$reinjectInstructionsPer property defines when to reinject instructions again. By default, it is set to 0 (disabled).beforeSend & afterSend
Called before and after a message is added to the chat history.beforeSaveHistory
Triggered before the chat history is saved.beforeResponse & afterResponse
Called before sending a message to the LLM and after receiving its response.beforeToolExecution & afterToolExecution
Triggered before and after a tool is executed.beforeStructuredOutput
Called before processing structured output.Best Practices
Keep hooks focused
Each hook - single responsibility.
Use exceptions for errors
Throw exceptions with clear messages instead of silently returning
false.Consider performance
Avoid heavy processing in hooks that run frequently.
Handle references carefully
When modifying referenced parameters (like
&$result), understand the implications.
