Skip to content

Troubleshooting

Common issues and their solutions.

Installation Issues

Package Not Found

Error:

Package cognesy/instructor-laravel not found

Solution: Ensure you have the correct package name and your Composer is up to date:

composer clear-cache
composer require cognesy/instructor-laravel

Service Provider Not Registered

Error:

Class 'Cognesy\Instructor\Laravel\Facades\StructuredOutput' not found

Solution: If auto-discovery is disabled, manually register the provider:

// config/app.php
'providers' => [
    Cognesy\Instructor\Laravel\InstructorServiceProvider::class,
],

Or clear the cached configuration:

php artisan config:clear
php artisan cache:clear

API Key Issues

API Key Not Configured

Error:

No API key configured for connection 'openai'

Solution: Add your API key to .env:

OPENAI_API_KEY=sk-your-key-here

Then clear config cache:

php artisan config:clear

Invalid API Key

Error:

401 Unauthorized: Invalid API key

Solution: 1. Verify your API key is correct 2. Check the key hasn't expired 3. Ensure the key has the required permissions 4. Verify there are no extra spaces in .env

Rate Limiting

Error:

429 Too Many Requests

Solution: 1. Implement retry logic with exponential backoff 2. Upgrade your API plan for higher limits 3. Add caching to reduce API calls

use Illuminate\Support\Facades\RateLimiter;

if (RateLimiter::tooManyAttempts('llm-calls', 60)) {
    throw new TooManyRequestsException();
}

RateLimiter::hit('llm-calls');

Extraction Issues

Response Does Not Match Model

Error:

Failed to deserialize response to PersonData

Solution: 1. Add more descriptive property comments 2. Provide examples 3. Increase max retries

final class PersonData
{
    public function __construct(
        /** The person's full legal name (first and last) */
        public readonly string $name,

        /** The person's age as a whole number */
        public readonly int $age,
    ) {}
}

$result = StructuredOutput::with(
    messages: $text,
    responseModel: PersonData::class,
    maxRetries: 5,  // Increase retries
    examples: [...], // Add examples
)->get();

Validation Failures

Error:

Validation failed after 3 retries

Solution: 1. Check your validation constraints aren't too strict 2. Review the error messages in logs 3. Adjust the retry prompt

$result = StructuredOutput::with(
    messages: $text,
    responseModel: MyModel::class,
    maxRetries: 5,
    retryPrompt: 'Previous response failed: {errors}. Please fix these specific issues.',
)->get();

Null Values for Required Fields

Problem: LLM returns null for fields you expected to have values.

Solution: 1. Make the input text clearer 2. Add better property descriptions 3. Use system prompts

$result = StructuredOutput::with(
    messages: $text,
    responseModel: MyModel::class,
    system: 'Extract all available information. If a field is not found in the text, make a reasonable inference based on context.',
)->get();

Timeout Issues

Request Timeout

Error:

cURL error 28: Operation timed out

Solution: Increase timeout in configuration:

// config/instructor.php
'http' => [
    'timeout' => 300, // 5 minutes
    'connect_timeout' => 60,
],

Or per-request:

$result = StructuredOutput::withOptions([
    'timeout' => 300,
])->with(...)->get();

Streaming Timeout

Problem: Streaming requests timeout before completion.

Solution:

set_time_limit(0); // Disable PHP timeout

$stream = StructuredOutput::with(...)
    ->withStreaming()
    ->stream();


Testing Issues

Fake Not Working

Problem: Real API calls are made despite using fake().

Solution: Ensure you call fake() BEFORE any extraction:

// CORRECT
$fake = StructuredOutput::fake([...]);
$result = $myService->extract(); // Uses fake

// WRONG
$result = $myService->extract(); // Real API call
$fake = StructuredOutput::fake([...]); // Too late!

Http::fake() Not Mocking

Problem: Http::fake() doesn't affect Instructor calls.

Solution: Ensure the HTTP driver is set to 'laravel':

// config/instructor.php
'http' => [
    'driver' => 'laravel',
],

Performance Issues

Slow Responses

Solutions: 1. Use a faster model (e.g., gpt-4o-mini instead of gpt-4o) 2. Use Groq for faster inference 3. Enable response caching 4. Reduce input size

// Use faster provider
$result = StructuredOutput::using('groq')
    ->with(...)->get();

// Cache responses
$result = Cache::remember($cacheKey, 3600, fn () =>
    StructuredOutput::with(...)->get()
);

High Token Usage

Solutions: 1. Use concise system prompts 2. Truncate long inputs 3. Use smaller context windows

// Truncate long text
$text = Str::limit($longText, 8000);

$result = StructuredOutput::with(
    messages: $text,
    responseModel: MyModel::class,
    system: 'Extract data. Be concise.', // Short prompt
)->get();

Memory Issues

Out of Memory

Error:

Allowed memory size exhausted

Solution: 1. Process in batches 2. Use streaming for large responses 3. Increase PHP memory limit

// Process in chunks
$documents->chunk(10)->each(function ($chunk) {
    foreach ($chunk as $doc) {
        $result = StructuredOutput::with(...)
            ->get();
        // Process and free memory
    }
    gc_collect_cycles();
});

Common Error Messages

Error Cause Solution
Connection refused API unreachable Check network/firewall
Invalid JSON Malformed response Increase retries, simplify model
Model not found Wrong model name Check model name spelling
Quota exceeded API limit reached Upgrade plan or wait
Context length exceeded Input too long Truncate input
Invalid request Malformed request Check request parameters

Getting Help

If you're still stuck:

  1. Check the logs:

    tail -f storage/logs/laravel.log
    

  2. Enable debug logging:

    // config/instructor.php
    'logging' => [
        'enabled' => true,
        'level' => 'debug',
    ],
    

  3. Test the API directly:

    php artisan instructor:test --preset=openai
    

  4. Check GitHub issues: https://github.com/cognesy/instructor-php/issues

  5. Ask for help: Open a new issue with:

  6. PHP version
  7. Laravel version
  8. Package version
  9. Error message
  10. Minimal reproduction code