{"id":28746821,"url":"https://github.com/rumendamyanov/php-chatbot","last_synced_at":"2026-05-04T21:34:27.184Z","repository":{"id":299191490,"uuid":"1002127771","full_name":"RumenDamyanov/php-chatbot","owner":"RumenDamyanov","description":"A modern, framework-agnostic PHP package for adding customizable, AI-powered chat popups to any web application. Includes adapters for Laravel and Symfony, supports multiple AI providers, and is easy to extend.","archived":false,"fork":false,"pushed_at":"2025-06-15T08:07:50.000Z","size":0,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"master","last_synced_at":"2025-06-15T08:45:42.127Z","etag":null,"topics":["ai","ai-models","chatbot","laravel","php","symfony"],"latest_commit_sha":null,"homepage":"","language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/RumenDamyanov.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE.md","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2025-06-14T19:18:45.000Z","updated_at":"2025-06-15T08:09:13.000Z","dependencies_parsed_at":"2025-06-15T08:45:45.394Z","dependency_job_id":"d87670bc-124c-498b-936d-bc91d2245e67","html_url":"https://github.com/RumenDamyanov/php-chatbot","commit_stats":null,"previous_names":["rumendamyanov/php-chatbot"],"tags_count":1,"template":false,"template_full_name":null,"purl":"pkg:github/RumenDamyanov/php-chatbot","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/RumenDamyanov%2Fphp-chatbot","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/RumenDamyanov%2Fphp-chatbot/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/RumenDamyanov%2Fphp-chatbot/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/RumenDamyanov%2Fphp-chatbot/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/RumenDamyanov","download_url":"https://codeload.github.com/RumenDamyanov/php-chatbot/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/RumenDamyanov%2Fphp-chatbot/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":260192311,"owners_count":22972595,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["ai","ai-models","chatbot","laravel","php","symfony"],"created_at":"2025-06-16T15:48:41.575Z","updated_at":"2026-05-04T21:34:27.177Z","avatar_url":"https://github.com/RumenDamyanov.png","language":"PHP","funding_links":[],"categories":[],"sub_categories":[],"readme":"# php-chatbot\n\n[![CI](https://github.com/RumenDamyanov/php-chatbot/actions/workflows/ci.yml/badge.svg)](https://github.com/RumenDamyanov/php-chatbot/actions/workflows/ci.yml)\n[![Analyze](https://github.com/RumenDamyanov/php-chatbot/actions/workflows/analyze.yml/badge.svg)](https://github.com/RumenDamyanov/php-chatbot/actions/workflows/analyze.yml)\n[![Style](https://github.com/RumenDamyanov/php-chatbot/actions/workflows/style.yml/badge.svg)](https://github.com/RumenDamyanov/php-chatbot/actions/workflows/style.yml)\n[![CodeQL](https://github.com/RumenDamyanov/php-chatbot/actions/workflows/github-code-scanning/codeql/badge.svg)](https://github.com/RumenDamyanov/php-chatbot/actions/workflows/github-code-scanning/codeql)\n[![Dependabot](https://github.com/RumenDamyanov/php-chatbot/actions/workflows/dependabot/dependabot-updates/badge.svg)](https://github.com/RumenDamyanov/php-chatbot/actions/workflows/dependabot/dependabot-updates)\n[![codecov](https://codecov.io/gh/RumenDamyanov/php-chatbot/branch/master/graph/badge.svg)](https://codecov.io/gh/RumenDamyanov/php-chatbot)\n\n\n\u003e 📖 **Documentation**: [Contributing](CONTRIBUTING.md) · [Security](SECURITY.md) · [Changelog](CHANGELOG.md) · [Funding](FUNDING.md)\n\n**php-chatbot** is a modern, framework-agnostic PHP package for integrating an AI-powered chat popup into any web application. It features out-of-the-box support for Laravel and Symfony, a flexible model abstraction for using OpenAI, Anthropic, xAI, Google Gemini, Meta, and more, and is designed for easy customization and extension. Build your own UI or use the provided minimal frontend as a starting point. High test coverage, static analysis, and coding standards are included.\n\n## 📦 Part of the Chatbot Family\n\nThis is the PHP implementation of our multi-language chatbot library:\n\n- 🐘 **[php-chatbot](https://github.com/RumenDamyanov/php-chatbot)** - PHP implementation (this package)\n- 📘 **[npm-chatbot](https://github.com/RumenDamyanov/npm-chatbot)** - TypeScript/JavaScript implementation\n- 🔷 **[go-chatbot](https://github.com/RumenDamyanov/go-chatbot)** - Go implementation\n\nAll implementations share the same API design and features, making it easy to switch between languages or maintain consistency across polyglot projects.\n\n## 🔗 Recommended Projects\n\nIf you find **php-chatbot** useful, you might also be interested in these related projects:\n\n- 🔍 **[php-seo](https://github.com/RumenDamyanov/php-seo)** - Comprehensive SEO toolkit for PHP applications\n- 🗺️ **[php-sitemap](https://github.com/RumenDamyanov/php-sitemap)** - Dynamic XML sitemap generator for PHP\n- 🌍 **[php-geolocation](https://github.com/RumenDamyanov/php-geolocation)** - IP geolocation and geographic data tools\n\n## Features\n\n- Plug-and-play chat popup UI (minimal frontend dependencies)\n- **Token \u0026 Cost Tracking** - Monitor API usage and optimize costs with detailed token analytics\n- **Conversation Memory** - Persistent context across messages with file/Redis/database storage\n- **Streaming Responses** - Real-time token-by-token output for better UX\n- **Rate Limiting** - Built-in request throttling with memory and Redis backends\n- **Response Caching** - Intelligent caching to reduce API costs and improve performance\n- **Health Monitoring** - Comprehensive health checks for models, storage, and cache\n- **Exception Hierarchy** - Robust error handling with specific exception types\n- Laravel \u0026 Symfony support via adapters/service providers\n- AI model abstraction via contracts (swap models easily)\n- Customizable prompts, tone, language, and scope\n- Emoji and multi-script support (Cyrillic, Greek, Armenian, Asian, etc.)\n- Security safeguards against abuse\n- High test coverage (80%+, 540+ tests with Pest)\n- Static analysis (PHPStan Level MAX) \u0026 coding standards (PSR-12, Symfony style)\n\n## 📚 Documentation \u0026 Wiki\n\nComprehensive documentation and guides are available in our [GitHub Wiki](https://github.com/RumenDamyanov/php-chatbot/wiki):\n\n### 🚀 Getting Started\n- **[Installation Guide](https://github.com/RumenDamyanov/php-chatbot/wiki/Installation-Guide)** - Step-by-step installation for all environments\n- **[Quick Start Guide](https://github.com/RumenDamyanov/php-chatbot/wiki/Quick-Start-Guide)** - Get up and running in minutes\n- **[Configuration](https://github.com/RumenDamyanov/php-chatbot/wiki/Configuration)** - Complete configuration reference\n\n### 🔧 Implementation Guides\n- **[Framework Integration](https://github.com/RumenDamyanov/php-chatbot/wiki/Framework-Integration)** - Laravel, Symfony, and plain PHP setup\n- **[Frontend Integration](https://github.com/RumenDamyanov/php-chatbot/wiki/Frontend-Integration)** - React, Vue, Angular components and examples\n- **[AI Models](https://github.com/RumenDamyanov/php-chatbot/wiki/AI-Models)** - Provider comparison and configuration\n- **[Token \u0026 Cost Tracking](https://github.com/RumenDamyanov/php-chatbot/wiki/Token-Tracking)** - Monitor API usage, track costs, and optimize spending\n- **[Conversation Memory](https://github.com/RumenDamyanov/php-chatbot/wiki/Conversation-Memory)** - Persistent context with file/Redis/database storage\n- **[Rate Limiting](https://github.com/RumenDamyanov/php-chatbot/wiki/Rate-Limiting)** - Built-in request throttling and abuse prevention\n- **[Response Caching](https://github.com/RumenDamyanov/php-chatbot/wiki/Response-Caching)** - Smart caching to reduce API costs\n- **[Health Monitoring](https://github.com/RumenDamyanov/php-chatbot/wiki/Health-Monitoring)** - System health checks and monitoring\n\n### 📖 Examples \u0026 Best Practices\n- **[Examples](https://github.com/RumenDamyanov/php-chatbot/wiki/Examples)** - Real-world implementations and use cases\n- **[Best Practices](https://github.com/RumenDamyanov/php-chatbot/wiki/Best-Practices)** - Production deployment and security guidelines\n- **[Security \u0026 Filtering](https://github.com/RumenDamyanov/php-chatbot/wiki/Security-and-Filtering)** - Content filtering and abuse prevention\n- **[Streaming Responses](https://github.com/RumenDamyanov/php-chatbot/wiki/Streaming-Responses)** - How to use streaming responses\n\n### 🛠️ Development \u0026 Support\n- **[API Reference](https://github.com/RumenDamyanov/php-chatbot/wiki/API-Reference)** - Complete API documentation\n- **[Troubleshooting](https://github.com/RumenDamyanov/php-chatbot/wiki/Troubleshooting)** - Common issues and solutions\n- **[Contributing](https://github.com/RumenDamyanov/php-chatbot/wiki/Contributing)** - How to contribute to the project\n- **[FAQ](https://github.com/RumenDamyanov/php-chatbot/wiki/FAQ)** - Frequently asked questions\n\n\u003e 💡 **Tip**: The wiki contains production-ready examples, troubleshooting guides, and comprehensive API documentation that goes beyond this README.\n\n## Supported AI Providers \u0026 Models\n\n| Provider   | Example Models / Notes                                 | API Key Required | Local/Remote | Streaming |\n|------------|--------------------------------------------------------|------------------|--------------|-----------|\n| OpenAI     | gpt-4.1, gpt-4o, gpt-4o-mini, gpt-3.5-turbo, etc.      | Yes              | Remote       | ✅        |\n| Anthropic  | Claude 3 Sonnet, 3.7, 4, etc.                          | Yes              | Remote       | ✅        |\n| xAI        | Grok-1, Grok-1.5, etc.                                 | Yes              | Remote       | ✅        |\n| Google     | Gemini 1.5 Pro, Gemini 1.5 Flash, etc.                 | Yes              | Remote       | ✅        |\n| Meta       | Llama 3 (8B, 70B), etc.                                | Yes              | Remote       | ✅        |\n| DeepSeek   | DeepSeek Chat, DeepSeek Coder, etc.                    | Yes              | Remote       | ✅        |\n| Ollama     | llama2, mistral, phi3, and any local Ollama model      | No (local) / Opt | Local/Remote | ✅        |\n| Free model | Simple fallback, no API key required                   | No               | Local        | ❌        |\n\n## Installation\n\n```bash\ncomposer require rumenx/php-chatbot\n```\n\n### Laravel\n\n- Package auto-discovers the service provider.\n- Publish config: `php artisan vendor:publish --provider=\"Rumenx\\\\PhpChatbot\\\\Adapters\\\\Laravel\\\\PhpChatbotServiceProvider\"`\n\n### Symfony\n\n- Register the bundle in your `bundles.php`.\n- Publish config: `php bin/console chatbot:publish-config`\n\n## Usage\n\n1. Add the chat popup to your layout (see `/resources/views` for examples).\n2. Configure your preferred AI model and prompts in the config file (`src/Config/phpchatbot.php`).\n3. Optionally, customize the frontend (CSS/JS) in `/resources`.\n\n### API Keys \u0026 Credentials\n\n**Never hardcode API keys or secrets in your codebase.**\n\n- Use environment variables (e.g. `.env` file) or your infrastructure's secret management.\n- The config file will check for environment variables (e.g. `OPENAI_API_KEY`, `ANTHROPIC_API_KEY`, etc.) first.\n- See `.env.example` for reference.\n\n## Quick Start\n\n```php\nuse Rumenx\\PhpChatbot\\PhpChatbot;\nuse Rumenx\\PhpChatbot\\Models\\ModelFactory;\n\n$config = require 'src/Config/phpchatbot.php';\n$model = ModelFactory::make($config);\n$chatbot = new PhpChatbot($model, $config);\n\n$reply = $chatbot-\u003eask('Hello!');\necho $reply;\n```\n\n### Token \u0026 Cost Tracking\n\nMonitor API usage and optimize costs with built-in token tracking:\n\n```php\nuse Rumenx\\PhpChatbot\\PhpChatbot;\nuse Rumenx\\PhpChatbot\\Models\\OpenAiModel;\n\n$model = new OpenAiModel('your-api-key', 'gpt-4o');\n$chatbot = new PhpChatbot($model);\n\n// Make a request\n$response = $chatbot-\u003eask('Explain quantum computing');\necho $response;\n\n// Track token usage\n$usage = $chatbot-\u003egetLastTokenUsage();\necho \"Tokens used: {$usage-\u003etotalTokens}\\n\";\n\n// Calculate cost\n$cost = $chatbot-\u003egetLastCost();\necho \"Cost: $\" . number_format($cost, 4) . \"\\n\";\n\n// Estimate cost before making a request\n$estimatedCost = $chatbot-\u003eestimateCost('This is my prompt');\necho \"Estimated: $\" . number_format($estimatedCost, 6) . \"\\n\";\n```\n\nSee the **[Token \u0026 Cost Tracking Guide](https://github.com/RumenDamyanov/php-chatbot/wiki/Token-Tracking)** for budget management, cost optimization tips, and provider comparison.\n\n## Streaming Responses\n\n**php-chatbot** now supports streaming responses for real-time chat experiences! Streaming allows you to receive and display responses as they are generated, creating a more interactive user experience.\n\n### Supported Models\n\nThe following AI providers support streaming:\n\n- ✅ OpenAI (all models)\n- ✅ Anthropic Claude (all models)\n- ✅ Google Gemini (all models)\n- ✅ xAI Grok (all models)\n- ✅ Meta LLaMA (all models)\n- ✅ DeepSeek (all models)\n- ✅ Ollama (all models)\n\n### Basic Streaming Example\n\n```php\nuse Rumenx\\PhpChatbot\\PhpChatbot;\nuse Rumenx\\PhpChatbot\\Models\\OpenAiModel;\n\n$model = new OpenAiModel('your-api-key');\n$chatbot = new PhpChatbot($model);\n\n// Get streaming response\nforeach ($chatbot-\u003easkStream('Hello!') as $chunk) {\n    echo $chunk;\n    flush(); // Send to browser immediately\n}\n```\n\n### Backend Streaming API Example\n\nFor Server-Sent Events (SSE) streaming to frontend:\n\n```php\n// Set headers for SSE\nheader('Content-Type: text/event-stream');\nheader('Cache-Control: no-cache');\nheader('X-Accel-Buffering: no'); // Disable nginx buffering\n\n$model = ModelFactory::make($config);\n$chatbot = new PhpChatbot($model, $config);\n\n// Stream chunks to client\nforeach ($chatbot-\u003easkStream($message, $context) as $chunk) {\n    echo \"data: \" . json_encode(['chunk' =\u003e $chunk]) . \"\\n\\n\";\n    flush();\n}\n\necho \"data: [DONE]\\n\\n\";\nflush();\n```\n\n### Frontend Integration (JavaScript)\n\n```javascript\nconst eventSource = new EventSource('/api/chatbot/stream?message=' + encodeURIComponent(message));\n\neventSource.onmessage = function(event) {\n    if (event.data === '[DONE]') {\n        eventSource.close();\n        return;\n    }\n    \n    const data = JSON.parse(event.data);\n    // Append chunk to chat UI\n    chatMessageElement.textContent += data.chunk;\n};\n\neventSource.onerror = function() {\n    eventSource.close();\n};\n```\n\n### Checking Streaming Support\n\n```php\nuse Rumenx\\PhpChatbot\\Contracts\\StreamableModelInterface;\n\nif ($model instanceof StreamableModelInterface \u0026\u0026 $model-\u003esupportsStreaming()) {\n    // Use streaming\n    foreach ($chatbot-\u003easkStream($message) as $chunk) {\n        // Process chunk...\n    }\n} else {\n    // Fallback to regular response\n    $reply = $chatbot-\u003eask($message);\n}\n```\n\n\u003e 💡 **Note**: Not all models support streaming. The `DefaultAiModel` (fallback) does not support streaming. Always check if your model implements `StreamableModelInterface` before using `askStream()`.\n\n## Rate Limiting\n\n**php-chatbot** includes built-in rate limiting to prevent API abuse and control costs. Configure rate limits per user, IP, or session.\n\n### Supported Backends\n\n- ✅ **Memory** - In-memory rate limiting (default, single-server)\n- ✅ **Redis** - Distributed rate limiting (multi-server, production-ready)\n\n### Basic Usage\n\n```php\nuse Rumenx\\PhpChatbot\\PhpChatbot;\nuse Rumenx\\PhpChatbot\\Models\\OpenAiModel;\n\n$config = require 'src/Config/phpchatbot.php';\n$config['rate_limiting'] = [\n    'enabled' =\u003e true,\n    'driver' =\u003e 'memory', // or 'redis'\n    'limits' =\u003e [\n        'requests' =\u003e 10,    // 10 requests\n        'window' =\u003e 60,      // per 60 seconds\n    ],\n];\n\n$model = new OpenAiModel('your-api-key');\n$chatbot = new PhpChatbot($model, $config);\n\ntry {\n    $reply = $chatbot-\u003eask('Hello!');\n} catch (\\Rumenx\\PhpChatbot\\RateLimiting\\RateLimitException $e) {\n    // Rate limit exceeded\n    echo \"Too many requests. Try again in {$e-\u003egetRetryAfter()} seconds.\";\n}\n```\n\n### Redis Configuration\n\n```php\n$config['rate_limiting'] = [\n    'enabled' =\u003e true,\n    'driver' =\u003e 'redis',\n    'limits' =\u003e [\n        'requests' =\u003e 100,\n        'window' =\u003e 3600,  // 100 requests per hour\n    ],\n    'redis' =\u003e [\n        'host' =\u003e '127.0.0.1',\n        'port' =\u003e 6379,\n        'database' =\u003e 0,\n    ],\n];\n```\n\n\u003e 💡 **Tip**: Use Redis for production deployments with multiple servers. Memory backend is perfect for single-server setups.\n\n## Response Caching\n\nReduce API costs and improve response times with intelligent response caching.\n\n### Supported Backends\n\n- ✅ **Memory** - In-memory cache (fast, single request)\n- ✅ **File** - File-based cache (persistent, single-server)\n- ✅ **Redis** - Distributed cache (multi-server, recommended for production)\n\n### Basic Usage\n\n```php\n$config['cache'] = [\n    'enabled' =\u003e true,\n    'driver' =\u003e 'file',  // 'memory', 'file', or 'redis'\n    'ttl' =\u003e 3600,       // Cache for 1 hour\n    'path' =\u003e '/tmp/chatbot-cache',  // for file driver\n];\n\n$chatbot = new PhpChatbot($model, $config);\n\n// First call: hits API\n$reply1 = $chatbot-\u003eask('What is PHP?');\n\n// Second call: returns cached response (no API call)\n$reply2 = $chatbot-\u003eask('What is PHP?');\n```\n\n### Cache Key Generation\n\nCache keys are automatically generated based on:\n- User message (normalized)\n- Model name and configuration\n- System prompt\n- Conversation context\n\n### Redis Cache Configuration\n\n```php\n$config['cache'] = [\n    'enabled' =\u003e true,\n    'driver' =\u003e 'redis',\n    'ttl' =\u003e 7200,  // 2 hours\n    'redis' =\u003e [\n        'host' =\u003e '127.0.0.1',\n        'port' =\u003e 6379,\n        'database' =\u003e 1,\n    ],\n];\n```\n\n\u003e 💡 **Tip**: Enable caching for FAQ-style chatbots or when users ask similar questions frequently.\n\n## Health Monitoring\n\nMonitor the health of your chatbot infrastructure with built-in health checks.\n\n### Supported Health Checks\n\n- ✅ **Model Health** - AI provider availability and response time\n- ✅ **Storage Health** - Conversation memory storage (file/Redis/database)\n- ✅ **Cache Health** - Caching system availability\n\n### Basic Usage\n\n```php\nuse Rumenx\\PhpChatbot\\Health\\HealthMonitor;\nuse Rumenx\\PhpChatbot\\Health\\ModelHealthChecker;\nuse Rumenx\\PhpChatbot\\Health\\StorageHealthChecker;\nuse Rumenx\\PhpChatbot\\Health\\CacheHealthChecker;\n\n$model = new OpenAiModel('your-api-key');\n$storage = new FileStorage('/tmp/chatbot-memory');\n$cache = new MemoryCache();\n\n$monitor = new HealthMonitor();\n$monitor-\u003eregisterChecker('model', new ModelHealthChecker($model));\n$monitor-\u003eregisterChecker('storage', new StorageHealthChecker($storage));\n$monitor-\u003eregisterChecker('cache', new CacheHealthChecker($cache));\n\n// Check overall health\n$results = $monitor-\u003echeckAll();\n$overallHealth = $monitor-\u003egetOverallHealth($results);\n\necho \"System Health: {$overallHealth-\u003evalue}\\n\";\n\nforeach ($results as $name =\u003e $result) {\n    echo \"{$name}: {$result-\u003estatus-\u003evalue} \";\n    echo \"({$result-\u003emetrics['response_time']}ms)\\n\";\n    \n    if ($result-\u003emessage) {\n        echo \"  → {$result-\u003emessage}\\n\";\n    }\n}\n```\n\n### Health Status Levels\n\n- 🟢 **HEALTHY** - All systems operational\n- 🟡 **DEGRADED** - System working but with issues\n- 🔴 **UNHEALTHY** - System not functional\n\n### Integration with Monitoring Tools\n\n```php\n// HTTP endpoint for health checks\nRoute::get('/health/chatbot', function () {\n    $results = $healthMonitor-\u003echeckAll();\n    $status = $healthMonitor-\u003egetOverallHealth($results);\n    \n    return response()-\u003ejson([\n        'status' =\u003e $status-\u003evalue,\n        'checks' =\u003e array_map(fn($r) =\u003e [\n            'status' =\u003e $r-\u003estatus-\u003evalue,\n            'message' =\u003e $r-\u003emessage,\n            'metrics' =\u003e $r-\u003emetrics,\n        ], $results),\n    ], $status === HealthStatus::HEALTHY ? 200 : 503);\n});\n```\n\n\u003e 💡 **Tip**: Integrate with tools like Datadog, New Relic, or Prometheus for comprehensive monitoring.\n\n## Exception Handling\n\n**php-chatbot** provides a comprehensive exception hierarchy for precise error handling and debugging.\n\n### Exception Types\n\n```php\nuse Rumenx\\PhpChatbot\\Exceptions\\PhpChatbotException;      // Base exception\nuse Rumenx\\PhpChatbot\\Exceptions\\ApiException;            // API-related errors\nuse Rumenx\\PhpChatbot\\Exceptions\\NetworkException;        // Network/connectivity errors\nuse Rumenx\\PhpChatbot\\Exceptions\\ModelException;          // Model-specific errors\nuse Rumenx\\PhpChatbot\\Exceptions\\InvalidConfigException;  // Configuration errors\nuse Rumenx\\PhpChatbot\\Exceptions\\MemoryException;         // Memory storage errors\nuse Rumenx\\PhpChatbot\\RateLimiting\\RateLimitException;    // Rate limit errors\n```\n\n### Exception Handling Example\n\n```php\nuse Rumenx\\PhpChatbot\\Exceptions\\ApiException;\nuse Rumenx\\PhpChatbot\\Exceptions\\NetworkException;\nuse Rumenx\\PhpChatbot\\Exceptions\\RateLimitException;\n\ntry {\n    $reply = $chatbot-\u003eask($message);\n    echo $reply;\n} catch (RateLimitException $e) {\n    // User exceeded rate limit\n    http_response_code(429);\n    echo json_encode([\n        'error' =\u003e 'Too many requests',\n        'retry_after' =\u003e $e-\u003egetRetryAfter(),\n    ]);\n} catch (ApiException $e) {\n    // API error (invalid key, quota exceeded, etc.)\n    http_response_code(502);\n    echo json_encode([\n        'error' =\u003e 'AI service error',\n        'details' =\u003e $e-\u003egetMessage(),\n        'status_code' =\u003e $e-\u003egetStatusCode(),\n    ]);\n} catch (NetworkException $e) {\n    // Network/connectivity error\n    http_response_code(503);\n    echo json_encode([\n        'error' =\u003e 'Service temporarily unavailable',\n        'details' =\u003e $e-\u003egetMessage(),\n    ]);\n} catch (\\Exception $e) {\n    // Generic error\n    http_response_code(500);\n    echo json_encode(['error' =\u003e 'Internal server error']);\n}\n```\n\n### Disable Exceptions (Return Error Strings)\n\nFor backward compatibility, you can disable exception throwing:\n\n```php\n$config['throw_exceptions'] = false;\n\n$chatbot = new PhpChatbot($model, $config);\n$reply = $chatbot-\u003eask($message);\n\n// Errors will be returned as strings instead of throwing exceptions\nif (str_starts_with($reply, 'Error:')) {\n    // Handle error\n}\n```\n\n\u003e 💡 **Tip**: Keep `throw_exceptions` enabled (default) for production. Use specific catch blocks for granular error handling.\n\n## Example .env\n\n```env\n# AI Provider API Keys\nOPENAI_API_KEY=sk-...\nANTHROPIC_API_KEY=...\nGEMINI_API_KEY=...\nXAI_API_KEY=...\nMETA_API_KEY=...\nDEEPSEEK_API_KEY=...\n\n# Rate Limiting (optional)\nRATE_LIMIT_ENABLED=true\nRATE_LIMIT_DRIVER=memory  # or 'redis'\nRATE_LIMIT_REQUESTS=10\nRATE_LIMIT_WINDOW=60\n\n# Caching (optional)\nCACHE_ENABLED=true\nCACHE_DRIVER=file  # 'memory', 'file', or 'redis'\nCACHE_TTL=3600\nCACHE_PATH=/tmp/chatbot-cache\n\n# Redis Configuration (if using Redis for rate limiting or caching)\nREDIS_HOST=127.0.0.1\nREDIS_PORT=6379\nREDIS_DATABASE=0\n\n# Exception Handling (optional, default: true)\nTHROW_EXCEPTIONS=true\n```\n\n## API Endpoint Contract\n\n- **Endpoint:** `/php-chatbot/message`\n- **Request:**\n\n```json\n{ \"message\": \"Hello\" }\n```\n\n- **Response:**\n\n```json\n{ \"reply\": \"Hi! How can I help you?\" }\n```\n\n## Symfony Backend Example\n\n```php\n// src/Controller/ChatbotController.php\nnamespace App\\Controller;\n\nuse Symfony\\Bundle\\FrameworkBundle\\Controller\\AbstractController;\nuse Symfony\\Component\\HttpFoundation\\Request;\nuse Symfony\\Component\\HttpFoundation\\JsonResponse;\nuse Rumenx\\PhpChatbot\\PhpChatbot;\nuse Rumenx\\PhpChatbot\\Models\\ModelFactory;\n\nclass ChatbotController extends AbstractController\n{\n    public function message(Request $request): JsonResponse\n    {\n        $config = require $this-\u003egetParameter('kernel.project_dir').'/src/Config/phpchatbot.php';\n        $model = ModelFactory::make($config);\n        $chatbot = new PhpChatbot($model, $config);\n        $input = $request-\u003etoArray()['message'] ?? '';\n        $reply = $chatbot-\u003eask($input);\n        return $this-\u003ejson(['reply' =\u003e $reply]);\n    }\n}\n```\n\n## Testing\n\n```bash\ncomposer test\n```\n\n## Running Tests with Coverage\n\n```sh\ncomposer test\n# or for coverage with minimum threshold\n./vendor/bin/pest --coverage --min=80\n# current coverage: 80.6% ✅\n```\n\n## Static Analysis\n\n```bash\ncomposer analyze\n```\n\n## Coding Standards\n\n```bash\ncomposer style\n```\n\n## Security\n\n- Input validation and abuse prevention built-in\n- Built-in rate limiting with memory and Redis backends\n- Content filtering middleware available via config\n- Comprehensive exception handling for security monitoring\n- Configurable request throttling per user/IP/session\n\n## Rate Limiting \u0026 Abuse Prevention\n\n**php-chatbot** includes built-in rate limiting (see [Rate Limiting](#rate-limiting) section above). For additional framework-level protection, you can combine it with Laravel/Symfony middleware:\n\n### Laravel Example\n\n```php\n// routes/web.php\nRoute::post('/php-chatbot/message', function (Request $request) {\n    // ...existing code...\n})-\u003emiddleware('throttle:60,1'); // Framework-level: 60 requests per minute per IP\n```\n\n### Combined Protection (Recommended)\n\n```php\n// Framework middleware: Protects against DDoS (IP-based)\nRoute::middleware('throttle:60,1')-\u003egroup(function () {\n    // Built-in rate limiter: Protects against API abuse (user/session-based)\n    $config['rate_limiting'] = [\n        'enabled' =\u003e true,\n        'limits' =\u003e ['requests' =\u003e 10, 'window' =\u003e 60], // 10 AI calls per minute\n    ];\n});\n```\n\n\u003e 💡 **Best Practice**: Use framework middleware for broad DDoS protection and built-in rate limiting for fine-grained API cost control.\n\n## JavaScript Framework Components\n\nYou can use the provided chat popup as a plain HTML/JS snippet, or integrate a modern component for Vue, React, or Angular:\n\n- **Vue**: `resources/js/components/PhpChatbotVue.vue`\n- **React**: `resources/js/components/PhpChatbotReact.jsx`\n- **Angular**: `resources/js/components/PhpChatbotAngular.html` (with TypeScript logic)\n\n### JS Component Usage\n\n1. **Copy the component** into your app's source tree.\n2. **Import and register** it in your app (see your framework's docs).\n3. **Customize the backend endpoint** (`/php-chatbot/message`) as needed.\n4. **Build your assets** (e.g. with Vite, Webpack, or your framework's CLI).\n\n#### Example (Vue)\n\n```js\n// main.js\nimport PhpChatbotVue from './components/PhpChatbotVue.vue';\napp.component('PhpChatbotVue', PhpChatbotVue);\n```\n\n#### Example (React)\n\n```js\nimport PhpChatbotReact from './components/PhpChatbotReact.jsx';\n\u003cPhpChatbotReact /\u003e\n```\n\n#### Example (Angular)\n\n- Copy the HTML, TypeScript, and CSS into your Angular component files.\n- Register and use `\u003cphp-chatbot-angular\u003e\u003c/php-chatbot-angular\u003e` in your template.\n\n### JS Component Customization\n\n- You can style or extend the components as needed.\n- You may add your own framework component in a similar way.\n- The backend endpoint is framework-agnostic; you can point it to any PHP route/controller.\n\n## TypeScript Example (React)\n\nA modern TypeScript React chatbot component is provided as an example in `resources/js/components/PhpChatbotTs.tsx`.\n\n**How to use:**\n\n1. Copy `PhpChatbotTs.tsx` into your React app's components folder.\n2. Import and use it in your app:\n\n   ```tsx\n   import PhpChatbotTs from './components/PhpChatbotTs';\n   // ...\n   \u003cPhpChatbotTs /\u003e\n   ```\n\n3. Make sure your backend endpoint `/php-chatbot/message` is set up as described above.\n4. Style as needed (the component uses inline styles for demo purposes, but you can use your own CSS/SCSS).\n\n\u003e This component is a minimal, framework-agnostic starting point. You are encouraged to extend or restyle it to fit your app.\n\n## Backend Integration Example\n\nTo handle chat requests, add a route/controller in your backend (Laravel, Symfony, or plain PHP) that receives POST requests at `/php-chatbot/message` and returns a JSON response. Example for Laravel:\n\n```php\n// routes/web.php\nuse Illuminate\\Http\\Request;\nuse Rumenx\\PhpChatbot\\PhpChatbot;\nuse Rumenx\\PhpChatbot\\Models\\ModelFactory;\nuse Illuminate\\Support\\Facades\\Log;\n\nRoute::post('/php-chatbot/message', function (Request $request) {\n    $config = config('phpchatbot');\n    $model = ModelFactory::make($config);\n    $chatbot = new PhpChatbot($model, $config);\n    $context = [\n        'prompt' =\u003e $config['prompt'],\n        'logger' =\u003e Log::getFacadeRoot(), // Optional PSR-3 logger\n    ];\n    $reply = $chatbot-\u003eask($request-\u003einput('message'), $context);\n    return response()-\u003ejson(['reply' =\u003e $reply]);\n});\n```\n\nFor plain PHP, use:\n\n```php\n// public/php-chatbot-message.php\nrequire '../vendor/autoload.php';\nuse Rumenx\\PhpChatbot\\PhpChatbot;\nuse Rumenx\\PhpChatbot\\Models\\ModelFactory;\n$config = require '../src/Config/phpchatbot.php';\n$model = ModelFactory::make($config);\n$chatbot = new PhpChatbot($model, $config);\n$input = json_decode(file_get_contents('php://input'), true)['message'] ?? '';\n$reply = $chatbot-\u003eask($input);\nheader('Content-Type: application/json');\necho json_encode(['reply' =\u003e $reply]);\n```\n\n## Frontend Styles (SCSS)\n\nThe chat popup styles are written in modern SCSS for maintainability. You can find the source in `resources/css/chatbot.scss`.\n\nTo compile SCSS to CSS:\n\n1. **Install Sass** (if you haven't already):\n\n   ```sh\n   npm install --save-dev sass\n   ```\n\n2. **Add this script** to your `package.json`:\n\n   ```json\n   \"scripts\": {\n     \"scss\": \"sass resources/css/chatbot.scss resources/css/chatbot.css --no-source-map\"\n   }\n   ```\n\n3. **Compile SCSS**:\n\n   ```sh\n   npm run scss\n   ```\n\nOr use the Sass CLI directly:\n\n```sh\nsass resources/css/chatbot.scss resources/css/chatbot.css --no-source-map\n```\n\nTo watch for changes automatically:\n\n```sh\nsass --watch resources/css/chatbot.scss:resources/css/chatbot.css --no-source-map\n```\n\n\u003e Only commit the compiled `chatbot.css` for production/deployment. For more options, see [Sass documentation](https://sass-lang.com/documentation/cli/dart-sass).\n\n## Customizing Frontend Styles \u0026 Views (Best Practice)\n\nThe provided CSS/SCSS and view files (`resources/css/`, `resources/views/`) are **optional and basic**. They are meant as a starting point for your own implementation. **You are encouraged to build your own UI and styles on top of or instead of these defaults.**\n\n**Do not edit files directly in the `vendor/` folder or inside the package source.**\n\n### How to Safely Override Views and Styles\n\n- **Copy the provided view files** (e.g. `resources/views/popup.blade.php` or `popup.php`) into your own application's views directory. Update your app to use your custom view.\n- **Copy and modify the SCSS/CSS** (`resources/css/chatbot.scss` or `chatbot.css`) into your own asset pipeline. Import, extend, or replace as needed.\n- **For Laravel/Symfony:**\n  - Publish the package views/config (see the Installation section above) and edit the published files in your app, not in `vendor/`.\n  - Example (Laravel):\n\n    ```sh\n    php artisan vendor:publish --provider=\"Rumenx\\PhpChatbot\\Adapters\\Laravel\\PhpChatbotServiceProvider\" --tag=views\n    ```\n\n  - Example (Symfony):\n\n    ```sh\n    php bin/console chatbot:publish-views\n    ```\n\n- **For plain PHP:** Copy the view and style files to your public or template directory and reference them in your HTML.\n\n\u003e **Important:** If you edit files directly in `vendor/rumenx/php-chatbot/`, your changes will be lost on the next `composer update`. Always override or extend in your own app.\n\n### Principle\n\n- **Treat the package's frontend as a reference implementation.**\n- **Override or extend in your own codebase for all customizations.**\n- **Never edit vendor files directly.**\n\n## Configuration Best Practices\n\n**Never edit files in the `vendor/` directory.**\n\n- For Laravel: Publish the config file to your app's `config/` directory using:\n  ```sh\n  php artisan vendor:publish --provider=\"Rumenx\\PhpChatbot\\Adapters\\Laravel\\PhpChatbotServiceProvider\"\n  ```\n  Then edit `config/phpchatbot.php` in your app. This file will not be overwritten by package updates.\n\n- For Symfony: Use the provided command to publish config to your app's config directory, then edit as needed.\n\n- For plain PHP or other frameworks: **Use an environment variable to point to your own config file.**\n\n  1. Copy `src/Config/phpchatbot.php` to a safe location in your project (e.g., `config/phpchatbot.php`).\n  2. Set the environment variable in your `.env` or server config:\n     ```env\n     PHPCHATBOT_CONFIG_PATH=/path/to/your/config/phpchatbot.php\n     ```\n  3. In your bootstrap or controller, load config like this:\n     ```php\n     $configPath = getenv('PHPCHATBOT_CONFIG_PATH') ?: __DIR__ . '/../vendor/rumenx/php-chatbot/src/Config/phpchatbot.php';\n     $config = require $configPath;\n     ```\n\n- **Always use environment variables for secrets and API keys.**\n- **Never edit or commit changes to files in `vendor/`.**\n- **Document your custom config location for your team.**\n\n**Example usage in a plain PHP project:**\n\n```php\n$configPath = getenv('PHPCHATBOT_CONFIG_PATH') ?: __DIR__ . '/../vendor/rumenx/php-chatbot/src/Config/phpchatbot.php';\n$config = require $configPath;\n$model = ModelFactory::make($config);\n$chatbot = new PhpChatbot($model, $config);\n```\n\n\u003e This approach ensures your configuration is safe from being overwritten during package updates and is easy to manage in any deployment environment.\n\n## Best Practices\n\n- Never edit files in `vendor/`\n- Always copy views/styles to your own app before customizing\n- Use environment variables for secrets\n- Use the provided JS/TS components as a starting point, not as production code\n- Keep your customizations outside the package directory for upgrade safety\n\n## Quality \u0026 Standards\n\n**php-chatbot** is built to production-grade standards:\n\n### ✅ Code Quality\n- **Strict Types**: `declare(strict_types=1)` in all PHP files for maximum type safety\n- **PSR-12**: Follows PSR-12 coding standards (Symfony style)\n- **PHPStan Level MAX**: Static analysis at the highest level (9) with zero errors\n- **PHPCS**: Automated code style checking and enforcement\n\n### ✅ Testing\n- **540+ Tests**: Comprehensive test suite using Pest PHP\n- **80.6% Coverage**: Production-grade code coverage\n- **CI/CD**: Automated testing on GitHub Actions (multiple PHP versions)\n- **Edge Cases**: Extensive testing of error conditions and edge cases\n\n### ✅ Architecture\n- **SOLID Principles**: Clean, maintainable, and extensible code\n- **Interface-Driven**: Model abstraction via contracts\n- **Factory Pattern**: Easy model instantiation and configuration\n- **Dependency Injection**: Testable and flexible design\n\n### ✅ Production-Ready\n- **Error Handling**: Comprehensive exception hierarchy\n- **Rate Limiting**: Built-in request throttling\n- **Response Caching**: Intelligent caching to reduce costs\n- **Health Monitoring**: System health checks and observability\n- **Logging**: PSR-3 logger support for debugging and monitoring\n\n\u003e 💡 **Philosophy**: Simple to start, powerful in production. No compromises on code quality.\n\n## What's Included\n\n| Feature                | Location/Example                                 | Optional/Required |\n|------------------------|--------------------------------------------------|-------------------|\n| PHP Core Classes       | `src/`                                           | Required          |\n| Laravel Adapter        | `src/Adapters/Laravel/`                          | Optional          |\n| Symfony Adapter        | `src/Adapters/Symfony/`                          | Optional          |\n| Config File            | `src/Config/phpchatbot.php`                      | Required          |\n| Blade/PHP Views        | `resources/views/`                               | Optional          |\n| CSS/SCSS               | `resources/css/chatbot.scss`/`chatbot.css`       | Optional          |\n| JS/TS Components       | `resources/js/components/`                       | Optional          |\n| Example .env           | `.env.example`                                   | Optional          |\n| Tests                  | `tests/`                                         | Optional          |\n\n## Chat Message Filtering Middleware\n\nThe package includes a configurable chat message filtering middleware to help ensure safe, appropriate, and guideline-aligned AI responses. This middleware:\n\n- Filters and optionally rephrases user-submitted messages before they reach the AI model.\n- Appends hidden system instructions (not visible in chat history) to the AI context, enforcing safety and communication guidelines.\n- All filtering rules (profanities, aggression patterns, link regex) and system instructions are fully configurable in `src/Config/phpchatbot.php`.\n\n**Example configuration:**\n\n```php\n'message_filtering' =\u003e [\n    'instructions' =\u003e [\n        'Avoid sharing external links.',\n        'Refrain from quoting controversial sources.',\n        'Use appropriate language.',\n        'Reject harmful or dangerous requests.',\n        'De-escalate potential conflicts and calm aggressive or rude users.',\n    ],\n    'profanities' =\u003e ['badword1', 'badword2'],\n    'aggression_patterns' =\u003e ['hate', 'kill', 'stupid', 'idiot'],\n    'link_pattern' =\u003e '/https?:\\/\\/[\\w\\.-]+/i',\n],\n```\n\n**Example usage in your controller or chat service:**\n\n```php\nuse Rumenx\\PhpChatbot\\Middleware\\ChatMessageFilterMiddleware;\n\n$config = require 'src/Config/phpchatbot.php';\n$filterCfg = $config['message_filtering'] ?? [];\n$middleware = new ChatMessageFilterMiddleware(\n    $filterCfg['instructions'] ?? [],\n    $filterCfg['profanities'] ?? [],\n    $filterCfg['aggression_patterns'] ?? [],\n    $filterCfg['link_pattern'] ?? ''\n);\n\n// Before sending to the AI model:\n$filtered = $middleware-\u003ehandle($userMessage, $context);\n$reply = $chatbot-\u003eask($filtered['message'], $filtered['context']);\n```\n\n**Purpose:**\n- Promotes safe, respectful, and effective communication.\n- Prevents misuse, abuse, and unsafe outputs.\n- All rules are transparent and configurable—no hidden censorship or manipulation.\n\n## Questions \u0026 Support\n\nFor questions, issues, or feature requests, please use the [GitHub Issues](https://github.com/RumenDamyanov/php-chatbot/issues) page.\n\nFor security vulnerabilities, please see our [Security Policy](SECURITY.md).\n\n## Contributing\n\nSee [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines on how to contribute.\n\n## Code of Conduct\n\nThis project adheres to a Code of Conduct to ensure a welcoming and inclusive environment for all contributors. See [CODE_OF_CONDUCT.md](CODE_OF_CONDUCT.md) for details.\n\n## Support the Project\n\nIf you find this project helpful, consider supporting its development. See [FUNDING.md](FUNDING.md) for ways to contribute.\n\n## Changelog\n\nSee [CHANGELOG.md](CHANGELOG.md) for a detailed history of changes and releases.\n\n## License\n\nMIT. See [LICENSE.md](LICENSE.md).\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Frumendamyanov%2Fphp-chatbot","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Frumendamyanov%2Fphp-chatbot","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Frumendamyanov%2Fphp-chatbot/lists"}