Search by

adachsoft / ai-agent-memory-budget-tool

Arkadiusz Adach

Memory budget conversation context strategy with self-managed soft-clear tool for adachsoft/ai-agent.

Package info

gitlab.com/a.adach/ai-agent-memory-budget-tool

Issues

pkg:composer/adachsoft/ai-agent-memory-budget-tool

Statistics

Installs: 8

Dependents: 0

Suggesters: 0

Stars: 0

v0.1.1 2026-11-27 21:57 UTC

This package is auto-updated.

Last update: 2026-11-27 20:57:30 UTC


README

Memory budget management for adachsoft/ai-agent conversations, with a self-managed soft-clear tool.

This package provides:

  • MemoryBudgetConversationContextStrategy – a conversation context strategy that:
    • applies soft clear based on a trim marker (clearedAt),
    • enforces a hard token limit with safe auto-eviction of the oldest messages,
    • injects a configurable memory status message into the conversation,
  • clear_conversation tool (ClearConversationTool) – a tool that marks the current conversation as soft-cleared,
  • SPI interfaces for plugging in your own storage, token counter and conversation id provider.

The goal of this package is to keep LLM conversation context under control without losing the full history in your storage.

Installation

Require the package in your application (standalone usage):

composer require adachsoft/ai-agent-memory-budget-tool

In a monorepo setup (like this repository), the package is wired via a path repository in the root composer.json:

{
  "repositories": [
    {
      "type": "path",
      "url": "packages/ai-agent-memory-budget-tool",
      "options": { "symlink": true }
    }
  ],
  "require": {
    "adachsoft/ai-agent-memory-budget-tool": "*@dev"
  }
}

Requirements

  • PHP 8.3 or later.
  • Composer for installing the package and its dependencies.

Strategy: MemoryBudgetConversationContextStrategy

MemoryBudgetConversationContextStrategy implements AdachSoft\AiAgent\Spi\Conversation\ConversationContextStrategyInterface.

On every turn it performs three steps:

  1. Soft clear – hides messages older than the last clearedAt marker;
  2. Hard limit eviction – optionally evicts the oldest messages until the token budget fits the configured limit;
  3. Status injection – optionally injects a memory status message into the conversation.

The strategy is stateless – it only reads the trim marker and never writes it. The clear_conversation tool is responsible for setting the marker.

Parameters (MemoryBudgetStrategyParams)

All configuration keys are defined as constants in MemoryBudgetStrategyParams. Defaults are chosen to be safe for most usages.

KeyDefaultDescription
hard_limit_tokens20000Hard token budget for the trimmed conversation (without the injected status message).
alert_threshold_percent95Percentage of the budget that triggers an additional alert appended to the status message.
status_injection_enabledtrueWhen false, no status message is injected.
status_injection_role'system'Role of the injected status message.
status_injection_position'end'Where to inject the status message: start, before_last or end.
status_message_template'[Memory] %d%% used (%d / %d tokens).'sprintf template for the base status message: (percent, usedTokens, hardLimitTokens).
alert_message_template' [ALERT] Memory budget almost exhausted (%d%%). Summarize and call clear_conversation tool to reset.'sprintf template appended to the status message when the alert threshold is reached or exceeded. Empty string disables the alert.
eviction_enabledtrueWhen true, messages are auto-evicted to respect the hard limit. When false, strategy only performs soft clear and status injection.

Additional notes:

  • Status message tokens are not counted into usedTokens within a single transform() call. They will be included naturally on the next turn.
  • Hard limit eviction always preserves integrity of assistant(toolCalls) ↔ tool(result) pairs.

Tool: clear_conversation

ClearConversationTool implements AdachSoft\AiToolCall\SPI\ToolInterface and exposes a single tool named clear_conversation.

Description (tool definition):

Soft-clear the current conversation memory. Marks all current and earlier messages as hidden from the model in future turns while keeping them in storage. Call this when the memory budget alert appears or when starting a new logical task.

The tool uses an operation-based API with a single supported operation:

  • operation = "clear" – sets the clearedAt marker for the current conversation to "now".

Parameters schema

The tool advertises the following JSON schema in its definition:

{
  "type": "object",
  "required": ["operation"],
  "properties": {
    "operation": {
      "type": "string",
      "enum": ["clear"]
    }
  },
  "additionalProperties": false
}

A typical tool call payload:

{
  "operation": "clear"
}

On success, the tool returns a result payload similar to:

{
  "operation": "clear",
  "conversation_id": "123e4567-e89b-12d3-a456-426614174000",
  "cleared_at": "2025-01-01T12:34:56+00:00",
  "cleared": true
}

SPI overview

The package defines three key SPIs which you must implement or configure in your host application:

ConversationTrimMarkerRepositoryInterface

Responsible for persisting trim markers used by the strategy:

  • find(string $conversationId): ?ConversationTrimMarkerDto – returns the current marker or null;
  • save(ConversationTrimMarkerDto $marker): void – creates or updates the marker for a conversation;
  • delete(string $conversationId): void – removes a marker (no-op if missing).

A simple in-memory implementation InMemoryConversationTrimMarkerRepository is provided for tests and prototypes.

ConversationIdProviderInterface

Abstracts how the current conversation id is obtained:

  • getCurrentConversationId(): string – must return a stable id for the current conversation context.

If the id is not available, the implementation must throw ConversationIdUnavailableException. The clear_conversation tool will surface this as a ToolExecutionException.

TokenCounterInterface

Calculates the token usage for a given conversation slice:

  • countMessages(ChatMessageDtoCollection $messages): int – must return a non-negative integer.

By default the package uses ApproximateTokenCounter, which estimates token count as ceil(chars / 4) over role values, text and media content, tool-call names and JSON arguments, and tool-result content text. Tool-result text is already serialized and is not JSON-encoded again. You can replace it with a real tokenizer-based implementation if needed.

Wiring example

Below is a simplified example showing how you might wire the strategy and the tool inside your application. The exact wiring depends on your framework and DI container.

<?php

use AdachSoft\AiAgent\Spi\Conversation\ConversationContextStrategyInterface;
use AdachSoft\AiConversationModel\Message\Collection\ChatMessageDtoCollection;
use AdachSoft\AiAgentMemoryBudgetTool\MemoryBudgetConversationContextStrategy;
use AdachSoft\AiAgentMemoryBudgetTool\MemoryBudgetStrategyParams;
use AdachSoft\AiAgentMemoryBudgetTool\Spi\Repository\InMemoryConversationTrimMarkerRepository;
use AdachSoft\AiAgentMemoryBudgetTool\Spi\Conversation\ConversationIdProviderInterface;
use AdachSoft\AiAgentMemoryBudgetTool\Spi\Token\TokenCounterInterface;
use AdachSoft\AiAgentMemoryBudgetTool\Internal\ApproximateTokenCounter;
use AdachSoft\AiAgentMemoryBudgetTool\Tool\ClearConversationToolFactory;
use AdachSoft\AiToolCall\SPI\Collection\ConfigMap;

final class MyConversationIdProvider implements ConversationIdProviderInterface
{
    public function __construct(private readonly string $conversationId) {}

    public function getCurrentConversationId(): string
    {
        return $this->conversationId;
    }
}

// Shared infrastructure
$markerRepository = new InMemoryConversationTrimMarkerRepository();
$tokenCounter    = new ApproximateTokenCounter(); // or your own TokenCounterInterface

// Strategy wiring (registered under STRATEGY_ID in your agent runtime)
$strategy = new MemoryBudgetConversationContextStrategy(
    markerRepository: $markerRepository,
    tokenCounter: $tokenCounter,
);

// Example usage in your agent loop
$conversationId = '123e4567-e89b-12d3-a456-426614174000';
$fullHistory    = new ChatMessageDtoCollection(/* ... */);

$params = [
    MemoryBudgetStrategyParams::HARD_LIMIT_TOKENS => 20000,
    MemoryBudgetStrategyParams::ALERT_THRESHOLD_PERCENT => 95,
];

$trimmedWithStatus = $strategy->transform($conversationId, $fullHistory, $params);

// Tool wiring
$conversationIdProvider = new MyConversationIdProvider($conversationId);
$toolFactory            = ClearConversationToolFactory::withDefaults(
    markerRepository: $markerRepository,
    conversationIdProvider: $conversationIdProvider,
);

$clearConversationTool = $toolFactory->create(new ConfigMap([]));

You would then register both the strategy and the tool in your adachsoft/ai-agent configuration (for example via Symfony container wiring in this monorepo).

Testing

This package ships with its own PHPUnit configuration. From the monorepo root run:

vendor/bin/phpunit -c packages/ai-agent-memory-budget-tool/phpunit.xml.dist

For standalone usage (outside this monorepo), run PHPUnit with the package-level configuration file:

vendor/bin/phpunit -c phpunit.xml.dist

The test suite is expected to pass with no deprecations and no notices under PHPUnit 12.