sync: 鍚屾灞€鍩熺綉鏈€鏂颁唬鐮?(source master @ b69568e4)
This commit is contained in:
1 parent
4f7f07504a
commit
8bc8b0e082
1651 files changed
+278599
-11416
No files matched your search
@@ -88,7 +88,14 @@ class PlanAssembler:
|
||||
|
||||
for slot in strategy.slots:
|
||||
demand = slot.demand
|
||||
agent, reason = self._selector.pick(demand.role_key, catalog.agents, avoid_ids=used_user_ids)
|
||||
preferred = next(
|
||||
(item for item in catalog.agents if demand.agent_id and item.agent_id == demand.agent_id and item.enabled),
|
||||
None,
|
||||
)
|
||||
if preferred is not None:
|
||||
agent, reason = preferred, "规划智能体依据名称与描述选定"
|
||||
else:
|
||||
agent, reason = self._selector.pick(demand.role_key, catalog.agents, avoid_ids=used_user_ids)
|
||||
if agent.source == "user":
|
||||
used_user_ids.add(agent.agent_id)
|
||||
tools = _tools_for(demand.role_key, demand.suggested_tools, catalog.allowed_tool_names)
|
||||
@@ -100,7 +107,9 @@ class PlanAssembler:
|
||||
id=slot.slot_id,
|
||||
label=demand.angle or demand.display_name,
|
||||
role_key=demand.role_key,
|
||||
role_display_name=agent.name if agent.source == "user" else demand.display_name,
|
||||
role_display_name=agent.name,
|
||||
agent_id=agent.agent_id,
|
||||
agent_description=agent.description,
|
||||
angle=demand.angle,
|
||||
depends_on=list(slot.depends_on),
|
||||
mission=demand.mission,
|
||||
@@ -120,10 +129,10 @@ class PlanAssembler:
|
||||
reason=reason,
|
||||
)
|
||||
)
|
||||
if demand.role_key not in roles_by_key:
|
||||
roles_by_key[demand.role_key] = PlanRole(
|
||||
key=demand.role_key,
|
||||
display_name=demand.display_name,
|
||||
if agent.agent_id not in roles_by_key:
|
||||
roles_by_key[agent.agent_id] = PlanRole(
|
||||
key=agent.agent_id,
|
||||
display_name=agent.name,
|
||||
responsibility=demand.mission,
|
||||
angle=demand.angle,
|
||||
)
|
||||
|
||||
@@ -0,0 +1,608 @@
|
||||
"""规划师智能体(PlannerAgent)——真智能体,不是规则路由 + 模板文案。
|
||||
|
||||
设计 v2 的需求对话与工作流生成主路径:
|
||||
- ``converse``:与用户多轮自由对话确认需求。回复文案(含开场)完全由
|
||||
智能体生成并直接落库展示 —— 「收到您的报告需求。为了给出…」这类
|
||||
死模板文案已从该路径移除。
|
||||
- ``design_workflow``:带着**完整对话上下文**(规划师问了什么、用户
|
||||
答了什么)生成受词表约束的自定义工作流(``StrategyRoleSet``),
|
||||
与确定性模板走同一条 装配 → 校验 → 绑定 链路。
|
||||
|
||||
规则路由与模板只作为模型彻底不可用时的最后防线,不出现在用户面前。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import re
|
||||
from collections.abc import Callable
|
||||
from typing import Any
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field, ValidationError
|
||||
|
||||
from app.report_collaboration.agentscope_runtime.model_resolver import ROLE_MODEL_FIELD, RoleModelSnapshot, resolve_role_model
|
||||
from app.report_collaboration.contracts.plans import RoleDemand
|
||||
from app.report_collaboration.contracts.requirements import ReportRequirementSnapshot
|
||||
from app.report_collaboration.planning.catalog import AgentCatalogProjection
|
||||
from app.report_collaboration.planning.controller import RoleSlot, StrategyRoleSet
|
||||
from app.report_collaboration.requirement.intent_router import _merge_snapshot, apply_default_assumptions
|
||||
from deerflow.config.app_config import AppConfig, get_app_config
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# ── 词表(结构化输出的安全边界,LLM 不受约束的自由只在文案层) ─────────────
|
||||
|
||||
MEMBER_ROLES: tuple[str, ...] = tuple(key for key in ROLE_MODEL_FIELD if key != "coordinator")
|
||||
|
||||
ROLE_ARTIFACTS: dict[str, tuple[str, ...]] = {
|
||||
"researcher": ("EvidenceBundle",),
|
||||
"verifier": ("VerificationResult",),
|
||||
"analyst": ("AngleAnalysis",),
|
||||
"synthesizer": ("SynthesisOutline",),
|
||||
"writer": ("ReportSectionDraft",),
|
||||
"reviewer": ("ReviewDecision",),
|
||||
"reviser": ("ReportSectionDraft",),
|
||||
}
|
||||
|
||||
QUALITY_GATES: tuple[str, ...] = ("cite_required", "dual_verification", "independent_review", "coverage_matrix")
|
||||
|
||||
# ── 智能体输出契约 ─────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
class PlannerTurn(BaseModel):
|
||||
"""规划师一轮对话的完整产出:自由文案 + 结构化状态。"""
|
||||
|
||||
model_config = ConfigDict(extra="ignore")
|
||||
|
||||
action: str = "clarify"
|
||||
reply: str = ""
|
||||
questions: list[str] = Field(default_factory=list)
|
||||
impact: list[str] = Field(default_factory=list)
|
||||
assumptions: list[str] = Field(default_factory=list)
|
||||
requirement: dict[str, Any] = Field(default_factory=dict)
|
||||
|
||||
|
||||
class StrategyNodeDraft(BaseModel):
|
||||
model_config = ConfigDict(extra="ignore")
|
||||
|
||||
slot_id: str
|
||||
role_key: str
|
||||
agent_id: str | None = None
|
||||
display_name: str
|
||||
angle: str | None = None
|
||||
mission: str
|
||||
depends_on: list[str] = Field(default_factory=list)
|
||||
output_artifact_type: str
|
||||
suggested_tools: list[str] = Field(default_factory=list)
|
||||
|
||||
|
||||
class StrategyDraft(BaseModel):
|
||||
model_config = ConfigDict(extra="ignore")
|
||||
|
||||
reply: str = ""
|
||||
strategy: str = "custom"
|
||||
title: str
|
||||
summary: str
|
||||
rationale: str
|
||||
estimated_duration_seconds: int = 900
|
||||
estimated_cost_level: str = "medium"
|
||||
quality_gate_ids: list[str] = Field(default_factory=lambda: ["cite_required"])
|
||||
nodes: list[StrategyNodeDraft] = Field(default_factory=list)
|
||||
|
||||
|
||||
LlmFactory = Callable[[], Any]
|
||||
|
||||
|
||||
def planner_model_snapshot(app_config: AppConfig | None = None) -> RoleModelSnapshot:
|
||||
"""规划师身份沿用角色解析链:coordinator_model → planner_model → 默认模型。"""
|
||||
|
||||
return resolve_role_model("coordinator", app_config=app_config or get_app_config())
|
||||
|
||||
|
||||
def build_planner_llm(app_config: AppConfig | None = None) -> Any:
|
||||
from deerflow.models.factory import create_chat_model
|
||||
|
||||
snapshot = planner_model_snapshot(app_config)
|
||||
return create_chat_model(snapshot.config_name, app_config=app_config or get_app_config())
|
||||
|
||||
|
||||
_THINK_BLOCK_RE = re.compile(r"<think>.*?</think>", re.DOTALL | re.IGNORECASE)
|
||||
|
||||
|
||||
def _extract_json(text: str) -> dict[str, Any] | None:
|
||||
if not text:
|
||||
return None
|
||||
# 思考模型(MiniMax-M2.7 等)回复可能带 <think>…</think>;JSON 在思考块之后。
|
||||
# 先剥思考块提取;剥完没有再回退用全文(极端情况 JSON 混在思考内)。
|
||||
for candidate in (_THINK_BLOCK_RE.sub("", text).strip(), text.strip()):
|
||||
if not candidate:
|
||||
continue
|
||||
cleaned = candidate
|
||||
if cleaned.startswith("```"):
|
||||
cleaned = cleaned.strip("`")
|
||||
if cleaned.lower().startswith("json"):
|
||||
cleaned = cleaned[4:]
|
||||
cleaned = cleaned.strip()
|
||||
start = cleaned.find("{")
|
||||
end = cleaned.rfind("}")
|
||||
if start < 0 or end <= start:
|
||||
continue
|
||||
try:
|
||||
parsed = json.loads(cleaned[start : end + 1])
|
||||
except Exception:
|
||||
parsed = None
|
||||
if isinstance(parsed, dict):
|
||||
return parsed
|
||||
|
||||
# A provider may hit its output cap after emitting one or more complete
|
||||
# candidates but before closing the outer JSON object. Salvage those
|
||||
# complete candidate objects instead of losing the whole planning turn.
|
||||
decoder = json.JSONDecoder()
|
||||
decoded: list[dict[str, Any]] = []
|
||||
for match in re.finditer(r"\{", cleaned):
|
||||
try:
|
||||
value, _offset = decoder.raw_decode(cleaned[match.start() :])
|
||||
except (json.JSONDecodeError, ValueError):
|
||||
continue
|
||||
if isinstance(value, dict):
|
||||
decoded.append(value)
|
||||
bundle = next(
|
||||
(value for value in decoded if isinstance(value.get("candidates"), list)),
|
||||
None,
|
||||
)
|
||||
if bundle is not None:
|
||||
return bundle
|
||||
strategies = [
|
||||
value
|
||||
for value in decoded
|
||||
if isinstance(value.get("nodes"), list) and value.get("title")
|
||||
]
|
||||
if strategies:
|
||||
return {"candidates": strategies[:3]}
|
||||
if decoded:
|
||||
return decoded[0]
|
||||
return None
|
||||
|
||||
|
||||
async def _invoke_json(llm: Any, messages: list[Any]) -> tuple[dict[str, Any] | None, str]:
|
||||
"""调用模型并提取 JSON。返回 (解析结果, 原始文本);解析失败结果为 None。"""
|
||||
|
||||
try:
|
||||
response = await llm.ainvoke(messages)
|
||||
raw = getattr(response, "content", response)
|
||||
if isinstance(raw, list):
|
||||
raw = "".join(str(getattr(block, "text", block) if not isinstance(block, str) else block) for block in raw)
|
||||
raw = str(raw)
|
||||
return _extract_json(raw), raw
|
||||
except Exception as exc: # noqa: BLE001 — 智能体故障必须显式失败
|
||||
logger.warning("rc planner agent llm call failed: %s: %s", exc.__class__.__name__, exc)
|
||||
return None, ""
|
||||
|
||||
|
||||
async def _invoke_json_with_retry(llm: Any, system: str, user_prompt: str) -> dict[str, Any] | None:
|
||||
"""带一次格式重试:模型输出不含 JSON 时,附原始输出要求只出 JSON 再问一次。"""
|
||||
|
||||
parsed, raw = await _invoke_json(llm, [("system", system), ("human", user_prompt)])
|
||||
if parsed is None:
|
||||
logger.warning("rc planner reply without JSON (raw head: %.200s)", raw[:200])
|
||||
retry_prompt = (
|
||||
user_prompt
|
||||
+ "\n\n【格式提醒】你上一轮的输出没有包含合法 JSON。这次必须只输出一个 JSON 对象,"
|
||||
+ f"不要在 JSON 之外输出任何文字。你上一轮的输出是:{raw[:500]}"
|
||||
)
|
||||
parsed, _ = await _invoke_json(llm, [("system", system), ("human", retry_prompt)])
|
||||
return parsed
|
||||
|
||||
|
||||
# ── 规划师智能体 ───────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
class PlannerAgent:
|
||||
"""需求对话与工作流设计的唯一主路径(真智能体)。"""
|
||||
|
||||
def __init__(self, llm: Any, *, app_config: AppConfig | None = None) -> None:
|
||||
self._llm = llm
|
||||
self._app_config = app_config
|
||||
|
||||
# ── 需求对话 ───────────────────────────────────────────────────────────
|
||||
|
||||
async def converse(
|
||||
self,
|
||||
*,
|
||||
user_text: str,
|
||||
history: list[dict[str, str]],
|
||||
previous_snapshot: dict[str, Any] | None,
|
||||
previous_revision: int,
|
||||
clarification_round: int,
|
||||
max_rounds: int,
|
||||
) -> PlannerTurn | None:
|
||||
"""一轮规划对话。返回 None 表示智能体不可用(调用方走最后防线)。"""
|
||||
|
||||
forced = clarification_round >= max_rounds
|
||||
system = _CONVERSE_SYSTEM.format(
|
||||
roles=", ".join(MEMBER_ROLES),
|
||||
forced_note=(
|
||||
"\n\n【重要】澄清轮次已达上限,本轮你必须判定需求就绪(action=ready):"
|
||||
"自然地告诉用户你将按当前理解开始规划,把未能确认的点写进 assumptions。"
|
||||
if forced
|
||||
else ""
|
||||
),
|
||||
)
|
||||
known = {k: v for k, v in (previous_snapshot or {}).items() if v not in (None, "", [])}
|
||||
known.pop("revision", None)
|
||||
history_text = "\n".join(
|
||||
f"{'用户' if item.get('role') == 'human' else '规划师'}: {str(item.get('content') or '')[:400]}"
|
||||
for item in history[-10:]
|
||||
)
|
||||
user_prompt = (
|
||||
f"当前已确认的需求快照(JSON):{json.dumps(known, ensure_ascii=False)}\n\n"
|
||||
f"最近的对话:\n{history_text or '(无)'}\n\n"
|
||||
f"用户最新消息:{user_text}"
|
||||
)
|
||||
parsed = await _invoke_json_with_retry(self._llm, system, user_prompt)
|
||||
if parsed is None:
|
||||
return None
|
||||
try:
|
||||
turn = PlannerTurn.model_validate(parsed)
|
||||
except ValidationError:
|
||||
logger.warning("rc planner turn invalid: %s", str(parsed)[:200])
|
||||
return None
|
||||
if not (turn.reply or "").strip():
|
||||
return None
|
||||
if forced and turn.action != "ready":
|
||||
turn.action = "ready"
|
||||
if turn.action == "ready" and not turn.assumptions:
|
||||
turn.assumptions = ["按对话中已确认的信息直接规划"]
|
||||
return turn
|
||||
|
||||
def merge_requirement(
|
||||
self,
|
||||
turn: PlannerTurn,
|
||||
*,
|
||||
previous_snapshot: dict[str, Any] | None,
|
||||
previous_revision: int,
|
||||
) -> ReportRequirementSnapshot:
|
||||
"""把智能体本轮带回的需求字段合并进既有快照(revision 语义同规则路由)。"""
|
||||
|
||||
known = {k: v for k, v in (previous_snapshot or {}).items() if k != "revision"}
|
||||
# LLM 契约是「只填能确认的字段」;再过滤一次空值,避免空串覆盖已确认信息。
|
||||
patch = {
|
||||
k: v
|
||||
for k, v in (turn.requirement or {}).items()
|
||||
if k != "revision" and v not in (None, "", [])
|
||||
}
|
||||
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
|
||||
merged = _merge_snapshot(known, patch, revision=revision)
|
||||
if turn.action == "ready":
|
||||
merged = apply_default_assumptions(merged)[0]
|
||||
return merged
|
||||
|
||||
# ── 工作流设计 ─────────────────────────────────────────────────────────
|
||||
|
||||
async def design_workflow(
|
||||
self,
|
||||
*,
|
||||
requirement: ReportRequirementSnapshot,
|
||||
history: list[dict[str, str]],
|
||||
max_team_members: int = 8,
|
||||
) -> tuple[StrategyRoleSet, str] | None:
|
||||
"""带着完整对话上下文设计工作流;返回 (策略, 展示文案) 或 None。"""
|
||||
|
||||
fields = {k: v for k, v in requirement.model_dump().items() if v not in (None, "", [])}
|
||||
fields.pop("revision", None)
|
||||
history_text = "\n".join(
|
||||
f"{'用户' if item.get('role') == 'human' else '规划师'}: {str(item.get('content') or '')[:300]}"
|
||||
for item in history[-12:]
|
||||
)
|
||||
system = _DESIGN_SYSTEM.format(
|
||||
roles=", ".join(MEMBER_ROLES),
|
||||
artifacts="\n".join(f" - {role}: {' / '.join(arts)}" for role, arts in ROLE_ARTIFACTS.items()),
|
||||
gates=", ".join(QUALITY_GATES),
|
||||
max_nodes=min(max_team_members, 8),
|
||||
)
|
||||
user_prompt = (
|
||||
f"需求快照(JSON):{json.dumps(fields, ensure_ascii=False)}\n\n"
|
||||
f"需求确认阶段的对话(你与用户):\n{history_text or '(无)'}\n\n请设计工作流。"
|
||||
)
|
||||
parsed = await _invoke_json_with_retry(self._llm, system, user_prompt)
|
||||
if parsed is None:
|
||||
return None
|
||||
try:
|
||||
draft = StrategyDraft.model_validate(parsed)
|
||||
except ValidationError:
|
||||
logger.warning("rc planner strategy draft invalid: %s", str(parsed)[:200])
|
||||
return None
|
||||
strategy = _validate_strategy_dag(draft)
|
||||
if strategy is None:
|
||||
logger.warning("rc planner strategy failed vocabulary/DAG validation: %s", str(parsed)[:200])
|
||||
return None
|
||||
reply = (draft.reply or "").strip() or f"已按需求设计好协作工作流「{draft.title}」。"
|
||||
return strategy, reply
|
||||
|
||||
async def design_workflows(
|
||||
self,
|
||||
*,
|
||||
requirement: ReportRequirementSnapshot,
|
||||
history: list[dict[str, str]],
|
||||
catalog: AgentCatalogProjection,
|
||||
current_plans: list[dict[str, Any]] | None = None,
|
||||
adjustment_text: str | None = None,
|
||||
max_team_members: int = 8,
|
||||
) -> tuple[list[StrategyRoleSet], str] | None:
|
||||
"""Design selectable workflows from the real visible-agent catalog."""
|
||||
|
||||
messages = self.workflow_messages(
|
||||
requirement=requirement,
|
||||
history=history,
|
||||
catalog=catalog,
|
||||
current_plans=current_plans,
|
||||
adjustment_text=adjustment_text,
|
||||
max_team_members=max_team_members,
|
||||
)
|
||||
parsed = await _invoke_json_with_retry(self._llm, messages[0][1], messages[1][1])
|
||||
return self.parse_workflow_design(parsed)
|
||||
|
||||
def workflow_messages(
|
||||
self,
|
||||
*,
|
||||
requirement: ReportRequirementSnapshot,
|
||||
history: list[dict[str, str]],
|
||||
catalog: AgentCatalogProjection,
|
||||
current_plans: list[dict[str, Any]] | None = None,
|
||||
adjustment_text: str | None = None,
|
||||
max_team_members: int = 8,
|
||||
) -> list[tuple[str, str]]:
|
||||
"""Build the exact prompt used by blocking and streaming planners."""
|
||||
|
||||
fields = {k: v for k, v in requirement.model_dump().items() if v not in (None, "", [])}
|
||||
fields.pop("revision", None)
|
||||
agent_rows = [
|
||||
{
|
||||
"agent_id": item.agent_id,
|
||||
"name": item.name,
|
||||
"description": item.description,
|
||||
"skills": item.skills,
|
||||
"role_hints": item.role_hints,
|
||||
}
|
||||
for item in catalog.agents
|
||||
if item.enabled
|
||||
]
|
||||
history_text = "\n".join(
|
||||
f"{'用户' if item.get('role') == 'human' else '规划师'}: {str(item.get('content') or '')[:500]}"
|
||||
for item in history[-16:]
|
||||
)
|
||||
current = [
|
||||
{
|
||||
"index": index + 1,
|
||||
"title": plan.get("title"),
|
||||
"summary": plan.get("summary"),
|
||||
"nodes": [
|
||||
{
|
||||
"id": node.get("id"),
|
||||
"agent_id": node.get("agent_id"),
|
||||
"agent_name": node.get("role_display_name"),
|
||||
"mission": node.get("mission"),
|
||||
"depends_on": node.get("depends_on") or [],
|
||||
}
|
||||
for node in (plan.get("nodes") or [])
|
||||
],
|
||||
}
|
||||
for index, plan in enumerate(current_plans or [])
|
||||
]
|
||||
system = _DESIGN_BUNDLE_SYSTEM.format(
|
||||
roles=", ".join(MEMBER_ROLES),
|
||||
artifacts="\n".join(f" - {role}: {' / '.join(arts)}" for role, arts in ROLE_ARTIFACTS.items()),
|
||||
gates=", ".join(QUALITY_GATES),
|
||||
max_nodes=min(max_team_members, 6),
|
||||
)
|
||||
prompt = (
|
||||
f"已确认的用户意图:{json.dumps(fields, ensure_ascii=False)}\n\n"
|
||||
f"可用智能体目录(agent_id 只能从这里选择):\n{json.dumps(agent_rows, ensure_ascii=False)}\n\n"
|
||||
f"此前对话:\n{history_text or '(无)'}\n\n"
|
||||
f"当前候选工作流:\n{json.dumps(current, ensure_ascii=False)}\n\n"
|
||||
f"用户本轮调整要求:{adjustment_text or '首次规划,请给出差异明确的候选工作流'}\n\n"
|
||||
"请设计工作流。"
|
||||
)
|
||||
return [("system", system), ("human", prompt)]
|
||||
|
||||
def parse_workflow_design(
|
||||
self,
|
||||
parsed: dict[str, Any] | None,
|
||||
) -> tuple[list[StrategyRoleSet], str] | None:
|
||||
"""Validate a completed planner payload after blocking or SSE output."""
|
||||
|
||||
if parsed is None:
|
||||
return None
|
||||
raw_candidates = parsed.get("candidates")
|
||||
if not isinstance(raw_candidates, list):
|
||||
raw_candidates = [parsed]
|
||||
strategies: list[StrategyRoleSet] = []
|
||||
for raw in raw_candidates[:3]:
|
||||
try:
|
||||
draft = StrategyDraft.model_validate(raw)
|
||||
except ValidationError:
|
||||
continue
|
||||
strategy = _validate_strategy_dag(draft)
|
||||
if strategy is None:
|
||||
continue
|
||||
strategy.recommended = len(strategies) == 0
|
||||
strategies.append(strategy)
|
||||
if not strategies:
|
||||
return None
|
||||
reply = str(parsed.get("reply") or "").strip()
|
||||
if not reply:
|
||||
reply = "已根据可用智能体规划了候选工作流,你可以选择,也可以继续通过对话调整。"
|
||||
return strategies, reply
|
||||
|
||||
def workflow_reply_fallback(self, strategy: StrategyRoleSet) -> str:
|
||||
return (
|
||||
f"我按确认的需求设计了「{strategy.title}」:{strategy.summary}\n"
|
||||
"可以直接采用开始执行;想调整就告诉我(例如「加一条竞品对比线」)。"
|
||||
)
|
||||
|
||||
|
||||
# ── 提示词 ─────────────────────────────────────────────────────────────────
|
||||
|
||||
_CONVERSE_SYSTEM = """你是「报告协作工作台」的规划师智能体。用户想让你组织一个多智能体团队协作产出一份报告,你的任务是先通过自然对话把需求弄清楚,然后(由你自己)设计协作工作流。
|
||||
|
||||
你的对话风格:
|
||||
- 像一位资深顾问:先回应用户刚说的话,再追问。回复里**不要**出现「收到您的报告需求」这类机械开场——用你自己的话自然表达。
|
||||
- 每轮最多追问 2~3 个真正影响方案设计的问题:关注对象与范围、给谁看、必须覆盖的角度、篇幅与深度、时间范围、特殊约束。用户已说清的绝不重复问。
|
||||
- 用户回复后先简短确认你的理解(一两句),再决定是否继续问。
|
||||
- 信息足够时,自然地总结你对需求的把握并判定就绪(action=ready),告诉用户下一步你会为他们设计工作流。
|
||||
|
||||
可用的团队角色(供你构思,不必对用户罗列):{roles}{forced_note}
|
||||
|
||||
每轮严格输出一个 JSON 对象(不要输出 JSON 以外的文字):
|
||||
{{
|
||||
"reply": "给用户看的完整回复(自然对话,直接展示)",
|
||||
"action": "clarify" 或 "ready",
|
||||
"questions": ["追问的问题(与 reply 一致,供系统记录)"],
|
||||
"impact": ["为什么需要问(与 questions 对应)"],
|
||||
"assumptions": ["ready 时:你采用的默认假设"],
|
||||
"requirement": {{"topic": "...", "objective": "...", "audience": "...", "required_angles": ["..."], "time_range": "...", "length_target": "...", "tone": "..."}}
|
||||
}}
|
||||
|
||||
requirement 只填你从对话中能确认的字段(含此前轮次已确认的),其余省略。reply 用中文。"""
|
||||
|
||||
_DESIGN_SYSTEM = """你是「报告协作工作台」的规划师智能体。需求已经与你确认完毕,现在请设计多智能体协作工作流。
|
||||
|
||||
词表约束(结构化部分必须严格遵守):
|
||||
- role_key 只能取:{roles}
|
||||
- 各角色的 output_artifact_type 只能取:
|
||||
{artifacts}
|
||||
- quality_gate_ids 只能取:{gates}
|
||||
|
||||
结构要求:
|
||||
- 2~{max_nodes} 个节点;至少 1 个 writer;正式报告建议加 reviewer。
|
||||
- 研究线(researcher)按角度并行;research → verify → analyze → write → review 是常见主干,可按需求裁剪。
|
||||
- depends_on 引用其他节点的 slot_id;禁止环;至少一个节点 depends_on 为空(起点)。
|
||||
- slot_id 用简短英文(如 research-market / write-main)。mission 写清楚该节点做什么、产出什么。
|
||||
|
||||
严格输出 JSON(不要输出 JSON 以外的文字):
|
||||
{{
|
||||
"reply": "给用户看的介绍:说明你为什么这样设计(对应需求的哪些要求),一两句即可",
|
||||
"strategy": "custom",
|
||||
"title": "方案标题",
|
||||
"summary": "一句话概述团队构成与链路",
|
||||
"rationale": "设计理由",
|
||||
"estimated_duration_seconds": 1500,
|
||||
"estimated_cost_level": "low|medium|high",
|
||||
"quality_gate_ids": ["cite_required"],
|
||||
"nodes": [
|
||||
{{"slot_id": "research-market", "role_key": "researcher", "display_name": "研究员", "angle": "市场份额", "mission": "...", "depends_on": [], "output_artifact_type": "EvidenceBundle", "suggested_tools": ["web_search"]}}
|
||||
]
|
||||
}}"""
|
||||
|
||||
_DESIGN_BUNDLE_SYSTEM = """你是工作流规划智能体。用户意图已经确认,现在必须依据系统提供的智能体名称、描述、技能和角色提示,规划 2~3 个可供选择的多智能体工作流。
|
||||
思考过程保持简洁,分析完成后立刻输出最终 JSON,不要在 JSON 前重复总结。reply、summary、rationale 各不超过 80 个汉字,每个 mission 不超过 60 个汉字。
|
||||
|
||||
规划对象是“由哪些智能体按什么依赖关系协作”。不要继续追问报告内容,不要声称已经开始生成报告。如果用户要求修改某个现有方案,要识别“第几个方案”及替换、删除、添加智能体的要求,并保留其余合理结构。
|
||||
|
||||
硬约束:
|
||||
- 每个节点的 agent_id 必须逐字取自可用智能体目录,并结合 name、description、skills 判断是否胜任。
|
||||
- role_key 只能取:{roles}
|
||||
- output_artifact_type 对应关系:
|
||||
{artifacts}
|
||||
- quality_gate_ids 只能取:{gates}
|
||||
- 每个候选 2~{max_nodes} 个节点,至少包含一个 writer;depends_on 只能引用同候选内的 slot_id,禁止成环。
|
||||
- 2~3 个候选要有清楚差异,例如团队规模、并行度、审核强度或成本,不得仅改标题。
|
||||
|
||||
严格只输出 JSON:
|
||||
{{
|
||||
"reply": "候选工作流已规划完成,并说明可以继续用对话增删或替换智能体",
|
||||
"candidates": [
|
||||
{{
|
||||
"reply": "该候选的简短说明",
|
||||
"strategy": "custom_balanced",
|
||||
"title": "候选工作流标题",
|
||||
"summary": "团队和协作链路概述",
|
||||
"rationale": "为什么这些智能体适合用户意图",
|
||||
"estimated_duration_seconds": 1200,
|
||||
"estimated_cost_level": "low|medium|high",
|
||||
"quality_gate_ids": ["cite_required"],
|
||||
"nodes": [
|
||||
{{"slot_id": "research-a", "agent_id": "目录中的精确ID", "role_key": "researcher",
|
||||
"display_name": "节点职责名", "angle": "研究角度", "mission": "任务和产出",
|
||||
"depends_on": [], "output_artifact_type": "EvidenceBundle", "suggested_tools": ["web_search"]}},
|
||||
{{"slot_id": "write-main", "agent_id": "目录中的精确ID", "role_key": "writer",
|
||||
"display_name": "撰写节点", "mission": "整合产出", "depends_on": ["research-a"],
|
||||
"output_artifact_type": "ReportSectionDraft", "suggested_tools": []}}
|
||||
]
|
||||
}}
|
||||
]
|
||||
}}"""
|
||||
|
||||
|
||||
# ── 工作流草稿校验(词表 + DAG) ──────────────────────────────────────────
|
||||
|
||||
|
||||
def _validate_strategy_dag(draft: StrategyDraft) -> StrategyRoleSet | None:
|
||||
nodes = draft.nodes
|
||||
if not 2 <= len(nodes) <= 8:
|
||||
return None
|
||||
slot_ids = {node.slot_id for node in nodes}
|
||||
if len(slot_ids) != len(nodes):
|
||||
return None
|
||||
if not any(node.role_key == "writer" for node in nodes):
|
||||
return None
|
||||
for node in nodes:
|
||||
if node.role_key not in MEMBER_ROLES:
|
||||
return None
|
||||
if node.output_artifact_type not in ROLE_ARTIFACTS.get(node.role_key, ()):
|
||||
return None
|
||||
for dep in node.depends_on:
|
||||
if dep not in slot_ids or dep == node.slot_id:
|
||||
return None
|
||||
indegree = {node.slot_id: len(node.depends_on) for node in nodes}
|
||||
children: dict[str, list[str]] = {node.slot_id: [] for node in nodes}
|
||||
for node in nodes:
|
||||
for dep in node.depends_on:
|
||||
children[dep].append(node.slot_id)
|
||||
queue = [slot for slot, degree in indegree.items() if degree == 0]
|
||||
seen = 0
|
||||
while queue:
|
||||
current = queue.pop()
|
||||
seen += 1
|
||||
for child in children[current]:
|
||||
indegree[child] -= 1
|
||||
if indegree[child] == 0:
|
||||
queue.append(child)
|
||||
if seen != len(nodes):
|
||||
return None
|
||||
|
||||
gates = [gate for gate in draft.quality_gate_ids if gate in QUALITY_GATES] or ["cite_required"]
|
||||
return StrategyRoleSet(
|
||||
strategy="custom" if draft.strategy == "custom" else f"custom_{draft.strategy[:24]}",
|
||||
title=draft.title[:80],
|
||||
summary=draft.summary[:200],
|
||||
rationale=draft.rationale[:300],
|
||||
estimated_duration_seconds=max(300, min(int(draft.estimated_duration_seconds or 1500), 7200)),
|
||||
estimated_cost_level=draft.estimated_cost_level if draft.estimated_cost_level in {"low", "medium", "high"} else "medium",
|
||||
recommended=True,
|
||||
slots=[
|
||||
RoleSlot(
|
||||
slot_id=node.slot_id,
|
||||
demand=RoleDemand(
|
||||
role_key=node.role_key,
|
||||
agent_id=node.agent_id,
|
||||
display_name=node.display_name[:32] or node.role_key,
|
||||
angle=(node.angle or None),
|
||||
mission=node.mission[:400],
|
||||
depends_on_roles=[],
|
||||
output_artifact_type=node.output_artifact_type,
|
||||
suggested_tools=[tool for tool in node.suggested_tools if tool][:4],
|
||||
),
|
||||
depends_on=list(node.depends_on),
|
||||
)
|
||||
for node in nodes
|
||||
],
|
||||
quality_gate_ids=gates,
|
||||
)
|
||||
@@ -1,10 +1,11 @@
|
||||
"""Fulfill a durable plan_request: catalog → select → assemble → validate → persist.
|
||||
|
||||
Does not start a run. Rule-based until the BE-7 model adapter is wired.
|
||||
Does not start a run. P1.2 起优先由规划师 LLM 生成定制策略,模板为回退。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from typing import Any
|
||||
from uuid import uuid4
|
||||
|
||||
@@ -12,8 +13,9 @@ from app.report_collaboration.contracts.requirements import ReportRequirementSna
|
||||
from app.report_collaboration.planning.assembler import PlanAssembler
|
||||
from app.report_collaboration.planning.catalog import project_agent_catalog
|
||||
from app.report_collaboration.planning.controller import PlanController
|
||||
from app.report_collaboration.planning.planner_agent import LlmFactory
|
||||
from app.report_collaboration.planning.validator import apply_validation, validate_assembled_plan
|
||||
from app.report_collaboration.requirement.defaults import COORDINATOR_NAME, DEFAULT_TITLE
|
||||
from app.report_collaboration.requirement.defaults import DEFAULT_TITLE
|
||||
from deerflow.config.app_config import get_app_config
|
||||
from deerflow.config.report_collaboration_config import ReportCollaborationConfig
|
||||
from deerflow.persistence.report_collaboration import (
|
||||
@@ -22,6 +24,8 @@ from deerflow.persistence.report_collaboration import (
|
||||
ReportCollaborationValidationError,
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_BUSY = frozenset({"running", "awaiting_input", "reviewing", "completed", "failed", "cancelled"})
|
||||
|
||||
|
||||
@@ -51,17 +55,31 @@ class PlanProposalService:
|
||||
*,
|
||||
agent_store: Any | None = None,
|
||||
config: ReportCollaborationConfig | None = None,
|
||||
llm_factory: LlmFactory | None = None,
|
||||
) -> None:
|
||||
self._store = store
|
||||
self._agent_store = agent_store
|
||||
self._config = config
|
||||
self._controller = PlanController()
|
||||
self._assembler = PlanAssembler()
|
||||
self._llm_factory = llm_factory
|
||||
self._llm: Any | None = None
|
||||
self._llm_tried = False
|
||||
|
||||
def _cfg(self) -> ReportCollaborationConfig:
|
||||
return self._config or get_app_config().report_collaboration
|
||||
|
||||
async def fulfill(self, session_id: str, *, user_id: str, command_id: str, idempotency_key: str) -> list[dict[str, Any]]:
|
||||
async def fulfill(
|
||||
self,
|
||||
session_id: str,
|
||||
*,
|
||||
user_id: str,
|
||||
command_id: str,
|
||||
idempotency_key: str,
|
||||
adjustment_text: str | None = None,
|
||||
precomputed_design: tuple[list[Any], str] | None = None,
|
||||
planner_reasoning: str | None = None,
|
||||
planner_steps: list[dict[str, Any]] | None = None,
|
||||
) -> list[dict[str, Any]]:
|
||||
record = await self._store.get_session_record(session_id)
|
||||
if record is None:
|
||||
raise ReportCollaborationValidationError("NOT_FOUND", "会话不存在")
|
||||
@@ -71,12 +89,28 @@ class PlanProposalService:
|
||||
raise ReportCollaborationConflictError("SESSION_BUSY", "当前会话状态不允许生成方案", current_revision=int(record.get("requirement_revision") or 0))
|
||||
|
||||
try:
|
||||
return await self._build(session_id, user_id=user_id, command_id=command_id, idempotency_key=idempotency_key, record=record)
|
||||
requirement_state = record.get("requirement_json")
|
||||
if not isinstance(requirement_state, dict) or requirement_state.get("ready_to_plan") is not True:
|
||||
raise ReportCollaborationValidationError(
|
||||
"REQUIREMENT_NOT_READY",
|
||||
"规划师尚未确认完整意图,请先继续回答澄清问题",
|
||||
)
|
||||
return await self._build(
|
||||
session_id,
|
||||
user_id=user_id,
|
||||
command_id=command_id,
|
||||
idempotency_key=idempotency_key,
|
||||
record=record,
|
||||
adjustment_text=adjustment_text,
|
||||
precomputed_design=precomputed_design,
|
||||
planner_reasoning=planner_reasoning,
|
||||
planner_steps=planner_steps,
|
||||
)
|
||||
except Exception as exc:
|
||||
await self._fail_command(session_id, command_id, exc)
|
||||
await self.fail_command(session_id, command_id, exc)
|
||||
raise
|
||||
|
||||
async def _fail_command(self, session_id: str, command_id: str, exc: Exception) -> None:
|
||||
async def fail_command(self, session_id: str, command_id: str, exc: Exception) -> None:
|
||||
try:
|
||||
await self._store.update_command_status(command_id, status="failed", error=str(exc)[:500])
|
||||
record = await self._store.get_session_record(session_id)
|
||||
@@ -106,16 +140,60 @@ class PlanProposalService:
|
||||
command_id: str,
|
||||
idempotency_key: str,
|
||||
record: dict[str, Any],
|
||||
adjustment_text: str | None,
|
||||
precomputed_design: tuple[list[Any], str] | None,
|
||||
planner_reasoning: str | None,
|
||||
planner_steps: list[dict[str, Any]] | None,
|
||||
) -> list[dict[str, Any]]:
|
||||
requirement = requirement_from_session(record)
|
||||
cfg = self._cfg()
|
||||
catalog = await project_agent_catalog(user_id=user_id, config=cfg, agent_store=self._agent_store)
|
||||
strategies = self._controller.propose(
|
||||
requirement,
|
||||
max_parallel_tasks=cfg.max_parallel_tasks,
|
||||
max_team_members=cfg.max_team_members,
|
||||
)
|
||||
group_id = f"rpg_{uuid4().hex[:12]}"
|
||||
|
||||
# 规划师智能体带着完整对话、当前候选和真实智能体目录设计候选工作流。
|
||||
# 确定性策略仅用于补足候选数量,最终仍会绑定真实目录中的智能体。
|
||||
from app.report_collaboration.planning.planner_agent import PlannerAgent
|
||||
|
||||
history = [
|
||||
{"role": "human" if item.get("role") == "human" else "ai", "content": str(item.get("content") or "")}
|
||||
for item in await self._store.list_messages(session_id)
|
||||
]
|
||||
current_plans = [
|
||||
item
|
||||
for item in await self._store.list_plans(session_id)
|
||||
if item.get("status") in {"proposed", "selected"}
|
||||
]
|
||||
designed = precomputed_design
|
||||
if designed is None:
|
||||
designed = await PlannerAgent(self.planner_llm()).design_workflows(
|
||||
requirement=requirement,
|
||||
history=history,
|
||||
catalog=catalog,
|
||||
current_plans=current_plans,
|
||||
adjustment_text=adjustment_text,
|
||||
max_team_members=cfg.max_team_members,
|
||||
)
|
||||
if designed is None:
|
||||
raise ReportCollaborationValidationError(
|
||||
"PLANNER_UNAVAILABLE", "规划师智能体未能生成有效工作流,请重试或换个说法再试"
|
||||
)
|
||||
strategies: list[Any] = list(designed[0])
|
||||
planner_reply: str | None = designed[1]
|
||||
if len(strategies) < 2:
|
||||
existing = {item.strategy for item in strategies}
|
||||
for fallback in PlanController().propose(
|
||||
requirement,
|
||||
max_parallel_tasks=cfg.max_parallel_tasks,
|
||||
max_team_members=cfg.max_team_members,
|
||||
):
|
||||
if fallback.strategy in existing:
|
||||
continue
|
||||
fallback.recommended = not strategies
|
||||
strategies.append(fallback)
|
||||
existing.add(fallback.strategy)
|
||||
if len(strategies) >= 3:
|
||||
break
|
||||
|
||||
assembled_list = [
|
||||
self._assembler.assemble(
|
||||
strategy,
|
||||
@@ -140,13 +218,50 @@ class PlanProposalService:
|
||||
for candidate in persisted:
|
||||
saved.append(await self._store.insert_plan(session_id, candidate.model_dump()))
|
||||
await self._store.update_command_status(command_id, status="completed")
|
||||
content = planner_reply or "候选工作流已规划完成,你可以选择一个方案,也可以继续通过对话调整智能体结构。"
|
||||
await self._store.create_message(
|
||||
session_id,
|
||||
role="ai",
|
||||
content="已根据当前需求生成 3 个候选协作方案。请选择其中一个后再开始执行;选择方案不会自动开跑。",
|
||||
content=content,
|
||||
idempotency_key=f"{idempotency_key}:plans",
|
||||
name=COORDINATOR_NAME,
|
||||
metadata={"plan_request_command_id": command_id, "proposal_group_id": group_id},
|
||||
name="工作流规划师",
|
||||
metadata={
|
||||
"plan_request_command_id": command_id,
|
||||
"proposal_group_id": group_id,
|
||||
"plan_source": "planner_agent",
|
||||
**({"reasoning_content": planner_reasoning} if planner_reasoning else {}),
|
||||
},
|
||||
tool_calls=planner_steps or [],
|
||||
completed=True,
|
||||
)
|
||||
return saved
|
||||
|
||||
def planner_llm(self) -> Any:
|
||||
"""规划师模型:注入优先(测试);否则按 planner_llm_enabled 懒构建。不可用即抛错。"""
|
||||
|
||||
if self._llm_factory is not None:
|
||||
llm = self._llm_factory()
|
||||
if llm is None:
|
||||
raise ReportCollaborationValidationError("PLANNER_UNAVAILABLE", "规划师智能体不可用,请检查模型配置")
|
||||
return llm
|
||||
try:
|
||||
if not (self._config or get_app_config().report_collaboration).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._llm_tried:
|
||||
self._llm_tried = True
|
||||
try:
|
||||
from app.report_collaboration.planning.planner_agent import build_planner_llm
|
||||
|
||||
self._llm = build_planner_llm()
|
||||
except Exception as exc:
|
||||
logger.warning("rc planner agent llm build failed: %s", exc)
|
||||
self._llm = None
|
||||
if self._llm is None:
|
||||
raise ReportCollaborationValidationError("PLANNER_UNAVAILABLE", "规划师智能体不可用,请检查模型配置")
|
||||
return self._llm
|
||||
Reference in new issue
Block a user