This is an automated email from the ASF dual-hosted git repository. github-merge-queue[bot] pushed a commit to branch gh-readonly-queue/dev/pr-13414-54d110baa31af58a3c3c13df60b9f20938ac25ee in repository https://gitbox.apache.org/repos/asf/seatunnel.git
commit 02a7c22b3e663c3b4b1230703adb39f82d313f1d Author: SEZ <[email protected]> AuthorDate: Tue Nov 24 13:59:25 2026 +0000 [Fix][seatunnel-cli] Keep the real reason an OpenAI-compatible turn stopped (#13414) Co-authored-by: Claude Opus 5 <[email protected]> --- docs/en/ai-cli/quickstart.md | 12 ++ docs/zh/ai-cli/quickstart.md | 10 ++ seatunnel-cli/seatunnel_cli/llm_provider.py | 96 +++++++++++++- seatunnel-cli/tests/test_llm_provider_openai.py | 166 ++++++++++++++++++++++++ 4 files changed, 278 insertions(+), 6 deletions(-) diff --git a/docs/en/ai-cli/quickstart.md b/docs/en/ai-cli/quickstart.md index d6f0bab50d..04449ffb32 100644 --- a/docs/en/ai-cli/quickstart.md +++ b/docs/en/ai-cli/quickstart.md @@ -71,6 +71,18 @@ export ORCAROUTER_API_KEY=orc_... # export ORCAROUTER_ECHO_REASONING_CONTENT=true # optional: replay reasoning_content for reasoning models ``` +### Reasoning models and output limits + +For any OpenAI-compatible endpoint, the reasoning block is read under either +field name servers use for it — `reasoning_content` or `reasoning` (vLLM's +reasoning parser emits the latter from 0.34 on) — so no extra setting is +needed to keep reasoning working across servers. + +If a model stops at its output token limit before writing any answer, the CLI +reports that explicitly instead of treating the empty response as a finished +one. This usually means the reasoning consumed the whole budget: raise +`max_tokens`, shorten the request, or turn thinking off for the run. + ### OrcaRouter AI gateway [OrcaRouter](https://www.orcarouter.ai) is an OpenAI-compatible AI gateway diff --git a/docs/zh/ai-cli/quickstart.md b/docs/zh/ai-cli/quickstart.md index e1ce2dccc3..62327f18a9 100644 --- a/docs/zh/ai-cli/quickstart.md +++ b/docs/zh/ai-cli/quickstart.md @@ -70,6 +70,16 @@ export ORCAROUTER_API_KEY=orc_... # export ORCAROUTER_ECHO_REASONING_CONTENT=true # 可选:保留并回传推理模型的 reasoning_content ``` +### 推理模型与输出长度上限 + +对任意 OpenAI 兼容端点,推理内容会按服务端实际使用的字段名读取 —— +`reasoning_content` 或 `reasoning`(vLLM 的 reasoning parser 从 0.34 起使用后者)—— +因此跨服务端使用推理模型无需额外设置。 + +如果模型在写出任何回答之前就达到输出 token 上限,CLI 会明确报告这一情况, +而不是把空响应当成正常结束。这通常意味着推理占用了全部预算:可以提高 +`max_tokens`、缩短请求,或本次运行关闭思考模式。 + ### OrcaRouter AI 网关 [OrcaRouter](https://www.orcarouter.ai) 是一个 OpenAI 兼容的 AI 网关,在单个端点 diff --git a/seatunnel-cli/seatunnel_cli/llm_provider.py b/seatunnel-cli/seatunnel_cli/llm_provider.py index a15fb43dfe..39878acbbc 100644 --- a/seatunnel-cli/seatunnel_cli/llm_provider.py +++ b/seatunnel-cli/seatunnel_cli/llm_provider.py @@ -51,10 +51,56 @@ def _env_bool(name: str, default: bool) -> bool: return value.strip().lower() not in {"0", "false", "no", "off"} +class TruncatedOutputError(RuntimeError): + """The model stopped at the token limit without producing anything usable. + + Raised instead of returning the empty turn, because an empty assistant + message is indistinguishable from a model that simply had nothing to say: + the caller would carry on, generate no config and report a generic + failure, with the real cause -- the output budget -- nowhere in the error. + """ + + +# OpenAI-compatible servers report why generation stopped in `finish_reason`. +# The internal format in this module mirrors the Bedrock Converse vocabulary +# (`output.message.content` plus `stopReason`), so each one is translated into +# that vocabulary rather than invented here. +# +# Anything absent or unrecognised still becomes `end_turn`: OpenAI-compatible +# servers add their own values, and an unfamiliar one is not a reason to fail a +# call that returned usable content. +_OPENAI_STOP_REASONS = { + "stop": "end_turn", + "tool_calls": "tool_use", + "length": "max_tokens", + "content_filter": "content_filtered", +} + +# Reasoning models disagree on the field name. vLLM's reasoning parser emits +# `reasoning` from 0.34 on, while earlier builds and several hosted providers +# emit `reasoning_content`. Reading only one of them silently discards the +# whole reasoning block, and for a server that requires it to be replayed +# after a tool call that turns into a protocol error on the next request. +_OPENAI_REASONING_FIELDS = ("reasoning_content", "reasoning") + + +def _openai_stop_reason(finish_reason: str | None) -> str: + """Translate an OpenAI `finish_reason` into an internal stop reason.""" + return _OPENAI_STOP_REASONS.get(finish_reason or "", "end_turn") + + def format_llm_error(error: Exception) -> str: """Return an actionable error message for common provider protocol issues.""" message = str(error) lower = message.lower() + if isinstance(error, TruncatedOutputError): + return ( + f"{message}\n\n" + "Hint: the model hit its output token limit before writing any " + "answer. Raise max_tokens, shorten the request, or -- for a " + "reasoning model -- disable thinking so the budget is not spent " + "on reasoning that is then discarded." + ) if "reasoning_content" in lower and "passed back" in lower: return ( f"{message}\n\n" @@ -778,17 +824,21 @@ class OpenAIProvider(LLMProvider): stream = self._client.chat.completions.create(**kwargs) started_tools: dict[int, str] = {} # index -> tool_use_id + saw_text = False + saw_reasoning = False for chunk in stream: if not chunk.choices: continue choice = chunk.choices[0] delta = choice.delta - reasoning_content = self._get_openai_field(delta, "reasoning_content") + reasoning_content = self._get_openai_reasoning(delta) if reasoning_content: + saw_reasoning = True yield {"type": "reasoning_delta", "text": reasoning_content} if delta and delta.content: + saw_text = True yield {"type": "text_delta", "text": delta.content} if delta and delta.tool_calls: @@ -803,8 +853,20 @@ class OpenAIProvider(LLMProvider): if choice.finish_reason: for idx in sorted(started_tools): yield {"type": "tool_stop", "tool_use_id": started_tools[idx]} - sr = "tool_use" if choice.finish_reason == "tool_calls" else "end_turn" + sr = _openai_stop_reason(choice.finish_reason) yield {"type": "message_stop", "stop_reason": sr} + # Reasoning that consumed the whole budget is the case worth + # failing on: the turn ends with no text and no tool call, so + # there is nothing for the caller to act on, and reporting it + # as a normal stop sends it on to parse an empty config. + if sr == "max_tokens" and not saw_text and not started_tools: + raise TruncatedOutputError( + "The model stopped at the output token limit without " + "producing any content" + + (" (the budget was spent on reasoning)" + if saw_reasoning else "") + + "." + ) def _to_openai_messages(self, messages: list[dict], system: str = "") -> list[dict]: """Convert internal message format to OpenAI API format.""" @@ -907,7 +969,7 @@ class OpenAIProvider(LLMProvider): message = choice.message content = [] - reasoning_content = OpenAIProvider._get_openai_field(message, "reasoning_content") + reasoning_content = OpenAIProvider._get_openai_reasoning(message) if reasoning_content: content.append({"reasoningContent": reasoning_content}) @@ -924,15 +986,37 @@ class OpenAIProvider(LLMProvider): } }) - stop_reason = "end_turn" - if choice.finish_reason == "tool_calls": - stop_reason = "tool_use" + stop_reason = _openai_stop_reason(choice.finish_reason) + + # Same rule as the streaming path: a turn cut off before it wrote + # anything is a failed call, not an empty answer. + if stop_reason == "max_tokens" and not message.content and not message.tool_calls: + raise TruncatedOutputError( + "The model stopped at the output token limit without producing " + "any content" + + (" (the budget was spent on reasoning)" if reasoning_content else "") + + "." + ) return { "output": {"message": {"role": "assistant", "content": content}}, "stopReason": stop_reason, } + @staticmethod + def _get_openai_reasoning(obj): + """Read the reasoning block under whichever field name the server used. + + Both names are accepted because the field is not standardised; see + `_OPENAI_REASONING_FIELDS`. The first non-empty one wins, so a server + that sends both does not get its reasoning concatenated twice. + """ + for field_name in _OPENAI_REASONING_FIELDS: + value = OpenAIProvider._get_openai_field(obj, field_name) + if value: + return value + return None + @staticmethod def _get_openai_field(obj, field_name: str): """Read SDK fields, including provider-specific extra fields.""" diff --git a/seatunnel-cli/tests/test_llm_provider_openai.py b/seatunnel-cli/tests/test_llm_provider_openai.py index f44c995b82..5560c39eff 100644 --- a/seatunnel-cli/tests/test_llm_provider_openai.py +++ b/seatunnel-cli/tests/test_llm_provider_openai.py @@ -21,6 +21,7 @@ from types import SimpleNamespace from seatunnel_cli.llm_provider import ( LLMProvider, OpenAIProvider, + TruncatedOutputError, format_llm_error, ) @@ -253,6 +254,171 @@ class OpenAIProviderReasoningContentTest(unittest.TestCase): self.assertIn("OpenAI-compatible reasoning model", message) self.assertIn("OPENAI_ECHO_REASONING_CONTENT", message) + def test_openai_stream_accepts_the_reasoning_field_alias(self): + """vLLM's reasoning parser names the field `reasoning` from 0.34 on. + + Reading only `reasoning_content` dropped the whole block, and for a + server that requires it to be replayed after a tool call that became a + 400 on the following request. + """ + provider = OpenAIProvider.__new__(OpenAIProvider) + provider._model_id = "reasoning-model" + provider._client = _FakeOpenAIClient( + [ + _chunk(SimpleNamespace( + content=None, tool_calls=None, model_extra={"reasoning": "weighing sinks"}, + )), + _chunk(SimpleNamespace(content="env {}", tool_calls=None), finish_reason="stop"), + ] + ) + + events = list(provider.chat_stream([{"role": "user", "content": [{"text": "hi"}]}])) + + self.assertIn({"type": "reasoning_delta", "text": "weighing sinks"}, events) + self.assertIn({"type": "text_delta", "text": "env {}"}, events) + + def test_openai_response_accepts_the_reasoning_field_alias(self): + message = SimpleNamespace( + content="done", model_extra={"reasoning": "checked"}, tool_calls=None, + ) + response = SimpleNamespace( + choices=[SimpleNamespace(message=message, finish_reason="stop")] + ) + + self.assertEqual( + OpenAIProvider._from_openai_response(response)["output"]["message"]["content"], + [{"reasoningContent": "checked"}, {"text": "done"}], + ) + + def test_reasoning_content_wins_when_a_server_sends_both_names(self): + message = SimpleNamespace( + content="done", + model_extra={"reasoning_content": "canonical", "reasoning": "alias"}, + tool_calls=None, + ) + response = SimpleNamespace( + choices=[SimpleNamespace(message=message, finish_reason="stop")] + ) + + self.assertEqual( + OpenAIProvider._from_openai_response(response)["output"]["message"]["content"], + [{"reasoningContent": "canonical"}, {"text": "done"}], + ) + + +class OpenAIProviderStopReasonTest(unittest.TestCase): + """Every finish reason used to collapse to `end_turn` except tool_calls. + + That made a response truncated at the token limit indistinguishable from a + completed one, so the caller went on to parse a config that was cut in half + -- or absent entirely -- and reported a generic failure instead of the real + cause. + """ + + @staticmethod + def _response(finish_reason, content="env {}", tool_calls=None, reasoning=None): + message = SimpleNamespace( + content=content, + tool_calls=tool_calls, + model_extra={"reasoning_content": reasoning} if reasoning else {}, + ) + return SimpleNamespace( + choices=[SimpleNamespace(message=message, finish_reason=finish_reason)] + ) + + def test_finish_reasons_are_translated_rather_than_collapsed(self): + for finish_reason, expected in [ + ("stop", "end_turn"), + ("length", "max_tokens"), + ("content_filter", "content_filtered"), + ]: + with self.subTest(finish_reason=finish_reason): + result = OpenAIProvider._from_openai_response( + self._response(finish_reason) + ) + self.assertEqual(result["stopReason"], expected) + + def test_tool_calls_still_map_to_tool_use(self): + tool_call = SimpleNamespace( + id="t1", + function=SimpleNamespace(name="get_connector_detail", arguments="{}"), + ) + result = OpenAIProvider._from_openai_response( + self._response("tool_calls", content=None, tool_calls=[tool_call]) + ) + + self.assertEqual(result["stopReason"], "tool_use") + + def test_an_unknown_finish_reason_still_ends_the_turn(self): + """OpenAI-compatible servers add their own values. + + An unfamiliar one is not a reason to fail a call that returned usable + content, so the previous default is kept. + """ + result = OpenAIProvider._from_openai_response(self._response("eos_token")) + + self.assertEqual(result["stopReason"], "end_turn") + + def test_truncated_with_no_content_raises_rather_than_returning_an_empty_turn(self): + with self.assertRaises(TruncatedOutputError) as caught: + OpenAIProvider._from_openai_response( + self._response("length", content=None, reasoning="thinking at length") + ) + + self.assertIn("reasoning", str(caught.exception)) + + def test_truncated_with_partial_content_is_reported_not_raised(self): + """A half-written config is still the caller's to judge. + + Only the case with nothing at all to act on is failed here, so this + change cannot turn a usable short answer into an error. + """ + result = OpenAIProvider._from_openai_response( + self._response("length", content="env {\n parallelism = 1") + ) + + self.assertEqual(result["stopReason"], "max_tokens") + self.assertEqual( + result["output"]["message"]["content"], [{"text": "env {\n parallelism = 1"}] + ) + + def test_streaming_truncation_with_no_content_raises(self): + provider = OpenAIProvider.__new__(OpenAIProvider) + provider._model_id = "reasoning-model" + provider._client = _FakeOpenAIClient( + [ + _chunk(SimpleNamespace( + content=None, tool_calls=None, model_extra={"reasoning": "..."}, + )), + _chunk(SimpleNamespace(content=None, tool_calls=None), finish_reason="length"), + ] + ) + + with self.assertRaises(TruncatedOutputError): + list(provider.chat_stream([{"role": "user", "content": [{"text": "hi"}]}])) + + def test_streaming_truncation_after_text_reports_max_tokens_without_raising(self): + provider = OpenAIProvider.__new__(OpenAIProvider) + provider._model_id = "m" + provider._client = _FakeOpenAIClient( + [ + _chunk(SimpleNamespace(content="env {", tool_calls=None)), + _chunk(SimpleNamespace(content=None, tool_calls=None), finish_reason="length"), + ] + ) + + events = list(provider.chat_stream([{"role": "user", "content": [{"text": "hi"}]}])) + + self.assertEqual(events[-1], {"type": "message_stop", "stop_reason": "max_tokens"}) + + def test_truncated_output_error_gets_an_actionable_hint(self): + message = format_llm_error( + TruncatedOutputError("The model stopped at the output token limit.") + ) + + self.assertIn("max_tokens", message) + self.assertIn("disable thinking", message) + if __name__ == "__main__": unittest.main()
