Skip to content

feat(core)!: report finish reasons and stop on cut or filtered output - #98

Merged
gopaljigaur merged 3 commits into
mainfrom
feat/finish-reasons
Oct 15, 2026
Merged

gopaljigaur merged 3 commits into
mainfrom
feat/finish-reasons

Conversation

@gopaljigaur

@gopaljigaur gopaljigaur commented Oct 15, 2026 •

Copy link
Copy Markdown
Owner

Reads the provider's finish reason, as LiteLLM normalizes it, and stops a run whose output was cut or filtered instead of treating it as the answer.

What changed

  • StepFinished.finish_reason and RunResult.finish_reason (the last completion's) carry the value LiteLLM puts on the choice: stop, length, tool_calls, content_filter. Both are optional and None when there is none.
  • finish_reason="length" ends the run with the new stop reason max_tokens; content_filter ends it with the new stop reason content_filter. content is empty, as for the other stops without an answer, and guards don't run. Any partial text stays in the history as the assistant turn; a turn with no text is left out, since providers rewrite, drop or pass on an empty assistant message differently (LiteLLM turns it into a placeholder for Anthropic, drops it for Bedrock Converse and sends empty text to Gemini).
  • Tool calls of such a completion are not run and the turn is kept without them, so a tool call cut by the limit ends the run with max_tokens instead of an "arguments are not valid JSON" tool error, and the history needs no tool result.
  • The check is in the step loop on the assembled response, so streamed runs (the chunk builder keeps the last chunk's finish reason) and naive tool mode report the same. In naive mode the cut text is not emitted as a TextDelta, since it may be a call that no longer parses.
  • Docs: a short "Output limit and filtering" section in the agents guide, the RunResult table, the StepFinished row and the API reference, in docs/ and the website.

Provider mapping

Checked in LiteLLM's map_finish_reason (litellm_core_utils/core_helpers.py): Anthropic max_tokens and compaction and Gemini MAX_TOKENS map to length; Anthropic refusal, Gemini SAFETY/RECITATION/PROHIBITED_CONTENT and the like, and Bedrock guardrail_intervened map to content_filter; tool_use maps to tool_calls. Bedrock Converse goes through the same map. In streams, LiteLLM only rewrites stop to tool_calls, so length survives.

One stop reason, content_filter, covers refusals and filtering because the normalized value does not tell them apart. The provider's own value is mostly gone by then: on the non streamed Gemini path LiteLLM keeps it as native_finish_reason in provider_specific_fields; elsewhere it is lost. The run reports the normalized value so it means the same for every provider.

Decisions

  • content stays empty for max_tokens and content_filter. content is the answer the run ends on, and a cut or filtered completion is not one: returning it would make run() hand back half a sentence, or half a JSON document for a response_model, with nothing to tell it from a real answer. Every other stop without an answer (max_steps, budget, guard) already leaves content empty, and the partial text is still in the history and in the streamed deltas for callers who want it.
  • No automatic continuation on length. Common agent libraries leave it to the caller too, and continuing cannot repair a cut tool call. Callers can raise max_tokens or send a follow up run, since the partial turn is in the history.
  • A completion cut mid tool call runs none of its calls, even complete ones before the cut one: the turn is partial and the model did not finish deciding.

Breaking change

A run whose last completion finished with length or content_filter used to end completed with the partial text as content; it now ends max_tokens or content_filter with empty content, so run() returns "" for it, as it does for max_steps.

Tests

Mocked litellm.acompletion: finish reasons on each step and the result; cut text ends max_tokens with the partial turn in history; guards don't judge a cut answer; a cut native tool call is not run (non streamed and streamed) and leaves no empty turn; a complete call before a cut one is not run either; a cut naive call emits no text; content_filter streamed and not; a subagent cut by the limit gives its caller stopped without an answer: max_tokens. uv run pytest (407 passed), uv run pre-commit run --all-files and uv run mypy cyclops pass.

Closes #59

Each step's StepFinished and the RunResult now carry the completion's
finish_reason as LiteLLM normalizes it. A completion cut by the output
limit ends the run with stop_reason "max_tokens", and one the provider
filtered or refused ends it with "content_filter". Neither runs guards
or the completion's tool calls, so a cut tool call is no longer reported
as invalid JSON. Streamed and naive runs report the same.

BREAKING CHANGE: a run whose last completion has finish_reason "length"
or "content_filter" now ends with stop_reason "max_tokens" or
"content_filter" and empty content, where it ended with "completed" and
the partial text as content. StepFinished has a required finish_reason.

@gopaljigaur gopaljigaur left a comment

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nothing blocking. The core change is right: the finish reason is read on the assembled response, so native, naive and streamed runs agree, guards never see a cut answer, and a subagent cut by the limit gives its parent the tool error researcher stopped without an answer: max_tokens (checked with a scratch test). All eight new tests fail on main. uv run pytest (405 passed), uv run pre-commit run --all-files and uv run mypy cyclops pass on d83dd52.

LiteLLM facts (1.105.1, checked in source)

  • map_finish_reason: Anthropic max_tokens to length, refusal to content_filter, stop_sequence to stop, tool_use to tool_calls; Gemini MAX_TOKENS to length, SAFETY, RECITATION, PROHIBITED_CONTENT, BLOCKLIST, SPII, LANGUAGE and OTHER to content_filter; Bedrock guardrail_intervened to content_filter. Matches the PR body.
  • stream_chunk_builder takes the last non-None finish reason, and CustomStreamWrapper.finish_reason_handler only turns stop into tool_calls. Confirmed. _streamed_completion resets chunks per attempt, so a stream retried before content reports the finish reason of the attempt that succeeded.
  • Anthropic pause_turn is not in the map, so it becomes stop (with a LiteLLM warning) and the run ends completed on a paused server tool turn. Not changed by this PR and correctly not a stop here; a follow up could continue on it.
  • Anthropic compaction maps to length, so a context management compaction pause would end a run with max_tokens. See the inline note.
  • Gemini returns tool_calls whenever the message has a tool call (_check_finish_reason, and the stream handler once it has seen one), so MAX_TOKENS only reaches cyclops as length on text. Gemini function calls are whole, so no harm.
  • With response_model on Anthropic through the tool based JSON mode, LiteLLM sets stop_reason to stop (_resolve_json_mode_non_streaming), so a cut structured answer there still ends completed and fails in model_validate_json. Out of scope; maybe one line in the docs.
  • The PR body says LiteLLM does not keep refusals and filtering apart. Choices.__init__ keeps the provider value in provider_specific_fields["native_finish_reason"] when it maps it, and the Gemini path sets it too; the Anthropic non streamed path assigns the mapped value directly, so there it is lost. The body should say so; no code change needed.

Content on a cut answer
Keeping content empty is the right call for cyclops, and I would keep it: content is the answer guards accepted, max_steps and guard already return "", and run() callers only see the string, so partial text there is exactly the silent truncation #59 describes. The other SDKs differ more than the body says, though: Pydantic AI returns non empty text with finish_reason="length" as normal output and raises only when the response is empty (UnexpectedModelBehavior, ContentFilterError, IncompleteToolCall after retries); the Vercel AI SDK returns the partial text with finishReason: "length"; the OpenAI Agents SDK raises ModelBehaviorError on an incomplete Responses result and on an empty length chat completion, and returns the text otherwise. They agree on not continuing, which is what the body relies on, so a narrower sentence there would be accurate.

Running none of the calls of a cut completion is right too: the run ends either way, so a complete call that ran would leave a result the model never reads in this run, and keeping the turn without calls keeps the transcript valid with no tool results.

Inline

  1. StepFinished.finish_reason is a required str; a missing finish reason now fails the run.
  2. An empty cut turn goes into the history as "", which each provider rewrites differently.
  3. The comment on _FINISH_STOP_REASONS could name the compaction mapping.
  4. Naive mode still emits a cut tool call as a TextDelta.
  5. The "complete calls are not run" decision has no test.

Confidentiality and prose checks over the title, body, commits, added lines and comments are clean.

Comment thread cyclops/core/events.py Resolved
Comment thread cyclops/core/run.py Resolved
Comment thread cyclops/core/run.py Resolved
Comment thread cyclops/core/run.py Resolved
Comment thread tests/test_agent.py Resolved
… of events

StepFinished.finish_reason is optional, like RunResult's. A cut or
filtered completion with no text adds no assistant turn, since providers
rewrite or drop empty assistant text. In naive mode cut text is not
emitted as a TextDelta, as it may be a call that no longer parses.

@gopaljigaur gopaljigaur left a comment

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Two wording findings, no code bugs. On 69dca12, uv run pytest (407 passed), uv run pre-commit run --all-files and uv run mypy cyclops pass. All 10 finish reason tests fail against main's cyclops/. The two tests changed in 69dca12 (test_a_tool_call_cut_by_the_length_limit_is_not_run, test_a_naive_tool_call_cut_by_the_length_limit_ends_with_max_tokens) fail against d83dd52's cyclops/.

The five earlier threads, checked against the code

  1. StepFinished.finish_reason is Optional[str] = None, and the docs say so. The tests/test_skills.py change is right to keep: with main's version of the file the two agent tests fail, because a MagicMock attribute is neither str nor None. Setting a real finish_reason in the mock is the fix; widening the field to accept anything would only hide a malformed response.
  2. A cut or filtered completion with no text adds no turn (if content:), reasoning only turns included. Without a tool call to pair with, nothing has to send that reasoning back. The next run then sends two user turns in a row. I ran that history through LiteLLM's prompt factories, and Anthropic, Bedrock Converse and Gemini each merge them into one user turn, so the transcript is the same for all of them. OpenAI accepts it as is.
  3. The _FINISH_STOP_REASONS comment names the compaction mapping.
  4. Naive mode no longer emits a TextDelta for a completion that ends the run, and the test checks the events. Non naive runs still emit the partial text, as they should.
  5. test_a_complete_call_before_a_cut_one_is_not_run_either and test_run_cut_by_the_length_limit_gives_an_error_result both assert the claimed behaviour and fail on main.

PR body

  • "it is lost only on Anthropic's non streamed path" is wrong. native_finish_reason survives only where LiteLLM builds Choices from the provider's own value, and of the paths I read that is the non streamed Gemini path. Bedrock Converse passes an already mapped value to Choices (converse_transformation.py, initial_finish_reason = map_finish_reason(...)), so it is lost there too. Every streamed response loses it as well: StreamingChoices maps the value and keeps no native one, and stream_chunk_builder builds Choices from the mapped one. My first review only said the Anthropic non streamed path loses it, which may be where "only" came from. Suggest: "on the non streamed Gemini path LiteLLM keeps it as native_finish_reason in provider_specific_fields; elsewhere it is lost."
  • "Anthropic, Bedrock and Gemini each rewrite or drop an empty assistant message" does not hold for Gemini. See the inline thread.
  • The rest matches the code: the provider mapping, the decisions, the breaking change note and the test list (407 passed).

The confidentiality grep over the title, body, commits, added lines, comments and replies is clean, and so is the dash check.

Comment thread cyclops/core/run.py Resolved

@gopaljigaur gopaljigaur left a comment

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No findings.

Both round 2 findings are fixed and match LiteLLM 1.105.1. The run.py comment and the PR body now say that providers rewrite, drop or pass on an empty assistant turn: Anthropic gets a placeholder, Bedrock Converse drops it, and Gemini receives {"text": ""}. The body now says the native finish reason survives only on the non streamed Gemini path. That holds for the providers in scope: Bedrock Converse hands a mapped value to Choices, Anthropic assigns the mapped value directly, and streamed responses lose it through StreamingChoices and stream_chunk_builder.

52c1b8a sits directly on 69dca12 with the same merge base, so nothing changed apart from the three line comment in cyclops/core/run.py. uv run pytest (407 passed), pre-commit and mypy cyclops pass. The confidentiality grep and the dash check over the title, body, commits, added lines, comments and reviews are clean.

@gopaljigaur
gopaljigaur merged commit 88c1172 into main Oct 15, 2026
10 checks passed
@gopaljigaur
gopaljigaur deleted the feat/finish-reasons branch October 15, 2026 02:11
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Report finish reasons and handle truncated output

1 participant