Skip to content

Latest commit

 

History

History
481 lines (385 loc) · 11.4 KB

File metadata and controls

481 lines (385 loc) · 11.4 KB

Multi-Agent AI Executive System - Setup Guide

This guide walks you through setting up and using the Multi-Agent AI Executive System in your Laravel application.

📋 Table of Contents

  1. Installation
  2. Configuration
  3. Database
  4. Usage
  5. API Reference
  6. Examples

Installation

All code has been generated and ready to use. No additional dependencies need to be installed beyond what Laravel provides.

Files Created:

Migrations:

  • database/migrations/2026_04_02_000001_create_agents_table.php
  • database/migrations/2026_04_02_000002_create_agent_knowledge_table.php
  • database/migrations/2026_04_02_000003_create_agent_chats_table.php

Models:

  • app/Models/Agent.php - Main AI agent model
  • app/Models/AgentKnowledge.php - Knowledge base entries
  • app/Models/AgentChat.php - Chat history
  • Updated: app/Models/Merchant.php with agent relationships

Services:

  • app/Services/OpenRouterService.php - OpenRouter API integration

Controllers:

  • app/Http/Controllers/Merchant/AgentController.php - Agent management
  • app/Http/Controllers/Merchant/AiChatController.php - Chat interface

Policies:

  • app/Policies/AgentPolicy.php - Authorization

Routes:

  • Updated: routes/merchant.php with agent and chat routes

Views:

  • resources/views/merchant/agents/index.blade.php - Agent listing
  • resources/views/merchant/agents/create.blade.php - Create agent form
  • resources/views/merchant/chat/index.blade.php - Chat interface

Configuration:

  • Updated: config/services.php with OpenRouter config

Configuration

1. Get OpenRouter API Key

  1. Visit OpenRouter.io
  2. Sign up for a free account
  3. Navigate to API Keys section
  4. Copy your API key

2. Update .env File

Edit your .env file and add:

OPENROUTER_API_KEY=your-actual-api-key-here

3. Run Migrations

php artisan migrate

This creates the following tables:

  • agents - AI agents with system prompts
  • agent_knowledge - Training data for agents
  • agent_chats - Chat history

Database

Agents Table

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
);

Agent Knowledge Table

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
);

Agent Chats Table

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
);

Usage

Creating an Agent

// 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,
]);

Adding Knowledge Base

$agent->knowledge()->create([
    'title' => 'Company Brand Guidelines',
    'data_type' => 'text',
    'content' => 'Our brand colors are... Our tone is...',
]);

Chatting with an Agent

$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
}

Checking Tool Access

if ($agent->hasToolAccess('facebook')) {
    // Agent can post to Facebook
}

Agent-to-Agent Delegation

// CEO can delegate to CMO
$cmoAgent = $ceoAgent->delegateTo('CMO');

API Reference

AgentController

List Agents

  • Route: GET /merchant/agents
  • Response: Paginated list of agents

Create Agent

  • 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"
    }

View Agent

  • Route: GET /merchant/agents/{agent}
  • Response: Agent details with relationships

Update Agent

  • Route: PUT /merchant/agents/{agent}
  • Body: Same as create

Add Knowledge

  • Route: POST /merchant/agents/{agent}/knowledge
  • Body:
    {
      "title": "Knowledge Title",
      "data_type": "text",
      "content": "The actual knowledge content"
    }

Test Agent

  • Route: POST /merchant/agents/{agent}/test
  • Body: {"message": "Hello agent"}

AiChatController

Send Message

  • 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
    }

Get History

  • Route: GET /merchant/chat/agents/{agent}/history?session_id=abc&limit=20

Get Sessions

  • Route: GET /merchant/chat/agents/{agent}/sessions

Delete Session

  • Route: DELETE /merchant/chat/agents/{agent}/session
  • Body: {"session_id": "uuid"}

Get Stats

  • 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
    }

Examples

Example 1: Create a CEO Agent

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!']);
});

Example 2: Train an Agent

$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...',
    ],
]);

Example 3: Chat Flow

// 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());
}

Troubleshooting

OpenRouter API Error

  • Ensure OPENROUTER_API_KEY is set in .env
  • Check your API key is valid at openrouter.io
  • Verify your account has sufficient credits

Agent Not Responding

  • Check if agent is marked as is_active = true
  • Verify system_prompt is not empty
  • Ensure agent has a valid model name

Tool Access Denied

  • Check if tool is in agent's enabled_tools array
  • For sub-agents, verify parent has tool access
  • Check merchant permissions

Knowledge Not Being Used

  • Mark knowledge as is_active = true
  • Ensure knowledge content is populated
  • Check if agent can retrieve knowledge via relationships

Best Practices

  1. System Prompts: Be specific and detailed about the agent's role and expertise
  2. Knowledge Base: Regularly update with latest company information
  3. Tool Access: Only grant tools that agents actually need
  4. Session Management: Implement proper session cleanup for old chats
  5. Error Handling: Always check success flag in API responses
  6. Rate Limiting: OpenRouter has rate limits; implement backoff strategies
  7. Monitoring: Log all agent interactions for audit trails

Support Files Location

  • 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