-
-
Notifications
You must be signed in to change notification settings - Fork 1
Configuration
Rumen Damyanov edited this page Jul 31, 2025
·
1 revision
Complete guide to configuring php-chatbot for your specific needs.
- Configuration File
- Environment Variables
- Model Configuration
- Security Settings
- Framework-Specific Config
- Advanced Options
The main configuration file (config/phpchatbot.php) controls all aspects of the chatbot behavior.
<?php
return [
// AI Model Settings
'model' => 'openai', // AI provider to use
'api_key' => env('OPENAI_API_KEY'), // API key from environment
'model_name' => 'gpt-3.5-turbo', // Specific model name
// Response Settings
'prompt' => 'You are a helpful assistant.',
'language' => 'en',
'temperature' => 0.7,
'max_tokens' => 1000,
// Security Settings
'rate_limit' => 10, // Requests per minute
'timeout' => 30, // API timeout in seconds
'enable_logging' => true, // Log conversations
];<?php
return [
// === MODEL CONFIGURATION ===
'model' => 'openai',
'api_key' => env('OPENAI_API_KEY'),
'model_name' => 'gpt-3.5-turbo',
'endpoint' => null, // Custom endpoint (optional)
// === RESPONSE SETTINGS ===
'prompt' => 'You are a helpful assistant. Be concise and friendly.',
'language' => 'en',
'temperature' => 0.7, // 0.0-1.0 (creativity)
'max_tokens' => 1000, // Maximum response length
'top_p' => 1.0, // Nucleus sampling
'frequency_penalty' => 0, // Reduce repetition
'presence_penalty' => 0, // Encourage new topics
// === SECURITY & LIMITS ===
'timeout' => 30, // API timeout (seconds)
'rate_limit' => 10, // Requests per minute per IP
'rate_window' => 60, // Rate limit window (seconds)
'max_input_length' => 2000, // Maximum input characters
'enable_logging' => true, // Log conversations
// === MESSAGE FILTERING ===
'message_filtering' => [
'enabled' => true,
'instructions' => [
'Use appropriate language.',
'Avoid sharing external links.',
'Reject harmful requests.',
],
'profanities' => ['spam', 'abuse'],
'aggression_patterns' => ['hate', 'kill'],
'link_pattern' => '/https?:\/\/[\w\.-]+/i',
],
// === LOGGING & MONITORING ===
'logging' => [
'enabled' => true,
'level' => 'info', // debug, info, warning, error
'file' => 'chatbot.log', // Log file name
'max_size' => '10MB', // Rotate when this size
'keep_days' => 30, // Keep logs for days
],
// === CACHE SETTINGS ===
'cache' => [
'enabled' => false, // Enable response caching
'ttl' => 3600, // Cache lifetime (seconds)
'driver' => 'file', // file, redis, memcached
'prefix' => 'chatbot_', // Cache key prefix
],
// === UI CUSTOMIZATION ===
'ui' => [
'theme' => 'default', // UI theme
'position' => 'bottom-right', // Chat popup position
'auto_open' => false, // Auto-open chat
'greeting' => 'Hello! How can I help you?',
'placeholder' => 'Type your message...',
'send_button_text' => 'Send',
],
];Use environment variables for sensitive data and deployment-specific settings.
# AI Provider API Keys (choose one or more)
OPENAI_API_KEY=sk-your-openai-key-here
ANTHROPIC_API_KEY=your-anthropic-key-here
GEMINI_API_KEY=your-gemini-key-here
XAI_API_KEY=your-xai-key-here
META_API_KEY=your-meta-key-here
DEEPSEEK_API_KEY=your-deepseek-key-here# Model Configuration
PHPCHATBOT_MODEL=openai
PHPCHATBOT_MODEL_NAME=gpt-3.5-turbo
PHPCHATBOT_TEMPERATURE=0.7
PHPCHATBOT_MAX_TOKENS=1000
# Security Settings
PHPCHATBOT_RATE_LIMIT=10
PHPCHATBOT_TIMEOUT=30
PHPCHATBOT_ENABLE_LOGGING=true
# Custom Configuration
PHPCHATBOT_CONFIG_PATH=/path/to/custom/config.phpCreate different .env files for different environments:
.env.local (Development):
PHPCHATBOT_MODEL=default
PHPCHATBOT_ENABLE_LOGGING=true
PHPCHATBOT_RATE_LIMIT=100.env.staging (Staging):
PHPCHATBOT_MODEL=openai
OPENAI_API_KEY=sk-staging-key
PHPCHATBOT_RATE_LIMIT=20.env.production (Production):
PHPCHATBOT_MODEL=openai
OPENAI_API_KEY=sk-production-key
PHPCHATBOT_RATE_LIMIT=10
PHPCHATBOT_ENABLE_LOGGING=falseConfigure different AI models with specific settings.
return [
'model' => 'openai', // Default model
'models' => [
'openai' => [
'api_key' => env('OPENAI_API_KEY'),
'model_name' => 'gpt-3.5-turbo',
'temperature' => 0.7,
'max_tokens' => 1000,
],
'anthropic' => [
'api_key' => env('ANTHROPIC_API_KEY'),
'model_name' => 'claude-3-haiku-20240307',
'temperature' => 0.7,
'max_tokens' => 1000,
],
'gemini' => [
'api_key' => env('GEMINI_API_KEY'),
'model_name' => 'gemini-1.5-flash',
'temperature' => 0.7,
],
'ollama' => [
'base_url' => 'http://localhost:11434',
'model_name' => 'llama3.2',
'timeout' => 60,
],
],
];use Rumenx\PhpChatbot\PhpChatbot;
use Rumenx\PhpChatbot\Models\ModelFactory;
$config = require 'config/phpchatbot.php';
// Switch models at runtime
$openaiModel = ModelFactory::make(array_merge($config, ['model' => 'openai']));
$claudeModel = ModelFactory::make(array_merge($config, ['model' => 'anthropic']));
$chatbot = new PhpChatbot($openaiModel, $config);
// Switch to different model
$chatbot->setModel($claudeModel);return [
'model' => 'openai',
'fallback_models' => ['anthropic', 'gemini', 'default'],
'retry_config' => [
'max_retries' => 3,
'retry_delay' => 1, // seconds
'fallback_on_error' => true,
],
];Configure security features to protect against abuse and ensure safe operation.
'rate_limiting' => [
'enabled' => true,
'requests_per_minute' => 10,
'requests_per_hour' => 100,
'requests_per_day' => 1000,
'burst_limit' => 5, // Allow short bursts
'whitelist_ips' => [ // Exempt from rate limiting
'127.0.0.1',
'::1',
],
'storage' => 'file', // file, redis, database
],'input_validation' => [
'max_length' => 2000, // Maximum input characters
'min_length' => 1, // Minimum input characters
'allowed_languages' => ['en', 'es', 'fr'], // Language detection
'block_patterns' => [ // Regex patterns to block
'/\b(?:admin|root|password)\b/i',
'/\b(?:inject|script|eval)\b/i',
],
'sanitize_html' => true, // Strip HTML tags
'normalize_unicode' => true, // Normalize Unicode
],'content_filtering' => [
'enabled' => true,
'strict_mode' => false, // Stricter filtering
'custom_filters' => [
'profanity' => ['badword1', 'badword2'],
'sensitive' => ['password', 'secret', 'token'],
'spam' => ['click here', 'free money', 'urgent'],
],
'action_on_violation' => 'reject', // reject, warn, modify
'log_violations' => true,
],'api_security' => [
'cors_enabled' => true,
'allowed_origins' => ['https://yourdomain.com'],
'api_key_header' => 'X-API-Key',
'rate_limit_header' => true, // Include rate limit info in headers
'encrypt_logs' => true, // Encrypt conversation logs
'mask_sensitive_data' => true, // Mask API keys in logs
],config/phpchatbot.php:
<?php
return [
'model' => env('PHPCHATBOT_MODEL', 'openai'),
'api_key' => env('OPENAI_API_KEY'),
// Laravel-specific features
'use_laravel_cache' => true,
'use_laravel_queue' => false, // Queue API requests
'use_laravel_logging' => true, // Use Laravel's logging
'middleware' => ['web', 'throttle:60,1'],
'route' => [
'prefix' => 'chatbot',
'middleware' => ['web'],
'name' => 'chatbot.',
],
];Publishing Assets:
php artisan vendor:publish --provider="Rumenx\PhpChatbot\Adapters\Laravel\PhpChatbotServiceProvider" --tag=config
php artisan vendor:publish --provider="Rumenx\PhpChatbot\Adapters\Laravel\PhpChatbotServiceProvider" --tag=views
php artisan vendor:publish --provider="Rumenx\PhpChatbot\Adapters\Laravel\PhpChatbotServiceProvider" --tag=assetsconfig/packages/phpchatbot.yaml:
phpchatbot:
model: '%env(PHPCHATBOT_MODEL)%'
api_key: '%env(OPENAI_API_KEY)%'
# Symfony-specific features
use_symfony_cache: true
use_symfony_logger: true
cache_pool: 'app.cache.chatbot'
security:
csrf_protection: true
session_validation: true
routing:
prefix: '/chatbot'
requirements:
_locale: 'en|es|fr'services.yaml:
services:
Rumenx\PhpChatbot\PhpChatbot:
arguments:
$config: '%phpchatbot%'
tags: ['controller.service_arguments']config/phpchatbot.php:
<?php
// Load environment variables
if (file_exists(__DIR__ . '/../.env')) {
$dotenv = Dotenv\Dotenv::createImmutable(__DIR__ . '/..');
$dotenv->load();
}
return [
'model' => $_ENV['PHPCHATBOT_MODEL'] ?? 'default',
'api_key' => $_ENV['OPENAI_API_KEY'] ?? null,
// Plain PHP specific
'session_storage' => true, // Use PHP sessions for rate limiting
'file_logging' => true, // Log to files
'error_reporting' => E_ALL, // Error level
'paths' => [
'logs' => __DIR__ . '/../storage/logs',
'cache' => __DIR__ . '/../storage/cache',
'views' => __DIR__ . '/../resources/views',
],
];'middleware' => [
'enabled' => true,
'classes' => [
'auth' => App\Middleware\AuthMiddleware::class,
'rate_limit' => App\Middleware\RateLimitMiddleware::class,
'logging' => App\Middleware\LoggingMiddleware::class,
],
'order' => ['auth', 'rate_limit', 'logging'],
],'webhooks' => [
'enabled' => true,
'endpoints' => [
'conversation_started' => 'https://api.yourapp.com/webhooks/chat-started',
'conversation_ended' => 'https://api.yourapp.com/webhooks/chat-ended',
'message_sent' => 'https://api.yourapp.com/webhooks/message',
],
'headers' => [
'Authorization' => 'Bearer your-webhook-token',
'Content-Type' => 'application/json',
],
'timeout' => 5,
'retry_attempts' => 3,
],'performance' => [
'enable_compression' => true, // Gzip responses
'enable_http2' => true, // Use HTTP/2 if available
'connection_pooling' => true, // Pool HTTP connections
'async_requests' => false, // Async API calls (requires ReactPHP)
'cache_responses' => [
'enabled' => true,
'ttl' => 3600, // Cache for 1 hour
'vary_by_user' => false, // User-specific caching
],
'preload_models' => true, // Preload model classes
'optimize_prompts' => true, // Optimize system prompts
],use Rumenx\PhpChatbot\Config\ConfigLoader;
// Load from database
$config = ConfigLoader::fromDatabase('chatbot_config');
// Load from JSON
$config = ConfigLoader::fromJson('/path/to/config.json');
// Load from YAML
$config = ConfigLoader::fromYaml('/path/to/config.yaml');
// Merge configurations
$config = ConfigLoader::merge([
ConfigLoader::fromFile('config/base.php'),
ConfigLoader::fromEnv(),
ConfigLoader::fromDatabase('overrides'),
]);Next: Security & Filtering