PHP code example of serhiilabs / laravel-ai-validator

1. Go to this page and download the library: Download serhiilabs/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/ */

    

serhiilabs / laravel-ai-validator example snippets


use SerhiiLabs\AiValidator\AiRule;

$request->validate([
    'bio'    => ['speech or personal attacks')],
    'city'   => ['

'driver' => \SerhiiLabs\AiValidator\Drivers\PrismDriver::class,

use SerhiiLabs\AiValidator\AiRule;

$validator = Validator::make($data, [
    'company_name' => ['

use SerhiiLabs\AiValidator\AiRule;

class StoreProfileRequest extends FormRequest
{
    public function rules(): array
    {
        return [
            'bio'      => ['tral sentiment, no complaints or insults')],
        ];
    }
}

'presets' => [
    'profanity-free' => 'No profanity, slurs, vulgar language, or sexually explicit content.',
    'no-pii' => 'No emails, phone numbers, SSNs, credit cards, or physical addresses.',
    'professional-tone' => 'Professional tone. No slang, aggression, or inappropriate humor.',
    'no-spam' => 'No spam, keyword stuffing, repetitive gibberish, or promotional content.',
    'bio-check' => 'Must be a professional biography, 1-3 sentences.',
],

AiRule::preset('profanity-free');
AiRule::preset('bio-check')
    ->timeout(30)
    ->errorMessage('Please write a short professional bio.');

AiRule::make('professional biography, 1-3 sentences')
    ->errorMessage('Please write a short professional bio.')

AiRule::make('appropriate content')
    ->using('anthropic', 'claude-haiku-4-5-20251001')

AiRule::make('appropriate content')->timeout(30)

use Closure;
use SerhiiLabs\AiValidator\Contracts\RuleOptionInterface;
use SerhiiLabs\AiValidator\ValueObjects\ValidationContext;
use SerhiiLabs\AiValidator\ValueObjects\ValidationResult;

final readonly class LogValidation implements RuleOptionInterface
{
    public function handle(ValidationContext $ctx, Closure $next): ValidationResult
    {
        $result = $next($ctx);

        Log::info('AI validation', [
            'attribute' => $ctx->attribute,
            'passed' => $result->passed,
        ]);

        return $result;
    }
}

AiRule::make('professional bio')
    ->with(new LogValidation)

use SerhiiLabs\AiValidator\AiRule;
use SerhiiLabs\Inscribe\Facades\Inscribe;

$description = Inscribe::make()
    ->separator("\n")
    ->include('validation.rules.no-spam')
    ->include('validation.rules.no-profanity')
    ->include('validation.bio', [
        'role' => $request->role,
        'industry' => $request->industry,
    ])
    ->build();

$request->validate([
    'bio' => ['

use SerhiiLabs\AiValidator\Contracts\DriverInterface;
use SerhiiLabs\AiValidator\ValueObjects\DriverRequest;
use SerhiiLabs\AiValidator\ValueObjects\DriverResponse;

final class MyDriver implements DriverInterface
{
    public function __construct(
        private string $defaultProvider = 'openai',
        private string $defaultModel = 'gpt-4o-mini',
        private int $defaultTimeout = 15,
    ) {}

    public function send(DriverRequest $request): DriverResponse
    {
        // $request->systemPrompt - system instructions (string)
        // $request->userPrompt   - the validation prompt (string)
        // $request->provider     - provider override (?string, null = use default)
        // $request->model        - model override (?string, null = use default)
        // $request->timeout      - timeout override (?int, null = use default)

        $provider = $request->provider ?? $this->defaultProvider;
        $model = $request->model ?? $this->defaultModel;
        $timeout = $request->timeout ?? $this->defaultTimeout;

        // Call your AI API here...

        return new DriverResponse(
            passed: $result['passed'],
            explanation: $result['explanation'],
        );
    }
}

// config/ai-validator.php
'driver' => \App\Ai\MyDriver::class,

$this->app->singleton(DriverInterface::class, MyDriver::class);

use SerhiiLabs\AiValidator\Contracts\ResultCacheInterface;

$this->app->singleton(ResultCacheInterface::class, MyCacheAdapter::class);

use SerhiiLabs\AiValidator\Exceptions\DriverException;
use SerhiiLabs\AiValidator\Exceptions\RateLimitExceededException;

try {
    $result = $aiValidator->validate($ctx);
} catch (RateLimitExceededException $e) {
    // Rate limit hit - $e->getMessage() 

// Custom TTL (seconds)
AiRule::make('not spam')->cacheTtl(1800)

// Disable cache for this rule
AiRule::make('constructive feedback')->withoutCache()

// Disable rate limit for critical validation
AiRule::make('fraud check')->withoutRateLimit()

final readonly class PerUserRateLimit implements RuleOptionInterface
{
    public function handle(ValidationContext $ctx, Closure $next): ValidationResult
    {
        $key = 'ai_validator:' . auth()->id();

        if (! RateLimiter::attempt($key, 10, fn () => null, 60)) {
            throw new RateLimitExceededException('Too many requests.');
        }

        return $next($ctx);
    }
}

// Usage: AiRule::make('real company name')->with(new PerUserRateLimit)

use SerhiiLabs\AiValidator\Exceptions\RateLimitExceededException;

use SerhiiLabs\AiValidator\Testing\AiValidatorFake;

// All AI rules pass
AiValidatorFake::pass();

// All AI rules fail with a message
AiValidatorFake::fail('Not a real company.');

// Clean up after test
AiValidatorFake::reset();

afterEach(fn () => AiValidatorFake::reset());

use SerhiiLabs\AiValidator\ValueObjects\ValidationResult;

$fake = AiValidatorFake::pass();
$fake->expectDescription('not spam', ValidationResult::failed('Looks like spam.'));

// Rules matching "not spam" will fail, everything else passes

$fake = AiValidatorFake::pass();

// ... run your code ...

$fake->assertCalledTimes(2);
$fake->assertCalledWithDescription('real company name');
$fake->assertCalledWithValue('Acme Corp');
$fake->assertNotCalled();

// Access raw call log for custom assertions
$fake->callLog(); // [['value' => ..., 'description' => ..., 'attribute' => ..., 'options' => [...]], ...]
bash
composer 
bash
php artisan vendor:publish --tag=ai-validator-config
bash
php artisan vendor:publish --tag=prism-config