Files
my-v0-server/app/processor/nodes/requirement_node.py
T
2026-10-01 09:25:01 -07:00

73 lines
3.7 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""沿用意图判断,提取具体需求"""
from langchain_core.messages import HumanMessage, SystemMessage
from app.clients.llm import get_llm
from app.processor.base import BaseNode
from app.processor.outcome_policy import decide_outcome
from app.processor.state import QueryState
from app.prompt.requirement import REQUIREMENT_SYSTEM_PROMPT, build_requirement_input
from app.schemas.requirement import Requirement
class RequirementNode(BaseNode):
name = "requirement_node"
async def process(self, state: QueryState) -> QueryState:
try:
return await self._generate(state)
except ValueError as error:
# 结构化输出解析失败或引用校验不通过(含 ValidationError、OutputParserException)
return self.fail_on_invalid_output(state, error, "需求理解的输出未通过校验")
async def _generate(self, state: QueryState) -> QueryState:
# 浅拷贝状态
updated_state: QueryState = state.copy()
# 获取输入节点已校验的上下文,包含用户需求、当前大屏和澄清记录
context = state["input_context"]
# 获取意图节点经过置信度判断的最终意图,本节点沿用该结果
intent = state["intent"]
llm_client = get_llm(Requirement)
# 异步调用模型,结合当前上下文提取目标、变更、约束及需要澄清的信息
llm_res = await llm_client.ainvoke(
[
# 系统消息提供稳定的需求提取规则和输出边界
SystemMessage(content=REQUIREMENT_SYSTEM_PROMPT),
# 用户消息承载本次需求、大屏、澄清记录和已确认的意图等具体资料
HumanMessage(
content=build_requirement_input(
context, intent, accepted_offer=state.get("accepted_offer")
)
),
]
)
# 用上游意图覆盖模型返回的 intent,避免需求提取阶段重新分类
# 覆盖后重新校验字段一致性,例如 unclear 必须要求澄清,qa 不能包含变更
requirement = Requirement.model_validate(
{**llm_res.model_dump(), "intent": intent}
)
# 收集当前大屏中真实存在的节点 ID,用于校验模型提取的变更目标
node_ids = {node.id for node in context.screen.nodes}
# 逐项检查需求变更,防止后续节点基于不存在的组件生成方案或动作
for change in requirement.changes:
# 用集合差集找出不在当前大屏中的目标 ID,非空时保存到 unknown_ids
if unknown_ids := set(change.target_ids) - node_ids:
# 如果存在无效目标,立即抛出异常,并排序输出 ID 以便定位问题
raise ValueError(f"需求引用了不存在的节点: {sorted(unknown_ids)}")
# 模型只负责理解需求,本轮执行、澄清还是直接回复统一由落地策略根据真实组件决定
decision = decide_outcome(requirement, context.screen)
# 保存落地后的需求,唯一候选已改写为明确目标,供后续澄清或范围判断使用
updated_state["requirement"] = decision.requirement
updated_state["requirement_outcome"] = decision.outcome
updated_state["notice"] = decision.notice
if decision.clarification is not None:
# 选项来自真实组件,无需再由澄清节点调用模型
updated_state["clarification"] = decision.clarification
updated_state["status"] = "waiting_for_input"
# 返回更新后的状态,由图继续执行后续节点
return updated_state