Skip to main content

Overview

Instructor dispatches events at every significant stage of its execution. You can listen to these events for logging, monitoring, debugging, or custom processing. All event classes extend Cognesy\Events\Event.

Listening to Events

Targeted Listeners

Use onEvent() on the StructuredOutputRuntime to listen for a specific event type:
use Cognesy\Instructor\Events\Response\ResponseValidationFailed;

$runtime = StructuredOutputRuntime::fromDefaults()
    ->onEvent(ResponseValidationFailed::class, function ($event) {
        logger()->warning('Validation failed', $event->toArray());
    });
// @doctest id="5772"

Wiretap (All Events)

Use wiretap() to receive every event dispatched by Instructor. This is useful for debugging or comprehensive logging:
$runtime = StructuredOutputRuntime::fromDefaults()
    ->wiretap(fn($event) => $event->print());
// @doctest id="f2fb"

Practical Example

use Cognesy\Instructor\StructuredOutput;
use Cognesy\Instructor\StructuredOutputRuntime;
use Cognesy\Instructor\Extras\Scalar\Scalar;
use Cognesy\Http\Events\HttpRequestSent;
use Cognesy\Http\Events\HttpResponseReceived;

$runtime = StructuredOutputRuntime::fromDefaults()
    // Log HTTP-level details
    ->onEvent(HttpRequestSent::class, fn($e) => dump($e))
    ->onEvent(HttpResponseReceived::class, fn($e) => dump($e))
    // Console-friendly output for all events
    ->wiretap(fn($event) => $event->print())
    // Structured logging
    ->wiretap(fn($event) => YourLogger::log($event->asLog()));

$result = (new StructuredOutput($runtime))
    ->with(
        messages: 'What is the population of Paris?',
        responseModel: Scalar::integer(),
    )
    ->get();
// @doctest id="bfc2"

Event Categories

Events are organized into namespaces that correspond to the processing stage:

High-Level Events (Events\StructuredOutput)

EventWhen
StructuredOutputStartedA structured output operation begins
StructuredOutputRequestReceivedThe request has been received by the runtime
StructuredOutputResponseGeneratedThe final StructuredOutputResponse has been produced
StructuredOutputResponseUpdatedA streaming partial response is emitted

Request Events (Events\Request)

EventWhen
ResponseModelRequestedA response model has been submitted for processing
ResponseModelBuildModeSelectedThe factory has chosen a build strategy
ResponseModelBuiltThe response model and schema are ready
NewValidationRecoveryAttemptA retry attempt is about to begin
StructuredOutputRecoveryLimitReachedAll retries have been exhausted
SequenceUpdatedA sequence item has been completed during streaming

Response Events (Events\Response)

EventWhen
ResponseDeserializationAttemptDeserialization is about to start
ResponseDeserializedDeserialization succeeded
ResponseDeserializationFailedDeserialization failed
CustomResponseDeserializationAttemptA CanDeserializeSelf implementation is being used
ResponseValidationAttemptValidation is about to start
ResponseValidatedValidation passed
ResponseValidationFailedValidation failed
CustomResponseValidationAttemptA CanValidateSelf implementation is being used
ResponseTransformationAttemptTransformation is about to start
ResponseTransformedTransformation succeeded
ResponseTransformationFailedTransformation failed
ResponseConvertedToObjectThe final object has been produced
ResponseGenerationFailedThe entire response generation pipeline failed

Extraction Events (Events\Extraction)

EventWhen
ExtractionStartedData extraction from the inference response begins
ExtractionCompletedExtraction succeeded
ExtractionFailedExtraction failed
ExtractionStrategyAttemptedA specific extraction strategy is being tried
ExtractionStrategySucceededThe strategy produced a result
ExtractionStrategyFailedThe strategy did not produce a result

Streaming Events (Events\PartialsGenerator)

EventWhen
ChunkReceivedA raw chunk arrived from the provider
StreamedResponseReceivedA streamed response chunk was processed
StreamedResponseFinishedThe stream has ended
PartialJsonReceivedA partial JSON fragment was accumulated
PartialResponseGeneratedA partial deserialized response is available
PartialResponseGenerationFailedPartial deserialization failed (non-fatal)
StreamedToolCallStartedA tool call began in the stream
StreamedToolCallUpdatedA tool call received more data
StreamedToolCallCompletedA tool call finished

Event Methods

Every event inherits the following convenience methods from Cognesy\Events\Event:
MethodDescription
print()Print a console-friendly representation
printLog()Print a log-formatted representation
printDebug()Print console output and dump the full event object
asConsole()Return the event formatted for console output
asLog()Return the event formatted for log output
toArray()Return the event data as an associative array
name()Return the short class name of the event
Events carry a $logLevel property (PSR log level) and a $data payload. The print() method respects a configurable log-level threshold. Instructor event payloads are normalized arrays. Structured-output lifecycle events also expose correlation fields such as requestId, executionId, attemptId, phase, and phaseId where applicable.