-
-
Notifications
You must be signed in to change notification settings - Fork 1
Troubleshooting
Common issues, solutions, and debugging techniques.
- Common Issues
- Installation Problems
- Configuration Errors
- API Connection Issues
- Frontend Problems
- Performance Issues
- Debugging Tips
- Getting Help
Common issues, solutions, and debugging techniques.
- Common Issues
- Installation Problems
- Configuration Errors
- API Connection Issues
- Frontend Problems
- Performance Issues
- Debugging Tips
- Getting Help
Symptom: Fatal error when trying to use the PhpChatbot class.
Causes & Solutions:
-
Composer autoloader not included:
// Make sure this is at the top of your file require_once 'vendor/autoload.php';
-
Package not installed properly:
composer install # or if already installed composer dump-autoload -
Wrong namespace used:
// Correct: use RumenX\PhpChatbot\PhpChatbot; // Wrong: use PhpChatbot\PhpChatbot;
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:
- Verify API key format (starts with
sk-for OpenAI) - Check API key has not expired
- Ensure sufficient credits/quota
- Test with a simple API call outside php-chatbot
Symptom: Network-related errors when contacting AI providers.
Solutions:
-
Increase timeout:
$chatbot = new PhpChatbot([ 'model' => 'openai', 'api_key' => 'your-key', 'timeout' => 60, // Increase from default 30 seconds ]);
-
Check network connectivity:
# Test connection to OpenAI curl -I https://api.openai.com # Test connection to Anthropic curl -I https://api.anthropic.com
-
Proxy configuration:
$chatbot = new PhpChatbot([ 'model' => 'openai', 'api_key' => 'your-key', 'proxy' => 'http://proxy.company.com:8080', ]);
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)
];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
]);Issue: composer require rumenx/php-chatbot fails with dependency conflicts.
Solutions:
-
Update Composer:
composer self-update
-
Clear Composer cache:
composer clear-cache composer install
-
Check PHP version requirements:
php --version # Should be 8.1+ composer show --platform -
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
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 phpCheck installed extensions:
php -m | grep -E "(curl|json|mbstring)"Issue: PHP memory exhausted during installation or runtime.
Solutions:
-
Increase memory limit:
# For Composer installation php -d memory_limit=512M composer require rumenx/php-chatbot # In php.ini memory_limit = 512M
-
For runtime:
ini_set('memory_limit', '512M');
Issue: API keys or config values not being read from .env files.
Solutions:
-
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
-
Load environment variables:
// Using vlucas/phpdotenv $dotenv = Dotenv\Dotenv::createImmutable(__DIR__); $dotenv->load(); // Access variables $apiKey = $_ENV['OPENAI_API_KEY'];
-
Framework-specific loading:
// Laravel $apiKey = config('services.openai.key'); // Symfony $apiKey = $this->getParameter('openai.api_key');
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,
],
];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.7Issue: SSL verification failures when connecting to APIs.
Solutions:
-
Update CA certificates:
# Ubuntu/Debian sudo apt-get update && sudo apt-get install ca-certificates # CentOS/RHEL sudo yum update ca-certificates
-
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', ]);
-
Download latest certificates:
# Download latest cacert.pem curl -o cacert.pem https://curl.haxx.se/ca/cacert.pem
Issue: Getting rate-limited by API providers.
Solutions:
-
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); } } }
-
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 } }
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
]);Issue: Cross-origin requests blocked in browser.
Solutions:
-
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; }
-
Laravel CORS:
composer require fruitcake/laravel-cors php artisan vendor:publish --tag="cors" -
Use proxy in development:
// React/Vue development proxy // package.json { "proxy": "http://localhost:8000" }
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;
}
}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%;
}
}Issue: Chatbot responses taking too long.
Solutions:
-
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 ]);
-
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;
-
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...' ]);
Issue: High memory consumption with large conversations.
Solutions:
-
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; }
-
Use streaming responses:
$chatbot = new PhpChatbot([ 'model' => 'openai', 'api_key' => 'your-key', 'stream' => true, // Enable streaming ]);
-
Clear variables:
// Clear large variables when done unset($largeConversationArray); gc_collect_cycles(); // Force garbage collection
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);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']);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;
}
}
}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 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- Check this troubleshooting guide for your specific issue
- Review the error logs for detailed error messages
- Test with minimal configuration to isolate the problem
- Check API provider status pages for service outages
- Verify your API keys and account limits
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
-
GitHub Issues: https://github.com/rumenx/php-chatbot/issues
- Check existing issues first
- Use issue templates
- Provide all requested information
-
Documentation: Wiki Pages
- Quick Start Guide
- Configuration examples
- API Reference
-
Community:
- Stack Overflow (tag: php-chatbot)
- PHP community forums
- Framework-specific communities (Laravel, Symfony)
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 MessageFull error message and stack trace
## Configuration
```php
// Your configuration (remove API keys)
$chatbot = new PhpChatbot([...]);
When requesting new features:
- Check if already requested in GitHub issues
- Explain the use case - why is this needed?
- Provide examples of how it would be used
- Consider contributing - pull requests welcome!
Next: API Reference for complete API documentation.