Laragent - Power of AI Agents in your Laravel project
Extracto
Power of AI Agents in your Laravel project
Resumen
Resumen Principal
LarAgent emerge como una solución robusta y accesible para la creación y gestión de agentes de IA directamente dentro de proyectos Laravel. El paquete se distingue por su sintaxis Eloquent-like, que permite a los desarrolladores de Laravel crear y configurar agentes de IA con una familiaridad y fluidez que se alinea con los patrones de diseño del framework. Ofrece una configuración altamente flexible para los agentes, permitiendo la especificación de modelos LLM, la gestión de historiales de chat (incluido el almacenamiento por usuario y diversas opciones de persistencia), y el ajuste de parámetros como la temperatura. Además, simplifica drásticamente la implementación de herramientas personalizadas mediante atributos, métodos o clases dedicadas, con soporte para la ejecución paralela. LarAgent busca democratizar el desarrollo de aplicaciones impulsadas por IA, integrando capacidades avanzadas de manera transparente y manteniendo la coherencia con el flujo de trabajo de Laravel.
Elementos Clave
-
Sintaxis Eloquent-like para Agentes de IA: LarAgent permite definir agentes de IA de una manera sorprendentemente similar a cómo se definen los modelos Eloquent en Laravel. A través de comandos Artisan como
php artisan make:agent YourAgentNamey la extensión de la claseLarAgent\Agent, los desarrolladores pueden crear estructuras de agentes que encapsulan lógica, instrucciones y configuraciones. Esto incluye la definición de propiedades como$model,$history,$providery$tools, facilitando la integración de la IA en un contexto Laravel familiar. -
Configuración Flexible y Gestión de Historial de Chat: El paquete ofrece una amplia gama de opciones de configuración para cada agente. Los desarrolladores pueden especificar el modelo LLM a utilizar (ej. 'gpt-4'), definir la estrategia de historial de chat (en-memoria, caché, JSON, etc., incluso por usuario o con nombres personalizados), ajustar la temperatura para controlar la creatividad de las respuestas, y habilitar o deshabilitar las llamadas paralelas a herramientas. Esta flexibilidad asegura que los agentes puedan adaptarse a diversas necesidades y casos de uso dentro de las aplicaciones.
-
Creación y Ejecución de Herramientas Personalizadas: LarAgent simplifica la creación de herramientas personalizadas que los agentes pueden utilizar para interactuar con el entorno. Estas herramientas pueden ser definidas directamente como métodos dentro de la clase del agente, mediante clases dedicadas o a través de un facade de herramientas, utilizando atributos como
#[Tool]. Una característica destacada es la capacidad de ejecutar herramientas en paralelo, lo que mejora la eficiencia y la complejidad de las interacciones del agente con múltiples funcionalidades o servicios externos. -
Hoja de Ruta Ambiciosa y Extensibilidad: El proyecto tiene una hoja de ruta detallada que incluye mejoras significativas en la experiencia del desarrollador, como más comandos Artisan (
make:agent:tool,make:llm-driver), y capacidades de IA mejoradas, incluyendo integración con Gemini y Anthropic, soporte de streaming, RAG (Retrieval Augmented Generation) y bases de conocimiento integradas, y seguridad mejorada para el historial de chat (encriptación opcional). La arquitectura es altamente extensible, permitiendo la creación de controladores LLM y soluciones de historial de chat personalizadas.
Análisis e Implicaciones
LarAgent representa un paso significativo para la comunidad Laravel al ofrecer un marco estructurado y familiar para el desarrollo de agentes de IA. Su enfoque en la simplicidad y la integración fluida permite a los desarrolladores de Laravel aprovechar el poder de la inteligencia artificial generativa sin una curva de aprendizaje pronunciada, potenciando la creación de aplicaciones más inteligentes y dinámicas.
Contexto Adicional
El paquete requiere Laravel 10.x o superior y PHP 8.3 o superior para su funcionamiento, y se puede instalar fácilmente a través de Composer, con documentación oficial y un servidor de Discord disponibles para soporte.
Contenido
The easiest way to create and maintain AI agents in your Laravel projects.
Each GitHub ⭐️ helps the community grow. Thanks for the support!
Jump to Official Documentation
If you prefer article to get started, check it out: Laravel AI Agent Development Made Easy
You can find other tutorials here: Tutorials
Any questions? Join our Discord server!
Need to use LarAgent outside of Laravel? Check out this Docs.
Table of Contents
- 📖 Introduction
- 🎉 Features
- 📅 Planned
- 🚀 Getting Started
- 🤝 Contributing
- 🤝 Getting Help
- 🧪 Testing
- 🔒 Security
- 🙌 Credits
- 📜 License
- 🛣️ Roadmap
Introduction
LarAgent brings the power of AI agents to your Laravel projects with an elegant syntax. Create, extend, and manage AI agents with ease while maintaining Laravel's fluent API design patterns.
What if you can create AI agents just like you create any other Eloquent model?
Why not?! 👇
php artisan make:agent YourAgentName
And it looks familiar, isn't it?
namespace App\AiAgents;
use LarAgent\Agent;
class YourAgentName extends Agent
{
protected $model = 'gpt-4';
protected $history = 'in_memory';
protected $provider = 'default';
protected $tools = [];
public function instructions()
{
return "Define your agent's instructions here.";
}
public function prompt($message)
{
return $message;
}
}
And you can tweak the configs, like history
// ...
protected $history = \LarAgent\History\CacheChatHistory::class;
// ...
Or add temperature:
// ...
protected $temperature = 0.5;
// ...
Even disable parallel tool calls:
// ...
protected $parallelToolCalls = false;
// ...
Oh, and add a new tool as well:
// ...
#[Tool('Get the current weather in a given location')]
public function exampleWeatherTool($location, $unit = 'celsius')
{
return 'The weather in '.$location.' is '.'20'.' degrees '.$unit;
}
// ...
And run it, per user:
Use App\AiAgents\YourAgentName;
// ...
YourAgentName::forUser(auth()->user())->respond($message);
Or use a custom name for the chat history:
Use App\AiAgents\YourAgentName;
// ...
YourAgentName::for("custom_history_name")->respond($message);
Let's find out more in documentation 👍
Features
- Eloquent-like syntax for creating and managing AI agents
- Laravel-style artisan commands
- Flexible agent configuration (model, temperature, context window, etc.)
- Structured output handling
- Image input support
- Easily extendable, including chat histories and LLM drivers
- Multiple built-in chat history storage options (in-memory, cache, json, etc.)
- Per-user chat history management
- Custom chat history naming support
- Custom tool creation with attribute-based configuration
- Tools via classes
- Tools via methods of AI agent class (Auto)
Toolfacade for shortened tool creation- Parallel tool execution capability (can be disabled)
- Extensive Event system for agent interactions (Nearly everything is hookable)
- Multiple provider support (Can be set per model)
- Support for both Laravel and standalone usage
Planned
Here's what's coming next to make LarAgent even more powerful:
Developer Experience 🛠️
- Artisan Commands for Rapid Development
agent:chat:clear AgentName- Clear all chat histories for a specific agent while preserving keys ✔️agent:chat:remove AgentName- Completely remove all chat histories and keys for a specific agent ✔️make:agent:tool- Generate tool classes with ready-to-use stubsmake:agent:chat-history- Scaffold custom chat history implementationsmake:llm-driver- Create custom LLM driver integrations
- Native Laravel events support - Support for Laravel events
- Debug mode - Should log all processes happening under the hood
Enhanced AI Capabilities 🧠
- Prism Package Integration - Additional LLM providers support
- Gemini Integration - Additional LLM provider ✔️
- Anthropic Integration - Additional LLM provider
- Usage abstraction - Abstraction for tokens usage
- Streaming Support - Out-of-the-box support for streaming responses ✔️
- RAG & Knowledge Base
- Built-in vector storage providers
- Seamless document embeddings integration
- Smart context management
- Ready-to-use Tools - Built-in tools as traits
- Structured Output at runtime - Allow defining the response JSON Schema at runtime.
- Transfer tool - One of the methods of agents chaining
Security & Storage 🔒
- Enhanced Chat History Security - Optional encryption for sensitive conversations
Advanced Integrations 🔌
- Provider Fallback System - Automatic fallback to alternative providers ✔️
- Voice Chat Support - Out of the box support for voice interactions with your agents
Stay tuned! We're constantly working on making LarAgent the most versatile AI agent framework for Laravel.
Getting Started
Requirements
- Laravel 10.x or higher
- PHP 8.3 or higher
Installation
You can install the package via composer:
composer require maestroerror/laragent
You can publish the config file with:
php artisan vendor:publish --tag="laragent-config"
These are the contents of the published config file:
return [
'default_driver' => \LarAgent\Drivers\OpenAi\OpenAiDriver::class,
'default_chat_history' => \LarAgent\History\InMemoryChatHistory::class,
'providers' => [
'default' => [
'label' => 'openai',
'api_key' => env('OPENAI_API_KEY'),
'default_context_window' => 50000,
'default_max_completion_tokens' => 100,
'default_temperature' => 1,
],
],
];
Configuration
You can configure the package by editing the config/laragent.php file. Here is an example of custom provider with all possible configurations you can apply:
// Example custom provider with all possible configurations
'custom_provider' => [
// Just name for reference, changes nothing
'label' => 'mini',
'model' => 'gpt-3.5-turbo',
'api_key' => env('CUSTOM_API_KEY'),
'api_url' => env('CUSTOM_API_URL'),
// Default driver and chat history
'driver' => \LarAgent\Drivers\OpenAi\OpenAiDriver::class,
'chat_history' => \LarAgent\History\InMemoryChatHistory::class,
'default_context_window' => 15000,
'default_max_completion_tokens' => 100,
'default_temperature' => 1,
// Enable/disable parallel tool calls
'parallel_tool_calls' => true,
// Store metadata with messages
'store_meta' => true,
// Save chat keys to memory via chatHistory
'save_chat_keys' => true,
],
Provider just gives you the defaults. Every config can be overridden per agent in agent class.
Contributing
We welcome contributions to LarAgent! Whether it's improving documentation, fixing bugs, or adding new features, your help is appreciated. Here's how you can contribute.
We aim to review all pull requests within a 2 weeks. Thank you for contributing to LarAgent!
Getting Help
- Open an issue for bugs or feature requests
- Join discussions in existing issues
- Join community server on Discord
- Reach out to maintainers for guidance
Testing
composer test
Security
Please review our security policy on how to report security vulnerabilities.
Credits
Thanks to these people and projects, LarAgent would not be possible without them:
License
The MIT License (MIT). Please see License File for more information.
Roadmap
Please see Planned for more information on the future development of LarAgent.
Fuente: Laravel Library