Agents are the foundation of LarAgent. They define how your AI assistant behaves, what tools it can use, and how it processes information.

Creating an Agent

You can create a new agent manually by extending the LarAgent\Agent class. This is the parent class for building your custom AI agent with specific capabilities and behaviors.
Using make:agent command is a recommended way of creating agents.
namespace App\AiAgents;

use LarAgent\Agent;

class MyAgent extends Agent
{
    // Your agent implementation
}
For rapid development, you can use the artisan command to generate a new agent with a basic structure:
php artisan make:agent MyAgent
This will create a new agent class in the App\AiAgents directory with all the necessary boilerplate code:
YourAgentName.php
<?php

namespace App\AiAgents;

use LarAgent\Agent;

class YourAgentName extends Agent
{
    protected $model = 'gpt-4o-mini';

    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;
    }
}

Configuring an Agent

Agents can be configured through various properties and methods to customize their behavior. Here are the core configuration options:

Core methods

The agent also provides several core methods that you can override to customize its behavior:

// Define the agent's system instructions
// This sets the behavior, role, and capabilities of your agent
// For simple textual instructions, use the `instructions` property
// For more complex instructions or dynamic behavior, use the `instructions` method
public function instructions()
{
    return "Define your agent's instructions here.";
}

Properties

Instructions

/** @var string - Define the agent's behavior and role */
protected $instructions;
This property sets the system instructions for your agent, defining its behavior, personality, and capabilities.
// Example
protected $instructions = "You are a helpful assistant specialized in weather forecasting.";

History

/** @var string - Choose from built-in chat history types */
protected $history;
Choose from built-in chat history implementations: “in_memory”, “session”, “cache”, “file”, or “json”.
// Example
protected $history = 'cache';

// Or use a class
protected $history = \LarAgent\History\CacheChatHistory::class;

Driver

/** @var string - Specify which LLM driver to use */
protected $driver;
The driver class that handles communication with the AI provider.
// Example
protected $driver = \LarAgent\Drivers\OpenAi\OpenAiDriver::class;

Provider

/** @var string - Select the AI provider configuration */
protected $provider = 'default';
References a provider configuration from your config file.
// Example
protected $provider = 'openai-gpt4';

Model

/** @var string - Choose which language model to use */
protected $model = 'gpt-4o-mini';
The specific model to use from your chosen provider.
// Example
protected $model = 'gpt-4o';

Other properties

All config properties have relevant setter (chainable methods) you can use to set them at runtime. For example, $maxCompletionTokens -> maxCompletionTokens(int $tokens), $topP -> topP(float $topP) and etc.
All config properties can be defined by config file in provider settings. For example, $maxCompletionTokens -> max_completion_tokens => 2000 and etc.
Tokens
/** @var int - Set the maximum number of tokens in the completion */
protected $maxCompletionTokens;
Limits the length of the AI’s response.
// Example
protected $maxCompletionTokens = 2000;
Temperature
/** @var float - Control response creativity */
protected $temperature;
Controls randomness: 0.0 for focused responses, 2.0 for creative ones.
// Example
protected $temperature = 0.7; // Balanced
Message
/** @var string|null - Current message being processed */
protected $message;
n
/** @var int|null */
protected $n;
How many chat completion choices to generate for each input message. Note that you will be charged based on the number of generated tokens across all of the choices. Keep n as 1 to minimize costs.
In case of $n > 1, the agent will return an array of responses.
top_p
/** @var float|null */
protected $topP;
An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered.
We generally recommend altering $topP or $temperature but not both.
frequency_penalty
/** @var float|null */
protected $frequencyPenalty;
Number between -2.0 and 2.0. Positive values penalize new tokens based on their existing frequency in the text so far, decreasing the model’s likelihood to repeat the same line verbatim.
presence_penalty
/** @var float|null */
protected $presencePenalty;
Number between -2.0 and 2.0. Positive values penalize new tokens based on whether they appear in the text so far, increasing the model’s likelihood to talk about new topics.

Using an Agent

There are two ways to interact with your agent: direct response or chainable methods.

Direct Response

The simplest way is to use the for() method to specify a chat history name and get an immediate response:
// Using a specific chat history name
echo WeatherAgent::for('test_chat')->respond('What is the weather like?');

Using Chainable Methods

For more control over the interaction, you can use the chainable syntax:
$response = WeatherAgent::for('test_chat')
    ->message('What is the weather like?')  // Set the message
    ->temperature(0.7)                      // Optional: Override temperature
    ->respond();                            // Get the response

Ready made user message

Instead of passing a string as a message, you can build your own UserMessage instance. It allows you to add metadata to the message, such as the user ID or request ID. Also, using different methods associated with UserMessage instance.
$userMessage = Message::user($finalPrompt, ['userRequest' => $userRequestId]);

$response = WeatherAgent::for('test_chat')->message($userMessage)->respond();
If you use UserMessage instance instead string, it will bypass the prompt method.

Return message

By default, respond method returns:
  • string with regular request
  • array of string if $n is greater than 1.
  • array Associative array of defined structured output schema.
You can change the return type by using returnMessage method or setting $returnMessage property to true, which will enforce respond method to return MessageInterface instance.
// Returns MessageInterface -> AssistantMessage instance
$response = WeatherAgent::for('test_chat')->returnMessage()->respond();
If returnMessage is true and structured output is defined, beforeStructuredOutput hook will not happen, because structured output is not processed to array.

Image input

You can pass publicly accessible image URLs to the agent as an array of strings.
$images = [
    'https://example.com/image.jpg',
    'https://example.com/image2.jpg',
];

$response = WeatherAgent::for('test_chat')->withImages($images)->respond();
Alternative way to pass images is to use base64 encoded data.
$imageUrls = [
    'data:image/jpeg;base64,' . base64_encode($img)
];

$response = ImageAgent::for('test')->withImages($imageUrls)->respond("Analyze images");
Base64 image input Contributed by havspect in issue #74.

Audio input

You can pass base64 encoded audio data to the agent as an array of arrays containing the format and data. Supported formats by OpenAI: “wav”, “mp3”, “ogg”, “flac”, “m4a”, “webm”
$audios = [
    [
        'format' => 'mp3',
        'data' => $base64Audio
    ]
];

echo WeatherAgent::for('test_chat')->withAudios($audios)->respond();

Agent Mutators Reference

Here are some chainable methods to modify the agent’s behavior on the fly:

Agent Accessors Reference

You can access the agent’s properties using these methods on an instance of the agent:

Example Configuration

class WeatherAgent extends Agent
{
    protected $model = 'gpt-4o';
    protected $history = 'session';
    protected $temperature = 0.7;
    
    public function instructions()
    {
        return "You are a weather expert assistant. Provide accurate weather information.";
    }
    
    public function prompt(string $message)
    {
        return "Weather query: " . $message;
    }
}