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.
Copy
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:
Copy
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
Copy
<?phpnamespace 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; }}
The agent also provides several core methods that you can override to customize its behavior:
Copy
// 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` methodpublic function instructions(){return "Define your agent's instructions here.";}
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
Copy
/** @var int - Set the maximum number of tokens in the completion */protected $maxCompletionTokens;
Limits the length of the AI’s response.
Copy
// Exampleprotected $maxCompletionTokens = 2000;
Temperature
Copy
/** @var float - Control response creativity */protected $temperature;
Controls randomness: 0.0 for focused responses, 2.0 for creative ones.
/** @var string|null - Current message being processed */protected $message;
n
Copy
/** @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
Copy
/** @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.
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
Copy
/** @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.
For more control over the interaction, you can use the chainable syntax:
Copy
$response = WeatherAgent::for('test_chat') ->message('What is the weather like?') // Set the message ->temperature(0.7) // Optional: Override temperature ->respond(); // Get the response
If you don’t need to maintain conversation histories, you can just replace for with make method:
Copy
echo WeatherAgent::make() ->message('What is the weather like?') // Set the message ->temperature(0.7) // Optional: Override temperature ->respond(); // Get the response
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.
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.
If returnMessage is true and structured output is defined,
beforeStructuredOutput hook will not happen, because structured output is
not processed to array.
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”
Here are some chainable methods to modify the agent’s behavior on the fly:
message() - Set the message
Copy
/** * Set the message for the agent to process */public function message(string|UserMessage $message);
Sets the message that will be sent to the AI model.
Copy
// Example$agent = WeatherAgent::for('test_chat');$agent->message('What is the weather like today?')->respond();
withImages() - Add images
Copy
/** * Add images to the agent's input (message) * @param array $imageUrls Array of image URLs */public function withImages(array $imageUrls);
Adds images to the message for multimodal models.
Copy
// Example$agent->message('What's in this image?') ->withImages(['https://example.com/image.jpg']) ->respond();
withAudios() - Add audios
Copy
/** * Add audios to the agent's input (message) * Array of arrays: ['data' => 'base64', 'format' => 'wav'] * Possible formats: "wav", "mp3", "ogg", "flac", "m4a", "webm" * @param array $audioStrings Array of audio data */public function withAudios(array $audioStrings);
Adds audios to the message, use for multimodal models.
Copy
// Example $audios = [ [ 'format' => 'mp3', 'data' => $base64Audio ] ];$agent->message('What's in this audio?') ->withAudios($audios) ->respond();
withModel() - Change model
Copy
/** * Decide model dynamically in your controller * @param string $model Model identifier (e.g., 'gpt-4o', 'gpt-3.5-turbo') */public function withModel(string $model);
Overrides the default model for this specific call.
/** * @param MessageInterface */public function addMessage(MessageInterface $message);
Adds a custom message to the chat history. MessageInterface: Easily created with Message class: Message::system('Your message here')
Use with caution, as it is added directly to the chat history and keep in mind that history needs to keep certain structure defined by openai.
Copy
// Exampleuse LarAgent\Message;$agent->addMessage(Message::system('Remember to be concise')) ->message('Explain quantum computing') ->respond();
clear() - Clear history
Copy
public function clear();
Clear the chat history. This removes all messages from the chat history
You can access the agent’s properties using these methods on an instance of the agent:
getChatSessionId() - Get session ID
Copy
/** * Get the current chat session ID * String like "[AGENT_NAME]_[MODEL_NAME]_[CHAT_NAME]" * CHAT_NAME is defined by "for" method * Example: WeatherAgent_gtp-4o-mini_test-chat */public function getChatSessionId(): string;
Returns the unique identifier for the current chat session.
/** * Get all chat keys associated with this agent class */public function getChatKeys(): array;
Returns all chat keys associated with this agent class.
Copy
// Example$chatKeys = $agent->getChatKeys();// Returns: ["user_1_chat", "user_2_chat", ...]// You can use this to list all active conversationsforeach ($chatKeys as $key) { echo "Active chat: " . $key . "\n";}
getModalities() - Get modalities
public
Copy
function getModalities(): array; ``` Returns all modalities associated withthis agent class. ```php // Example $modalities = $agent->getModalities(); //Returns: ["text", "image", "audio"] ```</Accordion><Accordion title="getAudio() - Get audio">```php/** * Get all audio associated with this agent class */public function getAudio(): ?array;
Returns all audio associated with this agent class.
Copy
// Example$audio = $agent->getAudio();// Returns: null or array of audio data containing arrays of format and data// [// [// 'format' => 'mp3',// 'data' => $base64Audio// ]// ]
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; }}