sync update from LAN repo (source dhk-1 @ 3e87be55)
This commit is contained in:
1 parent
ab6068a7c1
commit
42f2a26fa8
1482 files changed
+227759
-9584
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,
|
||||
)
|
||||
|
||||
+188
-2
@@ -16,13 +16,15 @@ from __future__ import annotations
|
||||
import json
|
||||
import logging
|
||||
import re
|
||||
from typing import Any, Callable
|
||||
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
|
||||
@@ -66,6 +68,7 @@ class StrategyNodeDraft(BaseModel):
|
||||
|
||||
slot_id: str
|
||||
role_key: str
|
||||
agent_id: str | None = None
|
||||
display_name: str
|
||||
angle: str | None = None
|
||||
mission: str
|
||||
@@ -128,9 +131,37 @@ def _extract_json(text: str) -> dict[str, Any] | None:
|
||||
try:
|
||||
parsed = json.loads(cleaned[start : end + 1])
|
||||
except Exception:
|
||||
continue
|
||||
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
|
||||
|
||||
|
||||
@@ -295,6 +326,121 @@ class PlannerAgent:
|
||||
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"
|
||||
@@ -355,6 +501,45 @@ _DESIGN_SYSTEM = """你是「报告协作工作台」的规划师智能体。需
|
||||
]
|
||||
}}"""
|
||||
|
||||
_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) ──────────────────────────────────────────
|
||||
|
||||
@@ -407,6 +592,7 @@ def _validate_strategy_dag(draft: StrategyDraft) -> StrategyRoleSet | None:
|
||||
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],
|
||||
|
||||
@@ -12,9 +12,10 @@ 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.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 (
|
||||
@@ -67,7 +68,18 @@ class PlanProposalService:
|
||||
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", "会话不存在")
|
||||
@@ -77,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)
|
||||
@@ -112,32 +140,59 @@ 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)
|
||||
group_id = f"rpg_{uuid4().hex[:12]}"
|
||||
|
||||
# P1-R:规划师智能体是唯一路径 —— 带着完整对话上下文设计工作流。
|
||||
# 模型不可用即无法继续(无模板兜底)。
|
||||
# 规划师智能体带着完整对话、当前候选和真实智能体目录设计候选工作流。
|
||||
# 确定性策略仅用于补足候选数量,最终仍会绑定真实目录中的智能体。
|
||||
from app.report_collaboration.planning.planner_agent import PlannerAgent
|
||||
|
||||
llm = self._planner_llm()
|
||||
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)
|
||||
]
|
||||
designed = await PlannerAgent(llm).design_workflow(
|
||||
requirement=requirement,
|
||||
history=history,
|
||||
max_team_members=cfg.max_team_members,
|
||||
)
|
||||
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] = [designed[0]]
|
||||
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(
|
||||
@@ -163,19 +218,25 @@ 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 "工作流已生成,可开始执行。"
|
||||
content = planner_reply or "候选工作流已规划完成,你可以选择一个方案,也可以继续通过对话调整智能体结构。"
|
||||
await self._store.create_message(
|
||||
session_id,
|
||||
role="ai",
|
||||
content=content,
|
||||
idempotency_key=f"{idempotency_key}:plans",
|
||||
name=COORDINATOR_NAME,
|
||||
metadata={"plan_request_command_id": command_id, "proposal_group_id": group_id, "plan_source": "planner_agent"},
|
||||
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:
|
||||
def planner_llm(self) -> Any:
|
||||
"""规划师模型:注入优先(测试);否则按 planner_llm_enabled 懒构建。不可用即抛错。"""
|
||||
|
||||
if self._llm_factory is not None:
|
||||
|
||||
Reference in new issue
Block a user