From adb25a2e22387b07827440a65eb087c2fd22d8e2 Mon Sep 17 00:00:00 2001 From: root <953994191@qq.com> Date: Wed, 6 May 2026 15:10:33 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BC=98=E5=8C=96=EF=BC=9A=E9=87=8D=E6=9E=84?= =?UTF-8?q?=20state=EF=BC=8C=E5=88=86=E7=A6=BB=E6=8C=81=E4=B9=85=E5=8C=96?= =?UTF-8?q?=E5=92=8C=E4=B8=B4=E6=97=B6=E5=AD=97=E6=AE=B5=EF=BC=8C=E5=AE=8C?= =?UTF-8?q?=E5=96=84=20init=5Fstate=5Fnode?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 主要改动: 1. 移除无用字段 system_prompt 2. 重新组织 state,明确标注「持久化字段」和「临时字段」 3. 完善 init_state_node,重置所有临时字段 4. 解决数据残留隐患,确保每轮对话开始时状态干净 --- backend/app/main_graph/nodes/routing.py | 84 +++++++++++++++++++++++-- backend/app/main_graph/state.py | 79 +++++++++++++---------- 2 files changed, 125 insertions(+), 38 deletions(-) diff --git a/backend/app/main_graph/nodes/routing.py b/backend/app/main_graph/nodes/routing.py index 01ce993..7f9926d 100644 --- a/backend/app/main_graph/nodes/routing.py +++ b/backend/app/main_graph/nodes/routing.py @@ -11,21 +11,97 @@ from datetime import datetime from backend.app.core.intent import get_route_by_reasoning, ReasoningAction -from ...main_graph.state import MainGraphState +from ...main_graph.state import ( + MainGraphState, + CurrentAction, + ReactReasoningState, + HybridRouterState, + FastPathState +) from backend.app.logger import info # ========== 初始化状态节点 ========== def init_state_node(state: MainGraphState) -> MainGraphState: - """初始化状态节点:在流程开始时设置初始值""" + """ + 初始化状态节点:在流程开始时设置初始值 + + 重置策略: + - 持久化字段(如 messages、turns_since_last_summary)不重置 + - 临时字段(如 rag_context、final_result)重置为初始值 + """ + # 持久化字段保留原样 + # - messages + # - turns_since_last_summary + # - user_id + + # ========== 重置临时字段 ========== + + # 主图控制字段 + state.user_query = "" + state.current_action = CurrentAction.NONE + state.current_model = "" + state.intent_confidence = 0.0 + + # React 推理专用字段 + state.reasoning_step = 0 + state.last_action = "" + state.reasoning_history = [] + + # RAG 相关字段 + state.rag_context = "" + state.rag_retrieved = False + state.rag_docs = [] + state.rag_confidence = 0.0 + state.rag_attempts = 0 + + # 联网搜索相关字段 + state.web_search_results = [] + + # 错误处理字段 + state.errors = [] + state.current_error = None + state.retry_action = None + state.error_message = "" + + # 子图结果字段 + state.news_result = None + state.dictionary_result = None + state.contact_result = None + + # 执行状态 + state.current_phase = "initializing" + state.final_result = "" + state.success = False + + # 元数据 + state.start_time = None + state.end_time = None + + # 结构化状态 + state.react_reasoning = ReactReasoningState() + state.hybrid_router = HybridRouterState() + state.fast_path = FastPathState() + + # 统计字段 + state.llm_calls = 0 + state.last_token_usage = {} + state.last_elapsed_time = 0.0 + state.memory_context = "" + + # 向后兼容字段 + state.debug_info = {} + + # 设置初始值 state.current_phase = "initializing" state.reasoning_step = 0 state.start_time = datetime.now().isoformat() - + + # 从 messages 中提取 user_query(如果没有的话) if not state.user_query and state.messages: last_msg = state.messages[-1] state.user_query = getattr(last_msg, "content", str(last_msg)) - + return state diff --git a/backend/app/main_graph/state.py b/backend/app/main_graph/state.py index 5656e8b..a6aad6b 100644 --- a/backend/app/main_graph/state.py +++ b/backend/app/main_graph/state.py @@ -1,6 +1,10 @@ """ 主图状态定义 - React 模式增强版 Main Graph State Definition - React Mode Enhanced + +字段分类说明: +- 持久化字段:跨轮次保留,不重置 +- 临时字段:每轮对话开始时重置 """ from enum import Enum, auto @@ -10,7 +14,7 @@ from langgraph.graph import add_messages from langchain_core.messages import BaseMessage -# ========== 新的类型 ========== +# ========== 枚举类型 ========== class CurrentAction(Enum): """主图当前操作类型""" NONE = auto() @@ -43,21 +47,21 @@ class ErrorRecord: @dataclass class ReactReasoningState: - """React 推理状态 - 替代 debug_info 中的相关字段""" + """React 推理状态""" last_reasoning: Optional[Dict[str, Any]] = None reasoning_result: Optional[Any] = None # 实际类型是 ReasoningResult @dataclass class HybridRouterState: - """混合路由状态 - 替代 debug_info 中的相关字段""" + """混合路由状态""" decision: Optional[Any] = None # 实际类型是 HybridRouterResult start_time: Optional[str] = None @dataclass class FastPathState: - """快速路径状态 - 替代 debug_info 中的相关字段""" + """快速路径状态""" chitchat_success: bool = False rag_success: bool = False tool_success: bool = False @@ -68,70 +72,77 @@ class FastPathState: @dataclass class MainGraphState: """ - - 旧代码的 MessagesState 兼容性字段 - - React 推理控制字段 - - 循环和错误处理 - - 子图结果占位 - - 用户信息 - """ - # ========== 旧 MessagesState 兼容性字段 ========== - messages: Annotated[Sequence[BaseMessage], add_messages] = field(default_factory=list) - llm_calls: int = 0 - memory_context: str = "" - system_prompt: str = "" - turns_since_last_summary: int = 0 # 新增:来自旧状态 - last_token_usage: Dict[str, Any] = field(default_factory=dict) # 新增:来自旧状态 - last_elapsed_time: float = 0.0 # 新增:来自旧状态 + 主图状态定义 - # ========== 主图控制字段 ========== + 字段分类: + - 持久化字段:跨轮次保留,不重置 + - 临时字段:每轮对话开始时重置 + """ + + # ================================================== + # 持久化字段(每轮保留) + # ================================================== + + messages: Annotated[Sequence[BaseMessage], add_messages] = field(default_factory=list) + turns_since_last_summary: int = 0 # 距离上次总结的轮数 + user_id: str = "" + + # ================================================== + # 临时字段(每轮重置) + # ================================================== + + # 主图控制字段 user_query: str = "" current_action: CurrentAction = CurrentAction.NONE - current_model: str = "" # 新增:本次请求使用的模型 + current_model: str = "" # 本次请求使用的模型 intent_confidence: float = 0.0 - # ========== React 推理专用字段 ========== + # React 推理专用字段 reasoning_step: int = 0 - max_steps: int = 10 # 从 40 改到 10,避免过长循环 + max_steps: int = 10 # 避免过长循环 last_action: str = "" reasoning_history: List[Dict[str, Any]] = field(default_factory=list) - # ========== RAG 相关字段 ========== + # RAG 相关字段 rag_context: str = "" rag_retrieved: bool = False rag_docs: List[Dict[str, Any]] = field(default_factory=list) rag_confidence: float = 0.0 # RAG 检索置信度 (0.0-1.0) rag_attempts: int = 0 # RAG 检索次数统计 - # ========== 联网搜索相关字段 ========== + # 联网搜索相关字段 web_search_results: List[str] = field(default_factory=list) - # ========== 错误处理字段 ========== + # 错误处理字段 errors: List[ErrorRecord] = field(default_factory=list) current_error: Optional[ErrorRecord] = None retry_action: Optional[str] = None + error_message: str = "" - # ========== 子图结果占位 ========== + # 子图结果字段 news_result: Optional[Dict[str, Any]] = None dictionary_result: Optional[Dict[str, Any]] = None contact_result: Optional[Dict[str, Any]] = None - # ========== 用户信息 ========== - user_id: str = "" - - # ========== 执行状态 ========== + # 执行状态 current_phase: str = "init" - error_message: str = "" final_result: str = "" success: bool = False - # ========== 元数据 ========== + # 元数据 start_time: Optional[str] = None end_time: Optional[str] = None - # ========== 结构化状态(替代黑盒 debug_info)========== + # 结构化状态 react_reasoning: ReactReasoningState = field(default_factory=ReactReasoningState) hybrid_router: HybridRouterState = field(default_factory=HybridRouterState) fast_path: FastPathState = field(default_factory=FastPathState) - # ========== 向后兼容 ========== + # 统计字段(用于反馈) + llm_calls: int = 0 + last_token_usage: Dict[str, Any] = field(default_factory=dict) + last_elapsed_time: float = 0.0 + memory_context: str = "" # 记忆检索结果 + + # 向后兼容(保留但不推荐使用) debug_info: Dict[str, Any] = field(default_factory=dict)