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