A dynamic AI assistant package for Laravel applications that automatically discovers schema and provides real-time AI capabilities. Works with any Laravel application without configuration!
- Dynamic Schema Discovery: Automatically analyzes your Laravel models and database structure
- AI Metadata Generation: Creates comprehensive metadata for AI consumption
- Real-time Communication: WebSocket support for instant AI responses
- Tool Discovery: Automatically creates CRUD tools for each model
- Secure Authentication: Token-based authentication with IP restrictions
- Conversation Management: Persistent chat history and context
- Extensible: Easy to add custom tools and capabilities
- Zero Configuration: Works out of the box with any Laravel app
- Production Ready: Built-in security, validation, and error handling
composer require dits-sa/laravel-ai-assistant
php artisan ai:install
<?php
// app/Models/Project.php
use LaravelAIAssistant\Traits\AICapable;
class Project extends Model
{
use AICapable;
}
php artisan ai:generate-metadata
# Get AI token
curl -X POST "http://your-app.com/api/ai/auth/token" \
-H "Authorization: Bearer YOUR_AUTH_TOKEN"
# List projects
curl -X GET "http://your-app.com/api/ai/models/project" \
-H "X-AI-Token: YOUR_AI_TOKEN"
That's it! Your Laravel app now has AI capabilities! π
composer require dits-sa/laravel-ai-assistant
composer require dits-sa/laravel-ai-assistant:dev-main
# Add repository
composer config repositories.local path ./packages/laravel-ai-assistant
# Install package
composer require dits-sa/laravel-ai-assistant:dev-main
php artisan ai:install
This will:
- Publish configuration files
- Run database migrations
- Generate initial AI metadata
<?php
use LaravelAIAssistant\Traits\AICapable;
class Project extends Model
{
use AICapable;
// Optional: Override AI methods for custom behavior
public function aiSearch(string $query, array $fields = []): Collection
{
// Custom search logic
return $this->where('name', 'like', "%{$query}%")
->orWhere('description', 'like', "%{$query}%")
->get();
}
}
Edit config/ai-assistant.php
:
'capabilities' => [
'per_model' => [
'Project' => [
'can_create' => true,
'can_update' => true,
'can_delete' => false,
],
'User' => [
'can_create' => false,
'can_delete' => false,
],
]
],
php artisan ai:generate-metadata
// config/ai-assistant.php
return [
'enabled' => true,
'api' => [
'prefix' => 'api/ai',
'middleware' => ['auth:sanctum', 'ai.security'],
'rate_limit' => '60,1',
],
'security' => [
'token_expiry' => 24, // hours
'max_requests_per_minute' => 60,
'allowed_ips' => '', // comma-separated
],
'models' => [
'exclude' => ['User', 'PasswordReset', 'Migration'],
'include_only' => [], // If specified, only these models
'custom_descriptions' => [
'Project' => 'Investment projects and properties',
]
],
'capabilities' => [
'default' => [
'can_list' => true,
'can_search' => true,
'can_create' => false,
'can_update' => false,
'can_delete' => false,
],
'per_model' => [
'Project' => ['can_create' => true, 'can_update' => true],
]
],
];
The package automatically creates dynamic API endpoints for all your models:
Method | Endpoint | Description |
---|---|---|
GET |
/api/ai/metadata |
Get AI metadata and available tools |
GET |
/api/ai/models/{modelName} |
List model records with pagination |
GET |
/api/ai/models/{modelName}/search |
Search model records |
POST |
/api/ai/models/{modelName} |
Create new model record |
PUT |
/api/ai/models/{modelName} |
Update existing model record |
DELETE |
/api/ai/models/{modelName} |
Delete model record |
GET |
/api/ai/models/{modelName}/{id} |
Get single model record |
POST |
/api/ai/auth/token |
Generate AI authentication token |
POST |
/api/ai/auth/validate |
Validate AI token |
GET |
/api/ai/conversations |
List user conversations |
POST |
/api/ai/conversations |
Create new conversation |
The package automatically discovers and creates API endpoints for any Laravel model:
- User β
/api/ai/models/user
- Project β
/api/ai/models/project
- Order β
/api/ai/models/order
- Product β
/api/ai/models/product
- Any Model β
/api/ai/models/{ModelName}
Generate an AI token:
curl -X POST /api/ai/auth/token \
-H "Authorization: Bearer YOUR_AUTH_TOKEN" \
-H "Content-Type: application/json"
Use the token for AI requests:
curl -X GET /api/ai/metadata \
-H "X-AI-Token: YOUR_AI_TOKEN" \
-H "Content-Type: application/json"
curl -X GET "/api/ai/models/project?limit=10&offset=0" \
-H "X-AI-Token: YOUR_AI_TOKEN"
curl -X GET "/api/ai/models/project/search?query=investment&limit=5" \
-H "X-AI-Token: YOUR_AI_TOKEN"
curl -X POST "/api/ai/models/project" \
-H "X-AI-Token: YOUR_AI_TOKEN" \
-H "Content-Type: application/json" \
-d '{"name": "New Project", "description": "Project description"}'
curl -X GET "/api/ai/models/project?filters[status]=active&filters[type]=investment" \
-H "X-AI-Token: YOUR_AI_TOKEN"
# List all products
curl -X GET "/api/ai/models/product?limit=20" \
-H "X-AI-Token: YOUR_AI_TOKEN"
# Search for products
curl -X GET "/api/ai/models/product/search?query=laptop&limit=10" \
-H "X-AI-Token: YOUR_AI_TOKEN"
# Create new product
curl -X POST "/api/ai/models/product" \
-H "X-AI-Token: YOUR_AI_TOKEN" \
-H "Content-Type: application/json" \
-d '{"name": "MacBook Pro", "price": 1999.99, "category": "laptops"}'
# Update product status
curl -X PUT "/api/ai/models/product" \
-H "X-AI-Token: YOUR_AI_TOKEN" \
-H "Content-Type: application/json" \
-d '{"id": 123, "status": "active"}'
# List active projects
curl -X GET "/api/ai/models/project?filters[status]=active" \
-H "X-AI-Token: YOUR_AI_TOKEN"
# Search projects by client
curl -X GET "/api/ai/models/project/search?query=client_name&fields=name,client" \
-H "X-AI-Token: YOUR_AI_TOKEN"
# Get project with relationships
curl -X GET "/api/ai/models/project?with=client,tasks&id=123" \
-H "X-AI-Token: YOUR_AI_TOKEN"
# List users with pagination
curl -X GET "/api/ai/models/user?limit=50&offset=0" \
-H "X-AI-Token: YOUR_AI_TOKEN"
# Search users by role
curl -X GET "/api/ai/models/user?filters[role]=admin" \
-H "X-AI-Token: YOUR_AI_TOKEN"
# Get user profile with relationships
curl -X GET "/api/ai/models/user?with=profile,orders&id=456" \
-H "X-AI-Token: YOUR_AI_TOKEN"
import React, { useState, useEffect } from 'react';
import { DynamicAIChat } from '@/components/AI/DynamicAIChat';
function App() {
const [showAI, setShowAI] = useState(false);
const [aiToken, setAiToken] = useState(null);
useEffect(() => {
// Get AI token when component mounts
fetchAIToken();
}, []);
const fetchAIToken = async () => {
try {
const response = await fetch('/api/ai/auth/token', {
method: 'POST',
headers: {
'Authorization': `Bearer ${authToken}`,
'Content-Type': 'application/json'
}
});
if (response.ok) {
const data = await response.json();
setAiToken(data.data.token);
}
} catch (error) {
console.error('Failed to get AI token:', error);
}
};
return (
<div>
<button
onClick={() => setShowAI(true)}
className="fixed bottom-4 right-4 bg-blue-500 text-white p-3 rounded-full shadow-lg hover:bg-blue-600"
>
π€ AI Assistant
</button>
<DynamicAIChat
isOpen={showAI}
onClose={() => setShowAI(false)}
aiToken={aiToken}
/>
</div>
);
}
<template>
<div>
<button @click="showAI = true" class="ai-button">
π€ AI Assistant
</button>
<DynamicAIChat
v-if="showAI"
:is-open="showAI"
@close="showAI = false"
:ai-token="aiToken"
/>
</div>
</template>
<script>
import DynamicAIChat from '@/components/AI/DynamicAIChat.vue';
export default {
components: {
DynamicAIChat
},
data() {
return {
showAI: false,
aiToken: null
}
},
async mounted() {
await this.fetchAIToken();
},
methods: {
async fetchAIToken() {
try {
const response = await fetch('/api/ai/auth/token', {
method: 'POST',
headers: {
'Authorization': `Bearer ${this.authToken}`,
'Content-Type': 'application/json'
}
});
if (response.ok) {
const data = await response.json();
this.aiToken = data.data.token;
}
} catch (error) {
console.error('Failed to get AI token:', error);
}
}
}
}
</script>
- Deploy AI Service to your VPS
- Configure WebSocket for real-time communication
- Set up OpenAI integration
- Connect to Laravel API
See the VPS Setup Guide for detailed instructions.
php artisan ai:generate-metadata
Options:
--output=path
- Custom output file path--format=json|yaml
- Output format--force
- Force regeneration
php artisan ai:clear-cache
Options:
--all
- Clear all AI cache--metadata
- Clear only metadata cache--tokens
- Clear only token cache
php artisan ai:install
Options:
--force
- Force installation--publish-config
- Publish config only--publish-migrations
- Publish migrations only
- Tokens are stored in cache with expiration
- IP restrictions can be configured
- Rate limiting prevents abuse
- Tokens are validated on each request
- All inputs are validated and sanitized
- SQL injection protection
- XSS protection
- CSRF protection
- Configurable rate limits per IP
- Separate limits for different operations
- Automatic blocking of abusive requests
# Run package tests
composer test
# Run specific test
php artisan test --filter=AIAssistantTest
- Metadata is cached for performance
- Configurable cache TTL
- Automatic cache invalidation
- Efficient queries with proper indexing
- Eager loading for relationships
- Pagination for large datasets
- Optimized for memory usage
- Garbage collection for large operations
- Connection pooling
- Fork the repository
- Create a feature branch
- Make your changes
- Add tests
- Submit a pull request
This package is open-sourced software licensed under the MIT license.
# Clear composer cache
composer clear-cache
# Update composer
composer update
# Check if package is installed
composer show dits-sa/laravel-ai-assistant
// Make sure you have the correct import
use LaravelAIAssistant\Traits\AICapable;
class YourModel extends Model
{
use AICapable;
}
# Check if routes are registered
php artisan route:list | grep ai
# Clear route cache
php artisan route:clear
# Check middleware configuration
php artisan config:show ai-assistant
# Clear all caches
php artisan cache:clear
php artisan config:clear
php artisan route:clear
# Regenerate metadata
php artisan ai:clear-cache --all
php artisan ai:generate-metadata --force
# Check package installation
composer show dits-sa/laravel-ai-assistant
# Test schema analysis
php artisan tinker
>>> app(\LaravelAIAssistant\Services\SchemaAnalyzer::class)->analyzeApplication()
# Test metadata generation
php artisan tinker
>>> app(\LaravelAIAssistant\Services\AIMetadataGenerator::class)->generateMetadata()
# Check configuration
php artisan config:show ai-assistant
- GitHub Issues: Report bugs and request features
- Documentation: Complete documentation
- Email Support: info@dits-sa.com
- Community: Join our Discord community
- Enable Caching: Configure Redis or Memcached for better performance
- Optimize Queries: Use eager loading for relationships
- Rate Limiting: Configure appropriate rate limits for your use case
- Database Indexing: Add indexes for frequently searched fields
A: Yes! The package automatically discovers your models and database structure, so it works with any Laravel application without configuration.
A: No! You only need to add the AICapable
trait to models you want to make available to the AI. Your existing models remain unchanged.
A: Yes! The package includes token-based authentication, rate limiting, input validation, and IP restrictions. All data is validated and sanitized.
A: Yes! You can override any AI method in your models and configure capabilities in the config file.
A: Yes! The package supports Laravel 9, 10, and 11 with PHP 8.1+.
A: Absolutely! The package is production-ready with comprehensive testing, security features, and error handling.
A: The package scans your app/Models
directory, analyzes your database schema, and automatically creates API endpoints and AI tools for each model.
A: Yes! You can define custom tools in the configuration file or override methods in your models.
- β¨ Initial Release
- π Dynamic schema discovery for any Laravel application
- π€ AI metadata generation with comprehensive descriptions
- π Dynamic API endpoints for all model operations
- π‘οΈ Security middleware with rate limiting and token validation
- π¬ Conversation management with persistent chat history
- π― AICapable trait for easy model integration
- π Artisan commands for package management
- βοΈ React frontend components for AI chat interface
- π Complete documentation and installation guides
- π§ Zero configuration - works out of the box
- π Production ready with comprehensive testing
- π Support for Laravel 9, 10, and 11
- π PHP 8.1+ support
- π MIT License
- π Zero Configuration: Works with any Laravel app instantly
- π Dynamic Discovery: Automatically finds and analyzes your data
- π‘οΈ Production Ready: Built-in security and error handling
- β‘ High Performance: Optimized for speed and memory usage
- π§ Extensible: Easy to customize and extend
- π Well Documented: Comprehensive guides and examples
- π Universal: Works with any Laravel application
- π‘ Smart: AI-powered data understanding and manipulation
Made with β€οΈ by DITS SA for the Laravel community