AI Integration
Complete guide to using LaraDashboard's AI-powered content generation with OpenAI and Claude, including configuration and the Agentic CMS command center.
AI Integration
LaraDashboard features an Agentic CMS with AI-powered content generation capabilities. This guide covers configuring AI providers, using the command center, and integrating AI into your workflows.
Overview
What is Agentic CMS?
LaraDashboard's Agentic CMS is an AI-powered command center that allows you to:
- Generate content using natural language commands
- Enhance and modify existing content
- Automate repetitive content tasks
- Get AI assistance for writing and editing
Supported Providers
| Provider | Default Model | Best For |
|---|---|---|
| OpenAI | GPT-6 Luna (gpt-6-luna) |
General content generation, image generation (DALL-E 3) |
| Anthropic | Claude 3 Haiku | Long-form content, analysis, structured output |
| Google Gemini | Gemini 2.0 Flash | Fast responses, cost-effective |
| Ollama | Llama 3.2 | Local/private deployment, no API key needed |
OpenAI models available in Settings → Integrations: GPT-6 Luna (gpt-6-luna, fast and affordable, the default) and GPT-6 Sol (gpt-6-sol, most capable). The retired GPT-4o, GPT-4 Turbo and GPT-3.5 Turbo models were removed in v1.5.0; sites that had one selected fall back to the default.
Use outside AI agents (MCP)
The command center runs AI inside the admin. To let an external agent — Claude.ai, Claude Desktop, Cursor or Claude Code — work with your site instead, turn on the built-in MCP server:
See MCP Server for setup and MCP tools for developers to add tools from your own modules.
Configuration
Admin settings
Choose the default provider, models, API keys and maximum tokens under Settings → Integrations. These values take priority over .env.
Environment Variables
.env values are fallbacks, used when a key or model isn't set in the admin:
# OpenAI
OPENAI_API_KEY=sk-...
OPENAI_MODEL=gpt-6-luna
# Anthropic (Claude)
ANTHROPIC_API_KEY=sk-ant-...
ANTHROPIC_MODEL=claude-3-haiku-20240307
# Google Gemini
GEMINI_API_KEY=...
GEMINI_MODEL=gemini-2.0-flash
# Ollama (local LLM — no API key needed)
OLLAMA_BASE_URL=http://localhost:11434
OLLAMA_MODEL=llama3.2
Config File
config/ai.php holds the provider fallbacks. Keys and models saved under Settings → Integrations take priority over these values.
<?php
return [
'openai' => [
'api_key' => env('OPENAI_API_KEY'),
'model' => env('OPENAI_MODEL', 'gpt-6-luna'),
],
'anthropic' => [
'api_key' => env('ANTHROPIC_API_KEY'),
'model' => env('ANTHROPIC_MODEL', 'claude-3-haiku-20240307'),
],
'gemini' => [
'api_key' => env('GEMINI_API_KEY'),
'model' => env('GEMINI_MODEL', 'gemini-2.0-flash'),
],
'ollama' => [
'base_url' => env('OLLAMA_BASE_URL', 'http://localhost:11434'),
'model' => env('OLLAMA_MODEL', 'llama3.2'),
],
];
Using the Command Center
Accessing the Command Center
The AI Command Center is available when editing content:
- Navigate to any post/page editor
- Click the AI Assistant button (🤖)
- The command center panel opens
Command Syntax
Enter natural language commands:
Generate a 500-word blog post about Laravel best practices
Summarize this article in 3 bullet points
Rewrite this paragraph to be more engaging
Available Commands
Content Generation
| Command | Description |
|---|---|
Generate [description] |
Create new content |
Write [description] |
Alias for generate |
Create [type] about [topic] |
Generate specific content type |
Examples:
Generate a product description for a wireless mouse
Write an introduction for a blog about AI
Create a headline for an article about climate change
Content Enhancement
| Command | Description |
|---|---|
Improve [selection] |
Enhance selected text |
Rewrite [selection] |
Rewrite in different style |
Expand [selection] |
Make content longer |
Summarize [selection] |
Create a summary |
Simplify [selection] |
Make easier to read |
Examples:
Improve the introduction paragraph
Rewrite this in a professional tone
Expand the features section
Summarize this article in 100 words
SEO Optimization
| Command | Description |
|---|---|
Generate meta description |
Create SEO description |
Suggest keywords for [topic] |
Get keyword ideas |
Optimize title for SEO |
Improve title |
Translation
| Command | Description |
|---|---|
Translate to [language] |
Translate content |
Localize for [region] |
Adapt for region |
Streaming Responses
AI responses stream in real-time for better UX:
// Response appears progressively
"Generating... ▌"
"Here is your content: Lorem ipsum... ▌"
"Here is your content: Lorem ipsum dolor sit amet..."
Programmatic Usage
AiContentGeneratorService
Use AI in your own code through App\Services\AiContentGeneratorService. It uses the default provider from Settings → Integrations unless you pick one with setProvider().
use App\Services\AiContentGeneratorService;
class ContentController extends Controller
{
public function __construct(
private AiContentGeneratorService $ai
) {}
public function generate(Request $request)
{
if (! $this->ai->isConfigured()) {
return response()->json(['message' => 'AI is not configured.'], 422);
}
// Returns the parsed result as an array (e.g. title/content for posts).
$result = $this->ai->generateContent($request->input('prompt'), 'general');
return response()->json($result);
}
}
Available Methods
// One-shot generation; $type selects the system prompt (e.g. 'general').
$result = $ai->generateContent('Write a product description for…', 'general');
// Rewrite existing text
$text = $ai->modifyText($existingContent, 'Make this more concise');
// Multi-turn chat (v1.4.5+) — OpenAI, Claude, Gemini and Ollama
$reply = $ai->chatCompletion([
['role' => 'system', 'content' => 'You are a helpful editor.'],
['role' => 'user', 'content' => 'Suggest three titles for a CRM guide.'],
], temperature: 0.7, maxTokens: 500);
// SEO title/description/keywords from page context
$seo = $ai->generateSeoMeta(['title' => $post->title, 'content' => $post->content]);
// Images (OpenAI DALL-E only)
if ($ai->canGenerateImages()) {
$image = $ai->generateImage('A clean dashboard illustration', '1792x1024');
}
// Use a specific provider: openai, claude, gemini or ollama
$result = $ai->setProvider('claude')->generateContent('Analyze this changelog…');
// Introspection
$ai->getAvailableProviders();
$ai->getDefaultProvider();
$ai->getMaxTokens();
API Endpoints
# Get available providers
GET /api/v1/ai/providers
# Generate content
POST /api/v1/ai/generate-content
{
"prompt": "Write a blog post about...",
"provider": "openai",
"options": {
"max_tokens": 1000
}
}
# Modify text (admin session route, used by the editor)
POST /admin/ai/modify-text
{
"text": "Original text here...",
"instruction": "Make it shorter"
}
# Stream generation (admin session route, used by the command center)
POST /admin/ai/command/process-stream
{
"command": "Generate article about AI",
"context": {}
}
Command Logging
Viewing Logs
All AI commands are logged for auditing:
- Navigate to Settings → AI → Command History
- View command, response, user, and timestamp
- Filter by date, user, or command type
Log Structure
// ai_command_logs table
[
'user_id' => 1,
'command' => 'Generate blog post...',
'provider' => 'openai',
'model' => 'gpt-6-luna',
'parameters' => ['max_tokens' => 1000],
'response_tokens' => 850,
'duration_ms' => 2500,
'status' => 'success',
'created_at' => '2024-01-15 10:30:00',
]
Cost Management
Token Usage
Monitor token usage:
// Get usage statistics
$stats = $aiService->getUsageStats([
'user_id' => auth()->id(),
'period' => 'month',
]);
// Returns
[
'total_tokens' => 50000,
'total_requests' => 150,
'estimated_cost' => 1.50,
]
Rate Limiting
Configure rate limits per user:
// config/ai.php
'rate_limits' => [
'default' => 20, // requests per minute
'premium' => 100, // for premium users
],
Cost Estimation
// Estimate before generating
$estimate = $aiService->estimateCost([
'prompt' => $prompt,
'max_tokens' => 1000,
]);
// Returns
[
'input_tokens' => 150,
'output_tokens' => 1000,
'estimated_cost' => 0.045,
]
Prompt Engineering
System Prompts
Configure default system prompts:
// In service or config
$systemPrompts = [
'content_writer' => "You are a professional content writer...",
'seo_expert' => "You are an SEO specialist...",
'translator' => "You are a professional translator...",
];
Context Injection
Provide context for better results by putting it in the prompt:
$context = [
'brand' => 'TechCorp',
'product_type' => 'Wireless Mouse',
'features' => ['ergonomic', 'long battery', 'multi-device'],
'tone' => 'professional',
'target_audience' => 'business professionals',
];
$result = $aiService->generateContent(
"Write a product description.\n\nContext:\n" . json_encode($context, JSON_PRETTY_PRINT),
'general'
);
Template Prompts
Create reusable prompt templates:
// Store templates
$templates = [
'blog_post' => [
'system' => 'You are a skilled blog writer...',
'template' => "Write a {length} word blog post about {topic}. Include {sections} sections. Tone: {tone}.",
],
'product_description' => [
'system' => 'You are an e-commerce copywriter...',
'template' => "Write a compelling product description for {product}. Highlight: {features}. Target audience: {audience}.",
],
];
// Use template
$result = $aiService->generateFromTemplate('blog_post', [
'length' => 800,
'topic' => 'Laravel Performance',
'sections' => 5,
'tone' => 'informative',
]);
Error Handling
Common Errors
try {
$result = $aiService->generate($params);
} catch (AiProviderException $e) {
// Provider API error
Log::error('AI Provider Error: ' . $e->getMessage());
} catch (RateLimitException $e) {
// Rate limit exceeded
return response()->json([
'error' => 'Too many requests. Please wait.',
'retry_after' => $e->retryAfter,
], 429);
} catch (InsufficientCreditsException $e) {
// No API credits
return response()->json([
'error' => 'API credits exhausted.',
], 402);
}
Fallback Providers
Configure fallback when primary fails:
// config/ai.php
'fallback' => [
'enabled' => true,
'order' => ['openai', 'claude'],
'on_errors' => ['rate_limit', 'timeout', 'server_error'],
],
Security Considerations
API Key Security
- Never commit API keys to version control
- Use environment variables
- Rotate keys periodically
- Use separate keys for production/development
Content Moderation
Enable content filtering:
// config/ai.php
'moderation' => [
'enabled' => true,
'block_categories' => ['hate', 'violence', 'sexual'],
'log_blocked' => true,
],
User Permissions
Control AI access:
// Permissions
'ai.use' // Can use AI features
'ai.settings' // Can configure AI
'ai.view_logs' // Can view command logs
Hooks
AI Hooks
use TorMorten\Eventy\Facades\Events as Eventy;
// Before AI generation
Eventy::action('ai.before_generate', function ($params, $user) {
// Log or modify params
});
// After AI generation
Eventy::action('ai.after_generate', function ($result, $params, $user) {
// Post-process result
});
// Filter AI prompt
$prompt = Eventy::filter('ai.prompt', $prompt, $context);
// Filter AI result
$content = Eventy::filter('ai.result', $content, $command);
Best Practices
Prompt Design
- Be specific and clear
- Provide context
- Specify format requirements
- Set appropriate length limits
- Include examples when helpful
Performance
- Use streaming for long content
- Cache repeated queries
- Batch similar requests
- Monitor token usage
Quality
- Review AI-generated content
- Edit and personalize
- Check facts and accuracy
- Maintain brand voice
Troubleshooting
No Response
- Check API key is valid
- Verify network connectivity
- Check rate limits
- Review error logs
Poor Quality Output
- Improve prompt specificity
- Provide more context
- Adjust temperature (lower = more focused)
- Try different model
Slow Generation
- Reduce max_tokens
- Use a faster model (GPT-6 Luna instead of GPT-6 Sol)
- Enable streaming
- Check network latency
CRM AI Capabilities
The CRM module includes extensive AI integration across all major entities:
Contact Intelligence
- Lead Scoring — Score contacts 0-100 based on profile completeness and engagement
- Data Enrichment — Enrich contact profiles with AI-inferred data
- Duplicate Detection — Fuzzy matching to find potential duplicate contacts
- Smart Segmentation — AI-powered suggestions for contact segments
- Activity Summaries — Generate narrative summaries of contact interactions
Deal Intelligence
- Deal Scoring — Health scoring and win probability for deals
- Pipeline Forecasting — Revenue predictions based on deal stages and velocity
- Stale Deal Detection — Identify deals that need attention
- Next Step Suggestions — AI recommendations for deal progression
Support Intelligence
- Ticket Categorization — Auto-categorize incoming support tickets
- Sentiment Analysis — Detect customer sentiment in ticket messages
- Reply Suggestions — AI-generated reply drafts for support agents
Campaign & Invoice AI
- Email Subject Generation — Generate high-converting subject lines
- Email Body Improvement — Enhance campaign email content
- Payment Prediction — Predict invoice payment likelihood
- Follow-up Suggestions — AI-generated follow-up email drafts
Dashboard Insights
- Daily/Weekly Digest — AI-generated summaries of CRM activity
- Dashboard Insights — Pattern detection and trend analysis
- Follow-up Recommendations — Prioritized follow-up suggestions
CRM AI features are controlled individually via Settings → CRM → AI. Each capability can be toggled on or off independently.
Adding AI to Your Module
LaraDashboard provides a modular AI architecture that any module can extend using the Capability / Action / Context pattern.
For a complete developer guide on integrating AI into your module, see:
- AI Architecture for Module Developers — Contracts, registries, implementation examples, and the CRM reference
Next Steps
- AI Architecture for Modules - Build AI-powered modules
- Content Management - Use AI in content
- Email Templates - AI for emails
- Module Development - Build custom modules
