Skip to main content

Creating an Agent

The recommended way to create a new agent is using the artisan command:
php artisan make:agent MyAgent
This generates a new agent class in the App\AiAgents directory with all the necessary boilerplate:
App/AiAgents/MyAgent.php
<?php

namespace App\AiAgents;

use LarAgent\Agent;

class MyAgent 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;
    }
}
Name your agents descriptively based on their purpose. CustomerSupportAgent is clearer than Agent1 or MyAgent.

Core Methods

Override these methods to customize your agent’s behavior:

instructions()

The system prompt that shapes how your agent responds. This defines the agent’s personality, role, and guidelines.
public function instructions()
{
    return "You are an expert financial advisor. Provide clear, 
            actionable advice while always recommending users 
            consult with a certified professional for major decisions.";
}
For simple, static instructions you can use the $instructions property instead of the method.
For complex or dynamic instructions, consider using Blade template files. This keeps your agent class clean and allows you to leverage Blade’s templating features like conditionals and loops.

prompt()

Process or augment the user’s message before sending it to the LLM. Useful for adding context, formatting, or implementing RAG patterns.
public function prompt($message)
{
    $context = $this->retrieveRelevantContext($message);
    
    return "Context: {$context}\n\nUser question: {$message}";
}

model()

Dynamically determine which model to use based on custom logic:
public function model()
{
    // Use a more powerful model for complex queries
    if ($this->isComplexQuery()) {
        return 'gpt-4o';
    }
    
    return 'gpt-4o-mini';
}

API Key and URL

Override these methods to dynamically set API credentials:
public function getApiKey()
{
    // Use different API keys per tenant
    return auth()->user()->team->openai_api_key;
}

public function getApiUrl()
{
    return config('services.openai.url');
}

Configuration Properties

Model & Provider

PropertyTypeDescription
$modelstringThe LLM model to use (e.g., gpt-4o-mini, gpt-4o)
$providerstringProvider configuration name from config/laragent.php
$driverstringDriver class for LLM communication
class MyAgent extends Agent
{
    protected $model = 'gpt-4o';
    protected $provider = 'openai';
    protected $driver = \LarAgent\Drivers\OpenAi\OpenAiDriver::class;
}
LarAgent supports multiple AI providers including OpenAI, Anthropic, Gemini, Groq, and Ollama. See LLM Drivers for setup instructions and available options.

Response Settings

Control how the LLM generates responses:
Controls randomness in responses. Range: 0.0 (focused/deterministic) to 2.0 (creative/random).
protected $temperature = 0.7; // Balanced
Maximum number of tokens in the AI’s response.
protected $maxCompletionTokens = 2000;
Generate multiple completion choices. Note: You’ll be charged for all generated tokens.
protected $n = 3; // Returns array of 3 responses
Alternative to temperature. The model considers tokens with top_p probability mass.
protected $topP = 0.1; // Only top 10% probability tokens
Use either $temperature or $topP, not both.
Penalizes tokens based on their frequency in the text. Range: -2.0 to 2.0.
protected $frequencyPenalty = 0.5; // Reduces verbatim repetition
Penalizes tokens based on whether they’ve appeared. Range: -2.0 to 2.0.
protected $presencePenalty = 0.5; // Encourages discussing new topics
All configuration properties can also be set via the provider settings in config/laragent.php.

History & Tools

PropertyTypeDescription
$historystringChat history storage: in_memory, session, cache, file
$toolsarrayArray of tool classes the agent can use
class MyAgent extends Agent
{
    protected $history = 'cache';
    
    protected $tools = [
        \App\Tools\WeatherTool::class,
        \App\Tools\CalculatorTool::class,
    ];
}
Both Context (chat history, data models) and Tools are core features of LarAgent with extensive configuration options. The properties shown here are just the basics.
  • Learn about context management, storage drivers, and truncation strategies in the Context page
  • Explore tool creation, parameters, and execution in the Tools Section

Arbitrary Configuration

Pass custom configuration values to the driver for provider-specific settings or experimental features:

class MyAgent extends Agent
{
    protected $configs = [
        'reasoning_effort' => 'high',
        'custom_header' => 'value',
    ];
}

Custom configurations are passed directly to the driver, allowing you to leverage provider-specific features without modifying the agent’s core properties.

Runtime Configuration

Override any configuration at runtime using chainable methods:
$response = WeatherAgent::for('user-123')
    ->withModel('gpt-4o')
    ->temperature(0.9)
    ->maxCompletionTokens(1000)
    ->respond('Write a creative story');
All properties have corresponding chainable methods:
  • $temperaturetemperature(float $temp)
  • $maxCompletionTokensmaxCompletionTokens(int $tokens)
  • $topPtopP(float $value)
  • And so on…

Next Steps