TechnicalBuild an agent

Build an agentLesson 8 of 10

Compacting long conversations

Stop a long conversation getting too big by replacing it with a summary.

3 min readLesson

Build an agent8

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

You'll learn

  • Explain why history cannot grow forever
  • Create a PHP attribute to configure each agent
  • Read the attribute with Reflection
  • Summarise the history and reset it

How it works

History grows with every message and tool result. Eventually it is too long, and too expensive, to send. Compacting means: once the history has more items than a limit, ask the AI to summarise it, then replace the whole history with that one summary.

Each agent sets its own limit with a PHP attribute on the class: #[CompactsAfter(30)]. The base Agent reads it with PHP’s Reflection API and falls back to 30.

The check runs at the start of every prompt(): maybeCompact() → shouldCompact() → compact().

  • Context window: The most text the AI can take in one request.
  • Attribute: A small class of settings attached to another class. It does nothing until code reads it.
  • Reflection: PHP’s way of inspecting a class at runtime, including its attributes.

Step by step

1Create the attribute

Create this new file.

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) {}
}

The CompactsAfter attribute class.

The CompactsAfter attribute class.

2Add compacting to the Agent class

Replace Agent.php with this version. Compared to Lesson 6 it adds two imports, a $this->maybeCompact(); call as the first line of prompt(), and a new “Compacting” section at the bottom with four methods.

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

The history is sent to the summariser as one block of JSON text. Sending it as normal messages can cause API errors when it contains tool calls.

maybeCompact() and shouldCompact().

maybeCompact() and shouldCompact().

compact(): summarise, then reset the history.

compact(): summarise, then reset the history.

3Put the attribute on the chatbot

For testing, use a tiny limit so you can see it happen. Open ChatbotAgent.php, add use App\Ai\Attributes\CompactsAfter; to the imports, and add the attribute on the line above the class:

Edit · app/Ai/Agents/ChatbotAgent.php

#[CompactsAfter(3)]
class ChatbotAgent extends Agent

Change it back to 30 when you have finished testing.

Replace file · app/Ai/Agents/ChatbotAgent.php (with 30)

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

Testing with a threshold of 3.

Testing with a threshold of 3.

Check your work

Run php artisan agent and type:

Have three or four short exchanges, e.g. My name is Sam, then I like tea, then What do you know about me?

You should see

It still knows your name and that you like tea, even though the history was replaced. To see the summary, temporarily add dump($this->history); at the end of compact(): one item starting [Earlier Conversation Summary].

If it doesn’t work

  • It never compacts: The check is <, not <=: it compacts only once the count goes over the limit. Each turn adds at least two items.
  • Request timed out: Summaries can be slow. The Agent sets Http::timeout(120); raise it if needed.

Check yourself

1The sewer chat has gone on all night. Why is the summary added with role: user?

Reveal answer

✓ Answer

So the AI treats it as context it was given, not as something it said itself.

2What is a simpler but cruder alternative to summarising the patrol?

Reveal answer

✓ Answer

Dropping the oldest messages. Summarising keeps the important facts.