TechnicalBuild an agent

Build an agentLesson 3 of 10

The agent loop

Give the AI tools, and add an inner loop that runs them until the AI has an answer.

4 min readLesson

Build an agent3

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

You'll learn

  • Describe a tool to the AI with a name, description and parameters
  • Spot function_call items in a reply and run them
  • Send results back with function_call_output and a matching call_id
  • Explain the difference between the outer and inner loop

How it works

Ask the chat “What time is it?” and it cannot know. Tools fix that. A tool is a function you describe to the AI. When it needs one, it asks your code to run it.

You list tools in the request. When the AI wants one, its output contains a function_call item with the tool name, the arguments (as a JSON string) and a call_id.

Your code runs the tool, adds a function_call_output with the same call_id to the history, and calls the AI again. That repeat is the inner loop. When a reply contains no function calls, the AI is done: print the text and go back to waiting for you.

  • Outer loop: Your back-and-forth with the agent.
  • Inner loop: The agent calling tools and the AI again until it has an answer.
  • call_id: Links each tool result to the request it answers.
  • 'strict' => true: Forces the AI to send arguments in exactly the shape you declared.

Step by step

1Generate the command

This is the command you will keep improving for the rest of the course.

Run

php artisan make:command AgentCommand

2Write the agent loop

Replace the file with this. Read it in this order: the outer while, the inner while, finding function calls, running them, adding the outputs, and going round again.

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

<?php

namespace App\Console\Commands;

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 3: an outer loop (you) and an inner loop (the agent using tools).
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']}");

                    $output = match ($call['name']) {
                        'get_current_time' => now()->toIso8601String(),
                        'read_file' => file_get_contents(
                            base_path(json_decode($call['arguments'])->path)
                        ),
                        default => "Error: unknown tool {$call['name']}",
                    };

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

    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,
                'tools' => [
                    [
                        'type' => 'function',
                        'name' => 'get_current_time',
                        'description' => 'Get the current server time as an ISO 8601 string.',
                    ],
                    [
                        '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,
                    ],
                ],
            ])
            ->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");
    }
}

The small outputText() helper replaces output[0].content[0].text. Once tools are involved, the first output item is often a function call rather than a message.

Adding a tools array to the request: get_current_time.

Adding a tools array to the request: get_current_time.

Answering a tool call with a function_call_output and its call_id.

Answering a tool call with a function_call_output and its call_id.

A tool with parameters: read_file takes a path.

A tool with parameters: read_file takes a path.

Collecting every function_call with collect()->filter().

Collecting every function_call with collect()->filter().

3Run it

Ask something that needs a tool.

Run

php artisan agent

Check your work

Run php artisan agent and type:

What time is it? Then try: Read package.json and composer.json and tell me what this project uses.

You should see

Running tool: get_current_time then the time. For the second prompt, two Running tool: read_file lines (one per file), then a summary.

If it doesn’t work

  • Undefined array key "content": You are reading output[0] when it is a function call. Use outputText().
  • Answer prints forever: The break after printing the final answer is missing.
  • Attempt to read property "type" on array: Items are arrays: use $item['type'], not $item->type.
  • Invalid type for input: You pushed an array inside an array. Add one item: $this->history[] = [...].
  • Crash when the file does not exist: Expected for now. Lesson 4 makes read_file return a friendly error instead.

Check yourself

1Leo asks for two tools in one reply: find the pizza, then check the sewer map. How many function_call_output items do you add?

Reveal answer

✓ Answer

Two, one per call, each with its own call_id.

2How does the inner loop know Leo is finished and can sheath the katanas?

Reveal answer

✓ Answer

The reply contains no function_call items.

3Does the AI run the tool itself, or does your PHP do the sewer work?

Reveal answer

✓ Answer

No. It only asks. Your PHP runs the tool and sends back the result.