This guide walks you through setting up and using the Multi-Agent AI Executive System in your Laravel application.
All code has been generated and ready to use. No additional dependencies need to be installed beyond what Laravel provides.
Migrations:
database/migrations/2026_04_02_000001_create_agents_table.phpdatabase/migrations/2026_04_02_000002_create_agent_knowledge_table.phpdatabase/migrations/2026_04_02_000003_create_agent_chats_table.php
Models:
app/Models/Agent.php- Main AI agent modelapp/Models/AgentKnowledge.php- Knowledge base entriesapp/Models/AgentChat.php- Chat history- Updated:
app/Models/Merchant.phpwith agent relationships
Services:
app/Services/OpenRouterService.php- OpenRouter API integration
Controllers:
app/Http/Controllers/Merchant/AgentController.php- Agent managementapp/Http/Controllers/Merchant/AiChatController.php- Chat interface
Policies:
app/Policies/AgentPolicy.php- Authorization
Routes:
- Updated:
routes/merchant.phpwith agent and chat routes
Views:
resources/views/merchant/agents/index.blade.php- Agent listingresources/views/merchant/agents/create.blade.php- Create agent formresources/views/merchant/chat/index.blade.php- Chat interface
Configuration:
- Updated:
config/services.phpwith OpenRouter config
- Visit OpenRouter.io
- Sign up for a free account
- Navigate to API Keys section
- Copy your API key
Edit your .env file and add:
OPENROUTER_API_KEY=your-actual-api-key-herephp artisan migrateThis creates the following tables:
agents- AI agents with system promptsagent_knowledge- Training data for agentsagent_chats- Chat history
CREATE TABLE agents (
id BIGINT PRIMARY KEY,
merchant_id BIGINT FOREIGN KEY,
parent_id BIGINT FOREIGN KEY (self-referencing),
name VARCHAR(255),
role ENUM('CEO', 'CMO', 'CFO', 'CTO', 'HR', 'CUSTOM'),
system_prompt LONGTEXT,
model_name VARCHAR(255),
enabled_tools JSON,
settings JSON,
is_active BOOLEAN,
priority INT,
avatar_url VARCHAR(255) NULLABLE,
description TEXT NULLABLE,
timestamps
);CREATE TABLE agent_knowledge (
id BIGINT PRIMARY KEY,
agent_id BIGINT FOREIGN KEY,
data_type ENUM('text', 'file', 'url', 'context'),
title VARCHAR(255) NULLABLE,
content LONGTEXT,
source_url VARCHAR(255) NULLABLE,
file_path VARCHAR(255) NULLABLE,
usage_count INT,
is_active BOOLEAN,
timestamps
);CREATE TABLE agent_chats (
id BIGINT PRIMARY KEY,
merchant_id BIGINT FOREIGN KEY,
agent_id BIGINT FOREIGN KEY,
user_id BIGINT FOREIGN KEY NULLABLE,
sender_role ENUM('user', 'assistant'),
message LONGTEXT,
metadata JSON NULLABLE,
session_id VARCHAR(255) NULLABLE,
timestamps
);// In controller or console
$merchant = Merchant::find(1);
$agent = $merchant->agents()->create([
'name' => 'Chief Marketing Officer',
'role' => 'CMO',
'system_prompt' => 'You are the CMO responsible for marketing strategy...',
'model_name' => 'meta-llama/llama-3-8b-instruct:free',
'enabled_tools' => ['facebook', 'twitter', 'google_analytics'],
'settings' => [
'temperature' => 0.7,
'max_tokens' => 1024,
],
'is_active' => true,
]);$agent->knowledge()->create([
'title' => 'Company Brand Guidelines',
'data_type' => 'text',
'content' => 'Our brand colors are... Our tone is...',
]);$service = new OpenRouterService();
$service->setAgent($agent);
$result = $service->chat(
'How should we market our new product?',
session()->getId()
);
if ($result['success']) {
echo $result['message']; // AI response
}if ($agent->hasToolAccess('facebook')) {
// Agent can post to Facebook
}// CEO can delegate to CMO
$cmoAgent = $ceoAgent->delegateTo('CMO');- Route:
GET /merchant/agents - Response: Paginated list of agents
- Route:
POST /merchant/agents - Body:
{ "name": "Agent Name", "role": "CMO", "system_prompt": "Instructions...", "parent_id": null, "enabled_tools": ["facebook", "twitter"], "model_name": "meta-llama/llama-3-8b-instruct:free" }
- Route:
GET /merchant/agents/{agent} - Response: Agent details with relationships
- Route:
PUT /merchant/agents/{agent} - Body: Same as create
- Route:
POST /merchant/agents/{agent}/knowledge - Body:
{ "title": "Knowledge Title", "data_type": "text", "content": "The actual knowledge content" }
- Route:
POST /merchant/agents/{agent}/test - Body:
{"message": "Hello agent"}
- Route:
POST /merchant/chat/agents/{agent}/message - Body:
{ "message": "Your message here", "session_id": "optional-session-id" } - Response:
{ "success": true, "message": "AI response text", "session_id": "uuid", "chat_id": 123 }
- Route:
GET /merchant/chat/agents/{agent}/history?session_id=abc&limit=20
- Route:
GET /merchant/chat/agents/{agent}/sessions
- Route:
DELETE /merchant/chat/agents/{agent}/session - Body:
{"session_id": "uuid"}
- Route:
GET /merchant/chat/agents/{agent}/stats - Response:
{ "total_messages": 45, "user_messages": 20, "assistant_messages": 25, "total_sessions": 5, "knowledge_entries": 10, "sub_agents": 3 }
Route::post('/setup-agents', function () {
$merchant = auth()->user()->merchant;
// Create CEO
$ceo = $merchant->agents()->create([
'name' => 'Alexander',
'role' => 'CEO',
'system_prompt' => '''
You are Alexander, the CEO of this company.
Your role is to:
- Oversee all business operations
- Make strategic decisions
- Delegate tasks to department heads
- Report to the board
You can delegate to your team members (CMO, CFO, CTO, etc.)
''',
'enabled_tools' => ['email', 'google_calendar'],
'is_active' => true,
]);
// Create CMO sub-agent
$cmo = $merchant->agents()->create([
'name' => 'Maria',
'role' => 'CMO',
'parent_id' => $ceo->id,
'system_prompt' => '''
You are Maria, the Chief Marketing Officer.
You report to the CEO and manage marketing strategy.
''',
'enabled_tools' => ['facebook', 'twitter', 'linkedin', 'google_analytics'],
'is_active' => true,
]);
// Create CFO sub-agent
$cfo = $merchant->agents()->create([
'name' => 'James',
'role' => 'CFO',
'parent_id' => $ceo->id,
'system_prompt' => '''
You are James, the Chief Financial Officer.
You report to the CEO and manage company finances.
''',
'enabled_tools' => ['email', 'google_sheets'],
'is_active' => true,
]);
return response()->json(['success' => true, 'message' => 'Team created!']);
});$agent = Agent::find(1);
// Add company knowledge
$agent->knowledge()->createMany([
[
'title' => 'Company History',
'data_type' => 'text',
'content' => 'Founded in 2020, our company specializes in...',
],
[
'title' => 'Product Catalog',
'data_type' => 'url',
'source_url' => 'https://example.com/products',
],
[
'title' => 'Marketing Guidelines',
'data_type' => 'text',
'content' => 'Our brand voice is friendly and professional...',
],
]);// Frontend JavaScript
async function askAgentAboutMarketing() {
const agentId = 2; // CMO agent
// Create session
let sessionId = await createChatSession(agentId);
// Send first message
let response1 = await sendChatMessage(agentId, {
message: "What's our current marketing strategy?",
session_id: sessionId
});
console.log(response1.message); // AI response
// Ask follow-up
let response2 = await sendChatMessage(agentId, {
message: "Can you suggest a social media campaign?",
session_id: sessionId
});
console.log(response2.message);
// Get conversation history
let history = await getChatHistory(agentId, sessionId);
console.log(history);
}
function createChatSession(agentId) {
return fetch(`/merchant/chat/agents/${agentId}/session`, {
method: 'POST',
headers: {
'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
}
}).then(r => r.json()).then(d => d.session_id);
}
function sendChatMessage(agentId, data) {
return fetch(`/merchant/chat/agents/${agentId}/message`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
},
body: JSON.stringify(data)
}).then(r => r.json());
}- Ensure
OPENROUTER_API_KEYis set in.env - Check your API key is valid at openrouter.io
- Verify your account has sufficient credits
- Check if agent is marked as
is_active = true - Verify
system_promptis not empty - Ensure agent has a valid model name
- Check if tool is in agent's
enabled_toolsarray - For sub-agents, verify parent has tool access
- Check merchant permissions
- Mark knowledge as
is_active = true - Ensure knowledge content is populated
- Check if agent can retrieve knowledge via relationships
- System Prompts: Be specific and detailed about the agent's role and expertise
- Knowledge Base: Regularly update with latest company information
- Tool Access: Only grant tools that agents actually need
- Session Management: Implement proper session cleanup for old chats
- Error Handling: Always check
successflag in API responses - Rate Limiting: OpenRouter has rate limits; implement backoff strategies
- Monitoring: Log all agent interactions for audit trails
- Models:
app/Models/ - Controllers:
app/Http/Controllers/Merchant/ - Services:
app/Services/ - Views:
resources/views/merchant/ - Migrations:
database/migrations/ - Routes:
routes/merchant.php
Created: April 2, 2026
Version: 1.0