Skip to content

Troubleshooting

Rumen Damyanov edited this page Jul 31, 2025 · 2 revisions

Troubleshooting

Common issues, solutions, and debugging techniques.

Table of Contents

Troubleshooting

Common issues, solutions, and debugging techniques.

Table of Contents

Common Issues

"Class 'RumenX\PhpChatbot\PhpChatbot' not found"

Symptom: Fatal error when trying to use the PhpChatbot class.

Causes & Solutions:

  1. Composer autoloader not included:

    // Make sure this is at the top of your file
    require_once 'vendor/autoload.php';
  2. Package not installed properly:

    composer install
    # or if already installed
    composer dump-autoload
  3. Wrong namespace used:

    // Correct:
    use RumenX\PhpChatbot\PhpChatbot;
    
    // Wrong:
    use PhpChatbot\PhpChatbot;

"Invalid API key" or "Authentication failed"

Symptom: 401 Unauthorized or authentication errors from AI providers.

Solution:

// Check your API key configuration
$chatbot = new PhpChatbot([
    'model' => 'openai',
    'api_key' => 'sk-your-actual-key-here', // Verify this is correct
]);

// For environment variables:
$chatbot = new PhpChatbot([
    'model' => 'openai',
    'api_key' => $_ENV['OPENAI_API_KEY'], // Check .env file
]);

Debug steps:

  1. Verify API key format (starts with sk- for OpenAI)
  2. Check API key has not expired
  3. Ensure sufficient credits/quota
  4. Test with a simple API call outside php-chatbot

"Connection timeout" or "Request failed"

Symptom: Network-related errors when contacting AI providers.

Solutions:

  1. Increase timeout:

    $chatbot = new PhpChatbot([
        'model' => 'openai',
        'api_key' => 'your-key',
        'timeout' => 60, // Increase from default 30 seconds
    ]);
  2. Check network connectivity:

    # Test connection to OpenAI
    curl -I https://api.openai.com
    
    # Test connection to Anthropic
    curl -I https://api.anthropic.com
  3. Proxy configuration:

    $chatbot = new PhpChatbot([
        'model' => 'openai',
        'api_key' => 'your-key',
        'proxy' => 'http://proxy.company.com:8080',
    ]);

"Token limit exceeded" errors

Symptom: Messages failing with token-related errors.

Solution:

$chatbot = new PhpChatbot([
    'model' => 'openai',
    'api_key' => 'your-key',
    'max_tokens' => 100, // Reduce if hitting limits
    'temperature' => 0.7,
]);

// For long conversations, manage context:
$conversation = [
    // Keep only last N messages to stay under token limits
    ...array_slice($fullConversation, -10)
];

"Model not found" or "Invalid model"

Symptom: Errors about unavailable models.

Solution:

// Check available models for each provider:

// OpenAI models (as of 2024)
$validModels = ['gpt-4', 'gpt-4-turbo', 'gpt-3.5-turbo'];

// Anthropic models
$validModels = ['claude-3-opus-20240229', 'claude-3-sonnet-20240229', 'claude-3-haiku-20240307'];

// Use a valid model:
$chatbot = new PhpChatbot([
    'model' => 'openai',
    'api_key' => 'your-key',
    'model_name' => 'gpt-4', // Specify exact model
]);

Installation Problems

Composer Installation Fails

Issue: composer require rumenx/php-chatbot fails with dependency conflicts.

Solutions:

  1. Update Composer:

    composer self-update
  2. Clear Composer cache:

    composer clear-cache
    composer install
  3. Check PHP version requirements:

    php --version  # Should be 8.1+
    composer show --platform
  4. Resolve dependency conflicts:

    # Check what's conflicting
    composer why-not rumenx/php-chatbot
    
    # Update dependencies
    composer update
    
    # Force installation (use carefully)
    composer require rumenx/php-chatbot --ignore-platform-reqs

Extension Requirements Missing

Issue: Missing PHP extensions required by dependencies.

Common missing extensions:

# Install missing extensions (Ubuntu/Debian)
sudo apt-get install php-curl php-json php-mbstring

# Install missing extensions (CentOS/RHEL)
sudo yum install php-curl php-json php-mbstring

# Install missing extensions (macOS with Homebrew)
brew install php

Check installed extensions:

php -m | grep -E "(curl|json|mbstring)"

Memory Limit Issues

Issue: PHP memory exhausted during installation or runtime.

Solutions:

  1. Increase memory limit:

    # For Composer installation
    php -d memory_limit=512M composer require rumenx/php-chatbot
    
    # In php.ini
    memory_limit = 512M
  2. For runtime:

    ini_set('memory_limit', '512M');

Configuration Errors

Environment Variables Not Loading

Issue: API keys or config values not being read from .env files.

Solutions:

  1. Check .env file location and format:

    # .env should be in project root
    OPENAI_API_KEY=sk-your-key-here
    ANTHROPIC_API_KEY=your-anthropic-key
    
    # No spaces around = sign
    # No quotes unless needed
  2. Load environment variables:

    // Using vlucas/phpdotenv
    $dotenv = Dotenv\Dotenv::createImmutable(__DIR__);
    $dotenv->load();
    
    // Access variables
    $apiKey = $_ENV['OPENAI_API_KEY'];
  3. Framework-specific loading:

    // Laravel
    $apiKey = config('services.openai.key');
    
    // Symfony
    $apiKey = $this->getParameter('openai.api_key');

Invalid Configuration Format

Issue: Configuration not being recognized or causing errors.

Correct configuration examples:

// Minimal configuration
$chatbot = new PhpChatbot([
    'model' => 'openai',
    'api_key' => 'your-key',
]);

// Full configuration
$chatbot = new PhpChatbot([
    'model' => 'openai',
    'api_key' => 'your-key',
    'temperature' => 0.7,
    'max_tokens' => 150,
    'timeout' => 30,
    'model_name' => 'gpt-4',
]);

// Multiple models
$config = [
    'openai' => [
        'api_key' => 'sk-...',
        'model_name' => 'gpt-4',
        'temperature' => 0.7,
    ],
    'anthropic' => [
        'api_key' => 'your-anthropic-key',
        'model_name' => 'claude-3-sonnet-20240229',
        'temperature' => 0.7,
    ],
];

Framework Integration Issues

Laravel Integration Problems:

// 1. Publish config file
php artisan vendor:publish --provider="RumenX\PhpChatbot\Laravel\PhpChatbotServiceProvider"

// 2. Check config/chatbot.php exists and is properly formatted

// 3. Clear config cache
php artisan config:clear
php artisan config:cache

// 4. Check service provider is registered
// config/app.php
'providers' => [
    // ...
    RumenX\PhpChatbot\Laravel\PhpChatbotServiceProvider::class,
],

Symfony Integration Problems:

# config/packages/php_chatbot.yaml
php_chatbot:
    default_model: 'openai'
    models:
        openai:
            api_key: '%env(OPENAI_API_KEY)%'
            model_name: 'gpt-4'
            temperature: 0.7

API Connection Issues

SSL/TLS Certificate Problems

Issue: SSL verification failures when connecting to APIs.

Solutions:

  1. Update CA certificates:

    # Ubuntu/Debian
    sudo apt-get update && sudo apt-get install ca-certificates
    
    # CentOS/RHEL
    sudo yum update ca-certificates
  2. Configure SSL context:

    $chatbot = new PhpChatbot([
        'model' => 'openai',
        'api_key' => 'your-key',
        'ssl_verify' => true, // or false for testing only
        'ssl_cafile' => '/path/to/cacert.pem',
    ]);
  3. Download latest certificates:

    # Download latest cacert.pem
    curl -o cacert.pem https://curl.haxx.se/ca/cacert.pem

Rate Limiting Issues

Issue: Getting rate-limited by API providers.

Solutions:

  1. Implement exponential backoff:

    function sendWithRetry($chatbot, $message, $maxRetries = 3) {
        for ($i = 0; $i < $maxRetries; $i++) {
            try {
                return $chatbot->sendMessage($message);
            } catch (RateLimitException $e) {
                if ($i === $maxRetries - 1) throw $e;
                
                $delay = pow(2, $i); // Exponential backoff
                sleep($delay);
            }
        }
    }
  2. Use queue system:

    // Laravel Queue example
    class ProcessChatMessage implements ShouldQueue
    {
        public $backoff = [1, 5, 10]; // Retry delays
        public $tries = 3;
        
        public function handle()
        {
            // Process message
        }
    }

API Response Format Changes

Issue: Unexpected response format from AI providers.

Debug response format:

try {
    $response = $chatbot->sendMessage('Hello');
    error_log('API Response: ' . print_r($response, true));
} catch (Exception $e) {
    error_log('API Error: ' . $e->getMessage());
    error_log('Response body: ' . $e->getResponseBody());
}

Handle different response formats:

$chatbot = new PhpChatbot([
    'model' => 'openai',
    'api_key' => 'your-key',
    'response_format' => 'auto', // Let library handle format detection
]);

Frontend Problems

CORS Issues

Issue: Cross-origin requests blocked in browser.

Solutions:

  1. Configure CORS headers (PHP):

    // Add to your chatbot endpoint
    header('Access-Control-Allow-Origin: *');
    header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
    header('Access-Control-Allow-Headers: Content-Type, Authorization');
    
    if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
        http_response_code(200);
        exit;
    }
  2. Laravel CORS:

    composer require fruitcake/laravel-cors
    php artisan vendor:publish --tag="cors"
  3. Use proxy in development:

    // React/Vue development proxy
    // package.json
    {
      "proxy": "http://localhost:8000"
    }

JavaScript Integration Issues

Issue: Frontend not receiving proper responses.

Debug JavaScript requests:

async function sendMessage(message) {
    try {
        const response = await fetch('/api/chatbot/message', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
            },
            body: JSON.stringify({ message })
        });
        
        if (!response.ok) {
            console.error('HTTP Error:', response.status, response.statusText);
            const errorText = await response.text();
            console.error('Error Body:', errorText);
            throw new Error(`HTTP ${response.status}: ${response.statusText}`);
        }
        
        const data = await response.json();
        console.log('Success:', data);
        return data;
        
    } catch (error) {
        console.error('Request failed:', error);
        throw error;
    }
}

Styling and Display Issues

Common CSS fixes:

/* Chat container */
.chatbot-container {
    max-height: 400px;
    overflow-y: auto;
    border: 1px solid #ddd;
    border-radius: 8px;
    padding: 1rem;
}

/* Message bubbles */
.message {
    margin-bottom: 1rem;
    padding: 0.5rem 1rem;
    border-radius: 1rem;
    max-width: 80%;
}

.message.user {
    background-color: #007bff;
    color: white;
    margin-left: auto;
    text-align: right;
}

.message.assistant {
    background-color: #f1f1f1;
    color: #333;
}

/* Responsive design */
@media (max-width: 768px) {
    .chatbot-container {
        max-height: 300px;
    }
    
    .message {
        max-width: 90%;
    }
}

Performance Issues

Slow Response Times

Issue: Chatbot responses taking too long.

Solutions:

  1. Optimize API requests:

    $chatbot = new PhpChatbot([
        'model' => 'openai',
        'api_key' => 'your-key',
        'max_tokens' => 100, // Reduce for faster responses
        'temperature' => 0.7,
        'timeout' => 15,     // Reduce timeout
    ]);
  2. Implement caching:

    $cacheKey = md5($message);
    
    if ($cached = cache()->get($cacheKey)) {
        return $cached;
    }
    
    $response = $chatbot->sendMessage($message);
    cache()->put($cacheKey, $response, 3600); // Cache for 1 hour
    
    return $response;
  3. Use queues for async processing:

    // Queue the message processing
    ProcessChatMessage::dispatch($message, $userId);
    
    // Return immediate response
    return response()->json([
        'status' => 'processing',
        'message' => 'Your message is being processed...'
    ]);

Memory Usage Issues

Issue: High memory consumption with large conversations.

Solutions:

  1. Limit conversation history:

    function limitConversationHistory($conversation, $maxMessages = 20) {
        if (count($conversation) > $maxMessages) {
            // Keep first message (system prompt) and last N messages
            return array_merge(
                [$conversation[0]], // System message
                array_slice($conversation, -($maxMessages - 1))
            );
        }
        return $conversation;
    }
  2. Use streaming responses:

    $chatbot = new PhpChatbot([
        'model' => 'openai',
        'api_key' => 'your-key',
        'stream' => true, // Enable streaming
    ]);
  3. Clear variables:

    // Clear large variables when done
    unset($largeConversationArray);
    gc_collect_cycles(); // Force garbage collection

Database Performance

Issue: Slow database queries for conversation storage.

Optimization strategies:

-- Add indexes for common queries
CREATE INDEX idx_conversations_user_updated ON conversations(user_id, updated_at);
CREATE INDEX idx_messages_conversation_created ON messages(conversation_id, created_at);

-- Archive old conversations
CREATE TABLE conversations_archive AS 
SELECT * FROM conversations 
WHERE updated_at < DATE_SUB(NOW(), INTERVAL 6 MONTH);

DELETE FROM conversations 
WHERE updated_at < DATE_SUB(NOW(), INTERVAL 6 MONTH);

Debugging Tips

Enable Debug Mode

Enable verbose logging:

$chatbot = new PhpChatbot([
    'model' => 'openai',
    'api_key' => 'your-key',
    'debug' => true, // Enable debug mode
]);

// Laravel debug
config(['app.debug' => true]);
config(['logging.default' => 'daily']);

Log API Requests and Responses

class DebugChatbot extends PhpChatbot 
{
    public function sendMessage($message, $conversation = []) 
    {
        $startTime = microtime(true);
        
        error_log("Chatbot Request: " . json_encode([
            'message' => $message,
            'conversation_length' => count($conversation),
            'timestamp' => date('Y-m-d H:i:s')
        ]));
        
        try {
            $response = parent::sendMessage($message, $conversation);
            
            $duration = (microtime(true) - $startTime) * 1000;
            
            error_log("Chatbot Response: " . json_encode([
                'reply_length' => strlen($response['reply']),
                'duration_ms' => round($duration, 2),
                'success' => true
            ]));
            
            return $response;
            
        } catch (Exception $e) {
            error_log("Chatbot Error: " . json_encode([
                'error' => $e->getMessage(),
                'duration_ms' => round((microtime(true) - $startTime) * 1000, 2),
                'success' => false
            ]));
            
            throw $e;
        }
    }
}

Test with Minimal Example

Create isolated test script:

<?php
require_once 'vendor/autoload.php';

use RumenX\PhpChatbot\PhpChatbot;

// Minimal test
try {
    $chatbot = new PhpChatbot([
        'model' => 'openai',
        'api_key' => 'your-key-here',
    ]);
    
    echo "Testing basic functionality...\n";
    $response = $chatbot->sendMessage('Hello, world!');
    echo "✓ Success: " . $response['reply'] . "\n";
    
} catch (Exception $e) {
    echo "✗ Error: " . $e->getMessage() . "\n";
    echo "File: " . $e->getFile() . "\n";
    echo "Line: " . $e->getLine() . "\n";
}

Check Dependencies

# Check all dependencies are properly installed
composer show

# Check for security vulnerabilities
composer audit

# Validate composer.json
composer validate

# Check PHP extensions
php -m

# Check PHP version
php --version

Getting Help

Before Asking for Help

  1. Check this troubleshooting guide for your specific issue
  2. Review the error logs for detailed error messages
  3. Test with minimal configuration to isolate the problem
  4. Check API provider status pages for service outages
  5. Verify your API keys and account limits

Information to Include

When seeking help, please include:

1. PHP version: php --version
2. Package version: composer show rumenx/php-chatbot
3. Operating system: uname -a (Linux/Mac) or ver (Windows)
4. Error message (complete with stack trace)
5. Configuration being used (without API keys)
6. Steps to reproduce the issue
7. Expected vs actual behavior

Where to Get Help

  1. GitHub Issues: https://github.com/rumenx/php-chatbot/issues

    • Check existing issues first
    • Use issue templates
    • Provide all requested information
  2. Documentation: Wiki Pages

    • Quick Start Guide
    • Configuration examples
    • API Reference
  3. Community:

    • Stack Overflow (tag: php-chatbot)
    • PHP community forums
    • Framework-specific communities (Laravel, Symfony)

Creating a Bug Report

Good bug report template:

## Bug Description
Brief description of the issue

## Environment
- PHP Version: 8.2.0
- Package Version: 1.0.0
- Framework: Laravel 10.x / Symfony 6.x / Plain PHP
- OS: Ubuntu 22.04

## Steps to Reproduce
1. Create new PhpChatbot instance
2. Call sendMessage() with...
3. Error occurs

## Expected Behavior
What should happen

## Actual Behavior
What actually happens

## Error Message

Full error message and stack trace


## Configuration
```php
// Your configuration (remove API keys)
$chatbot = new PhpChatbot([...]);

Feature Requests

When requesting new features:

  1. Check if already requested in GitHub issues
  2. Explain the use case - why is this needed?
  3. Provide examples of how it would be used
  4. Consider contributing - pull requests welcome!

Next: API Reference for complete API documentation.

Clone this wiki locally