TechnicalBuild an agent

Build an agentLesson 9 of 10

Load a guidelines file

Read a project rules file (like CLAUDE.md or AGENTS.md) into the agent’s instructions.

2 min readLesson

Build an agent9

Before you start Finish Lesson 8. This lesson changes files from it.

You'll learn

  • Write a short project guidelines file
  • Build instructions from a persona plus the guidelines
  • Test the instructions with Pest

How it works

Coding agents read a guidelines file from your project. Here it is LEO.md (Leo is the agent’s name). Keep it short: every line is sent with every request.

The base instructions() becomes persona + guidelines. Child agents override persona(), so they all get the guidelines for free.

Guidelines go in instructions, not in the history, so compacting can never summarise them away.

  • Guidelines file: Project rules added to the instructions on every request.
  • Pest: A PHP testing tool included with new Laravel apps.

Step by step

1Create LEO.md

Create this file in the project root (next to composer.json).

New file · LEO.md

## Coding Requirements

- Favor Pest over PHPUnit.
- Never use PHP docblocks.

LEO.md: short, bullet-point project rules.

LEO.md: short, bullet-point project rules.

2Add the guidelines to instructions()

In Agent.php, replace the instructions() method with this one:

Edit · app/Ai/Agents/Agent.php → instructions()

public function instructions(): string
{
    $instructions = $this->persona();

    if (file_exists($guidelines = base_path('LEO.md'))) {
        $instructions .= "\n\n## Project Guidelines\n\n".file_get_contents($guidelines);
    }

    return $instructions;
}

The full file is below if you prefer to replace it.

instructions() = persona + guidelines.

instructions() = persona + guidelines.

3Write the tests

Generate a Pest test, replace its contents, then run it. The second test keeps a backup of your real LEO.md while it runs.

Run

php artisan make:test AgentTest --pest

Replace file · tests/Feature/AgentTest.php

<?php

use App\Ai\Agents\Agent;

test('it prepares the agent instructions', function () {
    expect((new Agent)->instructions())->toStartWith('You are a helpful AI assistant.');
});

test('it optionally loads LEO.md guidelines', function () {
    $path = base_path('LEO.md');
    $original = @file_get_contents($path); // keep your real file safe

    $guidelines = '- Use Pest instead of PHPUnit.';
    file_put_contents($path, $guidelines);

    expect((new Agent)->instructions())
        ->toContain('## Project Guidelines')
        ->toContain($guidelines);

    $original === false ? @unlink($path) : file_put_contents($path, $original);
});

Run

php artisan test --filter=AgentTest

Replace file · app/Ai/Agents/Agent.php

<?php

namespace App\Ai\Agents;

use App\Ai\Attributes\CompactsAfter;
use App\Ai\Tools\Tool;
use Illuminate\Support\Facades\Http;
use ReflectionClass;

use function Laravel\Prompts\info;

class Agent
{
    /** The conversation so far: everything we send back to the AI each time. */
    protected array $history = [];

    // ---------------------------------------------------------------
    //  Things a child agent can override
    // ---------------------------------------------------------------

    /** Who the agent is. Override this in a child class. */
    public function persona(): string
    {
        return 'You are a helpful AI assistant.';
    }

    /** The tools this agent may call. */
    public function tools(): array
    {
        return [];
    }

    /** Optional JSON schema the final answer must match (structured output). */
    public function schema(): array
    {
        return [];
    }

    // ---------------------------------------------------------------
    //  Instructions = persona + LEO.md guidelines
    // ---------------------------------------------------------------

    public function instructions(): string
    {
        $instructions = $this->persona();

        if (file_exists($guidelines = base_path('LEO.md'))) {
            $instructions .= "\n\n## Project Guidelines\n\n".file_get_contents($guidelines);
        }

        return $instructions;
    }

    public function messages(): array
    {
        return $this->history;
    }

    // ---------------------------------------------------------------
    //  The agent loop
    // ---------------------------------------------------------------

    public function prompt(string $prompt): string
    {
        $this->maybeCompact();

        $this->history[] = ['role' => 'user', 'content' => $prompt];

        // The inner loop: the agent's "inner dialogue".
        while (true) {
            $response = $this->runModel();

            // Record everything the AI said, including any tool requests.
            $this->history = [...$this->history, ...$response['output']];

            $toolCalls = collect($response['output'])
                ->filter(fn (array $item) => $item['type'] === 'function_call');

            // No tools requested? Then this is the final answer.
            if ($toolCalls->isEmpty()) {
                return static::text($response);
            }

            $toolCalls->each(fn (array $call) => $this->runTool($call));
        }
    }

    protected function runTool(array $call): void
    {
        if (app()->runningInConsole()) {
            info("Running tool: {$call['name']}({$call['arguments']})");
        }

        $tool = collect($this->tools())
            ->first(fn (Tool $tool) => $tool->definition()['name'] === $call['name']);

        $output = $tool
            ? $tool->use(json_decode($call['arguments'], associative: true) ?? [])
            : "Error: unknown tool {$call['name']}";

        // Send the result back, linked to the request by its call_id.
        $this->history[] = [
            'type' => 'function_call_output',
            'call_id' => $call['call_id'],
            'output' => (string) $output,
        ];
    }

    protected function runModel(): array
    {
        $payload = [
            'model' => config('services.openai.model'),
            'instructions' => $this->instructions(),
            'input' => $this->history,
        ];

        if ($this->tools()) {
            $payload['tools'] = array_map(fn (Tool $tool) => $tool->definition(), $this->tools());
        }

        // Only ask for structured output when the agent defines a schema.
        if ($this->schema()) {
            $payload['text'] = [
                'format' => [
                    'type' => 'json_schema',
                    'name' => 'assistant_response',
                    'strict' => true,
                    'schema' => $this->schema(),
                ],
            ];
        }

        return Http::withToken(config('services.openai.key'))
            ->timeout(120)
            ->post('https://api.openai.com/v1/responses', $payload)
            ->throw()
            ->json();
    }

    /**
     * Pull every piece of text out of a response.
     * Safer than $response['output'][0]['content'][0]['text'],
     * because the first output item is not always a message.
     */
    public static function text(array $response): string
    {
        return collect($response['output'] ?? [])
            ->where('type', 'message')
            ->flatMap(fn (array $message) => $message['content'] ?? [])
            ->where('type', 'output_text')
            ->pluck('text')
            ->implode("\n");
    }

    // ---------------------------------------------------------------
    //  Compacting: summarise long conversations
    // ---------------------------------------------------------------

    protected function maybeCompact(): void
    {
        if ($this->shouldCompact()) {
            $this->compact();
        }
    }

    protected function shouldCompact(): bool
    {
        return $this->threshold() < count($this->history);
    }

    protected function threshold(): int
    {
        $attributes = (new ReflectionClass($this))->getAttributes(CompactsAfter::class);

        return $attributes ? $attributes[0]->newInstance()->threshold : 30;
    }

    protected function compact(): void
    {
        $response = Http::withToken(config('services.openai.key'))
            ->timeout(120)
            ->post('https://api.openai.com/v1/responses', [
                'model' => config('services.openai.model'),
                'instructions' => 'Summarize the following conversation history concisely. '
                    .'Preserve key facts, decisions, tool results and unresolved questions. '
                    .'Omit pleasantries and redundant exchanges.',
                // Sent as one block of JSON text, so tool calls in the history can't confuse the API.
                'input' => [
                    ['role' => 'user', 'content' => json_encode($this->history, JSON_PRETTY_PRINT)],
                ],
            ])
            ->throw()
            ->json();

        $this->history = [
            ['role' => 'user', 'content' => "[Earlier Conversation Summary]\n\n".static::text($response)],
        ];
    }
}

A Pest test for the optional guidelines file.

A Pest test for the optional guidelines file.

Check your work

Run php artisan agent and type:

In php artisan agent: Write a test for the /contact route.

You should see

Both tests pass when you run them. The agent writes a Pest test with no docblocks, as LEO.md asks.

If it doesn’t work

  • Call to protected method instructions(): Make instructions() public.
  • A facade root has not been set: Tests that use base_path() need Laravel booted. Put them in tests/Feature, not tests/Unit.

Check yourself

Leo’s rules live in LEO.md, like Splinter’s list on the lair wall. Why do guidelines go in instructions and not in the history?

Reveal answer

✓ Answer

Instructions are sent fresh every request and never compacted, so the rules cannot be lost.