Repository navigation
feat(core)!: report finish reasons and stop on cut or filtered output - #98
Conversation
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
left a comment
There was a problem hiding this comment.
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: Anthropicmax_tokenstolength,refusaltocontent_filter,stop_sequencetostop,tool_usetotool_calls; GeminiMAX_TOKENStolength,SAFETY,RECITATION,PROHIBITED_CONTENT,BLOCKLIST,SPII,LANGUAGEandOTHERtocontent_filter; Bedrockguardrail_intervenedtocontent_filter. Matches the PR body.stream_chunk_buildertakes the last non-None finish reason, andCustomStreamWrapper.finish_reason_handleronly turnsstopintotool_calls. Confirmed._streamed_completionresetschunksper attempt, so a stream retried before content reports the finish reason of the attempt that succeeded.- Anthropic
pause_turnis not in the map, so it becomesstop(with a LiteLLM warning) and the run endscompletedon a paused server tool turn. Not changed by this PR and correctly not a stop here; a follow up could continue on it. - Anthropic
compactionmaps tolength, so a context management compaction pause would end a run withmax_tokens. See the inline note. - Gemini returns
tool_callswhenever the message has a tool call (_check_finish_reason, and the stream handler once it has seen one), soMAX_TOKENSonly reaches cyclops aslengthon text. Gemini function calls are whole, so no harm. - With
response_modelon Anthropic through the tool based JSON mode, LiteLLM setsstop_reasontostop(_resolve_json_mode_non_streaming), so a cut structured answer there still endscompletedand fails inmodel_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 inprovider_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
StepFinished.finish_reasonis a requiredstr; a missing finish reason now fails the run.- An empty cut turn goes into the history as
"", which each provider rewrites differently. - The comment on
_FINISH_STOP_REASONScould name thecompactionmapping. - Naive mode still emits a cut tool call as a
TextDelta. - 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.
… 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
left a comment
There was a problem hiding this comment.
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
StepFinished.finish_reasonisOptional[str] = None, and the docs say so. Thetests/test_skills.pychange is right to keep: with main's version of the file the two agent tests fail, because aMagicMockattribute is neitherstrnorNone. Setting a realfinish_reasonin the mock is the fix; widening the field to accept anything would only hide a malformed response.- 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. - The
_FINISH_STOP_REASONScomment names the compaction mapping. - Naive mode no longer emits a
TextDeltafor a completion that ends the run, and the test checks the events. Non naive runs still emit the partial text, as they should. test_a_complete_call_before_a_cut_one_is_not_run_eitherandtest_run_cut_by_the_length_limit_gives_an_error_resultboth assert the claimed behaviour and fail on main.
PR body
- "it is lost only on Anthropic's non streamed path" is wrong.
native_finish_reasonsurvives only where LiteLLM buildsChoicesfrom 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 toChoices(converse_transformation.py,initial_finish_reason = map_finish_reason(...)), so it is lost there too. Every streamed response loses it as well:StreamingChoicesmaps the value and keeps no native one, andstream_chunk_builderbuildsChoicesfrom 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 asnative_finish_reasoninprovider_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.
43d6040 to
52c1b8a
Compare
gopaljigaur
left a comment
There was a problem hiding this comment.
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.
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_reasonandRunResult.finish_reason(the last completion's) carry the value LiteLLM puts on the choice:stop,length,tool_calls,content_filter. Both are optional andNonewhen there is none.finish_reason="length"ends the run with the new stop reasonmax_tokens;content_filterends it with the new stop reasoncontent_filter.contentis 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).max_tokensinstead of an "arguments are not valid JSON" tool error, and the history needs no tool result.TextDelta, since it may be a call that no longer parses.RunResulttable, theStepFinishedrow and the API reference, indocs/and the website.Provider mapping
Checked in LiteLLM's
map_finish_reason(litellm_core_utils/core_helpers.py): Anthropicmax_tokensandcompactionand GeminiMAX_TOKENSmap tolength; Anthropicrefusal, GeminiSAFETY/RECITATION/PROHIBITED_CONTENTand the like, and Bedrockguardrail_intervenedmap tocontent_filter;tool_usemaps totool_calls. Bedrock Converse goes through the same map. In streams, LiteLLM only rewritesstoptotool_calls, solengthsurvives.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 asnative_finish_reasoninprovider_specific_fields; elsewhere it is lost. The run reports the normalized value so it means the same for every provider.Decisions
contentstays empty formax_tokensandcontent_filter.contentis the answer the run ends on, and a cut or filtered completion is not one: returning it would makerun()hand back half a sentence, or half a JSON document for aresponse_model, with nothing to tell it from a real answer. Every other stop without an answer (max_steps,budget,guard) already leavescontentempty, and the partial text is still in the history and in the streamed deltas for callers who want it.length. Common agent libraries leave it to the caller too, and continuing cannot repair a cut tool call. Callers can raisemax_tokensor send a follow up run, since the partial turn is in the history.Breaking change
A run whose last completion finished with
lengthorcontent_filterused to endcompletedwith the partial text ascontent; it now endsmax_tokensorcontent_filterwith emptycontent, sorun()returns""for it, as it does formax_steps.Tests
Mocked
litellm.acompletion: finish reasons on each step and the result; cut text endsmax_tokenswith 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_filterstreamed and not; a subagent cut by the limit gives its callerstopped without an answer: max_tokens.uv run pytest(407 passed),uv run pre-commit run --all-filesanduv run mypy cyclopspass.Closes #59