Skip to content
Rumen Damyanov edited this page Jul 31, 2025 · 1 revision

Frequently Asked Questions

Common questions and answers about php-chatbot.

Table of Contents

Frequently Asked Questions

Common questions and answers about php-chatbot.

Table of Contents

General Questions

What is php-chatbot?

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.

What PHP versions are supported?

php-chatbot requires PHP 8.3 or higher. We recommend using the latest stable PHP version for the best performance and security.

Is it free to use?

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).

Which frameworks does it support?

php-chatbot is framework-agnostic but includes specific integrations for:

  • Laravel (Service Provider, Facade, Artisan commands)
  • Symfony (Bundle, Services, Commands)
  • Plain PHP (Standalone usage)

Can I use multiple AI providers?

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');

How is this different from other chatbot libraries?

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

Installation & Setup

How do I install php-chatbot?

Install via Composer:

composer require rumenx/php-chatbot

For Laravel:

php artisan vendor:publish --provider="RumenX\PhpChatbot\Providers\LaravelServiceProvider"

What are the minimum requirements?

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

Do I need to configure anything after installation?

Yes, you need to:

  1. Set up environment variables:

    OPENAI_API_KEY=your_openai_key
    ANTHROPIC_API_KEY=your_anthropic_key
  2. Publish configuration (Laravel):

    php artisan vendor:publish --tag=php-chatbot-config
  3. Configure your chosen AI provider in the config file

How do I get API keys for AI providers?

OpenAI:

  1. Go to OpenAI API
  2. Create account and add billing
  3. Generate API key

Anthropic:

  1. Visit Anthropic Console
  2. Create account and verify
  3. Generate API key

Google Gemini:

  1. Go to Google AI Studio
  2. Create/select project
  3. Generate API key

Can I test without API keys?

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."

Configuration

How do I configure different AI models?

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,
];

How do I customize message filtering?

$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'],
        ],
    ],
];

Can I use custom prompts?

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',
    ],
];

How do I configure conversation memory?

$config = [
    'conversation' => [
        'enabled' => true,
        'max_history' => 10, // Remember last 10 messages
        'storage' => 'session', // or 'database', 'redis'
    ],
];

AI Models & Providers

Which AI models are supported?

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

How do I switch between AI providers?

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);

Which provider should I choose?

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

How do I handle API rate limits?

$config = [
    'retry' => [
        'enabled' => true,
        'max_attempts' => 3,
        'delay' => 1000, // milliseconds
        'backoff' => 'exponential',
    ],
];

Can I use multiple providers for redundancy?

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);
}

Frontend Integration

What frontend frameworks are supported?

We provide pre-built components for:

  • React (with TypeScript)
  • Vue 3 (Composition API)
  • Angular (Standalone components)
  • Vanilla JavaScript (ES6+)

How do I integrate with React?

import { Chatbot } from './components/Chatbot';

function App() {
  return (
    <div>
      <h1>My App</h1>
      <Chatbot 
        apiUrl="/api/chatbot"
        title="Support Chat"
        position="bottom-right"
      />
    </div>
  );
}

How do I customize the chat UI?

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.

Can I add file upload to the chat?

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
});

How do I handle different screen sizes?

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);
  }
}

Security & Privacy

How is user data protected?

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

What data is sent to AI providers?

Sent to AI providers:

  • User message content
  • Conversation context (if enabled)
  • System prompts

NOT sent:

  • User personal information
  • Session data
  • IP addresses
  • Authentication tokens

How do I implement content filtering?

$config = [
    'security' => [
        'content_filter' => [
            'enabled' => true,
            'blocked_words' => ['inappropriate', 'spam'],
            'max_length' => 2000,
            'require_moderation' => true,
        ],
    ],
];

Can I log conversations for review?

$config = [
    'logging' => [
        'enabled' => true,
        'level' => 'info',
        'store_conversations' => true,
        'retention_days' => 30,
    ],
];

Note: Always comply with privacy laws (GDPR, CCPA) when logging.

How do I handle sensitive information?

// 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());

Performance

How fast is php-chatbot?

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

How do I optimize performance?

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));

Can I cache responses?

Yes! Enable response caching:

$config = [
    'cache' => [
        'enabled' => true,
        'driver' => 'redis', // or 'file', 'database'
        'ttl' => 3600, // Cache for 1 hour
        'key_prefix' => 'chatbot_',
    ],
];

How do I handle high traffic?

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);

Troubleshooting

I'm getting "API key not found" errors

Solutions:

  1. Check environment file:

    # .env
    OPENAI_API_KEY=sk-your-actual-key-here
  2. Verify key in code:

    echo env('OPENAI_API_KEY'); // Should show your key
  3. Clear cache (Laravel):

    php artisan config:clear
    php artisan cache:clear

API requests are failing

Common causes:

1. Invalid API key:

# Test your API key
curl -H "Authorization: Bearer YOUR_API_KEY" \
  https://api.openai.com/v1/models

2. 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,
    ],
];

Frontend chat widget not appearing

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);

Responses are slow or timing out

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,
    ],
];

Laravel integration not working

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 chatbot

Memory or performance issues

1. 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)
];

Still having issues?

  1. Check the logs for detailed error messages
  2. Search existing issues on GitHub
  3. Create a new issue with:
    • PHP version
    • Package version
    • Error message
    • Minimal reproduction code
  4. Join discussions for community help

Need more help? Check our Troubleshooting Guide or open an issue on GitHub.


Back to: Wiki Home

Clone this wiki locally