Open
【功能挑战赛】赛道二: ClarifyBudget 最小澄清(澄清预算+阻塞维度分类+假设标注) #7339
S26266Add on 5 hours ago
【功能挑战赛】赛道二: ClarifyBudget 最小澄清(澄清预算+阻塞维度分类+假设标注) #7339
Open
Total: 5 files changed+455-32
| @@ -57,6 +57,10 @@ class Settings(BaseSettings): | |||
| 57 | workflow_max_concurrency: int = 3 # 最大并行数 | 57 | workflow_max_concurrency: int = 3 # 最大并行数 |
| 58 | workflow_checkpoint_dir: str = "" # Checkpoint 目录,为空则用 ~/.mofix/workflows | 58 | workflow_checkpoint_dir: str = "" # Checkpoint 目录,为空则用 ~/.mofix/workflows |
| 59 | workflow_verify_enabled: bool = True # 默认启用验证步骤 | 59 | workflow_verify_enabled: bool = True # 默认启用验证步骤 |
| 60 | + # ClarifyBudget(最小澄清):/workflow 模糊度阈值(超过才触发澄清)与最大澄清轮数 | ||
| 61 | + # (超限后未澄清的非阻塞维度按默认假设推进并标注 assumptions,不再无限追问) | ||
| 62 | + workflow_clarify_ambiguity_threshold: float = 0.45 | ||
| 63 | + workflow_clarify_max_rounds: int = 3 | ||
| 60 | workflow_mcp_tool_timeout_seconds: int = Field(default=6 * 3600, gt=0) | 64 | workflow_mcp_tool_timeout_seconds: int = Field(default=6 * 3600, gt=0) |
| 61 | workflow_claude_skill_timeout_seconds: int = Field(default=6 * 3600, gt=0) | 65 | workflow_claude_skill_timeout_seconds: int = Field(default=6 * 3600, gt=0) |
| 62 | workflow_skill_timeout_seconds: float = Field(default=6 * 3600.0, gt=0) | 66 | workflow_skill_timeout_seconds: float = Field(default=6 * 3600.0, gt=0) |
| @@ -2646,7 +2646,8 @@ async def _chat_completions_stream_impl( | |||
| 2646 | 2646 | ||
| 2647 | from app.tools.workflow.brainstorming import assess_ambiguity | 2647 | from app.tools.workflow.brainstorming import assess_ambiguity |
| 2648 | score, missing_dimensions = await assess_ambiguity(args) | 2648 | score, missing_dimensions = await assess_ambiguity(args) |
| 2649 | - if score > 0.45 and missing_dimensions: | 2649 | + # ClarifyBudget:模糊度阈值与最大轮数均配置化(默认 0.45 / 3 轮,行为不变) |
| 2650 | + if score > settings.workflow_clarify_ambiguity_threshold and missing_dimensions: | ||
| 2650 | if trace_collector: | 2651 | if trace_collector: |
| 2651 | trace_collector.on_command_dispatch("workflow", args) | 2652 | trace_collector.on_command_dispatch("workflow", args) |
| 2652 | session = BrainstormingSession(session_id=request.c_id) | 2653 | session = BrainstormingSession(session_id=request.c_id) |
| @@ -47,6 +47,13 @@ from app.services.chat_selection import ( | |||
| 47 | match_option_text, | 47 | match_option_text, |
| 48 | parse_selection_number, | 48 | parse_selection_number, |
| 49 | ) | 49 | ) |
| 50 | +from app.tools.workflow.clarify_budget import ( | ||
| 51 | + ClarifyAction, | ||
| 52 | + assumptions_notice, | ||
| 53 | + build_assumptions, | ||
| 54 | + classify_pending, | ||
| 55 | + decide_action, | ||
| 56 | +) | ||
| 50 | 57 | ||
| 51 | 58 | ||
| 52 | # ── 状态枚举 ─────────────────────────────────────────────────────────── | 59 | # ── 状态枚举 ─────────────────────────────────────────────────────────── |
| @@ -338,10 +345,15 @@ class BrainstormingSession: | |||
| 338 | self, | 345 | self, |
| 339 | session_id: str | None = None, | 346 | session_id: str | None = None, |
| 340 | llm=None, | 347 | llm=None, |
| 348 | + max_rounds: int | None = None, | ||
| 341 | ): | 349 | ): |
| 342 | self.session_id = session_id or f"bs-{uuid.uuid4().hex[:12]}" | 350 | self.session_id = session_id or f"bs-{uuid.uuid4().hex[:12]}" |
| 343 | self.state = BrainstormState.INITIAL | 351 | self.state = BrainstormState.INITIAL |
| 344 | self.llm = llm or build_workflow_llm() | 352 | self.llm = llm or build_workflow_llm() |
| 353 | + # ClarifyBudget:澄清预算(None 时读配置,默认 3 轮) | ||
| 354 | + self.max_rounds = max_rounds if max_rounds is not None else settings.workflow_clarify_max_rounds | ||
| 355 | + # 超预算后置位:预算已尽,LLM 再回 question 一律降级出方案,不再追问 | ||
| 356 | + self._budget_exhausted = False | ||
| 345 | 357 | ||
| 346 | # 用户输入 | 358 | # 用户输入 |
| 347 | self.user_input: str = "" | 359 | self.user_input: str = "" |
| @@ -349,6 +361,9 @@ class BrainstormingSession: | |||
| 349 | # 已澄清的维度 | 361 | # 已澄清的维度 |
| 350 | self.clarified_dimensions: dict[str, str] = {} | 362 | self.clarified_dimensions: dict[str, str] = {} |
| 351 | 363 | ||
| 364 | + # 超预算推进时记录的默认假设(assumptions) | ||
| 365 | + self.assumptions: dict[str, str] = {} | ||
| 366 | + | ||
| 352 | # 已问过的问题(去重) | 367 | # 已问过的问题(去重) |
| 353 | self.questions_asked: list[str] = [] | 368 | self.questions_asked: list[str] = [] |
| 354 | 369 | ||
| @@ -546,6 +561,8 @@ class BrainstormingSession: | |||
| 546 | "user_input": self.user_input, | 561 | "user_input": self.user_input, |
| 547 | "clarified_dimensions": dict(self.clarified_dimensions), | 562 | "clarified_dimensions": dict(self.clarified_dimensions), |
| 548 | "questions_asked": list(self.questions_asked), | 563 | "questions_asked": list(self.questions_asked), |
| 564 | + "assumptions": dict(self.assumptions), | ||
| 565 | + "max_rounds": self.max_rounds, | ||
| 549 | "proposals": [p.model_dump() for p in self.proposals], | 566 | "proposals": [p.model_dump() for p in self.proposals], |
| 550 | "selected_proposal_index": self.selected_proposal_index, | 567 | "selected_proposal_index": self.selected_proposal_index, |
| 551 | "design_doc": self.design_doc.model_dump() if self.design_doc else None, | 568 | "design_doc": self.design_doc.model_dump() if self.design_doc else None, |
| @@ -560,6 +577,8 @@ class BrainstormingSession: | |||
| 560 | session.user_input = data.get("user_input", "") | 577 | session.user_input = data.get("user_input", "") |
| 561 | session.clarified_dimensions = data.get("clarified_dimensions", {}) | 578 | session.clarified_dimensions = data.get("clarified_dimensions", {}) |
| 562 | session.questions_asked = data.get("questions_asked", []) | 579 | session.questions_asked = data.get("questions_asked", []) |
| 580 | + session.assumptions = dict(data.get("assumptions", {})) | ||
| 581 | + session.max_rounds = data.get("max_rounds") or settings.workflow_clarify_max_rounds | ||
| 563 | session.proposals = [BrainstormProposal(**p) for p in data.get("proposals", [])] | 582 | session.proposals = [BrainstormProposal(**p) for p in data.get("proposals", [])] |
| 564 | session.selected_proposal_index = data.get("selected_proposal_index") | 583 | session.selected_proposal_index = data.get("selected_proposal_index") |
| 565 | if data.get("design_doc"): | 584 | if data.get("design_doc"): |
| @@ -577,6 +596,9 @@ class BrainstormingSession: | |||
| 577 | 596 | ||
| 578 | pending = self._identify_pending_dimensions() | 597 | pending = self._identify_pending_dimensions() |
| 579 | 598 | ||
| 599 | + # ClarifyBudget:超预算推进时把假设显式告知 LLM(可随时被用户修正) | ||
| 600 | + assumption_block = assumptions_notice(self.assumptions) if self.assumptions else "" | ||
| 601 | + | ||
| 580 | # 优先级规则:用户提到了模型系列(如 Qwen)但没有具体版本号 → 优先澄清 model_name | 602 | # 优先级规则:用户提到了模型系列(如 Qwen)但没有具体版本号 → 优先澄清 model_name |
| 581 | priority_rule = "" | 603 | priority_rule = "" |
| 582 | lower_input = self.user_input.lower() | 604 | lower_input = self.user_input.lower() |
| @@ -599,6 +621,7 @@ class BrainstormingSession: | |||
| 599 | 621 | ||
| 600 | **当前状态**: {self.state.value} | 622 | **当前状态**: {self.state.value} |
| 601 | **已问问题数**: {len(self.questions_asked)}{priority_rule} | 623 | **已问问题数**: {len(self.questions_asked)}{priority_rule} |
| 624 | +{assumption_block} | ||
| 602 | """ | 625 | """ |
| 603 | 626 | ||
| 604 | messages = [{"role": "system", "content": system}] | 627 | messages = [{"role": "system", "content": system}] |
| @@ -625,6 +648,15 @@ class BrainstormingSession: | |||
| 625 | pending = [d for d in all_dimensions if d not in self.clarified_dimensions] | 648 | pending = [d for d in all_dimensions if d not in self.clarified_dimensions] |
| 626 | return "\n".join(f"- {d}" for d in pending) if pending else "(全部维度已澄清)" | 649 | return "\n".join(f"- {d}" for d in pending) if pending else "(全部维度已澄清)" |
| 627 | 650 | ||
| 651 | + def _pending_dimension_list(self) -> list[str]: | ||
| 652 | + """待澄清维度名列表(ClarifyBudget 据此区分阻塞/非阻塞维度)。""" | ||
| 653 | + dims: list[str] = [] | ||
| 654 | + for line in self._identify_pending_dimensions().splitlines(): | ||
| 655 | + dim = line.strip().lstrip("- ").strip() | ||
| 656 | + if dim and not dim.startswith("("): | ||
| 657 | + dims.append(dim) | ||
| 658 | + return dims | ||
| 659 | + | ||
| 628 | def _call_llm(self) -> dict: | 660 | def _call_llm(self) -> dict: |
| 629 | """调用 LLM 获取下一步响应。""" | 661 | """调用 LLM 获取下一步响应。""" |
| 630 | messages = self._build_llm_messages() | 662 | messages = self._build_llm_messages() |
| @@ -660,37 +692,38 @@ class BrainstormingSession: | |||
| 660 | 692 | ||
| 661 | def _fallback_response(self) -> dict: | 693 | def _fallback_response(self) -> dict: |
| 662 | """LLM 调用失败时的降级响应。""" | 694 | """LLM 调用失败时的降级响应。""" |
| 663 | - if self.state == BrainstormState.INITIAL: | 695 | + if self.state in (BrainstormState.INITIAL, BrainstormState.CLARIFYING): |
| 664 | - return { | 696 | + if self.state == BrainstormState.INITIAL: |
| 665 | - "type": "question", | 697 | + return { |
| 666 | - "question": { | 698 | + "type": "question", |
| 667 | - "text": "请提供需要处理的模型信息?(例如 ModelScope 链接或模型名称)", | 699 | + "question": { |
| 668 | - "options": ["提供 ModelScope 链接", "提供 HuggingFace 链接", "手动指定模型名称和规模"], | 700 | + "text": "请提供需要处理的模型信息?(例如 ModelScope 链接或模型名称)", |
| 669 | - "dimension": "model_name", | 701 | + "options": ["提供 ModelScope 链接", "提供 HuggingFace 链接", "手动指定模型名称和规模"], |
| 670 | - }, | 702 | + "dimension": "model_name", |
| 671 | - "assessment": "clarify_needed", | 703 | + }, |
| 672 | - } | 704 | + "assessment": "clarify_needed", |
| 673 | - if "model_name" not in self.clarified_dimensions: | 705 | + } |
| 674 | - return { | 706 | + if "model_name" not in self.clarified_dimensions: |
| 675 | - "type": "question", | 707 | + return { |
| 676 | - "question": { | 708 | + "type": "question", |
| 677 | - "text": "需要处理哪个模型?", | 709 | + "question": { |
| 678 | - "options": ["Qwen3-8B", "Qwen3-14B", "DeepSeek-V3", "DeepSeek-R1"], | 710 | + "text": "需要处理哪个模型?", |
| 679 | - "dimension": "model_name", | 711 | + "options": ["Qwen3-8B", "Qwen3-14B", "DeepSeek-V3", "DeepSeek-R1"], |
| 680 | - }, | 712 | + "dimension": "model_name", |
| 681 | - "assessment": "clarify_needed", | 713 | + }, |
| 682 | - } | 714 | + "assessment": "clarify_needed", |
| 683 | - if "model_name" in self.clarified_dimensions and "inference_framework" not in self.clarified_dimensions: | 715 | + } |
| 684 | - return { | 716 | + if "model_name" in self.clarified_dimensions and "inference_framework" not in self.clarified_dimensions: |
| 685 | - "type": "question", | 717 | + return { |
| 686 | - "question": { | 718 | + "type": "question", |
| 687 | - "text": "使用哪个推理框架?", | 719 | + "question": { |
| 688 | - "options": ["vLLM-Ascend", "SGLang", "MindIE", "LMDeploy"], | 720 | + "text": "使用哪个推理框架?", |
| 689 | - "dimension": "inference_framework", | 721 | + "options": ["vLLM-Ascend", "SGLang", "MindIE", "LMDeploy"], |
| 690 | - }, | 722 | + "dimension": "inference_framework", |
| 691 | - "assessment": "clarify_needed", | 723 | + }, |
| 692 | - } | 724 | + "assessment": "clarify_needed", |
| 693 | - # 降级到方案 | 725 | + } |
| 726 | + # PROPOSING(含 ClarifyBudget 超预算降级):直接出方案,不再追问 | ||
| 694 | return { | 727 | return { |
| 695 | "type": "proposals", | 728 | "type": "proposals", |
| 696 | "proposals": [ | 729 | "proposals": [ |
| @@ -719,6 +752,18 @@ class BrainstormingSession: | |||
| 719 | 752 | ||
| 720 | # --- question --- | 753 | # --- question --- |
| 721 | if response_type == "question": | 754 | if response_type == "question": |
| 755 | + # ClarifyBudget:预算已尽 → 不再追问,降级出方案(防澄清死循环) | ||
| 756 | + if self._budget_exhausted: | ||
| 757 | + return self._fallback_response() | ||
| 758 | + pending_blocking, pending_non_blocking = classify_pending( | ||
| 759 | + self._pending_dimension_list() | ||
| 760 | + ) | ||
| 761 | + if decide_action( | ||
| 762 | + rounds_used=len(self.questions_asked), | ||
| 763 | + max_rounds=self.max_rounds, | ||
| 764 | + pending_blocking=pending_blocking, | ||
| 765 | + ) == ClarifyAction.PROCEED_WITH_ASSUMPTIONS: | ||
| 766 | + return self._proceed_with_assumptions(pending_non_blocking) | ||
| 722 | self.state = BrainstormState.CLARIFYING | 767 | self.state = BrainstormState.CLARIFYING |
| 723 | q_data = response.get("question", {}) | 768 | q_data = response.get("question", {}) |
| 724 | q = BrainstormQuestion( | 769 | q = BrainstormQuestion( |
| @@ -785,6 +830,25 @@ class BrainstormingSession: | |||
| 785 | options=["继续", "重新开始", "结束"], | 830 | options=["继续", "重新开始", "结束"], |
| 786 | )} | 831 | )} |
| 787 | 832 | ||
| 833 | + def _proceed_with_assumptions(self, pending_non_blocking: list[str]) -> dict: | ||
| 834 | + """澄清预算耗尽:未澄清的非阻塞维度按默认假设推进,显式标注后出方案。""" | ||
| 835 | + new_assumptions = build_assumptions(pending_non_blocking) | ||
| 836 | + self.assumptions.update(new_assumptions) | ||
| 837 | + self._budget_exhausted = True | ||
| 838 | + self.state = BrainstormState.PROPOSING | ||
| 839 | + self.history.append({ | ||
| 840 | + "role": "assistant", | ||
| 841 | + "type": "auto_assumption", | ||
| 842 | + "content": assumptions_notice(self.assumptions), | ||
| 843 | + "data": {"assumptions": dict(self.assumptions)}, | ||
| 844 | + }) | ||
| 845 | + # 让 LLM 基于已有信息 + 假设直接出方案(不再追问) | ||
| 846 | + response = self._call_llm() | ||
| 847 | + result = self._process_llm_response(response) | ||
| 848 | + # LLM 仍回 question:因 _budget_exhausted 已置位,_process_llm_response | ||
| 849 | + # 会降级到 _fallback_response 出方案(state 已 PROPOSING → 走 proposals 分支),不会递归追问。 | ||
| 850 | + return result | ||
| 851 | + | ||
| 788 | def _handle_proposal_selection(self, index: int) -> dict: | 852 | def _handle_proposal_selection(self, index: int) -> dict: |
| 789 | """用户选择了第 *index* 个方案,生成设计文档。""" | 853 | """用户选择了第 *index* 个方案,生成设计文档。""" |
| 790 | if index < 0 or index >= len(self.proposals): | 854 | if index < 0 or index >= len(self.proposals): |
| @@ -835,6 +899,9 @@ class BrainstormingSession: | |||
| 835 | "user_input": self.user_input, | 899 | "user_input": self.user_input, |
| 836 | "dimensions": dict(self.clarified_dimensions), | 900 | "dimensions": dict(self.clarified_dimensions), |
| 837 | } | 901 | } |
| 902 | + if self.assumptions: | ||
| 903 | + # ClarifyBudget:超预算推进的假设随上下文传给规划器(显式标注) | ||
| 904 | + context["assumptions"] = dict(self.assumptions) | ||
| 838 | if self.design_doc: | 905 | if self.design_doc: |
| 839 | context["design_doc"] = self.design_doc.model_dump() | 906 | context["design_doc"] = self.design_doc.model_dump() |
| 840 | if self.selected_proposal_index is not None: | 907 | if self.selected_proposal_index is not None: |
| @@ -0,0 +1,115 @@ | |||
| 1 | +"""ClarifyBudget — 澄清预算决策(最小澄清)。 | ||
| 2 | + | ||
| 3 | +核心思想:澄清是有预算的。 | ||
| 4 | + | ||
| 5 | +- 只问会改变计划的「阻塞维度」:模型、推理框架、优化目标缺失会直接改变 | ||
| 6 | + 工作流计划,必须澄清;量化、精度要求、使用场景等维度缺失时用默认假设 | ||
| 7 | + 推进即可,问了也不会改变计划结构。 | ||
| 8 | +- 每轮 1 问、最多 N 轮(默认 3,可配置)。 | ||
| 9 | +- 超预算后:未澄清的非阻塞维度按默认假设推进,并在会话上下文/历史里 | ||
| 10 | + 显式标注 assumptions,不再无限追问(避免澄清死循环拖垮交互体验)。 | ||
| 11 | + | ||
| 12 | +本模块为纯决策函数,不依赖 LLM / IO,全部 CPU 可测。 | ||
| 13 | +""" | ||
| 14 | + | ||
| 15 | +from __future__ import annotations | ||
| 16 | + | ||
| 17 | +from enum import Enum | ||
| 18 | + | ||
| 19 | + | ||
| 20 | +# ── 维度分类 ────────────────────────────────────────────────────────── | ||
| 21 | + | ||
| 22 | +# 阻塞维度:缺失会直接改变工作流计划(选模型/框架/目标不同 → 计划不同),必须澄清。 | ||
| 23 | +BLOCKING_DIMENSIONS: tuple[str, ...] = ( | ||
| 24 | + "model_name", | ||
| 25 | + "inference_framework", | ||
| 26 | + "optimization_goal", | ||
| 27 | +) | ||
| 28 | + | ||
| 29 | +# 非阻塞维度:缺失时用默认假设推进即可(默认值不改变计划结构)。 | ||
| 30 | +NON_BLOCKING_DEFAULT_ASSUMPTIONS: dict[str, str] = { | ||
| 31 | + "quantization": "按模型默认精度(不额外量化)", | ||
| 32 | + "accuracy_requirement": "以官方基线精度为准(不额外加严)", | ||
| 33 | + "use_case": "在线推理", | ||
| 34 | +} | ||
| 35 | + | ||
| 36 | +# 兜底:未知维度一律按非阻塞处理(宁可带假设推进,不无限追问)。 | ||
| 37 | +DEFAULT_ASSUMPTION = "未澄清,按默认假设推进" | ||
| 38 | + | ||
| 39 | + | ||
| 40 | +def classify_pending(pending: list[str]) -> tuple[list[str], list[str]]: | ||
| 41 | + """把待澄清维度分为 (阻塞维度, 非阻塞维度)。 | ||
| 42 | + | ||
| 43 | + Args: | ||
| 44 | + pending: 尚未澄清的维度名列表。 | ||
| 45 | + | ||
| 46 | + Returns: | ||
| 47 | + ``(blocking, non_blocking)``——保持输入顺序、去重。 | ||
| 48 | + """ | ||
| 49 | + seen: set[str] = set() | ||
| 50 | + blocking: list[str] = [] | ||
| 51 | + non_blocking: list[str] = [] | ||
| 52 | + for dim in pending or []: | ||
| 53 | + if not dim or dim in seen: | ||
| 54 | + continue | ||
| 55 | + seen.add(dim) | ||
| 56 | + if dim in BLOCKING_DIMENSIONS: | ||
| 57 | + blocking.append(dim) | ||
| 58 | + else: | ||
| 59 | + non_blocking.append(dim) | ||
| 60 | + return blocking, non_blocking | ||
| 61 | + | ||
| 62 | + | ||
| 63 | +# ── 预算决策 ────────────────────────────────────────────────────────── | ||
| 64 | + | ||
| 65 | + | ||
| 66 | +class ClarifyAction(str, Enum): | ||
| 67 | + """澄清预算决策结果。""" | ||
| 68 | + | ||
| 69 | + ASK = "ask" # 预算内且仍有阻塞维度 → 继续问 | ||
| 70 | + PROCEED_WITH_ASSUMPTIONS = "proceed" # 预算耗尽或无阻塞维度 → 带假设推进 | ||
| 71 | + | ||
| 72 | + | ||
| 73 | +def decide_action( | ||
| 74 | + *, | ||
| 75 | + rounds_used: int, | ||
| 76 | + max_rounds: int, | ||
| 77 | + pending_blocking: list[str], | ||
| 78 | +) -> ClarifyAction: | ||
| 79 | + """决定下一轮是继续提问还是带假设直接推进。 | ||
| 80 | + | ||
| 81 | + Args: | ||
| 82 | + rounds_used: 已问过的问题轮数。 | ||
| 83 | + max_rounds: 澄清预算上限(<=0 视为 1,至少给一轮提问机会)。 | ||
| 84 | + pending_blocking: 仍未澄清的阻塞维度。 | ||
| 85 | + | ||
| 86 | + Returns: | ||
| 87 | + ``ClarifyAction.ASK`` 或 ``ClarifyAction.PROCEED_WITH_ASSUMPTIONS``。 | ||
| 88 | + """ | ||
| 89 | + budget = max(int(max_rounds), 1) if max_rounds is not None else 1 | ||
| 90 | + if rounds_used >= budget: | ||
| 91 | + return ClarifyAction.PROCEED_WITH_ASSUMPTIONS | ||
| 92 | + if not pending_blocking: | ||
| 93 | + return ClarifyAction.PROCEED_WITH_ASSUMPTIONS | ||
| 94 | + return ClarifyAction.ASK | ||
| 95 | + | ||
| 96 | + | ||
| 97 | +def build_assumptions(pending_non_blocking: list[str]) -> dict[str, str]: | ||
| 98 | + """为非阻塞维度生成默认假设。""" | ||
| 99 | + assumptions: dict[str, str] = {} | ||
| 100 | + for dim in pending_non_blocking or []: | ||
| 101 | + if dim in NON_BLOCKING_DEFAULT_ASSUMPTIONS: | ||
| 102 | + assumptions[dim] = NON_BLOCKING_DEFAULT_ASSUMPTIONS[dim] | ||
| 103 | + else: | ||
| 104 | + assumptions[dim] = DEFAULT_ASSUMPTION | ||
| 105 | + return assumptions | ||
| 106 | + | ||
| 107 | + | ||
| 108 | +def assumptions_notice(assumptions: dict[str, str]) -> str: | ||
| 109 | + """生成给 LLM/用户的假设标注文案(超预算推进时显式声明)。""" | ||
| 110 | + if not assumptions: | ||
| 111 | + return "" | ||
| 112 | + items = "\n".join(f"- {k}:{v}" for k, v in assumptions.items()) | ||
| 113 | + return ( | ||
| 114 | + "**澄清预算已用尽,以下维度按默认假设推进**(用户可随时修正):\n" + items | ||
| 115 | + ) | ||
| @@ -0,0 +1,236 @@ | |||
| 1 | +"""Test ClarifyBudget — 澄清预算决策与 BrainstormingSession 集成。""" | ||
| 2 | + | ||
| 3 | +from __future__ import annotations | ||
| 4 | + | ||
| 5 | +from unittest.mock import MagicMock | ||
| 6 | + | ||
| 7 | +import pytest | ||
| 8 | + | ||
| 9 | +from app.config import settings | ||
| 10 | +from app.tools.workflow.brainstorming import ( | ||
| 11 | + BrainstormState, | ||
| 12 | + BrainstormingSession, | ||
| 13 | +) | ||
| 14 | +from app.tools.workflow.clarify_budget import ( | ||
| 15 | + ClarifyAction, | ||
| 16 | + assumptions_notice, | ||
| 17 | + build_assumptions, | ||
| 18 | + classify_pending, | ||
| 19 | + decide_action, | ||
| 20 | +) | ||
| 21 | + | ||
| 22 | + | ||
| 23 | +class TestClassifyPending: | ||
| 24 | + def test_blocking_vs_non_blocking(self): | ||
| 25 | + blocking, non_blocking = classify_pending( | ||
| 26 | + ["model_name", "quantization", "optimization_goal", "use_case"] | ||
| 27 | + ) | ||
| 28 | + assert blocking == ["model_name", "optimization_goal"] | ||
| 29 | + assert non_blocking == ["quantization", "use_case"] | ||
| 30 | + | ||
| 31 | + def test_all_blocking(self): | ||
| 32 | + blocking, non_blocking = classify_pending( | ||
| 33 | + ["model_name", "inference_framework", "optimization_goal"] | ||
| 34 | + ) | ||
| 35 | + assert blocking == ["model_name", "inference_framework", "optimization_goal"] | ||
| 36 | + assert non_blocking == [] | ||
| 37 | + | ||
| 38 | + def test_all_non_blocking(self): | ||
| 39 | + blocking, non_blocking = classify_pending(["quantization", "accuracy_requirement"]) | ||
| 40 | + assert blocking == [] | ||
| 41 | + assert non_blocking == ["quantization", "accuracy_requirement"] | ||
| 42 | + | ||
| 43 | + def test_unknown_dimension_is_non_blocking(self): | ||
| 44 | + """未知维度按非阻塞处理(宁可带假设推进,不无限追问)。""" | ||
| 45 | + blocking, non_blocking = classify_pending(["some_future_dimension"]) | ||
| 46 | + assert blocking == [] | ||
| 47 | + assert non_blocking == ["some_future_dimension"] | ||
| 48 | + | ||
| 49 | + def test_empty_and_dedup(self): | ||
| 50 | + blocking, non_blocking = classify_pending([None, "", "model_name", "model_name"]) | ||
| 51 | + assert blocking == ["model_name"] | ||
| 52 | + assert non_blocking == [] | ||
| 53 | + | ||
| 54 | + | ||
| 55 | +class TestDecideAction: | ||
| 56 | + def test_ask_when_budget_left_and_blocking_pending(self): | ||
| 57 | + assert decide_action( | ||
| 58 | + rounds_used=1, max_rounds=3, pending_blocking=["model_name"] | ||
| 59 | + ) == ClarifyAction.ASK | ||
| 60 | + | ||
| 61 | + def test_proceed_when_budget_exhausted(self): | ||
| 62 | + """超预算:即使仍有阻塞维度也带假设推进(核心:不再无限追问)。""" | ||
| 63 | + assert decide_action( | ||
| 64 | + rounds_used=3, max_rounds=3, pending_blocking=["model_name"] | ||
| 65 | + ) == ClarifyAction.PROCEED_WITH_ASSUMPTIONS | ||
| 66 | + | ||
| 67 | + def test_proceed_when_no_blocking_pending(self): | ||
| 68 | + """无阻塞维度:非阻塞维度走假设,不值得再问。""" | ||
| 69 | + assert decide_action( | ||
| 70 | + rounds_used=0, max_rounds=3, pending_blocking=[] | ||
| 71 | + ) == ClarifyAction.PROCEED_WITH_ASSUMPTIONS | ||
| 72 | + | ||
| 73 | + def test_max_rounds_zero_gives_at_least_one_round(self): | ||
| 74 | + assert decide_action( | ||
| 75 | + rounds_used=0, max_rounds=0, pending_blocking=["model_name"] | ||
| 76 | + ) == ClarifyAction.ASK | ||
| 77 | + assert decide_action( | ||
| 78 | + rounds_used=1, max_rounds=0, pending_blocking=["model_name"] | ||
| 79 | + ) == ClarifyAction.PROCEED_WITH_ASSUMPTIONS | ||
| 80 | + | ||
| 81 | + def test_negative_rounds_used_treated_as_zero(self): | ||
| 82 | + assert decide_action( | ||
| 83 | + rounds_used=-2, max_rounds=3, pending_blocking=["model_name"] | ||
| 84 | + ) == ClarifyAction.ASK | ||
| 85 | + | ||
| 86 | + | ||
| 87 | +class TestBuildAssumptions: | ||
| 88 | + def test_known_non_blocking_dimensions(self): | ||
| 89 | + assumptions = build_assumptions(["quantization", "use_case"]) | ||
| 90 | + assert assumptions["quantization"] == "按模型默认精度(不额外量化)" | ||
| 91 | + assert assumptions["use_case"] == "在线推理" | ||
| 92 | + | ||
| 93 | + def test_unknown_dimension_gets_default(self): | ||
| 94 | + assumptions = build_assumptions(["some_future_dimension"]) | ||
| 95 | + assert assumptions["some_future_dimension"] == "未澄清,按默认假设推进" | ||
| 96 | + | ||
| 97 | + def test_empty(self): | ||
| 98 | + assert build_assumptions([]) == {} | ||
| 99 | + | ||
| 100 | + | ||
| 101 | +class TestAssumptionsNotice: | ||
| 102 | + def test_lists_assumptions(self): | ||
| 103 | + notice = assumptions_notice({"quantization": "按模型默认精度(不额外量化)"}) | ||
| 104 | + assert "澄清预算已用尽" in notice | ||
| 105 | + assert "quantization" in notice | ||
| 106 | + | ||
| 107 | + def test_empty_returns_blank(self): | ||
| 108 | + assert assumptions_notice({}) == "" | ||
| 109 | + | ||
| 110 | + | ||
| 111 | +class TestSessionClarifyBudget: | ||
| 112 | + @staticmethod | ||
| 113 | + def _question_response(dimension: str = "model_name") -> dict: | ||
| 114 | + return { | ||
| 115 | + "type": "question", | ||
| 116 | + "question": {"text": f"which {dimension}?", "options": ["A", "B"], "dimension": dimension}, | ||
| 117 | + "assessment": "clarify_needed", | ||
| 118 | + } | ||
| 119 | + | ||
| 120 | + def test_max_rounds_defaults_from_settings(self): | ||
| 121 | + session = BrainstormingSession(llm=MagicMock()) | ||
| 122 | + assert session.max_rounds == settings.workflow_clarify_max_rounds | ||
| 123 | + assert session.max_rounds == 3 | ||
| 124 | + assert session.assumptions == {} | ||
| 125 | + | ||
| 126 | + def test_explicit_max_rounds(self): | ||
| 127 | + session = BrainstormingSession(llm=MagicMock(), max_rounds=1) | ||
| 128 | + assert session.max_rounds == 1 | ||
| 129 | + | ||
| 130 | + def test_budget_exhausted_proceeds_with_assumptions(self, monkeypatch): | ||
| 131 | + """max_rounds=2:第 3 轮不再问(阻塞维度仍缺),带假设直接进 PROPOSING。""" | ||
| 132 | + session = BrainstormingSession(llm=MagicMock(), max_rounds=2) | ||
| 133 | + session.user_input = "帮我适配一个模型" | ||
| 134 | + | ||
| 135 | + def fake_llm(self): | ||
| 136 | + if "model_name" not in self.clarified_dimensions: | ||
| 137 | + return TestSessionClarifyBudget._question_response("model_name") | ||
| 138 | + if "inference_framework" not in self.clarified_dimensions: | ||
| 139 | + return TestSessionClarifyBudget._question_response("inference_framework") | ||
| 140 | + return TestSessionClarifyBudget._question_response("optimization_goal") | ||
| 141 | + | ||
| 142 | + monkeypatch.setattr(type(session), "_call_llm", fake_llm) | ||
| 143 | + | ||
| 144 | + session.start("帮我适配一个模型") | ||
| 145 | + assert session.state == BrainstormState.CLARIFYING | ||
| 146 | + assert len(session.questions_asked) == 1 # start 问过 model_name | ||
| 147 | + session.answer("q1", "Qwen3-8B") # 第 1 轮回答:预算内继续问 inference_framework | ||
| 148 | + assert session.state == BrainstormState.CLARIFYING | ||
| 149 | + assert len(session.questions_asked) == 2 | ||
| 150 | + | ||
| 151 | + # 第 3 轮:预算已尽(rounds_used=2 >= max_rounds=2)→ 不再问, | ||
| 152 | + # quantization 等非阻塞维度按假设推进进 PROPOSING | ||
| 153 | + responses = iter([ | ||
| 154 | + TestSessionClarifyBudget._question_response("optimization_goal"), # LLM 仍想问 → 被预算拦截 | ||
| 155 | + {"type": "proposals", "proposals": [{"title": "标准流程", "description": "d"}], "assessment": "ready_for_proposals"}, | ||
| 156 | + ]) | ||
| 157 | + monkeypatch.setattr(type(session), "_call_llm", lambda self: next(responses)) | ||
| 158 | + result = session.answer("q2", "vLLM-Ascend") | ||
| 159 | + assert result["type"] == "proposals" | ||
| 160 | + assert session.state == BrainstormState.PROPOSING | ||
| 161 | + assert len(session.questions_asked) == 2 # 预算外不再新增问题 | ||
| 162 | + assert session.assumptions.get("quantization") == "按模型默认精度(不额外量化)" | ||
| 163 | + assert session.assumptions.get("accuracy_requirement") == "以官方基线精度为准(不额外加严)" | ||
| 164 | + assert session.assumptions.get("use_case") == "在线推理" | ||
| 165 | + assert any(h.get("type") == "auto_assumption" for h in session.history) | ||
| 166 | + | ||
| 167 | + def test_no_blocking_dimension_proceeds_immediately(self, monkeypatch): | ||
| 168 | + """只缺非阻塞维度(quantization)→ LLM 想问也不问,带假设直接进 PROPOSING。""" | ||
| 169 | + session = BrainstormingSession(llm=MagicMock(), max_rounds=3) | ||
| 170 | + session.clarified_dimensions = { | ||
| 171 | + "model_name": "Qwen3-8B", | ||
| 172 | + "inference_framework": "vLLM-Ascend", | ||
| 173 | + "optimization_goal": "吞吐量", | ||
| 174 | + } | ||
| 175 | + session.state = BrainstormState.CLARIFYING | ||
| 176 | + responses = iter([ | ||
| 177 | + TestSessionClarifyBudget._question_response("quantization"), # LLM 想问量化 | ||
| 178 | + {"type": "proposals", "proposals": [{"title": "P1", "description": "d"}], "assessment": "ready_for_proposals"}, | ||
| 179 | + ]) | ||
| 180 | + monkeypatch.setattr(type(session), "_call_llm", lambda self: next(responses)) | ||
| 181 | + result = session.answer("q1", "量化吗?") | ||
| 182 | + assert result["type"] == "proposals" | ||
| 183 | + assert len(session.questions_asked) == 0 | ||
| 184 | + assert session.assumptions.get("quantization") == "按模型默认精度(不额外量化)" | ||
| 185 | + | ||
| 186 | + def test_budget_exhausted_llm_question_falls_back_not_recurses(self, monkeypatch): | ||
| 187 | + """预算已尽且 LLM 仍回 question → 降级 fallback 出方案,不递归追问。""" | ||
| 188 | + session = BrainstormingSession(llm=MagicMock(), max_rounds=1) | ||
| 189 | + session.user_input = "帮我适配一个模型" | ||
| 190 | + monkeypatch.setattr(type(session), "_call_llm", lambda self: TestSessionClarifyBudget._question_response()) | ||
| 191 | + session.start("帮我适配一个模型") | ||
| 192 | + assert len(session.questions_asked) == 1 | ||
| 193 | + assert session._budget_exhausted is False | ||
| 194 | + # 预算已尽:再触发 question 处理 → fallback proposals | ||
| 195 | + result = session._process_llm_response(TestSessionClarifyBudget._question_response()) | ||
| 196 | + assert result["type"] == "proposals" | ||
| 197 | + assert session.state == BrainstormState.PROPOSING | ||
| 198 | + assert len(session.questions_asked) == 1 # 没有新增问题 | ||
| 199 | + | ||
| 200 | + def test_assumptions_in_context_and_messages(self, monkeypatch): | ||
| 201 | + session = BrainstormingSession(llm=MagicMock(), max_rounds=1) | ||
| 202 | + session.user_input = "帮我适配一个模型" | ||
| 203 | + responses = iter([ | ||
| 204 | + TestSessionClarifyBudget._question_response("model_name"), # 第 1 轮:预算内照问 | ||
| 205 | + TestSessionClarifyBudget._question_response("optimization_goal"), # 预算已尽 → 拦截 | ||
| 206 | + {"type": "proposals", "proposals": [{"title": "P1", "description": "d"}], "assessment": "ready_for_proposals"}, | ||
| 207 | + ]) | ||
| 208 | + monkeypatch.setattr(type(session), "_call_llm", lambda self: next(responses)) | ||
| 209 | + session.start("帮我适配一个模型") | ||
| 210 | + session.answer("q1", "Qwen3-8B") # 预算已尽 → 带假设推进 | ||
| 211 | + context = session._build_context() | ||
| 212 | + assert context["assumptions"]["quantization"] == "按模型默认精度(不额外量化)" | ||
| 213 | + messages = session._build_llm_messages() | ||
| 214 | + joined = "\n".join(m["content"] for m in messages) | ||
| 215 | + assert "澄清预算已用尽" in joined | ||
| 216 | + assert "quantization" in joined | ||
| 217 | + | ||
| 218 | + def test_to_dict_roundtrip_preserves_budget_state(self): | ||
| 219 | + session = BrainstormingSession(llm=MagicMock(), max_rounds=2) | ||
| 220 | + session.assumptions = {"quantization": "按模型默认精度(不额外量化)"} | ||
| 221 | + restored = BrainstormingSession.from_dict(session.to_dict()) | ||
| 222 | + assert restored.max_rounds == 2 | ||
| 223 | + assert restored.assumptions == {"quantization": "按模型默认精度(不额外量化)"} | ||
| 224 | + | ||
| 225 | + def test_existing_behavior_unchanged_within_budget(self, monkeypatch): | ||
| 226 | + """预算内行为不变:多轮提问仍逐轮进行(不提前推进)。""" | ||
| 227 | + session = BrainstormingSession(llm=MagicMock(), max_rounds=3) | ||
| 228 | + session.user_input = "帮我适配一个模型" | ||
| 229 | + monkeypatch.setattr(type(session), "_call_llm", lambda self: TestSessionClarifyBudget._question_response()) | ||
| 230 | + session.start("帮我适配一个模型") | ||
| 231 | + assert session.state == BrainstormState.CLARIFYING | ||
| 232 | + session.answer("q1", "Qwen3-8B") | ||
| 233 | + assert session.state == BrainstormState.CLARIFYING | ||
| 234 | + assert session.clarified_dimensions.get("model_name") == "Qwen3-8B" | ||
| 235 | + assert len(session.questions_asked) == 2 # start 问过 1 轮,answer 后又问了 1 轮 | ||
| 236 | + assert session.assumptions == {} # 预算内不产生假设 | ||