初始化
This commit is contained in:
1 parent
34474bd5fc
commit
b638b541d0
3008 files changed
+837699
No files matched your search
@@ -0,0 +1,22 @@
|
||||
"""Candidate-plan pipeline: catalog, selector, controller, assembler, validator."""
|
||||
|
||||
from app.report_collaboration.planning.assembler import AssembledPlan, PlanAssembler
|
||||
from app.report_collaboration.planning.catalog import AgentCatalogProjection, CatalogAgent, project_agent_catalog
|
||||
from app.report_collaboration.planning.controller import PlanController, StrategyRoleSet
|
||||
from app.report_collaboration.planning.selector import AgentSelector
|
||||
from app.report_collaboration.planning.service import PlanProposalService, requirement_from_session
|
||||
from app.report_collaboration.planning.validator import validate_assembled_plan
|
||||
|
||||
__all__ = [
|
||||
"AgentCatalogProjection",
|
||||
"AgentSelector",
|
||||
"AssembledPlan",
|
||||
"CatalogAgent",
|
||||
"PlanAssembler",
|
||||
"PlanController",
|
||||
"PlanProposalService",
|
||||
"StrategyRoleSet",
|
||||
"project_agent_catalog",
|
||||
"requirement_from_session",
|
||||
"validate_assembled_plan",
|
||||
]
|
||||
@@ -0,0 +1,158 @@
|
||||
"""Bind RoleDemand slots to catalog agents, allowlisted tools, budgets and quality gates."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from uuid import uuid4
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
|
||||
from app.report_collaboration.contracts.plans import PlanEdge, PlanNode, PlanRole, PlanValidation, QualityGateSpec, ReportPlanCandidate
|
||||
from app.report_collaboration.contracts.requirements import ReportRequirementSnapshot
|
||||
from app.report_collaboration.planning.catalog import AgentCatalogProjection
|
||||
from app.report_collaboration.planning.controller import StrategyRoleSet
|
||||
from app.report_collaboration.planning.selector import AgentSelector
|
||||
from deerflow.config.report_collaboration_config import ReportCollaborationConfig
|
||||
|
||||
_GATE_LABELS: dict[str, tuple[str, str]] = {
|
||||
"cite_required": ("来源核验", "关键事实必须给出可核对来源"),
|
||||
"dual_verification": ("双重核验", "高风险结论需两条独立核验链"),
|
||||
"independent_review": ("独立审稿", "审稿员不得覆盖报告正文,只输出 ReviewDecision"),
|
||||
"coverage_matrix": ("角度覆盖", "必选角度均需有对应证据与分析"),
|
||||
}
|
||||
|
||||
_ACCEPTANCE: dict[str, list[str]] = {
|
||||
"EvidenceBundle": ["至少包含带 source_id 的事实或摘录", "覆盖本节点角度,缺口写入 coverage_gaps"],
|
||||
"VerificationResult": ["关键数字均标注支持或反对证据", "冲突来源不得省略"],
|
||||
"AngleAnalysis": ["结论必须引用已核验证据 ID", "写明假设与局限"],
|
||||
"ReportVersion": ["模板章节完整", "关键事实带引用"],
|
||||
"ReviewDecision": ["问题可映射到具体节点或章节", "不得改写报告正文"],
|
||||
}
|
||||
|
||||
|
||||
class NodeBinding(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
node_id: str
|
||||
agent_id: str
|
||||
agent_name: str
|
||||
role_key: str
|
||||
reason: str
|
||||
|
||||
|
||||
class AssembledPlan(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
candidate: ReportPlanCandidate
|
||||
bindings: list[NodeBinding] = Field(default_factory=list)
|
||||
|
||||
|
||||
def _tools_for(role_key: str, suggested: list[str], allowed: list[str]) -> list[str]:
|
||||
wanted = list(suggested)
|
||||
if role_key == "researcher":
|
||||
wanted = ["web_search", "web_fetch", "knowledge_search"]
|
||||
elif role_key in {"verifier", "analyst", "synthesizer"}:
|
||||
wanted = ["knowledge_search"]
|
||||
else:
|
||||
wanted = []
|
||||
return [name for name in wanted if name in allowed]
|
||||
|
||||
|
||||
def _input_types(output_by_id: dict[str, str], depends_on: list[str]) -> list[str]:
|
||||
types: list[str] = []
|
||||
for node_id in depends_on:
|
||||
artifact = output_by_id.get(node_id)
|
||||
if artifact and artifact not in types:
|
||||
types.append(artifact)
|
||||
return types
|
||||
|
||||
|
||||
class PlanAssembler:
|
||||
def __init__(self, *, selector: AgentSelector | None = None) -> None:
|
||||
self._selector = selector or AgentSelector()
|
||||
|
||||
def assemble(
|
||||
self,
|
||||
strategy: StrategyRoleSet,
|
||||
*,
|
||||
requirement: ReportRequirementSnapshot,
|
||||
catalog: AgentCatalogProjection,
|
||||
config: ReportCollaborationConfig,
|
||||
proposal_group_id: str,
|
||||
revision: int = 1,
|
||||
) -> AssembledPlan:
|
||||
used_user_ids: set[str] = set()
|
||||
bindings: list[NodeBinding] = []
|
||||
nodes: list[PlanNode] = []
|
||||
roles_by_key: dict[str, PlanRole] = {}
|
||||
output_by_id: dict[str, str] = {}
|
||||
|
||||
for slot in strategy.slots:
|
||||
demand = slot.demand
|
||||
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)
|
||||
artifact = demand.output_artifact_type
|
||||
criteria = list(_ACCEPTANCE.get(artifact, ["成果必须通过对应 Schema 与验收器"]))
|
||||
if demand.angle:
|
||||
criteria.append(f"覆盖角度:{demand.angle}")
|
||||
node = PlanNode(
|
||||
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,
|
||||
angle=demand.angle,
|
||||
depends_on=list(slot.depends_on),
|
||||
mission=demand.mission,
|
||||
output_artifact_type=artifact,
|
||||
input_artifact_types=_input_types(output_by_id, slot.depends_on),
|
||||
allowed_tools=tools,
|
||||
acceptance_criteria=criteria,
|
||||
)
|
||||
output_by_id[slot.slot_id] = artifact
|
||||
nodes.append(node)
|
||||
bindings.append(
|
||||
NodeBinding(
|
||||
node_id=slot.slot_id,
|
||||
agent_id=agent.agent_id,
|
||||
agent_name=agent.name,
|
||||
role_key=demand.role_key,
|
||||
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,
|
||||
responsibility=demand.mission,
|
||||
angle=demand.angle,
|
||||
)
|
||||
|
||||
edges = [PlanEdge(source=dep, target=node.id) for node in nodes for dep in node.depends_on]
|
||||
gates = [
|
||||
QualityGateSpec(id=gate_id, label=_GATE_LABELS.get(gate_id, (gate_id, ""))[0], description=_GATE_LABELS.get(gate_id, (gate_id, ""))[1] or None)
|
||||
for gate_id in strategy.quality_gate_ids
|
||||
]
|
||||
bound_names = "、".join(dict.fromkeys(item.agent_name for item in bindings))
|
||||
rationale = f"{strategy.rationale} 绑定:{bound_names}。"
|
||||
candidate = ReportPlanCandidate(
|
||||
id=f"rcp_{strategy.strategy}_{uuid4().hex[:10]}",
|
||||
proposal_group_id=proposal_group_id,
|
||||
title=strategy.title,
|
||||
strategy=strategy.strategy,
|
||||
summary=strategy.summary,
|
||||
rationale=rationale,
|
||||
recommended=strategy.recommended,
|
||||
estimated_duration_seconds=strategy.estimated_duration_seconds,
|
||||
estimated_cost_level=strategy.estimated_cost_level, # type: ignore[arg-type]
|
||||
requirement_revision=requirement.revision,
|
||||
roles=list(roles_by_key.values()),
|
||||
nodes=nodes,
|
||||
edges=edges,
|
||||
quality_gates=gates,
|
||||
report_structure_id=requirement.report_structure_id,
|
||||
validation=PlanValidation(ok=True, errors=[]),
|
||||
revision=revision,
|
||||
status="proposed",
|
||||
)
|
||||
return AssembledPlan(candidate=candidate, bindings=bindings)
|
||||
@@ -0,0 +1,163 @@
|
||||
"""User-visible agent/skill/tool projection. Never includes SOUL or credentials."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Literal
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
|
||||
from deerflow.config.report_collaboration_config import ReportCollaborationConfig
|
||||
|
||||
_SECRET_KEYS = frozenset(
|
||||
{
|
||||
"soul",
|
||||
"soul_md",
|
||||
"soul_markdown",
|
||||
"system_prompt",
|
||||
"api_key",
|
||||
"api_keys",
|
||||
"base_url",
|
||||
"baseurl",
|
||||
"password",
|
||||
"secret",
|
||||
"secrets",
|
||||
"token",
|
||||
"access_token",
|
||||
"headers",
|
||||
"credentials",
|
||||
"authorization",
|
||||
"private_key",
|
||||
}
|
||||
)
|
||||
|
||||
BUILTIN_ROLE_PROFILES: tuple[tuple[str, str, str, str], ...] = (
|
||||
("rc.role.coordinator", "协调者", "coordinator", "提出候选计划、澄清与修复建议;不能自行改库或宣告节点完成"),
|
||||
("rc.role.researcher", "研究员", "researcher", "检索并整理带出处、日期和摘录的证据"),
|
||||
("rc.role.verifier", "核验员", "verifier", "核对数字口径、时效、冲突来源,输出可用结论"),
|
||||
("rc.role.analyst", "分析员", "analyst", "按角度形成有证据支撑的判断、假设和局限"),
|
||||
("rc.role.synthesizer", "综合员", "synthesizer", "把分角度结论收成论证主线和章节大纲"),
|
||||
("rc.role.writer", "撰写员", "writer", "按模板写出带引用的报告正文"),
|
||||
("rc.role.reviewer", "审稿员", "reviewer", "独立审稿,只输出 ReviewDecision,不覆盖报告"),
|
||||
("rc.role.reviser", "修订员", "reviser", "按审稿意见定向返工指定章节或节点"),
|
||||
)
|
||||
|
||||
|
||||
class CatalogAgent(BaseModel):
|
||||
"""Safe metadata a planner may see. No SOUL, keys, or provider URLs."""
|
||||
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
agent_id: str
|
||||
name: str
|
||||
description: str
|
||||
skills: list[str] = Field(default_factory=list)
|
||||
tool_groups: list[str] = Field(default_factory=list)
|
||||
role_hints: list[str] = Field(default_factory=list)
|
||||
source: Literal["user", "builtin_role"]
|
||||
enabled: bool = True
|
||||
|
||||
|
||||
class CatalogTool(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
name: str
|
||||
kind: Literal["web", "knowledge", "artifact", "other"] = "other"
|
||||
|
||||
|
||||
class AgentCatalogProjection(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
agents: list[CatalogAgent]
|
||||
tools: list[CatalogTool]
|
||||
allowed_tool_names: list[str]
|
||||
|
||||
|
||||
def _kind_for_tool(name: str) -> Literal["web", "knowledge", "artifact", "other"]:
|
||||
if name in {"web_search", "web_fetch"}:
|
||||
return "web"
|
||||
if name in {"knowledge_search", "wiki_search"}:
|
||||
return "knowledge"
|
||||
if name in {"submit_artifact", "read_artifact"}:
|
||||
return "artifact"
|
||||
return "other"
|
||||
|
||||
|
||||
def _strip_secrets(row: dict[str, Any]) -> dict[str, Any]:
|
||||
return {key: value for key, value in row.items() if key.lower() not in _SECRET_KEYS}
|
||||
|
||||
|
||||
def builtin_role_agents() -> list[CatalogAgent]:
|
||||
return [
|
||||
CatalogAgent(
|
||||
agent_id=agent_id,
|
||||
name=name,
|
||||
description=description,
|
||||
role_hints=[role_key],
|
||||
source="builtin_role",
|
||||
)
|
||||
for agent_id, name, role_key, description in BUILTIN_ROLE_PROFILES
|
||||
]
|
||||
|
||||
|
||||
def _role_hints_from_text(*parts: str) -> list[str]:
|
||||
blob = " ".join(part or "" for part in parts).lower()
|
||||
hints: list[str] = []
|
||||
mapping: tuple[tuple[str, tuple[str, ...]], ...] = (
|
||||
("researcher", ("检索", "研究", "搜索", "research", "search", "情报")),
|
||||
("verifier", ("核验", "校验", "核实", "verify", "fact")),
|
||||
("analyst", ("分析", "研判", "analyst")),
|
||||
("synthesizer", ("综合", "大纲", "synthesis")),
|
||||
("writer", ("写作", "撰写", "撰稿", "write")),
|
||||
("reviewer", ("审稿", "评审", "review")),
|
||||
("reviser", ("修订", "润色", "revise")),
|
||||
("coordinator", ("协调", "规划", "coordinator")),
|
||||
)
|
||||
for role_key, keywords in mapping:
|
||||
if any(keyword.lower() in blob for keyword in keywords):
|
||||
hints.append(role_key)
|
||||
return hints
|
||||
|
||||
|
||||
async def project_agent_catalog(
|
||||
*,
|
||||
user_id: str,
|
||||
config: ReportCollaborationConfig,
|
||||
agent_store: Any | None = None,
|
||||
) -> AgentCatalogProjection:
|
||||
"""Read enabled, user-visible agents plus builtin role profiles."""
|
||||
|
||||
tools = [CatalogTool(name=name, kind=_kind_for_tool(name)) for name in config.allowed_tools]
|
||||
agents = builtin_role_agents()
|
||||
if agent_store is None:
|
||||
return AgentCatalogProjection(agents=agents, tools=tools, allowed_tool_names=list(config.allowed_tools))
|
||||
|
||||
visible = await agent_store.list_visible(user_id)
|
||||
extras: dict[str, dict[str, Any]] = {}
|
||||
getter = getattr(agent_store, "get_extras_for", None)
|
||||
if callable(getter) and visible:
|
||||
extras = await getter([str(row.get("id")) for row in visible if row.get("id")])
|
||||
seen = {item.agent_id for item in agents}
|
||||
for raw in visible:
|
||||
row = _strip_secrets(dict(raw or {}))
|
||||
agent_id = str(row.get("id") or "").strip()
|
||||
if not agent_id or agent_id in seen:
|
||||
continue
|
||||
extra = extras.get(agent_id) or {}
|
||||
skills = [str(item) for item in (extra.get("skills") or []) if item]
|
||||
tool_groups = [str(item) for item in (extra.get("tool_groups") or []) if item]
|
||||
description = str(row.get("description") or "")
|
||||
name = str(row.get("name") or agent_id)
|
||||
agents.append(
|
||||
CatalogAgent(
|
||||
agent_id=agent_id,
|
||||
name=name,
|
||||
description=description[:500],
|
||||
skills=skills,
|
||||
tool_groups=tool_groups,
|
||||
role_hints=_role_hints_from_text(name, description, " ".join(skills)),
|
||||
source="user",
|
||||
enabled=True,
|
||||
)
|
||||
)
|
||||
seen.add(agent_id)
|
||||
return AgentCatalogProjection(agents=agents, tools=tools, allowed_tool_names=list(config.allowed_tools))
|
||||
@@ -0,0 +1,313 @@
|
||||
"""PlanController: 2–3 strategy RoleDemand graphs. Models never emit executable graphs."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
|
||||
from app.report_collaboration.contracts.plans import RoleDemand
|
||||
from app.report_collaboration.contracts.requirements import ReportRequirementSnapshot
|
||||
from app.report_collaboration.requirement.defaults import DEFAULT_ANGLES
|
||||
|
||||
STRATEGIES: tuple[str, ...] = ("balanced_review", "parallel_depth", "focused_fast")
|
||||
|
||||
|
||||
class RoleSlot(BaseModel):
|
||||
"""Controller-local slot. ``demand`` is what a model would emit; ``slot_id`` is server-assigned."""
|
||||
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
slot_id: str
|
||||
demand: RoleDemand
|
||||
depends_on: list[str] = Field(default_factory=list)
|
||||
|
||||
|
||||
class StrategyRoleSet(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
strategy: str
|
||||
title: str
|
||||
summary: str
|
||||
rationale: str
|
||||
estimated_duration_seconds: int
|
||||
estimated_cost_level: str
|
||||
recommended: bool = False
|
||||
slots: list[RoleSlot] = Field(default_factory=list)
|
||||
quality_gate_ids: list[str] = Field(default_factory=list)
|
||||
|
||||
|
||||
def resolve_angles(requirement: ReportRequirementSnapshot, count: int) -> list[str]:
|
||||
excluded = {item.strip() for item in requirement.excluded_angles if item and item.strip()}
|
||||
source = [item for item in requirement.required_angles if item.strip() and item.strip() not in excluded]
|
||||
if not source:
|
||||
source = [item for item in DEFAULT_ANGLES if item not in excluded]
|
||||
if not source:
|
||||
source = ["综合趋势"]
|
||||
if count <= 1:
|
||||
return source[:1]
|
||||
picked = source[:count]
|
||||
return picked if picked else source[:1]
|
||||
|
||||
|
||||
def _research_demand(angle: str) -> RoleDemand:
|
||||
return RoleDemand(
|
||||
role_key="researcher",
|
||||
display_name="研究员",
|
||||
angle=angle,
|
||||
mission=f"检索并整理「{angle}」的事实、来源、日期和摘录,覆盖冲突与缺口",
|
||||
depends_on_roles=[],
|
||||
output_artifact_type="EvidenceBundle",
|
||||
suggested_tools=["web_search", "web_fetch", "knowledge_search"],
|
||||
)
|
||||
|
||||
|
||||
class PlanController:
|
||||
"""Deterministic strategy templates. A later planner model may only fill RoleDemand."""
|
||||
|
||||
def propose(self, requirement: ReportRequirementSnapshot, *, max_parallel_tasks: int, max_team_members: int) -> list[StrategyRoleSet]:
|
||||
topic = requirement.topic
|
||||
focused_angles = resolve_angles(requirement, 1)
|
||||
balanced_n = min(2, max(1, max_parallel_tasks))
|
||||
parallel_n = min(3, max(1, max_parallel_tasks), max(1, max_team_members - 5))
|
||||
balanced_angles = resolve_angles(requirement, balanced_n)
|
||||
parallel_angles = resolve_angles(requirement, parallel_n)
|
||||
return [
|
||||
self._balanced(topic, balanced_angles),
|
||||
self._parallel(topic, parallel_angles),
|
||||
self._focused(topic, focused_angles),
|
||||
]
|
||||
|
||||
def _balanced(self, topic: str, angles: list[str]) -> StrategyRoleSet:
|
||||
slots: list[RoleSlot] = []
|
||||
research_ids: list[str] = []
|
||||
for index, angle in enumerate(angles):
|
||||
slot_id = f"research-{index}"
|
||||
research_ids.append(slot_id)
|
||||
slots.append(
|
||||
RoleSlot(
|
||||
slot_id=slot_id,
|
||||
demand=_research_demand(angle),
|
||||
depends_on=[],
|
||||
)
|
||||
)
|
||||
slots.append(
|
||||
RoleSlot(
|
||||
slot_id="verify",
|
||||
demand=RoleDemand(
|
||||
role_key="verifier",
|
||||
display_name="核验员",
|
||||
mission="交叉核验关键数字口径、时效与冲突来源",
|
||||
depends_on_roles=["researcher"],
|
||||
output_artifact_type="VerificationResult",
|
||||
),
|
||||
depends_on=list(research_ids),
|
||||
)
|
||||
)
|
||||
slots.append(
|
||||
RoleSlot(
|
||||
slot_id="analyze",
|
||||
demand=RoleDemand(
|
||||
role_key="analyst",
|
||||
display_name="分析员",
|
||||
mission=f"综合各角度证据,形成关于「{topic}」的判断、假设和局限",
|
||||
depends_on_roles=["verifier"],
|
||||
output_artifact_type="AngleAnalysis",
|
||||
),
|
||||
depends_on=["verify"],
|
||||
)
|
||||
)
|
||||
slots.append(
|
||||
RoleSlot(
|
||||
slot_id="write",
|
||||
demand=RoleDemand(
|
||||
role_key="writer",
|
||||
display_name="撰写员",
|
||||
mission="按模板撰写带引用的完整报告",
|
||||
depends_on_roles=["analyst"],
|
||||
output_artifact_type="ReportVersion",
|
||||
),
|
||||
depends_on=["analyze"],
|
||||
)
|
||||
)
|
||||
slots.append(
|
||||
RoleSlot(
|
||||
slot_id="review",
|
||||
demand=RoleDemand(
|
||||
role_key="reviewer",
|
||||
display_name="审稿员",
|
||||
mission="独立审稿:结论与证据一致、章节完整",
|
||||
depends_on_roles=["writer"],
|
||||
output_artifact_type="ReviewDecision",
|
||||
),
|
||||
depends_on=["write"],
|
||||
)
|
||||
)
|
||||
return StrategyRoleSet(
|
||||
strategy="balanced_review",
|
||||
title="均衡协作 · 研究核验写作审稿全链路",
|
||||
summary=f"{len(angles)} 条研究线 + 交叉核验 + 分析 + 写作 + 独立审稿,质量与成本均衡。",
|
||||
rationale="在覆盖主要角度的同时控制团队规模,适合大多数正式报告。",
|
||||
estimated_duration_seconds=1500,
|
||||
estimated_cost_level="medium",
|
||||
recommended=True,
|
||||
slots=slots,
|
||||
quality_gate_ids=["cite_required", "independent_review"],
|
||||
)
|
||||
|
||||
def _parallel(self, topic: str, angles: list[str]) -> StrategyRoleSet:
|
||||
slots: list[RoleSlot] = []
|
||||
research_ids: list[str] = []
|
||||
for index, angle in enumerate(angles):
|
||||
slot_id = f"research-{index}"
|
||||
research_ids.append(slot_id)
|
||||
slots.append(RoleSlot(slot_id=slot_id, demand=_research_demand(angle), depends_on=[]))
|
||||
mid = max(1, len(research_ids) // 2)
|
||||
first, second = research_ids[:mid], research_ids[mid:] or research_ids[:1]
|
||||
slots.append(
|
||||
RoleSlot(
|
||||
slot_id="verify-a",
|
||||
demand=RoleDemand(
|
||||
role_key="verifier",
|
||||
display_name="核验员",
|
||||
angle="主证据链",
|
||||
mission="核验前半研究线的口径、时效与冲突",
|
||||
depends_on_roles=["researcher"],
|
||||
output_artifact_type="VerificationResult",
|
||||
),
|
||||
depends_on=list(first),
|
||||
)
|
||||
)
|
||||
slots.append(
|
||||
RoleSlot(
|
||||
slot_id="verify-b",
|
||||
demand=RoleDemand(
|
||||
role_key="verifier",
|
||||
display_name="核验员",
|
||||
angle="交叉证据链",
|
||||
mission="二次核验其余研究线与高风险结论",
|
||||
depends_on_roles=["researcher"],
|
||||
output_artifact_type="VerificationResult",
|
||||
),
|
||||
depends_on=list(second),
|
||||
)
|
||||
)
|
||||
slots.append(
|
||||
RoleSlot(
|
||||
slot_id="analyze",
|
||||
demand=RoleDemand(
|
||||
role_key="analyst",
|
||||
display_name="分析员",
|
||||
mission=f"分角度深入分析「{topic}」,并给出 12–24 个月展望",
|
||||
depends_on_roles=["verifier"],
|
||||
output_artifact_type="AngleAnalysis",
|
||||
),
|
||||
depends_on=["verify-a", "verify-b"],
|
||||
)
|
||||
)
|
||||
slots.append(
|
||||
RoleSlot(
|
||||
slot_id="write",
|
||||
demand=RoleDemand(
|
||||
role_key="writer",
|
||||
display_name="撰写员",
|
||||
mission="撰写完整报告",
|
||||
depends_on_roles=["analyst"],
|
||||
output_artifact_type="ReportVersion",
|
||||
),
|
||||
depends_on=["analyze"],
|
||||
)
|
||||
)
|
||||
slots.append(
|
||||
RoleSlot(
|
||||
slot_id="review",
|
||||
demand=RoleDemand(
|
||||
role_key="reviewer",
|
||||
display_name="审稿员",
|
||||
mission="高风险场景独立审稿",
|
||||
depends_on_roles=["writer"],
|
||||
output_artifact_type="ReviewDecision",
|
||||
),
|
||||
depends_on=["write"],
|
||||
)
|
||||
)
|
||||
return StrategyRoleSet(
|
||||
strategy="parallel_depth",
|
||||
title="深度并行 · 多角度双重核验",
|
||||
summary=f"{len(angles)} 条并行研究 + 双重核验 + 分析 + 写作 + 审稿,覆盖更广、成本更高。",
|
||||
rationale="面向高风险决策:角度覆盖与证据强度优先,接受更高成本与时长。",
|
||||
estimated_duration_seconds=2400,
|
||||
estimated_cost_level="high",
|
||||
slots=slots,
|
||||
quality_gate_ids=["cite_required", "dual_verification", "independent_review", "coverage_matrix"],
|
||||
)
|
||||
|
||||
def _focused(self, topic: str, angles: list[str]) -> StrategyRoleSet:
|
||||
angle = angles[0]
|
||||
slots = [
|
||||
RoleSlot(
|
||||
slot_id="research-0",
|
||||
demand=RoleDemand(
|
||||
role_key="researcher",
|
||||
display_name="研究员",
|
||||
angle=angle,
|
||||
mission=f"按指定角度「{angle}」检索证据,范围收窄",
|
||||
depends_on_roles=[],
|
||||
output_artifact_type="EvidenceBundle",
|
||||
suggested_tools=["web_search", "web_fetch", "knowledge_search"],
|
||||
),
|
||||
depends_on=[],
|
||||
),
|
||||
RoleSlot(
|
||||
slot_id="verify",
|
||||
demand=RoleDemand(
|
||||
role_key="verifier",
|
||||
display_name="核验员",
|
||||
mission="核验关键事实与数字来源",
|
||||
depends_on_roles=["researcher"],
|
||||
output_artifact_type="VerificationResult",
|
||||
),
|
||||
depends_on=["research-0"],
|
||||
),
|
||||
RoleSlot(
|
||||
slot_id="analyze",
|
||||
demand=RoleDemand(
|
||||
role_key="analyst",
|
||||
display_name="分析员",
|
||||
mission=f"形成关于「{topic}」的聚焦结论",
|
||||
depends_on_roles=["verifier"],
|
||||
output_artifact_type="AngleAnalysis",
|
||||
),
|
||||
depends_on=["verify"],
|
||||
),
|
||||
RoleSlot(
|
||||
slot_id="write",
|
||||
demand=RoleDemand(
|
||||
role_key="writer",
|
||||
display_name="撰写员",
|
||||
mission="快速产出带引用的报告",
|
||||
depends_on_roles=["analyst"],
|
||||
output_artifact_type="ReportVersion",
|
||||
),
|
||||
depends_on=["analyze"],
|
||||
),
|
||||
RoleSlot(
|
||||
slot_id="review",
|
||||
demand=RoleDemand(
|
||||
role_key="reviewer",
|
||||
display_name="审稿员",
|
||||
mission="快速审稿,拦截高危问题",
|
||||
depends_on_roles=["writer"],
|
||||
output_artifact_type="ReviewDecision",
|
||||
),
|
||||
depends_on=["write"],
|
||||
),
|
||||
]
|
||||
return StrategyRoleSet(
|
||||
strategy="focused_fast",
|
||||
title="快速聚焦 · 窄范围短链路",
|
||||
summary="单研究线 + 核验 + 分析 + 写作 + 审稿,保留引用核验与审稿,最快出稿。",
|
||||
rationale="适合时间紧、角度已知、需要可信结论而非全面覆盖的场景。",
|
||||
estimated_duration_seconds=800,
|
||||
estimated_cost_level="low",
|
||||
slots=slots,
|
||||
quality_gate_ids=["cite_required", "independent_review"],
|
||||
)
|
||||
@@ -0,0 +1,71 @@
|
||||
"""Rule filter plus deterministic rerank. Does not call a model (BE-7 adapter not wired)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app.report_collaboration.planning.catalog import CatalogAgent
|
||||
|
||||
_ROLE_KEYWORDS: dict[str, tuple[str, ...]] = {
|
||||
"coordinator": ("协调", "规划", "coordinator"),
|
||||
"researcher": ("检索", "研究", "搜索", "research", "search", "情报"),
|
||||
"verifier": ("核验", "校验", "核实", "verify", "fact"),
|
||||
"analyst": ("分析", "研判", "analyst"),
|
||||
"synthesizer": ("综合", "大纲", "synthesis"),
|
||||
"writer": ("写作", "撰写", "撰稿", "write"),
|
||||
"reviewer": ("审稿", "评审", "review"),
|
||||
"reviser": ("修订", "润色", "revise"),
|
||||
}
|
||||
|
||||
|
||||
def score_agent_for_role(agent: CatalogAgent, role_key: str) -> tuple[int, str]:
|
||||
"""Return (score, reason). Builtin matching role is always selectable as fallback."""
|
||||
|
||||
if not agent.enabled:
|
||||
return 0, "未启用"
|
||||
blob = f"{agent.name} {agent.description} {' '.join(agent.skills)} {' '.join(agent.tool_groups)}".lower()
|
||||
hits = [keyword for keyword in _ROLE_KEYWORDS.get(role_key, ()) if keyword.lower() in blob]
|
||||
score = 0
|
||||
reasons: list[str] = []
|
||||
if role_key in agent.role_hints:
|
||||
score += 4
|
||||
reasons.append(f"能力标签含{role_key}")
|
||||
if hits:
|
||||
score += 2 * len(hits)
|
||||
reasons.append("命中:" + "、".join(hits[:3]))
|
||||
if agent.source == "user" and score > 0:
|
||||
score += 8
|
||||
reasons.append("用户可见智能体优先")
|
||||
if agent.source == "builtin_role" and role_key in agent.role_hints:
|
||||
score += 3
|
||||
reasons.append("内置角色兜底")
|
||||
if score <= 0:
|
||||
return 0, "与该职责不匹配"
|
||||
return score, ";".join(reasons)
|
||||
|
||||
|
||||
class AgentSelector:
|
||||
def rank(self, role_key: str, agents: list[CatalogAgent]) -> list[tuple[CatalogAgent, int, str]]:
|
||||
ranked: list[tuple[CatalogAgent, int, str]] = []
|
||||
for agent in agents:
|
||||
score, reason = score_agent_for_role(agent, role_key)
|
||||
if score > 0:
|
||||
ranked.append((agent, score, reason))
|
||||
ranked.sort(key=lambda item: (-item[1], 0 if item[0].source == "user" else 1, item[0].agent_id))
|
||||
return ranked
|
||||
|
||||
def pick(
|
||||
self,
|
||||
role_key: str,
|
||||
agents: list[CatalogAgent],
|
||||
*,
|
||||
avoid_ids: set[str] | None = None,
|
||||
) -> tuple[CatalogAgent, str]:
|
||||
avoid = avoid_ids or set()
|
||||
ranked = self.rank(role_key, agents)
|
||||
for agent, _score, reason in ranked:
|
||||
if agent.agent_id in avoid and agent.source == "user":
|
||||
continue
|
||||
return agent, reason
|
||||
builtin = next((item for item in agents if item.source == "builtin_role" and role_key in item.role_hints), None)
|
||||
if builtin is None:
|
||||
raise LookupError(f"catalog has no agent for role {role_key}")
|
||||
return builtin, "内置角色兜底"
|
||||
@@ -0,0 +1,152 @@
|
||||
"""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.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
from uuid import uuid4
|
||||
|
||||
from app.report_collaboration.contracts.requirements import ReportRequirementSnapshot
|
||||
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.validator import apply_validation, validate_assembled_plan
|
||||
from app.report_collaboration.requirement.defaults import COORDINATOR_NAME, 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 (
|
||||
ReportCollaborationConflictError,
|
||||
ReportCollaborationStore,
|
||||
ReportCollaborationValidationError,
|
||||
)
|
||||
|
||||
_BUSY = frozenset({"running", "awaiting_input", "reviewing", "completed", "failed", "cancelled"})
|
||||
|
||||
|
||||
def requirement_from_session(record: dict[str, Any]) -> ReportRequirementSnapshot:
|
||||
raw = record.get("requirement_json")
|
||||
snapshot: dict[str, Any] | None = None
|
||||
if isinstance(raw, dict) and isinstance(raw.get("snapshot"), dict):
|
||||
snapshot = dict(raw["snapshot"])
|
||||
elif isinstance(raw, dict) and raw.get("topic"):
|
||||
snapshot = dict(raw)
|
||||
if snapshot is None or not str(snapshot.get("topic") or "").strip() or snapshot.get("topic") == "未指定主题":
|
||||
title = str(record.get("title") or "").strip()
|
||||
if title and title not in {DEFAULT_TITLE, ""}:
|
||||
snapshot = {"topic": title, "required_angles": [], "excluded_angles": [], "revision": max(1, int(record.get("requirement_revision") or 1))}
|
||||
else:
|
||||
raise ReportCollaborationValidationError("REQUIREMENT_INCOMPLETE", "请先说明报告主题,再生成协作方案")
|
||||
snapshot.setdefault("required_angles", [])
|
||||
snapshot.setdefault("excluded_angles", [])
|
||||
snapshot["revision"] = max(1, int(snapshot.get("revision") or record.get("requirement_revision") or 1))
|
||||
return ReportRequirementSnapshot.model_validate(snapshot)
|
||||
|
||||
|
||||
class PlanProposalService:
|
||||
def __init__(
|
||||
self,
|
||||
store: ReportCollaborationStore,
|
||||
*,
|
||||
agent_store: Any | None = None,
|
||||
config: ReportCollaborationConfig | None = None,
|
||||
) -> None:
|
||||
self._store = store
|
||||
self._agent_store = agent_store
|
||||
self._config = config
|
||||
self._controller = PlanController()
|
||||
self._assembler = PlanAssembler()
|
||||
|
||||
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]]:
|
||||
record = await self._store.get_session_record(session_id)
|
||||
if record is None:
|
||||
raise ReportCollaborationValidationError("NOT_FOUND", "会话不存在")
|
||||
if record.get("selected_plan_id"):
|
||||
raise ReportCollaborationConflictError("PLAN_ALREADY_SELECTED", "会话已选定方案,无法重新规划", current_revision=int(record.get("requirement_revision") or 0))
|
||||
if record.get("status") in _BUSY:
|
||||
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)
|
||||
except Exception as 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:
|
||||
try:
|
||||
await self._store.update_command_status(command_id, status="failed", error=str(exc)[:500])
|
||||
record = await self._store.get_session_record(session_id)
|
||||
if record is None or record.get("status") != "planning":
|
||||
return
|
||||
plans = await self._store.list_plans(session_id)
|
||||
if any(item.get("status") in {"proposed", "selected"} for item in plans):
|
||||
restore = "proposal_ready"
|
||||
elif int(record.get("requirement_revision") or 0) > 0:
|
||||
restore = "clarifying"
|
||||
else:
|
||||
restore = "empty"
|
||||
await self._store.save_requirement_state(
|
||||
session_id,
|
||||
requirement_json=record.get("requirement_json") or {},
|
||||
requirement_revision=int(record.get("requirement_revision") or 0),
|
||||
status=restore,
|
||||
)
|
||||
except Exception:
|
||||
return
|
||||
|
||||
async def _build(
|
||||
self,
|
||||
session_id: str,
|
||||
*,
|
||||
user_id: str,
|
||||
command_id: str,
|
||||
idempotency_key: str,
|
||||
record: dict[str, Any],
|
||||
) -> 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]}"
|
||||
assembled_list = [
|
||||
self._assembler.assemble(
|
||||
strategy,
|
||||
requirement=requirement,
|
||||
catalog=catalog,
|
||||
config=cfg,
|
||||
proposal_group_id=group_id,
|
||||
revision=1,
|
||||
)
|
||||
for strategy in strategies
|
||||
]
|
||||
persisted: list[dict[str, Any]] = []
|
||||
for assembled in assembled_list:
|
||||
validation = validate_assembled_plan(assembled, catalog=catalog, config=cfg)
|
||||
apply_validation(assembled, validation)
|
||||
if not validation.ok:
|
||||
raise ReportCollaborationValidationError("PLAN_INVALID", ";".join(validation.errors))
|
||||
persisted.append(assembled.candidate)
|
||||
|
||||
await self._store.supersede_proposed_plans(session_id)
|
||||
saved: list[dict[str, Any]] = []
|
||||
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")
|
||||
await self._store.create_message(
|
||||
session_id,
|
||||
role="ai",
|
||||
content="已根据当前需求生成 3 个候选协作方案。请选择其中一个后再开始执行;选择方案不会自动开跑。",
|
||||
idempotency_key=f"{idempotency_key}:plans",
|
||||
name=COORDINATOR_NAME,
|
||||
metadata={"plan_request_command_id": command_id, "proposal_group_id": group_id},
|
||||
completed=True,
|
||||
)
|
||||
return saved
|
||||
@@ -0,0 +1,97 @@
|
||||
"""Validate assembled plans: catalog IDs, tools, DAG, concurrency, budget, artifact contracts."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app.report_collaboration.contracts.enums import ArtifactType
|
||||
from app.report_collaboration.contracts.plans import PlanValidation, ReportPlanCandidate
|
||||
from app.report_collaboration.planning.assembler import AssembledPlan
|
||||
from app.report_collaboration.planning.catalog import AgentCatalogProjection
|
||||
from deerflow.config.report_collaboration_config import ReportCollaborationConfig
|
||||
|
||||
_ARTIFACTS = set(ArtifactType.__args__) # type: ignore[attr-defined]
|
||||
|
||||
|
||||
def _cycle_errors(candidate: ReportPlanCandidate) -> list[str]:
|
||||
ids = {node.id for node in candidate.nodes}
|
||||
incoming: dict[str, int] = {node.id: 0 for node in candidate.nodes}
|
||||
adj: dict[str, list[str]] = {node.id: [] for node in candidate.nodes}
|
||||
errors: list[str] = []
|
||||
for node in candidate.nodes:
|
||||
for dep in node.depends_on:
|
||||
if dep not in ids:
|
||||
errors.append(f"节点 {node.id} 依赖了不存在的 {dep}")
|
||||
continue
|
||||
adj[dep].append(node.id)
|
||||
incoming[node.id] += 1
|
||||
ready = [node_id for node_id, count in incoming.items() if count == 0]
|
||||
seen = 0
|
||||
while ready:
|
||||
current = ready.pop()
|
||||
seen += 1
|
||||
for nxt in adj[current]:
|
||||
incoming[nxt] -= 1
|
||||
if incoming[nxt] == 0:
|
||||
ready.append(nxt)
|
||||
if seen != len(candidate.nodes):
|
||||
errors.append("候选图存在循环,返工只能由运行时台账表达")
|
||||
return errors
|
||||
|
||||
|
||||
def validate_assembled_plan(
|
||||
assembled: AssembledPlan,
|
||||
*,
|
||||
catalog: AgentCatalogProjection,
|
||||
config: ReportCollaborationConfig,
|
||||
) -> PlanValidation:
|
||||
candidate = assembled.candidate
|
||||
errors: list[str] = []
|
||||
catalog_ids = {item.agent_id for item in catalog.agents}
|
||||
allowed_tools = set(catalog.allowed_tool_names)
|
||||
node_ids: list[str] = []
|
||||
|
||||
if len(candidate.nodes) > config.max_team_members:
|
||||
errors.append(f"团队人数 {len(candidate.nodes)} 超过上限 {config.max_team_members}")
|
||||
|
||||
parallel_roots = [node.id for node in candidate.nodes if not node.depends_on]
|
||||
if len(parallel_roots) > config.max_parallel_tasks:
|
||||
errors.append(f"并行波次 {len(parallel_roots)} 超过上限 {config.max_parallel_tasks}")
|
||||
|
||||
for node in candidate.nodes:
|
||||
if node.id in node_ids:
|
||||
errors.append(f"重复节点 id:{node.id}")
|
||||
node_ids.append(node.id)
|
||||
if not node.output_artifact_type:
|
||||
errors.append(f"节点 {node.id} 缺少成果类型")
|
||||
elif node.output_artifact_type not in _ARTIFACTS:
|
||||
errors.append(f"节点 {node.id} 成果类型非法:{node.output_artifact_type}")
|
||||
if not node.acceptance_criteria:
|
||||
errors.append(f"节点 {node.id} 缺少验收标准")
|
||||
for tool in node.allowed_tools:
|
||||
if tool not in allowed_tools:
|
||||
errors.append(f"节点 {node.id} 使用了未允许的工具 {tool}")
|
||||
|
||||
for binding in assembled.bindings:
|
||||
if binding.agent_id not in catalog_ids:
|
||||
errors.append(f"节点 {binding.node_id} 引用了目录外智能体 {binding.agent_id}")
|
||||
|
||||
errors.extend(_cycle_errors(candidate))
|
||||
|
||||
edge_pairs = {(edge.source, edge.target) for edge in candidate.edges}
|
||||
for node in candidate.nodes:
|
||||
for dep in node.depends_on:
|
||||
if (dep, node.id) not in edge_pairs:
|
||||
errors.append(f"缺少边 {dep} → {node.id}")
|
||||
|
||||
if candidate.estimated_cost_level not in {"low", "medium", "high"}:
|
||||
errors.append("缺少成本档位")
|
||||
if candidate.estimated_duration_seconds <= 0:
|
||||
errors.append("缺少预估时长")
|
||||
if not candidate.quality_gates:
|
||||
errors.append("缺少质量门")
|
||||
|
||||
return PlanValidation(ok=not errors, errors=errors)
|
||||
|
||||
|
||||
def apply_validation(assembled: AssembledPlan, validation: PlanValidation) -> AssembledPlan:
|
||||
assembled.candidate.validation = validation
|
||||
return assembled
|
||||
Reference in new issue
Block a user