Configure and manage conversation history storage with flexible drivers and truncation strategies
The Chat History system in LarAgent stores and manages conversation messages between users and AI agents. It provides automatic persistence, lazy loading, and flexible storage driver configuration.
Set storage drivers directly in your agent class using the $history property:
Using String Aliases
Using Driver Classes
Method Override
Copy
class SupportAgent extends Agent{ protected $instructions = 'You are a helpful support agent.'; // Use string alias for built-in storage protected $history = 'cache';}
Copy
use LarAgent\Context\Drivers\CacheStorage;use LarAgent\Context\Drivers\FileStorage;class SupportAgent extends Agent{ protected $instructions = 'You are a helpful support agent.'; // Single driver or array with fallback chain protected $history = [ CacheStorage::class, // Primary FileStorage::class, // Fallback ];}
Copy
class CustomAgent extends Agent{ protected $instructions = 'You are a custom agent.'; protected function historyStorageDrivers(): string|array { return [ new EloquentStorage(\App\Models\CustomMessage::class), ]; }}
// Get the chat history instance$chatHistory = $agent->chatHistory();// Get all messages$messages = $chatHistory->getMessages();// Get the last message$lastMessage = $chatHistory->getLastMessage();// Get message count$count = $chatHistory->count();// Convert to array$messagesArray = $chatHistory->toArray();
use LarAgent\Message;// Add a user message$agent->addMessage(Message::user('Hello, I need help.'));// Add an assistant message$agent->addMessage(Message::assistant('Of course! How can I help you?'));// Add a system message$agent->addMessage(Message::system('Additional context...'));
All messages support metadata. Use $message->addMeta([...]) to attach custom data or pass it during creation as second argument Message::user('text', ['key' => 'value']).
// Metadata automatically added to messages[ 'agent' => 'SupportAgent', // Agent name 'model' => 'gpt-4', // Model used // Custom metadata added via $message->addMeta([...])]
// Clear all messages (keeps the session)$agent->clear();// Using Context Facade for bulk operationsuse LarAgent\Facades\Context;// Clear all chats for an agentContext::of(SupportAgent::class)->clearAllChats();// Clear all chats for a specific userContext::of(SupportAgent::class) ->forUser('user-123') ->clearAllChats();
Check out the Context Facade for more on using the Context facade.
You can also use artisan commands during development to clear chat histories.
// Read/refresh from storage$agent->chatHistory()->read();// Save to storage (only if there are changes)$agent->chatHistory()->save();// Force write to storage (bypasses dirty check)$agent->chatHistory()->writeToMemory();// Force read from storage drivers (bypasses lazy loading)$agent->chatHistory()->readFromMemory();
Control when chat history is synchronized with storage:
Copy
class SupportAgent extends Agent{ /** * Force read history from storage on agent initialization * Default: false (uses lazy loading) */ protected $forceReadHistory = false; /** * Force save history after each agent response * Default: false (saves at end of request lifecycle) */ protected $forceSaveHistory = false;}
In long-running environments (Laravel Octane, FrankenPHP, Swoole), agent instances may persist across requests. Use both flags to ensure data freshness:
Copy
class OctaneSafeAgent extends Agent{ protected $instructions = 'You are a helpful assistant.'; // Always read fresh data protected $forceReadHistory = true; // Save immediately protected $forceSaveHistory = true;}
When conversations exceed the model’s context window, truncation strategies automatically reduce the conversation size while preserving important context.
Override the truncationStrategy() method for full control:
Copy
use LarAgent\Context\Truncation\SummarizationStrategy;class CustomTruncationAgent extends Agent{ protected $instructions = 'You are a helpful assistant.'; /** * Override to provide a custom truncation strategy. */ protected function truncationStrategy(): ?\LarAgent\Context\Contracts\TruncationStrategy { return new SummarizationStrategy([ 'keep_messages' => 20, 'summary_agent' => \App\AiAgents\CustomSummarizerAgent::class, 'summary_title' => 'Previous conversation context', 'preserve_system' => true, ]); } /** * Override to check if truncation should be enabled. */ public function shouldTruncate(): bool { // Custom logic - e.g., only truncate in production if (app()->environment('testing')) { return false; } return parent::shouldTruncate(); } /** * Override to set a custom truncation threshold. */ public function getTruncationThreshold(): int { // Dynamic threshold based on model return match ($this->model()) { 'gpt-4' => 50000, 'gpt-3.5-turbo' => 10000, default => 30000, }; }}
The truncationThreshold is NOT the model’s context window. Set it to 30-50% of the model’s actual context window to leave room for system prompts, tools, and responses.