Files
my-v0-server/app/processor/nodes/action_node.py
T
2026-10-01 09:52:43 -07:00

207 lines
9.4 KiB
Python

"""将简单修改或包含新增、调整的规划转换为动作列表"""
import json
from langchain.agents.structured_output import (
StructuredOutputError,
StructuredOutputValidationError,
)
from langchain_core.exceptions import OutputParserException
from langchain_core.messages import HumanMessage, SystemMessage
from pydantic import ValidationError
from app.actions.plan import assemble_plan_actions, plan_block_reason, plan_materials
from app.clients.llm import get_llm
from app.processor.base import BaseNode
from app.processor.material_agent import field_group_directory, invoke_with_field_tools
from app.processor.state import QueryState
from app.prompt.action import build_action_prompt, uses_material_fields
from app.schemas.action_validation import ActionValidationError, schema_errors
from app.schemas.actions import ActionBatch, AddAction
from app.schemas.operations import is_direct_operation
GENERATION_ERROR = ActionValidationError(
code="generation_error",
message="模型输出无法解析为 ActionBatch,请按协议重新生成",
)
def can_generate_actions(state: QueryState) -> bool:
# 没有阻塞原因时才允许生成动作,路由和节点入口复用同一套能力检查
return action_block_reason(state) is None
def action_block_reason(state: QueryState) -> str | None:
# 如果已有大屏规划,按规划检查资源、目标和操作是否受支持
if state.get("screen_plan") is not None:
return plan_block_reason(state)
# 没有规划时,读取需求和范围,检查是否可以直接生成简单修改动作
requirement = state["requirement"]
scope = state["change_scope"]
# 如果需求尚未澄清完整,不能猜测用户意图并生成动作
if requirement.needs_clarification:
return "需求尚未澄清完整,不能生成动作"
# 如果需要规划或不是修改已有大屏,则必须先完成规划流程
if scope.needs_planning or requirement.intent != "modify_screen":
return "当前需求需要先完成规划,不能直接生成动作"
# 如果没有具体变更,就没有可转换为动作的需求
if not requirement.changes:
return "需求中没有可执行的变更"
# 收集不支持的目标范围与操作组合,防止只执行需求中受支持的部分
# 直接操作仅支持下列已有节点修改和画布属性修改
unsupported = [
f"{change.target_scope}/{change.operation}"
for change in requirement.changes
if not is_direct_operation(change.target_scope, change.operation)
]
# 如果存在不支持的操作,按出现顺序去重后返回原因,便于展示失败信息
if unsupported:
return "当前尚未支持的直接操作:" + "、".join(dict.fromkeys(unsupported))
# 所有检查通过,返回 None 表示没有阻塞原因
return None
class ActionNode(BaseNode):
name = "action_node"
async def process(self, state: QueryState) -> QueryState:
# 浅拷贝状态
updated_state: QueryState = state.copy()
# 如果已有规划但不满足执行条件,记录原因并直接结束本节点,避免无效模型调用
if state.get("screen_plan") is not None and (
reason := plan_block_reason(state)
):
# 清空旧动作及模拟结果,标记失败,防止后续误用上一轮生成内容
updated_state.update(
actions=None,
validation_passed=False,
validation_errors=[],
simulated_screen=None,
failure_reason=reason,
status="failed",
)
return updated_state
# 将输入上下文、结构化需求和修改范围转成字典,作为本次模型输入
payload = {
"input_context": state["input_context"].model_dump(mode="json"),
"requirement": state["requirement"].model_dump(mode="json"),
"change_scope": state["change_scope"].model_dump(mode="json"),
}
# 如果已有规划,补充规划内容及新增组件需要的物料配置
if state.get("screen_plan") is not None:
payload["screen_plan"] = state["screen_plan"].model_dump(mode="json")
payload["component_materials"] = plan_materials(state)
# 如果本轮是动作修正,提供修正建议、上一轮动作和校验错误供模型参考
if state.get("repair_plan") is not None:
payload.update(
repair_plan=state["repair_plan"].model_dump(mode="json"),
# 上一轮可能在解析阶段就失败,没有动作时按空列表传入
previous_actions=[
action.model_dump(mode="json")
for action in state.get("actions") or []
],
validation_errors=[
error.model_dump() for error in state.get("validation_errors", [])
],
)
system_prompt = build_action_prompt(
state["requirement"],
state.get("screen_plan"),
repairing=state.get("repair_plan") is not None,
)
# 需要写组件属性时提供相关组件的字段分组,模型再按需查询字段定义
with_fields = uses_material_fields(
state["requirement"], state.get("screen_plan")
)
if with_fields:
payload["field_groups"] = field_group_directory(state)
# 将本次具体资料放入用户消息,保留中文以便阅读和排查
content = json.dumps(payload, ensure_ascii=False)
# 旧动作及错误已放入模型输入,现在清空输出状态,避免本轮失败后残留旧结果
updated_state["actions"] = None
updated_state["validation_passed"] = None
updated_state["validation_errors"] = []
updated_state["simulated_screen"] = None
updated_state["failure_reason"] = None
updated_state["status"] = "running"
# 捕获输出结构和解析错误,转换成统一校验结果供后续修正流程使用
try:
# 异步调用模型,根据需求、规划及是否正在修正选择对应的系统规则
if with_fields:
result = await invoke_with_field_tools(
ActionBatch, system_prompt, content
)
else:
result = await get_llm(ActionBatch).ainvoke(
[
SystemMessage(content=system_prompt),
HumanMessage(content=content),
]
)
# 响应中没有工具调用时解析器会返回 None
if result is None:
raise OutputParserException("模型未返回结构化结果")
raw = result.model_dump()
# 规划生成的新增节点只保留显式提供的字段,避免模型默认值覆盖物料默认配置
if state.get("screen_plan") is not None:
# 将原动作对象与序列化结果逐项对应,只调整新增动作的节点数据
for source, target in zip(result.actions, raw["actions"]):
if isinstance(source, AddAction):
target["node"] = source.node.model_dump(exclude_unset=True)
# 统一校验整批动作的字段和结构,格式不合法时抛出 ValidationError
batch = ActionBatch.model_validate(raw)
# 如果已有规划,使用物料默认配置补全新增节点,并同步示例数据标记
if state.get("screen_plan") is not None:
batch = assemble_plan_actions(state, batch)
except ValidationError as error:
# 将结构校验异常转换为统一错误列表,返回状态以进入后续修正判断
updated_state["validation_passed"] = False
updated_state["validation_errors"] = schema_errors(error)
return updated_state
except StructuredOutputValidationError as error:
# 查询字段后的输出不符合结构,与直接输出时的处理一致
updated_state["validation_passed"] = False
updated_state["validation_errors"] = (
schema_errors(error.source)
if isinstance(error.source, ValidationError)
else [GENERATION_ERROR]
)
return updated_state
except (OutputParserException, StructuredOutputError):
# 如果模型输出无法解析,记录生成错误,提示后续按 ActionBatch 协议重新生成
updated_state["validation_passed"] = False
updated_state["validation_errors"] = [GENERATION_ERROR]
return updated_state
# 模型确认现有能力无法满足需求时直接失败收尾,不进入重试
if batch.unsupported_reason:
updated_state.update(
actions=[],
validation_passed=False,
failure_reason=f"动作生成判断无法完成:{batch.unsupported_reason}",
status="failed",
)
return updated_state
# 保存生成的动作,实际目标、规划一致性及模拟执行结果仍由后续校验节点检查
updated_state["actions"] = batch.actions
# 返回待校验状态,此时 validation_passed 仍为 None,不代表动作已执行或通过校验
return updated_state