sentix / ai-chatbot
Smart, multi-provider AI chatbot widget package with automatic Eloquent context extraction for Laravel.
Requires
- php: ^8.0|^8.1|^8.2|^8.3|^8.4
- illuminate/http: ^9.0|^10.0|^11.0|^12.0|^13.0
- illuminate/support: ^9.0|^10.0|^11.0|^12.0|^13.0
README
A lightweight, framework-agnostic (zero Tailwind/Bootstrap dependency), driver-architected AI Chatbot widget for Laravel with real-time SSE streaming, automatic Eloquent context extraction, SaaS Multi-Tenant settings resolution, Provider Auto-Failover switching, RAG relevance ranking, Quick Action Chips, Text-to-Speech, IndexedDB persistence, Function Calling Tools, built-in rate limiting, and zero-scrollbar modern UI.
🆕 What's New in v1.5.0
- 🏢 SaaS Multi-Tenant Database Settings Resolution: Automatically checks
setting('gemini_api_key'),setting('gemini_model'),setting('active_provider')for multi-tenant SaaS apps before falling back to Laravelconfig(). - 🔄 Provider Auto-Failover Switching (Max 3 Attempts): If active AI provider returns quota limits (HTTP 429) or errors, the chatbot automatically switches to the next configured fallback provider seamlessly.
- 🛡️ User-Facing Clean Fallback Error Message: Raw 429 status codes or API provider names are hidden from end-users; friendly fallback string displayed while full technical details are logged to
storage/logs/ai-chatbot.log.
🌟 Key Features
- 🏗️ Driver-Based Architecture (
AiDriverInterface): Drivers are decoupled inSentix\AiChatbot\Drivers\. Easily extend and add custom LLM drivers! - 🤖 7 Built-in AI Drivers: Google Gemini, OpenAI ChatGPT, Anthropic Claude, DeepSeek, Groq, Mistral, Perplexity.
- ⚡ Response Cache Management: Built-in caching support to save API costs and speed up response times.
- 🧩 Trait Driven Context Extraction (
HasAiContext): Adduse HasAiContext;to any Eloquent model and defineprotected $aiFields = ['field1', 'field2'];. - 🔗 Automatic Relationship Traversal: Automatically detects and extracts nested related models if they also use the
HasAiContexttrait. - 🎨 Framework Agnostic Styling: Built with custom, self-contained CSS. Works in any application regardless of whether it uses Tailwind, Bootstrap, or plain HTML.
🚀 Installation & Setup
1. Add Repository to composer.json
Add the local package path to your main Laravel application's composer.json:
"repositories": [ { "type": "path", "url": "../plugins/AiChatbot" } ]
Then run:
composer require sentix/ai-chatbot:@dev
2. Publish Configuration & Assets
Publish configuration file and static assets:
# Publish configuration file php artisan vendor:publish --tag=ai-chatbot-config # Publish frontend assets (CSS/JS) php artisan vendor:publish --tag=ai-chatbot-assets
3. Add Widget to Blade Views
Render the chatbot widget in your main layout file (e.g., resources/views/layouts/app.blade.php) right before </body>:
<!-- Blade Component Syntax (Recommended) --> <x-ai-chatbot /> <!-- Or with Custom Props --> <x-ai-chatbot name="Support Assistant" primary-color="#6366f1" secondary-color="#9333ea" /> <!-- Or Blade Directive Syntax --> @aiChatbotWidget
🧩 Eloquent Context Extraction & Relationships (HasAiContext)
The package automatically extracts Eloquent model data and relationship hierarchies to provide live database context to the AI Chatbot.
1. Add Trait to your Eloquent Models
Add Sentix\AiChatbot\Traits\HasAiContext trait to any Eloquent model and define the $aiFields property to specify which database columns the AI is allowed to see:
namespace App\Models; use Illuminate\Database\Eloquent\Model; use Sentix\AiChatbot\Traits\HasAiContext; class Product extends Model { use HasAiContext; // Define fields exposed to the AI chatbot (defaults to $fillable if not set) protected $aiFields = ['id', 'name', 'price', 'description', 'in_stock']; // Relationships are automatically detected if the related model ALSO uses HasAiContext! public function category() { return $this->belongsTo(Category::class); } public function reviews() { return $this->hasMany(Review::class); } }
2. Enable Trait on Related Models (Relationship Traversal)
When the package queries Product, it scans all relationship methods (category, reviews). If the related model (Category or Review) also uses HasAiContext, relationship data is automatically nested into the AI context prompt!
namespace App\Models; use Illuminate\Database\Eloquent\Model; use Sentix\AiChatbot\Traits\HasAiContext; class Category extends Model { use HasAiContext; protected $aiFields = ['id', 'name', 'slug']; }
3. Register Models in config/ai-chatbot.php
List all top-level Eloquent models in config/ai-chatbot.php under context_models:
'context_models' => [ \App\Models\Product::class, \App\Models\Category::class, \App\Models\Order::class, ],
4. User-Scoped Data Filtering (Multi-Tenant / Personal Data)
If your app requires the AI chatbot to only answer questions about the currently logged-in user's data (e.g. "Show my orders"):
- Enable user scoping in
.env:AI_CHATBOT_CONTEXT_USER_SCOPED=true
- The package will automatically filter records matching
user_id == auth()->id(), or you can define a customscopeUserScoped($query, $userId)scope on your model:
public function scopeUserScoped($query, $userId) { return $query->where('customer_id', $userId); }
5. Custom Knowledge Base & Static App Guides (custom_context)
You can define custom static knowledge base arrays, feature FAQs, menu navigation guides, or form filling instructions in config/ai-chatbot.php under custom_context:
'custom_context' => [ 'How to add products' => 'Go to Admin > Products > Click Add Product. Fill in Name, Price, SKU, and Category.', 'Menu Navigation' => 'Header menu includes Dashboard, Inventory, Orders, Finance, and Settings.', 'Finance Guide' => 'In Finance tab, you can view total income, expenses, and pending invoices.', ],
🛠️ Registering Custom AI Tools (Function Calling)
You can register custom PHP tools implementing Sentix\AiChatbot\Contracts\AiToolInterface:
use Sentix\AiChatbot\Contracts\AiToolInterface; use Sentix\AiChatbot\Tools\AiToolRegistry; class GetOrderStatusTool implements AiToolInterface { public function name(): string { return 'get_order_status'; } public function description(): string { return 'Get live delivery status of an order using order ID.'; } public function parameters(): array { return [ 'order_id' => 'string (required)', ]; } public function execute(array $arguments): string { $orderId = $arguments['order_id'] ?? ''; return "Order #{$orderId} status: Shipped and out for delivery."; } } // Register in your AppServiceProvider: AiToolRegistry::register('get_order_status', GetOrderStatusTool::class);
🔌 Adding Custom AI Drivers
You can easily register a custom AI driver implementing Sentix\AiChatbot\Contracts\AiDriverInterface:
use Sentix\AiChatbot\Contracts\AiDriverInterface; use Sentix\AiChatbot\Drivers\AiDriverFactory; class MyCustomAiDriver implements AiDriverInterface { public function ask(string $prompt, array $chatHistory, string $systemPrompt, array $config): string { return "Response from MyCustomAiDriver"; } public function askStream(string $prompt, array $chatHistory, string $systemPrompt, array $config, \Closure $onChunk): void { $onChunk("Streaming chunk response..."); } public function testConnection(string $apiKey, string $model): bool { return true; } } // Register in your AppServiceProvider: AiDriverFactory::extend('my_custom_ai', MyCustomAiDriver::class);
⚙️ Environment Variables (.env)
AI_CHATBOT_ENABLED=true AI_CHATBOT_NAME="My AI Assistant" AI_CHATBOT_PRIMARY_COLOR="#6366f1" AI_CHATBOT_SECONDARY_COLOR="#9333ea" AI_ACTIVE_PROVIDER=gemini # Streaming & Rate Limit Settings AI_CHATBOT_STREAMING_ENABLED=true AI_CHATBOT_RATE_LIMIT_ENABLED=true AI_CHATBOT_RATE_LIMIT_MAX=20 AI_CHATBOT_RATE_LIMIT_DECAY=1 # Context Optimization AI_CHATBOT_CONTEXT_MAX_RECORDS=20 AI_CHATBOT_CONTEXT_USER_SCOPED=false AI_CHATBOT_CONTEXT_MAX_LENGTH=8000 # Cache Settings AI_CHATBOT_CACHE_ENABLED=true AI_CHATBOT_CACHE_TTL=3600 # API Keys GEMINI_API_KEY="AIzaSy..." OPENAI_API_KEY="sk-..." CLAUDE_API_KEY="sk-ant-..." DEEPSEEK_API_KEY="sk-..." GROQ_API_KEY="gsk_..." MISTRAL_API_KEY="..." PERPLEXITY_API_KEY="pplx-..."
📄 License
MIT License. Created by Sentix.