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
$loader = require 'vendor/autoload.php';
$loader->add('Cognesy\\Instructor\\', __DIR__.'../../src/');
use Cognesy\Instructor\Instructor;
use Symfony\Component\Validator\Constraints as Assert;
class UserDetails
{
public string $name;
#[Assert\Email]
#[Assert\NotBlank]
public string $email;
}
$caughtException = false;
try {
$user = (new Instructor)->request(
messages: [['role' => 'user', 'content' => "you can reply to me via mail -- Jason"]],
responseModel: UserDetails::class,
)->get();
dump($user);
} catch(Exception $e) {
$caughtException = true;
}
assert(!isset($user));
assert($caughtException === true);
?>