PHP code example of andmarruda / laravel-agents

1. Go to this page and download the library: Download andmarruda/laravel-agents library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

andmarruda / laravel-agents example snippets


LaravelAgents::model('openai/gpt-4.1-mini');
LaravelAgents::model('anthropic/claude-sonnet-4');
LaravelAgents::model('fireworks/accounts/fireworks/models/llama-v3p1-70b-instruct');

use Andmarruda\LaravelAgents\Data\ImageGenerationRequest;
use Andmarruda\LaravelAgents\Facades\LaravelAgents;

$response = LaravelAgents::image('openai/gpt-image-1')
    ->generate(new ImageGenerationRequest(
        prompt: 'A clean Laravel agent orchestration diagram',
        size: '1024x1024',
    ));

$url = $response->firstUrl();
$base64 = $response->firstBase64();

$image = LaravelAgents::kernel()
    ->image()
    ->generate(new ImageGenerationRequest(prompt: 'A product launch illustration'));

use Andmarruda\LaravelAgents\Data\Billing\BillingQuery;
use Andmarruda\LaravelAgents\Facades\LaravelAgents;

$costs = LaravelAgents::billing('openai')->costs(new BillingQuery(
    startTime: '2026-06-01',
    endTime: '2026-07-01',
    bucketWidth: '1d',
));

$completions = LaravelAgents::billing()->usage('completions', new BillingQuery(
    startTime: now()->subWeek(),
    endTime: now(),
    bucketWidth: '1d',
    groupBy: 'model',
));



namespace App\Agents;

use Andmarruda\LaravelAgents\Agents\Agent;

final class ResearchAgent extends Agent
{
    public function configure(): void
    {
        $this->nameAs('researcher');
        $this->description('Finds facts, constraints, and useful context.');
        $this->instructions('You are a careful research agent. Be concise and cite uncertainty.');
        $this->model('openai/gpt-4.1-mini');
    }
}

use App\Agents\ResearchAgent;
use Andmarruda\LaravelAgents\Facades\LaravelAgents;

$response = LaravelAgents::agent(ResearchAgent::class)
    ->generate('Summarize the trade-offs of using AI agents in a Laravel app.');

echo $response->content;



namespace App\Agents;

use Andmarruda\LaravelAgents\Agents\SupervisorAgent;

final class ManagerAgent extends SupervisorAgent
{
    public function configure(): void
    {
        $this->nameAs('manager');
        $this->description('Coordinates specialist agents and produces the final answer.');
        $this->instructions('Use the best worker for each step. Stop when the task is complete.');
        $this->model('anthropic/claude-sonnet-4');
        $this->maxSteps(8);
        $this->withAgents([
            ResearchAgent::class,
            WriterAgent::class,
            ReviewerAgent::class,
        ]);
    }
}

use App\Agents\ManagerAgent;
use Andmarruda\LaravelAgents\Facades\LaravelAgents;

$response = LaravelAgents::agent(ManagerAgent::class)
    ->generate('Research, write, and review a launch plan for a Laravel AI package.');

echo $response->content;

$steps = $response->steps;

$response = LaravelAgents::agent(ResearchAgent::class)
    ->generate('Analyze this project.', [
        'project_id' => $project->id,
        'user_id' => $user->id,
        'constraints' => ['alpha', 'no persistent memory yet'],
    ]);

$response = LaravelAgents::agent(ResearchAgent::class)
    ->generate('Find useful context.');

$traceId = $response->meta['trace_id'];

use Andmarruda\LaravelAgents\Facades\LaravelAgents;
use Andmarruda\LaravelAgents\RAG\Loaders\FileDocumentLoader;

$summary = LaravelAgents::indexer()->index(
    new FileDocumentLoader(storage_path('knowledge/guide.md')),
    namespace: 'product-docs',
);

$results = LaravelAgents::retriever(namespace: 'product-docs')
    ->retrieve('How do agents call tools?', limit: 5);

use Andmarruda\LaravelAgents\Facades\LaravelAgents;
use Andmarruda\LaravelAgents\Workflows\WorkflowContext;

$response = LaravelAgents::workflow()
    ->named('invoice-review')
    ->then('normalize', function (array $invoice, WorkflowContext $context): array {
        $context->put('currency', 'USD');

        return [
            ...$invoice,
            'total' => (float) $invoice['total'],
        ];
    })
    ->branch(
        fn (array $invoice): string => $invoice['total'] >= 1000 ? 'approval' : 'auto',
        [
            'approval' => fn (array $invoice): array => [...$invoice, 'status' => 'waiting_approval'],
            'auto' => fn (array $invoice): array => [...$invoice, 'status' => 'approved'],
        ],
        'approval_gate',
    )
    ->run(['id' => 10, 'total' => '1250.00']);

$invoice = $response->data;
$steps = $response->steps;
$context = $response->meta['context'];

use Andmarruda\LaravelAgents\Workflows\Step;
use Andmarruda\LaravelAgents\Workflows\WorkflowContext;

final class AddTaxStep implements Step
{
    public function handle(mixed $input, WorkflowContext $context): array
    {
        return [
            ...$input,
            'total' => $input['total'] * 1.08,
        ];
    }
}

$response = LaravelAgents::workflow()
    ->inputSchema(['name' => 'eet', fn (array $input): array => ['message' => 'Hello '.$input['name']])
    ->run(['name' => 'Ana']);

use Andmarruda\LaravelAgents\Workflows\InMemoryWorkflowStore;

$store = new InMemoryWorkflowStore();

$response = LaravelAgents::workflow()
    ->then('prepare', fn (array $input): array => [...$input, 'prepared' => true])
    ->approval('manager_approval', 'Approve this invoice?', ['role' => 'manager'])
    ->then('finish', fn (array $input): array => [...$input, 'finished' => true])
    ->run(['id' => 10], store: $store);

if ($response->status === 'awaiting_approval') {
    $snapshotId = $response->snapshot->id;
}

$resumed = LaravelAgents::workflow()
    ->then('prepare', fn (array $input): array => [...$input, 'prepared' => true])
    ->approval('manager_approval', 'Approve this invoice?', ['role' => 'manager'])
    ->then('finish', fn (array $input): array => [...$input, 'finished' => true])
    ->resume($snapshotId, ['approved_by' => auth()->id()], $store);

final class InvoiceWorkflow extends \Andmarruda\LaravelAgents\Workflows\Workflow
{
    public function __construct()
    {
        parent::__construct('invoice-workflow');

        $this
            ->then(NormalizeInvoice::class)
            ->approval('manager_approval', 'Approve this invoice?')
            ->then(SaveInvoice::class);
    }
}

(new InvoiceWorkflow())->dispatch(['id' => 10]);
bash
php artisan vendor:publish --tag=agents-config
bash
php artisan vendor:publish --tag=agents-migrations
php artisan migrate
bash
php artisan vendor:publish --tag=agents-rag-pgvector-migrations
php artisan migrate