adk-python icon indicating copy to clipboard operation
adk-python copied to clipboard

Smart Context Pruning with Token-Aware Filtering

Open sarojrout opened this issue 11 months ago • 6 comments

Is your feature request related to a problem? Please describe. Yes. The existing ContextFilterPlugin only keeps N invocations but doesn't consider:

  1. Actual Token Count: It only counts invocations, not actual tokens. A single invocation with a large tool response could exceed context limits
  2. Relevance: It removes important context while keeping less relevant content based only on recency
  3. Context Window Pressure: No proactive management before hitting limits - it only filters after the fact
  4. No Token Awareness: Can't optimize for token efficiency when context is getting full
# ContextFilterPlugin keeps last 5 invocations
# But one invocation might have a 10k token tool response
# While another has just 100 tokens
# Result: Context exceeds limits even with only 5 invocations

Describe the solution you'd like Enhance ContextFilterPlugin with token-aware and relevance-based filtering:

class SmartContextFilterPlugin(BasePlugin):
    """Intelligent context filtering based on tokens and relevance."""
    
    max_context_tokens: int = 32000
    relevance_threshold: float = 0.7
    preserve_tool_results: bool = True
    preserve_user_corrections: bool = True
    use_embeddings: bool = True  # For relevance scoring
    warn_at_percent: float = 0.8  # Warn when 80% full
  1. Token Counting: Monitor actual token count of context before each LLM call
  2. Proactive Pruning: When approaching max_context_tokens, remove least relevant events first
  3. Relevance Scoring: Use embeddings to score relevance of each event to current query
  4. Priority Preservation: Always preserve:
    • Tool results (critical for agent reasoning)
    • User corrections (important feedback)
    • Recent events (within last N invocations)
  5. Early Warnings: Log warnings when context is 80% full
  6. Semantic Deduplication: Remove redundant information (e.g., repeated instructions)

Usage:

from google.adk.plugins import SmartContextFilterPlugin
from google.adk import App, Agent

app = App(
    name="my_app",
    root_agent=agent,
    plugins=[
        SmartContextFilterPlugin(
            max_context_tokens=32000,
            relevance_threshold=0.7,
            preserve_tool_results=True
        )
    ]
)

Describe alternatives you've considered

  1. Manual Context Management: Users manually manage context size:

    • Requires constant monitoring
    • Error-prone
    • Doesn't scale
  2. Fixed Invocation Count: Current approach of keeping N invocations:

    • Doesn't account for token variance
    • Can still exceed limits
    • No relevance consideration
  3. Post-Processing Filtering: Filter after context is built:

    • Less efficient
    • May remove context already sent to model
    • Doesn't prevent hitting limits Additional context
  • Long-running conversations: Sessions that accumulate many turns
  • Multi-agent systems: Shared context that needs optimization
  • Cost-sensitive deployments: Need to maximize context efficiency
  • Large tool responses: When tools return substantial data

Implementation Notes:

  • Can extend existing ContextFilterPlugin or create new plugin
  • Requires token counting utility (can reuse from context cache manager)
  • Embedding-based relevance requires embedding model (optional)
  • Should integrate with event compaction for maximum efficiency

Related Code:

  • Current implementation: src/google/adk/plugins/context_filter_plugin.py
  • Token estimation: src/google/adk/models/gemini_context_cache_manager.py:314 (_estimate_request_tokens)
  • Event compaction: src/google/adk/apps/compaction.py

Priority:

High - Significant cost savings potential and improves context management.

sarojrout avatar Dec 05 '25 00:12 sarojrout

@Jacksunwei , let me know your thoughts. I can work on it. thanks!

sarojrout avatar Dec 09 '25 07:12 sarojrout

Im waiting this update also.

kursatdinc avatar Dec 24 '25 19:12 kursatdinc

I don't think a new plugin is necessary. This feature was released recently and is native to ADK: https://google.github.io/adk-docs/context/compaction/

However it is broken if you are using database sessions storage: https://github.com/google/adk-python/issues/3487#issuecomment-3692336559

ryanovas avatar Dec 28 '25 20:12 ryanovas

hello @ryanovas , ADK's current context compaction mechanism uses a fixed interval measured in invocations — for example, compress every 3 invocation events. This means:

  • the system groups and summarizes events after a set number of turns But, it doesn't know how big each event is in tokens when making that decision — a single event could be 10 tokens or 10,000 tokens and compaction treats them the same.

sarojrout avatar Dec 30 '25 20:12 sarojrout

@sarojrout Thank you for bringing this to our attention. The request is under review, and I’ll keep you updated if any additional information is required. We appreciate your patience.

klateefa avatar Feb 11 '26 08:02 klateefa

You can configure EventsCompactionConfig on your application with token_threshold and event_retention_size. Once the prompt exceeds the token threshold, ADK automatically prunes and summarizes the conversation history, keeping only the last N events.

See code reference:

src/google/adk/apps/_configs.py#L70-L85 src/google/adk/apps/app.py#L84 Closing this issue as supported.

DeanChensj avatar Jul 09 '26 22:07 DeanChensj