PHP code example of gazu1986 / laravel-ai-validator

1. Go to this page and download the library: Download gazu1986/laravel-ai-validator library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

gazu1986 / laravel-ai-validator example snippets


// 😩 The reality of working with AI APIs
$response = $openai->chat($prompt);
$json = json_decode($response, true);

if (json_last_error() !== JSON_ERROR_NONE) {
    // retry? log? throw? strip markdown fences?
}

if (!isset($json['sentiment']) || !in_array($json['sentiment'], ['positive', 'negative'])) {
    // retry with error context? give up?
}

// ... 30 more lines of defensive code

// 😎 With Laravel AI Validator
$result = AiValidator::validate(
    'Analyze the sentiment of this review: "Great product!"',
    new SentimentSchema()
);

$result->dataOrFail(); // Typed, validated data — or throws with full attempt history

use gazu1986\AiValidator\Support\StructuredOutput;

class ProductReviewSchema extends StructuredOutput
{
    public function rules(): array
    {
        return [
            'sentiment'  => [', 'min:1'],
            'pros.*'     => ['string', 'max:100'],
            'cons'       => ['present', 'array'],
            'cons.*'     => ['string', 'max:100'],
        ];
    }
}

use gazu1986\AiValidator\Facades\AiValidator;

$result = AiValidator::validate(
    'Analyze this review: "Amazing laptop, but the keyboard feels cheap"',
    new ProductReviewSchema()
);

if ($result->success) {
    $data = $result->data;
    // ['sentiment' => 'mixed', 'confidence' => 0.85, 'summary' => '...', ...]
}

$result = AiValidator::validateWithRules(
    'Extract the person name and age from: "John is 30 years old"',
    [
        'name' => ['

class ProductReviewSchema extends StructuredOutput
{
    public function rules(): array { /* ... */ }

    public function cast(array $validatedData): ProductReviewDTO
    {
        return new ProductReviewDTO(
            sentiment: Sentiment::from($validatedData['sentiment']),
            confidence: (float) $validatedData['confidence'],
            summary: $validatedData['summary'],
            pros: $validatedData['pros'],
            cons: $validatedData['cons'],
        );
    }
}

// Usage
$result = AiValidator::validate($prompt, new ProductReviewSchema());
$dto = $result->dataOrFail(); // ProductReviewDTO instance — or throws

// Default provider (from config)
AiValidator::validate($prompt, $schema);

// Use Anthropic for this request
AiValidator::using('anthropic')->validate($prompt, $schema);

// Use Ollama for local development
AiValidator::using('ollama')->validate($prompt, $schema);

// Override max attempts per-request
$result = AiValidator::maxAttempts(5)->validate($prompt, $schema);

// Check what happened
$result->attemptCount;   // How many attempts were needed
$result->totalTokens();  // Total tokens consumed across all attempts
$result->attempts;       // Array of AttemptLog objects

$result = AiValidator::validate($prompt, $schema);

if (!$result->success) {
    // What went wrong on the last attempt?
    $lastAttempt = end($result->attempts);
    $lastAttempt->jsonValid;         // Was it valid JSON?
    $lastAttempt->schemaValid;       // Did it pass validation?
    $lastAttempt->validationErrors;  // Laravel validation errors
    $lastAttempt->rawResponse;       // Raw AI response text
}

// Or throw with full context
try {
    $result->dataOrFail();
} catch (ValidationFailedException $e) {
    $e->lastErrors();  // Validation errors from final attempt
    $e->attempts;      // Full attempt history
}

class ContactExtractionSchema extends StructuredOutput
{
    public function rules(): array { /* ... */ }

    public function systemPrompt(): string
    {
        return <<<'PROMPT'
        You are a contact information extractor.
        Extract all people mentioned and their details.
        Respond with ONLY valid JSON matching the 

// config/ai-validator.php

return [
    'default_provider' => env('AI_VALIDATOR_PROVIDER', 'openai'),

    'providers' => [
        'openai' => [
            'api_key' => env('OPENAI_API_KEY'),
            'model' => env('AI_VALIDATOR_OPENAI_MODEL', 'gpt-4o'),
            'temperature' => 0.0,
        ],
        'anthropic' => [
            'api_key' => env('ANTHROPIC_API_KEY'),
            'model' => env('AI_VALIDATOR_ANTHROPIC_MODEL', 'claude-sonnet-4-5-20250929'),
        ],
        'ollama' => [
            'base_url' => env('OLLAMA_BASE_URL', 'http://localhost:11434'),
            'model' => 'llama3',
        ],
    ],

    'retry' => [
        'max_attempts' => 3,
        'backoff_ms' => 500,
        'backoff_multiplier' => 2.0,
    ],

    'cache' => [
        'enabled' => false,
        'ttl' => 3600,
    ],

    'logging' => [
        'enabled' => true,
        'log_prompts' => false,
        'log_responses' => false,
    ],
];

use Illuminate\Support\Facades\Http;

Http::fake([
    'api.openai.com/*' => Http::response([
        'choices' => [[
            'message' => ['content' => '{"name":"John","age":30}'],
            'finish_reason' => 'stop',
        ]],
        'model' => 'gpt-4o',
        'usage' => ['prompt_tokens' => 100, 'completion_tokens' => 50, 'total_tokens' => 150],
    ]),
]);

$result = AiValidator::validateWithRules('Extract info', [
    'name' => ['
bash
php artisan vendor:publish --tag=ai-validator-config
bash
php artisan make:ai-schema ProductReviewSchema