crewAI icon indicating copy to clipboard operation
crewAI copied to clipboard

[BUG] Chunking split (#7014) doesn't subtract the summarizer's own prompt overhead, so split chunks can still exceed the LLM's window

Open jay-k opened this issue 3 months ago • 5 comments

Description

#7014 (merged as 638842151, "Handle oversized single messages during chunking") added _expand_oversized_message / _split_text_by_token_limit in utilities/agent_utils.py to split an oversized message into [Part i/n] pieces before summarizing, each sized to fit max_tokens = llm.get_context_window_size() (agent_utils.py:1104).

That budget is computed from the raw conversation content only. But the actual request sent to the LLM (_asummarize_chunks / summarize_messages, agent_utils.py:1072) wraps that content in:

  • summarizer_system_message (~38 tokens)
  • the summarize_instruction template around {conversation} (~185 tokens)

That's ~224 tokens of fixed overhead per chunk that never gets subtracted from the budget. A chunk sized to exactly fit get_context_window_size() reliably comes back ~224 tokens over budget once wrapped, so if the LLM enforces its window like a real provider does, that call fails.

Two consequences:

  1. At any window where ~224 tokens is a non-trivial fraction of get_context_window_size(), the fix cannot succeed at all. Every chunk the splitter produces, no matter how fine-grained, is oversized once wrapped, so summarization exhausts max_retry_limit and the task fails.
  2. In that regime, chunking is worse than not chunking. Each failed attempt restarts execute_task() from scratch (agent/core.py _handle_execution_error → execute_task), so a fixed multi-chunk conversation burns chunks_per_attempt × (max_retry_limit + 1) LLM calls before failing. That's more than the code before #7014 needs, which sends one oversized call, fails, and gives up in max_retry_limit + 1 calls total.

Steps to Reproduce

No API key needed. The LLM is a minimal fake that enforces its declared window the way a real provider does (see Screenshots/Code snippets for why this is faithful to real provider behavior, not an artifact of faking it).

  1. pip install crewai==1.15.18
  2. Save the script below as repro.py
  3. python repro.py
  4. Observe the printed call(): N tokens (window=1000) lines, followed by an unhandled ValueError after 3 attempts

Expected behavior

Either:

  • Chunking should keep every produced chunk under the LLM's actual window (accounting for the summarizer's own prompt overhead), so summarization succeeds whenever the pre-#7014 code would also eventually succeed with a smaller window; or
  • If a window is genuinely too small for even one chunk to fit, that should fail no worse (in call count) than not attempting to chunk at all, not several times worse.

Screenshots/Code snippets

from crewai import Agent, Crew, Task
from crewai.llms.base_llm import BaseLLM


class TinyWindowLLM(BaseLLM):
    def __init__(self, window: int):
        super().__init__(model="tiny-window-test")
        self.window = window

    def get_context_window_size(self) -> int:
        return int(self.window * 0.85)  # matches CrewAI's own CONTEXT_WINDOW_USAGE_RATIO

    def supports_function_calling(self) -> bool:
        return False

    def supports_stop_words(self) -> bool:
        return True

    def _render(self, messages):
        if isinstance(messages, str):
            return messages
        return "\n".join(f"{m.get('role')}: {m.get('content', '')}" for m in messages)

    def call(self, messages, tools=None, callbacks=None, available_functions=None, **kwargs):
        rendered = self._render(messages)
        tokens = len(rendered) // 4
        print(f"  call(): {tokens} tokens (window={self.window})")
        if tokens > self.window:
            raise ValueError(
                f"This model's maximum context length is {self.window} tokens. "
                f"However, your messages resulted in {tokens} tokens. "
                "Please reduce the length of the messages."
            )
        return "Final Answer: done"

    async def acall(self, messages, **kwargs):
        return self.call(messages, **kwargs)


WINDOW = 1000  # fails here; try 260-800 for a more dramatic case, 1800+ to see it succeed

llm = TinyWindowLLM(window=WINDOW)
agent = Agent(
    role="Senior Research Analyst",
    goal="Summarize a long prompt",
    backstory="x" * 5000,
    llm=llm,
    respect_context_window=True,  # default, shown for clarity
    max_retry_limit=2,            # default
)
task = Task(
    description="Summarize this payload:\n" + "y" * 7000,
    expected_output="A short summary.",
    agent=agent,
)
Crew(agents=[agent], tasks=[task], memory=False).kickoff()

Observed output (window=1000)

call(): 3079 tokens (window=1000)   # initial agent call, correctly rejected
call(): 1077 tokens (window=1000)   # chunk 1 of the split summary -- still over budget
call(): 1077 tokens (window=1000)   # chunk 2
call(): 348 tokens (window=1000)    # chunk 3 (fits, but the other two didn't)
# ... repeats 2 more times (max_retry_limit=2 => 3 total attempts) ...
ValueError: This model's maximum context length is 1000 tokens. However, your messages
resulted in 1077 tokens. Please reduce the length of the messages.

Each 1077-token chunk is a piece of the split content (budgeted to get_context_window_size() = 850) plus the ~224-token summarizer wrapper: 850 + 224 = 1074 ≈ 1077. The chunk never had a chance of fitting. Splitting it smaller doesn't help, since the fixed overhead is per-chunk, not proportional to content size.

This is not an artifact of the fake LLM

The repro's TinyWindowLLM.call() raises a plain ValueError, not something litellm-shaped. So it's fair to ask whether that actually reaches the same code path a real provider's error would. It does, and here's the trace through crewAI's own source that shows why:

  1. A real provider call through litellm raises litellm.exceptions.ContextWindowExceededError (module litellm.exceptions), typically carrying the same "maximum context length" wording OpenAI's API uses.
  2. crewai.llm.LLM's response handlers (llm.py:1094, 1287, 1438, 1710) catch the raw exception, check it against LLMContextLengthExceededError._is_context_limit_error() (utilities/exceptions/context_window_exceeding_exception.py:42-44, substring match on phrases including "maximum context length"), and re-raise it as CrewAI's own LLMContextLengthExceededError (raise LLMContextLengthExceededError(error_msg) from e), whose module is crewai.utilities.exceptions.context_window_exceeding_exception, not litellm.*.
  3. crew_agent_executor.py's except block has an early exit (if e.__class__.__module__.startswith("litellm"): raise e) that skips the retry/summarize path for unrecognized litellm errors (auth, rate limits, etc.). Because step 2 already re-wrapped the exception under CrewAI's own module, this check does not fire for context-length errors specifically, and execution falls through to is_context_length_exceeded(e) → handle_context_length() → the same chunking path exercised above.

So a real provider's context-length error lands in exactly the same place the repro's ValueError does; the fake LLM only skips the litellm round-trip, not the code path.

Operating System

Other (specify in additional context): macOS 26.5.2 (build 25F84), not yet in the dropdown list. Not OS-specific, the bug is in pure Python token-budget arithmetic.

Python Version

3.11

crewAI Version

1.15.18

crewAI Tools Version

N/A, not used by the repro (no tools involved).

Virtual Environment

Venv

Evidence

Two checkouts were compared, not a single commit's before/after:

  • "no chunk-splitting" baseline: 638842151^ (9b1f4938f02671d2066e336c8bfdcfb2f27c99ee), the commit immediately before #7014 merged. An oversized message is sent unsplit; no _expand_oversized_message exists yet.
  • "current chunk-splitting" baseline: tag 1.15.18 (4bc5d2924218e892bd0bc91b46352b49b0d3a740), the current release, which contains #7014 plus ~40 later commits. Three of those touch the same files (6ad3bf939, 9652af6ae, d0e920862); none of them alter chunk-budget arithmetic.

Swept window from 260 to 4000 against both checkouts (fixed 5000-char backstory + 7000-char task description, TinyWindowLLM above, N=10 repeats per point, identical prompt-hash sequences across all repeats, no nondeterminism observed):

window 638842151^ (no splitting) 1.15.18 (current splitting) 1.15.18 outcome
260 6 calls, fails 30 calls, fails 5x more calls than no splitting at all
500 6 calls, fails 18 calls, fails 3x more calls
800 6 calls, fails 12 calls, fails 2x more calls
1000 6 calls, fails 12 calls, fails 2x more calls
1500 6 calls, fails 9 calls, fails 1.5x more calls
1800 6 calls, fails 3 calls, succeeds splitting now helps
2200+ 2 calls, succeeds 2 calls, succeeds window large enough that neither needs to split

The fix only pays off once the window is large enough to amortize the ~224-token wrapper overhead relative to get_context_window_size(). Below that, it doesn't just fail to help. It multiplies the number of failed LLM calls before giving up, on the current release, not just at the original fix commit.

Possible Solution

Subtract the summarizer's own fixed overhead from the budget used to size chunks, e.g. in summarize_messages (agent_utils.py:1104):

overhead = _estimate_token_count(
    I18N_DEFAULT.slice("summarizer_system_message")
    + I18N_DEFAULT.slice("summarize_instruction")
)
max_tokens = max(1, llm.get_context_window_size() - overhead)

so _split_messages_into_chunks / _expand_oversized_message budget against the space actually left over after the wrapper, not the full get_context_window_size().

Additional context

None beyond the above.

jay-k avatar Aug 31 '26 16:08 jay-k

The important regression shape here is not only “chunk math is off”; it is a recovery mechanism deterministically multiplies paid failures without changing the condition that caused them.

A portable fixture could bind each attempt to:

  • provider/model context-window contract;
  • raw content token estimate;
  • fixed wrapper/prompt overhead;
  • effective per-chunk request size;
  • retry ordinal + chunk count;
  • request digest / failure digest;
  • whether the next attempt changed any relevant budget or input.

Invariant: a recovery transform should never mint more retry authority when its own deterministic accounting proves the transformed requests remain impossible under the same limit. If the produced chunk + wrapper still exceeds the declared window, the correct outcome is a configuration/recovery failure, not another full agent retry with the same arithmetic.

The window sweep in this issue is a particularly good breaker: at small windows the “fix” turns 6 failed calls into as many as 30, while remaining fully deterministic and network-free with the fake provider.

I maintain AgentCI (https://github.com/jinngimk-lang/agentci), which is collecting no-progress/retry-amplification fixtures. This issue would make a strong provider-neutral case because it already has deterministic call-count evidence across multiple budgets. I’d preserve CrewAI as canonical provenance; no compatibility/certification claim is implied.

jinngimk-lang avatar Sep 01 '26 06:09 jinngimk-lang

Verified the claim against current main (lib/crewai/src/crewai/utilities/agent_utils.py) — the missing-overhead analysis is correct, and there are two additional observations that make the fix slightly more involved than "subtract a constant":

1. The codebase already has the right pattern — it's just applied one level down.

_expand_oversized_message (agent_utils.py:908-916) already reserves the fixed [Part i/n] prefix from the budget:

# Reserve budget for the [Part i/n] prefix added to each sub-message.
body_max_tokens = max(1, max_tokens - 5)

So the "subtract the fixed overhead from the chunk budget" idea is already established in this file — it's simply missing at the summarization layer where summarize_messages uses the full max_tokens = llm.get_context_window_size() (line 1116) for _split_messages_into_chunks, with the wrapper added afterwards (lines 1066-1075 async / 1129-1139 sync). The fix can follow the exact same one-line pattern: compute the wrapper once (serialize summarizer_system_message + summarize_instruction.format(conversation="")) and subtract it from the budget before splitting.

2. The wrapper is not the only unaccounted term — the formatter adds per-message overhead after chunking.

_format_messages_for_summary (lines 941-988) runs after the chunk boundaries are decided, and it amplifies each message:

  • every message gains a role label ([USER]: / [ASSISTANT]: / [TOOL_RESULT (name)]: , lines 978-984)
  • every tool-call message additionally gains a [Called tools: a, b, c] line (line 972)
  • messages are joined with \n\n separators (line 988)

So the real per-chunk overhead is:

overhead(chunk) = wrapper (~224) + sum(role labels + separators over messages in chunk)

The second term grows with message count, not content size. A chunk of 100 short messages pays ~200-400 extra tokens of labels — comparable to or larger than the wrapper itself — and it is invisible to _split_messages_into_chunks, which counts only raw message content (line 1006-1012). The "~224 fixed tokens" framing is a lower bound, not the total.

3. Consistency between budgeter and sender matters more than the heuristic.

The whole budget path uses _estimate_token_count (chars // 4, lines 900/911). That heuristic is fine for the purpose — the bug is the asymmetry: the budget counts raw content, the request sends content + labels + wrapper. Whatever counter is used, it should be applied to the actual assembled request (message formatting + wrapper), not to the raw messages. In that spirit the strongest regression test is not a unit test on _split_text_by_token_limit but an assertion on the assembled request, e.g.:

for chunk in _split_messages_into_chunks(messages, window):
    assembled = [system_msg] + [format_message_for_llm(
        I18N_DEFAULT.slice("summarize_instruction").format(
            conversation=_format_messages_for_summary(chunk)))]
    assert _estimate_token_count("\n".join(m["content"] for m in assembled)) <= window

That test fails on current main for any chunk with several messages — which is exactly the point. The TokenCalcHandler callbacks already threaded through _summarize_one/summarize_messages could also be reused to measure the real request once and cache the wrapper cost per model, instead of hardcoding 224.

(The retry-amplification consequence — a recovery path that deterministically re-fires the same over-budget request — is well covered by jinngimk-lang's fixture proposal; the accounting above is the input-side half of that invariant.)

pm25coder avatar Sep 01 '26 11:09 pm25coder

Thanks for the detailed write-up. The missing subtract is real, but we already reserve room for that wrapper.

get_context_window_size() returns 85% of the raw model window (CONTEXT_WINDOW_USAGE_RATIO = 0.85). summarize_messages budgets chunks against that reduced size, so the leftover 15% is the slack for the summarizer system/instruction overlay (~224 tokens).

That only overflows when 15% of the raw window is smaller than the wrapper — the ~1000-token case in the repro (150 < 224). Every model we ship in LLM_CONTEXT_WINDOW_SIZES is at least 4096 (15% = 614). Default is 8192 (15% = 1228). On those windows the wrapper fits, which matches the table in the issue (fail at 1000, succeed by 1800+).

We are not going to subtract the wrapper again on top of the existing buffer. Closing as not planned.

Vidit-Ostwal avatar Sep 01 '26 15:09 Vidit-Ostwal

OSS-147

linear[bot] avatar Sep 01 '26 15:09 linear[bot]

Thanks. That resolves it, and the 15% reservation makes sense. The 0.85 ratio isn't a buffer for the wrapper in the docs I could find, so I'd missed that reading.

One thing that may still be worth a small fix. The wrapper-fits guarantee depends on the window being ≥ ~1500 tokens, but nothing enforces that. LLM_CONTEXT_WINDOW_SIZES holds for shipped models, but BaseLLM.get_context_window_size() is overridable and defaults to 4096. A custom LLM returning 1000, or a local model at num_ctx=2048, lands in the failing regime with no warning. The failure mode is 3 identical retry cycles then an error, with no indication that the window is the cause.

Not asking you to subtract twice. A one-line guard would cover it, warn or raise when get_context_window_size() * 0.15 is below the wrapper size, so the user gets "context window too small for summarization" instead of an opaque cascade.

Happy to send that as a PR if it's welcome.

jay-k avatar Sep 01 '26 17:09 jay-k