adachsoft / ai-agent-memory-budget-tool
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
pkg:composer/adachsoft/ai-agent-memory-budget-tool
Requires
- php: ^8.3
- adachsoft/ai-agent: ^0.13 || ^0.14
- adachsoft/ai-conversation-model: ^0.2.0
- adachsoft/ai-tool-call: ^2.0.0
- justinrainbow/json-schema: ^5.2 || ^6.0
- psr/clock: ^1.0
Requires (Dev)
- adachsoft/php-code-style: ^0.7.4
- friendsofphp/php-cs-fixer: ^3.95
- phpstan/phpstan: ^2.3
- phpunit/phpunit: ^12.4
- rector/rector: ^2.9
- symplify/phpstan-rules: ^14.19
Suggests
None
Provides
None
Conflicts
None
Replaces
None
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,
- applies soft clear based on a trim marker (
clear_conversationtool (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:
- Soft clear – hides messages older than the last
clearedAtmarker; - Hard limit eviction – optionally evicts the oldest messages until the token budget fits the configured limit;
- 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.
| Key | Default | Description |
|---|---|---|
hard_limit_tokens | 20000 | Hard token budget for the trimmed conversation (without the injected status message). |
alert_threshold_percent | 95 | Percentage of the budget that triggers an additional alert appended to the status message. |
status_injection_enabled | true | When 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_enabled | true | When 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
usedTokenswithin a singletransform()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 theclearedAtmarker 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 ornull;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.