-
-
Notifications
You must be signed in to change notification settings - Fork 1
FAQ
Common questions and answers about php-chatbot.
- General Questions
- Installation & Setup
- Configuration
- AI Models & Providers
- Frontend Integration
- Security & Privacy
- Performance
- Troubleshooting
Common questions and answers about php-chatbot.
- General Questions
- Installation & Setup
- Configuration
- AI Models & Providers
- Frontend Integration
- Security & Privacy
- Performance
- Troubleshooting
php-chatbot is a modern, framework-agnostic PHP package that provides AI-powered chat functionality for web applications. It supports multiple AI providers (OpenAI, Anthropic, Google Gemini, etc.) and includes built-in security features, frontend components, and framework integrations.
php-chatbot requires PHP 8.3 or higher. We recommend using the latest stable PHP version for the best performance and security.
Yes! php-chatbot is open source and released under the MIT License. You can use it freely in both personal and commercial projects. However, you'll need API keys from AI providers (which may have their own costs).
php-chatbot is framework-agnostic but includes specific integrations for:
- Laravel (Service Provider, Facade, Artisan commands)
- Symfony (Bundle, Services, Commands)
- Plain PHP (Standalone usage)
Yes! You can switch between providers or even use multiple providers simultaneously:
// Switch providers dynamically
$chatbot->setModel('openai');
$response1 = $chatbot->sendMessage('Hello');
$chatbot->setModel('anthropic');
$response2 = $chatbot->sendMessage('Hello');Key differentiators:
- ✅ Multiple AI providers in one package
- ✅ Built-in security and filtering
- ✅ Frontend components included
- ✅ Framework integrations ready
- ✅ High test coverage (90%+)
- ✅ Production-ready with proper error handling
Install via Composer:
composer require rumenx/php-chatbotFor Laravel:
php artisan vendor:publish --provider="RumenX\PhpChatbot\Providers\LaravelServiceProvider"System Requirements:
- PHP 8.1+ with extensions:
curl,json,mbstring - Composer 2.0+
- At least one AI provider API key
Optional Requirements:
- Redis/Memcached for rate limiting
- Laravel 9+ or Symfony 5+ for framework features
Yes, you need to:
-
Set up environment variables:
OPENAI_API_KEY=your_openai_key ANTHROPIC_API_KEY=your_anthropic_key
-
Publish configuration (Laravel):
php artisan vendor:publish --tag=php-chatbot-config
-
Configure your chosen AI provider in the config file
OpenAI:
- Go to OpenAI API
- Create account and add billing
- Generate API key
Anthropic:
- Visit Anthropic Console
- Create account and verify
- Generate API key
Google Gemini:
- Go to Google AI Studio
- Create/select project
- Generate API key
Yes! You can use the DefaultAiModel for testing:
$chatbot = new PhpChatbot([
'model' => 'default',
// No API key needed for testing
]);
$response = $chatbot->sendMessage('Hello');
// Returns: "This is a default response for testing purposes."OpenAI Configuration:
$config = [
'model' => 'openai',
'api_key' => env('OPENAI_API_KEY'),
'gpt_model' => 'gpt-4',
'temperature' => 0.7,
'max_tokens' => 150,
];Anthropic Configuration:
$config = [
'model' => 'anthropic',
'api_key' => env('ANTHROPIC_API_KEY'),
'claude_model' => 'claude-3-sonnet-20240229',
'temperature' => 0.7,
'max_tokens' => 150,
];$config = [
'security' => [
'max_message_length' => 2000,
'rate_limit' => [
'enabled' => true,
'max_requests' => 10,
'time_window' => 60, // seconds
],
'content_filter' => [
'enabled' => true,
'blocked_words' => ['spam', 'abuse'],
],
],
];Yes! You can set system prompts for different AI models:
$config = [
'system_prompt' => 'You are a helpful customer service assistant. Be polite and concise.',
'context' => [
'role' => 'assistant',
'company' => 'Acme Corp',
'domain' => 'e-commerce',
],
];$config = [
'conversation' => [
'enabled' => true,
'max_history' => 10, // Remember last 10 messages
'storage' => 'session', // or 'database', 'redis'
],
];OpenAI:
- GPT-4, GPT-4 Turbo
- GPT-3.5 Turbo
- Custom fine-tuned models
Anthropic:
- Claude-3 (Opus, Sonnet, Haiku)
- Claude-2.1, Claude-2.0
Google:
- Gemini Pro, Gemini Pro Vision
- PaLM 2
Meta:
- Llama 2, Code Llama
Others:
- Ollama (local models)
- xAI Grok
- DeepSeek
At runtime:
$chatbot = new PhpChatbot();
// Use OpenAI
$chatbot->setModel('openai');
$response1 = $chatbot->sendMessage('Hello');
// Switch to Anthropic
$chatbot->setModel('anthropic');
$response2 = $chatbot->sendMessage('Hello');Via configuration:
$config = ['model' => 'anthropic']; // Change this
$chatbot = new PhpChatbot($config);For general use: OpenAI GPT-4 (balanced quality/cost) For creativity: Anthropic Claude-3 Opus (best quality) For speed: OpenAI GPT-3.5 Turbo (fastest/cheapest) For privacy: Ollama (local/self-hosted) For coding: OpenAI GPT-4 or Meta Code Llama
$config = [
'retry' => [
'enabled' => true,
'max_attempts' => 3,
'delay' => 1000, // milliseconds
'backoff' => 'exponential',
],
];Yes! Implement a fallback strategy:
$chatbot = new PhpChatbot(['model' => 'openai']);
try {
$response = $chatbot->sendMessage($message);
} catch (ApiException $e) {
// Fallback to Anthropic
$chatbot->setModel('anthropic');
$response = $chatbot->sendMessage($message);
}We provide pre-built components for:
- React (with TypeScript)
- Vue 3 (Composition API)
- Angular (Standalone components)
- Vanilla JavaScript (ES6+)
import { Chatbot } from './components/Chatbot';
function App() {
return (
<div>
<h1>My App</h1>
<Chatbot
apiUrl="/api/chatbot"
title="Support Chat"
position="bottom-right"
/>
</div>
);
}CSS Variables (easiest):
.chatbot-container {
--primary-color: #your-brand-color;
--background-color: #ffffff;
}Custom CSS:
.chatbot-popup {
border-radius: 20px;
box-shadow: 0 10px 40px rgba(0,0,0,0.2);
}Custom Component: Build your own using our API endpoints.
Not built-in, but you can extend the components:
// Add file input to chat
const fileInput = document.createElement('input');
fileInput.type = 'file';
fileInput.accept = 'image/*,.pdf,.doc,.docx';
// Handle file upload
fileInput.addEventListener('change', async (e) => {
const file = e.target.files[0];
// Upload and send file reference to chatbot
});The components are responsive by default:
/* Desktop */
.chatbot-popup {
width: 350px;
height: 500px;
}
/* Mobile */
@media (max-width: 768px) {
.chatbot-popup {
width: calc(100vw - 20px);
height: calc(100vh - 100px);
}
}Built-in Security Features:
- ✅ Input sanitization and validation
- ✅ Rate limiting to prevent abuse
- ✅ Content filtering for inappropriate messages
- ✅ CSRF protection for web requests
- ✅ API key encryption in transit
Sent to AI providers:
- User message content
- Conversation context (if enabled)
- System prompts
NOT sent:
- User personal information
- Session data
- IP addresses
- Authentication tokens
$config = [
'security' => [
'content_filter' => [
'enabled' => true,
'blocked_words' => ['inappropriate', 'spam'],
'max_length' => 2000,
'require_moderation' => true,
],
],
];$config = [
'logging' => [
'enabled' => true,
'level' => 'info',
'store_conversations' => true,
'retention_days' => 30,
],
];Note: Always comply with privacy laws (GDPR, CCPA) when logging.
// Custom middleware for PII detection
class PiiFilterMiddleware implements MiddlewareInterface
{
public function process(string $message): string
{
// Remove emails, phone numbers, SSNs, etc.
$filtered = preg_replace('/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b/', '[EMAIL]', $message);
return $filtered;
}
}
$chatbot->addMiddleware(new PiiFilterMiddleware());Typical response times:
- OpenAI GPT-3.5: 1-3 seconds
- OpenAI GPT-4: 3-8 seconds
- Anthropic Claude: 2-5 seconds
- Local models (Ollama): 5-15 seconds
PHP processing overhead: <50ms
1. Use faster models for simple queries:
$config = [
'model' => 'openai',
'gpt_model' => 'gpt-3.5-turbo', // Faster than GPT-4
];2. Implement caching:
$config = [
'cache' => [
'enabled' => true,
'ttl' => 3600, // 1 hour
'driver' => 'redis',
],
];3. Optimize message length:
$config = [
'max_tokens' => 100, // Shorter responses = faster
'temperature' => 0.3, // More deterministic = faster
];4. Use async processing:
// Queue long-running requests
Queue::push(new ProcessChatMessage($message));Yes! Enable response caching:
$config = [
'cache' => [
'enabled' => true,
'driver' => 'redis', // or 'file', 'database'
'ttl' => 3600, // Cache for 1 hour
'key_prefix' => 'chatbot_',
],
];1. Use queue workers:
// Laravel
php artisan queue:work --queue=chatbot
// Process messages asynchronously
Queue::push(new ProcessChatMessage($message));2. Implement rate limiting:
$config = [
'rate_limit' => [
'enabled' => true,
'max_requests' => 100,
'time_window' => 3600, // Per hour
],
];3. Load balance AI providers:
$providers = ['openai', 'anthropic', 'google'];
$selected = $providers[array_rand($providers)];
$chatbot->setModel($selected);Solutions:
-
Check environment file:
# .env OPENAI_API_KEY=sk-your-actual-key-here -
Verify key in code:
echo env('OPENAI_API_KEY'); // Should show your key
-
Clear cache (Laravel):
php artisan config:clear php artisan cache:clear
Common causes:
1. Invalid API key:
# Test your API key
curl -H "Authorization: Bearer YOUR_API_KEY" \
https://api.openai.com/v1/models2. Rate limits exceeded:
// Implement retry logic
$config = [
'retry' => [
'max_attempts' => 3,
'delay' => 2000,
],
];3. Network/SSL issues:
// Check cURL configuration
$config = [
'http' => [
'verify_ssl' => false, // Only for development!
'timeout' => 30,
],
];Check these common issues:
1. JavaScript errors:
// Open browser console (F12) and check for errors
console.log('Chatbot script loaded');2. CSS conflicts:
/* Ensure proper z-index */
.chatbot-container {
z-index: 9999 !important;
}3. API endpoint not working:
// Test API endpoint directly
fetch('/api/chatbot', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ message: 'test' })
})
.then(r => r.json())
.then(console.log);Optimization strategies:
1. Reduce context length:
$config = [
'max_tokens' => 100, // Shorter responses
'conversation' => [
'max_history' => 3, // Less context
],
];2. Use faster models:
$config = [
'model' => 'openai',
'gpt_model' => 'gpt-3.5-turbo', // Faster than GPT-4
];3. Implement timeout handling:
$config = [
'timeout' => 30, // 30 seconds max
'retry' => [
'enabled' => true,
'max_attempts' => 2,
],
];Common Laravel issues:
1. Service provider not registered:
// config/app.php
'providers' => [
// ...
RumenX\PhpChatbot\Providers\LaravelServiceProvider::class,
],2. Configuration not published:
php artisan vendor:publish --provider="RumenX\PhpChatbot\Providers\LaravelServiceProvider"3. Routes not working:
# Check if routes are registered
php artisan route:list | grep chatbot1. Profile your application:
// Add to your code
$start = memory_get_usage();
$chatbot->sendMessage($message);
$memory = memory_get_usage() - $start;
echo "Memory used: " . ($memory / 1024) . "KB";2. Optimize configuration:
$config = [
'conversation' => [
'max_history' => 5, // Reduce memory usage
],
'cache' => [
'enabled' => true, // Cache responses
],
];3. Use streaming for long responses:
$config = [
'stream' => true, // Stream responses (if supported)
];- Check the logs for detailed error messages
- Search existing issues on GitHub
-
Create a new issue with:
- PHP version
- Package version
- Error message
- Minimal reproduction code
- Join discussions for community help
Need more help? Check our Troubleshooting Guide or open an issue on GitHub.
Back to: Wiki Home