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 Laravel framework for building and maintaining AI agents. Define agents, tools, memories, and workflows with an Eloquent-style API, structured outputs, pluggable context/memory, multi-agent orchestration with queues, and MCP tool support.

View on GitHub
Deep Wiki
Context7

Getting Started

First Steps

  1. Installation: Add LarAgent via Composer:

    composer require maestroerror/laragent
    php artisan vendor:publish --tag="laragent-config"
    
  2. Configure Providers: Update config/laragent.php with your API keys (e.g., OpenAI, Anthropic) and preferred defaults.

  3. Create Your First Agent: Generate an agent class:

    php artisan make:agent CustomerSupportAgent
    
  4. Define Agent Logic: Customize the generated agent class (app/AiAgents/CustomerSupportAgent.php) with:

    • Instructions (instructions() method)
    • Tools (annotated methods with #[Tool])
    • Provider/config overrides (e.g., $model = 'gpt-4')
  5. Test Locally: Use Tinker to interact with your agent:

    php artisan tinker
    
    $agent = new \App\AiAgents\CustomerSupportAgent();
    $response = $agent->forUser(auth()->user())->respond("How do I reset my password?");
    dd($response);
    

Key First-Use Cases

  • Chatbot Integration: Build a real-time chat interface using the agent’s respond() method.
  • Automated Workflows: Chain agent responses with Laravel queues for async processing.
  • Tool Integration: Connect to external APIs via annotated tools (e.g., database queries, payment processing).

Implementation Patterns

Core Workflows

  1. Agent Lifecycle:

    • Creation: Extend LarAgent\Agent and override methods like instructions().
    • Execution: Use respond() with optional context (user, history name).
    • Tool Usage: Annotate methods with #[Tool] and define input/output schemas.
  2. Provider Management:

    • Multi-Provider Fallback: Configure an array of providers in $provider (e.g., ['openai', 'gemini']).
    • Dynamic Overrides: Override provider settings per agent (e.g., $temperature = 0.3).
  3. History Handling:

    • Per-User Storage: Use forUser() to scope history to authenticated users.
    • Custom Namespaces: Pass a string to for() to create isolated chat histories (e.g., for("support_tickets")).
  4. Tool Integration:

    • Method-Based Tools: Annotate public methods with #[Tool] and define parameters.
    • Facade Tools: Use Tool::make() for reusable tools outside agent classes.
    • Parallel Execution: Enable $parallelToolCalls = true for concurrent tool calls.

Integration Tips

  • Laravel Events: Listen to AgentResponding, AgentResponded, or ToolExecuting events for custom logic.
  • API Exposure: Use the built-in OpenAI-compatible endpoint (/api/agents/{agent}) for frontend integration.
  • Queue Jobs: Wrap agent responses in AgentJob for async processing:
    AgentJob::dispatch(new CustomerSupportAgent(), $message, $user);
    
  • Testing: Mock agents with LarAgent\Testing\Fakes\FakeAgent for unit tests.

Example: Multi-Step Agent

class OrderProcessingAgent extends Agent {
    protected $tools = ['fetchOrder', 'updateOrderStatus'];

    #[Tool('Fetch order details by ID')]
    public function fetchOrder(string $orderId) {
        return Order::findOrFail($orderId)->toArray();
    }

    #[Tool('Update order status')]
    public function updateOrderStatus(string $orderId, string $status) {
        return Order::where('id', $orderId)->update(['status' => $status]);
    }

    public function instructions() {
        return "Process customer orders by fetching details and updating statuses.";
    }
}

Gotchas and Tips

Common Pitfalls

  1. Tool Schema Mismatches:

    • Issue: Tools may fail if input schemas don’t match the agent’s expectations.
    • Fix: Use #[Tool(schema: "...")] to explicitly define JSON schemas for complex tools.
    • Debug: Check laravel.log for ToolValidationException errors.
  2. Rate Limits:

    • Issue: High temperature or large context windows may trigger API rate limits.
    • Fix: Implement AgentRateLimited event listeners or use fallback providers.
  3. History Bloat:

    • Issue: In-memory history grows unbounded.
    • Fix: Switch to CacheChatHistory or DatabaseChatHistory for persistent storage.
  4. Parallel Tool Calls:

    • Issue: Disabled by default ($parallelToolCalls = false), which may slow down workflows.
    • Fix: Enable for performance-critical tools, but handle race conditions in tool logic.

Debugging Tips

  • Log Agent Interactions: Use AgentResponding event to log input/output:
    event(new AgentResponding($agent, $message, $history));
    
  • Inspect Tools: Dump tool definitions with:
    dd($agent->getTools());
    
  • Test Providers: Use the fake provider for offline testing:
    config(['laragent.providers.default.driver' => \LarAgent\Drivers\Fake\FakeDriver::class]);
    

Configuration Quirks

  1. Provider Labels:

    • Must match keys in config/laragent.php (case-sensitive).
    • Example: $provider = 'openai' requires 'openai' => [...] in config.
  2. Chat History Keys:

    • Default key format: {agent_class}:{user_id}:{history_name}.
    • Override with $historyKey property in the agent class.
  3. Extras Handling:

    • Model-specific extras (e.g., reasoning_effort) must be set in $extras:
    protected $extras = ['reasoning_effort' => 'high'];
    

Extension Points

  1. Custom Drivers:

    • Extend LarAgent\Drivers\LlmDriver and register in config/laragent.php:
    'custom_driver' => [
        'driver' => \App\Drivers\CustomDriver::class,
        // ...
    ],
    
  2. Chat History:

    • Create a new history class extending LarAgent\History\ChatHistory and publish it:
    php artisan make:history CustomDatabaseHistory
    
  3. Events:

    • Extend agent behavior by listening to events (e.g., AgentResponded):
    event(new AgentResponded($agent, $response));
    
  4. Tool Facade:

    • Register custom tool facades in AppServiceProvider:
    Tool::extend('custom', function () {
        return new CustomTool();
    });
    

Performance Tips

  • Batch Tools: Group related tools into a single method to reduce API calls.
  • Cache Responses: Use Laravel’s cache to store frequent tool responses.
  • Streaming: Use respondStreamed() for large responses to avoid memory issues.

Security Notes

  • API Keys: Never hardcode keys; use environment variables or Laravel’s vault.
  • Tool Validation: Always validate tool inputs to prevent injection attacks.
  • Rate Limiting: Implement middleware to throttle agent requests:
    Route::middleware(['throttle:10,1'])->group(function () {
        Route::post('/api/agents/{agent}', [AgentController::class, 'respond']);
    });
    
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.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport