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-13152-7ce26cca72689b33e3a189ac79004dfc35be9ff8 in repository https://gitbox.apache.org/repos/asf/seatunnel.git
commit c2e900d973400d47405d0dd7e4d3081c89ac80c2 Author: SEZ <[email protected]> AuthorDate: Sat Nov 7 06:47:54 2026 +0000 [Fix][seatunnel-cli] Bound the number of clarifying questions (#13152) Co-authored-by: SEZ9 <[email protected]> --- seatunnel-cli/seatunnel_cli/agents.py | 74 +++++++--- .../test_orchestrator_clarification_rounds.py | 162 +++++++++++++++++++++ 2 files changed, 218 insertions(+), 18 deletions(-) diff --git a/seatunnel-cli/seatunnel_cli/agents.py b/seatunnel-cli/seatunnel_cli/agents.py index edc190cb752..4480af0371e 100644 --- a/seatunnel-cli/seatunnel_cli/agents.py +++ b/seatunnel-cli/seatunnel_cli/agents.py @@ -1355,6 +1355,11 @@ class Orchestrator: # enriched prompt are all built from the latest message alone. Without # this the reply replaces the requirement instead of adding to it. self._original_request: str | None = None + # Consecutive clarifying questions for the current requirement. Without + # a bound, a planner that keeps failing to resolve a pipeline and a + # caller that keeps answering loop forever, and the accumulated + # requirement grows with every round. + self._clarification_rounds: int = 0 self._connector_metadata_block: str = "" # ─── Context window management ─── @@ -1375,8 +1380,7 @@ class Orchestrator: into whatever requirement happened to be open before. """ self.conversation_history = list(history) - self.pending_question = None - self._original_request = None + self._reset_exchange() def _trimmed_history(self) -> list[dict]: """Return a context-window-friendly view of conversation_history. @@ -1458,6 +1462,49 @@ class Orchestrator: system = system + "\n\n" + block return system + # Matches the three rounds the validate/fix loop already allows, so the two + # retry budgets in this class are the same number rather than two numbers a + # reader has to remember. + MAX_CLARIFICATION_ROUNDS = 3 + + def _ask(self, question: str) -> dict: + """Record an outstanding question, or give up if we have asked enough. + + Both question exits route through here so the round count cannot be + forgotten by one of them, and so a future third exit inherits the + bound rather than reintroducing the loop. + + Giving up is a plain error rather than generating anyway: the two facts + still missing after three attempts are ones only the user has, and a + config invented without them would pass every later gate while moving + the wrong data. + """ + if self._clarification_rounds >= self.MAX_CLARIFICATION_ROUNDS: + content = ( + f"I asked {self._clarification_rounds} times and still cannot " + "work out the data flow, so I am stopping rather than guessing.\n" + "\nTo generate a config I need at least:\n" + "- the source: which system, and how to reach it " + "(host, port, database, table)\n" + "- the destination: the same again, or where the output should go\n" + ) + if question: + content += f"\nThe last thing I asked was:\n{question}\n" + self._reset_exchange() + return {"type": "error", "content": content, + "config": None, "explanation": None} + + self._clarification_rounds += 1 + self.pending_question = question + return {"type": "question", "content": question, + "config": None, "explanation": None} + + def _reset_exchange(self) -> None: + """Forget the current requirement and everything tracking it.""" + self.pending_question = None + self._original_request = None + self._clarification_rounds = 0 + def _effective_request(self, user_input: str) -> str: """The requirement as it now stands, across a clarifying question. @@ -1514,12 +1561,12 @@ class Orchestrator: plan_result = self._run_planner() if plan_result["type"] == "question": - self.pending_question = plan_result.get("content") - return plan_result + asked = self._ask(plan_result.get("content") or "") + # Preserve the planner's own fields when it is still worth asking. + return plan_result if asked["type"] == "question" else asked if plan_result["type"] == "chat": - self.pending_question = None - self._original_request = None + self._reset_exchange() self.conversation_history.append({ "role": "assistant", "content": [{"text": plan_result["content"]}], @@ -1564,17 +1611,10 @@ class Orchestrator: missing = skill.fill_and_check( effective_request, self.memory_store, self.client) if missing: - question = ( + return self._ask( "I need a few more details to generate the config:\n" + "\n".join(f"- {m}" for m in missing) ) - self.pending_question = question - return { - "type": "question", - "content": question, - "config": None, - "explanation": None, - } # Fetch metadata and build enriched prompt self._connector_metadata_block = skill.fetch_all_metadata(self.on_status) @@ -1629,8 +1669,7 @@ class Orchestrator: # The requirement has been served, so the next message starts a # new one rather than adding to this. - self.pending_question = None - self._original_request = None + self._reset_exchange() # Add assistant message to history self.conversation_history.append({ @@ -1660,8 +1699,7 @@ class Orchestrator: break # Return best effort after max rounds - self.pending_question = None - self._original_request = None + self._reset_exchange() self.conversation_history.append({ "role": "assistant", "content": [{"text": f"Here is the generated config:\n```hocon\n{config}\n```\n\n{explanation}"}], diff --git a/seatunnel-cli/tests/test_orchestrator_clarification_rounds.py b/seatunnel-cli/tests/test_orchestrator_clarification_rounds.py new file mode 100644 index 00000000000..895af2d4750 --- /dev/null +++ b/seatunnel-cli/tests/test_orchestrator_clarification_rounds.py @@ -0,0 +1,162 @@ +# +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You under the Apache License, Version 2.0 +# (the "License"); you may not use this file except in compliance with +# the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +"""Clarifying questions must not repeat forever. + +A planner that keeps failing to resolve a pipeline and a caller that keeps +answering produce an endless exchange, and because each reply is accumulated +onto the requirement, the text sent to the model grows with every round. +""" + +import unittest +from unittest import mock + +from seatunnel_cli.agents import Orchestrator + + +class RoundsAreBoundedTest(unittest.TestCase): + def setUp(self): + self.orchestrator = Orchestrator(client=mock.MagicMock()) + + def _always_asks(self): + return mock.patch.object( + self.orchestrator, "_run_planner", + return_value={"type": "question", "content": "Which database?", + "config": None, "explanation": None}, + ) + + def test_the_first_rounds_still_ask(self): + with self._always_asks(): + for _ in range(Orchestrator.MAX_CLARIFICATION_ROUNDS): + result = self.orchestrator.process_user_input("something vague") + self.assertEqual(result["type"], "question") + + def test_the_next_round_gives_up_instead_of_asking_again(self): + with self._always_asks(): + for _ in range(Orchestrator.MAX_CLARIFICATION_ROUNDS): + self.orchestrator.process_user_input("something vague") + result = self.orchestrator.process_user_input("still vague") + + self.assertEqual(result["type"], "error") + self.assertIsNone(result["config"]) + + def test_giving_up_says_what_is_actually_needed(self): + with self._always_asks(): + for _ in range(Orchestrator.MAX_CLARIFICATION_ROUNDS + 1): + result = self.orchestrator.process_user_input("vague") + + # Telling the user the two facts only they have is the whole point of + # stopping rather than generating something ungrounded. + self.assertIn("the source", result["content"]) + self.assertIn("the destination", result["content"]) + self.assertIn("Which database?", result["content"]) + + def test_giving_up_clears_the_exchange(self): + with self._always_asks(): + for _ in range(Orchestrator.MAX_CLARIFICATION_ROUNDS + 1): + self.orchestrator.process_user_input("vague") + + self.assertIsNone(self.orchestrator.pending_question) + self.assertIsNone(self.orchestrator._original_request) + self.assertEqual(self.orchestrator._clarification_rounds, 0) + + def test_the_requirement_stops_growing_once_we_give_up(self): + """Each reply is appended, so an unbounded loop grows the prompt.""" + lengths = [] + with self._always_asks(): + for _ in range(Orchestrator.MAX_CLARIFICATION_ROUNDS + 1): + self.orchestrator.process_user_input("a" * 200) + lengths.append(len(self.orchestrator._original_request or "")) + + self.assertEqual(lengths[-1], 0, "the exchange should have been reset") + self.assertLessEqual( + max(lengths), + 200 * (Orchestrator.MAX_CLARIFICATION_ROUNDS + 1) + 500, + "accumulated requirement grew beyond the round bound", + ) + + +class CounterResetsTest(unittest.TestCase): + """A served or abandoned requirement must not leave the count behind. + + Otherwise a user who needed one clarification earlier gets fewer, or none, + on their next unrelated request. + """ + + def setUp(self): + self.orchestrator = Orchestrator(client=mock.MagicMock()) + self.skill = mock.MagicMock() + self.skill.fill_and_check.return_value = [] + self.skill.fetch_all_metadata.return_value = "## Connector Option Rules\n" + self.skill.build_enriched_prompt.return_value = "## User Request:\nx" + + def _ask_once(self): + with mock.patch.object( + self.orchestrator, "_run_planner", + return_value={"type": "question", "content": "Which database?", + "config": None, "explanation": None}, + ): + self.orchestrator.process_user_input("vague") + self.assertEqual(self.orchestrator._clarification_rounds, 1) + + def test_a_delivered_config_resets_the_count(self): + self._ask_once() + + with mock.patch.object( + self.orchestrator, "_run_planner", + return_value={"type": "plan", + "content": "source: Jdbc\nsink: Console\nmode: BATCH"}, + ), mock.patch("seatunnel_cli.skills.SkillExecutor", return_value=self.skill), \ + mock.patch("seatunnel_cli.skills.SkillRouter.match", return_value=[]), \ + mock.patch.object( + self.orchestrator, "_run_config_generator", + return_value={"config": "env {}\nsource {}\nsink {}", + "explanation": ""}), \ + mock.patch.object(self.orchestrator, "_run_validator", + return_value="PASS"), \ + mock.patch("seatunnel_cli.agents.dry_run_config", + return_value={"valid": True, "phase1_local": "VALID", + "phase2_check": "PASS", "phase3_api": None, + "summary": ""}): + result = self.orchestrator.process_user_input("MySQL to console.") + + self.assertEqual(result["type"], "config") + self.assertEqual(self.orchestrator._clarification_rounds, 0) + + def test_a_chat_reply_resets_the_count(self): + self._ask_once() + + with mock.patch.object( + self.orchestrator, "_run_planner", + return_value={"type": "chat", "content": "SeaTunnel is an ETL tool."}, + ): + self.orchestrator.process_user_input("What is SeaTunnel?") + + self.assertEqual(self.orchestrator._clarification_rounds, 0) + + def test_resuming_a_session_resets_the_count(self): + self._ask_once() + + self.orchestrator.load_history([ + {"role": "user", "content": [{"text": "an earlier session"}]}, + ]) + + self.assertEqual(self.orchestrator._clarification_rounds, 0) + + +if __name__ == "__main__": + unittest.main()
