Listen to AI Agent Events
The AI Agent provider emits events that you can subscribe to in order to respond to changes in the agent's state or behavior. These events allow you to build reactive UIs and implement custom logic.
Available events
Event | Description | Parameters |
---|---|---|
stateChange | Triggered when the provider state changes | (newState, previousState, context) |
loadingError | Triggered when an error occurs during loading | (error, context) |
beforeToolCall | Triggered before a tool call is executed | (toolCall, context) |
afterToolCall | Triggered after a tool call is executed | (toolCall, context) |
runFinished | Triggered when an AI Agent run is completed | (context) |
Subscribing to events
There are two ways to subscribe to events. When you initialize the provider, you can pass event handlers as options.
const provider = new AiAgentProvider({
onStateChange: (newState, previousState, context) => {
console.log('State changed:', newState)
// Update UI based on new state
},
onLoadingError: (error, context) => {
console.error('Loading error:', error)
// Show error message to the user
},
})
Or you can subscribe to events using the on
method and unsubscribe using the off
method.
// Define event handlers
const handleStateChange = (newState, previousState, context) => {
console.log('State changed:', newState)
// Update UI based on new state
}
// Subscribe to events
provider.on('stateChange', handleStateChange)
// Later, unsubscribe when no longer needed
provider.off('stateChange', handleStateChange)