developer-unijaya/laravel-ai-chatbox
Installation
composer require developer-unijaya/laravel-ai-chatbox
php artisan vendor:publish --provider="DeveloperUnijaya\LaravelAiChatbox\ServiceProvider" --tag="config"
php artisan migrate
Configure .env
Add your AI provider credentials (e.g., OpenAI, Ollama):
AI_CHATBOX_PROVIDER=openai
OPENAI_API_KEY=your_key_here
Basic Usage Add the chatbox widget to a Blade view:
@chatbox
Or use the Vue component directly in a frontend framework:
<template>
<ai-chatbox />
</template>
First Interaction Trigger a chat via JavaScript:
window.aiChatbox.sendMessage("Hello, how can you help me?");
RAG Integration
ChatboxDocument model to store and embed documents for retrieval-augmented generation (RAG).
$document = new ChatboxDocument();
$document->content = "Your document content here";
$document->save();
rag_enabled=true) and query with context:
$response = AiChatbox::query("What is this document about?", ['rag' => true]);
Streaming Responses
streaming_enabled=true) and handle chunks in the frontend:
window.aiChatbox.sendMessage("Stream this response", {
onStream: (chunk) => console.log(chunk)
});
Customizing Prompts
'system_prompt' => "You are a helpful assistant for our Laravel application.",
$response = AiChatbox::query("Help me", [
'prompt' => "Act as a Laravel expert."
]);
Multi-Provider Support
AiChatbox::setProvider('ollama');
$response = AiChatbox::query("Your question");
Vue 3 Frontend Integration
<template>
<ai-chatbox @message-sent="customLogic">
<template #message="{ message }">
<div class="custom-message">{{ message.text }}</div>
</template>
</ai-chatbox>
</template>
window.aiChatbox.$on('response-received', (response) => {
// Handle response
});
Middleware for Authenticated Chats
Route::middleware(['auth'])->group(function () {
Route::post('/chat', [AiChatboxController::class, 'handle']);
});
API Rate Limits
async function sendMessage(message) {
try {
await window.aiChatbox.sendMessage(message, {
retryDelay: 1000 // ms
});
} catch (error) {
if (error.response?.status === 429) {
await new Promise(resolve => setTimeout(resolve, 1000));
sendMessage(message); // Retry
}
}
}
RAG Performance
chunk_size and overlap in config to optimize embeddings.'rag' => [
'cache_embeddings' => true,
],
Vue Component Conflicts
ai-chatbox variable conflicts with other libraries.window.laravelAiChatbox = new AiChatbox();
Ollama Local Setup
ollama serve).'ollama' => [
'endpoint' => 'http://localhost:11434',
],
Token Limits
window.aiChatbox.setMaxMessages(5); // Keep only last 5 messages
temperature and max_tokens in config to control response length.Frontend State Management
// Store messages
$user->messages()->create(['content' => $message]);
// Load messages on init
window.aiChatbox.loadMessages();
Log API Responses Enable debug mode in config:
'debug' => true,
Check Laravel logs for raw API responses.
Validate Prompts
Use AiChatbox::validatePrompt() to check for issues before sending:
if (!AiChatbox::validatePrompt("Your prompt here")) {
// Handle invalid prompt
}
Test with Mock Providers
Use the mock provider in config for local testing:
'provider' => 'mock',
Mock responses are defined in config/ai-chatbox.php under mock_responses.
Custom Providers
Extend the AiProvider interface to support new APIs:
class CustomProvider implements AiProvider {
public function generate($prompt, array $options) {
// Implement custom logic
}
}
Register the provider in the config:
'providers' => [
'custom' => \App\Providers\CustomProvider::class,
],
Webhook Integration Trigger actions via webhooks (e.g., save responses to a database):
AiChatbox::onResponse(function ($response) {
\App\Models\ChatLog::create([
'user_id' => auth()->id(),
'response' => $response['content'],
]);
});
Dynamic UI Themes Pass theme options to the Vue component:
<ai-chatbox :theme="{ primaryColor: '#3b82f6' }" />
Extend the default theme in resources/js/ai-chatbox/theme.js.
Moderation Middleware Add moderation checks before sending prompts:
AiChatbox::beforeSend(function ($prompt) {
if (str_contains(strtolower($prompt), 'inappropriate')) {
throw new \Exception("Prompt rejected.");
}
});
How can I help you explore Laravel packages today?