Context Strategies & Defaults

Complete guide to context management strategies, defaults, and customization

Context strategies decide how an agent compacts history โ€” truncate, prune, or summarise โ€” when the conversation nears the model’s limit.

python
from praisonaiagents import Agent

# All four spellings enable the sliding_window strategy:
Agent(instructions="t", context="sliding_window")
Agent(instructions="t", context="sliding-window")
Agent(instructions="t", context="SLIDING_WINDOW")
Agent(instructions="t", context=" sliding_window ")

# The context_manager is actually built โ€” previously the last three silently returned None:
assert Agent(instructions="t", context="sliding-window").context_manager is not None
Call (Python)Before PR #4186After PR #4186
Agent(context="sliding_window")โœ… context_manager setโœ… context_manager set
Agent(context="sliding-window")โš  validated โ†’ context_manager=Noneโœ… context_manager set
Agent(context="SLIDING_WINDOW")โš  validated โ†’ context_manager=Noneโœ… context_manager set
Agent(context=" sliding_window ")โš  validated โ†’ context_manager=Noneโœ… context_manager set
python
from praisonaiagents import Agent

agent = Agent(
    name="strategy-agent",
    instructions="Apply the right context strategy when history grows.",
)
agent.start("Continue this long task without losing important details.")

The user picks a compaction strategy; the agent applies truncation, chunking, or summarisation when context nears the limit.

Diagram

Context Management

Yes

No

๐Ÿ’ฌ User Request

๐Ÿค– Agent

Usage > 80%?

โš™๏ธ Compact Strategy

โœ… Response

Quick Start

  1. Enable with defaults
    python
    from praisonaiagents import Agent
    
    agent = Agent(
        instructions="You are helpful.",
        context=True,
    )
  2. Fine-tune strategy and threshold
    python
    from praisonaiagents import Agent, ManagerConfig
    
    agent = Agent(
        instructions="You are a code assistant.",
        context=ManagerConfig(
            auto_compact=True,
            compact_threshold=0.8,
            strategy="smart",
            output_reserve=16384,
        ),
    )

Default Behavior

Interactive Mode (praisonai chat)

SettingDefaultReason
context=FalseZero overhead for simple chats
When enabled:
– auto_compactTruePrevent overflow automatically
– compact_threshold0.8Trigger at 80% usage
– strategysmartBest balance of preservation
– output_reserveModel-specific8K-16K tokens

To enable in CLI:

bash
praisonai chat --context  # Enable with defaults

Auto-Agents Mode (Agents)

SettingDefaultReason
context=FalseZero overhead for simple tasks
When enabled:
– auto_compactTrueHandle long multi-agent tasks
– compact_threshold0.8Trigger at 80% usage
– strategysmartPreserve important context

To enable:

python
from praisonaiagents import AgentTeam

agents = AgentTeam(
    agents=[...],
    context=True,  # Enable for all agents
)

Optimization Strategies

Strategy Overview

StrategyDescriptionProsCons
truncateRemove oldest messages firstFast, simple; keeps tool pairs intactLoses early context
sliding_windowKeep N most recent messagesPreserves recent; keeps tool pairs intactLoses early context
prune_toolsTruncate old tool outputsKeeps messagesMay lose tool details
non_destructiveCompact only messages marked non-critical; preserves everything elseBest when tool outputs are heavy but must not be summarisedTagged messages still occupy storage
summarizeReplace old messages with summaryPreserves meaningSlower, uses API
conversationStructured summaries with topic/goal trackingPreserves narrativeRequires analysis
smartCombine strategies intelligentlyBest balanceMore complex

When to Use Each

  • truncate: Simple chatbots, Q&A agents
  • sliding_window: Long conversations where recent context matters most
  • prune_tools: Tool-heavy agents with large outputs
  • non_destructive: Heavy tool outputs you must keep โ€” tags old messages out of the effective window instead of deleting them
  • summarize: When historical context is critical
  • conversation: Multi-hour planning sessions, iterative development โ€” automatically falls back to smart when compaction ratio isn’t meaningful, making it safe as a default for long-running agents
  • smart (recommended): Production use, balances all concerns

Tool-call safety

Every strategy keeps assistant tool_calls messages and their matching tool results on the same side of the compaction boundary. If the raw token/message cut lands between a pair, the boundary is snapped outward so the pair is preserved together.

Diagram

Boundary snap

๐Ÿงพ Raw cut
splits a pair

โœ‚๏ธ Snap outward

โœ… Pair kept together
on the recent side

For truncate, the token-budget loop additionally drops a leading assistant tool_calls message together with all of its tool results in a single step. No configuration required โ€” this behaviour is on by default for every strategy.

Overflow Handling

Threshold Playbook

UsageLevelAction
70%INFOMonitor usage, no action needed
80%NOTICEConsider optimization soon
90%WARNINGTrigger auto-compact if enabled
95%CRITICALAggressive optimization required
100%OVERFLOWImmediate truncation to prevent API error

“Immediate truncation” at 100% now counts the system prompt and tool schemas in the overhead, not just history tokens. An agent whose system prompt or tool block grew large will trip emergency truncation earlier than before โ€” this is intentional and keeps the request inside the model window.

Automatic Handling

When auto_compact=True, the system automatically:

  1. Monitors token usage before each API call
  2. Triggers optimization when threshold is reached
  3. Applies the configured strategy
  4. Logs the optimization event
  5. If the configured strategy fails, falls back to emergency truncation targeting ~80% of the model window (result payload includes emergency_truncated: True)

Failure Fallback

If the configured strategy raises, _apply_context_management no longer returns the history unchanged. It:

  1. Logs the failure at error level (was warning).
  2. Recomputes the model limit via get_model_limit.
  3. Adds the system prompt and tool-schema token cost as overhead.
  4. If history + overhead > 95% of the window, calls emergency_truncate targeting max(1, int(model_limit * 0.8) - overhead).
  5. Returns {"emergency_truncated": True} so observability sinks can see the fallback fired.

A misconfigured strategy therefore never sends an over-budget request โ€” the hard limit stays in place.

python
from praisonaiagents import Agent, ManagerConfig

agent = Agent(
    instructions="You are a support assistant.",
    context=ManagerConfig(
        strategy="truncate",  # Any of the seven strategies is now reliable
        auto_compact=True,
        compact_threshold=0.8,
    ),
)

# When the configured strategy fails, the fallback still keeps the request
# inside the model window and marks the result.
result = agent.chat("Long conversation continues here...")
# result.metadata may include:
#   {"emergency_truncated": True}
python
# Example: Custom threshold
agent = Agent(
    instructions="...",
    context=ManagerConfig(
        auto_compact=True,
        compact_threshold=0.7,  # Earlier trigger
        strategy="smart",
    ),
)

Budgeting

Token Allocation

The context budget is divided into segments:

SegmentDefaultDescription
System Prompt2,000Agent instructions
Rules500Behavioral rules
Skills500Skill definitions
Memory1,000Long-term memory
Tools Schema2,000Tool definitions
Tool Outputs20,000Tool call results
HistoryRemainingConversation history
Buffer1,000Safety margin

Custom Budgets

python
from praisonaiagents.context import ContextBudgeter

budgeter = ContextBudgeter(
    model="gpt-4o",
    system_prompt_budget=3000,
    tools_schema_budget=5000,
    memory_budget=2000,
)
budget = budgeter.allocate()
print(f"Usable: {budget.usable:,} tokens")

Monitoring

Enable Context Monitoring

python
agent = Agent(
    instructions="...",
    context=ManagerConfig(
        monitor_enabled=True,
        monitor_path="./context_debug.txt",
        monitor_format="human",  # or "json"
    ),
)

Snapshot Output Example

================================================================================
PRAISONAI CONTEXT SNAPSHOT
================================================================================
Timestamp: 2026-01-08T12:00:00Z
Model: gpt-4o-mini
Model Limit: 128,000 tokens
Output Reserve: 16,384 tokens
Usable Budget: 111,616 tokens

--------------------------------------------------------------------------------
TOKEN LEDGER
--------------------------------------------------------------------------------
Segment              |     Tokens |     Budget |    Usage
--------------------------------------------------------------------------------
System Prompt        |        150 |      2,000 |    7.5%
History              |      5,230 |     84,616 |    6.2%
Tool Outputs         |      1,200 |     20,000 |    6.0%
--------------------------------------------------------------------------------
TOTAL                |      6,580 |    111,616 |    5.9%

Percentage Display

Context utilization is displayed with smart formatting:

  • Values < 0.1%: Shows <0.1%
  • Values < 1%: Shows 2 decimal places (e.g., 0.02%)
  • Values >= 1%: Shows 1 decimal place (e.g., 5.3%)

Multi-Agent Policies

Isolated (Default)

Each agent has its own context ledger:

python
from praisonaiagents import ManagerConfig

agent1 = Agent(
    instructions="Researcher",
    context=ManagerConfig(policy="isolated"),
)
agent2 = Agent(
    instructions="Writer", 
    context=ManagerConfig(policy="isolated"),
)

Shared

Agents share a common context ledger:

python
from praisonaiagents import AgentTeam

agents = AgentTeam(
    agents=[agent1, agent2],
    context=ManagerConfig(policy="shared"),
)

Redaction & Security

Sensitive data is automatically redacted in snapshots:

  • API keys (OpenAI, Anthropic, Google, AWS, etc.)
  • Passwords and secrets
  • Email addresses (optional)
  • Custom patterns
python
agent = Agent(
    instructions="...",
    context=ManagerConfig(
        monitor_enabled=True,
        redact_sensitive=True,
    ),
)

Configuration Reference

ManagerConfig Options

OptionTypeDefaultDescription
auto_compactboolTrueAuto-optimize on threshold
compact_thresholdfloat0.8Trigger at this usage %
strategystr"smart"Optimization strategy
conversation_compactionboolFalseEnable intelligent conversation compaction
conversation_analyzer_strategystr"hybrid"Strategy: hybrid, rule_based, llm_only
conversation_min_compaction_ratiofloat0.3Minimum compression ratio for conversation compaction
output_reserveintModel-specificReserved for output
monitor_enabledboolFalseEnable snapshots
monitor_pathstrNoneSnapshot file path
monitor_formatstr"human""human" or "json"
redact_sensitiveboolTrueRedact secrets
policystr"isolated"Multi-agent policy

How It Works

Diagram
StrategyAgentUserStrategyAgentUseralt[usage >compact_threshold]Long conversation requestCheck token usage vs thresholdApply compact strategyCompressed contextGenerate responseResponse

Best Practices

Pick strategy by session length

Short chats can use truncate; long support threads benefit from smart or LLM summarisation.

Isolate multi-agent context

Use policy="isolated" unless agents explicitly share a workspace.

Leave redaction on

redact_sensitive=True protects API keys in tool results from appearing in logs.

Revisit strategy after model changes

A larger context window may let you switch to lighter strategies and save latency.

Verify your build includes PR #4242 before non-smart strategies

If you pinned PraisonAI at a build before PR #4242, only strategy="smart" actually compacted. All other values raised TypeError inside ContextManager and were silently swallowed โ€” including the emergency truncation. Verify your build includes PR #4242 (merged Aug 2026) before shipping a non-smart strategy to production.

Tool-using bots stay valid across compaction

When your agent calls tools inside a long conversation, compaction never separates an assistant tool_calls message from its tool result. This holds for every strategy โ€” truncate, sliding_window, prune_tools, summarize, conversation, and smart. Long-lived Telegram/Slack/gateway bots on strict providers keep working across weeks of history without provider 400s.

Related