Context Management Overview

Complete visual guide to context management architecture, terminology, and optimization strategies

Diagram

Context Management Overview

📋 User Request

⚙️ Context Management Overview

✅ Result

python
from praisonaiagents import Agent

agent = Agent(
    name="assistant",
    instructions="You are a helpful assistant.",
    context_window=8000,
)
agent.start("Summarise the last 10 messages without losing context.")

Context Management Overview

This page provides a comprehensive visual guide to how context management works in PraisonAI Agents.

The user opens this overview to see how budgeting, compaction, and monitoring fit together before tuning an agent.

Diagram

Context Management

📝 Messages

⚙️ Budget

✂️ Compact

🤖 Agent

✅ Response

What Makes PraisonAI Context Management Best-in-Class

Feature Comparison

FeaturePraisonAILangChainCrewAIAgno
Smart Defaults✅❌❌❌
Lazy Loading (0ms overhead)✅❌❌❌
Session Deduplication✅❌❌⚠️
LLM Summarization✅⚠️❌❌
Per-Tool Limits✅❌❌❌
6 Compaction Strategies✅❌❌❌
Benefit Checking✅❌❌❌
Auto-Compaction✅❌❌❌
Snapshot Replay✅❌❌❌
Multi-Memory Aggregation✅❌✅❌

Architecture

Diagram

📤 Optimized Context

🔧 Optimization Strategies

⚙️ Context Manager

📥 Context Sources

System Prompt
~2000 tokens

Chat History
Variable

Tool Schemas
~2000 tokens

Tool Outputs
~20000 tokens

Memory/RAG
~4000 tokens

Token Estimator

Budget Allocator

Deduplication

Optimizer

Truncate

Sliding Window

Prune Tools

Summarize

Smart

LLM API Call

Multi-Agent Context Flow

Diagram
Session CacheAgent 3Agent 2Agent 1WorkflowSession CacheAgent 3Agent 2Agent 1WorkflowCreate shared session cacheStart with inputAdd content hashReturn outputPass output as inputCheck hash (deduplicate)Add new content hashReturn outputPass output as inputCheck hash (deduplicate)Return final output

Terminology Reference

Core Concepts

TermDefinitionDefault
Context WindowMaximum tokens an LLM can process in one requestModel-specific (128K for GPT-4o)
Token BudgetAllocated tokens for each context segmentAuto-calculated
Compact ThresholdUsage % that triggers optimization80%
Output ReserveTokens reserved for LLM response8000-16000

Optimization Strategies

StrategyHow It WorksBest For
TruncateRemoves oldest messages firstSimple chatbots
Sliding WindowKeeps N most recent messagesLong conversations
Prune ToolsTruncates old tool outputsTool-heavy agents
SummarizeReplaces old messages with summaryCritical context
SmartCombines all strategies intelligentlyProduction use

Token Segments

Diagram
66%16%13%3%2%2%Token Budget Allocation (128K model)HistoryTool OutputsOutput ReserveMemory/RAGSystem PromptTool Schemas

Defaults Reference

ContextConfig Defaults

python
ContextConfig(
    auto_compact=True,           # Auto-optimize when threshold reached
    compact_threshold=0.8,       # Trigger at 80% usage
    strategy="smart",            # Use smart optimization
    output_reserve=8000,         # Reserve for LLM response
    history_ratio=0.6,           # 60% of usable for history
    tool_output_max=10000,       # Max tokens per tool output
    prune_after_tokens=40000,    # Start pruning after 40K
    keep_recent_turns=5,         # Keep last 5 turns intact
    tool_limits={},              # Per-tool output limits
)

Per-Tool Limits

Configure different limits for different tools:

yaml
context:
  auto_compact: true
  tool_limits:
    tavily_search: 2000      # Search results: 2000 chars
    tavily_extract: 5000     # Full page: 5000 chars
    code_executor: 10000     # Code output: 10000 chars

Overflow Handling

Diagram

< 70%

70-80%

80-90%

90-95%

Unsupported markdown: blockquote

Optimization

Auto-compact

Aggressive truncation

Emergency truncation

Normal

Warning

Critical

Emergency

Overflow

LevelUsageAction
Normal< 70%No action
Warning70-80%Monitor
Critical80-90%Auto-compact triggers
Emergency90-95%Aggressive optimization
Overflow> 95%Emergency truncation

Session Deduplication

Prevents duplicate content across agents in multi-agent workflows:

Diagram

Agent 3

Agent 2

Session Cache

Agent 1

Duplicate

Duplicate

Duplicate

Content A

Hash A ✓

Hash B ✓

Content A (skip)

Content B

Content A (skip)

Content B (skip)

Content C

CLI Commands

Analytics Dashboard

bash
# View analytics for recent sessions
praisonai replay dashboard

# Analyze specific session
praisonai replay dashboard <session_id>

# JSON output
praisonai replay dashboard --json

Session Statistics

bash
# View session stats
praisonai replay context <session_id> --stats

Output:

TOKEN USAGE BY AGENT:
  deep_researcher      ██████████████████████████████    956,146 (75.5%)
  content_writer       ███                               113,023 (8.9%)

CONTEXT EFFICIENCY:
  ⚠️  Duplicates Found:  236
  ⚠️  Wasted Tokens:     135,279 (10.7%)

Smart Default Context

New in v1.0: Context management is now automatically enabled when your agent has tools:

python
from praisonaiagents import Agent

# Context auto-enabled because tools are present
agent = Agent(
    instructions="You are helpful",
    tools=[my_search_tool]  # context=True automatically
)

# No tools = no context overhead
simple_agent = Agent(
    instructions="You are helpful"
    # context=None (disabled, zero overhead)
)

# Explicitly disable even with tools
agent = Agent(
    instructions="You are helpful",
    tools=[my_search_tool],
    context=False  # Override smart default
)

Quick Start Examples

  1. Enable or Customise
    Enable Context
    from praisonaiagents import Agent
    
    agent = Agent(
        instructions="You are helpful",
        context=True  # Enable with defaults (or auto-enabled with tools)
    )
    Custom Config
    from praisonaiagents import Agent, ManagerConfig
    
    agent = Agent(
        instructions="You are helpful",
        context=ManagerConfig(
            auto_compact=True,
            compact_threshold=0.7,
            strategy="smart",
            llm_summarize=True,  # Enable LLM-powered summarization
            smart_tool_summarize=True,  # Summarize tool outputs before truncating (default)
            tool_summarize_limits={"tavily_search": 1000, "web_scraper": 5000},  # Per-tool thresholds
            tool_limits={"tavily_search": 2000}
        )
    )
    YAML Config
    context:
      auto_compact: true
      compact_threshold: 0.7
      strategy: smart
      llm_summarize: true
      smart_tool_summarize: true
      tool_summarize_limits:
        tavily_search: 1000
        web_scraper: 5000
      tool_limits:
        tavily_search: 2000
        tavily_extract: 5000

Process Flow Diagrams

Sequential Process Flow

How context flows through agents in sequential execution:

Diagram
Context Manager 3Agent 3Context Manager 2Agent 2Session CacheContext Manager 1Agent 1WorkflowUser InputContext Manager 3Agent 3Context Manager 2Agent 2Session CacheContext Manager 1Agent 1WorkflowUser InputSkip duplicate contentStart taskCreate shared session cacheExecute with inputProcess contextEstimate tokensApply budgetAdd content hashesReturn output_1Execute with output_1Process contextCheck for duplicatesAdd new hashesReturn output_2Execute with output_2Process contextCheck for duplicatesReturn final outputReturn result

Hierarchical Process Flow

How context flows in manager-worker hierarchies:

Diagram
Worker 3Worker 2Worker 1Session CacheManager ContextManager AgentUserWorker 3Worker 2Worker 1Session CacheManager ContextManager AgentUserpar[Parallel Workers]Complex taskProcess contextInitialize cacheDecompose taskSubtask 1Check/add hashesResult 1Subtask 2Check/add hashesResult 2Subtask 3Check/add hashesResult 3Aggregate resultsDeduplicateFinal synthesis

Workflow Process Flow

How context flows through workflow steps:

Diagram

Workflow Execution

Step 3: Write

Step 2: Analyze

Step 1: Research

Yes

No

Yes

No

Agent 3

Start

Create Session Cache

Agent 1

Context Manager

Over threshold?

Auto-compact

Pass through

Output 1

Agent 2

Context Manager

Deduplicate vs Cache

Over threshold?

Auto-compact

Pass through

Output 2

Context Manager

Deduplicate vs Cache

Final Output

End

Optimization Strategy Diagrams

Truncate Strategy

Diagram

After (100K tokens)

Msg 3

Msg 4

Msg 5

Before (150K tokens)

Msg 1

Msg 2

Msg 3

Msg 4

Msg 5

Truncate Oldest

Sliding Window Strategy

Diagram

After (5 messages)

Msgs 16-20
Preserved

Before (20 messages)

Msgs 1-15
Old

Msgs 16-20
Recent

Keep Last N

Prune Tools Strategy

Diagram

After Pruning

Tool Output 1
10K tokens ✂️

Tool Output 2
10K tokens ✂️

Tool Output 3
10K tokens ✂️

Before Pruning

Tool Output 1
50K tokens

Tool Output 2
30K tokens

Tool Output 3
20K tokens

Truncate to Limit

Summarize Strategy

Diagram

After (6 messages)

Before (50 messages)

Messages 1-45
Old History

Messages 46-50
Recent

LLM Summarization

[Summary]
Key points from
45 messages

Messages 46-50
Preserved

Smart Strategy (Combined)

Diagram

Yes

Yes

No

No

Step 3: Summarize

LLM summarization

Step 2: Sliding Window

Keep recent messages

Step 1: Prune Tools

Truncate tool outputs

Over Budget

Under budget?

Done ✓

Under budget?

Context Overflow Handling

What Happens When Context Exceeds Limits

Diagram

< 70%

70-80%

80-90%

90-95%

Unsupported markdown: blockquote

New Message

Estimate Total Tokens

Usage Level?

Normal: No Action

Warning: Monitor

Critical: Auto-Compact

Emergency: Aggressive Optimization

Overflow: Emergency Truncation

Apply Smart Strategy

Prune + Window + Summarize

Remove Oldest Until Safe

Continue Processing

Tool Output Overflow Handling

Diagram

< tool_limit

Unsupported markdown: blockquote

Yes

No

Tool Execution

Tool Output

Output Size?

Pass Through

Truncate to Limit

Add [truncated] marker

Add to Context

Within Budget?

Continue

Apply Optimization Strategy

LLM Summarization

Enable intelligent summarization using the agent’s LLM:

python
from praisonaiagents import Agent, ContextConfig

agent = Agent(
    instructions="You are helpful",
    context=ContextConfig(
        auto_compact=True,
        llm_summarize=True,  # Enable LLM-powered summarization
        strategy="smart"
    )
)

When llm_summarize=True:

  • Old messages are summarized by the LLM instead of truncated
  • Key facts, decisions, and context are preserved
  • More intelligent compression than simple truncation

Best Practices

Start with ContextConfig defaults

Enable auto_compact and a sensible strategy before tuning low-level APIs.

Enable LLM summarisation for quality

llm_summarize=True keeps key facts when history must shrink.

Layer budget, ledger, and monitor

Budget allocation, usage tracking, and snapshots solve different problems — use all three when debugging.

Read strategy docs before custom hooks

Built-in strategies cover most cases; custom hooks add complexity only when required.

Related Pages