"""沿用意图判断,提取具体需求""" import json 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 if __name__ == "__main__": import asyncio from pydantic import BaseModel from app.clients.decision import close_decision_engine from app.processor.nodes.input_node import InputNode from app.processor.nodes.intent_node import IntentNode async def main(): # 1. 修改这里的请求,测试具体需求提取 state: QueryState = { "request": { "prompt": "把销售额统计向右移动 50px,其他不变", "screen": { "canvas": {"width": 1920, "height": 1080}, "nodes": [ { "id": "sales-chart", "type": "bar-chart", "name": "销售额统计", "layout": {"x": 26, "y": 34.8, "width": 400, "height": 260}, "props": {"option": {"title": {"text": "销售额统计"}}}, } ], "dataSource": [], }, "context": {"selected_node_ids": ["sales-chart"]}, } } # 2. 依次执行输入、意图判断和需求理解 try: # 先将原始请求校验为统一的输入上下文 state = InputNode().process(state) # 调用 Jev 判断意图,为需求提取提供已确认的分类结果 state = await IntentNode().process(state) # 基于上下文和意图调用模型,提取结构化需求 node = RequirementNode() final_state = await node.process(state) finally: # 无论处理成功还是抛出异常,都关闭示例使用的 Jev 连接 await close_decision_engine() # 3. 打印完整 state # 将状态中的 Pydantic 模型转成字典,其他值保持原样,以便输出 JSON print( json.dumps( { key: value.model_dump(mode="json", exclude_unset=True) if isinstance(value, BaseModel) else value for key, value in final_state.items() }, ensure_ascii=False, indent=2, ) ) # 启动事件循环,执行上面的异步调试流程 asyncio.run(main())