TechnicalBuild an agent

Build an agentLesson 6 of 10

Agent classes and structured output

Move the agent loop into reusable Agent classes, and force an answer into an exact JSON shape.

4 min readLesson

Build an agent6

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

You'll learn

  • Move the loop out of the command into a base Agent class
  • Make different agents by overriding persona(), tools() and schema()
  • Use structured output so the answer always has the same keys
  • Call an agent from ordinary code, not only a chat

How it works

Different jobs need different agents: a sarcastic chatbot, a grammar helper and so on. So the loop moves into a base Agent class. Each child agent overrides its persona (who it is), its tools and, optionally, its schema.

Structured output means giving the AI a JSON Schema for its final answer. It must reply in that shape, so your code can rely on keys like nouns or verbs always being there. It goes in the request as text.format.

The command becomes tiny: create the agent once, then call $agent->prompt($prompt) in a loop.

  • Persona: The agent’s own part of the instructions, e.g. “You are sarcastic…”.
  • JSON Schema: A standard way to describe the shape of JSON: types, required keys, allowed values.
  • text.format: Where the schema goes in the request.

Step by step

1Create the base Agent class

This holds the loop from AgentCommand, now split into prompt(), runTool() and runModel(). It only sends tools and text.format when the agent has some.

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

<?php

namespace App\Ai\Agents;

use App\Ai\Tools\Tool;
use Illuminate\Support\Facades\Http;

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: what the AI is told before every request
    // ---------------------------------------------------------------

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

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

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

    public function prompt(string $prompt): string
    {
        $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");
    }
}

The loop now lives in the Agent class.

The loop now lives in the Agent class.

2Create the chatbot agent

Your chat agent: a persona and the three tools you have built so far.

New file · app/Ai/Agents/ChatbotAgent.php

<?php

namespace App\Ai\Agents;

use App\Ai\Tools\CurrentTime;
use App\Ai\Tools\ReadFile;
use App\Ai\Tools\Revenue;

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 CurrentTime,
            new ReadFile,
            new Revenue,
        ];
    }
}

3Slim down AgentCommand

Replace the whole command. The loop has moved into the agent, so all that is left is asking for input and printing the answer. Typing exit now quits.

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

Create the agent before the while loop. Inside it, every message would start a new agent with an empty history.

The command just prompts the agent.

The command just prompts the agent.

4Create a grammar agent with a schema

This agent has no tools, but it has a schema(). Its answer will always be an object with nouns, adjectives and verbs lists.

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

Structured output: text.format with a JSON schema.

Structured output: text.format with a JSON schema.

GrammarAssistantAgent: its own instructions and schema.

GrammarAssistantAgent: its own instructions and schema.

5Create a command that uses it

Generate the command, then replace its contents. It sends one sentence and dumps the decoded array.

Run

php artisan make:command GrammarCommand

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

Check your work

Run

Run

php artisan grammar "The big brown dog jumps over the green car."

You should see

An array like nouns: [dog, car], adjectives: [big, brown, green], verbs: [jumps]. Run it again: the keys are always the same. Then run php artisan agent and check the chatbot still uses its tools (and is a little rude).

If it doesn’t work

  • expected an object but got an array (text.format): You sent an empty schema. Only add text.format when schema() is not empty.
  • The agent forgets everything each message: You create the agent inside the while loop. Move it above.

Check yourself

1A new turtle extends the base agent. What three methods does a child agent override?

Reveal answer

✓ Answer

persona(), tools() and schema().

2April’s code needs the pizza total on fixed keys. Why is structured output useful when calling an agent from code?

Reveal answer

✓ Answer

Your code can read fixed keys from the answer instead of parsing free text.