sync: 鍚屾灞€鍩熺綉鏈€鏂颁唬鐮?(source master @ b69568e4)
This commit is contained in:
1 parent
4f7f07504a
commit
8bc8b0e082
1651 files changed
+278599
-11416
No files matched your search
@@ -1,6 +1,6 @@
|
||||
"""Pre-plan requirement resolution package."""
|
||||
|
||||
from app.report_collaboration.requirement.intent_router import PrePlanDecision, route_pre_plan_turn
|
||||
from app.report_collaboration.requirement.intent_router import PrePlanDecision
|
||||
from app.report_collaboration.requirement.resolver import RequirementResolver
|
||||
|
||||
__all__ = ["PrePlanDecision", "RequirementResolver", "route_pre_plan_turn"]
|
||||
__all__ = ["PrePlanDecision", "RequirementResolver"]
|
||||
+11
-79
@@ -1,4 +1,9 @@
|
||||
"""Pre-plan IntentRouterAgent: understand the user turn, never dispatch work."""
|
||||
"""Pre-plan 数据结构与快照合并工具。
|
||||
|
||||
P1-R 之后需求确认完全由规划师智能体(``planning/planner_agent.py``)驱动;
|
||||
本模块只保留被复用的数据结构与合并工具。原规则路由 ``route_pre_plan_turn``
|
||||
已按设计 v2 移除 —— 模型不可用即报错,不再有规则兜底。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -7,12 +12,11 @@ from typing import Any, Literal
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
|
||||
from app.report_collaboration.contracts.requirements import ReportRequirementSnapshot
|
||||
from app.report_collaboration.requirement.defaults import DEFAULT_ANGLES, DEFAULT_AUDIENCE, DEFAULT_LANGUAGE, DEFAULT_SOURCE_CONSTRAINTS, DEFAULT_TONE, PLAN_AFFECTING_GAPS
|
||||
from app.report_collaboration.requirement.extractor import extract_requirement_patch, wants_direct_start
|
||||
from app.report_collaboration.requirement.defaults import DEFAULT_ANGLES, DEFAULT_AUDIENCE, DEFAULT_LANGUAGE, DEFAULT_SOURCE_CONSTRAINTS, DEFAULT_TONE
|
||||
|
||||
|
||||
class PrePlanDecision(BaseModel):
|
||||
"""Structured output of the pre-plan router. It never builds a graph or starts a run."""
|
||||
"""规划师智能体一轮决策。It never builds a graph or starts a run."""
|
||||
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
@@ -24,11 +28,13 @@ class PrePlanDecision(BaseModel):
|
||||
used_defaults: bool = False
|
||||
reason: str
|
||||
confidence: float = Field(ge=0, le=1)
|
||||
#: 规划师智能体产出的完整对话文案,直接落库展示。
|
||||
reply: str | None = None
|
||||
|
||||
|
||||
def _merge_snapshot(previous: dict[str, Any] | None, patch: dict[str, Any], *, revision: int) -> ReportRequirementSnapshot:
|
||||
base = dict(previous or {})
|
||||
base.update(patch)
|
||||
base.update(patch or {})
|
||||
topic = str(base.get("topic") or "").strip()
|
||||
return ReportRequirementSnapshot(
|
||||
topic=topic or "未指定主题",
|
||||
@@ -49,21 +55,6 @@ def _merge_snapshot(previous: dict[str, Any] | None, patch: dict[str, Any], *, r
|
||||
)
|
||||
|
||||
|
||||
def _gaps(requirement: ReportRequirementSnapshot) -> list[tuple[str, str, str]]:
|
||||
missing: list[tuple[str, str, str]] = []
|
||||
if not requirement.topic or requirement.topic == "未指定主题":
|
||||
missing.append(("topic", "这份报告要写什么主题?请用一两句话说明对象、时间和目的。", "没有主题无法选择方案"))
|
||||
for field, question, impact in PLAN_AFFECTING_GAPS:
|
||||
value = getattr(requirement, field, None)
|
||||
if field == "required_angles":
|
||||
empty = not value
|
||||
else:
|
||||
empty = not (value or "").strip()
|
||||
if empty:
|
||||
missing.append((field, question, impact))
|
||||
return missing
|
||||
|
||||
|
||||
def apply_default_assumptions(requirement: ReportRequirementSnapshot) -> tuple[ReportRequirementSnapshot, list[str]]:
|
||||
assumptions: list[str] = []
|
||||
data = requirement.model_dump()
|
||||
@@ -82,62 +73,3 @@ def apply_default_assumptions(requirement: ReportRequirementSnapshot) -> tuple[R
|
||||
data["tone"] = DEFAULT_TONE
|
||||
assumptions.append(DEFAULT_TONE)
|
||||
return ReportRequirementSnapshot.model_validate(data), assumptions
|
||||
|
||||
|
||||
def route_pre_plan_turn(
|
||||
text: str,
|
||||
*,
|
||||
previous_snapshot: dict[str, Any] | None,
|
||||
previous_revision: int,
|
||||
clarification_round: int,
|
||||
max_clarification_rounds: int,
|
||||
) -> PrePlanDecision:
|
||||
"""Rule-based pre-plan routing. Does not call tools or create plans."""
|
||||
|
||||
patch = extract_requirement_patch(text, previous=previous_snapshot)
|
||||
revision = max(1, int(previous_revision) + 1) if previous_snapshot or patch else max(1, int(previous_revision) or 1)
|
||||
if not previous_snapshot:
|
||||
revision = 1
|
||||
requirement = _merge_snapshot(previous_snapshot, patch, revision=revision)
|
||||
skip = wants_direct_start(text)
|
||||
hit_cap = clarification_round >= max_clarification_rounds
|
||||
gaps = _gaps(requirement)
|
||||
|
||||
if requirement.topic == "未指定主题" and skip:
|
||||
return PrePlanDecision(
|
||||
action="clarify",
|
||||
requirement=requirement,
|
||||
questions=["这份报告要写什么主题?请用一两句话说明对象、时间和目的。"],
|
||||
impact=["没有主题无法选择方案"],
|
||||
reason="用户要求直接开始,但还没有主题",
|
||||
confidence=0.9,
|
||||
)
|
||||
|
||||
if skip or (hit_cap and gaps):
|
||||
filled, assumptions = apply_default_assumptions(requirement)
|
||||
return PrePlanDecision(
|
||||
action="ready",
|
||||
requirement=filled,
|
||||
assumptions=assumptions,
|
||||
used_defaults=True,
|
||||
reason="用户要求按默认假设继续" if skip else "已达澄清上限,使用明确假设继续",
|
||||
confidence=0.86 if skip else 0.7,
|
||||
)
|
||||
|
||||
if gaps:
|
||||
return PrePlanDecision(
|
||||
action="clarify",
|
||||
requirement=requirement,
|
||||
questions=[item[1] for item in gaps],
|
||||
impact=[item[2] for item in gaps],
|
||||
reason="缺少真正影响方案选择的信息",
|
||||
confidence=0.8,
|
||||
)
|
||||
|
||||
return PrePlanDecision(
|
||||
action="ready",
|
||||
requirement=requirement,
|
||||
reason="必要信息已齐,可以进入规划",
|
||||
confidence=0.84,
|
||||
used_defaults=False,
|
||||
)
|
||||
+142
-67
@@ -1,18 +1,39 @@
|
||||
"""Validate and persist requirement revisions. Never starts planning or a run."""
|
||||
"""Requirement resolver: the planner agent is the only path.
|
||||
|
||||
模型不可用即无法继续 —— 直接抛 ``PLANNER_UNAVAILABLE``,没有任何规则/
|
||||
模板兜底(设计 v2:需求确认必须由真智能体完成)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from typing import Any
|
||||
from uuid import uuid4
|
||||
|
||||
from app.report_collaboration.contracts.clarifications import ClarificationRecord
|
||||
from app.report_collaboration.contracts.requirements import ReportRequirementSnapshot
|
||||
from app.report_collaboration.requirement.defaults import COORDINATOR_NAME, DEFAULT_TITLE
|
||||
from app.report_collaboration.requirement.intent_router import PrePlanDecision, route_pre_plan_turn
|
||||
from app.report_collaboration.requirement.intent_router import PrePlanDecision
|
||||
from deerflow.config.app_config import get_app_config
|
||||
from deerflow.persistence.report_collaboration import ReportCollaborationStore
|
||||
from deerflow.persistence.report_collaboration import (
|
||||
ReportCollaborationStore,
|
||||
ReportCollaborationValidationError,
|
||||
)
|
||||
from deerflow.persistence.report_collaboration.codec import iso_now
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# 仅供类型注解;运行时惰性导入避免 requirement ↔ planning 循环依赖。
|
||||
LlmFactory = Any
|
||||
|
||||
|
||||
def _title_from_topic(topic: str, current: str | None) -> str | None:
|
||||
if current and current != DEFAULT_TITLE:
|
||||
return None
|
||||
cleaned = (topic or "").strip()
|
||||
if not cleaned or cleaned == "未指定主题":
|
||||
return None
|
||||
return cleaned[:40]
|
||||
|
||||
|
||||
def _state_from_session(record: dict[str, Any]) -> dict[str, Any]:
|
||||
raw = record.get("requirement_json")
|
||||
@@ -35,58 +56,56 @@ def _state_from_session(record: dict[str, Any]) -> dict[str, Any]:
|
||||
return {"snapshot": None, "clarifications": [], "assumptions": [], "clarification_round": 0, "ready_to_plan": False}
|
||||
|
||||
|
||||
def _dump_state(
|
||||
*,
|
||||
snapshot: ReportRequirementSnapshot,
|
||||
clarifications: list[dict[str, Any]],
|
||||
assumptions: list[str],
|
||||
clarification_round: int,
|
||||
ready_to_plan: bool,
|
||||
) -> dict[str, Any]:
|
||||
return {
|
||||
"snapshot": snapshot.model_dump(),
|
||||
"clarifications": clarifications,
|
||||
"assumptions": assumptions,
|
||||
"clarification_round": clarification_round,
|
||||
"ready_to_plan": ready_to_plan,
|
||||
}
|
||||
|
||||
|
||||
def format_clarification_message(questions: list[str], *, allow_skip: bool = True) -> str:
|
||||
numbered = "\n".join(f"{index}. {question}" for index, question in enumerate(questions, start=1))
|
||||
suffix = "\n\n也可以直接回复「直接开始」,我会按默认假设记录需求。澄清完成不会自动生成方案。" if allow_skip else ""
|
||||
return f"收到您的报告需求。为了给出最合适的协作方案,请先确认:\n\n{numbered}{suffix}"
|
||||
|
||||
|
||||
def format_ready_message(decision: PrePlanDecision) -> str:
|
||||
req = decision.requirement
|
||||
angles = "、".join(req.required_angles) if req.required_angles else "(未指定)"
|
||||
lines = [
|
||||
f"已写入需求版本 v{req.revision}。",
|
||||
f"主题:{req.topic}",
|
||||
f"读者:{req.audience or '未指定'}",
|
||||
f"角度:{angles}",
|
||||
]
|
||||
if decision.assumptions:
|
||||
lines.append("默认假设:" + ";".join(decision.assumptions) + "。")
|
||||
lines.append("澄清完成不等于已经生成候选方案,需要显式发起规划后才会出现方案卡。")
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def _title_from_topic(topic: str, current: str | None) -> str | None:
|
||||
if current and current != DEFAULT_TITLE:
|
||||
return None
|
||||
cleaned = (topic or "").strip()
|
||||
if not cleaned or cleaned == "未指定主题":
|
||||
return None
|
||||
return cleaned[:40]
|
||||
|
||||
|
||||
class RequirementResolver:
|
||||
"""Writes requirement revisions and clarification records. Does not enqueue plans."""
|
||||
|
||||
def __init__(self, store: ReportCollaborationStore) -> None:
|
||||
def __init__(
|
||||
self,
|
||||
store: ReportCollaborationStore,
|
||||
*,
|
||||
planner_llm_factory: LlmFactory | None = None,
|
||||
config: Any | None = None,
|
||||
) -> None:
|
||||
self._store = store
|
||||
self._planner_llm_factory = planner_llm_factory
|
||||
self._config = config
|
||||
self._default_llm: Any = None
|
||||
self._default_llm_tried = False
|
||||
|
||||
def _planner_llm(self) -> Any:
|
||||
"""规划师模型:注入优先(测试);否则按 planner_llm_enabled 懒构建。不可用即抛错。"""
|
||||
|
||||
if self._planner_llm_factory is not None:
|
||||
llm = self._planner_llm_factory()
|
||||
if llm is None:
|
||||
raise ReportCollaborationValidationError("PLANNER_UNAVAILABLE", "规划师智能体不可用,请检查模型配置")
|
||||
return llm
|
||||
try:
|
||||
from deerflow.config.report_collaboration_config import ReportCollaborationConfig
|
||||
|
||||
cfg: Any = self._config
|
||||
if cfg is None:
|
||||
cfg = get_app_config().report_collaboration
|
||||
if not ReportCollaborationConfig.model_validate(cfg).planner_llm_enabled:
|
||||
raise ReportCollaborationValidationError(
|
||||
"PLANNER_UNAVAILABLE", "规划师智能体未启用(report_collaboration.planner_llm_enabled)"
|
||||
)
|
||||
except ReportCollaborationValidationError:
|
||||
raise
|
||||
except Exception as exc:
|
||||
raise ReportCollaborationValidationError("PLANNER_UNAVAILABLE", f"规划师智能体配置不可读:{exc}") from None
|
||||
if not self._default_llm_tried:
|
||||
self._default_llm_tried = True
|
||||
try:
|
||||
from app.report_collaboration.planning.planner_agent import build_planner_llm
|
||||
|
||||
self._default_llm = build_planner_llm()
|
||||
except Exception as exc:
|
||||
logger.warning("rc planner agent llm build failed: %s", exc)
|
||||
self._default_llm = None
|
||||
if self._default_llm is None:
|
||||
raise ReportCollaborationValidationError("PLANNER_UNAVAILABLE", "规划师智能体不可用,请检查模型配置")
|
||||
return self._default_llm
|
||||
|
||||
async def handle_user_message(
|
||||
self,
|
||||
@@ -111,16 +130,67 @@ class RequirementResolver:
|
||||
cfg_rounds = max_clarification_rounds
|
||||
if cfg_rounds is None:
|
||||
cfg_rounds = int(get_app_config().report_collaboration.max_clarification_rounds)
|
||||
decision = route_pre_plan_turn(
|
||||
str(user_message.get("content") or ""),
|
||||
previous_snapshot=state["snapshot"],
|
||||
|
||||
text = str(user_message.get("content") or "")
|
||||
history = [
|
||||
{"role": "human" if item.get("role") == "human" else "ai", "content": str(item.get("content") or "")}
|
||||
for item in messages
|
||||
if item.get("message_id") != user_message["message_id"]
|
||||
]
|
||||
|
||||
decision = await self._agent_decision(
|
||||
text,
|
||||
history=history,
|
||||
state=state,
|
||||
previous_revision=int(record.get("requirement_revision") or 0),
|
||||
clarification_round=int(state["clarification_round"] or 0),
|
||||
max_clarification_rounds=cfg_rounds,
|
||||
max_rounds=cfg_rounds,
|
||||
)
|
||||
if decision is None:
|
||||
# 模型调用失败/输出不合法 —— 无法继续,直接报错(无兜底)。
|
||||
raise ReportCollaborationValidationError("PLANNER_UNAVAILABLE", "规划师智能体本轮未返回有效决策,请重试")
|
||||
await self._apply(session_id, record, state, decision, user_message=user_message, idempotency_key=idempotency_key)
|
||||
return decision
|
||||
|
||||
async def _agent_decision(
|
||||
self,
|
||||
text: str,
|
||||
*,
|
||||
history: list[dict[str, str]],
|
||||
state: dict[str, Any],
|
||||
previous_revision: int,
|
||||
max_rounds: int,
|
||||
) -> PrePlanDecision | None:
|
||||
llm = self._planner_llm()
|
||||
from app.report_collaboration.planning.planner_agent import PlannerAgent
|
||||
|
||||
agent = PlannerAgent(llm)
|
||||
turn = await agent.converse(
|
||||
user_text=text,
|
||||
history=history,
|
||||
previous_snapshot=state["snapshot"],
|
||||
previous_revision=previous_revision,
|
||||
clarification_round=int(state["clarification_round"] or 0),
|
||||
max_rounds=max_rounds,
|
||||
)
|
||||
if turn is None:
|
||||
return None
|
||||
requirement = agent.merge_requirement(
|
||||
turn,
|
||||
previous_snapshot=state["snapshot"],
|
||||
previous_revision=previous_revision,
|
||||
)
|
||||
return PrePlanDecision(
|
||||
action="ready" if turn.action == "ready" else "clarify",
|
||||
requirement=requirement,
|
||||
questions=[item for item in turn.questions if item and item.strip()][:3],
|
||||
impact=[item for item in turn.impact if item][:3],
|
||||
assumptions=[item for item in turn.assumptions if item],
|
||||
used_defaults=bool(turn.assumptions),
|
||||
reason="planner_agent",
|
||||
confidence=0.9,
|
||||
reply=turn.reply.strip(),
|
||||
)
|
||||
|
||||
async def _apply(
|
||||
self,
|
||||
session_id: str,
|
||||
@@ -146,7 +216,7 @@ class RequirementResolver:
|
||||
created_at=iso_now(),
|
||||
)
|
||||
clarifications.append(clarification.model_dump())
|
||||
content = format_clarification_message(decision.questions)
|
||||
content = decision.reply or ""
|
||||
metadata = {
|
||||
"preplan_for": user_message["message_id"],
|
||||
"clarification": clarification.model_dump(),
|
||||
@@ -155,17 +225,22 @@ class RequirementResolver:
|
||||
else:
|
||||
for item in clarifications:
|
||||
item["resolved"] = True
|
||||
content = format_ready_message(decision)
|
||||
metadata = {"preplan_for": user_message["message_id"], "ready_to_plan": True}
|
||||
content = decision.reply or ""
|
||||
metadata = {
|
||||
"preplan_for": user_message["message_id"],
|
||||
"ready_to_plan": True,
|
||||
# 结构化需求快照:前端据此渲染「需求摘要卡」(计划模式 UI)。
|
||||
"requirement": decision.requirement.model_dump(),
|
||||
}
|
||||
ready = True
|
||||
|
||||
payload = _dump_state(
|
||||
snapshot=decision.requirement,
|
||||
clarifications=clarifications,
|
||||
assumptions=list(decision.assumptions),
|
||||
clarification_round=round_count,
|
||||
ready_to_plan=ready,
|
||||
)
|
||||
payload = {
|
||||
"snapshot": decision.requirement.model_dump(),
|
||||
"clarifications": clarifications,
|
||||
"assumptions": list(decision.assumptions),
|
||||
"clarification_round": round_count,
|
||||
"ready_to_plan": ready,
|
||||
}
|
||||
await self._store.save_requirement_state(
|
||||
session_id,
|
||||
requirement_json=payload,
|
||||
|
||||
Reference in new issue
Block a user