leo-the-agent/
├── LEO.md guidelines (Lesson 9)
├── app/
│ ├── Ai/
│ │ ├── Agents/ Agent, ChatbotAgent, GrammarAssistantAgent
│ │ ├── Attributes/ CompactsAfter (Lesson 8)
│ │ ├── Memory/ Store (Lesson 10)
│ │ └── Tools/ Tool + 10 tools, Concerns/ResolvesProjectPaths
│ └── Console/Commands/ Chat, Dialog, Agent, Grammar
├── storage/LEO_MEMORY.md created by the remember tool
└── tests/Feature/AgentTest.php
Build an agentReference
Final code
The finished agent after Lesson 10. Pick a file and copy it.
1 min readReference
Where everything lives
Every file
New file · app/Ai/Agents/Agent.php
<?php
namespace App\Ai\Agents;
use App\Ai\Attributes\CompactsAfter;
use App\Ai\Memory\Store;
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 + memory
// ---------------------------------------------------------------
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);
}
if ($memory = (new Store)->fetch()) {
$instructions .= "\n\n## What You Remember About The User\n\n".$memory;
}
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)],
];
}
}
New file · app/Ai/Agents/ChatbotAgent.php
<?php
namespace App\Ai\Agents;
use App\Ai\Attributes\CompactsAfter;
use App\Ai\Tools\CurrentTime;
use App\Ai\Tools\EditFile;
use App\Ai\Tools\Glob;
use App\Ai\Tools\Memory;
use App\Ai\Tools\ReadFile;
use App\Ai\Tools\Revenue;
use App\Ai\Tools\RunBash;
use App\Ai\Tools\SearchFiles;
use App\Ai\Tools\WriteFile;
#[CompactsAfter(30)]
class ChatbotAgent extends Agent
{
public function persona(): string
{
return 'You are a bit of a jerk and are sarcastic with every reply, but you help out with programming tasks.';
}
public function tools(): array
{
return [
new ReadFile,
new WriteFile,
new EditFile,
new Glob,
new SearchFiles,
new RunBash,
new CurrentTime,
new Revenue,
new Memory,
];
}
}
New file · app/Ai/Agents/GrammarAssistantAgent.php
<?php
namespace App\Ai\Agents;
class GrammarAssistantAgent extends Agent
{
public function persona(): string
{
return 'You are a helpful grammar assistant for third grade. '
.'Your only job is to split the sentence you are given into its grammatical parts.';
}
public function schema(): array
{
$list = ['type' => 'array', 'items' => ['type' => 'string']];
return [
'type' => 'object',
'properties' => [
'nouns' => $list,
'adjectives' => $list,
'verbs' => $list,
],
'required' => ['nouns', 'adjectives', 'verbs'],
'additionalProperties' => false,
];
}
}
New file · app/Ai/Attributes/CompactsAfter.php
<?php
namespace App\Ai\Attributes;
use Attribute;
#[Attribute(Attribute::TARGET_CLASS)]
class CompactsAfter
{
public function __construct(public readonly int $threshold) {}
}
New file · app/Ai/Memory/Store.php
<?php
namespace App\Ai\Memory;
class Store
{
public function path(): string
{
return storage_path('LEO_MEMORY.md');
}
public function fetch(): string
{
return @file_get_contents($this->path()) ?: '';
}
public function update(string $memory): void
{
// LOCK_EX stops two writes from clashing.
file_put_contents($this->path(), $memory, LOCK_EX);
}
}
New file · app/Ai/Tools/Tool.php
<?php
namespace App\Ai\Tools;
interface Tool
{
/**
* The JSON description the AI reads to decide whether to call this tool.
*/
public function definition(): array;
/**
* Actually run the tool. $arguments are already JSON-decoded.
*/
public function use(array $arguments = []): string;
}
New file · app/Ai/Tools/Concerns/ResolvesProjectPaths.php
<?php
namespace App\Ai\Tools\Concerns;
trait ResolvesProjectPaths
{
/**
* Turn a relative path into an absolute one inside the project,
* and refuse anything that tries to escape it (e.g. "../../etc/passwd").
*/
protected function resolve(string $path): ?string
{
$root = realpath(base_path());
$full = $root.'/'.ltrim($path, '/');
// For files or folders that don't exist yet, check the nearest folder that does.
$check = $full;
while (! file_exists($check) && $check !== dirname($check)) {
$check = dirname($check);
}
$real = realpath($check);
if ($real === false || ($real !== $root && ! str_starts_with($real, $root.'/'))) {
return null;
}
return $full;
}
}
New file · app/Ai/Tools/CurrentTime.php
<?php
namespace App\Ai\Tools;
class CurrentTime implements Tool
{
public function definition(): array
{
return [
'type' => 'function',
'name' => 'get_current_time',
'description' => 'Get the current server time as an ISO 8601 string.',
];
}
public function use(array $arguments = []): string
{
return now()->toIso8601String();
}
}
New file · app/Ai/Tools/ReadFile.php
<?php
namespace App\Ai\Tools;
use App\Ai\Tools\Concerns\ResolvesProjectPaths;
class ReadFile implements Tool
{
use ResolvesProjectPaths;
public function definition(): array
{
return [
'type' => 'function',
'name' => 'read_file',
'description' => 'Read the contents of a file, relative to the project root.',
'parameters' => [
'type' => 'object',
'properties' => [
'path' => ['type' => 'string', 'description' => 'The relative path to the file.'],
],
'required' => ['path'],
'additionalProperties' => false,
],
'strict' => true,
];
}
public function use(array $arguments = []): string
{
$path = $this->resolve($arguments['path']);
if (! $path || ! is_file($path)) {
return "Error: file not found: {$arguments['path']}";
}
return file_get_contents($path);
}
}
New file · app/Ai/Tools/Revenue.php
<?php
namespace App\Ai\Tools;
class Revenue implements Tool
{
public function definition(): array
{
return [
'type' => 'function',
'name' => 'site_revenue',
'description' => 'Get the site revenue for a daily, monthly, quarterly or yearly period.',
'parameters' => [
'type' => 'object',
'properties' => [
'period' => [
'type' => 'string',
'enum' => ['daily', 'monthly', 'quarterly', 'yearly'],
'description' => 'The period of time to fetch revenue for.',
],
],
'required' => ['period'],
'additionalProperties' => false,
],
'strict' => true,
];
}
public function use(array $arguments = []): string
{
// Fake numbers. In a real app this would be a database query.
$revenue = [
'daily' => 900,
'monthly' => 30000,
'quarterly' => 120000,
'yearly' => 480000,
][$arguments['period']] ?? null;
return $revenue === null ? 'Unknown period.' : (string) $revenue;
}
}
New file · app/Ai/Tools/WriteFile.php
<?php
namespace App\Ai\Tools;
use App\Ai\Tools\Concerns\ResolvesProjectPaths;
class WriteFile implements Tool
{
use ResolvesProjectPaths;
public function definition(): array
{
return [
'type' => 'function',
'name' => 'write_file',
'description' => 'Create a file, or completely overwrite an existing one, relative to the project root.',
'parameters' => [
'type' => 'object',
'properties' => [
'path' => ['type' => 'string', 'description' => 'The relative path to the file.'],
'content' => ['type' => 'string', 'description' => 'The full contents to write.'],
],
'required' => ['path', 'content'],
'additionalProperties' => false,
],
'strict' => true,
];
}
public function use(array $arguments = []): string
{
$path = $this->resolve($arguments['path']);
if (! $path) {
return 'Error: path is outside the project.';
}
if (! is_dir(dirname($path))) {
mkdir(dirname($path), 0755, recursive: true);
}
file_put_contents($path, $arguments['content']);
return "Wrote {$arguments['path']}";
}
}
New file · app/Ai/Tools/EditFile.php
<?php
namespace App\Ai\Tools;
use App\Ai\Tools\Concerns\ResolvesProjectPaths;
class EditFile implements Tool
{
use ResolvesProjectPaths;
public function definition(): array
{
return [
'type' => 'function',
'name' => 'edit_file',
'description' => 'Replace one exact piece of text in a file with new text. Read the file first.',
'parameters' => [
'type' => 'object',
'properties' => [
'path' => ['type' => 'string', 'description' => 'The relative path to the file.'],
'old_text' => ['type' => 'string', 'description' => 'The exact text to find. Must appear once.'],
'new_text' => ['type' => 'string', 'description' => 'The text to put in its place.'],
],
'required' => ['path', 'old_text', 'new_text'],
'additionalProperties' => false,
],
'strict' => true,
];
}
public function use(array $arguments = []): string
{
$path = $this->resolve($arguments['path']);
if (! $path || ! is_file($path)) {
return "Error: file not found: {$arguments['path']}";
}
$contents = file_get_contents($path);
$count = substr_count($contents, $arguments['old_text']);
if ($count !== 1) {
return "Error: expected the text to appear once, found it {$count} times.";
}
file_put_contents($path, str_replace($arguments['old_text'], $arguments['new_text'], $contents));
return "Edited {$arguments['path']}";
}
}
New file · app/Ai/Tools/Glob.php
<?php
namespace App\Ai\Tools;
class Glob implements Tool
{
public function definition(): array
{
return [
'type' => 'function',
'name' => 'glob',
'description' => 'List project files matching a glob pattern, e.g. "routes/*.php" or "app/*/*.php".',
'parameters' => [
'type' => 'object',
'properties' => [
'pattern' => ['type' => 'string', 'description' => 'A glob pattern relative to the project root.'],
],
'required' => ['pattern'],
'additionalProperties' => false,
],
'strict' => true,
];
}
public function use(array $arguments = []): string
{
$root = base_path().'/';
$files = array_map(
fn ($file) => str_replace($root, '', $file),
glob($root.ltrim($arguments['pattern'], '/')) ?: []
);
return $files ? implode("\n", $files) : 'No files matched.';
}
}
New file · app/Ai/Tools/SearchFiles.php
<?php
namespace App\Ai\Tools;
use Symfony\Component\Process\Process;
class SearchFiles implements Tool
{
public function definition(): array
{
return [
'type' => 'function',
'name' => 'search_files',
'description' => 'Search project files for a piece of text. Returns matching lines with file names and line numbers.',
'parameters' => [
'type' => 'object',
'properties' => [
'query' => ['type' => 'string', 'description' => 'The text to search for.'],
'directory' => ['type' => 'string', 'description' => 'Folder to search in, relative to the project root. Use "." for everything.'],
],
'required' => ['query', 'directory'],
'additionalProperties' => false,
],
'strict' => true,
];
}
public function use(array $arguments = []): string
{
$process = new Process(
['grep', '-rn', '--exclude-dir=vendor', '--exclude-dir=node_modules', '-F', $arguments['query'], $arguments['directory']],
base_path(),
timeout: 30,
);
$process->run();
return $process->getOutput() ?: 'No matches.';
}
}
New file · app/Ai/Tools/RunBash.php
<?php
namespace App\Ai\Tools;
use Symfony\Component\Process\Process;
class RunBash implements Tool
{
public function definition(): array
{
return [
'type' => 'function',
'name' => 'run_bash',
'description' => 'Execute a bash command in the project root and return its output.',
'parameters' => [
'type' => 'object',
'properties' => [
'command' => ['type' => 'string', 'description' => 'The bash command to execute.'],
],
'required' => ['command'],
'additionalProperties' => false,
],
'strict' => true,
];
}
public function use(array $arguments = []): string
{
// WARNING: this lets the AI run any command on your machine.
// Only use it on a project you are happy to experiment with.
$process = Process::fromShellCommandline($arguments['command'], base_path(), timeout: 30);
$process->run();
if (! $process->isSuccessful()) {
return $process->getErrorOutput() ?: $process->getOutput();
}
return $process->getOutput();
}
}
New file · app/Ai/Tools/Memory.php
<?php
namespace App\Ai\Tools;
use App\Ai\Agents\Agent;
use App\Ai\Memory\Store;
use Illuminate\Support\Facades\Http;
class Memory implements Tool
{
public function __construct(protected Store $store = new Store) {}
public function definition(): array
{
return [
'type' => 'function',
'name' => 'remember',
'description' => <<<'DESC'
Save a stable, long-term fact about the user or their project.
Only use this for things that will still be useful in future sessions, such as:
- preferences ("prefers Pest over PHPUnit")
- project context ("works on a Laravel + Inertia app")
- identity ("goes by Jeffrey")
Do NOT use it for small talk, temporary state, secrets or API keys,
or anything already in the project guidelines or existing memories.
Write the fact as a short third-person sentence that makes sense on its own.
DESC,
'parameters' => [
'type' => 'object',
'properties' => [
'fact' => ['type' => 'string', 'description' => 'The fact to remember.'],
],
'required' => ['fact'],
'additionalProperties' => false,
],
'strict' => true,
];
}
public function use(array $arguments = []): string
{
$fact = $arguments['fact'];
$memory = $this->store->fetch();
$refreshed = $this->refresh($memory, $fact);
if (trim($refreshed) === trim($memory)) {
return "Fact already known: {$fact}";
}
$this->store->update($refreshed);
return "Fact remembered: {$fact}";
}
/**
* Ask the AI to merge the new fact into the existing memory file.
*/
protected function refresh(string $memory, string $fact): string
{
$response = Http::withToken(config('services.openai.key'))
->post('https://api.openai.com/v1/responses', [
'model' => config('services.openai.model'),
'instructions' => <<<'INSTR'
You maintain a short markdown list of long-term facts about a user.
You get the existing markdown and one new candidate fact. Return the full, updated markdown.
- If the fact is new, add it as a bullet point.
- If it is already covered, return the existing markdown unchanged.
- If it updates or contradicts an existing fact, replace the old fact.
- Do not add or remove anything else. Return only markdown, no code fences.
INSTR,
'input' => [
['role' => 'user', 'content' => "Existing memory:\n\n{$memory}\n\nNew fact:\n\n{$fact}"],
],
])
->throw()
->json();
// If something odd comes back, keep what we had.
return Agent::text($response) ?: $memory;
}
}
New file · app/Console/Commands/AgentCommand.php
<?php
namespace App\Console\Commands;
use App\Ai\Agents\ChatbotAgent;
use Illuminate\Console\Command;
use function Laravel\Prompts\info;
use function Laravel\Prompts\spin;
use function Laravel\Prompts\text;
// The command just talks to an Agent class.
class AgentCommand extends Command
{
protected $signature = 'agent';
protected $description = 'Chat with Leo, the agent';
public function handle(): void
{
// Create the agent ONCE, outside the loop, so it keeps its history.
$agent = new ChatbotAgent;
while (true) {
$prompt = text('What is on your mind?', placeholder: 'Type "exit" to quit', required: true);
if (strtolower(trim($prompt)) === 'exit') {
return;
}
$response = spin(fn () => $agent->prompt($prompt), 'Hmm... thinking about that.');
info($response);
}
}
}
New file · app/Console/Commands/GrammarCommand.php
<?php
namespace App\Console\Commands;
use App\Ai\Agents\GrammarAssistantAgent;
use Illuminate\Console\Command;
// Structured output demo: the answer always comes back in the same JSON shape.
class GrammarCommand extends Command
{
protected $signature = 'grammar {sentence}';
protected $description = 'Split a sentence into nouns, adjectives and verbs';
public function handle(): void
{
$json = (new GrammarAssistantAgent)->prompt($this->argument('sentence'));
dump(json_decode($json, associative: true));
}
}
New 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);
});
New file · LEO.md
## Coding Requirements
- Favor Pest over PHPUnit.
- Never use PHP docblocks.
