TechnicalBuild an agent

Build an agentLesson 5 of 10

Make a revenue tool

Answer “How much did we earn last quarter?” with a tool that only accepts a fixed list of options.

2 min readLesson

Build an agent5

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

You'll learn

  • Add a new tool in two steps
  • Limit an argument to a set of values with enum
  • Return tool results as strings

How it works

A new tool is just a new class. site_revenue takes one argument, period, and an enum limits it to daily, monthly, quarterly or yearly.

With strict on, the AI can only send one of those four values. The numbers here are made up. In a real app this is where your database query would go.

  • enum: JSON Schema for “only these values are allowed”.

Step by step

1Create the Revenue tool

Create this new file.

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;
    }
}

The enum limits period to four values.

The enum limits period to four values.

use() looks up a (fake) number for the period.

use() looks up a (fake) number for the period.

2Register the tool

Open AgentCommand.php. Add use App\Ai\Tools\Revenue; to the imports at the top, then change the line inside tools() to this:

Edit · AgentCommand.php → tools()

return [new CurrentTime, new ReadFile, new Revenue];

Prefer to replace the whole file? The complete version is below.

Replace file · app/Console/Commands/AgentCommand.php

<?php

namespace App\Console\Commands;

use App\Ai\Tools\CurrentTime;
use App\Ai\Tools\ReadFile;
use App\Ai\Tools\Revenue;
use App\Ai\Tools\Tool;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Http;

use function Laravel\Prompts\info;
use function Laravel\Prompts\spin;
use function Laravel\Prompts\text;

// Lesson 5: each tool is its own class; the loop just finds and runs it.
class AgentCommand extends Command
{
    protected $signature = 'agent';

    protected $description = 'Chat with an agent that can use tools';

    protected array $history = [];

    public function handle(): void
    {
        // OUTER loop: your conversation with the agent.
        while (true) {
            $prompt = text('What is on your mind?', required: true);

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

            // INNER loop: the agent keeps going until it has an answer.
            while (true) {
                $response = spin(fn () => $this->runModel(), 'Hmm... thinking about that.');

                $this->history = [...$this->history, ...$response['output']];

                // Find every tool the AI wants us to run (there can be several).
                $functionCalls = collect($response['output'])
                    ->filter(fn ($item) => $item['type'] === 'function_call');

                // None? Then the AI has its final answer.
                if ($functionCalls->isEmpty()) {
                    info($this->outputText($response));
                    break;
                }

                $functionCalls->each(function (array $call) {
                    info("Running tool: {$call['name']}");

                    // Find the tool whose name matches the call.
                    $tool = collect($this->tools())
                        ->first(fn (Tool $tool) => $tool->definition()['name'] === $call['name']);

                    // Decode the arguments once, so every tool gets a plain PHP array.
                    $output = $tool
                        ? $tool->use(json_decode($call['arguments'], associative: true) ?? [])
                        : "Error: unknown tool {$call['name']}";

                    $this->history[] = [
                        'type' => 'function_call_output',
                        'call_id' => $call['call_id'],
                        'output' => (string) $output,
                    ];
                });
            }
        }
    }

    // Every tool the agent may use. New tool = new class + one entry here.
    protected function tools(): array
    {
        return [new CurrentTime, new ReadFile, new Revenue];
    }

    protected function runModel(): array
    {
        return Http::withToken(config('services.openai.key'))
            ->post('https://api.openai.com/v1/responses', [
                'model' => config('services.openai.model'),
                'instructions' => 'You are a helpful assistant.',
                'input' => $this->history,
                // Send each tool's definition, not the tool object itself.
                'tools' => array_map(fn (Tool $tool) => $tool->definition(), $this->tools()),
            ])
            ->throw()
            ->json();
    }

    // The first output item is not always a message (it can be a tool call),
    // so collect the text from every message item instead of using [0].
    protected function outputText(array $response): string
    {
        return collect($response['output'])
            ->where('type', 'message')
            ->flatMap(fn ($message) => $message['content'])
            ->where('type', 'output_text')
            ->pluck('text')
            ->implode("\n");
    }
}

Check your work

Run php artisan agent and type:

How much did we earn last quarter?

You should see

Running tool: site_revenue, then $120,000.

If it doesn’t work

  • Invalid type for output: expected a string: A tool returned a number. Cast it: (string) $revenue.
  • Copied the definition from ReadFile?: Update required too. It must say ['period'], not ['path'].

Check yourself

Leo can report pizza money for last month, last quarter, or last year. What stops the AI asking for “weekly” revenue?

Reveal answer

✓ Answer

The enum list, together with 'strict' => true.