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.
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).
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();
}
}
First Interaction
$response = CustomerSupportAgent::forUser(auth()->user())
->respond("How do I track my order #12345?");
make:agent, make:tool (for standalone tools).BeforeAgentExecution, AfterToolExecution (in app/Providers/EventServiceProvider.php).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
]);
Tool Integration
#[Tool] attribute):
#[Tool('Validate email address')]
public function validateEmail($email) {
return validator()->make(['email' => $email], ['email' => 'required|email'])->passes();
}
Tool facade):
use LarAgent\Tool;
Tool::make('SendEmail', SendEmailService::class);
Multi-Agent Workflows
// Chain agents sequentially
$workflow = new AgentWorkflow();
$workflow->add(CustomerSupportAgent::class)
->add(AnalyticsAgent::class)
->execute("Analyze customer feedback for order #12345");
Memory Management
$agent->forUser($user)->respond("..."); // Uses `CacheChatHistory` by default
protected $history = \LarAgent\History\DatabaseChatHistory::class;
LarAgent\Api\AgentController for REST endpoints:
Route::post('/agents/{agent}/chat', [AgentController::class, 'chat']);
Event::listen(AfterAgentExecution::class, function ($event) {
Analytics::logAgentInteraction($event->agent, $event->response);
});
LarAgent\Testing\AgentFakes:
$fakeAgent = Agent::fake();
$fakeAgent->shouldRespondWith("Mocked response");
Tool Execution Quirks
$parallelToolCalls = false if tools have side effects.#[Tool('Update user profile')]
public function updateProfile(array $data) {
if (!array_key_exists('email', $data)) {
throw new \InvalidArgumentException("Email is required");
}
// ...
}
Rate Limiting
default_truncation_threshold in providers to avoid token overflows.LarAgent\Drivers\RateLimitedDriver for API key rotation.Event Order
BeforeAgentExecution fires before BeforeToolExecution. Override carefully to avoid infinite loops.Provider Fallbacks
['default', 'gemini']) require all providers to support the same tools.config/laragent.php:
'debug' => env('APP_DEBUG', false),
dd($agent->lastResponse()) to debug structured outputs.dd($agent->getHistory()->getMessages());
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,
// ...
],
]
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));
}
// ...
}
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
}
LarAgent\Cache\AgentCache:
$agent->cacheResponses(60); // Cache for 60 seconds
LarAgent\Input\MultiModalInput:
$response = $agent->respondWithFiles("Analyze this image", $imagePath);
protected $outputFormat = 'json';
How can I help you explore Laravel packages today?