> ## Documentation Index
> Fetch the complete documentation index at: https://docs.vizra.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Events API Reference

> Become an agent lifecycle ninja. Master every moment of agent execution with comprehensive event hooks. Monitor, debug, extend - turn your agents into observable, intelligent systems.

<Warning>
  **Vizra ADK is in maintenance mode.** It continues to work and receives compatibility fixes, but no new features are planned. For evaluating AI agents — now built on the official [Laravel AI SDK](https://github.com/laravel/ai) — check out [Vizra Evals](/), its successor for the evaluation use-case. Coming from ADK? See the [migration guide](/evals/migrate-from-vizra-adk).
</Warning>

## Event Overview

All class-based events are in the `Vizra\VizraADK\Events` namespace and use Laravel's event system.

```php theme={null}
use Vizra\VizraADK\Events\AgentExecutionStarting;
use Illuminate\Support\Facades\Event;

// Listen to an event
Event::listen(AgentExecutionStarting::class, function (AgentExecutionStarting $event) {
    Log::info('Agent starting', [
        'agent' => $event->agentName,
        'input' => $event->input
    ]);
});
```

## Agent Execution Events

<AccordionGroup>
  <Accordion title="AgentExecutionStarting">
    Fired when an agent begins execution.

    ```php theme={null}
    class AgentExecutionStarting
    {
        public function __construct(
            public AgentContext $context,
            public string $agentName,
            public mixed $input
        ) {}
    }
    ```

    **Properties:**

    | Property | Description |
    | - | - |
    | `$context` | The agent execution context |
    | `$agentName` | Name of the agent being executed |
    | `$input` | Initial input provided to the agent |
  </Accordion>

  <Accordion title="AgentExecutionFinished">
    Fired when an agent completes execution.

    ```php theme={null}
    class AgentExecutionFinished
    {
        public function __construct(
            public AgentContext $context,
            public string $agentName
        ) {}
    }
    ```

    **Properties:**

    | Property | Description |
    | - | - |
    | `$context` | The agent execution context |
    | `$agentName` | Name of the agent that finished |
  </Accordion>

  <Accordion title="AgentResponseGenerated">
    Fired when an agent generates its final response.

    ```php theme={null}
    class AgentResponseGenerated
    {
        public function __construct(
            public AgentContext $context,
            public string $agentName,
            public mixed $finalResponse
        ) {}
    }
    ```

    **Properties:**

    | Property | Description |
    | - | - |
    | `$context` | The agent execution context |
    | `$agentName` | Name of the agent |
    | `$finalResponse` | The final response generated by the agent |
  </Accordion>
</AccordionGroup>

## LLM Interaction Events

<AccordionGroup>
  <Accordion title="LlmCallInitiating">
    Fired before making a call to the LLM.

    ```php theme={null}
    class LlmCallInitiating
    {
        public function __construct(
            public AgentContext $context,
            public string $agentName,
            public array $promptMessages
        ) {}
    }
    ```

    **Properties:**

    | Property | Description |
    | - | - |
    | `$context` | The agent execution context |
    | `$agentName` | Name of the agent making the call |
    | `$promptMessages` | Array of messages being sent to the LLM |
  </Accordion>

  <Accordion title="LlmResponseReceived">
    Fired after receiving a response from the LLM.

    ```php theme={null}
    class LlmResponseReceived
    {
        public function __construct(
            public AgentContext $context,
            public string $agentName,
            public mixed $llmResponse,
            public ?PendingRequest $request = null
        ) {}
    }
    ```

    **Properties:**

    | Property | Description |
    | - | - |
    | `$context` | The agent execution context |
    | `$agentName` | Name of the agent |
    | `$llmResponse` | The response from the LLM |
    | `$request` | The Prism request object (optional) |
  </Accordion>

  <Accordion title="LlmCallFailed">
    Fired when an LLM API call fails.

    ```php theme={null}
    class LlmCallFailed
    {
        public function __construct(
            public AgentContext $context,
            public string $agentName,
            public Throwable $exception,
            public ?PendingRequest $request = null
        ) {}
    }
    ```

    **Properties:**

    | Property | Description |
    | - | - |
    | `$context` | The agent execution context |
    | `$agentName` | Name of the agent |
    | `$exception` | The exception that caused the failure |
    | `$request` | The failed request details (optional) |
  </Accordion>
</AccordionGroup>

## Tool Execution Events

<AccordionGroup>
  <Accordion title="ToolCallInitiating">
    Fired before executing a tool.

    ```php theme={null}
    class ToolCallInitiating
    {
        public function __construct(
            public AgentContext $context,
            public string $agentName,
            public string $toolName,
            public array $arguments
        ) {}
    }
    ```

    **Properties:**

    | Property | Description |
    | - | - |
    | `$context` | The agent execution context |
    | `$agentName` | Name of the agent executing the tool |
    | `$toolName` | Name of the tool being called |
    | `$arguments` | Arguments passed to the tool |
  </Accordion>

  <Accordion title="ToolCallCompleted">
    Fired after a tool completes execution.

    ```php theme={null}
    class ToolCallCompleted
    {
        public function __construct(
            public AgentContext $context,
            public string $agentName,
            public string $toolName,
            public string $result // JSON string
        ) {}
    }
    ```

    **Properties:**

    | Property | Description |
    | - | - |
    | `$context` | The agent execution context |
    | `$agentName` | Name of the agent |
    | `$toolName` | Name of the tool that completed |
    | `$result` | JSON-encoded result from the tool |
  </Accordion>

  <Accordion title="ToolCallFailed">
    Fired when a tool call encounters an error.

    ```php theme={null}
    class ToolCallFailed
    {
        public function __construct(
            public AgentContext $context,
            public string $agentName,
            public string $toolName,
            public Throwable $exception
        ) {}
    }
    ```

    **Properties:**

    | Property | Description |
    | - | - |
    | `$context` | The agent execution context |
    | `$agentName` | Name of the agent |
    | `$toolName` | Name of the tool that failed |
    | `$exception` | The exception that caused the failure |
  </Accordion>
</AccordionGroup>

## State Management Events

<AccordionGroup>
  <Accordion title="StateUpdated">
    Fired when agent state is updated.

    ```php theme={null}
    class StateUpdated
    {
        public function __construct(
            public AgentContext $context,
            public string $key,
            public mixed $value
        ) {}
    }
    ```

    **Properties:**

    | Property | Description |
    | - | - |
    | `$context` | The agent execution context |
    | `$key` | The state key that was updated |
    | `$value` | The new value |
  </Accordion>

  <Accordion title="MemoryUpdated">
    Fired when agent memory is updated.

    ```php theme={null}
    class MemoryUpdated
    {
        public function __construct(
            public AgentMemory $memory,
            public ?AgentSession $session,
            public string $updateType
        ) {}
    }
    ```

    **Properties:**

    | Property | Description |
    | - | - |
    | `$memory` | The agent memory instance |
    | `$session` | The associated session (optional) |
    | `$updateType` | Type of update performed |

    **Update Types:**

    | Type | Description |
    | - | - |
    | `'session_completed'` | Session summary extracted |
    | `'learning_added'` | New learning stored |
    | `'fact_added'` | New fact stored |
  </Accordion>
</AccordionGroup>

## Multi-Agent Events

<AccordionGroup>
  <Accordion title="TaskDelegated">
    Fired when an agent delegates a task to a sub-agent.

    ```php theme={null}
    class TaskDelegated
    {
        public function __construct(
            public AgentContext $parentContext,
            public AgentContext $subAgentContext,
            public string $parentAgentName,
            public string $subAgentName,
            public string $taskInput,
            public string $contextSummary,
            public int $delegationDepth
        ) {}
    }
    ```

    **Properties:**

    | Property | Description |
    | - | - |
    | `$parentContext` | Context of the delegating agent |
    | `$subAgentContext` | Context for the sub-agent |
    | `$parentAgentName` | Name of the parent agent |
    | `$subAgentName` | Name of the sub-agent receiving the task |
    | `$taskInput` | The task being delegated |
    | `$contextSummary` | Summary of context passed to sub-agent |
    | `$delegationDepth` | Current depth of delegation chain |
  </Accordion>
</AccordionGroup>

## Media Generation Events

These are string-based events fired by `MediaGenerationJob` when processing queued media generation tasks (images, audio, etc.).

```php theme={null}
use Illuminate\Support\Facades\Event;

// Listen to media events
Event::listen('media.job.completed', function (array $payload) {
    Log::info('Media job completed', [
        'job_id' => $payload['job_id'],
        'agent' => $payload['agent_class'],
    ]);
});
```

<AccordionGroup>
  <Accordion title="media.job.completed">
    Fired when any media generation job completes successfully.

    ```php theme={null}
    event('media.job.completed', [
        'job_id' => $jobId,
        'agent_class' => $agentClass,
        'response' => $response,  // ImageResponse or AudioResponse
    ]);
    ```

    **Payload:**

    | Key | Type | Description |
    | - | - | - |
    | `job_id` | `string` | Unique identifier for the job |
    | `agent_class` | `string` | Fully qualified class name of the media agent |
    | `response` | `ImageResponse\|AudioResponse` | The generated media response object |

    **Example:**

    ```php theme={null}
    Event::listen('media.job.completed', function (array $payload) {
        $url = $payload['response']->url();

        // Notify user that their image is ready
        Notification::send($user, new MediaReadyNotification($url));
    });
    ```
  </Accordion>

  <Accordion title="media.{agent_name}.completed">
    Fired when a specific agent's media job completes. The event name includes the agent's name (e.g., `media.image_agent.completed`).

    ```php theme={null}
    event("media.{$agentName}.completed", [
        'job_id' => $jobId,
        'response' => $response,
        'session_id' => $sessionId,
    ]);
    ```

    **Payload:**

    | Key | Type | Description |
    | - | - | - |
    | `job_id` | `string` | Unique identifier for the job |
    | `response` | `ImageResponse\|AudioResponse` | The generated media response object |
    | `session_id` | `string` | Session ID associated with the job |

    **Example:**

    ```php theme={null}
    // Listen specifically for image agent completions
    Event::listen('media.image_agent.completed', function (array $payload) {
        $sessionId = $payload['session_id'];
        $imageUrl = $payload['response']->url();

        // Update the session with the generated image
        broadcast(new ImageGeneratedEvent($sessionId, $imageUrl));
    });

    // Listen for audio agent completions
    Event::listen('media.audio_agent.completed', function (array $payload) {
        // Handle audio-specific logic
    });
    ```
  </Accordion>

  <Accordion title="media.job.failed">
    Fired when a media generation job fails after all retry attempts.

    ```php theme={null}
    event('media.job.failed', [
        'job_id' => $jobId,
        'agent_class' => $agentClass,
        'error' => $exception->getMessage(),
    ]);
    ```

    **Payload:**

    | Key | Type | Description |
    | - | - | - |
    | `job_id` | `string` | Unique identifier for the failed job |
    | `agent_class` | `string` | Fully qualified class name of the media agent |
    | `error` | `string` | Error message describing the failure |

    **Example:**

    ```php theme={null}
    Event::listen('media.job.failed', function (array $payload) {
        Log::error('Media generation failed', [
            'job_id' => $payload['job_id'],
            'agent' => $payload['agent_class'],
            'error' => $payload['error'],
        ]);

        // Notify user of failure
        Notification::send($user, new MediaFailedNotification($payload['error']));
    });
    ```
  </Accordion>
</AccordionGroup>

## Usage Examples

### Monitoring Agent Performance

```php theme={null}
use Vizra\VizraADK\Events\{AgentExecutionStarting, AgentExecutionFinished};
use Illuminate\Support\Facades\Event;

class AgentPerformanceMonitor
{
    private array $startTimes = [];

    public function register(): void
    {
        Event::listen(AgentExecutionStarting::class, [$this, 'handleStart']);
        Event::listen(AgentExecutionFinished::class, [$this, 'handleFinish']);
    }

    public function handleStart(AgentExecutionStarting $event): void
    {
        $this->startTimes[$event->context->getSessionId()] = microtime(true);
    }

    public function handleFinish(AgentExecutionFinished $event): void
    {
        $sessionId = $event->context->getSessionId();
        $duration = microtime(true) - $this->startTimes[$sessionId];

        Log::info('Agent execution completed', [
            'agent' => $event->agentName,
            'duration' => round($duration, 2) . 's'
        ]);
    }
}
```

### Debugging Tool Calls

```php theme={null}
Event::listen(ToolCallInitiating::class, function (ToolCallInitiating $event) {
    Log::debug('Tool call starting', [
        'tool' => $event->toolName,
        'arguments' => $event->arguments,
        'session' => $event->context->getSessionId()
    ]);
});

Event::listen(ToolCallCompleted::class, function (ToolCallCompleted $event) {
    $result = json_decode($event->result, true);
    Log::debug('Tool call completed', [
        'tool' => $event->toolName,
        'success' => $result['success'] ?? false
    ]);
});
```

### Memory Tracking

```php theme={null}
Event::listen(MemoryUpdated::class, function (MemoryUpdated $event) {
    switch ($event->updateType) {
        case 'learning_added':
            Log::info('New learning stored', [
                'agent' => $event->memory->agent_name,
                'learning' => $event->memory->learnings->last()
            ]);
            break;

        case 'fact_added':
            Log::info('New fact stored', [
                'agent' => $event->memory->agent_name,
                'fact' => $event->memory->facts->last()
            ]);
            break;
    }
});
```

<Note>
  **Event Best Practices:**

  * Use event listeners for cross-cutting concerns like logging and monitoring
  * Keep event handlers lightweight to avoid impacting agent performance
  * Use queued listeners for heavy processing tasks
  * Events are synchronous by default - be mindful of execution time
  * All class-based events include the AgentContext for accessing session state
  * Tool results are JSON strings - decode them for processing
  * Media events are string-based and receive array payloads
</Note>

## Next Steps

<CardGroup cols={2}>
  <Card title="Agent Lifecycle" icon="rotate" href="/concepts/agents">
    Learn about the agent execution flow
  </Card>

  <Card title="API Reference" icon="book" href="/api-reference">
    View all API references
  </Card>
</CardGroup>


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.