from praisonaiagents import get_optimizer, OptimizerStrategy# Get an optimizeroptimizer = get_optimizer(OptimizerStrategy.SMART)# Optimize messages to target token countmessages = [...] # Your conversation historyoptimized, stats = optimizer.optimize(messages, target_tokens=50000)print(f"Reduced from {len(messages)} to {len(optimized)} messages")print(f"Saved {stats.tokens_saved} tokens")
LLM function for conversation analysis. If None, falls back to rule-based analysis.
min_compaction_ratio
float
0.3
Minimum compression ratio to attempt compaction. Below this, falls back to SmartOptimizer.
analyzer_strategy
str
"hybrid"
One of "hybrid", "rule_based", "keyword".
preserve_recent
int
5
Number of recent messages to keep intact.
llm_summarize_fn
Optional[callable]
None
LLM function for summarization.
ConversationOptimizer automatically falls back to SmartOptimizer when the compaction ratio is not meaningful (target_tokens / original_tokens > (1 - min_compaction_ratio)) or when internal errors occur during compaction. This ensures safe operation while preserving advanced conversation analysis when beneficial.
Best for: Multi-hour planning, iterative development, long support sessions where topic/goal continuity matters more than literal message history.See Intelligent Conversation Compaction for the full conceptual deep-dive.
Best for: Long conversations requiring intelligent summarization with audit trails.
The LLMContextCompressorOptimizer is exposed as LLM_CONTEXT_COMPRESSOR_OPTIMIZER but is not in OPTIMIZER_REGISTRY — users must instantiate it directly with an llm_client.
Tags messages for exclusion without deleting them (enables undo).
from praisonaiagents import NonDestructiveOptimizeroptimizer = NonDestructiveOptimizer()result, stats = optimizer.optimize(messages, target_tokens=10000)# Messages are tagged with 'excluded': True# Use get_effective_history() to filter
Best for: When you need to preserve full history for audit/undo.
The optimizer preserves tool_call/tool_result pairs to maintain API validity:
# These pairs are kept together or removed together{"role": "assistant", "tool_calls": [{"id": "call_123", ...}]}{"role": "tool", "tool_call_id": "call_123", "content": "..."}