Skip to main content

Overview

Instructor uses validation to verify if the response generated by LLM meets the requirements of your response model. If the response does not meet the requirements, Instructor will throw an exception. Instructor uses Symfony’s Validator component to validate the response, check their documentation for more information on the usage: https://symfony.com/doc/current/components/validator.html Following example demonstrates how to use Symfony Validator’s constraints to validate the email field of response.

Example

<?php
require 'examples/boot.php';

use Cognesy\Instructor\StructuredOutput;
use Cognesy\Instructor\Validation\Exceptions\ValidationException;
use Symfony\Component\Validator\Constraints as Assert;

class UserDetails
{
    public string $name;
    #[Assert\Email]
    #[Assert\NotBlank]
    /** Find user's email provided in the text or empty if it is missing */
    public ?string $email;
}

$caughtException = false;
$runtimeError = false;
try {
    $user = StructuredOutput::using('openai')
        ->withResponseClass(UserDetails::class)
        ->withMessages([['role' => 'user', 'content' => "you can reply to me via mail -- Jason"]])
        ->get();
} catch (ValidationException $e) {
    $caughtException = true;
    echo "Validation worked.\n";
} catch (Throwable $e) {
    // Provider/runtime failures are not validation behavior and should not fail the example.
    $runtimeError = true;
    echo "Validation failed with unexpected exception: {$e->getMessage()}\n";
}

if ($runtimeError) {
    echo "Skipping strict validation assertions due provider/runtime error.\n";
    return;
}

assert($caughtException === true);
assert(!isset($user));
?>