crewAI icon indicating copy to clipboard operation
crewAI copied to clipboard

[BUG] Truncated responses are detected in the Bedrock provider only; other providers accept them silently

Open JoaquinDG opened this issue 3 months ago • 11 comments

AI-assisted contribution. This issue was researched and drafted with Claude Code, and reviewed by me before filing. Per CONTRIBUTING.md this needs the llm-generated label; I do not have triage permission here, so could a maintainer please apply it. Everything below was reproduced against crewai 1.15.16 today, and the scripts are included so you can re-run any of it.

Description

crewai/llms/providers/bedrock/completion.py checks whether the provider stopped because it hit the token cap, and warns:

if stop_reason == "max_tokens":
    logging.warning("Response truncated due to max_tokens limit")

No other provider does. In crewai 1.15.16 that check exists at four sites, all in bedrock/completion.py (683, 1121, 1285, 1723). Grepping the published wheel for any equivalent branch elsewhere returns nothing:

$ grep -rnE 'stop_reason *== *"max_tokens"|finish_reason *== *"length"|== *"MAX_TOKENS"' crewai/
crewai/llms/providers/bedrock/completion.py:683
crewai/llms/providers/bedrock/completion.py:1121
crewai/llms/providers/bedrock/completion.py:1285
crewai/llms/providers/bedrock/completion.py:1723

So on Anthropic, OpenAI, Azure, Gemini, openai_compatible and Snowflake, a response cut off mid-sentence is handed back to the agent as if it were a complete answer. The agent then reasons over a partial result, or parses it and fails, with nothing distinguishing "the model was interrupted" from "the model answered badly".

Observed end to end

A one-agent crew with max_tokens=16, capturing both every WARNING-or-above log record and the finish_reason crewAI puts on its own LLMCallCompletedEvent:

[openai] openai/gpt-4o-mini
  finish_reason crewAI observed : ['length']
  task result                   : 'The TCP three-way handshake is a fundamental process used to establish a reliable connec'
  warnings logged               : 0
  truncation warnings           : 0

[anthropic] anthropic/claude-haiku-4-5-20251001
  finish_reason crewAI observed : ['max_tokens']
  task result                   : '# TCP Three-Way Handshake: A Detailed Explanation'
  warnings logged               : 0
  truncation warnings           : 0

Both runs return the cut-off text as the successful task result. The Anthropic run returns a markdown heading with no body under it. Nothing in either run indicates the answer is incomplete.

The two lines worth putting side by side are finish_reason crewAI observed: ['length'] and warnings logged: 0. crewAI had the signal, on its own event bus, and did not act on it. That is the entire report.

The value looks like it is already within reach. Every provider extracts it at the call site:

  • anthropic/completion.py:1010: finish_reason, response_id = self._extract_finish_reason_and_id(...)
  • azure/completion.py:864
  • gemini/completion.py:847
  • openai/completion.py:978

and forwards it to LLMCallCompletedEvent(finish_reason=...), so it is in scope at the point a check would go. Outside Bedrock nothing reads it.

Why the silence is costly

Two provider behaviours make this cost more than it might appear.

Some models return zero visible characters while billing a full budget. Measured 2026-08-16 with a 16-token cap on one prompt, one call per provider:

provider model finish reason visible chars output tokens
anthropic claude-haiku-4-5-20251001 max_tokens 49 16
openai gpt-4o-mini length 90 16
gemini gemini-3.7-flash MAX_TOKENS 43 12
deepseek deepseek-v4-flash length 0 16
moonshot kimi-k2.6 length 0 16

And with reasoning models given a 200-token cap, where thinking consumes the budget before any answer is emitted:

provider model finish reason visible chars output tokens
anthropic claude-sonnet-5 max_tokens 623 200
gemini gemini-3.7-flash MAX_TOKENS 29 196
deepseek deepseek-v4-pro length 0 200
moonshot kimi-k3 length 0 200

An empty string that cost 200 output tokens is indistinguishable, downstream of the provider layer, from a model that declined to answer. The finish reason is the only thing that separates them, and it is the thing being dropped.

Retrying does not help. A retry at the same max_tokens truncates at the same place, so the failure is not transient. It is a configuration problem that presents as a model problem. Measured on a separate router that escalated on this signal, the truncation was read as a quality failure and escalated to a stronger model, which truncated identically at the same ceiling. The remedy is a larger cap rather than a larger model, and at the moment there is no signal available to tell the caller which of the two they need.

Steps to Reproduce

The provider-layer gap is a property of the published artifact, so it can be checked without a key:

  1. curl -sL -o crewai.whl "$(curl -s https://pypi.org/pypi/crewai/1.15.16/json | python3 -c "import json,sys;print(next(f['url'] for f in json.load(sys.stdin)['urls'] if f['filename'].endswith('.whl')))")"
  2. unzip -q crewai.whl -d x && cd x
  3. grep -rnE 'stop_reason *== *"max_tokens"|finish_reason *== *"length"|== *"MAX_TOKENS"' crewai/
  4. Every hit is in crewai/llms/providers/bedrock/completion.py.
  5. grep -rn -i truncat crewai/ | grep -i warn, and the only two warnings are Bedrock's.

For the end-to-end behaviour, run a one-agent crew against any non-Bedrock provider with a small cap, and watch the logs and the event bus at the same time:

llm = LLM(model="openai/gpt-4o-mini", max_tokens=16)

@crewai_event_bus.on(LLMCallCompletedEvent)
def record(source, event):
    print("finish_reason:", event.finish_reason)   # -> 'length'

agent = Agent(role="Explainer", goal="Explain networking clearly",
              backstory="You explain protocols.", llm=llm, max_iter=2)
task = Task(description="Explain the TCP three-way handshake in detail.",
            expected_output="A detailed explanation.", agent=agent)
print(Crew(agents=[agent], tasks=[task]).kickoff())

The event prints finish_reason: length, the crew returns the truncated text as its result, and no warning is logged at any level.

Expected behavior

A response terminated by the token cap is distinguishable from a complete one on every provider, not just Bedrock. At minimum the same logging.warning Bedrock already emits, naming the current max_tokens so the reader knows which knob to turn.

Screenshots/Code snippets

Existing Bedrock precedent, crewai/llms/providers/bedrock/completion.py:683:

if stop_reason == "max_tokens":
    logging.warning("Response truncated due to max_tokens limit")

Equivalent point in the Anthropic provider, anthropic/completion.py:1010, where finish_reason is already bound and no check happens:

finish_reason, response_id = self._extract_finish_reason_and_id(response)
# ... forwarded to LLMCallCompletedEvent(finish_reason=finish_reason) and no further use

Operating System

macOS 26.5 (arm64)

Python Version

3.13.15 (uv-managed CPython)

crewAI Version

1.15.16 (published wheel from PyPI)

crewAI Tools Version

N/A, the finding is in crewai core

Virtual Environment

Venv (uv)

Evidence

Three independent pieces, all re-runnable:

  1. Source, against the published wheel, not a git checkout, so it reflects exactly what users install. Output above, reproducible in three commands with no API key.
  2. Provider behaviour, live: 9 calls across 5 providers on 2026-08-16, raw HTTP, no framework in the path. Tables above.
  3. crewAI end to end: one-agent crew on crewai 1.15.16 / Python 3.13.15, capturing logs and the event bus together. Output above.

One honest gap: the Gemini leg of the end-to-end run returned transient 503 UNAVAILABLE ("experiencing high demand") rather than completing, so Gemini is covered by the source inspection and the raw-HTTP table but not by an end-to-end crew run. OpenAI and Anthropic both completed and both show the behaviour.

The empty-content-with-billed-tokens behaviour was first measured across five providers here, with method and raw numbers: https://github.com/JoaquinDG/governor/blob/main/experiments/FINDINGS.md#f5-reasoning-models-bill-output-tokens-and-emit-no-text

Possible Solution

Mirror the Bedrock check into the other providers at the point where finish_reason is already in scope. Roughly, per provider:

if finish_reason in ("length", "max_tokens", "MAX_TOKENS"):
    logging.warning(
        "Response truncated: finish_reason=%r. Consider increasing max_tokens (current: %s).",
        finish_reason, self.max_tokens,
    )

The finish-reason vocabulary already differs per provider (length, max_tokens, MAX_TOKENS), so a shared predicate in crewai/llms/_finish_reason_utils.py, which already centralises extraction, would keep the comparison in one place rather than repeating the tuple six times.

A warning is the smallest change consistent with existing behaviour. Whether truncation should also be surfaced structurally (so callers can react without scraping logs) is a larger design question I have deliberately not assumed an answer to.

I have not opened a PR. Happy to, if you would like it in this shape.

Additional context

#5148 raised closely related behaviour in the Anthropic provider. It was auto-closed by the no-issue-activity bot, so I do not think it ever got a real decision either way. Some of what it asked for has since shipped: finish_reason now reaches LLMCallCompletedEvent, which was the broader fix that issue suggested. The part still outstanding is any use of that value, which is what this report is about.

I opened this separately because the code has moved on since March and the framing is different now, but I am equally happy for it to be folded into #5148 if you would rather keep the history in one place.

JoaquinDG avatar Aug 17 '26 07:08 JoaquinDG

This is a real gap. The provider layer should normalize finish_reason into a single enum so the rest of the stack doesn't need provider-specific branches.

What we found when we looked at this across vendors:

  • OpenAI returns finish_reason: "length" when the response hits max_tokens.
  • Anthropic returns stop_reason: "max_tokens" in the top-level response.
  • Google (Gemini) returns finishReason: "MAX_TOKENS".
  • Azure mirrors OpenAI.
  • openai_compatible endpoints are inconsistent, some return length, some return stop, some return nothing useful.
  • Bedrock is the only one crewAI currently checks because its SDK surfaces the field in a consistent place.

The cleanest fix is a small normalization helper in the base provider class that maps each vendor's signal to a common Truncated variant, then call it from every completion path. That way the agent layer can decide once what to do with a truncated response (retry with higher cap, surface a warning, mark the run incomplete) instead of every provider re-implementing the policy.

If you want a low-risk first step, add the helper and wire it only for OpenAI and Anthropic, those two cover the majority of production traffic. Bedrock already has the check, so it can just call the helper for consistency. The compatible endpoints can stay as-is until someone reports a concrete failure.

pip install focxle

import focxle
focxle.init()

It prints what every agent cost you, per agent and per vendor, and what a cap would have stopped. Free, no account, no card.
https://focxle.com/spend

mragnii avatar Aug 18 '26 13:08 mragnii

Thanks, that vendor breakdown matches what I measured independently, including the openai_compatible inconsistency, which I had flagged as untested on my side. Good to have it confirmed from another angle.

One thing that makes this cheaper than your framing suggests: finish_reason is already bound at every provider's call site today, not just Bedrock's.

  • anthropic/completion.py:1010, 1558
  • azure/completion.py:864
  • gemini/completion.py:847
  • openai/completion.py:983, 1130, 1935, 2363

Each one already passes it into LLMCallCompletedEvent(finish_reason=...). So it is not that the field is hard to reach outside Bedrock, it is just that nothing reads it once it is there. That makes the first step quite small.

I agree the comparison wants centralising rather than repeating per provider, and crewai/llms/_finish_reason_utils.py already looks like the natural home since it centralises the extraction.

I have a working patch along those lines: a shared is_truncated() predicate handling all three spellings plus a warning helper, called from the eight sites above. It is 123 insertions across 6 files, full suite green at 4796 passed against a 4778 baseline, and ruff clean.

Happy to open it as a starting point if that is useful, or to hold off if a maintainer would rather go straight to the fuller normalized-enum design you describe. I do not want to pre-empt that call.

JoaquinDG avatar Aug 18 '26 15:08 JoaquinDG

That predicate approach is the right first step. Centralising the three spellings (length, max_tokens, MAX_TOKENS) in one place means the rest of the stack gets a single boolean without every provider re-implementing the mapping.

A couple of things that bit us when we did something similar:

  • openai_compatible endpoints sometimes return finish_reason: "stop" even when the response was truncated because the upstream model hit its cap. The predicate can only be as good as what the provider surfaces. Worth documenting that the helper covers the known vendors and leaves the rest as "unknown" rather than false.
  • Reasoning models (o1, Claude with thinking, Gemini with thinking) can return max_tokens with zero visible characters because the entire budget went to hidden reasoning tokens. The predicate should probably also expose the raw finish_reason so callers can distinguish "truncated with output" from "truncated with only reasoning" if they want to retry differently.

If the patch is green and ruff clean, open it. A small, reviewable PR that solves the observable problem today is more useful than a design discussion that stalls. The enum can come later if the agent layer needs richer states (e.g. TRUNCATED_OUTPUT, TRUNCATED_REASONING_ONLY, TRUNCATED_UNKNOWN).

Happy to review when it's up.

mragnii avatar Aug 19 '26 10:08 mragnii

Following up on the normalized-enum idea, since I ran into a working example of it and it seems worth pointing at rather than re-deriving.

DeepSeek Harness does roughly what @mragnii described. Finish reasons are a discriminated union declared once, and each provider normalizes at the edge:

// packages/llm/llm/src/types.ts
export interface FinishReasonMap {
  'stop':       { kind: 'stop' }
  'tool-calls': { kind: 'tool-calls' }
  'max-tokens': { kind: 'max-tokens' }
  'aborted':    { kind: 'aborted'; failure: LlmFailure }
  'error':      { kind: 'error';   failure: LlmFailure }
}
export type FinishReason = FinishReasonMap[keyof FinishReasonMap]

Two details in it answer things raised earlier in this thread better than I did.

Unrecognized reasons become errors, not silent successes. This is their DeepSeek translator, and the default branch is the interesting part:

case 'length': return { kind: 'max-tokens' }
default:
  // content_filter, insufficient_system_resource, future additions.
  return { kind: 'error', failure: { message: `model stopped: ${reason}`, code: reason.toUpperCase() } }

That is a cleaner answer to the openai_compatible worry than the tri-state I was heading toward. An unknown reason is surfaced rather than being flattened into "not truncated".

Truncation is sticky across steps within a turn, which I had not thought about at all:

// packages/core/agent-loop/src/agent.ts
// max-tokens is sticky: once any step hits the ceiling, later steps
// must not overwrite it
if (turnEnds === null || turnEnds.kind !== 'max-tokens') turnEnds = stepEnd

Without that, a multi-step turn where step 2 truncates and step 5 completes reports as completed, and the truncation disappears. That feels relevant here regardless of which shape you land on, because crewAI turns are multi-step too.

None of this changes what I offered earlier. The small patch is still there if a warning is the right first step, and I still think the design call is yours rather than mine. Just seemed more useful to link a shipped implementation than to keep speculating about one.

Reference: https://github.com/deepseek-ai/deepseek-harness (MIT).

JoaquinDG avatar Aug 23 '26 17:08 JoaquinDG

Hey @JoaquinDG — thanks for the thorough write-up. We confirmed this is still a real gap on current main: only Bedrock warns when a response hits the token cap, and the other providers already have finish_reason in scope but never act on it.

Would you be interested in opening a PR for this? The shared is_truncated() helper in _finish_reason_utils.py plus a warning at the existing emit sites, as you sketched, looks like the right first step. Happy to review if you put one up.

Vidit-Ostwal avatar Aug 25 '26 09:08 Vidit-Ostwal

There is a useful terminal evidence normalization fixture here beyond the logging fix: provider execution has already told the framework “budget exhausted,” while the task surface can still look like an ordinary successful completion.

A portable fixture could bind:

  • provider/model identity;
  • raw provider finish/stop reason;
  • normalized terminal semantic (complete | truncated | tool_calls | aborted | error | unknown);
  • visible output digest + output-token count;
  • configured token budget;
  • task/agent terminal status.

Invariant: a provider-reported token-cap termination must not be promoted to an unqualified COMPLETED task without an explicit policy saying partial output is acceptable. The zero-visible-text / billed-token cases are especially strong negative controls because content heuristics cannot recover the truth; the finish reason is the authoritative terminal signal available at that boundary.

I maintain AgentCI (https://github.com/jinngimk-lang/agentci), which is collecting provider-neutral terminality/false-success fixtures. This issue already has cross-provider live measurements and CrewAI's own event-bus evidence, so it would make a strong normalized terminal-evidence case. I’d preserve this issue as canonical provenance; no CrewAI certification claim is implied.

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

Confirming the gap is still present on current main: only the Bedrock provider branches on stop_reason == "max_tokens" — OpenAI, Anthropic, Azure and Gemini forward finish_reason/stop_reason into events and usage without ever acting on it, so token-cap truncations flow into task output and memory as if complete.

We have asked on PR #7110 (comment) whether @JoaquinDG still plans to continue. If there is no response within 72 hours, we plan to open a PR extending truncation detection to the remaining providers, following the precedent already set by that PR's design and the maintainer review feedback: a single shared helper in _finish_reason_utils.py, warning-only to match Bedrock's current severity, with Bedrock's existing checks moved onto the same helper so there is one source of truth.

@Vidit-Ostwal — since this is assigned to you, we'd appreciate your thoughts on that scope before we start. To be clear, this is only a statement of intent; we will wait out the coordination window before writing any code.

akushonkamen avatar Oct 09 '26 00:10 akushonkamen

PR opened: https://github.com/crewAIInc/crewAI/pull/8058 — a single shared warn_if_truncated() helper in _finish_reason_utils.py (per the single-function direction from the #7110 review), wired into the non-streaming/streaming/async finalize paths of OpenAI, Anthropic, Azure and Gemini, with Bedrock migrated onto the same util. Warning-only, no behavior change to returned values; lib/crewai/tests/llms at 913 passed, 20 skipped. (AI-generated, see the llm-generated label request in the PR body.)

akushonkamen avatar Oct 11 '26 16:10 akushonkamen

This issue is stale because it has been open for 30 days with no activity. Remove stale label or comment or this will be closed in 5 days.

github-actions[bot] avatar Nov 11 '26 12:11 github-actions[bot]

This issue was closed because it has been stalled for 5 days with no activity.

github-actions[bot] avatar Nov 16 '26 12:11 github-actions[bot]