PHP code example of alidaaer / laravel-ai-agent

1. Go to this page and download the library: Download alidaaer/laravel-ai-agent library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

alidaaer / laravel-ai-agent example snippets


'widget' => [
    'theme' => 'dark',
    'rtl' => false,
    'primary_color' => '#6366f1',
    'position' => 'bottom-right',
    'system_prompt' => 'You are a helpful shop assistant.',
],

use LaravelAIAgent\Attributes\AsAITool;

class ProductService
{
    #[AsAITool]  // Description auto-generated: "List products" ✨
    public function listProducts(): array
    {
        return Product::all()->toArray();
    }

    #[AsAITool]  // Types inferred: $price→number, $stock→integer
    public function addProduct(string $name, float $price, int $stock = 0): array
    {
        return Product::create(compact('name', 'price', 'stock'))->toArray();
    }
}

// routes/api.php
Route::post('/my-chat', function () {
    $response = Agent::conversation(request('conversation_id'))
        ->system('You are a helpful shop assistant')
        ->tools([ProductService::class])
        ->chat(request('message'));

    return response()->json(['response' => $response]);
});

#[AsAITool]  // Description: "List Products" (from method name)
public function listProducts(): array { }

#[AsAITool]  // Description: "Add Product"
public function addProduct(string $name, float $price): array { }

#[AsAITool('Search for products by name or category')]
public function search(string $query): array { }

#[AsAITool(
    description: 'Update product details',
    params: [
        'id:integer' => 'Product ID to update',
        'name' => 'New product name',          // type auto-inferred as string
        'price:number' => 'New price in USD',
    ]
)]
public function updateProduct(Request $request): array
{
    $product = Product::findOrFail($request->input('id'));
    $product->update($request->only(['name', 'price']));
    return ['success' => true, 'product' => $product->toArray()];
}

#[AsAITool]
public function showProduct(int $id)
{
    return view('product.show', ['product' => Product::findOrFail($id)]);
    // AI receives: {"product": {"id": 1, "name": "iPhone", "price": 999}} ✨
}

#[AsAITool]
public function activateProduct(int $id)
{
    Product::findOrFail($id)->update(['is_active' => true]);
    return redirect()->back()->with('message', 'Product activated!');
    // AI receives: {"message": "Product activated!"} ✨
}

#[AsAITool]
public function createProduct(string $name, float $price)
{
    $validator = Validator::make(compact('name', 'price'), [
        'name' => 'er: "Product name must be at least 3 characters" 🛡️

    return Product::create(compact('name', 'price'))->toArray();
}

#[AsAITool]
public function listProducts()
{
    $products = Product::all();

    if (isAICall()) {
        return ['count' => $products->count(), 'products' => $products->toArray()];
    }

    return view('products.index', compact('products'));
}

// OpenAI (default)
Agent::driver('openai')->chat("Hello");

// Google Gemini
Agent::driver('gemini')->chat("Hello");

// Anthropic Claude
Agent::driver('anthropic')->chat("Hello");

// OpenRouter (100+ models via single API)
Agent::driver('openrouter')->model('anthropic/claude-3.5-sonnet')->chat("Hello");

// Specific model override
Agent::driver('openai')->model('gpt-4o')->chat("Hello");

// app/AI/Agents/ShopAgent.php
class ShopAgent extends BaseAgent
{
    public function instructions(): string
    {
        return 'You are a friendly shop assistant. Help customers browse and order.';
    }

    public function tools(): array
    {
        return [\App\Services\ShopService::class];
    }

    // Optional: customize driver, model, middleware, widget...
    // public function driver(): ?string { return 'openai'; }
    // public function model(): ?string { return 'gpt-4o-mini'; }
    // public function routeMiddleware(): array { return ['web', 'auth']; }
}

use App\AI\Agents\AdminAgent;

class OrderService
{
    #[AsAITool]                                        // 👈 All agents see this
    public function listOrders(): array { /* ... */ }

    #[AsAITool(agents: [AdminAgent::class])]           // 👈 Admin only
    public function deleteOrder(int $id) { /* ... */ }

    #[AsAITool(agents: [AdminAgent::class])]           // 👈 Admin only
    public function advancedStats() { /* ... */ }
}

// In any Blade view
{!! \App\AI\Agents\ShopAgent::widget() !!}
{!! \App\AI\Agents\AdminAgent::widget() !!}
<script src="/ai-agent/widget.js"></script>

class AdminAgent extends BaseAgent
{
    public function widgetConfig(): array
    {
        return [
            'title' => 'Admin AI',
            'theme' => 'light',
            'lang' => 'ar',
            'primary_color' => '#ef4444',
            'position' => 'bottom-left',
        ];
    }
}

// Conversations are remembered!
Agent::conversation('user-123')
    ->tools([OrderService::class])
    ->chat("Show my orders");

// Later...
Agent::conversation('user-123')
    ->chat("Cancel the last one");
// AI remembers the context!

// config/ai-agent.php
return [
    'default' => env('AI_AGENT_DRIVER', 'openai'),
    'verify_ssl' => env('AI_AGENT_VERIFY_SSL', false),
    
    'drivers' => [
        'openai' => [
            'api_key' => env('OPENAI_API_KEY'),
            'model' => env('OPENAI_MODEL',env('AI_AGENT_MODEL','gpt-4o-mini')),
        ],
        'anthropic' => [ /* ... */ ],
        'gemini'    => [ /* ... */ ],
        'deepseek'  => [ /* ... */ ],
        'openrouter' => [ /* ... */ ],
    ],
    
    'discovery' => [
        'paths' => [app_path()],    // Scans all app/ by default
        'cache' => true,            // Cache discovered tools
    ],

    'memory' => [
        'driver' => env('AI_AGENT_MEMORY', 'session'),
        'summarize_after' => 10,    // AI-summarize every N messages
        'max_messages' => 100,      // Hard limit — delete oldest beyond this
        'recent_messages' => 4,     // Send last N messages to LLM
        'ai_summarization' => true, // Use AI for smart summaries
    ],

    'agents' => [
        \App\AI\Agents\ShopAgent::class,
        \App\AI\Agents\AdminAgent::class,
    ],

    'security' => [
        'enabled' => true,          // All security on by default
        'max_tool_calls_per_request' => 10,
        'max_iterations' => 10,
    ],
];

use LaravelAIAgent\Events\ToolCalled;
use LaravelAIAgent\Events\ToolExecuted;

Event::listen(ToolCalled::class, function ($event) {
    Log::info("AI called: " . $event->tool['name']);
});

Event::listen(ToolExecuted::class, function ($event) {
    Log::info("Result: " . json_encode($event->result));
});

// 1️⃣ Service with tools — place anywhere in app/
class ShopService
{
    #[AsAITool]
    public function listProducts(): array {
        return Product::all()->toArray();
    }

    #[AsAITool]
    public function addProduct(string $name, float $price): array {
        return Product::create(compact('name', 'price'))->toArray();
    }
}

// 3️⃣ Drop the widget in Blade — routes are auto-registered!
{!! \App\AI\Agents\ShopAgent::widget() !!}
<script src="/ai-agent/widget.js"></script>
bash
php artisan migrate
blade
{!! \LaravelAIAgent\Widget::render(['theme' => 'light', 'lang' => 'ar']) !!}
<script src="/ai-agent/widget.js"></script>
bash
php artisan make:agent ShopAgent
php artisan make:agent AdminAgent