Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Laragent Laravel Package

maestroerror/laragent

LarAgent is an open-source AI agent framework for Laravel. Build and maintain agents with an Eloquent-style API, pluggable tools (incl. MCP server support), memory/context management, multi-agent workflows, queues, and structured output for reliable integrations.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation

    composer require maestroerror/laragent
    php artisan vendor:publish --tag="laragent-config"
    

    Configure config/laragent.php with your API keys (e.g., OPENAI_API_KEY).

  2. Create Your First Agent

    php artisan make:agent CustomerSupportAgent
    

    Edit the generated agent class (app/AiAgents/CustomerSupportAgent.php):

    class CustomerSupportAgent extends Agent {
        protected $model = 'gpt-4';
        protected $history = \LarAgent\History\CacheChatHistory::class;
    
        public function instructions() {
            return "Handle customer support queries with empathy and precision.";
        }
    
        #[Tool('Fetch customer order details')]
        public function getOrderDetails($orderId) {
            return Order::find($orderId)->toArray();
        }
    }
    
  3. First Interaction

    $response = CustomerSupportAgent::forUser(auth()->user())
        ->respond("How do I track my order #12345?");
    

Where to Look First

  • Documentation: docs.laragent.ai (API reference, event system, tooling).
  • Artisan Commands: make:agent, make:tool (for standalone tools).
  • Events: BeforeAgentExecution, AfterToolExecution (in app/Providers/EventServiceProvider.php).

Implementation Patterns

Core Workflows

  1. Agent Lifecycle

    // Initialize with custom config
    $agent = new CustomerSupportAgent([
        'temperature' => 0.3,
        'tools' => ['getOrderDetails', 'checkInventory']
    ]);
    
    // Execute with context
    $response = $agent->respond("What's my delivery status?", [
        'user' => auth()->user(),
        'order_id' => 12345
    ]);
    
  2. Tool Integration

    • Method-based tools (auto-discovered via #[Tool] attribute):
      #[Tool('Validate email address')]
      public function validateEmail($email) {
          return validator()->make(['email' => $email], ['email' => 'required|email'])->passes();
      }
      
    • Class-based tools (via Tool facade):
      use LarAgent\Tool;
      
      Tool::make('SendEmail', SendEmailService::class);
      
  3. Multi-Agent Workflows

    // Chain agents sequentially
    $workflow = new AgentWorkflow();
    $workflow->add(CustomerSupportAgent::class)
             ->add(AnalyticsAgent::class)
             ->execute("Analyze customer feedback for order #12345");
    
  4. Memory Management

    • Per-user history:
      $agent->forUser($user)->respond("..."); // Uses `CacheChatHistory` by default
      
    • Custom history storage:
      protected $history = \LarAgent\History\DatabaseChatHistory::class;
      

Integration Tips

  • API Exposure: Use LarAgent\Api\AgentController for REST endpoints:
    Route::post('/agents/{agent}/chat', [AgentController::class, 'chat']);
    
  • Event Listeners: Hook into agent execution:
    Event::listen(AfterAgentExecution::class, function ($event) {
        Analytics::logAgentInteraction($event->agent, $event->response);
    });
    
  • Testing: Mock agents with LarAgent\Testing\AgentFakes:
    $fakeAgent = Agent::fake();
    $fakeAgent->shouldRespondWith("Mocked response");
    

Gotchas and Tips

Pitfalls

  1. Tool Execution Quirks

    • Parallel calls: Disable with $parallelToolCalls = false if tools have side effects.
    • Tool arguments: Validate inputs in tools to avoid malformed API calls:
      #[Tool('Update user profile')]
      public function updateProfile(array $data) {
          if (!array_key_exists('email', $data)) {
              throw new \InvalidArgumentException("Email is required");
          }
          // ...
      }
      
  2. Rate Limiting

    • Configure default_truncation_threshold in providers to avoid token overflows.
    • Use LarAgent\Drivers\RateLimitedDriver for API key rotation.
  3. Event Order

    • BeforeAgentExecution fires before BeforeToolExecution. Override carefully to avoid infinite loops.
  4. Provider Fallbacks

    • Multi-provider arrays (e.g., ['default', 'gemini']) require all providers to support the same tools.

Debugging Tips

  • Log Tool Calls: Enable debug mode in config/laragent.php:
    'debug' => env('APP_DEBUG', false),
    
  • Inspect Responses: Use dd($agent->lastResponse()) to debug structured outputs.
  • Chat History: Dump history with:
    dd($agent->getHistory()->getMessages());
    

Extension Points

  1. Custom Drivers Override LarAgent\Drivers\DriverInterface for new LLM providers:

    class CustomDriver implements DriverInterface {
        public function generate($prompt, array $options) {
            // ...
        }
    }
    

    Register in config/laragent.php:

    'providers' => [
        'custom' => [
            'driver' => \App\Drivers\CustomDriver::class,
            // ...
        ],
    ]
    
  2. Memory Plugins Extend LarAgent\History\ChatHistoryInterface for custom storage (e.g., Redis):

    class RedisChatHistory implements ChatHistoryInterface {
        public function save($key, array $messages) {
            Redis::hSet('laragent:history', $key, json_encode($messages));
        }
        // ...
    }
    
  3. Tool Validation Use #[Tool(validate: true)] to auto-validate arguments via Laravel’s validator:

    #[Tool('Create invoice', validate: true)]
    public function createInvoice(array $data) {
        // $data is pre-validated
    }
    

Pro Tips

  • Agent Caching: Cache frequent responses with LarAgent\Cache\AgentCache:
    $agent->cacheResponses(60); // Cache for 60 seconds
    
  • Multi-Modal Input: Handle images/files via LarAgent\Input\MultiModalInput:
    $response = $agent->respondWithFiles("Analyze this image", $imagePath);
    
  • Structured Output: Force JSON responses:
    protected $outputFormat = 'json';
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope