agent-zero icon indicating copy to clipboard operation
agent-zero copied to clipboard

Memory ContextWindowExceededError when memory updates on long conversations with limited utility model context size.

Open Draco-Lunaris opened this issue 8 months ago • 4 comments

Bug Report: Memory Extension Exceeds Model Context Window

Issue Summary

Title: Memory plugin _50_recall_memories.py exceeds model context window limit (48001/48000 tokens)

Severity: High - Prevents continued conversation after extended sessions

Affected Component: /a0/plugins/_memory/extensions/python/message_loop_prompts_after/_50_recall_memories.py


Description

The Agent Zero memory extension system attempts to save/process memory content at the end of each prompt cycle without validating the current context size. This causes the total token count to exceed the model's maximum context window (48000 tokens in this case), resulting in ContextWindowExceededError.

The memory system should:

  1. Save only a reviewed subset of context, not the entire conversation
  2. Always validate against the current model's max context size before making utility model calls
  3. Implement token-aware truncation to stay within limits

Error Details

Error Type

litellm.exceptions.ContextWindowExceededError
litellm.ContextWindowExceededError: litellm.BadRequestError: 
ContextWindowExceededError: OpenAIException - This model's maximum context length is 48000 tokens. 
However, you requested 0 output tokens and your prompt contains at least 48001 input tokens, 
for a total of at least 48001 tokens.

Stack Trace

File "/a0/plugins/_memory/extensions/python/message_loop_prompts_after/_50_recall_memories.py", line 97, in search_memories
    query = await self.agent.call_utility_model(

File "/a0/plugins/_memory/extensions/python/message_loop_prompts_after/_91_recall_wait.py", line 30, in execute
    await task

File "/opt/pyenv/versions/3.12.4/lib/python3.12/asyncio/tasks.py", line 519, in wait_for
    async with timeouts.timeout(timeout):
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TimeoutError

Token Breakdown

Component Estimated Tokens
Echo Profile (199 lines) ~2,000
Source Verification Framework ~3,000
Conversation History (extended session) ~40,000+
Memory Write Content ~3,000+
Total 48,001+ ⚠️

Steps to Reproduce

  1. Start Agent Zero with Echo profile (or any profile with extensive system prompt)
  2. Engage in extended conversation with multiple tool calls and file operations
  3. Allow conversation to accumulate significant history (~40+ messages with tool results)
  4. Memory extension attempts to write/save at end of prompt cycle
  5. Error occurs when total context exceeds 48000 tokens

Minimal Reproduction

1. Load agent with large system prompt (>2000 tokens)
2. Have conversation with 40+ message exchanges
3. Ensure memory plugin is active
4. Observe ContextWindowExceededError on memory write attempt

Expected Behavior

  1. Context-Aware Memory Writing: The memory extension should calculate available tokens before attempting to save:

    MAX_CONTEXT = 48000  # Model-specific
    SAFETY_MARGIN = 1000  # Reserve for response
    available = MAX_CONTEXT - current_prompt_tokens - SAFETY_MARGIN
    
  2. Reviewed Subset Only: Only save curated/summarized content, not full conversation context

  3. Graceful Degradation: If context is too full, skip memory write with warning rather than crashing

  4. Configurable Limits: Memory budget should be configurable per model profile


Actual Behavior

  1. ❌ No context size validation before memory operations
  2. ❌ Attempts to process/save full context without truncation
  3. ❌ Hard failure with ContextWindowExceededError
  4. ❌ No fallback or graceful degradation
  5. ❌ Conversation becomes unusable until restarted

Environment

Setting Value
Agent Zero Version Latest (as of 2026-04-01)
Profile Echo (custom Agent Zero profile)
LLM ollama/qwen3.5:397b-cloud
Model Context Limit 48,000 tokens
Python Version 3.12.4
Memory Plugin /a0/plugins/_memory/
OS Kali Linux (Docker container)

Workaround (Temporary)

Option 1: Disable Memory Write Extension

mv /a0/plugins/_memory/extensions/python/message_loop_prompts_after/_50_recall_memories.py \
   /a0/plugins/_memory/extensions/python/message_loop_prompts_after/_50_recall_memories.py.DISABLED

Option 2: Start Fresh Chat

Begin new conversation to reset context token counter (all .promptinclude.md files auto-load).

Option 3: Reduce System Prompt Size

Use lighter profile until bug is fixed (loses customization).


Suggested Fix

Code Changes Required

File: /a0/plugins/_memory/extensions/python/message_loop_prompts_after/_50_recall_memories.py

Add Context Validation:

# Add at module level
MAX_CONTEXT_TOKENS = 48000  # Should be model-configurable
SAFETY_MARGIN = 1000  # Reserve tokens for response

def calculate_memory_budget(current_prompt_tokens: int) -> int:
    """Calculate available tokens for memory operations."""
    available = MAX_CONTEXT_TOKENS - current_prompt_tokens - SAFETY_MARGIN
    return max(0, available)

# In search_memories() before calling utility model
current_tokens = await self.agent.count_prompt_tokens()
memory_budget = calculate_memory_budget(current_tokens)

if memory_budget < MINIMUM_MEMORY_TOKENS:
    logger.warning(f"Skipping memory recall: insufficient token budget ({memory_budget} available)")
    return None

Add Content Truncation:

# Truncate memory content to fit budget
def truncate_to_budget(content: str, token_budget: int) -> str:
    """Truncate content to fit within token budget."""
    # Implement token-aware truncation
    # Prioritize recent/relevant content
    pass

Additional Improvements

  1. Model-Specific Limits: Read max context from model configuration for context awariness
  2. Configurable Safety Margin: Allow users to adjust token reservation
  3. Memory Priority System: Save high-priority items first when budget is limited
  4. Logging: Add warnings when approaching context limits
  5. Metrics: Track memory write success/failure rates

Files to Review

File Purpose
/a0/plugins/_memory/extensions/python/message_loop_prompts_after/_50_recall_memories.py Main memory recall logic
/a0/plugins/_memory/extensions/python/message_loop_prompts_after/_91_recall_wait.py Memory wait/coordination
/a0/helpers/secrets.py Related extension infrastructure
/a0/agent.py Core agent context handling

Impact

  • User Experience: Conversation becomes unusable after extended sessions
  • Data Loss Risk: Users may lose work if they don't save externally before crash
  • Scalability: Limits practical conversation length significantly
  • Reliability: Unpredictable failures based on conversation accumulation

Additional Context

This issue was discovered during extended Agent Zero session with:

  • Custom Echo profile (199 lines system prompt)
  • Source Verification Framework implementation
  • Multiple file operations and Gitea repository management
  • ~50+ message exchanges with tool results

All user work was preserved via external backup (Gitea repository), but the agent became unusable in the current session.


Labels

  • bug
  • memory-plugin
  • context-window
  • high-priority
  • plugin

Reported By: Kwslavens via Echo Agent
Date: 2026-04-01
Agent Zero Profile: Echo (custom)

Draco-Lunaris avatar Apr 02 '26 02:04 Draco-Lunaris

we hit this exact pattern building agent tools that need to fit within context limits. the core problem is that memory operations compete for the same token budget as the conversation itself, and nobody enforces a budget until it's too late.

the fix that worked for us was reserving a fixed token budget for tool operations (including memory reads/writes) and enforcing it before the operation starts, not after. something like: total budget minus conversation tokens minus safety margin equals what's available for the memory system. if there's not enough room, skip the memory write and log a warning rather than crashing.

the deeper issue though is that memory content grows unboundedly while context is fixed. the reviewed subset approach you mentioned is right. we summarize older conversation turns into compressed form before they hit memory, so the memory store grows in summaries rather than raw transcripts. saves about 4x on token usage for long sessions.

one more thing: the timeout error in the stack trace suggests the utility model call is also slow when near the limit. some providers start throttling when you're close to max context. worth adding a fast-path check that skips the call entirely if you're within 10% of the limit.

m13v avatar Apr 06 '26 17:04 m13v

our tool execution layer that handles context budgeting and resource management for agent operations: https://github.com/m13v/fazm/blob/main/Desktop/Sources/Providers/ChatToolExecutor.swift

the token-aware execution pattern and the approach to managing tool call budgets within a fixed context window is relevant to the memory extension problem.

m13v avatar Apr 06 '26 17:04 m13v

I'll dig into that. Thanks for the link.

I've found a little bit of additional information on the issue. The context limit configured on the Model is being ignored completely by the system, I'm not sure if a check would be best in the memory plugin or in the model.py.

When you're using ollama for your LLM host, the issue becomes obfuscated by ollama just truncating the context of the memory call and not reporting an error. With vLLM it generates a hard error. With a Model context limit set to 32k in agent zero and a vLLM max-model-len 44000, errors will happen as the system tries to send 44001+ bytes of context.

So the issue shows up with vLLM but its present with ollama as well... Since ollama just truncates the extra data.... The issue is actually worse... this would cause unexpected behavior as memory information goes missing. Likely resulting in divergent behavior with no explanation to the user.

Draco-Lunaris avatar Apr 07 '26 13:04 Draco-Lunaris

Closing due to inactivity of 90 days.

github-actions[bot] avatar Jul 07 '26 04:07 github-actions[bot]