From 3400bea9efd9b8fec6737c24c375588d6f1e2f7c Mon Sep 17 00:00:00 2001 From: zhaoying Date: Mon, 5 Jan 2026 17:16:09 +0800 Subject: [PATCH 01/75] feat(web): update node icon --- web/src/assets/images/workflow/memory-read.png | Bin 0 -> 936 bytes web/src/assets/images/workflow/memory-write.png | Bin 0 -> 568 bytes web/src/views/Workflow/constant.ts | 8 +++++--- 3 files changed, 5 insertions(+), 3 deletions(-) create mode 100644 web/src/assets/images/workflow/memory-read.png create mode 100644 web/src/assets/images/workflow/memory-write.png diff --git a/web/src/assets/images/workflow/memory-read.png b/web/src/assets/images/workflow/memory-read.png new file mode 100644 index 0000000000000000000000000000000000000000..4b0cdc1d1c0934c1057013bc803db456882e21a0 GIT binary patch literal 936 zcmX}pe^Aq990&02bU+TgGY4I0mna%X!J(AYX&3>Ho$wV0NWv7vM9hn^_+ce!Lfo~{ zG^eD2MFvHpn;QcXHVDX#$q)G@j%_e0wy_NPF_a06z57ykJ@81*KGxviVaaI6bkjT*y#93awV$3ssx$QRfr+|vW)mQ|C|5+A+BTZ zb;OdYv9B8JYQ)_@!c8QK@tzn-5+vUOM~Z_|93sh(B15VShii~lgClYrtwly1j@RRZ zdT?)p+W;P^5g#=oyAe4GYW1iypx%JnBTyKjG@|Jt znjb(xlC&Xi-+GHo$6zFZtkwb0nWOD?4kJK>C;88Gn79Ly6ueQwtdwsH$BGr0*IAy7Zcq1QhN*Ik(+XElglm4HzI~*}sy#ayl(FHu)%i z;Jd%E&Gm8sZ5uyV_0p!s`<4E*1YS&P0&lP1Ameg1=Z4+j8PfD~K;ooJ%Lw~f8RMj3 jj9cjtfBTzm))CrFO(+qGt#;)~vT+J4l8BJJn_BP>xMn8t literal 0 HcmV?d00001 diff --git a/web/src/assets/images/workflow/memory-write.png b/web/src/assets/images/workflow/memory-write.png new file mode 100644 index 0000000000000000000000000000000000000000..83a50fd48c5caa4a0f2adf4721aca1b346dfb365 GIT binary patch literal 568 zcmV-80>}M{P)Yw#*< z@GfuhFL3cVcJVxU@srHDj_m8so zmA3eoxcHg5_?)}=s>J!L#`&?y`nb;e!qxlG-u&3){MqIF+UES@>;2{J{p#@k?DGEY z^8WDj{_*wx^Y{Mv`u_R*|NQ;`|NsA!<}OD7000eiQchC<8XQh*Zkx8*^7H)tasEvS z0003aNkl^ z)qhDjV(N>ask1fOd_5l7W+0-bY=XQn?B;_ToSpB>^9%R=#h??s8zdhJhfv@wU?j0h2ilU#9reU(p!K#4oJ z#lfLwK#2W?eKU)`Qyk;=MYF}RQ_Qh2{S}xK;_^bXB*hk#xVq7-NRi#+e~6MN%GM|l zVoVHI#o7#)Yg}tDGvmq*0CuGCLy8@H{2=8=Ge7J(&&M|=kAB6V$CTm#0000 Date: Mon, 5 Jan 2026 17:17:52 +0800 Subject: [PATCH 02/75] feat(workflow): support context injection in LLM node --- api/app/core/workflow/nodes/llm/node.py | 92 ++++++++++++++----------- 1 file changed, 51 insertions(+), 41 deletions(-) diff --git a/api/app/core/workflow/nodes/llm/node.py b/api/app/core/workflow/nodes/llm/node.py index 65826d84..334229f7 100644 --- a/api/app/core/workflow/nodes/llm/node.py +++ b/api/app/core/workflow/nodes/llm/node.py @@ -5,15 +5,17 @@ LLM 节点实现 """ import logging +import re from typing import Any from langchain_core.messages import AIMessage, SystemMessage, HumanMessage from app.core.workflow.nodes.base_node import BaseNode, WorkflowState from app.core.models import RedBearLLM, RedBearModelConfig +from app.core.workflow.nodes.llm.config import LLMNodeConfig from app.db import get_db_context from app.models import ModelType from app.services.model_service import ModelConfigService - + from app.core.exceptions import BusinessException from app.core.error_codes import BizCode @@ -63,8 +65,15 @@ class LLMNode(BaseNode): - user/human: 用户消息(HumanMessage) - ai/assistant: AI 消息(AIMessage) """ - - def _prepare_llm(self, state: WorkflowState,stream:bool = False) -> tuple[RedBearLLM, list | str]: + def __init__(self, node_config: dict[str, Any], workflow_config: dict[str, Any]): + super().__init__(node_config, workflow_config) + self.typed_config = LLMNodeConfig(**self.config) + + def _render_context(self, message,state): + context = f"{self._render_template(self.typed_config.context, state)}" + return re.sub(r"{{context}}", context, message) + + def _prepare_llm(self, state: WorkflowState, stream: bool = False) -> tuple[RedBearLLM, list | str]: """准备 LLM 实例(公共逻辑) Args: @@ -76,15 +85,16 @@ class LLMNode(BaseNode): # 1. 处理消息格式(优先使用 messages) messages_config = self.config.get("messages") - + if messages_config: # 使用 LangChain 消息格式 messages = [] for msg_config in messages_config: role = msg_config.get("role", "user").lower() content_template = msg_config.get("content", "") + content_template = self._render_context(content_template, state) content = self._render_template(content_template, state) - + # 根据角色创建对应的消息对象 if role == "system": messages.append(SystemMessage(content=content)) @@ -95,7 +105,7 @@ class LLMNode(BaseNode): else: logger.warning(f"未知的消息角色: {role},默认使用 user") messages.append(HumanMessage(content=content)) - + prompt_or_messages = messages else: # 使用简单的 prompt 格式(向后兼容) @@ -106,17 +116,17 @@ class LLMNode(BaseNode): model_id = self.config.get("model_id") if not model_id: raise ValueError(f"节点 {self.node_id} 缺少 model_id 配置") - + # 3. 在 with 块内完成所有数据库操作和数据提取 with get_db_context() as db: config = ModelConfigService.get_model_by_id(db=db, model_id=model_id) - - if not config: + + if not config: raise BusinessException("配置的模型不存在", BizCode.NOT_FOUND) - + if not config.api_keys or len(config.api_keys) == 0: raise BusinessException("模型配置缺少 API Key", BizCode.INVALID_PARAMETER) - + # 在 Session 关闭前提取所有需要的数据 api_config = config.api_keys[0] model_name = api_config.model_name @@ -124,26 +134,26 @@ class LLMNode(BaseNode): api_key = api_config.api_key api_base = api_config.api_base model_type = config.type - + # 4. 创建 LLM 实例(使用已提取的数据) # 注意:对于流式输出,需要在模型初始化时设置 streaming=True extra_params = {"streaming": stream} if stream else {} - + llm = RedBearLLM( RedBearModelConfig( model_name=model_name, - provider=provider, + provider=provider, api_key=api_key, base_url=api_base, extra_params=extra_params - ), + ), type=ModelType(model_type) ) - + logger.debug(f"创建 LLM 实例: provider={provider}, model={model_name}, streaming={stream}") - + return llm, prompt_or_messages - + async def execute(self, state: WorkflowState) -> AIMessage: """非流式执行 LLM 调用 @@ -153,10 +163,10 @@ class LLMNode(BaseNode): Returns: LLM 响应消息 """ - llm, prompt_or_messages = self._prepare_llm(state,True) - + llm, prompt_or_messages = self._prepare_llm(state, True) + logger.info(f"节点 {self.node_id} 开始执行 LLM 调用(非流式)") - + # 调用 LLM(支持字符串或消息列表) response = await llm.ainvoke(prompt_or_messages) # 提取内容 @@ -164,16 +174,16 @@ class LLMNode(BaseNode): content = response.content else: content = str(response) - + logger.info(f"节点 {self.node_id} LLM 调用完成,输出长度: {len(content)}") - + # 返回 AIMessage(包含响应元数据) return response if isinstance(response, AIMessage) else AIMessage(content=content) - + def _extract_input(self, state: WorkflowState) -> dict[str, Any]: """提取输入数据(用于记录)""" _, prompt_or_messages = self._prepare_llm(state) - + return { "prompt": prompt_or_messages if isinstance(prompt_or_messages, str) else None, "messages": [ @@ -186,13 +196,13 @@ class LLMNode(BaseNode): "max_tokens": self.config.get("max_tokens") } } - + def _extract_output(self, business_result: Any) -> str: """从 AIMessage 中提取文本内容""" if isinstance(business_result, AIMessage): return business_result.content return str(business_result) - + def _extract_token_usage(self, business_result: Any) -> dict[str, int] | None: """从 AIMessage 中提取 token 使用情况""" if isinstance(business_result, AIMessage) and hasattr(business_result, 'response_metadata'): @@ -204,7 +214,7 @@ class LLMNode(BaseNode): "total_tokens": usage.get('total_tokens', 0) } return None - + async def execute_stream(self, state: WorkflowState): """流式执行 LLM 调用 @@ -215,26 +225,26 @@ class LLMNode(BaseNode): 文本片段(chunk)或完成标记 """ from langgraph.config import get_stream_writer - + llm, prompt_or_messages = self._prepare_llm(state, True) - + logger.info(f"节点 {self.node_id} 开始执行 LLM 调用(流式)") logger.debug(f"LLM 配置: streaming={getattr(llm._model, 'streaming', 'unknown')}") - + # 检查是否有注入的 End 节点前缀配置 writer = get_stream_writer() end_prefix = getattr(self, '_end_node_prefix', None) - + logger.info(f"[LLM前缀] 节点 {self.node_id} 检查前缀配置: {end_prefix is not None}") if end_prefix: logger.info(f"[LLM前缀] 前缀内容: '{end_prefix}'") - + if end_prefix: # 渲染前缀(可能包含其他变量) try: rendered_prefix = self._render_template(end_prefix, state) logger.info(f"节点 {self.node_id} 提前发送 End 节点前缀: '{rendered_prefix[:50]}...'") - + # 提前发送 End 节点的前缀(使用 "message" 类型) writer({ "type": "message", # End 相关的内容都是 message 类型 @@ -246,12 +256,12 @@ class LLMNode(BaseNode): }) except Exception as e: logger.warning(f"渲染/发送 End 节点前缀失败: {e}") - + # 累积完整响应 full_response = "" last_chunk = None chunk_count = 0 - + # 调用 LLM(流式,支持字符串或消息列表) async for chunk in llm.astream(prompt_or_messages): # 提取内容 @@ -259,18 +269,18 @@ class LLMNode(BaseNode): content = chunk.content else: content = str(chunk) - + # 只有当内容不为空时才处理 if content: full_response += content last_chunk = chunk chunk_count += 1 - + # 流式返回每个文本片段 yield content - + logger.info(f"节点 {self.node_id} LLM 调用完成,输出长度: {len(full_response)}, 总 chunks: {chunk_count}") - + # 构建完整的 AIMessage(包含元数据) if isinstance(last_chunk, AIMessage): final_message = AIMessage( @@ -279,6 +289,6 @@ class LLMNode(BaseNode): ) else: final_message = AIMessage(content=full_response) - + # yield 完成标记 yield {"__final__": True, "result": final_message} From 29ccf956ec6e1d2e068980932c01cc0b405e11fb Mon Sep 17 00:00:00 2001 From: mengyonghao <1533512157@qq.com> Date: Mon, 5 Jan 2026 17:30:28 +0800 Subject: [PATCH 03/75] pref(workflow): skip orphan node check in runtime execution --- api/app/core/workflow/validator.py | 24 +++++++++++++----------- 1 file changed, 13 insertions(+), 11 deletions(-) diff --git a/api/app/core/workflow/validator.py b/api/app/core/workflow/validator.py index 00358d91..32f5ad80 100644 --- a/api/app/core/workflow/validator.py +++ b/api/app/core/workflow/validator.py @@ -87,7 +87,7 @@ class WorkflowValidator: return graphs @classmethod - def validate(cls, workflow_config: Union[dict[str, Any], Any]) -> tuple[bool, list[str]]: + def validate(cls, workflow_config: Union[dict[str, Any], Any], publish=False) -> tuple[bool, list[str]]: """验证工作流配置 Args: @@ -159,15 +159,17 @@ class WorkflowValidator: elif target not in node_id_set: errors.append(f"边 #{i} 的 target 节点不存在: {target}") - # 6. 验证所有节点可达(从 start 节点出发) - if start_nodes and not errors: # 只有在前面验证通过时才检查可达性 - reachable = WorkflowValidator._get_reachable_nodes( - start_nodes[0]["id"], - edges - ) - unreachable = node_id_set - reachable - if unreachable: - errors.append(f"以下节点无法从 start 节点到达: {unreachable}") + if publish: + # 仅在发布时验证所有节点可达 + # 6. 验证所有节点可达(从 start 节点出发) + if start_nodes and not errors: # 只有在前面验证通过时才检查可达性 + reachable = WorkflowValidator._get_reachable_nodes( + start_nodes[0]["id"], + edges + ) + unreachable = node_id_set - reachable + if unreachable: + errors.append(f"以下节点无法从 start 节点到达: {unreachable}") # 7. 检测循环依赖(非 loop 节点) if not errors: # 只有在前面验证通过时才检查循环 @@ -288,7 +290,7 @@ class WorkflowValidator: (is_valid, errors): 是否有效和错误列表 """ # 先执行基础验证 - is_valid, errors = WorkflowValidator.validate(workflow_config) + is_valid, errors = WorkflowValidator.validate(workflow_config, publish=True) if not is_valid: return False, errors From 679e518574da29afe26480455aade631e51c7caf Mon Sep 17 00:00:00 2001 From: zhaoying Date: Mon, 5 Jan 2026 17:31:16 +0800 Subject: [PATCH 04/75] fix(web): update ui --- web/src/views/ToolManagement/Inner.tsx | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/web/src/views/ToolManagement/Inner.tsx b/web/src/views/ToolManagement/Inner.tsx index d256d6c7..6f85e1f7 100644 --- a/web/src/views/ToolManagement/Inner.tsx +++ b/web/src/views/ToolManagement/Inner.tsx @@ -4,10 +4,9 @@ import { Col, Tag, List, - Space + Flex } from 'antd'; import { EyeOutlined } from '@ant-design/icons'; -import clsx from 'clsx' import { useTranslation } from 'react-i18next'; import dayjs, { type Dayjs } from 'dayjs' @@ -103,9 +102,9 @@ const Inner: React.FC<{ getStatusTag: (status: string) => ReactNode }> = ({ getS
{t(`tool.${item.config_data.tool_class}_features`)}
- + {InnerConfigData[item.config_data.tool_class].features.map(vo => { t(`tool.${vo}`) }) } - + {item.config_data.tool_class === 'DateTimeTool' ?
From 05ec76f940ba4812c8926eb934226bcf61666f85 Mon Sep 17 00:00:00 2001 From: mengyonghao <1533512157@qq.com> Date: Mon, 5 Jan 2026 17:31:28 +0800 Subject: [PATCH 05/75] perf(prompt_opt): optimize streaming output structure and add variable parsing --- api/app/controllers/prompt_optimizer_controller.py | 2 +- api/app/services/prompt_optimizer_service.py | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/api/app/controllers/prompt_optimizer_controller.py b/api/app/controllers/prompt_optimizer_controller.py index 2069dd66..c871c511 100644 --- a/api/app/controllers/prompt_optimizer_controller.py +++ b/api/app/controllers/prompt_optimizer_controller.py @@ -117,7 +117,7 @@ async def get_prompt_opt( user_require=data.message ): # chunk 是 prompt 的增量内容 - yield f"event:'message'\ndata: {json.dumps(chunk)}\n\n" + yield f"event:message\ndata: {json.dumps(chunk)}\n\n" return StreamingResponse( event_generator(), diff --git a/api/app/services/prompt_optimizer_service.py b/api/app/services/prompt_optimizer_service.py index 482e8213..b3ac1b79 100644 --- a/api/app/services/prompt_optimizer_service.py +++ b/api/app/services/prompt_optimizer_service.py @@ -231,9 +231,9 @@ class PromptOptimizerService: if m: prompt_index = m.start() prompt_finished = True - yield {"type": "delta", "content": buffer[idx:prompt_index]} + yield {"content": buffer[idx:prompt_index]} else: - yield {"type": "delta", "content": cache[idx:]} + yield {"content": cache[idx:]} if len(cache) != 0: idx = len(cache) @@ -249,8 +249,8 @@ class PromptOptimizerService: role=RoleType.ASSISTANT, content=desc ) - - yield {"type": "done", "desc": optim_result.get("desc")} + variables = self.parser_prompt_variables(optim_result.get("prompt")) + yield {"desc": optim_result.get("desc"), "variables": variables} @staticmethod def parser_prompt_variables(prompt: str): From d4a87187cbeea750d4c204809a3f2ea5c95821ec Mon Sep 17 00:00:00 2001 From: mengyonghao <1533512157@qq.com> Date: Mon, 5 Jan 2026 17:32:20 +0800 Subject: [PATCH 06/75] fix(workflow): fix memory node message field not supporting variables --- api/app/core/workflow/nodes/memory/node.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/api/app/core/workflow/nodes/memory/node.py b/api/app/core/workflow/nodes/memory/node.py index 09c9fc68..bb2366f6 100644 --- a/api/app/core/workflow/nodes/memory/node.py +++ b/api/app/core/workflow/nodes/memory/node.py @@ -24,7 +24,7 @@ class MemoryReadNode(BaseNode): return await MemoryAgentService().read_memory( group_id=end_user_id, - message=self.typed_config.message, + message=self._render_template(self.typed_config.message, state), config_id=self.typed_config.config_id, search_switch=self.typed_config.search_switch, history=[], @@ -51,7 +51,7 @@ class MemoryWriteNode(BaseNode): return await MemoryAgentService().write_memory( group_id=end_user_id, - message=self.typed_config.message, + message=self._render_template(self.typed_config.message, state), config_id=self.typed_config.config_id, db=db, storage_type="neo4j", From e1e77f70f9d53410eaba27d5ed2884503c6de5b0 Mon Sep 17 00:00:00 2001 From: mengyonghao <1533512157@qq.com> Date: Mon, 5 Jan 2026 17:37:45 +0800 Subject: [PATCH 07/75] feat(workflow): support context injection in LLM node --- api/app/core/workflow/nodes/llm/config.py | 35 ++++++++++++++--------- 1 file changed, 21 insertions(+), 14 deletions(-) diff --git a/api/app/core/workflow/nodes/llm/config.py b/api/app/core/workflow/nodes/llm/config.py index da94482b..8498fc38 100644 --- a/api/app/core/workflow/nodes/llm/config.py +++ b/api/app/core/workflow/nodes/llm/config.py @@ -1,5 +1,7 @@ """LLM 节点配置""" +from typing import Any + from pydantic import BaseModel, Field, field_validator from app.core.workflow.nodes.base_config import BaseNodeConfig, VariableDefinition, VariableType @@ -7,17 +9,17 @@ from app.core.workflow.nodes.base_config import BaseNodeConfig, VariableDefiniti class MessageConfig(BaseModel): """消息配置""" - + role: str = Field( ..., description="消息角色:system, user, assistant" ) - + content: str = Field( ..., description="消息内容,支持模板变量,如:{{ sys.message }}" ) - + @field_validator("role") @classmethod def validate_role(cls, v: str) -> str: @@ -35,24 +37,29 @@ class LLMNodeConfig(BaseNodeConfig): 1. 简单模式:使用 prompt 字段 2. 消息模式:使用 messages 字段(推荐) """ - + model_id: str = Field( ..., description="模型配置 ID" ) - + + context: Any = Field( + default="", + description="上下文" + ) + # 简单模式 prompt: str | None = Field( default=None, description="提示词模板(简单模式),支持变量引用" ) - + # 消息模式(推荐) messages: list[MessageConfig] | None = Field( default=None, description="消息列表(消息模式),支持多轮对话" ) - + # 模型参数 temperature: float | None = Field( default=0.7, @@ -60,35 +67,35 @@ class LLMNodeConfig(BaseNodeConfig): le=2.0, description="温度参数,控制输出的随机性" ) - + max_tokens: int | None = Field( default=1000, ge=1, le=32000, description="最大生成 token 数" ) - + top_p: float | None = Field( default=None, ge=0.0, le=1.0, description="Top-p 采样参数" ) - + frequency_penalty: float | None = Field( default=None, ge=-2.0, le=2.0, description="频率惩罚" ) - + presence_penalty: float | None = Field( default=None, ge=-2.0, le=2.0, description="存在惩罚" ) - + # 输出变量定义 output_variables: list[VariableDefinition] = Field( default_factory=lambda: [ @@ -105,14 +112,14 @@ class LLMNodeConfig(BaseNodeConfig): ], description="输出变量定义(自动生成,通常不需要修改)" ) - + @field_validator("messages", "prompt") @classmethod def validate_input_mode(cls, v, info): """验证输入模式:prompt 和 messages 至少有一个""" # 这个验证在 model_validator 中更合适 return v - + class Config: json_schema_extra = { "examples": [ From 71c5b54532279d0407381704850dcc364c7114b9 Mon Sep 17 00:00:00 2001 From: mengyonghao <1533512157@qq.com> Date: Mon, 5 Jan 2026 18:22:17 +0800 Subject: [PATCH 08/75] fix(workflow): throw exception when HTTP request node error handler is empty --- api/app/core/workflow/nodes/http_request/node.py | 14 +++++--------- 1 file changed, 5 insertions(+), 9 deletions(-) diff --git a/api/app/core/workflow/nodes/http_request/node.py b/api/app/core/workflow/nodes/http_request/node.py index 55919998..4374d847 100644 --- a/api/app/core/workflow/nodes/http_request/node.py +++ b/api/app/core/workflow/nodes/http_request/node.py @@ -208,17 +208,12 @@ class HttpRequestNode(BaseNode): retries -= 1 if retries > 0: await asyncio.sleep(self.typed_config.retry.retry_interval / 1000) + elif self.typed_config.error_handle.method == HttpErrorHandle.NONE: + raise e + except Exception as e: + raise RuntimeError(f"HTTP request node exception: {e}") else: match self.typed_config.error_handle.method: - case HttpErrorHandle.NONE: - logger.warning( - f"Node {self.node_id}: HTTP request failed, returning error response" - ) - return HttpRequestNodeOutput( - body="", - status_code=resp.status_code, - headers=resp.headers, - ).model_dump() case HttpErrorHandle.DEFAULT: logger.warning( f"Node {self.node_id}: HTTP request failed, returning default result" @@ -229,3 +224,4 @@ class HttpRequestNode(BaseNode): f"Node {self.node_id}: HTTP request failed, switching to error handling branch" ) return "ERROR" + raise RuntimeError("http request failed") From ebdf4e4c5e33fd36d495e9cb453fe84f45fca9f6 Mon Sep 17 00:00:00 2001 From: Mark Date: Mon, 5 Jan 2026 19:03:28 +0800 Subject: [PATCH 09/75] [fix] converfsation message duplicate entry problem --- api/app/services/draft_run_service.py | 5 +++-- api/app/services/multi_agent_orchestrator.py | 3 ++- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/api/app/services/draft_run_service.py b/api/app/services/draft_run_service.py index c0d2e3ff..eefc71c5 100644 --- a/api/app/services/draft_run_service.py +++ b/api/app/services/draft_run_service.py @@ -454,7 +454,8 @@ class DraftRunService: storage_type: Optional[str] = None, user_rag_memory_id: Optional[str] = None, web_search: bool = True, # 布尔类型默认值 - memory: bool = True # 布尔类型默认值 + memory: bool = True, # 布尔类型默认值 + sub_agent: bool = False # 是否是作为子Agent运行 ) -> AsyncGenerator[str, None]: """执行试运行(流式返回,使用 LangChain Agent) @@ -619,7 +620,7 @@ class DraftRunService: elapsed_time = time.time() - start_time # 10. 保存会话消息 - if agent_config.memory and agent_config.memory.get("enabled"): + if not sub_agent and agent_config.memory and agent_config.memory.get("enabled"): await self._save_conversation_message( conversation_id=conversation_id, user_message=message, diff --git a/api/app/services/multi_agent_orchestrator.py b/api/app/services/multi_agent_orchestrator.py index 85eaaad2..08ae7e57 100644 --- a/api/app/services/multi_agent_orchestrator.py +++ b/api/app/services/multi_agent_orchestrator.py @@ -1267,7 +1267,8 @@ class MultiAgentOrchestrator: storage_type=storage_type, user_rag_memory_id=user_rag_memory_id, web_search=web_search, - memory=memory + memory=memory, + sub_agent=True ): yield event From 0300abc45422090d0c01a9e40c8e6cf1b6ec8790 Mon Sep 17 00:00:00 2001 From: mengyonghao <1533512157@qq.com> Date: Tue, 6 Jan 2026 10:35:43 +0800 Subject: [PATCH 10/75] feat(workflow): fix concurrent update conflict of looping flag in parallel loop nodes --- api/app/core/workflow/nodes/base_node.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/api/app/core/workflow/nodes/base_node.py b/api/app/core/workflow/nodes/base_node.py index 8eb31fb4..a1ec2e1d 100644 --- a/api/app/core/workflow/nodes/base_node.py +++ b/api/app/core/workflow/nodes/base_node.py @@ -29,7 +29,7 @@ class WorkflowState(TypedDict): # Set of loop node IDs, used for assigning values in loop nodes cycle_nodes: list - looping: bool + looping: Annotated[bool, lambda x, y: x and y] # Input variables (passed from configured variables) # Uses a deep merge function, supporting nested dict updates (e.g., conv.xxx) From 049642ae48f34afe3fb81723d4287f39a224e0dc Mon Sep 17 00:00:00 2001 From: mengyonghao <1533512157@qq.com> Date: Tue, 6 Jan 2026 10:46:55 +0800 Subject: [PATCH 11/75] fix(workflow): require end node only in main graph during runtime validation --- api/app/core/workflow/validator.py | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/api/app/core/workflow/validator.py b/api/app/core/workflow/validator.py index 32f5ad80..6daf415d 100644 --- a/api/app/core/workflow/validator.py +++ b/api/app/core/workflow/validator.py @@ -91,6 +91,7 @@ class WorkflowValidator: """验证工作流配置 Args: + publish: 发布验证标识 workflow_config: 工作流配置字典或 WorkflowConfig Pydantic 模型 Returns: @@ -114,7 +115,7 @@ class WorkflowValidator: graphs = cls.get_subgraph(workflow_config) logger.info(graphs) - for graph in graphs: + for index, graph in enumerate(graphs): nodes = graph.get("nodes", []) edges = graph.get("edges", []) variables = graph.get("variables", []) @@ -125,10 +126,11 @@ class WorkflowValidator: elif len(start_nodes) > 1: errors.append(f"工作流只能有一个 start 节点,当前有 {len(start_nodes)} 个") - # 2. 验证 end 节点(至少一个) - end_nodes = [n for n in nodes if n.get("type") == NodeType.END] - if len(end_nodes) == 0: - errors.append("工作流必须至少有一个 end 节点") + if index == len(graphs) - 1: + # 2. 验证 主图end 节点(至少一个) + end_nodes = [n for n in nodes if n.get("type") == NodeType.END] + if len(end_nodes) == 0: + errors.append("工作流必须至少有一个 end 节点") # 3. 验证节点 ID 唯一性 node_ids = [n.get("id") for n in nodes] From 411525687ed07163dc69d71172f574d93a2c5115 Mon Sep 17 00:00:00 2001 From: mengyonghao <1533512157@qq.com> Date: Tue, 6 Jan 2026 11:38:03 +0800 Subject: [PATCH 12/75] fix(workflow): temporarily ignore non-text fields in knowledge retrieval node --- api/app/core/workflow/nodes/knowledge/node.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/api/app/core/workflow/nodes/knowledge/node.py b/api/app/core/workflow/nodes/knowledge/node.py index e12c6224..d9caae7e 100644 --- a/api/app/core/workflow/nodes/knowledge/node.py +++ b/api/app/core/workflow/nodes/knowledge/node.py @@ -203,15 +203,16 @@ class KnowledgeRetrievalNode(BaseNode): rs2 = vector_service.search_by_full_text(query=query, top_k=kb_config.top_k, indices=indices, score_threshold=kb_config.similarity_threshold) - # Deduplicate hybrid retrieval results + # Deduplicate hy brid retrieval results unique_rs = self._deduplicate_docs(rs1, rs2) vector_service.reranker = self.get_reranker_model() rs.extend(vector_service.rerank(query=query, docs=unique_rs, top_k=kb_config.top_k)) case _: raise RuntimeError("Unknown retrieval type") vector_service.reranker = self.get_reranker_model() + # TODO:其他重排序方式支持 final_rs = vector_service.rerank(query=query, docs=rs, top_k=self.typed_config.reranker_top_k) logger.info( f"Node {self.node_id}: knowledge base retrieval completed, results count: {len(final_rs)}" ) - return [chunk.model_dump() for chunk in final_rs] + return [chunk.page_content for chunk in final_rs] From 962b74a68ac8a219acd140908fad8f44eeec5af6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=B0=A2=E4=BF=8A=E7=94=B7?= Date: Tue, 6 Jan 2026 12:09:55 +0800 Subject: [PATCH 13/75] fix(workflow node): Workflow nodes and question classifier nodes - bug fixes --- .../nodes/question_classifier/node.py | 27 +- api/app/core/workflow/nodes/tool/config.py | 4 +- api/app/core/workflow/nodes/tool/node.py | 32 ++- api/app/repositories/tool_repository.py | 27 ++ api/app/services/tool_service.py | 243 +++++++++++++++++- 5 files changed, 314 insertions(+), 19 deletions(-) diff --git a/api/app/core/workflow/nodes/question_classifier/node.py b/api/app/core/workflow/nodes/question_classifier/node.py index 67f53801..b0f2c28d 100644 --- a/api/app/core/workflow/nodes/question_classifier/node.py +++ b/api/app/core/workflow/nodes/question_classifier/node.py @@ -65,7 +65,7 @@ class QuestionClassifierNode(BaseNode): category_map[category_name] = case_tag return category_map - async def execute(self, state: WorkflowState) -> str: + async def execute(self, state: WorkflowState) -> dict: """执行问题分类""" question = self.typed_config.input_variable supplement_prompt = self.typed_config.user_supplement_prompt or "" @@ -79,7 +79,15 @@ class QuestionClassifierNode(BaseNode): f"(默认分支:{DEFAULT_EMPTY_QUESTION_CASE},分类总数:{category_count})" ) # 若分类列表为空,返回默认unknown分支,否则返回CASE1 - return DEFAULT_EMPTY_QUESTION_CASE if category_count > 0 else "unknown" + if category_count > 0: + return { + "class_name": category_names[0], + "output": DEFAULT_EMPTY_QUESTION_CASE + } + return { + "class_name": "unknown", + "output": DEFAULT_EMPTY_QUESTION_CASE + } try: llm = self._get_llm_instance() @@ -111,7 +119,10 @@ class QuestionClassifierNode(BaseNode): log_supplement = supplement_prompt if supplement_prompt else "无" logger.info(f"节点 {self.node_id} 分类结果: {category}, 用户补充提示词:{log_supplement}") - return f"CASE{category_names.index(category) + 1}" + return { + "class_name": category, + "output": f"CASE{category_names.index(category) + 1}", + } except Exception as e: logger.error( f"节点 {self.node_id} 分类执行异常:{str(e)}", @@ -119,5 +130,11 @@ class QuestionClassifierNode(BaseNode): ) # 异常时返回默认分支,保证工作流容错性 if category_count > 0: - return DEFAULT_EMPTY_QUESTION_CASE - return "unknown" + return { + "class_name": category_names[0], + "output": DEFAULT_EMPTY_QUESTION_CASE + } + return { + "class_name": "unknown", + "output": DEFAULT_EMPTY_QUESTION_CASE + } diff --git a/api/app/core/workflow/nodes/tool/config.py b/api/app/core/workflow/nodes/tool/config.py index 487efae2..d3b1a644 100644 --- a/api/app/core/workflow/nodes/tool/config.py +++ b/api/app/core/workflow/nodes/tool/config.py @@ -1,4 +1,6 @@ from pydantic import Field +from typing import Any + from app.core.workflow.nodes.base_config import BaseNodeConfig @@ -6,4 +8,4 @@ class ToolNodeConfig(BaseNodeConfig): """工具节点配置""" tool_id: str = Field(..., description="工具ID") - tool_parameters: dict[str, str] = Field(default_factory=dict, description="工具参数映射,支持工作流变量") + tool_parameters: dict[str, Any] = Field(default_factory=dict, description="工具参数映射,支持工作流变量") diff --git a/api/app/core/workflow/nodes/tool/node.py b/api/app/core/workflow/nodes/tool/node.py index 993a3804..e1b5f380 100644 --- a/api/app/core/workflow/nodes/tool/node.py +++ b/api/app/core/workflow/nodes/tool/node.py @@ -1,5 +1,5 @@ import logging -import uuid +import re from typing import Any from app.core.workflow.nodes.base_node import BaseNode, WorkflowState @@ -9,6 +9,8 @@ from app.db import get_db_read logger = logging.getLogger(__name__) +TEMPLATE_PATTERN = re.compile(r"\{\{.*?\}\}") + class ToolNode(BaseNode): """工具节点""" @@ -25,25 +27,33 @@ class ToolNode(BaseNode): # 如果没有租户ID,尝试从工作流ID获取 if not tenant_id: - workflow_id = self.get_variable("sys.workflow_id", state) - if workflow_id: + workspace_id = self.get_variable("sys.workspace_id", state) + if workspace_id: from app.repositories.tool_repository import ToolRepository with get_db_read() as db: - tenant_id = ToolRepository.get_tenant_id_by_workflow_id(db, workflow_id) + tenant_id = ToolRepository.get_tenant_id_by_workspace_id(db, workspace_id) if not tenant_id: - tenant_id = uuid.UUID("6c2c91b0-3f49-4489-9157-2208aa56a097") - # logger.error(f"节点 {self.node_id} 缺少租户ID") - # return {"error": "缺少租户ID"} + logger.error(f"节点 {self.node_id} 缺少租户ID") + return { + "success": False, + "data": "缺少租户ID" + } # 渲染工具参数 rendered_parameters = {} for param_name, param_template in self.typed_config.tool_parameters.items(): - rendered_value = self._render_template(param_template, state) + if isinstance(param_template, str) and TEMPLATE_PATTERN.search(param_template): + try: + rendered_value = self._render_template(param_template, state) + except Exception as e: + raise ValueError(f"模板渲染失败:参数 {param_name} 的模板 {param_template} 解析错误") from e + else: + # 非模板参数(数字/布尔/普通字符串)直接保留原值 + rendered_value = param_template rendered_parameters[param_name] = rendered_value logger.info(f"节点 {self.node_id} 执行工具 {self.typed_config.tool_id},参数: {rendered_parameters}") - print(self.typed_config.tool_id) # 执行工具 with get_db_read() as db: @@ -54,7 +64,7 @@ class ToolNode(BaseNode): tenant_id=tenant_id, user_id=user_id ) - print(result) + if result.success: logger.info(f"节点 {self.node_id} 工具执行成功") return { @@ -66,7 +76,7 @@ class ToolNode(BaseNode): logger.error(f"节点 {self.node_id} 工具执行失败: {result.error}") return { "success": False, - "error": result.error, + "data": result.error, "error_code": result.error_code, "execution_time": result.execution_time } \ No newline at end of file diff --git a/api/app/repositories/tool_repository.py b/api/app/repositories/tool_repository.py index 3aa7b16e..257910c3 100644 --- a/api/app/repositories/tool_repository.py +++ b/api/app/repositories/tool_repository.py @@ -38,6 +38,33 @@ class ToolRepository: return result[0] if result else None + @staticmethod + def get_tenant_id_by_workspace_id(db: Session, workspace_id: str) -> Optional[uuid.UUID]: + """ + 根据空间ID获取tenant_id + + Args: + db: 数据库会话 + workspace_id: 空间ID + + Returns: + tenant_id或None + """ + from app.models.workspace_model import Workspace + + tenant_id = db.query(Workspace.tenant_id).filter( + Workspace.id == workspace_id + ).scalar() + + if tenant_id is not None and not isinstance(tenant_id, uuid.UUID): + # 兼容数据库中字段类型不匹配的情况(比如存储为字符串) + try: + tenant_id = uuid.UUID(tenant_id) + except (ValueError, TypeError): + return None + + return tenant_id + @staticmethod def find_by_tenant( db: Session, diff --git a/api/app/services/tool_service.py b/api/app/services/tool_service.py index 50cca957..ab5128fd 100644 --- a/api/app/services/tool_service.py +++ b/api/app/services/tool_service.py @@ -344,14 +344,16 @@ class ToolService: break if operation_param: - # 有多个操作 + # 有多个操作,为每个操作生成具体参数 methods = [] for operation in operation_param.enum: + # 获取该操作的具体参数 + operation_params = self._get_operation_specific_params(tool_instance, operation) methods.append({ "method_id": f"{config.name}_{operation}", "name": operation, "description": f"{config.description} - {operation}", - "parameters": [p for p in tool_instance.parameters if p.name != "operation"] + "parameters": operation_params }) return methods else: @@ -362,6 +364,243 @@ class ToolService: "description": config.description, "parameters": [p for p in tool_instance.parameters if p.name != "operation"] }] + + def _get_operation_specific_params(self, tool_instance: BaseTool, operation: str) -> List[Dict[str, Any]]: + """获取特定操作的参数列表""" + # 对于datetime_tool,根据操作类型返回相关参数 + if hasattr(tool_instance, 'name') and tool_instance.name == 'datetime_tool': + return self._get_datetime_tool_params(operation) + # 对于json_tool,根据操作类型返回相关参数 + elif hasattr(tool_instance, 'name') and tool_instance.name == 'json_tool': + return self._get_json_tool_params(operation) + + # 其他工具的默认处理:返回除operation外的所有参数 + return [{ + "name": param.name, + "type": param.type.value, + "description": param.description, + "required": param.required, + "default": param.default, + "enum": param.enum, + "minimum": param.minimum, + "maximum": param.maximum, + "pattern": param.pattern + } for param in tool_instance.parameters if param.name != "operation"] + + def _get_datetime_tool_params(self, operation: str) -> List[Dict[str, Any]]: + """获取datetime_tool特定操作的参数""" + if operation == "now": + return [ + { + "name": "to_timezone", + "type": "string", + "description": "目标时区(如:UTC, Asia/Shanghai)", + "required": False, + "default": "Asia/Shanghai" + }, + { + "name": "output_format", + "type": "string", + "description": "输出时间格式(如:%Y-%m-%d %H:%M:%S)", + "required": False, + "default": "%Y-%m-%d %H:%M:%S" + } + ] + elif operation == "format": + return [ + { + "name": "input_value", + "type": "string", + "description": "输入值(时间字符串或时间戳)", + "required": True + }, + { + "name": "input_format", + "type": "string", + "description": "输入时间格式(如:%Y-%m-%d %H:%M:%S)", + "required": False, + "default": "%Y-%m-%d %H:%M:%S" + }, + { + "name": "output_format", + "type": "string", + "description": "输出时间格式(如:%Y-%m-%d %H:%M:%S)", + "required": False, + "default": "%Y-%m-%d %H:%M:%S" + } + ] + elif operation == "convert_timezone": + return [ + { + "name": "input_value", + "type": "string", + "description": "输入值(时间字符串或时间戳)", + "required": True + }, + { + "name": "input_format", + "type": "string", + "description": "输入时间格式(如:%Y-%m-%d %H:%M:%S)", + "required": False, + "default": "%Y-%m-%d %H:%M:%S" + }, + { + "name": "output_format", + "type": "string", + "description": "输出时间格式(如:%Y-%m-%d %H:%M:%S)", + "required": False, + "default": "%Y-%m-%d %H:%M:%S" + }, + { + "name": "from_timezone", + "type": "string", + "description": "源时区(如:UTC, Asia/Shanghai)", + "required": False, + "default": "Asia/Shanghai" + }, + { + "name": "to_timezone", + "type": "string", + "description": "目标时区(如:UTC, Asia/Shanghai)", + "required": False, + "default": "Asia/Shanghai" + } + ] + elif operation == "timestamp_to_datetime": + return [ + { + "name": "input_value", + "type": "string", + "description": "输入值(时间字符串或时间戳)", + "required": True + }, + { + "name": "output_format", + "type": "string", + "description": "输出时间格式(如:%Y-%m-%d %H:%M:%S)", + "required": False, + "default": "%Y-%m-%d %H:%M:%S" + }, + { + "name": "to_timezone", + "type": "string", + "description": "目标时区(如:UTC, Asia/Shanghai)", + "required": False, + "default": "Asia/Shanghai" + } + ] + else: + # 默认返回所有参数(除了operation) + return [ + { + "name": "input_value", + "type": "string", + "description": "输入值(时间字符串或时间戳)", + "required": False + }, + { + "name": "input_format", + "type": "string", + "description": "输入时间格式(如:%Y-%m-%d %H:%M:%S)", + "required": False, + "default": "%Y-%m-%d %H:%M:%S" + }, + { + "name": "output_format", + "type": "string", + "description": "输出时间格式(如:%Y-%m-%d %H:%M:%S)", + "required": False, + "default": "%Y-%m-%d %H:%M:%S" + }, + { + "name": "from_timezone", + "type": "string", + "description": "源时区(如:UTC, Asia/Shanghai)", + "required": False, + "default": "Asia/Shanghai" + }, + { + "name": "to_timezone", + "type": "string", + "description": "目标时区(如:UTC, Asia/Shanghai)", + "required": False, + "default": "Asia/Shanghai" + }, + { + "name": "calculation", + "type": "string", + "description": "时间计算表达式(如:+1d, -2h, +30m)", + "required": False + } + ] + + def _get_json_tool_params(self, operation: str) -> List[Dict[str, Any]]: + """获取json_tool特定操作的参数""" + base_params = [ + { + "name": "input_data", + "type": "string", + "description": "输入数据(JSON字符串、YAML字符串或XML字符串)", + "required": True + } + ] + + if operation == "insert": + return base_params + [ + { + "name": "json_path", + "type": "string", + "description": "JSON路径表达式(如:$.user.name或users[0].name)", + "required": True + }, + { + "name": "new_value", + "type": "string", + "description": "新值(用于insert操作)", + "required": True + } + ] + elif operation == "replace": + return base_params + [ + { + "name": "json_path", + "type": "string", + "description": "JSON路径表达式(如:$.user.name或users[0].name)", + "required": True + }, + { + "name": "old_text", + "type": "string", + "description": "要替换的原文本(用于replace操作)", + "required": True + }, + { + "name": "new_text", + "type": "string", + "description": "替换后的新文本(用于replace操作)", + "required": True + } + ] + elif operation == "delete": + return base_params + [ + { + "name": "json_path", + "type": "string", + "description": "JSON路径表达式(如:$.user.name或users[0].name)", + "required": True + } + ] + elif operation == "parse": + return base_params + [ + { + "name": "json_path", + "type": "string", + "description": "JSON路径表达式(如:$.user.name或users[0].name)", + "required": True + } + ] + + return base_params async def _get_custom_tool_methods(self, config: ToolConfig) -> List[Dict[str, Any]]: """获取自定义工具的方法""" From 8d3ec8c047dcdd402e57b1ba084e78195c038208 Mon Sep 17 00:00:00 2001 From: zhaoying Date: Tue, 6 Jan 2026 13:06:24 +0800 Subject: [PATCH 14/75] fix(web): workflow bug --- web/src/i18n/en.ts | 29 ++- web/src/i18n/zh.ts | 27 ++- .../AddChatVariable/ChatVariableModal.tsx | 1 - .../Editor/plugin/CharacterCountPlugin.tsx | 9 +- .../Editor/plugin/InitialValuePlugin.tsx | 15 ++ .../Workflow/components/Nodes/AddNode.tsx | 6 +- .../Workflow/components/Nodes/LoopNode.tsx | 5 +- .../Workflow/components/PortClickHandler.tsx | 4 +- .../Properties/AssignmentList/index.tsx | 64 +++-- .../components/Properties/CaseList/index.tsx | 156 +++++++++---- .../Properties/ConditionList/index.tsx | 150 +++++++++--- .../Properties/CycleVarsList/index.tsx | 2 +- .../Properties/GroupVariableList/index.tsx | 5 +- .../Properties/HttpRequest/EditableTable.tsx | 219 +++++++----------- .../Properties/HttpRequest/index.tsx | 4 +- .../Properties/Knowledge/Knowledge.tsx | 47 ++-- .../Properties/MappingList/index.tsx | 51 ++-- .../components/Properties/MessageEditor.tsx | 133 +++++------ .../Workflow/components/Properties/index.tsx | 133 +++++++++-- web/src/views/Workflow/constant.ts | 12 +- .../views/Workflow/hooks/useWorkflowGraph.ts | 21 +- 21 files changed, 698 insertions(+), 395 deletions(-) diff --git a/web/src/i18n/en.ts b/web/src/i18n/en.ts index 0f3f5898..d186368b 100644 --- a/web/src/i18n/en.ts +++ b/web/src/i18n/en.ts @@ -1793,12 +1793,20 @@ Memory Bear: After the rebellion, regional warlordism intensified for several re "not_contains": 'Does Not Contain', "startwith": 'Starts With', "endwith": 'Ends With', - "eq": '==', - "ne": '!=', - "lt": '<', - "le": '<=', - "gt": '>', - "ge": '>=', + "eq": 'Equals', + "ne": 'Not Equals', + num: { + "eq": '=', + "ne": '≠', + "lt": '<', + "le": '≤', + "gt": '>', + "ge": '≥', + }, + boolean: { + "eq": 'Is', + "ne": 'Is Not', + }, else_desc: 'Used to define the logic that should be executed when the if condition is not met.' }, 'http-request': { @@ -1839,12 +1847,17 @@ Memory Bear: After the rebellion, regional warlordism intensified for several re loop: { cycle_vars: 'Loop Variables', condition: 'Loop Termination Condition', + max_loop: 'Maximum Loop Count', }, assigner: { assignments: 'Variables', - cover: 'Overwrite', + cover: 'Override', assign: 'Set', - clear: 'Clear' + clear: 'Clear', + add: '+=', + subtract: '-=', + multiply: '*=', + divide: '/=', }, iteration: { input: 'Input Variable', diff --git a/web/src/i18n/zh.ts b/web/src/i18n/zh.ts index 4aa03990..028bd1df 100644 --- a/web/src/i18n/zh.ts +++ b/web/src/i18n/zh.ts @@ -1893,12 +1893,20 @@ export const zh = { "not_contains": '不包含', "startwith": '开始是', "endwith": '结束是', - "eq": '==', - "ne": '!=', - "lt": '<', - "le": '<=', - "gt": '>', - "ge": '>=', + "eq": '是', + "ne": '不是', + num: { + "eq": '=', + "ne": '≠', + "lt": '<', + "le": '≤', + "gt": '>', + "ge": '≥', + }, + boolean: { + "eq": '是', + "ne": '不是', + }, else_desc: '用于定义当 if 条件不满足时应执行的逻辑。' }, 'http-request': { @@ -1939,12 +1947,17 @@ export const zh = { loop: { cycle_vars: '循环变量', condition: '循环终止条件', + max_loop: '最大循环次数', }, assigner: { assignments: '变量', cover: '覆盖', assign: '设置', - clear: '清空' + clear: '清空', + add: '+=', + subtract: '-=', + multiply: '*=', + divide: '/=', }, iteration: { input: '输入变量', diff --git a/web/src/views/Workflow/components/AddChatVariable/ChatVariableModal.tsx b/web/src/views/Workflow/components/AddChatVariable/ChatVariableModal.tsx index 571f1e4e..fabe45ba 100644 --- a/web/src/views/Workflow/components/AddChatVariable/ChatVariableModal.tsx +++ b/web/src/views/Workflow/components/AddChatVariable/ChatVariableModal.tsx @@ -26,7 +26,6 @@ const ChatVariableModal = forwardRef(); const [loading, setLoading] = useState(false) const [editIndex, setEditIndex] = useState(undefined) - const typeValue = Form.useWatch('type', form); // 封装取消方法,添加关闭弹窗逻辑 const handleClose = () => { diff --git a/web/src/views/Workflow/components/Editor/plugin/CharacterCountPlugin.tsx b/web/src/views/Workflow/components/Editor/plugin/CharacterCountPlugin.tsx index 963f824b..ed07392d 100644 --- a/web/src/views/Workflow/components/Editor/plugin/CharacterCountPlugin.tsx +++ b/web/src/views/Workflow/components/Editor/plugin/CharacterCountPlugin.tsx @@ -14,18 +14,23 @@ const CharacterCountPlugin = ({ setCount, onChange }: { setCount: (count: number let serializedContent = ''; // Traverse all nodes and serialize properly + const paragraphs: string[] = []; root.getChildren().forEach(child => { if ($isParagraphNode(child)) { + let paragraphContent = ''; child.getChildren().forEach(node => { if ($isVariableNode(node)) { - serializedContent += node.getTextContent(); + paragraphContent += node.getTextContent(); } else { - serializedContent += node.getTextContent(); + paragraphContent += node.getTextContent(); } }); + paragraphs.push(paragraphContent); } }); + serializedContent = paragraphs.join('\n'); + setCount(serializedContent.length); onChange?.(serializedContent); }); diff --git a/web/src/views/Workflow/components/Editor/plugin/InitialValuePlugin.tsx b/web/src/views/Workflow/components/Editor/plugin/InitialValuePlugin.tsx index 4059b300..93197150 100644 --- a/web/src/views/Workflow/components/Editor/plugin/InitialValuePlugin.tsx +++ b/web/src/views/Workflow/components/Editor/plugin/InitialValuePlugin.tsx @@ -26,6 +26,7 @@ const InitialValuePlugin: React.FC = ({ value, options parts.forEach(part => { const match = part.match(/^\{\{([^.]+)\.([^}]+)\}\}$/); const contextMatch = part.match(/^\{\{context\}\}$/); + const conversationMatch = part.match(/^\{\{conv\.([^}]+)\}\}$/); // 匹配{{context}}格式 if (contextMatch) { @@ -38,6 +39,20 @@ const InitialValuePlugin: React.FC = ({ value, options return } + // 匹配{{conv.xx}}格式 + if (conversationMatch) { + const [_, variableName] = conversationMatch; + const conversationSuggestion = options.find(s => + s.group === 'CONVERSATION' && s.label === variableName + ); + if (conversationSuggestion) { + paragraph.append($createVariableNode(conversationSuggestion)); + } else { + paragraph.append($createTextNode(part)); + } + return + } + // 匹配普通变量{{nodeId.label}}格式 if (match) { const [_, nodeId, label] = match; diff --git a/web/src/views/Workflow/components/Nodes/AddNode.tsx b/web/src/views/Workflow/components/Nodes/AddNode.tsx index a2f6d930..973a503c 100644 --- a/web/src/views/Workflow/components/Nodes/AddNode.tsx +++ b/web/src/views/Workflow/components/Nodes/AddNode.tsx @@ -13,13 +13,15 @@ const AddNode: ReactShapeConfig['component'] = ({ node, graph }) => { const handleNodeSelect = (selectedNodeType: any) => { const parentBBox = node.getBBox(); const cycleId = data.cycle; - + + const id = `${selectedNodeType.type.replace(/-/g, '_') }_${Date.now()}_${Math.random().toString(36).substr(2, 9)}` const newNode = graph.addNode({ ...(graphNodeLibrary[selectedNodeType.type] || graphNodeLibrary.default), x: parentBBox.x, y: parentBBox.y, + id, data: { - id: `${selectedNodeType.type}_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`, + id, type: selectedNodeType.type, icon: selectedNodeType.icon, name: t(`workflow.${selectedNodeType.type}`), diff --git a/web/src/views/Workflow/components/Nodes/LoopNode.tsx b/web/src/views/Workflow/components/Nodes/LoopNode.tsx index b0b8d4ce..37feb2dc 100644 --- a/web/src/views/Workflow/components/Nodes/LoopNode.tsx +++ b/web/src/views/Workflow/components/Nodes/LoopNode.tsx @@ -75,12 +75,15 @@ const LoopNode: ReactShapeConfig['component'] = ({ node, graph }) => { const parentBBox = node.getBBox(); const centerX = parentBBox.x + 24; // 默认节点宽度的一半 const centerY = parentBBox.y + 50; // 默认节点高度的一半 - + + const cycleStartNodeId = `cycle_start_${Date.now()}_${Math.random().toString(36).substr(2, 9)}` const cycleStartNode = graph.addNode({ ...graphNodeLibrary.cycleStart, x: centerX, y: centerY, + id: cycleStartNodeId, data: { + id: cycleStartNodeId, type: 'cycle-start', parentId: node.id, isDefault: true, // 标记为默认节点,不可删除 diff --git a/web/src/views/Workflow/components/PortClickHandler.tsx b/web/src/views/Workflow/components/PortClickHandler.tsx index 0be6fba1..9a644438 100644 --- a/web/src/views/Workflow/components/PortClickHandler.tsx +++ b/web/src/views/Workflow/components/PortClickHandler.tsx @@ -43,12 +43,14 @@ const PortClickHandler: React.FC = ({ graph }) => { const newY = sourceBBox.y; // 创建新节点 + const id = `${selectedNodeType.type.replace(/-/g, '_')}_${Date.now()}_${Math.random().toString(36).substr(2, 9)}` const newNode = graph.addNode({ ...(graphNodeLibrary[selectedNodeType.type] || graphNodeLibrary.default), x: newX, y: newY, + id, data: { - id: `${selectedNodeType.type}_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`, + id, type: selectedNodeType.type, icon: selectedNodeType.icon, name: t(`workflow.${selectedNodeType.type}`), diff --git a/web/src/views/Workflow/components/Properties/AssignmentList/index.tsx b/web/src/views/Workflow/components/Properties/AssignmentList/index.tsx index 34c133c7..eac3775f 100644 --- a/web/src/views/Workflow/components/Properties/AssignmentList/index.tsx +++ b/web/src/views/Workflow/components/Properties/AssignmentList/index.tsx @@ -1,6 +1,6 @@ import { type FC } from 'react' import { useTranslation } from 'react-i18next'; -import { Form, Input, Button, Row, Col, Select } from 'antd' +import { Form, Input, Row, Col, Select, InputNumber, Radio } from 'antd' import { MinusCircleOutlined, PlusOutlined } from '@ant-design/icons'; import type { Suggestion } from '../../Editor/plugin/AutocompletePlugin' import VariableSelect from '../VariableSelect' @@ -11,6 +11,23 @@ interface AssignmentListProps { options: Suggestion[]; } +const operationsObj = { + number: [ + { value: 'cover', label: 'workflow.config.assigner.cover' }, + { value: 'clear', label: 'workflow.config.assigner.clear' }, + { value: 'assign', label: 'workflow.config.assigner.assign' }, + { value: 'add', label: 'workflow.config.assigner.add' }, + { value: 'subtract', label: 'workflow.config.assigner.subtract' }, + { value: 'multiply', label: 'workflow.config.assigner.multiply' }, + { value: 'divide', label: 'workflow.config.assigner.divide' }, + ], + default: [ + { value: 'cover', label: 'workflow.config.assigner.cover' }, + { value: 'clear', label: 'workflow.config.assigner.clear' }, + { value: 'assign', label: 'workflow.config.assigner.assign' }, + ], +} + const AssignmentList: FC = ({ parentName, options = [], @@ -27,6 +44,11 @@ const AssignmentList: FC = ({ add({ operation: 'cover'})} />
{fields.map(({ key, name, ...restField }) => { + const variableSelector = form.getFieldValue([parentName, name, 'variable_selector']); + const selectedOption = options.find(option => `{{${option.value}}}` === variableSelector); + const dataType = selectedOption?.dataType; + const operationOptions = dataType === 'number' ? operationsObj.number : operationsObj.default; + return (
@@ -50,11 +72,10 @@ const AssignmentList: FC = ({ noStyle > ({ - value: key, - label: t(`workflow.config.if-else.${key}`) + options={operatorList.map(vo => ({ + ...vo, + label: t(String(vo?.label || '')) }))} size="small" popupMatchSelectWidth={false} + placeholder={t('common.pleaseSelect')} /> @@ -280,11 +321,48 @@ const CaseList: FC = ({ - {!hideRightField && ( - - - - )} + {!hideRightField && <> + {leftFieldType === 'number' + ? + + + ({ - value: key, - label: t(`workflow.config.if-else.${key}`) + options={operatorList.map(vo => ({ + ...vo, + label: t(String(vo?.label || '')) }))} size="small" popupMatchSelectWidth={false} @@ -104,14 +139,53 @@ const ConditionList: FC = ({ onClick={() => remove(field.name)} /> - - {!hideRightField && ( - - - - - - )} + + {!hideRightField && <> + {leftFieldType === 'number' + ? + + + { - console.log('value record', value) - handleChange(record.key, 'type', value) - }} - /> - ), - }, - { - title: t('workflow.config.value'), + const columns = useMemo(() => { + const baseColumns = [ + { + title: typeOptions.length > 0 ? t('workflow.config.name') : '键', + dataIndex: 'name', + width: typeOptions.length > 0 ? '35%' : '45%', + render: (text: string, record: TableRow) => ( + handleChange(record.key, 'name', value || '')} + /> + ), + } + ]; + + if (typeOptions.length > 0) { + baseColumns.push({ + title: t('workflow.config.type'), + dataIndex: 'type', + width: '20%', + render: (text: string, record: TableRow) => ( + - - - - - remove(name)} /> - + + + + + + + + + + + + + remove(name)} /> + + ))} diff --git a/web/src/views/ApplicationConfig/components/Editor/index.tsx b/web/src/views/ApplicationConfig/components/Editor/index.tsx new file mode 100644 index 00000000..d381e003 --- /dev/null +++ b/web/src/views/ApplicationConfig/components/Editor/index.tsx @@ -0,0 +1,91 @@ +import {forwardRef, useImperativeHandle } from 'react'; +import clsx from 'clsx'; +import { LexicalComposer } from '@lexical/react/LexicalComposer'; +import { RichTextPlugin } from '@lexical/react/LexicalRichTextPlugin'; +import { ContentEditable } from '@lexical/react/LexicalContentEditable'; +import { LexicalErrorBoundary } from '@lexical/react/LexicalErrorBoundary'; +import { $getSelection } from 'lexical'; +import { useLexicalComposerContext } from '@lexical/react/LexicalComposerContext'; +import InitialValuePlugin from './plugin/InitialValuePlugin' +import LineBreakPlugin from './plugin/LineBreakPlugin'; +import InsertTextPlugin from './plugin/InsertTextPlugin'; + +export interface EditorRef { + insertText: (text: string) => void; +} + +interface LexicalEditorProps { + className?: string; + placeholder?: string; + value?: string; + onChange?: (value: string) => void; + height?: number; +} + +const theme = { + paragraph: 'editor-paragraph', + text: { + bold: 'editor-text-bold', + italic: 'editor-text-italic', + }, +}; + +const EditorContent = forwardRef(({ + className = '', + value, + placeholder = "请输入内容...", + onChange, +}, ref) => { + const [editor] = useLexicalComposerContext(); + + useImperativeHandle(ref, () => ({ + insertText: (text: string) => { + editor.update(() => { + const selection = $getSelection(); + if (selection) { + selection.insertText(text); + } + }); + } + }), [editor]); + + return ( +
+ + } + placeholder={ +
+ {placeholder} +
+ } + ErrorBoundary={LexicalErrorBoundary} + /> + + + +
+ ); +}); + +const Editor = forwardRef((props, ref) => { + const initialConfig = { + namespace: 'Editor', + theme, + nodes: [], + onError: (error: Error) => { + console.error(error); + }, + }; + + return ( + + + + ); +}); + +export default Editor; \ No newline at end of file diff --git a/web/src/views/ApplicationConfig/components/Editor/plugin/InitialValuePlugin.tsx b/web/src/views/ApplicationConfig/components/Editor/plugin/InitialValuePlugin.tsx new file mode 100644 index 00000000..b1054055 --- /dev/null +++ b/web/src/views/ApplicationConfig/components/Editor/plugin/InitialValuePlugin.tsx @@ -0,0 +1,25 @@ +import { type FC, useEffect } from 'react'; +import { $getRoot, $createParagraphNode, $createTextNode } from 'lexical'; +import { useLexicalComposerContext } from '@lexical/react/LexicalComposerContext'; + +// 设置初始值的插件 +const InitialValuePlugin: FC<{ value?: string }> = ({ value }) => { + const [editor] = useLexicalComposerContext(); + + useEffect(() => { + if (value) { + editor.update(() => { + const root = $getRoot(); + root.clear(); + const paragraph = $createParagraphNode(); + const textNode = $createTextNode(value); + paragraph.append(textNode); + root.append(paragraph); + }); + } + }, [editor, value]); + + return null; +}; + +export default InitialValuePlugin \ No newline at end of file diff --git a/web/src/views/ApplicationConfig/components/Editor/plugin/InsertTextPlugin.tsx b/web/src/views/ApplicationConfig/components/Editor/plugin/InsertTextPlugin.tsx new file mode 100644 index 00000000..ca75c393 --- /dev/null +++ b/web/src/views/ApplicationConfig/components/Editor/plugin/InsertTextPlugin.tsx @@ -0,0 +1,24 @@ +import { forwardRef, useImperativeHandle } from 'react'; +import { $getSelection } from 'lexical'; +import { useLexicalComposerContext } from '@lexical/react/LexicalComposerContext'; +import type { EditorRef } from '../index' + +// 插入文本的插件 +const InsertTextPlugin = forwardRef((_, ref) => { + const [editor] = useLexicalComposerContext(); + + useImperativeHandle(ref, () => ({ + insertText: (text: string) => { + editor.update(() => { + const selection = $getSelection(); + if (selection) { + selection.insertText(text); + } + }); + } + }), [editor]); + + return null; +}); + +export default InsertTextPlugin; \ No newline at end of file diff --git a/web/src/views/ApplicationConfig/components/Editor/plugin/LineBreakPlugin.tsx b/web/src/views/ApplicationConfig/components/Editor/plugin/LineBreakPlugin.tsx new file mode 100644 index 00000000..63d1ffc4 --- /dev/null +++ b/web/src/views/ApplicationConfig/components/Editor/plugin/LineBreakPlugin.tsx @@ -0,0 +1,24 @@ +import { type FC, useEffect } from 'react'; +import { $getRoot } from 'lexical'; +import { useLexicalComposerContext } from '@lexical/react/LexicalComposerContext'; + +// 处理换行的插件 +const LineBreakPlugin: FC<{ onChange?: (value: string) => void }> = ({ onChange }) => { + const [editor] = useLexicalComposerContext(); + + useEffect(() => { + return editor.registerUpdateListener(({ editorState }) => { + editorState.read(() => { + const root = $getRoot(); + const textContent = root.getTextContent(); + // 将\n转换为实际换行 + const processedContent = textContent.replace(/\\n/g, '\n'); + onChange?.(processedContent); + }); + }); + }, [editor, onChange]); + + return null; +}; + +export default LineBreakPlugin; \ No newline at end of file diff --git a/web/src/views/Workflow/constant.ts b/web/src/views/Workflow/constant.ts index c398eb70..babc8614 100644 --- a/web/src/views/Workflow/constant.ts +++ b/web/src/views/Workflow/constant.ts @@ -394,7 +394,8 @@ export const nodeLibrary: NodeLibrary[] = [ defaultValue: {} }, retry: { - type: 'define', + type: 'switch', + defaultValue: false }, error_handle: { type: 'define', From 492401f9b7293abc0f1b96ec8ba7b7fa6085b375 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=B0=A2=E4=BF=8A=E7=94=B7?= Date: Tue, 6 Jan 2026 15:25:25 +0800 Subject: [PATCH 20/75] feat(agent tool): add agent tool plugin --- api/app/controllers/home_page_controller.py | 8 +- .../controllers/service/app_api_controller.py | 6 +- api/app/core/agent/langchain_agent.py | 8 +- api/app/core/config.py | 3 + api/app/core/tools/base.py | 10 +- api/app/core/tools/builtin/operation_tool.py | 216 ++++++++++++++++++ api/app/core/tools/custom/base.py | 8 + api/app/core/tools/langchain_adapter.py | 34 ++- api/app/core/tools/mcp/service_manager.py | 11 +- api/app/services/app_chat_service.py | 62 ++--- api/app/services/draft_run_service.py | 73 +++--- 11 files changed, 349 insertions(+), 90 deletions(-) create mode 100644 api/app/core/tools/builtin/operation_tool.py diff --git a/api/app/controllers/home_page_controller.py b/api/app/controllers/home_page_controller.py index 6665eec1..f1a5310d 100644 --- a/api/app/controllers/home_page_controller.py +++ b/api/app/controllers/home_page_controller.py @@ -1,6 +1,7 @@ from fastapi import APIRouter, Depends from sqlalchemy.orm import Session +from app.core.config import settings from app.core.response_utils import success from app.db import get_db from app.dependencies import get_current_user @@ -26,4 +27,9 @@ def get_workspace_list( ): """获取工作空间列表""" workspace_list = HomePageService.get_workspace_list(db, current_user.tenant_id) - return success(data=workspace_list, msg="工作空间列表获取成功") \ No newline at end of file + return success(data=workspace_list, msg="工作空间列表获取成功") + +@router.get("/version", response_model=ApiResponse) +def get_system_version(): + """获取系统版本号""" + return success(data={"version": settings.SYSTEM_VERSION}, msg="系统版本获取成功") \ No newline at end of file diff --git a/api/app/controllers/service/app_api_controller.py b/api/app/controllers/service/app_api_controller.py index 5a78a28b..ae40e2aa 100644 --- a/api/app/controllers/service/app_api_controller.py +++ b/api/app/controllers/service/app_api_controller.py @@ -153,7 +153,8 @@ async def chat( config=agent_config, memory=memory, storage_type=storage_type, - user_rag_memory_id=user_rag_memory_id + user_rag_memory_id=user_rag_memory_id, + workspace_id=workspace_id ): yield event @@ -177,7 +178,8 @@ async def chat( web_search=web_search, memory=memory, storage_type=storage_type, - user_rag_memory_id=user_rag_memory_id + user_rag_memory_id=user_rag_memory_id, + workspace_id=workspace_id ) return success(data=conversation_schema.ChatResponse(**result).model_dump(mode="json")) elif app_type == AppType.MULTI_AGENT: diff --git a/api/app/core/agent/langchain_agent.py b/api/app/core/agent/langchain_agent.py index 380b660c..acd8cc5b 100644 --- a/api/app/core/agent/langchain_agent.py +++ b/api/app/core/agent/langchain_agent.py @@ -97,8 +97,7 @@ class LangChainAgent: "temperature": temperature, "streaming": streaming, "tool_count": len(self.tools), - "tool_names": [tool.name for tool in self.tools] if self.tools else [], - "tool_count": len(self.tools) + "tool_names": [tool.name for tool in self.tools] if self.tools else [] } ) @@ -139,8 +138,11 @@ class LangChainAgent: messages.append(HumanMessage(content=user_content)) return messages + async def term_memory_save(self,messages,end_user_end,aimessages): - '''短长期存储redis,为不影响正常使用6句一段话,存储用户名加一个前缀,当数据存够6条返回给neo4j''' + """ + 短长期存储redis,为不影响正常使用6句一段话,存储用户名加一个前缀,当数据存够6条返回给neo4j + """ end_user_end=f"Term_{end_user_end}" print(messages) print(aimessages) diff --git a/api/app/core/config.py b/api/app/core/config.py index 7494b89d..b02b94a5 100644 --- a/api/app/core/config.py +++ b/api/app/core/config.py @@ -164,6 +164,9 @@ class Settings: TOOL_EXECUTION_TIMEOUT: int = int(os.getenv("TOOL_EXECUTION_TIMEOUT", "60")) TOOL_MAX_CONCURRENCY: int = int(os.getenv("TOOL_MAX_CONCURRENCY", "10")) ENABLE_TOOL_MANAGEMENT: bool = os.getenv("ENABLE_TOOL_MANAGEMENT", "true").lower() == "true" + + # official environment system version + SYSTEM_VERSION: str = os.getenv("SYSTEM_VERSION", "v1.0.0") def get_memory_output_path(self, filename: str = "") -> str: """ diff --git a/api/app/core/tools/base.py b/api/app/core/tools/base.py index ec15c50f..2cdc0f60 100644 --- a/api/app/core/tools/base.py +++ b/api/app/core/tools/base.py @@ -191,10 +191,14 @@ class BaseTool(ABC): execution_time=execution_time ) - def to_langchain_tool(self): - """转换为Langchain工具格式""" + def to_langchain_tool(self, operation: Optional[str] = None): + """转换为Langchain工具格式 + + Args: + operation: 特定操作(适用于有操作的工具) + """ from app.core.tools.langchain_adapter import LangchainAdapter - return LangchainAdapter.convert_tool(self) + return LangchainAdapter.convert_tool(self, operation) def __repr__(self): return f"<{self.__class__.__name__}(id={self.tool_id}, name={self.name})>" \ No newline at end of file diff --git a/api/app/core/tools/builtin/operation_tool.py b/api/app/core/tools/builtin/operation_tool.py new file mode 100644 index 00000000..126541a8 --- /dev/null +++ b/api/app/core/tools/builtin/operation_tool.py @@ -0,0 +1,216 @@ +"""操作工具 - 为特定操作创建的工具包装器""" +from typing import List +from app.core.tools.base import BaseTool, ToolParameter, ToolResult, ParameterType +from app.models import ToolType + + +class OperationTool(BaseTool): + """操作工具 - 包装基础工具的特定操作""" + + def __init__(self, base_tool: BaseTool, operation: str): + self.base_tool = base_tool + self.operation = operation + super().__init__(base_tool.tool_id, base_tool.config) + + @property + def name(self) -> str: + return f"{self.base_tool.name}_{self.operation}" + + @property + def tool_type(self) -> ToolType: + """工具类型""" + return ToolType.BUILTIN + + @property + def description(self) -> str: + return f"{self.base_tool.description} - {self.operation}" + + @property + def parameters(self) -> List[ToolParameter]: + """返回特定操作的参数""" + if self.base_tool.name == 'datetime_tool': + return self._get_datetime_params() + elif self.base_tool.name == 'json_tool': + return self._get_json_params() + else: + # 默认返回除operation外的所有参数 + return [p for p in self.base_tool.parameters if p.name != "operation"] + + def _get_datetime_params(self) -> List[ToolParameter]: + """获取datetime_tool特定操作的参数""" + if self.operation == "now": + return [ + ToolParameter( + name="to_timezone", + type=ParameterType.STRING, + description="目标时区(如:UTC, Asia/Shanghai)", + required=False, + default="Asia/Shanghai" + ), + ToolParameter( + name="output_format", + type=ParameterType.STRING, + description="输出时间格式(如:%Y-%m-%d %H:%M:%S)", + required=False, + default="%Y-%m-%d %H:%M:%S" + ) + ] + elif self.operation == "format": + return [ + ToolParameter( + name="input_value", + type=ParameterType.STRING, + description="输入值(时间字符串或时间戳)", + required=True + ), + ToolParameter( + name="input_format", + type=ParameterType.STRING, + description="输入时间格式(如:%Y-%m-%d %H:%M:%S)", + required=False, + default="%Y-%m-%d %H:%M:%S" + ), + ToolParameter( + name="output_format", + type=ParameterType.STRING, + description="输出时间格式(如:%Y-%m-%d %H:%M:%S)", + required=False, + default="%Y-%m-%d %H:%M:%S" + ) + ] + elif self.operation == "convert_timezone": + return [ + ToolParameter( + name="input_value", + type=ParameterType.STRING, + description="输入值(时间字符串或时间戳)", + required=True + ), + ToolParameter( + name="input_format", + type=ParameterType.STRING, + description="输入时间格式(如:%Y-%m-%d %H:%M:%S)", + required=False, + default="%Y-%m-%d %H:%M:%S" + ), + ToolParameter( + name="output_format", + type=ParameterType.STRING, + description="输出时间格式(如:%Y-%m-%d %H:%M:%S)", + required=False, + default="%Y-%m-%d %H:%M:%S" + ), + ToolParameter( + name="from_timezone", + type=ParameterType.STRING, + description="源时区(如:UTC, Asia/Shanghai)", + required=False, + default="Asia/Shanghai" + ), + ToolParameter( + name="to_timezone", + type=ParameterType.STRING, + description="目标时区(如:UTC, Asia/Shanghai)", + required=False, + default="Asia/Shanghai" + ) + ] + elif self.operation == "timestamp_to_datetime": + return [ + ToolParameter( + name="input_value", + type=ParameterType.STRING, + description="输入值(时间字符串或时间戳)", + required=True + ), + ToolParameter( + name="output_format", + type=ParameterType.STRING, + description="输出时间格式(如:%Y-%m-%d %H:%M:%S)", + required=False, + default="%Y-%m-%d %H:%M:%S" + ), + ToolParameter( + name="to_timezone", + type=ParameterType.STRING, + description="目标时区(如:UTC, Asia/Shanghai)", + required=False, + default="Asia/Shanghai" + ) + ] + else: + return [] + + def _get_json_params(self) -> List[ToolParameter]: + """获取json_tool特定操作的参数""" + base_params = [ + ToolParameter( + name="input_data", + type=ParameterType.STRING, + description="输入数据(JSON字符串、YAML字符串或XML字符串)", + required=True + ) + ] + + if self.operation == "insert": + return base_params + [ + ToolParameter( + name="json_path", + type=ParameterType.STRING, + description="JSON路径表达式(如:$.user.name或users[0].name)", + required=True + ), + ToolParameter( + name="new_value", + type=ParameterType.STRING, + description="新值(用于insert操作)", + required=True + ) + ] + elif self.operation == "replace": + return base_params + [ + ToolParameter( + name="json_path", + type=ParameterType.STRING, + description="JSON路径表达式(如:$.user.name或users[0].name)", + required=True + ), + ToolParameter( + name="old_text", + type=ParameterType.STRING, + description="要替换的原文本(用于replace操作)", + required=True + ), + ToolParameter( + name="new_text", + type=ParameterType.STRING, + description="替换后的新文本(用于replace操作)", + required=True + ) + ] + elif self.operation == "delete": + return base_params + [ + ToolParameter( + name="json_path", + type=ParameterType.STRING, + description="JSON路径表达式(如:$.user.name或users[0].name)", + required=True + ) + ] + elif self.operation == "parse": + return base_params + [ + ToolParameter( + name="json_path", + type=ParameterType.STRING, + description="JSON路径表达式(如:$.user.name或users[0].name)", + required=True + ) + ] + else: + return base_params + + async def execute(self, **kwargs) -> ToolResult: + """执行特定操作""" + # 添加operation参数 + kwargs["operation"] = self.operation + return await self.base_tool.execute(**kwargs) \ No newline at end of file diff --git a/api/app/core/tools/custom/base.py b/api/app/core/tools/custom/base.py index 0d656a8e..3dfe4c93 100644 --- a/api/app/core/tools/custom/base.py +++ b/api/app/core/tools/custom/base.py @@ -1,4 +1,5 @@ """自定义工具基类""" +import json import time from typing import Dict, Any, List, Optional import aiohttp @@ -135,6 +136,13 @@ class CustomTool(BaseTool): if not self.schema_content: return operations + + if isinstance(self.schema_content, str): + try: + self.schema_content = json.loads(self.schema_content) + except json.JSONDecodeError: + logger.error(f"无效的OpenAPI schema: {self.schema_content}") + return operations paths = self.schema_content.get("paths", {}) diff --git a/api/app/core/tools/langchain_adapter.py b/api/app/core/tools/langchain_adapter.py index 1b6969b9..89ccc205 100644 --- a/api/app/core/tools/langchain_adapter.py +++ b/api/app/core/tools/langchain_adapter.py @@ -38,7 +38,7 @@ class LangchainToolWrapper(LangchainBaseTool): name=tool_instance.name, description=tool_instance.description, args_schema=args_schema, - _tool_instance=tool_instance, + tool_instance=tool_instance, **kwargs ) @@ -59,7 +59,7 @@ class LangchainToolWrapper(LangchainBaseTool): """异步执行工具""" try: # 执行内部工具 - result = await self._tool_instance.safe_execute(**kwargs) + result = await self.tool_instance.safe_execute(**kwargs) # 转换结果为Langchain格式 return LangchainAdapter._format_result_for_langchain(result) @@ -73,24 +73,39 @@ class LangchainAdapter: """Langchain适配器 - 负责工具格式转换和标准化""" @staticmethod - def convert_tool(tool: BaseTool) -> LangchainToolWrapper: + def convert_tool(tool: BaseTool, operation: Optional[str] = None) -> LangchainToolWrapper: """将内部工具转换为Langchain工具 Args: tool: 内部工具实例 + operation: 特定操作(适用于有操作的工具) Returns: Langchain兼容的工具包装器 """ try: - wrapper = LangchainToolWrapper(tool_instance=tool) - logger.debug(f"工具转换成功: {tool.name} -> Langchain格式") - return wrapper + if operation and tool.name in ['datetime_tool', 'json_tool']: + # 为特定操作创建工具 + operation_tool = LangchainAdapter._create_operation_tool(tool, operation) + wrapper = LangchainToolWrapper(tool_instance=operation_tool) + logger.debug(f"工具转换成功: {tool.name}_{operation} -> Langchain格式") + return wrapper + else: + # 单个工具 + wrapper = LangchainToolWrapper(tool_instance=tool) + logger.debug(f"工具转换成功: {tool.name} -> Langchain格式") + return wrapper except Exception as e: logger.error(f"工具转换失败: {tool.name}, 错误: {e}") raise + @staticmethod + def _create_operation_tool(base_tool: BaseTool, operation: str) -> BaseTool: + """为特定操作创建工具实例""" + from app.core.tools.builtin.operation_tool import OperationTool + return OperationTool(base_tool, operation) + @staticmethod def convert_tools(tools: List[BaseTool]) -> List[LangchainToolWrapper]: """批量转换工具 @@ -110,7 +125,7 @@ class LangchainAdapter: except Exception as e: logger.error(f"跳过工具转换: {tool.name}, 错误: {e}") - logger.info(f"批量转换完成: {len(converted_tools)}/{len(tools)} 个工具") + logger.info(f"批量转换完成: {len(converted_tools)} 个工具") return converted_tools @staticmethod @@ -169,9 +184,10 @@ class LangchainAdapter: "ToolArgsSchema", (BaseModel,), { + "__module__": __name__, "__annotations__": annotations, - **fields, - "Config": type("Config", (), {"extra": "forbid"}) + "model_config": {"extra": "forbid"}, + **fields } ) diff --git a/api/app/core/tools/mcp/service_manager.py b/api/app/core/tools/mcp/service_manager.py index f7349201..01312444 100644 --- a/api/app/core/tools/mcp/service_manager.py +++ b/api/app/core/tools/mcp/service_manager.py @@ -16,14 +16,17 @@ logger = get_business_logger() class MCPServiceManager: """MCP服务管理器 - 管理MCP服务的生命周期""" - def __init__(self, db: Session): + def __init__(self, db: Session = None): """初始化MCP服务管理器 Args: - db: 数据库会话 + db: 数据库会话(可选) """ self.db = db - self.connection_pool = MCPConnectionPool(max_connections=20) + if db: + self.connection_pool = MCPConnectionPool(max_connections=20) + else: + self.connection_pool = None # 服务状态管理 self._services: Dict[str, Dict[str, Any]] = {} # service_id -> service_info @@ -592,7 +595,7 @@ class MCPServiceManager: except Exception as e: logger.error(f"清理失效服务失败: {e}") - + def get_manager_status(self) -> Dict[str, Any]: """获取管理器状态""" return { diff --git a/api/app/services/app_chat_service.py b/api/app/services/app_chat_service.py index 29e92cf6..735f13df 100644 --- a/api/app/services/app_chat_service.py +++ b/api/app/services/app_chat_service.py @@ -10,6 +10,8 @@ from sqlalchemy.orm import Session from app.core.agent.langchain_agent import LangChainAgent from app.core.logging_config import get_business_logger +from app.services.tool_service import ToolService +from app.repositories.tool_repository import ToolRepository from app.db import get_db from app.models import MultiAgentConfig, AgentConfig from app.schemas.prompt_schema import render_prompt_message, PromptMessageRole @@ -40,6 +42,7 @@ class AppChatService: memory: bool = True, storage_type: Optional[str] = None, user_rag_memory_id: Optional[str] = None, + workspace_id: Optional[str] = None ) -> Dict[str, Any]: """聊天(非流式)""" @@ -64,6 +67,20 @@ class AppChatService: # 准备工具列表 tools = [] + + # 获取工具服务 + tool_service = ToolService(self.db) + + # 从配置中获取启用的工具 + if hasattr(config, 'tools') and config.tools: + for tool_id, tool_config in config.tools.items(): + if tool_config.get("enabled", False): + # 根据工具名称查找工具实例 + tool_instance = tool_service._get_tool_instance(tool_id, ToolRepository.get_tenant_id_by_workspace_id(self.db, workspace_id)) + if tool_instance: + # 转换为LangChain工具 + langchain_tool = tool_instance.to_langchain_tool(tool_config.get("config", {}).get("operation", None)) + tools.append(langchain_tool) # 添加知识库检索工具 knowledge_retrieval = config.knowledge_retrieval @@ -83,21 +100,6 @@ class AppChatService: memory_tool = create_long_term_memory_tool(memory_config, user_id) tools.append(memory_tool) - web_tools = config.tools - # web_search_choice = web_tools.get("web_search", {}) - # web_search_enable = web_search_choice.get("enabled", False) - # if web_search == True: - # if web_search_enable == True: - # search_tool = create_web_search_tool({}) - # tools.append(search_tool) - # - # logger.debug( - # "已添加网络搜索工具", - # extra={ - # "tool_count": len(tools) - # } - # ) - # 获取模型参数 model_parameters = config.model_parameters @@ -170,6 +172,7 @@ class AppChatService: memory: bool = True, storage_type: Optional[str] = None, user_rag_memory_id: Optional[str] = None, + workspace_id: Optional[str] = None, ) -> AsyncGenerator[str, None]: """聊天(流式)""" @@ -641,6 +644,20 @@ class AppChatService: # 准备工具列表 tools = [] + + # 获取工具服务 + tool_service = ToolService(self.db) + + # 从配置中获取启用的工具 + if hasattr(config, 'tools') and config.tools: + for tool_id, tool_config in config.tools.items(): + if tool_config.get("enabled", False): + # 根据工具名称查找工具实例 + tool_instance = tool_service._get_tool_instance(tool_id, ToolRepository.get_tenant_id_by_workspace_id(self.db, workspace_id)) + if tool_instance: + # 转换为LangChain工具 + langchain_tool = tool_instance.to_langchain_tool(tool_config.get("config", {}).get("operation", None)) + tools.append(langchain_tool) # 添加知识库检索工具 knowledge_retrieval = config.get("knowledge_retrieval") @@ -660,21 +677,6 @@ class AppChatService: memory_tool = create_long_term_memory_tool(memory_config, user_id) tools.append(memory_tool) - web_tools = config.get("tools") - web_search_choice = web_tools.get("web_search", {}) - web_search_enable = web_search_choice.get("enabled", False) - if web_search == True: - if web_search_enable == True: - search_tool = create_web_search_tool({}) - tools.append(search_tool) - - logger.debug( - "已添加网络搜索工具", - extra={ - "tool_count": len(tools) - } - ) - # 获取模型参数 model_parameters = config.get("model_parameters", {}) diff --git a/api/app/services/draft_run_service.py b/api/app/services/draft_run_service.py index eefc71c5..79aebcce 100644 --- a/api/app/services/draft_run_service.py +++ b/api/app/services/draft_run_service.py @@ -10,19 +10,22 @@ import time import uuid from typing import Any, AsyncGenerator, Dict, List, Optional +from langchain.tools import tool +from pydantic import BaseModel, Field +from sqlalchemy import select +from sqlalchemy.orm import Session + from app.core.error_codes import BizCode from app.core.exceptions import BusinessException from app.core.logging_config import get_business_logger from app.core.rag.nlp.search import knowledge_retrieval from app.models import AgentConfig, ModelApiKey, ModelConfig +from app.repositories.tool_repository import ToolRepository from app.schemas.prompt_schema import PromptMessageRole, render_prompt_message from app.services.langchain_tool_server import Search from app.services.memory_agent_service import MemoryAgentService from app.services.model_parameter_merger import ModelParameterMerger -from langchain.tools import tool -from pydantic import BaseModel, Field -from sqlalchemy import select -from sqlalchemy.orm import Session +from app.services.tool_service import ToolService logger = get_business_logger() class KnowledgeRetrievalInput(BaseModel): @@ -291,24 +294,21 @@ class DraftRunService: # 4. 准备工具列表 tools = [] - # 添加网络搜索工具 - if web_search: - if agent_config.tools: - web_search_config = agent_config.tools.get("web_search", {}) - web_search_enable = web_search_config.get("enabled", False) + tool_service = ToolService(self.db) - if web_search_enable: - logger.info("网络搜索已启用") - # 创建网络搜索工具 - search_tool = create_web_search_tool(web_search_config) - tools.append(search_tool) - - logger.debug( - "已添加网络搜索工具", - extra={ - "tool_count": len(tools) - } - ) + # 从配置中获取启用的工具 + if hasattr(agent_config, 'tools') and agent_config.tools: + for tool_id, tool_config in agent_config.tools.items(): + if tool_config.get("enabled", False): + # 根据工具名称查找工具实例 + tool_instance = tool_service._get_tool_instance(tool_id, + ToolRepository.get_tenant_id_by_workspace_id( + self.db, str(workspace_id))) + if tool_instance: + # 转换为LangChain工具 + langchain_tool = tool_instance.to_langchain_tool( + tool_config.get("config", {}).get("operation", None)) + tools.append(langchain_tool) # 添加知识库检索工具 if agent_config.knowledge_retrieval: @@ -503,24 +503,21 @@ class DraftRunService: # 4. 准备工具列表 tools = [] - # 添加网络搜索工具 - if web_search: - if agent_config.tools: - web_search_config = agent_config.tools.get("web_search", {}) - web_search_enable = web_search_config.get("enabled", False) + tool_service = ToolService(self.db) - if web_search_enable: - logger.info("网络搜索已启用") - # 创建网络搜索工具 - search_tool = create_web_search_tool(web_search_config) - tools.append(search_tool) - - logger.debug( - "已添加网络搜索工具", - extra={ - "tool_count": len(tools) - } - ) + # 从配置中获取启用的工具 + if hasattr(agent_config, 'tools') and agent_config.tools: + for tool_id, tool_config in agent_config.tools.items(): + if tool_config.get("enabled", False): + # 根据工具名称查找工具实例 + tool_instance = tool_service._get_tool_instance(tool_id, + ToolRepository.get_tenant_id_by_workspace_id( + self.db, str(workspace_id))) + if tool_instance: + # 转换为LangChain工具 + langchain_tool = tool_instance.to_langchain_tool( + tool_config.get("config", {}).get("operation", None)) + tools.append(langchain_tool) # 添加知识库检索工具 if agent_config.knowledge_retrieval: From 9d0622b6cc0b8631a397dcc866613fba89a6895e Mon Sep 17 00:00:00 2001 From: zhaoying Date: Tue, 6 Jan 2026 15:36:25 +0800 Subject: [PATCH 21/75] feat(web): user summary api update --- web/src/i18n/en.ts | 2 + web/src/i18n/zh.ts | 2 + .../UserMemoryDetail/components/AboutMe.tsx | 40 ++++++++++++++++--- 3 files changed, 38 insertions(+), 6 deletions(-) diff --git a/web/src/i18n/en.ts b/web/src/i18n/en.ts index d186368b..630c6c7e 100644 --- a/web/src/i18n/en.ts +++ b/web/src/i18n/en.ts @@ -1218,6 +1218,8 @@ export const en = { key_findings: 'Key Findings', behavior_pattern: 'Behavior Pattern', growth_trajectory: 'Growth Trajectory', + personality: 'Personality Traits', + core_values: 'Core Values', }, space: { createSpace: 'Create Space', diff --git a/web/src/i18n/zh.ts b/web/src/i18n/zh.ts index 028bd1df..b50ed1d8 100644 --- a/web/src/i18n/zh.ts +++ b/web/src/i18n/zh.ts @@ -1299,6 +1299,8 @@ export const zh = { key_findings: '关键发现', behavior_pattern: '行为模式', growth_trajectory: '成长轨迹', + personality: '性格特点', + core_values: '核心价值观', }, space: { createSpace: '创建空间', diff --git a/web/src/views/UserMemoryDetail/components/AboutMe.tsx b/web/src/views/UserMemoryDetail/components/AboutMe.tsx index ba7e68fe..f2c94814 100644 --- a/web/src/views/UserMemoryDetail/components/AboutMe.tsx +++ b/web/src/views/UserMemoryDetail/components/AboutMe.tsx @@ -5,16 +5,25 @@ import { Skeleton } from 'antd'; import RbCard from '@/components/RbCard/Card' import Empty from '@/components/Empty'; +import RbAlert from '@/components/RbAlert'; import { getUserSummary, } from '@/api/memory' import type { AboutMeRef } from '../types' + +interface Data { + user_summary: string; + personality: string; + core_values: string; + one_sentence: string; + [key: string]: string; +} const AboutMe = forwardRef((_props, ref) => { const { t } = useTranslation() const { id } = useParams() const [loading, setLoading] = useState(false) - const [data, setData] = useState(null) + const [data, setData] = useState({} as Data) useEffect(() => { if (!id) return @@ -27,7 +36,7 @@ const AboutMe = forwardRef((_props, ref) => { setLoading(true) getUserSummary(id) .then((res) => { - setData((res as { summary?: string }).summary || null) + setData((res as Data) || null) }) .finally(() => { setLoading(false) @@ -44,10 +53,29 @@ const AboutMe = forwardRef((_props, ref) => { > {loading ? - : data - ?
- {data || '-'} -
+ : Object.keys(data).filter(key => data[key] !== null).length > 0 + ? <> + {data.user_summary && +
+ {data.user_summary} +
+ } + {data.personality && <> +
{t('userMemory.personality')}
+
+ {data.personality} +
+ } + {data.core_values && <> +
{t('userMemory.core_values')}
+
+ {data.core_values} +
+ } + {data.one_sentence && + {data.one_sentence} + } + : } From a940717ed009b0e675d7a7fe99135e1fd551fc88 Mon Sep 17 00:00:00 2001 From: Mark Date: Tue, 6 Jan 2026 17:11:52 +0800 Subject: [PATCH 22/75] [add] publish and share run add workflow type app --- .../controllers/public_share_controller.py | 74 +++- api/app/services/app_chat_service.py | 378 ++++++------------ api/app/services/app_service.py | 22 + api/app/services/multi_agent_orchestrator.py | 1 + api/app/services/workflow_service.py | 3 +- api/app/utils/app_config_utils.py | 28 +- 6 files changed, 249 insertions(+), 257 deletions(-) diff --git a/api/app/controllers/public_share_controller.py b/api/app/controllers/public_share_controller.py index 5fe4eb56..adb199fb 100644 --- a/api/app/controllers/public_share_controller.py +++ b/api/app/controllers/public_share_controller.py @@ -1,4 +1,5 @@ import hashlib +import json import uuid from typing import Annotated from fastapi import APIRouter, Depends, Query, Request @@ -18,7 +19,7 @@ from app.services.conversation_service import ConversationService from app.services.release_share_service import ReleaseShareService from app.services.shared_chat_service import SharedChatService from app.services.app_chat_service import AppChatService, get_app_chat_service -from app.utils.app_config_utils import dict_to_multi_agent_config, dict_to_workflow_config, agent_config_4_app_release, multi_agent_config_4_app_release +from app.utils.app_config_utils import dict_to_multi_agent_config, workflow_config_4_app_release, agent_config_4_app_release, multi_agent_config_4_app_release router = APIRouter(prefix="/public/share", tags=["Public Share"]) logger = get_business_logger() @@ -288,7 +289,7 @@ async def chat( password = None # Token 认证不需要密码 # end_user_id = user_id other_id = user_id - + # 提前验证和准备(在流式响应开始前完成) # 这样可以确保错误能正确返回,而不是在流式响应中间出错 from app.models.app_model import AppType @@ -364,6 +365,9 @@ async def chat( config = release.config or {} if not config.get("sub_agents"): raise BusinessException("多 Agent 应用未配置子 Agent", BizCode.AGENT_CONFIG_MISSING) + elif app_type == AppType.WORKFLOW: + # Multi-Agent 类型:验证多 Agent 配置 + pass else: raise BusinessException(f"不支持的应用类型: {app_type}", BizCode.APP_TYPE_NOT_SUPPORTED) @@ -469,6 +473,7 @@ async def chat( ) return success(data=conversation_schema.ChatResponse(**result).model_dump(mode="json")) elif app_type == AppType.MULTI_AGENT: + # config = workflow_config_4_app_release(release) config = multi_agent_config_4_app_release(release) if payload.stream: async def event_generator(): @@ -553,8 +558,71 @@ async def chat( # ) # return success(data=conversation_schema.ChatResponse(**result)) + elif app_type == AppType.WORKFLOW: + + config = workflow_config_4_app_release(release) + if payload.stream: + async def event_generator(): + async for event in app_chat_service.workflow_chat_stream( + + message=payload.message, + conversation_id=conversation.id, # 使用已创建的会话 ID + user_id=new_end_user.id, # 转换为字符串 + variables=payload.variables, + config=config, + web_search=payload.web_search, + memory=payload.memory, + storage_type=storage_type, + user_rag_memory_id=user_rag_memory_id, + app_id=release.app_id, + workspace_id=workspace_id + ): + event_type = event.get("event", "message") + event_data = event.get("data", {}) + + # 转换为标准 SSE 格式(字符串) + sse_message = f"event: {event_type}\ndata: {json.dumps(event_data)}\n\n" + yield sse_message + + return StreamingResponse( + event_generator(), + media_type="text/event-stream", + headers={ + "Cache-Control": "no-cache", + "Connection": "keep-alive", + "X-Accel-Buffering": "no" + } + ) + + # 多 Agent 非流式返回 + result = await app_chat_service.workflow_chat( + + message=payload.message, + conversation_id=conversation.id, # 使用已创建的会话 ID + user_id=new_end_user.id, # 转换为字符串 + variables=payload.variables, + config=config, + web_search=payload.web_search, + memory=payload.memory, + storage_type=storage_type, + user_rag_memory_id=user_rag_memory_id, + app_id=release.app_id, + workspace_id=workspace_id + ) + logger.debug( + "工作流试运行返回结果", + extra={ + "result_type": str(type(result)), + "has_response": "response" in result if isinstance(result, dict) else False + } + ) + return success( + data=result, + msg="工作流任务执行成功" + ) + # return success(data=conversation_schema.ChatResponse(**result).model_dump(mode="json")) + else: from app.core.exceptions import BusinessException from app.core.error_codes import BizCode raise BusinessException(f"不支持的应用类型: {app_type}", BizCode.APP_TYPE_NOT_SUPPORTED) - pass diff --git a/api/app/services/app_chat_service.py b/api/app/services/app_chat_service.py index 29e92cf6..6b7b3103 100644 --- a/api/app/services/app_chat_service.py +++ b/api/app/services/app_chat_service.py @@ -9,15 +9,18 @@ from fastapi import Depends from sqlalchemy.orm import Session from app.core.agent.langchain_agent import LangChainAgent +from app.core.error_codes import BizCode +from app.core.exceptions import BusinessException from app.core.logging_config import get_business_logger -from app.db import get_db -from app.models import MultiAgentConfig, AgentConfig +from app.db import get_db, get_db_context +from app.models import MultiAgentConfig, AgentConfig, WorkflowConfig from app.schemas.prompt_schema import render_prompt_message, PromptMessageRole from app.services.conversation_service import ConversationService from app.services.draft_run_service import create_knowledge_retrieval_tool, create_long_term_memory_tool from app.services.draft_run_service import create_web_search_tool from app.services.model_service import ModelApiKeyService from app.services.multi_agent_orchestrator import MultiAgentOrchestrator +from app.services.workflow_service import WorkflowService logger = get_business_logger() @@ -479,7 +482,9 @@ class AppChatService: self, message: str, conversation_id: uuid.UUID, - config: AgentConfig, + config: WorkflowConfig, + app_id: uuid.UUID, + workspace_id: uuid.UUID, user_id: Optional[str] = None, variables: Optional[Dict[str, Any]] = None, web_search: bool = False, @@ -488,281 +493,158 @@ class AppChatService: user_rag_memory_id: Optional[str] = None, ) -> Dict[str, Any]: """聊天(非流式)""" + workflow_service = WorkflowService(self.db) - start_time = time.time() - config_id = None + input_data = {"message":message, "variables": variables, + "conversation_id": str(conversation_id)} + inconfig = workflow_service.get_workflow_config(app_id) - if variables is None: - variables = {} + # 2. 创建执行记录 + execution = workflow_service.create_execution( + workflow_config_id=inconfig.id, + app_id=app_id, + trigger_type="manual", + triggered_by=None, + conversation_id=conversation_id, + input_data=input_data + ) - # 获取模型配置ID - model_config_id = config.default_model_config_id - api_key_obj = ModelApiKeyService.get_a_api_key(self.db ,model_config_id) - # 处理系统提示词(支持变量替换) - system_prompt = config.get("system_prompt", "") - if variables: - system_prompt_rendered = render_prompt_message( - system_prompt, - PromptMessageRole.USER, - variables + # 3. 构建工作流配置字典 + workflow_config_dict = { + "nodes": config.nodes, + "edges": config.edges, + "variables": config.variables, + "execution_config": config.execution_config + } + + # 4. 获取工作空间 ID(从 app 获取) + + # 5. 执行工作流 + from app.core.workflow.executor import execute_workflow + + try: + # 更新状态为运行中 + workflow_service.update_execution_status(execution.execution_id, "running") + + result = await execute_workflow( + workflow_config=workflow_config_dict, + input_data=input_data, + execution_id=execution.execution_id, + workspace_id=str(workspace_id), + user_id=user_id ) - system_prompt = system_prompt_rendered.get_text_content() or system_prompt - # 准备工具列表 - tools = [] - - # 添加知识库检索工具 - knowledge_retrieval = config.get("knowledge_retrieval") - if knowledge_retrieval: - knowledge_bases = knowledge_retrieval.get("knowledge_bases", []) - kb_ids = [kb.get("kb_id") for kb in knowledge_bases if kb.get("kb_id")] - if kb_ids: - kb_tool = create_knowledge_retrieval_tool(knowledge_retrieval, kb_ids, user_id) - tools.append(kb_tool) - - # 添加长期记忆工具 - memory_flag = False - if memory == True: - memory_config = config.get("memory", {}) - if memory_config.get("enabled") and user_id: - memory_flag = True - memory_tool = create_long_term_memory_tool(memory_config, user_id) - tools.append(memory_tool) - - web_tools = config.get("tools") - web_search_choice = web_tools.get("web_search", {}) - web_search_enable = web_search_choice.get("enabled", False) - if web_search == True: - if web_search_enable == True: - search_tool = create_web_search_tool({}) - tools.append(search_tool) - - logger.debug( - "已添加网络搜索工具", - extra={ - "tool_count": len(tools) - } + # 更新执行结果 + if result.get("status") == "completed": + workflow_service.update_execution_status( + execution.execution_id, + "completed", + output_data=result.get("node_outputs", {}) + ) + else: + workflow_service.update_execution_status( + execution.execution_id, + "failed", + error_message=result.get("error") ) - # 获取模型参数 - model_parameters = config.get("model_parameters", {}) + # 返回增强的响应结构 + return { + "execution_id": execution.execution_id, + "status": result.get("status"), + "output": result.get("output"), # 最终输出(字符串) + "output_data": result.get("node_outputs", {}), # 所有节点输出(详细数据) + "conversation_id": result.get("conversation_id"), # 所有节点输出(详细数据)payload., # 会话 ID + "error_message": result.get("error"), + "elapsed_time": result.get("elapsed_time"), + "token_usage": result.get("token_usage") + } - # 创建 LangChain Agent - agent = LangChainAgent( - model_name=api_key_obj.model_name, - api_key=api_key_obj.api_key, - provider=api_key_obj.provider, - api_base=api_key_obj.api_base, - temperature=model_parameters.get("temperature", 0.7), - max_tokens=model_parameters.get("max_tokens", 2000), - system_prompt=system_prompt, - tools=tools, - - ) - - # 加载历史消息 - history = [] - memory_config = {"enabled": True, 'max_history': 10} - if memory_config.get("enabled"): - messages = self.conversation_service.get_messages( - conversation_id=conversation_id, - limit=memory_config.get("max_history", 10) + except Exception as e: + logger.error(f"工作流执行失败: execution_id={execution.execution_id}, error={e}", exc_info=True) + workflow_service.update_execution_status( + execution.execution_id, + "failed", + error_message=str(e) + ) + raise BusinessException( + code=BizCode.INTERNAL_ERROR, + message=f"工作流执行失败: {str(e)}" ) - history = [ - {"role": msg.role, "content": msg.content} - for msg in messages - ] - - # 调用 Agent - result = await agent.chat( - message=message, - history=history, - context=None, - end_user_id=user_id, - storage_type=storage_type, - user_rag_memory_id=user_rag_memory_id, - config_id=config_id, - memory_flag=memory_flag - ) - - # 保存消息 - self.conversation_service.save_conversation_messages( - conversation_id=conversation_id, - user_message=message, - assistant_message=result["content"] - ) - - elapsed_time = time.time() - start_time - - return { - "conversation_id": conversation_id, - "message": result["content"], - "usage": result.get("usage", { - "prompt_tokens": 0, - "completion_tokens": 0, - "total_tokens": 0 - }), - "elapsed_time": elapsed_time - } async def workflow_chat_stream( self, message: str, conversation_id: uuid.UUID, - config: AgentConfig, + config: WorkflowConfig, + app_id: uuid.UUID, + workspace_id: uuid.UUID, user_id: Optional[str] = None, variables: Optional[Dict[str, Any]] = None, web_search: bool = False, memory: bool = True, storage_type: Optional[str] = None, user_rag_memory_id: Optional[str] = None, + ) -> AsyncGenerator[str, None]: """聊天(流式)""" + workflow_service = WorkflowService(self.db) + input_data = {"message": message, "variables": variables, + "conversation_id": str(conversation_id)} + inconfig = workflow_service.get_workflow_config(app_id) + # 2. 创建执行记录 + execution = workflow_service.create_execution( + workflow_config_id=inconfig.id, + app_id=app_id, + trigger_type="manual", + triggered_by=None, + conversation_id=conversation_id, + input_data=input_data + ) + + # 3. 构建工作流配置字典 + workflow_config_dict = { + "nodes": config.nodes, + "edges": config.edges, + "variables": config.variables, + "execution_config": config.execution_config + } + + # 4. 获取工作空间 ID(从 app 获取) + + # 5. 流式执行工作流 try: - start_time = time.time() - config_id = None + # 更新状态为运行中 + workflow_service.update_execution_status(execution.execution_id, "running") - if variables is None: - variables = {} - # 获取模型配置ID - model_config_id = config.default_model_config_id - api_key_obj = ModelApiKeyService.get_a_api_key(self.db ,model_config_id) - # 处理系统提示词(支持变量替换) - system_prompt = config.get("system_prompt", "") - if variables: - system_prompt_rendered = render_prompt_message( - system_prompt, - PromptMessageRole.USER, - variables - ) - system_prompt = system_prompt_rendered.get_text_content() or system_prompt - - # 准备工具列表 - tools = [] - - # 添加知识库检索工具 - knowledge_retrieval = config.get("knowledge_retrieval") - if knowledge_retrieval: - knowledge_bases = knowledge_retrieval.get("knowledge_bases", []) - kb_ids = [kb.get("kb_id") for kb in knowledge_bases if kb.get("kb_id")] - if kb_ids: - kb_tool = create_knowledge_retrieval_tool(knowledge_retrieval, kb_ids, user_id) - tools.append(kb_tool) - - # 添加长期记忆工具 - memory_flag = False - if memory: - memory_config = config.get("memory", {}) - if memory_config.get("enabled") and user_id: - memory_flag = True - memory_tool = create_long_term_memory_tool(memory_config, user_id) - tools.append(memory_tool) - - web_tools = config.get("tools") - web_search_choice = web_tools.get("web_search", {}) - web_search_enable = web_search_choice.get("enabled", False) - if web_search == True: - if web_search_enable == True: - search_tool = create_web_search_tool({}) - tools.append(search_tool) - - logger.debug( - "已添加网络搜索工具", - extra={ - "tool_count": len(tools) - } - ) - - # 获取模型参数 - model_parameters = config.get("model_parameters", {}) - - # 创建 LangChain Agent - agent = LangChainAgent( - model_name=api_key_obj.model_name, - api_key=api_key_obj.api_key, - provider=api_key_obj.provider, - api_base=api_key_obj.api_base, - temperature=model_parameters.get("temperature", 0.7), - max_tokens=model_parameters.get("max_tokens", 2000), - system_prompt=system_prompt, - tools=tools, - streaming=True - ) - - # 加载历史消息 - history = [] - memory_config = {"enabled": True, 'max_history': 10} - if memory_config.get("enabled"): - messages = self.conversation_service.get_messages( - conversation_id=conversation_id, - limit=memory_config.get("max_history", 10) - ) - history = [ - {"role": msg.role, "content": msg.content} - for msg in messages - ] - - # 发送开始事件 - yield f"event: start\ndata: {json.dumps({'conversation_id': str(conversation_id)}, ensure_ascii=False)}\n\n" - - # 流式调用 Agent - full_content = "" - async for chunk in agent.chat_stream( - message=message, - history=history, - context=None, - end_user_id=user_id, - storage_type=storage_type, - user_rag_memory_id=user_rag_memory_id, - config_id=config_id, - memory_flag=memory_flag + # 调用流式执行(executor 会发送 workflow_start 和 workflow_end 事件) + async for event in workflow_service._run_workflow_stream( + workflow_config=workflow_config_dict, + input_data=input_data, + execution_id=execution.execution_id, + workspace_id=str(workspace_id), + user_id=user_id ): - full_content += chunk - # 发送消息块事件 - yield f"event: message\ndata: {json.dumps({'content': chunk}, ensure_ascii=False)}\n\n" + # 直接转发 executor 的事件(已经是正确的格式) + yield event - elapsed_time = time.time() - start_time - - # 保存消息 - self.conversation_service.add_message( - conversation_id=conversation_id, - role="user", - content=message - ) - - self.conversation_service.add_message( - conversation_id=conversation_id, - role="assistant", - content=full_content, - meta_data={ - "model": api_key_obj.model_name, - "usage": {} - } - ) - - # 发送结束事件 - end_data = {"elapsed_time": elapsed_time, "message_length": len(full_content)} - yield f"event: end\ndata: {json.dumps(end_data, ensure_ascii=False)}\n\n" - - logger.info( - "流式聊天完成", - extra={ - "conversation_id": str(conversation_id), - "elapsed_time": elapsed_time, - "message_length": len(full_content) - } - ) - - except (GeneratorExit, asyncio.CancelledError): - # 生成器被关闭或任务被取消,正常退出 - logger.debug("流式聊天被中断") - raise except Exception as e: - logger.error(f"流式聊天失败: {str(e)}", exc_info=True) + logger.error(f"工作流流式执行失败: execution_id={execution.execution_id}, error={e}", exc_info=True) + workflow_service.update_execution_status( + execution.execution_id, + "failed", + error_message=str(e) + ) # 发送错误事件 - yield f"event: error\ndata: {json.dumps({'error': str(e)}, ensure_ascii=False)}\n\n" + yield { + "event": "error", + "data": { + "execution_id": execution.execution_id, + "error": str(e) + } + } # ==================== 依赖注入函数 ==================== diff --git a/api/app/services/app_service.py b/api/app/services/app_service.py index 95bcc07a..38097c4e 100644 --- a/api/app/services/app_service.py +++ b/api/app/services/app_service.py @@ -21,6 +21,7 @@ from app.core.exceptions import ( BusinessException, ) from app.core.logging_config import get_business_logger +from app.core.workflow.validator import WorkflowValidator from app.db import get_db from app.models import App, AgentConfig, AppRelease, MultiAgentConfig, WorkflowConfig from app.models.app_model import AppStatus, AppType @@ -31,6 +32,7 @@ from app.schemas.workflow_schema import WorkflowConfigUpdate from app.services.agent_config_converter import AgentConfigConverter from app.models import AppShare, Workspace from app.services.model_service import ModelApiKeyService +from app.services.workflow_service import WorkflowService # 获取业务日志器 logger = get_business_logger() @@ -1225,6 +1227,26 @@ class AppService: "orchestration_mode": multi_agent_cfg.orchestration_mode } ) + elif app.type == AppType.WORKFLOW: + service = WorkflowService(self.db) + workflow_cfg = service.get_workflow_config(app_id) + if not workflow_cfg: + raise BusinessException("应用缺少有效配置,无法发布", BizCode.CONFIG_MISSING) + + config = { + "nodes": workflow_cfg.nodes, + "edges": workflow_cfg.edges, + "variables": workflow_cfg.variables, + "execution_config": workflow_cfg.execution_config, + "triggers": workflow_cfg.triggers + } + + is_valid, errors = WorkflowValidator.validate_for_publish(config) + if not is_valid: + raise BusinessException("应用缺少有效配置,无法发布", BizCode.CONFIG_MISSING) + logger.info( + "应用发布配置准备完成" + ) now = datetime.datetime.now() version = self._get_next_version(app_id) diff --git a/api/app/services/multi_agent_orchestrator.py b/api/app/services/multi_agent_orchestrator.py index 08ae7e57..fd3ce229 100644 --- a/api/app/services/multi_agent_orchestrator.py +++ b/api/app/services/multi_agent_orchestrator.py @@ -1293,6 +1293,7 @@ class MultiAgentOrchestrator: conversation_id: 会话 ID user_id: 用户 ID + Returns: 执行结果 """ diff --git a/api/app/services/workflow_service.py b/api/app/services/workflow_service.py index d96efdf7..68d6279b 100644 --- a/api/app/services/workflow_service.py +++ b/api/app/services/workflow_service.py @@ -17,6 +17,7 @@ from app.core.workflow.validator import validate_workflow_config from app.db import get_db, get_db_context from app.models.workflow_model import WorkflowConfig, WorkflowExecution from app.repositories.end_user_repository import EndUserRepository +from app.services.multi_agent_service import convert_uuids_to_str from app.repositories.workflow_repository import ( WorkflowConfigRepository, WorkflowExecutionRepository, @@ -364,7 +365,7 @@ class WorkflowService: execution.status = status if output_data is not None: - execution.output_data = output_data + execution.output_data = convert_uuids_to_str(output_data) if error_message is not None: execution.error_message = error_message if error_node_id is not None: diff --git a/api/app/utils/app_config_utils.py b/api/app/utils/app_config_utils.py index 4fe692c1..97e64214 100644 --- a/api/app/utils/app_config_utils.py +++ b/api/app/utils/app_config_utils.py @@ -8,7 +8,7 @@ import uuid from typing import Dict, Any, Optional from datetime import datetime -from app.models import AppRelease +from app.models import AppRelease, WorkflowConfig from app.models.agent_app_config_model import AgentConfig from app.models.multi_agent_model import MultiAgentConfig @@ -28,7 +28,7 @@ class AgentConfigProxy: def agent_config_4_app_release(release: AppRelease ) -> AgentConfig: config_dict = release.config - + agent_config = AgentConfig( app_id=release.app_id, system_prompt=config_dict.get("system_prompt"), @@ -45,10 +45,10 @@ def agent_config_4_app_release(release: AppRelease ) -> AgentConfig: def multi_agent_config_4_app_release(release: AppRelease ) -> MultiAgentConfig: config_dict = release.config - + agent_config = MultiAgentConfig( - app_id=release.app_id, + app_id=release.app_id, default_model_config_id=release.default_model_config_id, model_parameters=config_dict.get("model_parameters"), master_agent_id=config_dict.get("master_agent_id"), @@ -58,11 +58,29 @@ def multi_agent_config_4_app_release(release: AppRelease ) -> MultiAgentConfig: routing_rules=config_dict.get("routing_rules"), execution_config=config_dict.get("execution_config", {}), aggregation_strategy=config_dict.get("aggregation_strategy", "merge"), - + ) return agent_config +def workflow_config_4_app_release(release: AppRelease ) -> WorkflowConfig: + + config_dict = release.config + + + config = WorkflowConfig( + id=release.id, + app_id=release.app_id, + nodes=config_dict.get("nodes", []), + edges=config_dict.get("edges", []), + variables=config_dict.get("variables", []), + execution_config=config_dict.get("execution_config", {}), + triggers=config_dict.get("triggers", []) + + ) + + return config + def dict_to_multi_agent_config(config_dict: Dict[str, Any], app_id: Optional[uuid.UUID] = None): """Convert dict to MultiAgentConfig model object From 6783375a140b38e22b2f96228da0f171ea8f7d1c Mon Sep 17 00:00:00 2001 From: Mark Date: Tue, 6 Jan 2026 17:55:42 +0800 Subject: [PATCH 23/75] [fix] model_parameters --- .../controllers/service/app_api_controller.py | 49 +++++++++++++------ api/app/services/agent_config_converter.py | 7 ++- 2 files changed, 40 insertions(+), 16 deletions(-) diff --git a/api/app/controllers/service/app_api_controller.py b/api/app/controllers/service/app_api_controller.py index 5a78a28b..54af0b57 100644 --- a/api/app/controllers/service/app_api_controller.py +++ b/api/app/controllers/service/app_api_controller.py @@ -1,4 +1,5 @@ """App 服务接口 - 基于 API Key 认证""" +import json from typing import Annotated from fastapi import APIRouter, Depends, Request, Body @@ -21,7 +22,7 @@ from app.schemas.api_key_schema import ApiKeyAuth from app.services import workspace_service from app.services.app_chat_service import AppChatService, get_app_chat_service from app.services.conversation_service import ConversationService, get_conversation_service -from app.utils.app_config_utils import dict_to_multi_agent_config, dict_to_workflow_config, agent_config_4_app_release, multi_agent_config_4_app_release +from app.utils.app_config_utils import dict_to_multi_agent_config, workflow_config_4_app_release, agent_config_4_app_release, multi_agent_config_4_app_release from app.services.app_service import get_app_service, AppService router = APIRouter(prefix="/app", tags=["V1 - App API"]) @@ -226,22 +227,29 @@ async def chat( return success(data=conversation_schema.ChatResponse(**result).model_dump(mode="json")) elif app_type == AppType.WORKFLOW: # 多 Agent 流式返回 - config = dict_to_workflow_config(app.current_release.config,app.id) + config = workflow_config_4_app_release(app.current_release) if payload.stream: async def event_generator(): async for event in app_chat_service.workflow_chat_stream( message=payload.message, conversation_id=conversation.id, # 使用已创建的会话 ID - user_id=end_user_id, # 转换为字符串 + user_id=new_end_user.id, # 转换为字符串 variables=payload.variables, config=config, - web_search=web_search, - memory=memory, - storage_type=storage_type, - user_rag_memory_id=user_rag_memory_id + web_search=payload.web_search, + memory=payload.memory, + storage_type=storage_type, + user_rag_memory_id=user_rag_memory_id, + app_id=app.app_id, + workspace_id=workspace_id ): - yield event + event_type = event.get("event", "message") + event_data = event.get("data", {}) + + # 转换为标准 SSE 格式(字符串) + sse_message = f"event: {event_type}\ndata: {json.dumps(event_data)}\n\n" + yield sse_message return StreamingResponse( event_generator(), @@ -253,21 +261,32 @@ async def chat( } ) - # 非流式返回 + # 多 Agent 非流式返回 result = await app_chat_service.workflow_chat( message=payload.message, conversation_id=conversation.id, # 使用已创建的会话 ID - user_id=end_user_id, # 转换为字符串 + user_id=new_end_user.id, # 转换为字符串 variables=payload.variables, config=config, - web_search=web_search, - memory=memory, + web_search=payload.web_search, + memory=payload.memory, storage_type=storage_type, - user_rag_memory_id=user_rag_memory_id + user_rag_memory_id=user_rag_memory_id, + app_id=app.app_id, + workspace_id=workspace_id + ) + logger.debug( + "工作流试运行返回结果", + extra={ + "result_type": str(type(result)), + "has_response": "response" in result if isinstance(result, dict) else False + } + ) + return success( + data=result, + msg="工作流任务执行成功" ) - - return success(data=conversation_schema.ChatResponse(**result).model_dump(mode="json")) else: from app.core.exceptions import BusinessException from app.core.error_codes import BizCode diff --git a/api/app/services/agent_config_converter.py b/api/app/services/agent_config_converter.py index 262c1c04..3ab14157 100644 --- a/api/app/services/agent_config_converter.py +++ b/api/app/services/agent_config_converter.py @@ -86,7 +86,12 @@ class AgentConfigConverter: # 1. 解析模型参数配置 if model_parameters: from app.schemas.app_schema import ModelParameters - result["model_parameters"] = ModelParameters(**model_parameters) + if isinstance(model_parameters, ModelParameters): + result["model_parameters"] = model_parameters + elif isinstance(model_parameters, dict): + result["model_parameters"] = ModelParameters(**model_parameters) + else: + result["model_parameters"] = ModelParameters() # 2. 解析知识库检索配置 if knowledge_retrieval: From 3183f3953581442b26e111677b082e1fee835c0b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=B9=90=E5=8A=9B=E9=BD=90?= <162269739+lanceyq@users.noreply.github.com> Date: Tue, 6 Jan 2026 18:03:28 +0800 Subject: [PATCH 24/75] Fix/Restore user information archive and one-sentence summary (#37) * [fix]fix memory insights * [fix]fix memory insights * [fix]Based on the correction of the code by sourcery-ai * [fix]Restore user information archive and one-sentence summary --- .../controllers/user_memory_controllers.py | 3 +- .../utils/prompt/prompts/user_summary.jinja2 | 32 +++++++------------ api/app/services/user_memory_service.py | 22 +++++++++++++ 3 files changed, 35 insertions(+), 22 deletions(-) diff --git a/api/app/controllers/user_memory_controllers.py b/api/app/controllers/user_memory_controllers.py index c54ebbd1..da12cbf6 100644 --- a/api/app/controllers/user_memory_controllers.py +++ b/api/app/controllers/user_memory_controllers.py @@ -11,6 +11,7 @@ from app.db import get_db from app.core.logging_config import get_api_logger from app.core.response_utils import success, fail from app.core.error_codes import BizCode +from app.core.api_key_utils import timestamp_to_datetime from app.services.user_memory_service import ( UserMemoryService, analytics_memory_types, @@ -356,7 +357,7 @@ async def update_end_user_profile( if 'hire_date' in update_data: hire_date_timestamp = update_data['hire_date'] if hire_date_timestamp is not None: - update_data['hire_date'] = UserMemoryService.timestamp_to_datetime(hire_date_timestamp) + update_data['hire_date'] = timestamp_to_datetime(hire_date_timestamp) # 如果是 None,保持 None(允许清空) for field, value in update_data.items(): diff --git a/api/app/core/memory/utils/prompt/prompts/user_summary.jinja2 b/api/app/core/memory/utils/prompt/prompts/user_summary.jinja2 index 373ab31e..2f452c53 100644 --- a/api/app/core/memory/utils/prompt/prompts/user_summary.jinja2 +++ b/api/app/core/memory/utils/prompt/prompts/user_summary.jinja2 @@ -85,33 +85,21 @@ Example Output: ===End of Example=== -===Reflection Process=== +===Internal Quality Checks (DO NOT OUTPUT)=== -After generating the profile, perform the following self-review steps: +Before generating your final output, internally verify: +1. All content is grounded in provided data (no fabrication) +2. Format follows the specified structure with correct headers +3. Tone is objective, third-person, and neutral +4. All four sections are complete and within character limits -**Step 1: Data Grounding Check** -- Verify all statements are supported by the provided entities and statements -- Ensure no fabricated or speculated information is included -- Confirm all claims can be traced back to the input data - -**Step 2: Format Compliance** -- Verify each section follows the specified format with section headers -- Check character count limits for each section -- Ensure proper use of section markers (【】) - -**Step 3: Tone and Style Review** -- Confirm objective third-person perspective is maintained -- Check for excessive adjectives or empty phrases -- Verify neutral and restrained tone throughout - -**Step 4: Completeness Check** -- Ensure all four sections are present and complete -- Verify each section addresses its specific focus area -- Confirm the one-sentence summary effectively captures the user's essence +**IMPORTANT: These checks are for your internal use only. DO NOT include them in your output.** ===Output Requirements=== +**CRITICAL: Your response must ONLY contain the four sections below. Do not include any reflection, self-review, or meta-commentary.** + **LANGUAGE REQUIREMENT:** - The output language should ALWAYS be Chinese (Simplified) - All section content must be in Chinese @@ -122,3 +110,5 @@ After generating the profile, perform the following self-review steps: - Content follows immediately after the header - Sections are separated by blank lines - Strictly adhere to character limits for each section +- **DO NOT include any text after the 【一句话总结】 section** +- **DO NOT output reflection steps, self-review, or verification notes** diff --git a/api/app/services/user_memory_service.py b/api/app/services/user_memory_service.py index 6fd72fce..40851835 100644 --- a/api/app/services/user_memory_service.py +++ b/api/app/services/user_memory_service.py @@ -1054,6 +1054,28 @@ async def analytics_user_summary(end_user_id: Optional[str] = None) -> Dict[str, core_values = core_values_match.group(1).strip() if core_values_match else "" one_sentence = one_sentence_match.group(1).strip() if one_sentence_match else "" + # 6) 清理可能包含的反思内容(防御性编程) + # 如果 LLM 仍然输出了反思内容,在这里过滤掉 + def clean_reflection_content(text: str) -> str: + """移除可能包含的反思内容""" + if not text: + return text + # 移除 "---" 之后的所有内容(通常是反思部分的开始) + if '---' in text: + text = text.split('---')[0].strip() + # 移除 "**Step" 开头的内容 + if '**Step' in text: + text = text.split('**Step')[0].strip() + # 移除 "Self-Review" 相关内容 + if 'Self-Review' in text or 'self-review' in text: + text = re.sub(r'[\-\*]*\s*Self-Review.*$', '', text, flags=re.IGNORECASE | re.DOTALL).strip() + return text + + user_summary = clean_reflection_content(user_summary) + personality = clean_reflection_content(personality) + core_values = clean_reflection_content(core_values) + one_sentence = clean_reflection_content(one_sentence) + return { "user_summary": user_summary, "personality": personality, From a716c607d72040dfad516fe3ac2e6375ce73aff7 Mon Sep 17 00:00:00 2001 From: mengyonghao <1533512157@qq.com> Date: Tue, 6 Jan 2026 18:44:40 +0800 Subject: [PATCH 25/75] fix(workflow): optimize input_type validation for loop variables --- .../core/workflow/nodes/cycle_graph/config.py | 22 ++++++++++++++++++- api/app/core/workflow/nodes/enums.py | 4 ++-- api/app/core/workflow/nodes/if_else/config.py | 10 +++++++++ 3 files changed, 33 insertions(+), 3 deletions(-) diff --git a/api/app/core/workflow/nodes/cycle_graph/config.py b/api/app/core/workflow/nodes/cycle_graph/config.py index fcf65717..2e57536e 100644 --- a/api/app/core/workflow/nodes/cycle_graph/config.py +++ b/api/app/core/workflow/nodes/cycle_graph/config.py @@ -1,6 +1,6 @@ from typing import Any -from pydantic import Field, BaseModel +from pydantic import Field, BaseModel, field_validator from app.core.workflow.nodes.base_config import BaseNodeConfig, VariableType from app.core.workflow.nodes.enums import ComparisonOperator, LogicOperator, ValueInputType @@ -27,6 +27,16 @@ class CycleVariable(BaseNodeConfig): description="Initial or current value of the loop variable" ) + @field_validator("input_type", mode="before") + @classmethod + def lower_input_type(cls, v): + if isinstance(v, str): + try: + return ValueInputType(v.lower()) + except ValueError: + raise ValueError(f"Invalid input_type: {v}") + return v + class ConditionDetail(BaseModel): operator: ComparisonOperator = Field( @@ -49,6 +59,16 @@ class ConditionDetail(BaseModel): description="Input type of the loop variable" ) + @field_validator("input_type", mode="before") + @classmethod + def lower_input_type(cls, v): + if isinstance(v, str): + try: + return ValueInputType(v.lower()) + except ValueError: + raise ValueError(f"Invalid input_type: {v}") + return v + class ConditionsConfig(BaseModel): """Configuration for loop condition evaluation""" diff --git a/api/app/core/workflow/nodes/enums.py b/api/app/core/workflow/nodes/enums.py index fbbbf845..c294bb11 100644 --- a/api/app/core/workflow/nodes/enums.py +++ b/api/app/core/workflow/nodes/enums.py @@ -93,5 +93,5 @@ class HttpErrorHandle(StrEnum): class ValueInputType(StrEnum): - VARIABLE = "Variable" - CONSTANT = "Constant" + VARIABLE = "variable" + CONSTANT = "constant" diff --git a/api/app/core/workflow/nodes/if_else/config.py b/api/app/core/workflow/nodes/if_else/config.py index 4dcb00d1..90b4bcde 100644 --- a/api/app/core/workflow/nodes/if_else/config.py +++ b/api/app/core/workflow/nodes/if_else/config.py @@ -27,6 +27,16 @@ class ConditionDetail(BaseModel): description="Value input type for comparison" ) + @field_validator("input_type", mode="before") + @classmethod + def lower_input_type(cls, v): + if isinstance(v, str): + try: + return ValueInputType(v.lower()) + except ValueError: + raise ValueError(f"Invalid input_type: {v}") + return v + class ConditionBranchConfig(BaseModel): """Configuration for a conditional branch""" From eabaae4a8f375e99f26f366fafa8957e8c795859 Mon Sep 17 00:00:00 2001 From: Mark Date: Tue, 6 Jan 2026 18:58:36 +0800 Subject: [PATCH 26/75] [fix] model parameter error --- api/app/controllers/app_controller.py | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/api/app/controllers/app_controller.py b/api/app/controllers/app_controller.py index 698f061d..d8479f97 100644 --- a/api/app/controllers/app_controller.py +++ b/api/app/controllers/app_controller.py @@ -728,9 +728,23 @@ async def draft_run_compare( from app.core.exceptions import ResourceNotFoundException raise ResourceNotFoundException("模型配置", str(model_item.model_config_id)) + # 获取 agent_cfg.model_parameters,如果是 ModelParameters 对象则转为字典 + agent_model_params = agent_cfg.model_parameters + if hasattr(agent_model_params, 'model_dump'): + agent_model_params = agent_model_params.model_dump() + elif not isinstance(agent_model_params, dict): + agent_model_params = {} + + # 获取 model_item.model_parameters,如果是 ModelParameters 对象则转为字典 + item_model_params = model_item.model_parameters + if hasattr(item_model_params, 'model_dump'): + item_model_params = item_model_params.model_dump() + elif not isinstance(item_model_params, dict): + item_model_params = {} + merged_parameters = { - **(agent_cfg.model_parameters or {}), - **(model_item.model_parameters or {}) + **(agent_model_params or {}), + **(item_model_params or {}) } model_configs.append({ From 070d9036b708dfc805c230facea5efc7b7b90790 Mon Sep 17 00:00:00 2001 From: yujiangping Date: Tue, 6 Jan 2026 19:22:08 +0800 Subject: [PATCH 27/75] feat(i18n): add graph translation key for knowledge graph feature - Add 'graph' translation key to English locale (en.ts) - Add 'graph' translation key to Chinese locale (zh.ts) - Support for graph display label in knowledge graph UI components --- web/src/i18n/en.ts | 1 + web/src/i18n/zh.ts | 1 + 2 files changed, 2 insertions(+) diff --git a/web/src/i18n/en.ts b/web/src/i18n/en.ts index e679bcee..b53ff2bc 100644 --- a/web/src/i18n/en.ts +++ b/web/src/i18n/en.ts @@ -695,6 +695,7 @@ export const en = { fileDurationLimitError: 'The duration of the media file exceeds the limit. The maximum supported duration is 150 seconds. Current duration', unableReadFile:'Unable to read the information of the media file. Please check the file format.', // Knowledge Graph related + graph: 'Graph', knowledgeGraph: 'Knowledge Graph', basicConfig: 'Basic Configuration', enableKnowledgeGraph: 'Enable Knowledge Graph', diff --git a/web/src/i18n/zh.ts b/web/src/i18n/zh.ts index abb95a79..141d4600 100644 --- a/web/src/i18n/zh.ts +++ b/web/src/i18n/zh.ts @@ -305,6 +305,7 @@ export const zh = { fileDurationLimitError: '媒体文件时长超过限制,最大支持150秒,当前时长', unableReadFile:'无法读取媒体文件信息,请检查文件格式', // 知识图谱相关 + graph: '图谱', knowledgeGraph: '知识图谱', basicConfig: '基础配置', enableKnowledgeGraph: '启用知识图谱', From 26947d85aedab6d058f52518c0ee925bfd6d661d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=B0=A2=E4=BF=8A=E7=94=B7?= Date: Tue, 6 Jan 2026 20:05:18 +0800 Subject: [PATCH 28/75] feat(agent tool): agent tool bug fix --- .../controllers/public_share_controller.py | 10 ++-- .../controllers/service/app_api_controller.py | 7 +-- api/app/core/agent/langchain_agent.py | 2 +- api/app/schemas/app_schema.py | 18 ++++-- api/app/services/agent_config_converter.py | 22 ++++---- api/app/services/app_chat_service.py | 55 +++++++++++++------ api/app/services/app_service.py | 10 ++-- api/app/services/draft_run_service.py | 18 +++--- 8 files changed, 86 insertions(+), 56 deletions(-) diff --git a/api/app/controllers/public_share_controller.py b/api/app/controllers/public_share_controller.py index adb199fb..02c73718 100644 --- a/api/app/controllers/public_share_controller.py +++ b/api/app/controllers/public_share_controller.py @@ -433,7 +433,8 @@ async def chat( config=agent_config, memory=payload.memory, storage_type=storage_type, - user_rag_memory_id=user_rag_memory_id + user_rag_memory_id=user_rag_memory_id, + workspace_id=workspace_id ): yield event @@ -469,7 +470,8 @@ async def chat( web_search=payload.web_search, memory=payload.memory, storage_type=storage_type, - user_rag_memory_id=user_rag_memory_id + user_rag_memory_id=user_rag_memory_id, + workspace_id=workspace_id ) return success(data=conversation_schema.ChatResponse(**result).model_dump(mode="json")) elif app_type == AppType.MULTI_AGENT: @@ -486,8 +488,8 @@ async def chat( config=config, web_search=payload.web_search, memory=payload.memory, - storage_type=storage_type, - user_rag_memory_id=user_rag_memory_id + storage_type=storage_type, + user_rag_memory_id=user_rag_memory_id ): yield event diff --git a/api/app/controllers/service/app_api_controller.py b/api/app/controllers/service/app_api_controller.py index 180310a6..583b4700 100644 --- a/api/app/controllers/service/app_api_controller.py +++ b/api/app/controllers/service/app_api_controller.py @@ -197,8 +197,8 @@ async def chat( config=config, web_search=web_search, memory=memory, - storage_type=storage_type, - user_rag_memory_id=user_rag_memory_id + storage_type=storage_type, + user_rag_memory_id=user_rag_memory_id ): yield event @@ -214,7 +214,6 @@ async def chat( # 多 Agent 非流式返回 result = await app_chat_service.multi_agent_chat( - message=payload.message, conversation_id=conversation.id, # 使用已创建的会话 ID user_id=end_user_id, # 转换为字符串 @@ -293,4 +292,4 @@ async def chat( from app.core.exceptions import BusinessException from app.core.error_codes import BizCode raise BusinessException(f"不支持的应用类型: {app_type}", BizCode.APP_TYPE_NOT_SUPPORTED) - pass + diff --git a/api/app/core/agent/langchain_agent.py b/api/app/core/agent/langchain_agent.py index acd8cc5b..ef9a489f 100644 --- a/api/app/core/agent/langchain_agent.py +++ b/api/app/core/agent/langchain_agent.py @@ -7,7 +7,6 @@ LangChain Agent 封装 - 支持流式输出 - 使用 RedBearLLM 支持多提供商 """ -import os import time from typing import Any, AsyncGenerator, Dict, List, Optional, Sequence @@ -156,6 +155,7 @@ class LangChainAgent: store.delete_duplicate_sessions() # logger.info(f'Redis_Agent:{end_user_end};{session_id}') return session_id + async def term_memory_redis_read(self,end_user_end): end_user_end = f"Term_{end_user_end}" history = store.find_user_apply_group(end_user_end, end_user_end, end_user_end) diff --git a/api/app/schemas/app_schema.py b/api/app/schemas/app_schema.py index 81cd704d..d20570ce 100644 --- a/api/app/schemas/app_schema.py +++ b/api/app/schemas/app_schema.py @@ -1,6 +1,6 @@ import datetime import uuid -from typing import Optional, Any, List, Dict +from typing import Optional, Any, List, Dict, Union from pydantic import BaseModel, Field, ConfigDict, field_serializer, field_validator @@ -36,6 +36,12 @@ class KnowledgeRetrievalConfig(BaseModel): class ToolConfig(BaseModel): + """工具配置""" + enabled: bool = Field(default=False, description="是否启用该工具") + tool_id: str = Field(default=None, description="工具ID") + operation: Optional[str] = Field(default_factory=dict, description="工具特定配置") + +class ToolOldConfig(BaseModel): """工具配置""" enabled: bool = Field(default=False, description="是否启用该工具") config: Optional[Dict[str, Any]] = Field(default_factory=dict, description="工具特定配置") @@ -103,9 +109,9 @@ class AgentConfigCreate(BaseModel): ) # 工具配置 - tools: Dict[str, ToolConfig] = Field( - default_factory=dict, - description="工具配置,key 为工具名称(web_search, code_interpreter, image_generation 等)" + tools: List[ToolConfig] = Field( + default_factory=list, + description="Agent 可用的工具列表" ) @@ -158,7 +164,7 @@ class AgentConfigUpdate(BaseModel): variables: Optional[List[VariableDefinition]] = Field(default=None, description="变量列表") # 工具配置 - tools: Optional[Dict[str, ToolConfig]] = Field(default=None, description="工具配置") + tools: Optional[List[ToolConfig]] = Field(default=None, description="工具列表") # ---------- Output Schemas ---------- @@ -216,7 +222,7 @@ class AgentConfig(BaseModel): variables: List[VariableDefinition] = [] # 工具配置 - tools: Dict[str, ToolConfig] = {} + tools: Union[List[ToolConfig], Dict[str, ToolOldConfig]] = [] is_active: bool created_at: datetime.datetime diff --git a/api/app/services/agent_config_converter.py b/api/app/services/agent_config_converter.py index 3ab14157..eda4b5c4 100644 --- a/api/app/services/agent_config_converter.py +++ b/api/app/services/agent_config_converter.py @@ -2,14 +2,14 @@ Agent 配置格式转换器 用于将 Pydantic 模型转换为数据库存储格式 """ -from typing import Dict, Any, Optional +from typing import Dict, Any, Optional, Union from app.schemas.app_schema import ( KnowledgeRetrievalConfig, MemoryConfig, VariableDefinition, ToolConfig, AgentConfigCreate, - AgentConfigUpdate, + AgentConfigUpdate, ToolOldConfig, ) @@ -47,10 +47,7 @@ class AgentConfigConverter: # 5. 工具配置 if hasattr(config, 'tools') and config.tools: - result["tools"] = { - name: tool.model_dump() - for name, tool in config.tools.items() - } + result["tools"] = [tool.model_dump() for tool in config.tools] return result @@ -60,7 +57,7 @@ class AgentConfigConverter: knowledge_retrieval: Optional[Dict[str, Any]], memory: Optional[Dict[str, Any]], variables: Optional[list], - tools: Optional[Dict[str, Any]], + tools: Optional[Union[list, Dict[str, Any]]], ) -> Dict[str, Any]: """ 将数据库存储格式转换为 Pydantic 对象 @@ -113,9 +110,12 @@ class AgentConfigConverter: # 5. 解析工具配置 if tools: - result["tools"] = { - name: ToolConfig(**tool_data) - for name, tool_data in tools.items() - } + if isinstance(tools, list): + result["tools"] = [ToolConfig(**tool_config) for tool_config in tools] + else: + result["tools"] = { + name: ToolOldConfig(**tool_data) + for name, tool_data in tools.items() + } return result diff --git a/api/app/services/app_chat_service.py b/api/app/services/app_chat_service.py index 917184c7..537eac8d 100644 --- a/api/app/services/app_chat_service.py +++ b/api/app/services/app_chat_service.py @@ -78,13 +78,17 @@ class AppChatService: # 从配置中获取启用的工具 if hasattr(config, 'tools') and config.tools: - for tool_id, tool_config in config.tools.items(): + for tool_config in config.tools: if tool_config.get("enabled", False): # 根据工具名称查找工具实例 - tool_instance = tool_service._get_tool_instance(tool_id, ToolRepository.get_tenant_id_by_workspace_id(self.db, workspace_id)) + tool_instance = tool_service._get_tool_instance(tool_config.get("tool_id", ""), + ToolRepository.get_tenant_id_by_workspace_id( + self.db, workspace_id)) if tool_instance: + if tool_instance.name == "baidu_search_tool" and not web_search: + continue # 转换为LangChain工具 - langchain_tool = tool_instance.to_langchain_tool(tool_config.get("config", {}).get("operation", None)) + langchain_tool = tool_instance.to_langchain_tool(tool_config.get("operation", None)) tools.append(langchain_tool) # 添加知识库检索工具 @@ -219,6 +223,23 @@ class AppChatService: # 准备工具列表 tools = [] + # 获取工具服务 + tool_service = ToolService(self.db) + + if hasattr(config, 'tools') and config.tools: + for tool_config in config.tools: + if tool_config.get("enabled", False): + # 根据工具名称查找工具实例 + tool_instance = tool_service._get_tool_instance(tool_config.get("tool_id", ""), + ToolRepository.get_tenant_id_by_workspace_id( + self.db, workspace_id)) + if tool_instance: + if tool_instance.name == "baidu_search_tool" and not web_search: + continue + # 转换为LangChain工具 + langchain_tool = tool_instance.to_langchain_tool(tool_config.get("operation", None)) + tools.append(langchain_tool) + # 添加知识库检索工具 knowledge_retrieval = config.knowledge_retrieval if knowledge_retrieval: @@ -237,20 +258,20 @@ class AppChatService: memory_tool = create_long_term_memory_tool(memory_config, user_id) tools.append(memory_tool) - web_tools = config.tools - web_search_choice = web_tools.get("web_search", {}) - web_search_enable = web_search_choice.get("enabled", False) - if web_search == True: - if web_search_enable == True: - search_tool = create_web_search_tool({}) - tools.append(search_tool) - - logger.debug( - "已添加网络搜索工具", - extra={ - "tool_count": len(tools) - } - ) + # web_tools = config.tools + # web_search_choice = web_tools.get("web_search", {}) + # web_search_enable = web_search_choice.get("enabled", False) + # if web_search == True: + # if web_search_enable == True: + # search_tool = create_web_search_tool({}) + # tools.append(search_tool) + # + # logger.debug( + # "已添加网络搜索工具", + # extra={ + # "tool_count": len(tools) + # } + # ) # 获取模型参数 model_parameters = config.model_parameters diff --git a/api/app/services/app_service.py b/api/app/services/app_service.py index 38097c4e..e15f68fe 100644 --- a/api/app/services/app_service.py +++ b/api/app/services/app_service.py @@ -307,7 +307,7 @@ class AppService: knowledge_retrieval=storage_data.get("knowledge_retrieval"), memory=storage_data.get("memory"), variables=storage_data.get("variables", []), - tools=storage_data.get("tools", {}), + tools=storage_data.get("tools", []), is_active=True, created_at=now, updated_at=now, @@ -689,7 +689,7 @@ class AppService: knowledge_retrieval=source_config.knowledge_retrieval.copy() if source_config.knowledge_retrieval else None, memory=source_config.memory.copy() if source_config.memory else None, variables=source_config.variables.copy() if source_config.variables else [], - tools=source_config.tools.copy() if source_config.tools else {}, + tools=source_config.tools.copy() if source_config.tools else [], is_active=True, created_at=now, updated_at=now, @@ -879,7 +879,7 @@ class AppService: # if data.variables is not None: agent_cfg.variables = storage_data.get("variables", []) # if data.tools is not None: - agent_cfg.tools = storage_data.get("tools", {}) + agent_cfg.tools = storage_data.get("tools", []) agent_cfg.updated_at = now @@ -966,7 +966,7 @@ class AppService: "max_history": 10 }, variables=[], - tools={}, + tools=[], is_active=True, created_at=now, updated_at=now, @@ -1183,7 +1183,7 @@ class AppService: "knowledge_retrieval": agent_cfg.knowledge_retrieval, "memory": agent_cfg.memory, "variables": agent_cfg.variables or [], - "tools": agent_cfg.tools or {}, + "tools": agent_cfg.tools or [], } # config = AgentConfigConverter.from_storage_format(agent_cfg) default_model_config_id = agent_cfg.default_model_config_id diff --git a/api/app/services/draft_run_service.py b/api/app/services/draft_run_service.py index 79aebcce..9a1dbd32 100644 --- a/api/app/services/draft_run_service.py +++ b/api/app/services/draft_run_service.py @@ -298,16 +298,17 @@ class DraftRunService: # 从配置中获取启用的工具 if hasattr(agent_config, 'tools') and agent_config.tools: - for tool_id, tool_config in agent_config.tools.items(): + for tool_config in agent_config.tools: if tool_config.get("enabled", False): # 根据工具名称查找工具实例 - tool_instance = tool_service._get_tool_instance(tool_id, + tool_instance = tool_service._get_tool_instance(tool_config.get("tool_id", ""), ToolRepository.get_tenant_id_by_workspace_id( self.db, str(workspace_id))) if tool_instance: + if tool_instance.name == "baidu_search_tool" and not web_search: + continue # 转换为LangChain工具 - langchain_tool = tool_instance.to_langchain_tool( - tool_config.get("config", {}).get("operation", None)) + langchain_tool = tool_instance.to_langchain_tool(tool_config.get("operation", None)) tools.append(langchain_tool) # 添加知识库检索工具 @@ -507,16 +508,17 @@ class DraftRunService: # 从配置中获取启用的工具 if hasattr(agent_config, 'tools') and agent_config.tools: - for tool_id, tool_config in agent_config.tools.items(): + for tool_config in agent_config.tools: if tool_config.get("enabled", False): # 根据工具名称查找工具实例 - tool_instance = tool_service._get_tool_instance(tool_id, + tool_instance = tool_service._get_tool_instance(tool_config.get("tool_id", ""), ToolRepository.get_tenant_id_by_workspace_id( self.db, str(workspace_id))) if tool_instance: + if tool_instance.name == "baidu_search_tool" and not web_search: + continue # 转换为LangChain工具 - langchain_tool = tool_instance.to_langchain_tool( - tool_config.get("config", {}).get("operation", None)) + langchain_tool = tool_instance.to_langchain_tool(tool_config.get("operation", None)) tools.append(langchain_tool) # 添加知识库检索工具 From 020d7445ec35c0ed2b7a5839438c937f238d88f6 Mon Sep 17 00:00:00 2001 From: zhaoying Date: Tue, 6 Jan 2026 20:14:43 +0800 Subject: [PATCH 29/75] feat(web): agent support add tools --- web/src/views/ApplicationConfig/Agent.tsx | 65 +++++--- .../components/Knowledge.tsx | 53 +++---- .../ApplicationConfig/components/ToolList.tsx | 149 ++++++++++++++++++ .../components/ToolModal.tsx | 145 +++++++++++++++++ web/src/views/ApplicationConfig/types.ts | 36 ++++- 5 files changed, 389 insertions(+), 59 deletions(-) create mode 100644 web/src/views/ApplicationConfig/components/ToolList.tsx create mode 100644 web/src/views/ApplicationConfig/components/ToolModal.tsx diff --git a/web/src/views/ApplicationConfig/Agent.tsx b/web/src/views/ApplicationConfig/Agent.tsx index c6aa63e8..f3e327ec 100644 --- a/web/src/views/ApplicationConfig/Agent.tsx +++ b/web/src/views/ApplicationConfig/Agent.tsx @@ -18,7 +18,9 @@ import type { Variable, MemoryConfig, AiPromptModalRef, - Source + Source, + ToolModalRef, + ToolOption } from './types' import type { Model } from '@/views/ModelManagement/types' import { getModelList } from '@/api/models'; @@ -31,6 +33,8 @@ import { memoryConfigListUrl } from '@/api/memory' import CustomSelect from '@/components/CustomSelect' import aiPrompt from '@/assets/images/application/aiPrompt.png' import AiPromptModal from './components/AiPromptModal' +import ToolModal from './components/ToolModal' +import ToolList from './components/ToolList' const DescWrapper: FC<{desc: string, className?: string}> = ({desc, className}) => { return ( @@ -47,12 +51,12 @@ const LabelWrapper: FC<{title: string, className?: string; children?: ReactNode}
) } -const SwitchWrapper: FC<{ title: string, desc: string, name: string }> = ({ title, desc, name }) => { +const SwitchWrapper: FC<{ title: string, desc?: string, name: string | string[]; needTransition?: boolean; }> = ({ title, desc, name, needTransition = true }) => { const { t } = useTranslation(); return (
- - + + {desc && } ((_props, ref) => { const [formData, setFormData] = useState<{ default_model_config_id?: string, model_parameters?: Config['model_parameters'], + tools: ToolOption[], } | null>(null) const values = Form.useWatch<{ memoryEnabled: boolean; memory_content?: string | number; - webSearch: boolean; } & Config>([], form) const [knowledgeConfig, setKnowledgeConfig] = useState({ knowledge_bases: [] }) @@ -149,17 +153,21 @@ const Agent = forwardRef((_props, ref) => { setLoading(true) getApplicationConfig(id as string).then(res => { const response = res as Config - setData(response) + setData({ + ...response, + tools: Array.isArray(response.tools) ? response.tools : [] + }) const { memory, tools } = response form.setFieldsValue({ ...response, memoryEnabled: memory?.enabled || false, memory_content: memory?.memory_content ? Number(memory?.memory_content) : undefined, - webSearch: tools?.web_search?.enabled || false, + tools: Array.isArray(tools) ? tools : [] }) setFormData({ default_model_config_id: response.default_model_config_id, model_parameters: response.model_parameters || {}, + tools: Array.isArray(tools) ? tools : [] }) if (response?.knowledge_retrieval?.knowledge_bases?.length) { getDefaultKnowledgeList(response) @@ -260,8 +268,9 @@ const Agent = forwardRef((_props, ref) => { // 保存Agent配置 const handleSave = (flag = true) => { if (!isSave || !data) return Promise.resolve() - const { memoryEnabled, memory_content, webSearch, ...rest } = values + const { memoryEnabled, memory_content, ...rest } = values const { knowledge_bases = [], ...knowledgeRest } = knowledgeConfig || {} + // 从原数据中获取memory的其他必要属性 const originalMemory = data.memory || ({} as MemoryConfig) @@ -285,15 +294,10 @@ const Agent = forwardRef((_props, ref) => { ...(item.config || {}) })) } as KnowledgeConfig : null, - tools: { - web_search: { - enabled: webSearch, - config: { - web_search: webSearch - } - } - } + tools: toolList } + + console.log('params', rest, params) return new Promise((resolve, reject) => { saveAgentConfig(data.app_id, params) @@ -342,6 +346,19 @@ const Agent = forwardRef((_props, ref) => { const updatePrompt = (value: string) => { form.setFieldValue('system_prompt', value) } + + const toolModalRef = useRef(null) + const [toolList, setToolList] = useState([]) + const handleAddTool = () => { + toolModalRef.current?.handleOpen() + } + const updateTools = (tool: ToolOption) => { + const tools = [...toolList, tool] + setToolList(tools) + form.setFieldValue('tools', tools) + } + + console.log('toolList', toolList) return ( <> {loading && } @@ -410,14 +427,12 @@ const Agent = forwardRef((_props, ref) => { data={data?.variables} onUpdate={setVariableList} /> + {/* 工具配置 */} - - - - {/* - */} - - + @@ -454,6 +469,10 @@ const Agent = forwardRef((_props, ref) => { defaultModel={defaultModel} refresh={updatePrompt} /> + ); }); diff --git a/web/src/views/ApplicationConfig/components/Knowledge.tsx b/web/src/views/ApplicationConfig/components/Knowledge.tsx index 0fac117d..bc1207e4 100644 --- a/web/src/views/ApplicationConfig/components/Knowledge.tsx +++ b/web/src/views/ApplicationConfig/components/Knowledge.tsx @@ -31,10 +31,6 @@ const Knowledge: FC<{data: KnowledgeConfig; onUpdate: (config: KnowledgeConfig) setEditConfig({ ...(data || {}) }) const knowledge_bases = [...(data.knowledge_bases || [])] setKnowledgeList(knowledge_bases) - onUpdate(prev => ({ - ...prev, - knowledge_bases: knowledge_bases, - })) } }, [data]) @@ -47,10 +43,10 @@ const Knowledge: FC<{data: KnowledgeConfig; onUpdate: (config: KnowledgeConfig) const handleDeleteKnowledge = (id: string) => { const list = knowledgeList.filter(item => item.id !== id) setKnowledgeList([...list]) - onUpdate(prev => ({ - ...prev, + onUpdate({ + ...editConfig, knowledge_bases: [...list], - })) + }) } const handleEditKnowledge = (item: KnowledgeBase) => { knowledgeConfigModalRef.current?.handleOpen(item) @@ -69,10 +65,10 @@ const Knowledge: FC<{data: KnowledgeConfig; onUpdate: (config: KnowledgeConfig) list = [...values as KnowledgeBase[]] } setKnowledgeList([...list]) - onUpdate(prev => ({ - ...prev, + onUpdate({ + ...editConfig, knowledge_bases: [...list], - })) + }) } else if (type === 'knowledgeConfig') { const index = knowledgeList.findIndex(item => item.id === (values as KnowledgeBase).kb_id) const list = [...knowledgeList] @@ -81,18 +77,19 @@ const Knowledge: FC<{data: KnowledgeConfig; onUpdate: (config: KnowledgeConfig) config: {...values as KnowledgeConfigForm} } setKnowledgeList([...list]) - onUpdate(prev => ({ - ...prev, + onUpdate({ + ...editConfig, knowledge_bases: [...list], - })) + }) } else if (type === 'rerankerConfig') { - setEditConfig(prev => ({ ...prev, ...(values as RerankerConfig) })) - onUpdate(prev => ({ - ...prev, - ...values, - reranker_id: values.rerank_model ? values.reranker_id : undefined, - reranker_top_k: values.rerank_model ? values.reranker_top_k : undefined, - })) + const rerankerValues = values as RerankerConfig + setEditConfig(prev => ({ ...prev, ...rerankerValues })) + onUpdate({ + ...editConfig, + ...rerankerValues, + reranker_id: rerankerValues.rerank_model ? rerankerValues.reranker_id : undefined, + reranker_top_k: rerankerValues.rerank_model ? rerankerValues.reranker_top_k : undefined, + }) } } return ( @@ -102,8 +99,8 @@ const Knowledge: FC<{data: KnowledgeConfig; onUpdate: (config: KnowledgeConfig) } > -
-
{t('application.associatedKnowledgeBase')}
+
+
{t('application.associatedKnowledgeBase')}
@@ -115,21 +112,21 @@ const Knowledge: FC<{data: KnowledgeConfig; onUpdate: (config: KnowledgeConfig) dataSource={knowledgeList} renderItem={(item) => ( -
-
+
+
{item.name} - + {item.status === 1 ? t('common.enable') : item.status === 0 ? t('common.disabled') : t('common.deleted')} -
{t('application.contains', {include_count: item.doc_num})}
+
{t('application.contains', {include_count: item.doc_num})}
handleEditKnowledge(item)} >
handleDeleteKnowledge(item.id)} >
diff --git a/web/src/views/ApplicationConfig/components/ToolList.tsx b/web/src/views/ApplicationConfig/components/ToolList.tsx new file mode 100644 index 00000000..9834b186 --- /dev/null +++ b/web/src/views/ApplicationConfig/components/ToolList.tsx @@ -0,0 +1,149 @@ +import { type FC, useRef, useState, useEffect } from 'react' +import { useTranslation } from 'react-i18next' +import { Space, Button, List, Switch } from 'antd' +import Card from './Card' +import type { + ToolModalRef, + ToolOption +} from '../types' +import Empty from '@/components/Empty' +import ToolModal from './ToolModal' +import { getToolMethods, getToolDetail } from '@/api/tools' + +const ToolList: FC<{ data: ToolOption[]; onUpdate: (config: ToolOption[]) => void}> = ({data, onUpdate}) => { + const { t } = useTranslation() + const toolModalRef = useRef(null) + const [toolList, setToolList] = useState([]) + useEffect(() => { + if (data) { + const processedData = data.map(async (item) => { + if (!item.label && item.tool_id) { + try { + const [toolDetail, methods] = await Promise.all([ + getToolDetail(item.tool_id), + getToolMethods(item.tool_id) + ]) + + switch ((toolDetail as any).tool_type) { + case 'mcp': + const mcpFilterItem = (methods as any[]).find(vo => vo.name === item.operation) + return { + ...item, + label: mcpFilterItem?.description, + method_id: mcpFilterItem?.method_id, + value: mcpFilterItem?.name, + description: mcpFilterItem?.description, + parameters: mcpFilterItem?.parameters + } + break + case 'builtin': + if ((methods as any[]).length > 1) { + const builtinFilterItem = (methods as any[]).find(vo => vo.name === item.operation) + return { + ...item, + label: builtinFilterItem?.description, + method_id: builtinFilterItem?.method_id, + value: builtinFilterItem?.name, + description: builtinFilterItem?.description, + parameters: builtinFilterItem?.parameters + } + } + return { + ...item, + label: (methods as any[])[0]?.description, + method_id: (methods as any[])[0]?.method_id, + value: (methods as any[])[0]?.name, + description: (methods as any[])[0]?.description, + parameters: (methods as any[])[0]?.parameters + } + break + default: + const customFilterItem = (methods as any[]).find(vo => vo.method_id === item.operation) + return { + ...item, + label: customFilterItem?.name, + method_id: customFilterItem?.method_id, + value: customFilterItem?.name, + description: customFilterItem?.description, + parameters: customFilterItem?.parameters + } + } + } catch (error) { + return item + } + } + return item + }) + + Promise.all(processedData).then(setToolList) + } + }, [data]) + + console.log('toolList', toolList) + + const handleAddTool = () => { + toolModalRef.current?.handleOpen() + } + const updateTools = (tool: ToolOption) => { + const list = [...toolList, tool] + setToolList(list) + onUpdate(list) + } + const handleDeleteTool = (index: number) => { + const list = toolList.filter((_item, idx) => idx !== index) + setToolList([...list]) + onUpdate(list) + } + const handleChangeEnabled = (index: number) => { + const list = toolList.map((item, idx) => { + if (idx === index) { + return { + ...item, + enabled: !item.enabled + } + } + return item + }) + setToolList([...list]) + onUpdate(list) + } + return ( + +{t('application.addTool')} + } + > + + {toolList.length === 0 + ? + : + ( + +
+
+ {item.label} +
+ +
handleDeleteTool(index)} + >
+ handleChangeEnabled(index)} /> +
+
+
+ )} + /> + } + +
+ ) +} +export default ToolList \ No newline at end of file diff --git a/web/src/views/ApplicationConfig/components/ToolModal.tsx b/web/src/views/ApplicationConfig/components/ToolModal.tsx new file mode 100644 index 00000000..64fd6044 --- /dev/null +++ b/web/src/views/ApplicationConfig/components/ToolModal.tsx @@ -0,0 +1,145 @@ +import { forwardRef, useImperativeHandle, useState } from 'react'; +import { Form, Cascader, type CascaderProps } from 'antd'; +import { useTranslation } from 'react-i18next'; + +import type { ToolModalRef, ToolOption } from '../types' +import RbModal from '@/components/RbModal' +import { getToolMethods, getTools } from '@/api/tools' +import type { ToolType, ToolItem } from '@/views/ToolManagement/types' + +const FormItem = Form.Item; + +interface ToolModalProps { + refresh: (tool: ToolOption) => void; +} + +const ToolModal = forwardRef(({ + refresh, +}, ref) => { + const { t } = useTranslation(); + const [visible, setVisible] = useState(false); + const [form] = Form.useForm(); + const [loading, setLoading] = useState(false) + const [optionList, setOptionList] = useState([ + { value: 'mcp', label: t('tool.mcp'), isLeaf: false }, + { value: 'builtin', label: t('tool.inner'), isLeaf: false }, + { value: 'custom', label: t('tool.custom'), isLeaf: false }, + ]) + const [selectdTools, setSelectedTools] = useState([]) + + // 封装取消方法,添加关闭弹窗逻辑 + const handleClose = () => { + setVisible(false); + form.resetFields(); + setLoading(false) + setSelectedTools([]) + }; + + const handleOpen = () => { + setVisible(true); + form.resetFields(); + setSelectedTools([]) + }; + // 封装保存方法,添加提交逻辑 + const handleSave = () => { + form.validateFields().then(() => { + setLoading(false) + let operation: any = undefined + if (selectdTools[0].value === 'mcp' || (selectdTools[0].value === 'builtin' && selectdTools[1]?.children && selectdTools[1].children.length > 1)) { + operation = selectdTools[2].value + } else if (selectdTools[0].value === 'custom') { + operation = selectdTools[2].method_id + } + + const tool = { + ...selectdTools[2], + label: selectdTools[0].value === 'custom' ? selectdTools[2].label : selectdTools[2].description, + tool_id: selectdTools[1].value as string, + enabled: true + } + if (operation) { + tool.operation = operation + } + refresh(tool) + handleClose() + }) + } + const loadData = (selectedOptions: ToolOption[]) => { + const targetOption = selectedOptions[selectedOptions.length - 1]; + if (selectedOptions.length === 1) { + getTools({ tool_type: targetOption.value as ToolType }) + .then(res => { + const response = res as ToolItem[] + targetOption.children = response.map((vo: any) => { + return { + value: vo.id, + label: vo.name, + isLeaf: response.length === 0, + } + }) + setOptionList([...optionList]) + }) + } else { + getToolMethods(targetOption.value as string) + .then(res => { + const response = res as Array<{ method_id: string; name: string }> + targetOption.children = response.map((vo: any) => { + return { + value: vo.name, + label: vo.name, + description: vo.description, + isLeaf: true, + method_id: vo.method_id, + parameters: vo.parameters + } + }) + setOptionList([...optionList]) + }) + } + }; + + const handleChange: CascaderProps['onChange'] = (_value, selectedOptions) => { + console.log('selectedOptions', selectedOptions) + setSelectedTools(selectedOptions) + } + + // 暴露给父组件的方法 + useImperativeHandle(ref, () => ({ + handleOpen, + handleClose + })); + + return ( + +
+ + + +
+
+ ); +}); + +export default ToolModal; \ No newline at end of file diff --git a/web/src/views/ApplicationConfig/types.ts b/web/src/views/ApplicationConfig/types.ts index 3a1c262c..cc6852b5 100644 --- a/web/src/views/ApplicationConfig/types.ts +++ b/web/src/views/ApplicationConfig/types.ts @@ -78,14 +78,7 @@ export interface Config extends MultiAgentConfig { knowledge_retrieval: KnowledgeConfig | null; memory?: MemoryConfig; variables: Variable[]; - tools: { - web_search: { - enabled: boolean; - config: { - web_search: boolean; - } - } - }; + tools: ToolOption[]; is_active: boolean; created_at: number; updated_at: number; @@ -211,4 +204,31 @@ export interface AiPromptForm { model_id?: string; message?: string; current_prompt?: string; +} +export interface ToolModalRef { + handleOpen: () => void; +} + +export interface ToolOption { + value?: string | number | null; + label?: React.ReactNode; + description?: string; + children?: ToolOption[]; + isLeaf?: boolean; + method_id?: string; + operation?: string; + parameters?: Parameter[]; + tool_id?: string; + enabled?: boolean; +} +export interface Parameter { + name: string; + type: string; + description: string; + required: boolean; + default: any; + enum: null | string[]; + minimum: number; + maximum: number; + pattern: null | string; } \ No newline at end of file From 7a1131d8afce0006b2542eb56e199ae2d08b3f10 Mon Sep 17 00:00:00 2001 From: zhaoying Date: Tue, 6 Jan 2026 20:35:01 +0800 Subject: [PATCH 30/75] fix(web): workflow bug --- .../Properties/AssignmentList/index.tsx | 25 +- .../components/Properties/CaseList/index.tsx | 14 +- .../Properties/ConditionList/index.tsx | 12 +- .../Properties/HttpRequest/EditableTable.tsx | 252 ++++++++---------- .../Properties/HttpRequest/index.tsx | 33 +-- .../Properties/ParamsList/ParamEditModal.tsx | 1 + .../Workflow/components/Properties/index.tsx | 4 +- web/src/views/Workflow/constant.ts | 6 +- .../views/Workflow/hooks/useWorkflowGraph.ts | 26 +- web/src/views/Workflow/types.ts | 2 +- 10 files changed, 177 insertions(+), 198 deletions(-) diff --git a/web/src/views/Workflow/components/Properties/AssignmentList/index.tsx b/web/src/views/Workflow/components/Properties/AssignmentList/index.tsx index eac3775f..2ac8397b 100644 --- a/web/src/views/Workflow/components/Properties/AssignmentList/index.tsx +++ b/web/src/views/Workflow/components/Properties/AssignmentList/index.tsx @@ -62,6 +62,10 @@ const AssignmentList: FC = ({ placeholder={t('common.pleaseSelect')} options={options} popupMatchSelectWidth={false} + onChange={() => { + form.setFieldValue([parentName, name, 'operation'], undefined); + form.setFieldValue([parentName, name, 'value'], undefined); + }} /> @@ -72,6 +76,7 @@ const AssignmentList: FC = ({ noStyle > ({ ...vo, diff --git a/web/src/views/Workflow/components/Properties/ConditionList/index.tsx b/web/src/views/Workflow/components/Properties/ConditionList/index.tsx index 2f544281..6d955647 100644 --- a/web/src/views/Workflow/components/Properties/ConditionList/index.tsx +++ b/web/src/views/Workflow/components/Properties/ConditionList/index.tsx @@ -9,7 +9,7 @@ import Editor from '../../Editor' interface Case { logical_operator: 'and' | 'or'; - expressions: Array<{ left: string; comparison_operator: string; right: string; input_type: string; }> + expressions: Array<{ left: string; operator: string; right: string; input_type: string; }> } interface CaseListProps { @@ -45,6 +45,8 @@ const operatorsObj: { [key: string]: SelectProps['options'] } = { boolean: [ { value: 'eq', label: 'workflow.config.if-else.boolean.eq' }, { value: 'ne', label: 'workflow.config.if-else.boolean.ne' }, + { value: 'empty', label: 'workflow.config.if-else.empty' }, + { value: 'not_empty', label: 'workflow.config.if-else.not_empty' }, ] } @@ -61,7 +63,7 @@ const ConditionList: FC = ({ expressions: { [index]: { left: newValue, - comparison_operator: undefined, + operator: undefined, right: undefined, input_type: undefined } @@ -87,7 +89,7 @@ const ConditionList: FC = ({ {fields.map((field, index) => { const expressions = form.getFieldValue([parentName, 'expressions']) || []; const currentExpression = expressions[index] || {}; - const currentOperator = currentExpression.comparison_operator; + const currentOperator = currentExpression.operator; const hideRightField = currentOperator === 'empty' || currentOperator === 'not_empty'; const leftFieldValue = currentExpression.left; const leftFieldOption = options.find(option => `{{${option.value}}}` === leftFieldValue); @@ -122,7 +124,7 @@ const ConditionList: FC = ({ - + + ) : ( + + )} + + + ); +}; + export interface TableRow { key: string; - name: string; - value: string; + name?: string; + value?: string; type?: string; } interface EditableTableProps { + parentName: string | string[]; title?: string; - value?: Record | TableRow[]; - onChange?: (value: TableRow[]) => void; options?: Suggestion[]; - typeOptions?: {value: string, label: string}[] + typeOptions?: { value: string, label: string }[] } const EditableTable: React.FC = ({ + parentName, title, - value, - onChange, options = [], typeOptions = [] }) => { - const { t } = useTranslation() - const [rows, setRows] = useState([]); + const { t } = useTranslation(); + const form = Form.useFormInstance(); + const values = Form.useWatch(typeof parentName === 'string' ? [parentName] : parentName, form); - useEffect(() => { - if (Array.isArray(value)) { - setRows([...value]) - } else if (value && Object.keys(value).length > 0) { - setRows(Object.entries(value).map(([key, val], index) => ({ - key: index.toString(), - name: key || '', - value: val || '', - type: typeOptions.length > 0 ? typeOptions[0].value : undefined - }))) - } else { - setRows([]) - } - }, [value, typeOptions]) + const createNewRow = (): TableRow => ({ + key: Date.now().toString(), + name: undefined, + value: undefined, + ...(typeOptions.length > 0 && { type: typeOptions[0].value }) + }); - const handleChange = (key: string, field: 'name' | 'value' | 'type', val: string) => { - const newRows = rows.map(row => - row.key === key ? { ...row, [field]: val } : row - ); - setRows(newRows); - onChange?.(newRows); - }; + const handleAdd = useCallback(() => { + form.setFieldValue(parentName, [...(values ?? []), createNewRow()]); + }, [form, parentName, values, typeOptions]); - const handleAdd = () => { - const newRow: TableRow = { - key: Date.now().toString(), - name: '', - value: '', - ...(typeOptions.length > 0 && { type: typeOptions[0].value }) - }; - const newRows = [...rows, newRow]; - setRows(newRows); - onChange?.(newRows); - }; + const handleDelete = useCallback((index: number) => { + const currentValues = form.getFieldValue(parentName) || []; + form.setFieldValue(parentName, currentValues.filter((_: TableRow, i: number) => i !== index)); + }, [form, parentName]); - const handleDelete = (key: string) => { - const newRows = rows.filter(row => row.key !== key); - setRows(newRows); - onChange?.(newRows); - }; + const createColumn = (dataIndex: string, inputType: 'select' | 'variableSelect', width: string, columnOptions: any[]) => ({ + title: t(`workflow.config.${dataIndex}`), + dataIndex, + width, + onCell: (_: TableRow, index?: number) => ({ + name: typeof parentName === 'string' ? [parentName, index ?? 0, dataIndex] : [...parentName, index ?? 0, dataIndex], + inputType, + options: columnOptions + } as any) + }); - const columns = useMemo(() => { - const baseColumns = [ + const columns: TableProps['columns'] = useMemo(() => { + const hasType = typeOptions.length > 0; + const baseWidth = hasType ? '35%' : '45%'; + + return [ + createColumn('name', 'variableSelect', baseWidth, options), + ...(hasType ? [createColumn('type', 'select', '20%', typeOptions)] : []), + createColumn('value', 'variableSelect', baseWidth, options), { - title: typeOptions.length > 0 ? t('workflow.config.name') : '键', - dataIndex: 'name', - width: typeOptions.length > 0 ? '35%' : '45%', - render: (text: string, record: TableRow) => ( - handleChange(record.key, 'name', value || '')} - /> - ), + title: '', + dataIndex: 'actions', + width: '10%', + render: (_: any, __: TableRow, index: number) => ( +
+ ) +} +export default EpisodicDetail \ No newline at end of file diff --git a/web/src/views/UserMemoryDetail/pages/ForgetDetail.tsx b/web/src/views/UserMemoryDetail/pages/ForgetDetail.tsx index 6a59d41a..f0ba04ff 100644 --- a/web/src/views/UserMemoryDetail/pages/ForgetDetail.tsx +++ b/web/src/views/UserMemoryDetail/pages/ForgetDetail.tsx @@ -20,7 +20,7 @@ const statusTagColors: Record { +const ForgetDetail: FC = () => { const { t } = useTranslation() const { id } = useParams() const [loading, setLoading] = useState(false) @@ -156,4 +156,4 @@ const ForgetOverview: FC = () => {
) } -export default ForgetOverview \ No newline at end of file +export default ForgetDetail \ No newline at end of file diff --git a/web/src/views/UserMemoryDetail/pages/GraphDetail.tsx b/web/src/views/UserMemoryDetail/pages/GraphDetail.tsx new file mode 100644 index 00000000..f3cf716c --- /dev/null +++ b/web/src/views/UserMemoryDetail/pages/GraphDetail.tsx @@ -0,0 +1,14 @@ +import { type FC } from 'react' +import { useTranslation } from 'react-i18next' +import { Row, Col } from 'antd' + +const GraphDetail: FC = () => { + const { t } = useTranslation() + + return ( +
+ GraphDetail +
+ ) +} +export default GraphDetail \ No newline at end of file diff --git a/web/src/views/UserMemoryDetail/pages/ImplicitDetail.tsx b/web/src/views/UserMemoryDetail/pages/ImplicitDetail.tsx new file mode 100644 index 00000000..ef23463a --- /dev/null +++ b/web/src/views/UserMemoryDetail/pages/ImplicitDetail.tsx @@ -0,0 +1,34 @@ +import { type FC } from 'react' +import { useTranslation } from 'react-i18next' +import { Row, Col } from 'antd' + +import Preferences from '../components/Preferences' +import Portrait from '../components/Portrait' +import InterestAreas from '../components/InterestAreas' +import Habits from '../components/Habits' + +const ImplicitDetail: FC = () => { + const { t } = useTranslation() + + return ( +
+
{t('implicitDetail.title')}
+ + + +
{t('implicitDetail.portraitTitle')}
+
{t('implicitDetail.portraitSubTitle')}
+ + + + + + + + + + +
+ ) +} +export default ImplicitDetail \ No newline at end of file diff --git a/web/src/views/UserMemoryDetail/pages/PerceptualDetail.tsx b/web/src/views/UserMemoryDetail/pages/PerceptualDetail.tsx new file mode 100644 index 00000000..7e2d5353 --- /dev/null +++ b/web/src/views/UserMemoryDetail/pages/PerceptualDetail.tsx @@ -0,0 +1,32 @@ +import { type FC } from 'react' +import { useTranslation } from 'react-i18next' +import { Row, Col } from 'antd' + +import PerceptualLastInfo from '../components/PerceptualLastInfo' +import Timeline from '../components/Timeline' + +const PerceptualDetail: FC = () => { + const { t } = useTranslation() + + return ( +
+
{t('perceptualDetail.lastInfo')}
+ + + + + + + + + + + + + +
{t('perceptualDetail.timeLine')}
+ +
+ ) +} +export default PerceptualDetail \ No newline at end of file diff --git a/web/src/views/UserMemoryDetail/pages/ShortTermDetail.tsx b/web/src/views/UserMemoryDetail/pages/ShortTermDetail.tsx new file mode 100644 index 00000000..6cc8eafc --- /dev/null +++ b/web/src/views/UserMemoryDetail/pages/ShortTermDetail.tsx @@ -0,0 +1,114 @@ +import { type FC, useEffect, useState } from 'react' +import { useTranslation } from 'react-i18next' +import { useParams } from 'react-router-dom' +import { Space, Skeleton } from 'antd' +import { + getShortTerm, +} from '@/api/memory' +import Empty from '@/components/Empty' + +interface ShortTermItem { + retrieval: Array<{ query: string; retrieval: string[]; }>; + message: string; + answer: string; +} +interface LongTermItem { + query: string; + retrieval: string; +} +interface ShortData { + short_term: ShortTermItem[]; + long_term: LongTermItem[]; + entity: number; + retrieval_number: number; + long_term_number: number; +} +const ShortTermDetail: FC = () => { + const { t } = useTranslation() + const { id } = useParams() + const [loading, setLoading] = useState(false) + const [data, setData] = useState({} as ShortData) + + useEffect(() => { + if (!id) return + getData() + }, [id]) + + const getData = () => { + if (!id) return + setLoading(true) + getShortTerm(id).then((res) => { + const response = res as ShortData + setData(response) + setLoading(false) + }) + .finally(() => { + setLoading(false) + }) + } + + return ( +
+
+
{t('shortTermDetail.title')}
+ +
+ {(['retrieval_number', 'entity', 'long_term_number'] as const).map(key => ( +
+
{(data as any)[key] ?? 0}
+ {t(`shortTermDetail.${key}`)} +
+ ))} +
+
+ + +
{t('shortTermDetail.shortTermTitle')}
+
{t('shortTermDetail.shortTermSubTitle')}
+ + {loading + ? + : !data.short_term || data.short_term.length === 0 + ? + :data.short_term?.map((vo, voIdx) => ( +
+
{vo.message}
+ + {vo.retrieval.map((item, index) => ( +
+
{t('shortTermDetail.query')}: {item.query}
+
{t('shortTermDetail.answer')}:
+ {item.retrieval.length > 0 ? item.retrieval.map((retrieval, retrievalIdx) => ( +
- {retrieval}
+ )) :
{t('shortTermDetail.noAnswer')}
} +
+ ))} +
+
{t('shortTermDetail.answer')}
+
{vo.answer}
+
+
+
+ )) + } +
+ +
{t('shortTermDetail.longTermTitle')}
+
{t('shortTermDetail.shortTermSubTitle')}
+ + {loading + ? + : !data.long_term || data.long_term.length === 0 + ? + : data.long_term?.map((vo, voIdx) => ( +
+
{vo.query}
+
{vo.retrieval}
+
+ )) + } +
+
+ ) +} +export default ShortTermDetail \ No newline at end of file diff --git a/web/src/views/UserMemoryDetail/pages/index.tsx b/web/src/views/UserMemoryDetail/pages/index.tsx index 6b78a210..da62c14e 100644 --- a/web/src/views/UserMemoryDetail/pages/index.tsx +++ b/web/src/views/UserMemoryDetail/pages/index.tsx @@ -1,15 +1,23 @@ -import { type FC, useEffect, useState } from 'react' -import { useParams } from 'react-router-dom' +import { type FC, useEffect, useState, useMemo } from 'react' +import { useParams, useNavigate } from 'react-router-dom' +import { useTranslation } from 'react-i18next' +import { Dropdown } from 'antd' import PageHeader from '../components/PageHeader' import StatementDetail from './StatementDetail' import ForgetDetail from './ForgetDetail' +import ImplicitDetail from './ImplicitDetail' +import ShortTermDetail from './ShortTermDetail' +import PerceptualDetail from './PerceptualDetail' +import EpisodicDetail from './EpisodicDetail' import { getEndUserProfile, } from '@/api/memory' const Detail: FC = () => { + const { t } = useTranslation() const { id, type } = useParams() + const navigate = useNavigate() const [name, setName] = useState('') useEffect(() => { if (!id) return @@ -23,17 +31,37 @@ const Detail: FC = () => { setName(response.other_name || response.id) }) } + const items = useMemo(() => { + return ['PERCEPTUAL_MEMORY', 'WORKING_MEMORY', 'EMOTIONAL_MEMORY', 'SHORT_TERM_MEMORY', 'IMPLICIT_MEMORY', 'EPISODIC_MEMORY', 'EXPLICIT_MEMORY', 'FORGETTING_MANAGEMENT'] + .map(key => ({ key, label: t(`userMemory.${key}`) })) + }, [t]) + const onClick = ({ key }: { key: string }) => { + navigate(`/user-memory/detail/${id}/${key}`, { replace: true }) + } - console.log('Detail', name) return (
+
+ - {type ? t(`userMemory.${type}`) : ''} +
+
+ + } />
{type === 'EMOTIONAL_MEMORY' && } {type === 'FORGETTING_MANAGEMENT' && } + {type === 'IMPLICIT_MEMORY' && } + {type === 'SHORT_TERM_MEMORY' && } + {type === 'PERCEPTUAL_MEMORY' && } {/** TODO */} + {type === 'EPISODIC_MEMORY' && }
) diff --git a/web/src/views/UserMemoryDetail/types.ts b/web/src/views/UserMemoryDetail/types.ts index 77dd653e..263494d0 100644 --- a/web/src/views/UserMemoryDetail/types.ts +++ b/web/src/views/UserMemoryDetail/types.ts @@ -44,6 +44,7 @@ export interface Data { export interface BaseProperties { content: string; created_at: number; + associative_memory: number; } export interface StatementNodeProperties { temporal_info: string; @@ -51,12 +52,21 @@ export interface StatementNodeProperties { statement: string; valid_at: string; created_at: number; + emotion_keywords: string[]; + emotion_type: string; + emotion_subject: string; + importance_score: number; + associative_memory: number; } export interface ExtractedEntityNodeProperties { description: string; name: string; entity_type: string; created_at: number; + aliases: string; + connect_strngth: string; + importance_score: number; + associative_memory: number; } export interface MemorySummaryNode { id: string; @@ -72,7 +82,7 @@ export interface MemorySummaryNode { created_at: number; } caption: string; - + associative_memory: number; } export interface Node { From 7d28717030955918a2f4b76bb6f2e14e91351dd6 Mon Sep 17 00:00:00 2001 From: lixinyue11 <94037597+lixinyue11@users.noreply.github.com> Date: Sat, 10 Jan 2026 12:37:11 +0800 Subject: [PATCH 62/75] Fix/develop memory deail (#63) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * 新增记忆空间详情 * 新增记忆空间详情 * 新增记忆关联的数量 * 修改记忆时间线 * 修改记忆时间线 * 修改记忆时间线 * Parameterize elementId in Cypher query --------- Co-authored-by: Ke Sun <33739460+keeees@users.noreply.github.com> --- .../controllers/user_memory_controllers.py | 1 + api/app/repositories/neo4j/cypher_queries.py | 109 +++++++-- .../memory_entity_relationship_service.py | 227 ++++++++++++++++-- api/app/services/user_memory_service.py | 12 +- 4 files changed, 307 insertions(+), 42 deletions(-) diff --git a/api/app/controllers/user_memory_controllers.py b/api/app/controllers/user_memory_controllers.py index 2f7667c1..32e0e239 100644 --- a/api/app/controllers/user_memory_controllers.py +++ b/api/app/controllers/user_memory_controllers.py @@ -393,6 +393,7 @@ async def update_end_user_profile( db.rollback() api_logger.error(f"用户信息更新失败: end_user_id={end_user_id}, error={str(e)}") return fail(BizCode.INTERNAL_ERROR, "用户信息更新失败", str(e)) + @router.get("/memory_space/timeline_memories", response_model=ApiResponse) async def memory_space_timeline_of_shared_memories(id: str, label: str, current_user: User = Depends(get_current_user), diff --git a/api/app/repositories/neo4j/cypher_queries.py b/api/app/repositories/neo4j/cypher_queries.py index 127ee78c..3bbd6b01 100644 --- a/api/app/repositories/neo4j/cypher_queries.py +++ b/api/app/repositories/neo4j/cypher_queries.py @@ -865,46 +865,113 @@ neo4j_query_all = """ '''针对当前节点下扩长的句子,实体和总结''' Memory_Timeline_ExtractedEntity=""" MATCH (n)-[r1]-(e)-[r2]-(ms) -WHERE elementId(n) =$id -AND (ms:ExtractedEntity OR ms:MemorySummary) +WHERE elementId(n) = $id + AND (ms:ExtractedEntity OR ms:MemorySummary) + RETURN - collect(DISTINCT coalesce(ms.name, n.name, e.name)) AS ExtractedEntity, - collect(DISTINCT ms.content) AS MemorySummary, - collect(DISTINCT e.statement) AS statement; + collect( + DISTINCT + CASE + WHEN ms:ExtractedEntity THEN { + text: ms.name, + created_at: ms.created_at, + type: "情景记忆" + } + END + ) AS ExtractedEntity, + + collect( + DISTINCT + CASE + WHEN ms:MemorySummary THEN { + text: ms.content, + created_at: ms.created_at, + type: "长期沉淀" + } + END + ) AS MemorySummary, + + collect( + DISTINCT { + text: e.statement, + created_at: e.created_at, + type: "情绪记忆" + } + ) AS statement; + + """ Memory_Timeline_MemorySummary=""" MATCH (n)-[r1]-(e)-[r2]-(ms) -WHERE elementId(n) = $id +WHERE elementId(n) =$id AND (ms:MemorySummary OR ms:ExtractedEntity) RETURN - collect(DISTINCT coalesce(ms.name, n.name, e.name)) AS ExtractedEntity, - collect(DISTINCT ms.content) AS MemorySummary, - collect(DISTINCT e.statement) AS statement;""" + collect( + DISTINCT + CASE + WHEN ms:ExtractedEntity THEN { + text: ms.name, + created_at: ms.created_at + } + END + ) AS ExtractedEntity, + + collect( + DISTINCT + CASE + WHEN n:MemorySummary THEN { + text: n.content, + created_at: n.created_at + } + END + ) AS MemorySummary, + + collect( + DISTINCT { + text: e.statement, + created_at: e.created_at + } + ) AS statement; +""" Memory_Timeline_Statement=""" MATCH (n) -WHERE elementId(n) = "4:f6039a9b-d553-4ba2-9b1c-d9a18917801f:77154" +WHERE elementId(n) = "4:f6039a9b-d553-4ba2-9b1c-d9a18917801f:77003" CALL { WITH n - MATCH (n)-[]-(m) - WHERE m:ExtractedEntity - AND NOT m:MemorySummary - AND NOT m:Chunk - RETURN collect(DISTINCT m.name) AS ExtractedEntity + MATCH (n)-[]-(m:ExtractedEntity) + WHERE NOT m:MemorySummary AND NOT m:Chunk + RETURN collect( + DISTINCT { + text: m.name, + created_at: m.created_at, + type: "情景记忆" + } + ) AS ExtractedEntity } CALL { WITH n - MATCH (n)-[]-(m) - WHERE m:MemorySummary - AND NOT m:Chunk - RETURN collect(DISTINCT m.content) AS MemorySummary + MATCH (n)-[]-(m:MemorySummary) + WHERE NOT m:Chunk + RETURN collect( + DISTINCT { + text: m.content, + created_at: m.created_at, + type: "长期沉淀" + } + ) AS MemorySummary } RETURN ExtractedEntity, MemorySummary, - collect(DISTINCT n.statement) AS Statement; + { + text: n.statement, + created_at: n.created_at, + type: "情绪记忆" + } AS statement; + """ @@ -978,4 +1045,4 @@ RETURN DISTINCT e.name AS name, e.importance_score AS importance_score; -""" \ No newline at end of file +""" diff --git a/api/app/services/memory_entity_relationship_service.py b/api/app/services/memory_entity_relationship_service.py index 9f0f6032..cdaa9ef7 100644 --- a/api/app/services/memory_entity_relationship_service.py +++ b/api/app/services/memory_entity_relationship_service.py @@ -24,9 +24,6 @@ class MemoryEntityService: self.id = id self.table = table self.connector = Neo4jConnector() - - - async def get_timeline_memories_server(self): """ 获取时间线记忆数据 @@ -135,13 +132,14 @@ class MemoryEntityService: processed_entity = self._process_field_value(extracted_entity, "ExtractedEntity") extracted_entity_list.extend(processed_entity) - # 去重 - memory_summary_list = list(set(memory_summary_list)) - statement_list = list(set(statement_list)) - extracted_entity_list = list(set(extracted_entity_list)) + # 去重 - 现在处理的是字典列表,需要更智能的去重 + memory_summary_list = self._deduplicate_dict_list(memory_summary_list) + statement_list = self._deduplicate_dict_list(statement_list) + extracted_entity_list = self._deduplicate_dict_list(extracted_entity_list) - # 合并所有数据 + # 合并所有数据并处理相同text的合并 all_timeline_data = memory_summary_list + statement_list + extracted_entity_list + all_timeline_data = self._merge_same_text_items(all_timeline_data) result = { "MemorySummary": memory_summary_list, @@ -154,7 +152,101 @@ class MemoryEntityService: return result - def _process_field_value(self, value: Any, field_name: str) -> List[str]: + def _deduplicate_dict_list(self, dict_list: List[Dict[str, Any]]) -> List[Dict[str, Any]]: + """ + 对字典列表进行去重 + + Args: + dict_list: 字典列表 + + Returns: + 去重后的字典列表 + """ + seen = set() + result = [] + + for item in dict_list: + # 使用text作为去重的键 + text = item.get('text', '') + if text and text not in seen: + seen.add(text) + result.append(item) + + return result + + def _merge_same_text_items(self, items: List[Dict[str, Any]]) -> List[Dict[str, Any]]: + """ + 合并具有相同text的项目,合并type字段,保留一个时间 + + Args: + items: 项目列表 + + Returns: + 合并后的项目列表 + """ + text_groups = {} + + # 按text分组 + for item in items: + text = item.get('text', '') + if not text: + continue + + if text not in text_groups: + text_groups[text] = { + 'text': text, + 'types': set(), + 'created_at': item.get('created_at'), + 'latest_time': item.get('created_at') + } + + # 添加type到集合中 + item_type = item.get('type') + if item_type: + text_groups[text]['types'].add(item_type) + + # 保留最新的时间(如果有的话) + current_time = item.get('created_at') + if current_time and (not text_groups[text]['latest_time'] or + self._is_later_time(current_time, text_groups[text]['latest_time'])): + text_groups[text]['latest_time'] = current_time + + # 转换为最终格式 + result = [] + for text, group_data in text_groups.items(): + merged_item = { + 'text': text, + 'type': ', '.join(sorted(group_data['types'])), # 合并多个type + 'created_at': group_data['latest_time'] + } + result.append(merged_item) + + # 按时间排序(最新的在前) + result.sort(key=lambda x: x.get('created_at', ''), reverse=True) + + return result + + def _is_later_time(self, time1: str, time2: str) -> bool: + """ + 比较两个时间字符串,判断time1是否晚于time2 + + Args: + time1: 时间字符串1 + time2: 时间字符串2 + + Returns: + time1是否晚于time2 + """ + try: + if not time1 or not time2: + return bool(time1) # 如果time2为空,time1存在就算更晚 + + # 简单的字符串比较(适用于ISO格式的时间) + return time1 > time2 + except Exception: + return False + + def _process_field_value(self, value: Any, field_name: str) -> List[Dict[str, Any]]: """ 处理字段值,支持字符串、列表等类型 @@ -163,30 +255,133 @@ class MemoryEntityService: field_name: 字段名称(用于日志) Returns: - 处理后的字符串列表 + 处理后的字典列表 """ processed_values = [] - + try: if isinstance(value, list): # 如果是列表,处理每个元素 for item in value: - if item is not None and str(item).strip() != '' and "MemorySummaryChunk" not in str(item): - processed_values.append(str(item)) + if self._is_valid_item(item): + processed_item = self._process_single_item(item) + if processed_item: + processed_values.append(processed_item) + elif isinstance(value, dict): + # 如果是字典,直接处理 + if self._is_valid_item(value): + processed_item = self._process_single_item(value) + if processed_item: + processed_values.append(processed_item) elif isinstance(value, str): - # 如果是字符串,直接处理 + # 如果是字符串,转换为字典格式 if value.strip() != '' and "MemorySummaryChunk" not in value: - processed_values.append(value) + processed_values.append({ + 'text': value, + 'type': field_name, + 'created_at': None + }) elif value is not None: # 其他类型转换为字符串 str_value = str(value) if str_value.strip() != '' and "MemorySummaryChunk" not in str_value: - processed_values.append(str_value) + processed_values.append({ + 'text': str_value, + 'type': field_name, + 'created_at': None + }) except Exception as e: logger.warning(f"处理字段 {field_name} 的值时出错: {e}, 值类型: {type(value)}, 值: {value}") return processed_values + def _is_valid_item(self, item: Any) -> bool: + """ + 检查项目是否有效 + + Args: + item: 要检查的项目 + + Returns: + 是否有效 + """ + if item is None: + return False + + if isinstance(item, dict): + text = item.get('text') + return (text is not None and + str(text).strip() != '' and + "MemorySummaryChunk" not in str(text)) + + return (str(item).strip() != '' and + "MemorySummaryChunk" not in str(item)) + + def _process_single_item(self, item: Dict[str, Any]) -> Optional[Dict[str, Any]]: + """ + 处理单个项目 + + Args: + item: 要处理的项目字典 + + Returns: + 处理后的项目字典 + """ + try: + text = item.get('text') + created_at = item.get('created_at') + item_type = item.get('type', '未知类型') + + # 转换Neo4j时间格式 + formatted_time = self._convert_neo4j_datetime(created_at) + + return { + 'text': text, + 'type': item_type, + 'created_at': formatted_time + } + except Exception as e: + logger.warning(f"处理单个项目时出错: {e}, 项目: {item}") + return None + + def _convert_neo4j_datetime(self, dt: Any) -> str: + """ + 转换Neo4j时间格式为标准时间字符串 + + Args: + dt: Neo4j时间对象或其他时间格式 + + Returns: + 格式化的时间字符串 + """ + if dt is None: + return None + + try: + # 处理Neo4j DateTime对象 + if isinstance(dt, Neo4jDateTime): + return dt.iso_format().replace('T', ' ').split('.')[0] + + # 处理其他neo4j时间类型 + if hasattr(dt, 'iso_format'): + return dt.iso_format().replace('T', ' ').split('.')[0] + + # 处理字符串格式的时间 + if isinstance(dt, str): + # 尝试解析ISO格式 + try: + parsed_dt = datetime.fromisoformat(dt.replace('Z', '+00:00')) + return parsed_dt.strftime("%Y-%m-%d %H:%M:%S") + except ValueError: + return dt + + # 其他情况直接转换为字符串 + return str(dt) + + except Exception as e: + logger.warning(f"转换时间格式失败: {e}, 原始值: {dt}") + return str(dt) if dt is not None else None + diff --git a/api/app/services/user_memory_service.py b/api/app/services/user_memory_service.py index a17e21f0..c8b4d98d 100644 --- a/api/app/services/user_memory_service.py +++ b/api/app/services/user_memory_service.py @@ -1394,7 +1394,7 @@ async def analytics_graph_data( "group_id": end_user_id, "limit": limit } - + # 执行节点查询 node_results = await _neo4j_connector.execute_query(node_query, **node_params) @@ -1409,7 +1409,7 @@ async def analytics_graph_data( node_props = record["properties"] # 根据节点类型提取需要的属性字段 - filtered_props = _extract_node_properties(node_label, node_props) + filtered_props = await _extract_node_properties(node_label, node_props,node_id) # 直接使用数据库中的 caption,如果没有则使用节点类型作为默认值 caption = filtered_props.get("caption", node_label) @@ -1515,7 +1515,7 @@ async def analytics_graph_data( # 辅助函数 -def _extract_node_properties(label: str, properties: Dict[str, Any]) -> Dict[str, Any]: +async def _extract_node_properties(label: str, properties: Dict[str, Any],node_id: str) -> Dict[str, Any]: """ 根据节点类型提取需要的属性字段 @@ -1542,7 +1542,8 @@ def _extract_node_properties(label: str, properties: Dict[str, Any]) -> Dict[str if not allowed_fields: # 对于未定义的节点类型,只返回基本字段 allowed_fields = ["name", "created_at", "caption"] - + count_neo4j=f"""MATCH (n)-[r]-(m) WHERE elementId(n) ="{node_id}" RETURN count(r) AS rel_count;""" + node_results = await (_neo4j_connector.execute_query(count_neo4j)) # 提取白名单中的字段 filtered_props = {} for field in allowed_fields: @@ -1550,7 +1551,8 @@ def _extract_node_properties(label: str, properties: Dict[str, Any]) -> Dict[str value = properties[field] # 清理 Neo4j 特殊类型 filtered_props[field] = _clean_neo4j_value(value) - + filtered_props['associative_memory']=[i['rel_count'] for i in node_results][0] + print(filtered_props) return filtered_props From 539821454a52e4c1f82940e4dd95b38b2e99d122 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=B9=90=E5=8A=9B=E9=BD=90?= <162269739+lanceyq@users.noreply.github.com> Date: Sat, 10 Jan 2026 16:35:32 +0800 Subject: [PATCH 63/75] Feature/episodic memory (#64) * [feature]episodic memory * [feature]episodic memory * [changes]AI review and modify code --- .../controllers/user_memory_controllers.py | 108 ++++ api/app/core/memory/models/graph_models.py | 3 + .../knowledge_extraction/memory_summary.py | 18 +- .../forgetting_engine/forgetting_strategy.py | 23 +- .../core/memory/utils/prompt/prompt_utils.py | 23 + .../episodic_type_classification.jinja2 | 57 ++ api/app/repositories/neo4j/add_nodes.py | 1 + api/app/repositories/neo4j/cypher_queries.py | 1 + api/app/schemas/user_memory_schema.py | 30 + api/app/services/user_memory_service.py | 570 +++++++++++++++++- 10 files changed, 825 insertions(+), 9 deletions(-) create mode 100644 api/app/core/memory/utils/prompt/prompts/episodic_type_classification.jinja2 create mode 100644 api/app/schemas/user_memory_schema.py diff --git a/api/app/controllers/user_memory_controllers.py b/api/app/controllers/user_memory_controllers.py index 32e0e239..a5378e4d 100644 --- a/api/app/controllers/user_memory_controllers.py +++ b/api/app/controllers/user_memory_controllers.py @@ -20,6 +20,11 @@ from app.services.user_memory_service import ( from app.services.memory_entity_relationship_service import MemoryEntityService,MemoryEmotion,MemoryInteraction from app.schemas.response_schema import ApiResponse from app.schemas.memory_storage_schema import GenerateCacheRequest +from app.schemas.user_memory_schema import ( + EpisodicMemoryOverviewRequest, + EpisodicMemoryDetailsRequest, +) + from app.schemas.end_user_schema import ( EndUserProfileResponse, EndUserProfileUpdate, @@ -433,3 +438,106 @@ async def memory_space_relationship_evolution(id: str, label: str, except Exception as e: api_logger.error(f"关系演变查询失败: id={id}, table={label}, error={str(e)}", exc_info=True) return fail(BizCode.INTERNAL_ERROR, "关系演变查询失败", str(e)) + + +@router.post("/classifications/episodic-memory", response_model=ApiResponse) +async def get_episodic_memory_overview_api( + request: EpisodicMemoryOverviewRequest, + current_user: User = Depends(get_current_user), + db: Session = Depends(get_db), +) -> dict: + """ + 获取情景记忆总览 + + 返回指定用户的所有情景记忆列表,包括标题和创建时间。 + 标题通过LLM自动生成。 + 支持通过时间范围、情景类型和标题关键词进行筛选。 + + """ + workspace_id = current_user.current_workspace_id + + # 检查用户是否已选择工作空间 + if workspace_id is None: + api_logger.warning(f"用户 {current_user.username} 尝试查询情景记忆总览但未选择工作空间") + return fail(BizCode.INVALID_PARAMETER, "请先切换到一个工作空间", "current_workspace_id is None") + + # 验证参数 + valid_time_ranges = ["all", "today", "this_week", "this_month"] + valid_episodic_types = ["all", "conversation", "project_work", "learning", "decision", "important_event"] + + if request.time_range not in valid_time_ranges: + return fail(BizCode.INVALID_PARAMETER, f"无效的时间范围参数,可选值:{', '.join(valid_time_ranges)}") + + if request.episodic_type not in valid_episodic_types: + return fail(BizCode.INVALID_PARAMETER, f"无效的情景类型参数,可选值:{', '.join(valid_episodic_types)}") + + # 处理 title_keyword(去除首尾空格) + title_keyword = request.title_keyword.strip() if request.title_keyword else None + + api_logger.info( + f"情景记忆总览查询请求: end_user_id={request.end_user_id}, user={current_user.username}, " + f"workspace={workspace_id}, time_range={request.time_range}, episodic_type={request.episodic_type}, " + f"title_keyword={title_keyword}" + ) + + try: + # 调用Service层方法 + result = await user_memory_service.get_episodic_memory_overview( + db, request.end_user_id, request.time_range, request.episodic_type, title_keyword + ) + + api_logger.info( + f"成功获取情景记忆总览: end_user_id={request.end_user_id}, " + f"total={result['total']}" + ) + return success(data=result, msg="查询成功") + + except Exception as e: + api_logger.error(f"情景记忆总览查询失败: end_user_id={request.end_user_id}, error={str(e)}") + return fail(BizCode.INTERNAL_ERROR, "情景记忆总览查询失败", str(e)) + + +@router.post("/classifications/episodic-memory-details", response_model=ApiResponse) +async def get_episodic_memory_details_api( + request: EpisodicMemoryDetailsRequest, + current_user: User = Depends(get_current_user), + db: Session = Depends(get_db), +) -> dict: + """ + 获取情景记忆详情 + + 返回指定情景记忆的详细信息,包括涉及对象、情景类型、内容记录和情绪。 + + """ + workspace_id = current_user.current_workspace_id + + # 检查用户是否已选择工作空间 + if workspace_id is None: + api_logger.warning(f"用户 {current_user.username} 尝试查询情景记忆详情但未选择工作空间") + return fail(BizCode.INVALID_PARAMETER, "请先切换到一个工作空间", "current_workspace_id is None") + + api_logger.info( + f"情景记忆详情查询请求: end_user_id={request.end_user_id}, summary_id={request.summary_id}, " + f"user={current_user.username}, workspace={workspace_id}" + ) + + try: + # 调用Service层方法 + result = await user_memory_service.get_episodic_memory_details( + db=db, + end_user_id=request.end_user_id, + summary_id=request.summary_id + ) + + api_logger.info( + f"成功获取情景记忆详情: end_user_id={request.end_user_id}, summary_id={request.summary_id}" + ) + return success(data=result, msg="查询成功") + + except ValueError as e: + # 处理情景记忆不存在的情况 + api_logger.warning(f"情景记忆不存在: end_user_id={request.end_user_id}, summary_id={request.summary_id}, error={str(e)}") + return fail(BizCode.INVALID_PARAMETER, "情景记忆不存在", str(e)) + except Exception as e: + api_logger.error(f"情景记忆详情查询失败: end_user_id={request.end_user_id}, summary_id={request.summary_id}, error={str(e)}") + return fail(BizCode.INTERNAL_ERROR, "情景记忆详情查询失败", str(e)) diff --git a/api/app/core/memory/models/graph_models.py b/api/app/core/memory/models/graph_models.py index 6ec1ca8e..1254388b 100644 --- a/api/app/core/memory/models/graph_models.py +++ b/api/app/core/memory/models/graph_models.py @@ -474,6 +474,8 @@ class MemorySummaryNode(Node): dialog_id: ID of the parent dialog chunk_ids: List of chunk IDs used to generate this summary content: Summary text content + name: Title/name of the memory summary (generated by LLM, used as title in API) + memory_type: Type/category of the episodic memory (e.g., Conversation, Project/Work, Learning, Decision, Important Event) summary_embedding: Optional embedding vector for the summary metadata: Additional metadata for the summary config_id: Configuration ID used to process this summary @@ -492,6 +494,7 @@ class MemorySummaryNode(Node): dialog_id: str = Field(..., description="ID of the parent dialog") chunk_ids: List[str] = Field(default_factory=list, description="List of chunk IDs used in the summary") content: str = Field(..., description="Summary text content") + memory_type: Optional[str] = Field(None, description="Type/category of the episodic memory") summary_embedding: Optional[List[float]] = Field(None, description="Embedding vector for the summary") metadata: dict = Field(default_factory=dict, description="Additional metadata for the summary") config_id: Optional[int | str] = Field(None, description="Configuration ID used to process this summary (integer or string)") diff --git a/api/app/core/memory/storage_services/extraction_engine/knowledge_extraction/memory_summary.py b/api/app/core/memory/storage_services/extraction_engine/knowledge_extraction/memory_summary.py index 70c1ceb3..c72b9a1f 100644 --- a/api/app/core/memory/storage_services/extraction_engine/knowledge_extraction/memory_summary.py +++ b/api/app/core/memory/storage_services/extraction_engine/knowledge_extraction/memory_summary.py @@ -59,13 +59,28 @@ async def _process_chunk_summary( ) summary_text = structured.summary.strip() + # Generate title and type for the summary + title = None + episodic_type = None + try: + from app.services.user_memory_service import UserMemoryService + title, episodic_type = await UserMemoryService.generate_title_and_type_for_summary( + content=summary_text, + end_user_id=dialog.group_id + ) + logger.info(f"Generated title and type for MemorySummary: title={title}, type={episodic_type}") + except Exception as e: + logger.warning(f"Failed to generate title and type for chunk {chunk.id}: {e}") + # Continue without title and type + # Embed the summary embedding = (await embedder.response([summary_text]))[0] # Build node per chunk + # Note: title is stored in the 'name' field, type is stored in 'memory_type' field node = MemorySummaryNode( id=uuid4().hex, - name=f"MemorySummaryChunk_{chunk.id}", + name=title if title else f"MemorySummaryChunk_{chunk.id}", group_id=dialog.group_id, user_id=dialog.user_id, apply_id=dialog.apply_id, @@ -75,6 +90,7 @@ async def _process_chunk_summary( dialog_id=dialog.id, chunk_ids=[chunk.id], content=summary_text, + memory_type=episodic_type, summary_embedding=embedding, metadata={"ref_id": dialog.ref_id}, config_id=dialog.config_id, # 添加 config_id diff --git a/api/app/core/memory/storage_services/forgetting_engine/forgetting_strategy.py b/api/app/core/memory/storage_services/forgetting_engine/forgetting_strategy.py index 5e1e35da..f1802166 100644 --- a/api/app/core/memory/storage_services/forgetting_engine/forgetting_strategy.py +++ b/api/app/core/memory/storage_services/forgetting_engine/forgetting_strategy.py @@ -247,6 +247,9 @@ class ForgettingStrategy: entity_activation = entity_node['entity_activation'] entity_importance = entity_node['entity_importance'] + # 获取 group_id(从 statement 或 entity 节点) + group_id = statement_node.get('group_id') or entity_node.get('group_id') + # 生成摘要内容 summary_text = await self._generate_summary( statement_text=statement_text, @@ -256,6 +259,19 @@ class ForgettingStrategy: db=db ) + # 生成标题和类型(使用LLM) + from app.services.user_memory_service import UserMemoryService + try: + title, episodic_type = await UserMemoryService.generate_title_and_type_for_summary( + content=summary_text, + end_user_id=group_id + ) + logger.info(f"成功为MemorySummary生成标题和类型: title={title}, type={episodic_type}") + except Exception as e: + logger.error(f"生成标题和类型失败,使用默认值: {str(e)}") + title = "未命名" + episodic_type = "其他" + # 计算继承的激活值和重要性(取较高值) inherited_activation = max(statement_activation, entity_activation) inherited_importance = max(statement_importance, entity_importance) @@ -268,9 +284,6 @@ class ForgettingStrategy: import uuid summary_id = f"summary_{uuid.uuid4().hex[:16]}" - # 获取 group_id(从 statement 或 entity 节点) - group_id = statement_node.get('group_id') or entity_node.get('group_id') - # 使用事务创建 MemorySummary 并删除原节点 async def merge_transaction(tx, **params): """事务函数:创建摘要节点并删除原节点""" @@ -287,6 +300,8 @@ class ForgettingStrategy: CREATE (ms:MemorySummary { id: $summary_id, summary: $summary_text, + name: $title, + memory_type: $episodic_type, original_statement_id: $statement_id, original_entity_id: $entity_id, activation_value: $inherited_activation, @@ -386,6 +401,8 @@ class ForgettingStrategy: params = { 'summary_id': summary_id, 'summary_text': summary_text, + 'title': title, + 'episodic_type': episodic_type, 'statement_id': statement_id, 'entity_id': entity_id, 'inherited_activation': inherited_activation, diff --git a/api/app/core/memory/utils/prompt/prompt_utils.py b/api/app/core/memory/utils/prompt/prompt_utils.py index 842f3c82..50593e49 100644 --- a/api/app/core/memory/utils/prompt/prompt_utils.py +++ b/api/app/core/memory/utils/prompt/prompt_utils.py @@ -386,3 +386,26 @@ async def render_memory_insight_prompt( }) return rendered_prompt + + +async def render_episodic_title_and_type_prompt(content: str) -> str: + """ + Renders the episodic title and type classification prompt using the episodic_type_classification.jinja2 template. + + Args: + content: The content of the episodic memory summary to analyze + + Returns: + Rendered prompt content as string + """ + template = prompt_env.get_template("episodic_type_classification.jinja2") + rendered_prompt = template.render(content=content) + + # 记录渲染结果到提示日志 + log_prompt_rendering('episodic title and type classification', rendered_prompt) + # 可选:记录模板渲染信息 + log_template_rendering('episodic_type_classification.jinja2', { + 'content_len': len(content) if content else 0 + }) + + return rendered_prompt diff --git a/api/app/core/memory/utils/prompt/prompts/episodic_type_classification.jinja2 b/api/app/core/memory/utils/prompt/prompts/episodic_type_classification.jinja2 new file mode 100644 index 00000000..fa382ec7 --- /dev/null +++ b/api/app/core/memory/utils/prompt/prompts/episodic_type_classification.jinja2 @@ -0,0 +1,57 @@ +=== Task === +Generate a concise title and classify the episodic memory into the most appropriate category. + +=== Requirements === +- Extract a clear, concise title (10-20 characters) that captures the core content +- Classify into exactly one category based on the primary theme +- Be specific and avoid ambiguity +- Output must be valid JSON conforming to the schema below + +=== Input === +{{ content }} + +=== Category Definitions === + +1. **conversation**: Daily communication, chat, discussion, and social interactions + - Keywords: chat, communication, discussion, dialogue, exchange + +2. **project_work**: Work-related tasks, projects, meetings, and collaboration + - Keywords: project, task, work, meeting, collaboration, business, client + +3. **learning**: Acquiring new knowledge, skill development, reading, and research + - Keywords: learning, reading, research, knowledge, skill, course, training + +4. **decision**: Making important decisions, choices, and planning + - Keywords: decision, choice, planning, consideration, evaluation, weighing + +5. **important_event**: Major events, milestones, and special experiences + - Keywords: important, major, milestone, special, memorable, celebration + +=== Analysis Steps === +1. Read the episodic memory content carefully +2. Identify the core theme and context +3. Extract a concise title +4. Compare against category definitions and keywords +5. Select the best matching category +6. If multiple categories apply, choose the primary one + +=== Output Schema === +**CRITICAL JSON FORMATTING REQUIREMENTS:** +1. Use only standard ASCII double quotes (") for JSON structure +2. Escape any quotation marks within string values using backslashes (\") +3. Ensure all JSON strings are properly closed and comma-separated +4. Do not include line breaks within JSON string values + +Return only a JSON object with title and type fields: +{ + "title": "Generated title here", + "type": "Category type here" +} + +The type field must be exactly one of: +- conversation +- project_work +- learning +- decision +- important_event + diff --git a/api/app/repositories/neo4j/add_nodes.py b/api/app/repositories/neo4j/add_nodes.py index 79466fa0..1e24eeae 100644 --- a/api/app/repositories/neo4j/add_nodes.py +++ b/api/app/repositories/neo4j/add_nodes.py @@ -211,6 +211,7 @@ async def add_memory_summary_nodes(summaries: List[MemorySummaryNode], connector "dialog_id": s.dialog_id, "chunk_ids": s.chunk_ids, "content": s.content, + "memory_type": s.memory_type, # 添加 memory_type 字段 "summary_embedding": s.summary_embedding if s.summary_embedding else None, "config_id": s.config_id, # 添加 config_id }) diff --git a/api/app/repositories/neo4j/cypher_queries.py b/api/app/repositories/neo4j/cypher_queries.py index 3bbd6b01..8c86cc4d 100644 --- a/api/app/repositories/neo4j/cypher_queries.py +++ b/api/app/repositories/neo4j/cypher_queries.py @@ -721,6 +721,7 @@ SET m += { dialog_id: summary.dialog_id, chunk_ids: summary.chunk_ids, content: summary.content, + memory_type: summary.memory_type, summary_embedding: summary.summary_embedding, config_id: summary.config_id, importance_score: CASE WHEN summary.importance_score IS NOT NULL THEN summary.importance_score ELSE coalesce(m.importance_score, 0.5) END, diff --git a/api/app/schemas/user_memory_schema.py b/api/app/schemas/user_memory_schema.py new file mode 100644 index 00000000..27a458b6 --- /dev/null +++ b/api/app/schemas/user_memory_schema.py @@ -0,0 +1,30 @@ +""" +用户记忆相关的请求和响应模型 +""" +from pydantic import BaseModel, Field +from typing import Optional + + +class EpisodicMemoryOverviewRequest(BaseModel): + """情景记忆总览查询请求""" + + end_user_id: str = Field(..., description="终端用户ID") + time_range: str = Field( + default="all", + description="时间范围筛选,可选值:all, today, this_week, this_month" + ) + episodic_type: str = Field( + default="all", + description="情景类型筛选,可选值:all, conversation, project_work, learning, decision, important_event" + ) + title_keyword: Optional[str] = Field( + default=None, + description="标题关键词,用于模糊搜索(可选)" + ) + + +class EpisodicMemoryDetailsRequest(BaseModel): + """情景记忆详情查询请求""" + + end_user_id: str = Field(..., description="终端用户ID") + summary_id: str = Field(..., description="情景记忆摘要ID") diff --git a/api/app/services/user_memory_service.py b/api/app/services/user_memory_service.py index c8b4d98d..3f0da196 100644 --- a/api/app/services/user_memory_service.py +++ b/api/app/services/user_memory_service.py @@ -315,16 +315,12 @@ class UserSummaryHelper: # ============================================================================ -# ============================================================================ -# Service Class -# ============================================================================ - - class UserMemoryService: """用户记忆服务类""" def __init__(self): logger.info("UserMemoryService initialized") + self.neo4j_connector = Neo4jConnector() @staticmethod def _datetime_to_timestamp(dt: Optional[Any]) -> Optional[int]: @@ -887,6 +883,570 @@ class UserMemoryService: "failed": failed, "errors": errors + [{"error": f"批量处理失败: {str(e)}"}] } + + async def _get_title_and_type( + self, + summary_id: str, + end_user_id: str + ) -> Tuple[str, str]: + """ + 读取情景记忆的标题(title)和类型(type) + + 仅负责读取已存在的title和type,不进行生成 + title从name属性读取,type从memory_type属性读取 + + Args: + summary_id: Summary节点的ID + end_user_id: 终端用户ID (group_id) + + Returns: + (标题, 类型)元组,如果不存在则返回默认值 + """ + try: + # 查询Summary节点的name(作为title)和memory_type(作为type) + query = """ + MATCH (s:MemorySummary) + WHERE elementId(s) = $summary_id AND s.group_id = $group_id + RETURN s.name AS title, s.memory_type AS type + """ + + result = await self.neo4j_connector.execute_query( + query, + summary_id=summary_id, + group_id=end_user_id + ) + + if not result or len(result) == 0: + logger.warning(f"未找到 summary_id={summary_id} 的节点") + return ("未知标题", "其他") + + record = result[0] + title = record.get("title") or "未命名" + episodic_type = record.get("type") or "其他" + + return (title, episodic_type) + + except Exception as e: + logger.error(f"读取标题和类型时出错: {str(e)}", exc_info=True) + return ("错误", "其他") + + @staticmethod + async def generate_title_and_type_for_summary( + content: str, + end_user_id: str + ) -> Tuple[str, str]: + """ + 为MemorySummary生成标题和类型(静态方法,用于创建节点时调用) + + 此方法应该在创建MemorySummary节点时调用,生成title和type + + Args: + content: Summary的内容文本 + end_user_id: 终端用户ID (group_id) + + Returns: + (标题, 类型)元组 + """ + from app.core.memory.utils.prompt.prompt_utils import render_episodic_title_and_type_prompt + import json + + # 定义有效的类型集合 + VALID_TYPES = { + "conversation", # 对话 + "project_work", # 项目/工作 + "learning", # 学习 + "decision", # 决策 + "important_event" # 重要事件 + } + DEFAULT_TYPE = "conversation" # 默认类型 + + try: + if not content: + logger.warning("content为空,无法生成标题和类型") + return ("空内容", DEFAULT_TYPE) + + # 1. 渲染Jinja2提示词模板 + prompt = await render_episodic_title_and_type_prompt(content) + + # 2. 调用LLM生成标题和类型 + llm_client = _get_llm_client_for_user(end_user_id) + messages = [ + {"role": "user", "content": prompt} + ] + + response = await llm_client.chat(messages=messages) + + # 3. 解析LLM响应 + content_response = response.content + if isinstance(content_response, list): + if len(content_response) > 0: + if isinstance(content_response[0], dict): + text = content_response[0].get('text', content_response[0].get('content', str(content_response[0]))) + full_response = str(text) + else: + full_response = str(content_response[0]) + else: + full_response = "" + elif isinstance(content_response, dict): + full_response = str(content_response.get('text', content_response.get('content', str(content_response)))) + else: + full_response = str(content_response) if content_response is not None else "" + + # 4. 解析JSON响应 + try: + # 尝试从响应中提取JSON + # 移除可能的markdown代码块标记 + json_str = full_response.strip() + if json_str.startswith("```json"): + json_str = json_str[7:] + if json_str.startswith("```"): + json_str = json_str[3:] + if json_str.endswith("```"): + json_str = json_str[:-3] + json_str = json_str.strip() + + result_data = json.loads(json_str) + title = result_data.get("title", "未知标题") + episodic_type_raw = result_data.get("type", DEFAULT_TYPE) + + # 5. 校验和归一化类型 + # 将类型转换为小写并去除空格 + episodic_type_normalized = str(episodic_type_raw).lower().strip() + + # 检查是否在有效类型集合中 + if episodic_type_normalized in VALID_TYPES: + episodic_type = episodic_type_normalized + else: + # 尝试映射常见的中文类型到英文 + type_mapping = { + "对话": "conversation", + "项目": "project_work", + "工作": "project_work", + "项目/工作": "project_work", + "学习": "learning", + "决策": "decision", + "重要事件": "important_event", + "事件": "important_event" + } + episodic_type = type_mapping.get(episodic_type_raw, DEFAULT_TYPE) + logger.warning( + f"LLM返回的类型 '{episodic_type_raw}' 不在有效集合中," + f"已归一化为 '{episodic_type}'" + ) + + logger.info(f"成功生成标题和类型: title={title}, type={episodic_type}") + return (title, episodic_type) + + except json.JSONDecodeError: + logger.error(f"无法解析LLM响应为JSON: {full_response}") + return ("解析失败", DEFAULT_TYPE) + + except Exception as e: + logger.error(f"生成标题和类型时出错: {str(e)}", exc_info=True) + return ("错误", DEFAULT_TYPE) + + async def _extract_involved_objects( + self, + summary_id: str, + end_user_id: str + ) -> List[str]: + """ + 提取情景记忆涉及的前3个最重要实体 + + Args: + summary_id: Summary节点的ID + end_user_id: 终端用户ID (group_id) + + Returns: + 前3个实体的name属性列表 + """ + try: + # 查询Summary节点指向的Statement节点,再查询Statement指向的ExtractedEntity节点 + # 按activation_value降序排序,返回前3个 + query = """ + MATCH (s:MemorySummary) + WHERE elementId(s) = $summary_id AND s.group_id = $group_id + MATCH (s)-[:DERIVED_FROM_STATEMENT]->(stmt:Statement) + MATCH (stmt)-[:REFERENCES_ENTITY]->(entity:ExtractedEntity) + WHERE entity.activation_value IS NOT NULL + RETURN DISTINCT entity.name AS name, entity.activation_value AS activation + ORDER BY activation DESC + LIMIT 3 + """ + + result = await self.neo4j_connector.execute_query( + query, + summary_id=summary_id, + group_id=end_user_id + ) + + # 提取实体名称 + involved_objects = [record["name"] for record in result if record.get("name")] + + logger.info(f"成功提取 summary_id={summary_id} 的涉及对象: {involved_objects}") + + return involved_objects + + except Exception as e: + logger.error(f"提取涉及对象时出错: {str(e)}", exc_info=True) + return [] + + async def _extract_content_records( + self, + summary_id: str, + end_user_id: str + ) -> List[str]: + """ + 提取情景记忆的内容记录 + + Args: + summary_id: Summary节点的ID + end_user_id: 终端用户ID (group_id) + + Returns: + 所有Statement节点的statement属性内容列表 + """ + try: + # 查询Summary节点指向的所有Statement节点 + query = """ + MATCH (s:MemorySummary) + WHERE elementId(s) = $summary_id AND s.group_id = $group_id + MATCH (s)-[:DERIVED_FROM_STATEMENT]->(stmt:Statement) + WHERE stmt.statement IS NOT NULL AND stmt.statement <> '' + RETURN stmt.statement AS statement + """ + + result = await self.neo4j_connector.execute_query( + query, + summary_id=summary_id, + group_id=end_user_id + ) + + # 提取statement内容 + content_records = [record["statement"] for record in result if record.get("statement")] + + logger.info(f"成功提取 summary_id={summary_id} 的内容记录,共 {len(content_records)} 条") + + return content_records + + except Exception as e: + logger.error(f"提取内容记录时出错: {str(e)}", exc_info=True) + return [] + + async def _extract_episodic_emotion( + self, + summary_id: str, + end_user_id: str + ) -> Optional[str]: + """ + 提取情景记忆的主要情绪 + + Args: + summary_id: Summary节点的ID + end_user_id: 终端用户ID (group_id) + + Returns: + 最大emotion_intensity对应的emotion_type,如果没有则返回None + """ + try: + # 查询Summary节点指向的所有Statement节点 + # 筛选具有emotion_type属性的节点 + # 按emotion_intensity降序排序,返回第一个 + query = """ + MATCH (s:MemorySummary) + WHERE elementId(s) = $summary_id AND s.group_id = $group_id + MATCH (s)-[:DERIVED_FROM_STATEMENT]->(stmt:Statement) + WHERE stmt.emotion_type IS NOT NULL + AND stmt.emotion_intensity IS NOT NULL + RETURN stmt.emotion_type AS emotion_type, + stmt.emotion_intensity AS emotion_intensity + ORDER BY emotion_intensity DESC + LIMIT 1 + """ + + result = await self.neo4j_connector.execute_query( + query, + summary_id=summary_id, + group_id=end_user_id + ) + + # 提取emotion_type + if result and len(result) > 0: + emotion_type = result[0].get("emotion_type") + logger.info(f"成功提取 summary_id={summary_id} 的情绪: {emotion_type}") + return emotion_type + else: + logger.info(f"summary_id={summary_id} 没有情绪信息") + return None + + except Exception as e: + logger.error(f"提取情景记忆情绪时出错: {str(e)}", exc_info=True) + return None + + async def get_episodic_memory_overview( + self, + db: Session, + end_user_id: str, + time_range: str = "all", + episodic_type: str = "all", + title_keyword: Optional[str] = None + ) -> Dict[str, Any]: + """ + 获取情景记忆总览信息 + + Args: + db: 数据库会话 + end_user_id: 终端用户ID + time_range: 时间范围筛选 + episodic_type: 情景类型筛选 + title_keyword: 标题关键词(可选,用于模糊搜索) + """ + try: + logger.info( + f"开始查询 end_user_id={end_user_id} 的情景记忆总览, " + f"time_range={time_range}, episodic_type={episodic_type}, title_keyword={title_keyword}" + ) + + # 1. 先查询所有情景记忆的总数(不受筛选条件限制) + total_all_query = """ + MATCH (s:MemorySummary) + WHERE s.group_id = $group_id + RETURN count(s) AS total_all + """ + total_all_result = await self.neo4j_connector.execute_query( + total_all_query, + group_id=end_user_id + ) + total_all = total_all_result[0]["total_all"] if total_all_result else 0 + + # 2. 计算时间范围的起始时间戳 + time_filter = self._calculate_time_filter(time_range) + + # 3. 构建Cypher查询 + query = """ + MATCH (s:MemorySummary) + WHERE s.group_id = $group_id + """ + + # 添加时间范围过滤 + if time_filter: + query += " AND s.created_at >= $time_filter" + + # 添加标题关键词过滤(如果提供了title_keyword) + if title_keyword: + query += " AND toLower(s.name) CONTAINS toLower($title_keyword)" + + query += """ + RETURN elementId(s) AS id, + s.created_at AS created_at, + s.memory_type AS type, + s.name AS title + ORDER BY s.created_at DESC + """ + + params = {"group_id": end_user_id} + if time_filter: + params["time_filter"] = time_filter + if title_keyword: + params["title_keyword"] = title_keyword + + result = await self.neo4j_connector.execute_query(query, **params) + + # 4. 如果没有数据,返回空列表 + if not result: + logger.info(f"end_user_id={end_user_id} 没有情景记忆数据") + return { + "total": 0, + "total_all": total_all, + "episodic_memories": [] + } + + # 5. 对每个节点读取标题和类型,并应用类型筛选 + episodic_memories = [] + for record in result: + summary_id = record["id"] + created_at_str = record.get("created_at") + memory_type = record.get("type", "其他") + title = record.get("title") or "未命名" # 直接从查询结果获取标题 + + # 应用情景类型筛选 + if episodic_type != "all": + # 检查类型是否匹配 + # 注意:Neo4j 中存储的 memory_type 现在应该是英文格式(如 "conversation", "project_work") + # 但为了兼容旧数据,我们也支持中文格式的匹配 + type_mapping = { + "conversation": "对话", + "project_work": "项目/工作", + "learning": "学习", + "decision": "决策", + "important_event": "重要事件" + } + + # 获取对应的中文类型(用于兼容旧数据) + chinese_type = type_mapping.get(episodic_type) + + # 检查类型是否匹配(支持新的英文格式和旧的中文格式) + if memory_type != episodic_type and memory_type != chinese_type: + continue + + # 转换时间戳 + created_at_timestamp = None + if created_at_str: + try: + from datetime import datetime + dt_object = datetime.fromisoformat(created_at_str.replace("Z", "+00:00")) + created_at_timestamp = int(dt_object.timestamp() * 1000) + except (ValueError, TypeError, AttributeError) as e: + logger.warning(f"无法解析时间戳: {created_at_str}, error={str(e)}") + + episodic_memories.append({ + "id": summary_id, + "title": title, + "type": memory_type, + "created_at": created_at_timestamp + }) + + logger.info( + f"成功获取 end_user_id={end_user_id} 的情景记忆总览," + f"筛选后 {len(episodic_memories)} 条,总共 {total_all} 条" + ) + + return { + "total": len(episodic_memories), + "total_all": total_all, + "episodic_memories": episodic_memories + } + + except Exception as e: + logger.error(f"获取情景记忆总览时出错: {str(e)}", exc_info=True) + raise + + def _calculate_time_filter(self, time_range: str) -> Optional[str]: + """ + 根据时间范围计算过滤的起始时间 + + Args: + time_range: 时间范围 (all/today/this_week/this_month) + + Returns: + ISO格式的时间字符串,如果是"all"则返回None + """ + from datetime import datetime, timedelta + import pytz + + if time_range == "all": + return None + + # 获取当前时间(UTC) + now = datetime.now(pytz.UTC) + + if time_range == "today": + # 今天的开始时间(00:00:00) + start_time = now.replace(hour=0, minute=0, second=0, microsecond=0) + elif time_range == "this_week": + # 本周的开始时间(周一00:00:00) + days_since_monday = now.weekday() + start_time = (now - timedelta(days=days_since_monday)).replace( + hour=0, minute=0, second=0, microsecond=0 + ) + elif time_range == "this_month": + # 本月的开始时间(1号00:00:00) + start_time = now.replace(day=1, hour=0, minute=0, second=0, microsecond=0) + else: + return None + + # 返回ISO格式字符串 + return start_time.isoformat() + + async def get_episodic_memory_details( + self, + db: Session, + end_user_id: str, + summary_id: str + ) -> Dict[str, Any]: + """ + 获取单个情景记忆的详细信息 + + """ + try: + logger.info(f"开始查询 end_user_id={end_user_id}, summary_id={summary_id} 的情景记忆详情") + + # 1. 查询指定的MemorySummary节点 + query = """ + MATCH (s:MemorySummary) + WHERE elementId(s) = $summary_id AND s.group_id = $group_id + RETURN elementId(s) AS id, s.created_at AS created_at + """ + + result = await self.neo4j_connector.execute_query( + query, + summary_id=summary_id, + group_id=end_user_id + ) + + # 2. 如果节点不存在,返回错误 + if not result or len(result) == 0: + logger.warning(f"未找到 summary_id={summary_id} 的情景记忆") + raise ValueError(f"情景记忆不存在: summary_id={summary_id}") + + # 3. 获取基本信息 + record = result[0] + created_at_str = record.get("created_at") + + # 转换时间戳 + created_at_timestamp = None + if created_at_str: + try: + from datetime import datetime + dt_object = datetime.fromisoformat(created_at_str.replace("Z", "+00:00")) + created_at_timestamp = int(dt_object.timestamp() * 1000) + except (ValueError, TypeError, AttributeError) as e: + logger.warning(f"无法解析时间戳: {created_at_str}, error={str(e)}") + + # 4. 调用_get_title_and_type读取标题和类型 + title, episodic_type = await self._get_title_and_type( + summary_id=summary_id, + end_user_id=end_user_id + ) + + # 5. 调用_extract_involved_objects提取涉及对象 + involved_objects = await self._extract_involved_objects( + summary_id=summary_id, + end_user_id=end_user_id + ) + + # 6. 调用_extract_content_records提取内容记录 + content_records = await self._extract_content_records( + summary_id=summary_id, + end_user_id=end_user_id + ) + + # 7. 调用_extract_episodic_emotion提取情绪 + emotion = await self._extract_episodic_emotion( + summary_id=summary_id, + end_user_id=end_user_id + ) + + # 8. 返回完整的详情信息 + details = { + "id": summary_id, + "created_at": created_at_timestamp, + "involved_objects": involved_objects, + "episodic_type": episodic_type, + "content_records": content_records, + "emotion": emotion + } + + logger.info(f"成功获取 summary_id={summary_id} 的情景记忆详情") + + return details + + except ValueError as e: + # 重新抛出ValueError,让Controller层处理 + raise + except Exception as e: + logger.error(f"获取情景记忆详情时出错: {str(e)}", exc_info=True) + raise # 独立的分析函数 From 177d514d137e0943a6a0bdd3dc08c0c16a27fe48 Mon Sep 17 00:00:00 2001 From: zhaoying Date: Sat, 10 Jan 2026 17:35:17 +0800 Subject: [PATCH 64/75] feat: user memory --- web/src/api/memory.ts | 14 ++ web/src/i18n/en.ts | 13 ++ web/src/i18n/zh.ts | 13 ++ web/src/routes/index.tsx | 1 - web/src/routes/routes.json | 3 +- .../UserMemoryDetail/components/AboutMe.tsx | 1 - .../components/EmotionLine.tsx | 173 +++++++++++++++++ .../components/ExplicitDetailModal.tsx | 100 ++++++++++ .../components/GraphDetail.tsx | 174 ++++++++++++++++++ .../UserMemoryDetail/components/Habits.tsx | 3 +- .../components/InterestAreas.tsx | 3 +- .../components/NodeStatistics.tsx | 3 +- .../components/RelationshipNetwork.tsx | 8 +- .../UserMemoryDetail/pages/EpisodicDetail.tsx | 5 +- .../UserMemoryDetail/pages/ExplicitDetail.tsx | 109 +++++++++++ .../UserMemoryDetail/pages/ForgetDetail.tsx | 3 +- .../UserMemoryDetail/pages/GraphDetail.tsx | 14 -- .../views/UserMemoryDetail/pages/index.tsx | 3 + web/src/views/UserMemoryDetail/types.ts | 3 + 19 files changed, 615 insertions(+), 31 deletions(-) create mode 100644 web/src/views/UserMemoryDetail/components/EmotionLine.tsx create mode 100644 web/src/views/UserMemoryDetail/components/ExplicitDetailModal.tsx create mode 100644 web/src/views/UserMemoryDetail/components/GraphDetail.tsx create mode 100644 web/src/views/UserMemoryDetail/pages/ExplicitDetail.tsx delete mode 100644 web/src/views/UserMemoryDetail/pages/GraphDetail.tsx diff --git a/web/src/api/memory.ts b/web/src/api/memory.ts index 39136da3..42f691a4 100644 --- a/web/src/api/memory.ts +++ b/web/src/api/memory.ts @@ -181,6 +181,20 @@ export const getEpisodicOverview = (data: { end_user_id: string; time_range: str export const getEpisodicDetail = (data: { end_user_id: string; summary_id: string; } ) => { return request.post(`/memory-storage/classifications/episodic-memory-details`, data) } +// 关系演化 +export const getRelationshipEvolution = (data: { id: string; label: string; } ) => { + return request.get(`/memory-storage/memory_space/relationship_evolution`, data) +} +// 共同记忆时间线 +export const getTimelineMemories = (data: { id: string; label: string; }) => { + return request.get(`/memory-storage/memory_space/timeline_memories`, data) +} +export const getExplicitMemory = (end_user_id: string) => { + return request.post(`/memory-storage/classifications/explicit-memory`, { end_user_id }) +} +export const getExplicitMemoryDetails = (data: { end_user_id: string, memory_id: string; }) => { + return request.post(`/memory-storage/classifications/explicit-memory-details`, data) +} /*************** end 用户记忆 相关接口 ******************************/ diff --git a/web/src/i18n/en.ts b/web/src/i18n/en.ts index c7c9a937..16d07add 100644 --- a/web/src/i18n/en.ts +++ b/web/src/i18n/en.ts @@ -1240,6 +1240,10 @@ export const en = { associative_memory: 'Associative Memory', unix: 'items', completeMemory: 'Complete Memory', + relationshipEvolution: 'Relationship Evolution', + timelineMemories: 'Shared Memory Timeline', + emotionLine: 'Emotion Changes Over Time', + interaction: 'Interaction Frequency & Relationship Stages', }, space: { createSpace: 'Create Space', @@ -2268,6 +2272,15 @@ Memory Bear: After the rebellion, regional warlordism intensified for several re section_count: 'Number of Sections', timeLine: 'Perception Timeline', lastInfo: 'Real-time Perception Dashboard', + }, + explicitDetail: { + episodic_memories: 'Episodic Memories', + semantic_memories: 'Semantic Memories', + content: 'Core Description', + created_at: 'Created At', + emotion: 'Emotion', + core_definition: 'Core Definition', + detailed_notes: 'Detailed Notes', } }, }; diff --git a/web/src/i18n/zh.ts b/web/src/i18n/zh.ts index d858b643..74c02720 100644 --- a/web/src/i18n/zh.ts +++ b/web/src/i18n/zh.ts @@ -1321,6 +1321,10 @@ export const zh = { associative_memory: '关联记忆', unix: '个', completeMemory: '完整记忆', + relationshipEvolution: '关系演化', + timelineMemories: '共同记忆时间线', + emotionLine: '情绪随时间变化', + interaction: '互动频率 & 关系阶段', }, space: { createSpace: '创建空间', @@ -2368,6 +2372,15 @@ export const zh = { section_count: '段落数', timeLine: '感知时间线', lastInfo: '实时感知仪表盘', + }, + explicitDetail: { + episodic_memories: '情景记忆', + semantic_memories: '语义记忆', + content: '核心描述', + created_at: '创建时间', + emotion: '情绪', + core_definition: '核心定义', + detailed_notes: '详细笔记', } }, } \ No newline at end of file diff --git a/web/src/routes/index.tsx b/web/src/routes/index.tsx index bc2f61e6..f3bd9c2d 100644 --- a/web/src/routes/index.tsx +++ b/web/src/routes/index.tsx @@ -61,7 +61,6 @@ const componentMap: Record>> = StatementDetail: lazy(() => import('@/views/UserMemoryDetail/pages/StatementDetail')), ForgetDetail: lazy(() => import('@/views/UserMemoryDetail/pages/ForgetDetail')), MemoryNodeDetail: lazy(() => import('@/views/UserMemoryDetail/pages/index')), - GraphDetail: lazy(() => import('@/views/UserMemoryDetail/pages/GraphDetail')), SelfReflectionEngine: lazy(() => import('@/views/SelfReflectionEngine')), OrderPayment: lazy(() => import('@/views/OrderPayment')), OrderHistory: lazy(() => import('@/views/OrderHistory')), diff --git a/web/src/routes/routes.json b/web/src/routes/routes.json index 2f332b72..ca6a3271 100644 --- a/web/src/routes/routes.json +++ b/web/src/routes/routes.json @@ -44,8 +44,7 @@ { "path": "/conversation/:token", "element": "Conversation" }, { "path": "/user-memory/neo4j/:id", "element": "Neo4jUserMemoryDetail" }, { "path": "/statement/:id", "element": "StatementDetail" }, - { "path": "/user-memory/detail/:id/:type", "element": "MemoryNodeDetail" }, - { "path": "/graph/:id", "element": "GraphDetail" } + { "path": "/user-memory/detail/:id/:type", "element": "MemoryNodeDetail" } ] }, { diff --git a/web/src/views/UserMemoryDetail/components/AboutMe.tsx b/web/src/views/UserMemoryDetail/components/AboutMe.tsx index f2c94814..f3f914c2 100644 --- a/web/src/views/UserMemoryDetail/components/AboutMe.tsx +++ b/web/src/views/UserMemoryDetail/components/AboutMe.tsx @@ -30,7 +30,6 @@ const AboutMe = forwardRef((_props, ref) => { getData() }, [id]) - // 记忆洞察 const getData = () => { if (!id) return setLoading(true) diff --git a/web/src/views/UserMemoryDetail/components/EmotionLine.tsx b/web/src/views/UserMemoryDetail/components/EmotionLine.tsx new file mode 100644 index 00000000..eb53439f --- /dev/null +++ b/web/src/views/UserMemoryDetail/components/EmotionLine.tsx @@ -0,0 +1,173 @@ +import { type FC, useRef } from 'react' +import { useTranslation } from 'react-i18next' +import ReactEcharts from 'echarts-for-react'; +import * as echarts from 'echarts'; +import Empty from '@/components/Empty' +import Loading from '@/components/Empty/Loading' +import type { Emotion } from './GraphDetail' + +interface EmotionLineProps { + chartData: Emotion[]; + loading?: boolean; +} + +const Colors = ['#369F21', '#155EEF', '#FF5D34'] + +const EmotionLine: FC = ({ chartData, loading }) => { + const { t } = useTranslation() + const chartRef = useRef(null); + + const getSeries = () => { + const emotionTypes = [...new Set(chartData.map(item => item.emotion_type))] + const timePoints = [...new Set(chartData.map(item => item.created_at))].sort() + + return emotionTypes.map((emotionType, index) => { + const emotionData = chartData.filter(item => item.emotion_type === emotionType) + const dataMap = new Map(emotionData.map(item => [item.created_at, item.emotion_intensity])) + const seriesData = timePoints.map(time => dataMap.get(time) || 0) + + return { + name: emotionType, + type: 'line', + smooth: true, + lineStyle: { + width: 3, + color: Colors[index % Colors.length] + }, + itemStyle: { + color: Colors[index % Colors.length] + }, + areaStyle: { + color: Colors[index % Colors.length], + opacity: 0.08 + }, + data: seriesData + } + }) + } + + return ( + <> +
{t('userMemory.emotionLine')}
+ {loading + ? + : !chartData || chartData.length === 0 + ? + : ` + params.forEach((param: any) => { + result += `${param.marker}${param.seriesName}: ${param.value}
` + }) + return result + } + }, + legend: { + bottom: 2, + padding: 0, + itemGap: 24, + itemWidth: 40, + itemHeight: 12, + borderRadius: 2, + orient: 'horizontal', + textStyle: { + color: '#5B6167', + fontFamily: 'PingFangSC, PingFang SC', + lineHeight: 16, + } + }, + grid: { + top: 16, + left: 30, + right: 36, + bottom: 48, + // containLabel: false + }, + xAxis: { + type: 'category', + data: [...new Set(chartData.map(item => item.created_at))].sort().map(time => { + const date = new Date(time) + return `${date.getFullYear()}.${String(date.getMonth() + 1).padStart(2, '0')}` + }), + boundaryGap: false, + axisLabel: { + color: '#A8A9AA', + fontFamily: 'PingFangSC, PingFang SC' + }, + axisLine: { + show: true, + lineStyle: { + color: '#EBEBEB' + } + }, + splitLine: { + show: true, + lineStyle: { + color: '#EBEBEB', + type: 'solid' + } + }, + axisTick: { + show: true, + lineStyle: { + color: '#EBEBEB', + type: 'solid' + } + } + }, + yAxis: { + type: 'value', + axisLabel: { + color: '#A8A9AA', + fontFamily: 'PingFangSC, PingFang SC' + }, + axisLine: { + show: true, + lineStyle: { + color: '#EBEBEB' + } + }, + splitLine: { + show: true, + lineStyle: { + color: '#EBEBEB', + type: 'solid' + } + }, + axisTick: { + show: true, + lineStyle: { + color: '#EBEBEB', + type: 'solid' + } + }, + max: 1, + min: 0 + }, + series: getSeries() + }} + style={{ height: '265px', width: '100%', minWidth: '100%' }} + notMerge={true} + lazyUpdate={true} + /> + } + + ) +} + +export default EmotionLine diff --git a/web/src/views/UserMemoryDetail/components/ExplicitDetailModal.tsx b/web/src/views/UserMemoryDetail/components/ExplicitDetailModal.tsx new file mode 100644 index 00000000..05d0597f --- /dev/null +++ b/web/src/views/UserMemoryDetail/components/ExplicitDetailModal.tsx @@ -0,0 +1,100 @@ +import { forwardRef, useImperativeHandle, useState, useCallback } from 'react'; +import { useParams } from 'react-router-dom' +import { Descriptions, Skeleton } from 'antd'; +import { useTranslation } from 'react-i18next'; + +import RbModal from '@/components/RbModal' +import { getExplicitMemoryDetails } from '@/api/memory' +import { formatDateTime } from '@/utils/format' +import type { ExplicitDetailModalRef, EpisodicMemory, SemanticMemory } from '../pages/ExplicitDetail' + + +interface Data { + memory_type: 'episodic' | 'semantic'; + title: string; + content: string; + emotion: string; + created_at: number; + + name: string; + core_definition: string; + detailed_notes: string; +} +const ExplicitDetailModal = forwardRef((_props, ref) => { + const { t } = useTranslation(); + const { id } = useParams() + const [visible, setVisible] = useState(false); + const [loading, setLoading] = useState(false); + const [data, setData] = useState({} as Data) + + // 封装取消方法,添加关闭弹窗逻辑 + const handleClose = () => { + setVisible(false); + setData({} as Data) + }; + + const handleOpen = (vo: EpisodicMemory | SemanticMemory) => { + setLoading(true) + getExplicitMemoryDetails({ + end_user_id: id as string, + memory_id: vo.id + }) + .then(res => { + setVisible(true); + setData(res as Data) + }) + .finally(() => { + setLoading(false) + }) + }; + + const getEmotionColor = (emotionType: string) => { + const colors: Record = { + joy: '#52c41a', + anger: '#ff4d4f', + sadness: '#1890ff', + fear: '#fa8c16', + neutral: '#8c8c8c', + surprise: '#722ed1' + } + return colors[emotionType] || '#8c8c8c' + } + + // 暴露给父组件的方法 + useImperativeHandle(ref, () => ({ + handleOpen, + })); + return ( + + {loading ? + : + {data.emotion && +
+
+ {t(`statementDetail.${data.emotion || 'neutral'}`)} +
+
} + {data.core_definition && + {data.core_definition} + } + {data.detailed_notes && + {data.detailed_notes} + } + {data.created_at && + {formatDateTime(data.created_at)} + } + {data.content && + {data.content} + } +
+ } +
+ ); +}); + +export default ExplicitDetailModal; \ No newline at end of file diff --git a/web/src/views/UserMemoryDetail/components/GraphDetail.tsx b/web/src/views/UserMemoryDetail/components/GraphDetail.tsx new file mode 100644 index 00000000..3b654a12 --- /dev/null +++ b/web/src/views/UserMemoryDetail/components/GraphDetail.tsx @@ -0,0 +1,174 @@ +import { type FC, useState, forwardRef, useImperativeHandle } from 'react' +import { useTranslation } from 'react-i18next' +import { useParams } from 'react-router-dom' +import { Row, Col, Tabs } from 'antd' + +import { getRelationshipEvolution, getTimelineMemories } from '@/api/memory' +import type { Node, GraphDetailRef } from '../types' +import RbDrawer from '@/components/RbDrawer' +import RbCard from '@/components/RbCard/Card' +import EmotionLine from './EmotionLine' + +export interface Emotion { + emotion_intensity: number; + emotion_type: string; + created_at: string | number; +} +export interface Interaction { + name: string; + importance_score: number; + interaction_count: number; +} + +const GraphDetail = forwardRef((_props, ref) => { + const { t } = useTranslation() + const { id } = useParams() + const [open, setOpen] = useState(false); + const [vo, setVo] = useState(null) + const [emotionData, setEmotionData] = useState([ + { + "emotion_intensity": 0.1, + "emotion_type": "neutral", + "created_at": "2026-01-07 19:14:34" + }, + { + "emotion_intensity": 0.2, + "emotion_type": "neutral", + "created_at": "2026-02-08 19:14:34" + }, + { + "emotion_intensity": 0.1, + "emotion_type": "neutral", + "created_at": "2026-03-09 19:14:34" + }, + { + "emotion_intensity": 0.1, + "emotion_type": "neutral", + "created_at": "2026-04-10 19:14:34" + }, + { + "emotion_intensity": 0.1, + "emotion_type": "sadness", + "created_at": "2026-01-07 19:14:34" + }, + { + "emotion_intensity": 0.2, + "emotion_type": "sadness", + "created_at": "2026-02-08 19:14:34" + }, + { + "emotion_intensity": 0.1, + "emotion_type": "sadness", + "created_at": "2026-03-09 19:14:34" + }, + { + "emotion_intensity": 0.1, + "emotion_type": "sadness", + "created_at": "2026-04-10 19:14:34" + }, + ]) + const [interactionData, setInteractionData] = useState([ + { + "name": "小蓝", + "importance_score": 0.5, + "interaction_count": 1 + } + ]) + const [timelineMemories, setTimelineMemories] = useState({ + "code": 0, + "msg": "共同记忆时间线", + "data": { + "success": true, + "data": { + "MemorySummary": [ + "小蓝今天原计划与小明野餐、与小绿看电影,但最终选择与姐姐小红一起看戏。", + "用户小明喜欢喝咖啡,每天都要喝拿铁。" + ], + "Statement": [ + "小蓝对是否去野餐或看电影感到犹豫。", + "小蓝和她姐姐小红出去看戏。", + "小明喜欢喝咖啡。", + "小明每天都要喝拿铁。", + "小明今天约小蓝出去野餐。" + ], + "ExtractedEntity": [ + "小明", + "咖啡", + "拿铁", + "小蓝", + "野餐" + ], + "timelines_memory": [ + "小蓝今天原计划与小明野餐、与小绿看电影,但最终选择与姐姐小红一起看戏。", + "用户小明喜欢喝咖啡,每天都要喝拿铁。", + "小蓝对是否去野餐或看电影感到犹豫。", + "小蓝和她姐姐小红出去看戏。", + "小明喜欢喝咖啡。", + "小明每天都要喝拿铁。", + "小明今天约小蓝出去野餐。", + "小明", + "咖啡", + "拿铁", + "小蓝", + "野餐" + ] + } + }, + "error": "", + "time": 1767852781464 + }) + + const handleCancel = () => { + setVo(null) + setOpen(false) + } + const handleOpen = (vo: Node) => { + setOpen(true) + setVo(vo) + getTimelineMemoriesData(vo) + } + const getRelationshipEvolutionData = (vo: Node) => { + if (!id || !vo.label) return + + getRelationshipEvolution({ id: id as string, label: vo.label }) + .then(res => { + const { emotion, interaction } = res as { emotion: { data: Emotion[]}; interaction: {data: Interaction[]} } || {} + setEmotionData(emotion?.data) + setInteractionData(interaction?.data) + }) + } + const getTimelineMemoriesData = (vo: Node) => { + if (!id || !vo.label) return + + getTimelineMemories({ id: id as string, label: vo.label }) + .then(res => { + + }) + } + + useImperativeHandle(ref, () => ({ + handleOpen, + })); + + return ( + +
{t('useMemory.relationshipEvolution')}
+ + + + + + +
{t('userMemory.interaction')}
+ +
+
+
+ ) +}) +export default GraphDetail \ No newline at end of file diff --git a/web/src/views/UserMemoryDetail/components/Habits.tsx b/web/src/views/UserMemoryDetail/components/Habits.tsx index 746d7164..93ef817f 100644 --- a/web/src/views/UserMemoryDetail/components/Habits.tsx +++ b/web/src/views/UserMemoryDetail/components/Habits.tsx @@ -12,7 +12,7 @@ interface HabitsItem { habit_description: string; frequency_pattern: string; time_context: string; - confidence_level: string; + confidence_level: number; supporting_summaries: string[]; first_observed: string; last_observed: string; @@ -31,7 +31,6 @@ const Habits: FC = () => { getData() }, [id]) - // 记忆洞察 const getData = () => { if (!id) return setLoading(true) diff --git a/web/src/views/UserMemoryDetail/components/InterestAreas.tsx b/web/src/views/UserMemoryDetail/components/InterestAreas.tsx index 357336f4..6f74d255 100644 --- a/web/src/views/UserMemoryDetail/components/InterestAreas.tsx +++ b/web/src/views/UserMemoryDetail/components/InterestAreas.tsx @@ -33,8 +33,7 @@ const InterestAreas: FC = () => { if (!id) return getData() }, [id]) - - // 记忆洞察 + const getData = () => { if (!id) return setLoading(true) diff --git a/web/src/views/UserMemoryDetail/components/NodeStatistics.tsx b/web/src/views/UserMemoryDetail/components/NodeStatistics.tsx index 8815c66d..0e032e45 100644 --- a/web/src/views/UserMemoryDetail/components/NodeStatistics.tsx +++ b/web/src/views/UserMemoryDetail/components/NodeStatistics.tsx @@ -47,8 +47,7 @@ const NodeStatistics: FC = () => { if (!id) return getData() }, [id]) - - // 记忆洞察 + const getData = () => { if (!id) return setLoading(true) diff --git a/web/src/views/UserMemoryDetail/components/RelationshipNetwork.tsx b/web/src/views/UserMemoryDetail/components/RelationshipNetwork.tsx index 4cce1100..641a37f6 100644 --- a/web/src/views/UserMemoryDetail/components/RelationshipNetwork.tsx +++ b/web/src/views/UserMemoryDetail/components/RelationshipNetwork.tsx @@ -7,12 +7,13 @@ import dayjs from 'dayjs' import RbCard from '@/components/RbCard/Card' import ReactEcharts from 'echarts-for-react' import detailEmpty from '@/assets/images/userMemory/detail_empty.png' -import type { Node, Edge, GraphData, StatementNodeProperties, ExtractedEntityNodeProperties } from '../types' +import type { Node, Edge, GraphData, StatementNodeProperties, ExtractedEntityNodeProperties, GraphDetailRef } from '../types' import { getMemorySearchEdges, } from '@/api/memory' import Empty from '@/components/Empty' import Tag from '@/components/Tag' +import GraphDetail from '../components/GraphDetail' const colors = ['#155EEF', '#369F21', '#4DA8FF', '#FF5D34', '#9C6FFF', '#FF8A4C', '#8BAEF7', '#FFB048'] const RelationshipNetwork:FC = () => { @@ -25,6 +26,7 @@ const RelationshipNetwork:FC = () => { const [categories, setCategories] = useState<{ name: string }[]>([]) const [selectedNode, setSelectedNode] = useState(null) // const [fullScreen, setFullScreen] = useState(false) + const graphDetailRef = useRef(null) console.log('categories', categories) // 关系网络 @@ -139,7 +141,7 @@ const RelationshipNetwork:FC = () => { const handleViewAll = () => { if (!selectedNode) return - window.open(`/#/graph/${selectedNode.id}`); + graphDetailRef.current?.handleOpen(selectedNode) } return ( @@ -332,6 +334,8 @@ const RelationshipNetwork:FC = () => {
+ + ) } diff --git a/web/src/views/UserMemoryDetail/pages/EpisodicDetail.tsx b/web/src/views/UserMemoryDetail/pages/EpisodicDetail.tsx index 4a7e4b1f..2940347d 100644 --- a/web/src/views/UserMemoryDetail/pages/EpisodicDetail.tsx +++ b/web/src/views/UserMemoryDetail/pages/EpisodicDetail.tsx @@ -72,10 +72,9 @@ const EpisodicDetail: FC = () => { useEffect(() => { if (!id) return - // getData() + getData() }, [id]) - - // 记忆洞察 + const getData = () => { if (!id) return setLoading(true) diff --git a/web/src/views/UserMemoryDetail/pages/ExplicitDetail.tsx b/web/src/views/UserMemoryDetail/pages/ExplicitDetail.tsx new file mode 100644 index 00000000..286e71be --- /dev/null +++ b/web/src/views/UserMemoryDetail/pages/ExplicitDetail.tsx @@ -0,0 +1,109 @@ +import { type FC, useEffect, useState, useRef } from 'react' +import { useTranslation } from 'react-i18next' +import { useParams } from 'react-router-dom' +import { List, Skeleton, Row, Col } from 'antd' +import RbCard from '@/components/RbCard/Card' +import { + getExplicitMemory, +} from '@/api/memory' +import { formatDateTime } from '@/utils/format' +import Empty from '@/components/Empty' +import ExplicitDetailModal from '../components/ExplicitDetailModal' + +export interface EpisodicMemory { + id: string; + title: string; + content: string; + created_at: number; +} +export interface SemanticMemory { + id: string; + name: string; + entity_type: string; + core_definition: string; + created_at: number; +} +interface Data { + episodic_memories: EpisodicMemory[]; + semantic_memories: SemanticMemory[] +} + +export interface ExplicitDetailModalRef { + handleOpen: (vo: EpisodicMemory | SemanticMemory) => void; +} + +const ExplicitDetail: FC = () => { + const { t } = useTranslation() + const { id } = useParams() + const explicitDetailModalRef = useRef(null) + const [loading, setLoading] = useState(false) + const [data, setData] = useState({ episodic_memories: [], semantic_memories: [] }) + + useEffect(() => { + if (!id) return + getData() + }, [id]) + + const getData = () => { + if (!id) return + setLoading(true) + getExplicitMemory(id).then((res) => { + const response = res as Data + setData(response) + setLoading(false) + }) + .finally(() => { + setLoading(false) + }) + } + const handleView = (item: EpisodicMemory | SemanticMemory) => { + explicitDetailModalRef.current?.handleOpen(item) + } + return ( +
+
{t('explicitDetail.episodic_memories')}
+ {loading ? + + : data.episodic_memories?.length > 0 ? ( + + {data.episodic_memories.map(item => ( + + handleView(item)} + > +
{formatDateTime(item.created_at)}
+
{item.content}
+
+ + ))} +
+ ) : } + +
{t('explicitDetail.semantic_memories')}
+ {loading ? + + : data.semantic_memories?.length > 0 ? ( + + {data.semantic_memories.map(item => ( + + handleView(item)} + > +
{item.core_definition}
+
+ + ))} +
+ ) : } + + +
+ ) +} +export default ExplicitDetail \ No newline at end of file diff --git a/web/src/views/UserMemoryDetail/pages/ForgetDetail.tsx b/web/src/views/UserMemoryDetail/pages/ForgetDetail.tsx index f0ba04ff..602dbf25 100644 --- a/web/src/views/UserMemoryDetail/pages/ForgetDetail.tsx +++ b/web/src/views/UserMemoryDetail/pages/ForgetDetail.tsx @@ -30,8 +30,7 @@ const ForgetDetail: FC = () => { if (!id) return getData() }, [id]) - - // 记忆洞察 + const getData = () => { if (!id) return setLoading(true) diff --git a/web/src/views/UserMemoryDetail/pages/GraphDetail.tsx b/web/src/views/UserMemoryDetail/pages/GraphDetail.tsx deleted file mode 100644 index f3cf716c..00000000 --- a/web/src/views/UserMemoryDetail/pages/GraphDetail.tsx +++ /dev/null @@ -1,14 +0,0 @@ -import { type FC } from 'react' -import { useTranslation } from 'react-i18next' -import { Row, Col } from 'antd' - -const GraphDetail: FC = () => { - const { t } = useTranslation() - - return ( -
- GraphDetail -
- ) -} -export default GraphDetail \ No newline at end of file diff --git a/web/src/views/UserMemoryDetail/pages/index.tsx b/web/src/views/UserMemoryDetail/pages/index.tsx index da62c14e..93468a94 100644 --- a/web/src/views/UserMemoryDetail/pages/index.tsx +++ b/web/src/views/UserMemoryDetail/pages/index.tsx @@ -10,6 +10,7 @@ import ImplicitDetail from './ImplicitDetail' import ShortTermDetail from './ShortTermDetail' import PerceptualDetail from './PerceptualDetail' import EpisodicDetail from './EpisodicDetail' +import ExplicitDetail from './ExplicitDetail' import { getEndUserProfile, } from '@/api/memory' @@ -62,6 +63,8 @@ const Detail: FC = () => { {type === 'SHORT_TERM_MEMORY' && } {type === 'PERCEPTUAL_MEMORY' && } {/** TODO */} {type === 'EPISODIC_MEMORY' && } + {/* {type === 'WORKING_MEMORY' && } */} {/** TODO */} + {type === 'EXPLICIT_MEMORY' && } {/** TODO */}
) diff --git a/web/src/views/UserMemoryDetail/types.ts b/web/src/views/UserMemoryDetail/types.ts index 263494d0..afed31fd 100644 --- a/web/src/views/UserMemoryDetail/types.ts +++ b/web/src/views/UserMemoryDetail/types.ts @@ -184,4 +184,7 @@ export interface ForgetData { last_access_time: number; }[], timestamp: number; +} +export interface GraphDetailRef { + handleOpen: (vo: Node) => void } \ No newline at end of file From 24ace52e27c46edf14623d2d10444903e14da9c9 Mon Sep 17 00:00:00 2001 From: zhaoying Date: Sat, 10 Jan 2026 17:44:06 +0800 Subject: [PATCH 65/75] bugfix: workflow bugfix --- .../AddChatVariable/ChatVariableModal.tsx | 56 ++--- .../components/AddChatVariable/index.tsx | 8 +- .../components/AddChatVariable/types.ts | 4 +- .../Properties/AssignmentList/index.tsx | 1 + .../components/Properties/CaseList/index.tsx | 8 +- .../Properties/ConditionList/index.tsx | 8 +- .../Properties/HttpRequest/index.tsx | 36 ++- .../Knowledge/KnowledgeConfigModal.tsx | 7 +- .../Knowledge/KnowledgeGlobalConfigModal.tsx | 7 +- .../Properties/ToolConfig/index.tsx | 9 +- .../Properties/VariableEditModal.tsx | 14 +- .../components/Properties/VariableSelect.tsx | 5 +- .../Workflow/components/Properties/index.tsx | 229 +++++++++--------- .../views/Workflow/hooks/useWorkflowGraph.ts | 20 +- web/src/views/Workflow/types.ts | 6 +- 15 files changed, 242 insertions(+), 176 deletions(-) diff --git a/web/src/views/Workflow/components/AddChatVariable/ChatVariableModal.tsx b/web/src/views/Workflow/components/AddChatVariable/ChatVariableModal.tsx index fabe45ba..aaaa2ab5 100644 --- a/web/src/views/Workflow/components/AddChatVariable/ChatVariableModal.tsx +++ b/web/src/views/Workflow/components/AddChatVariable/ChatVariableModal.tsx @@ -1,5 +1,5 @@ import { forwardRef, useImperativeHandle, useState } from 'react'; -import { Form, Input, Select, Checkbox, InputNumber } from 'antd'; +import { Form, Input, Select, InputNumber } from 'antd'; import { useTranslation } from 'react-i18next'; import type { ChatVariableModalRef } from './types' @@ -26,6 +26,7 @@ const ChatVariableModal = forwardRef(); const [loading, setLoading] = useState(false) const [editIndex, setEditIndex] = useState(undefined) + const type = Form.useWatch('type', form); // 封装取消方法,添加关闭弹窗逻辑 const handleClose = () => { @@ -38,7 +39,8 @@ const ChatVariableModal = forwardRef { setVisible(true); if (variable) { - form.setFieldsValue(variable) + const { default: _, ...rest } = variable + form.setFieldsValue({ ...rest }) setEditIndex(index) } else { form.resetFields(); @@ -48,7 +50,7 @@ const ChatVariableModal = forwardRef { form.validateFields().then((values) => { - refresh({ ...values }, editIndex) + refresh({ ...values, default: values.defaultValue }, editIndex) handleClose() }) } @@ -89,52 +91,36 @@ const ChatVariableModal = forwardRef - ); - } - return ; - }} - - - + {type === 'number' + ? + : type === 'boolean' + ? + } + - - - {t('workflow.config.parameter-extractor.required')} - ); diff --git a/web/src/views/Workflow/components/AddChatVariable/index.tsx b/web/src/views/Workflow/components/AddChatVariable/index.tsx index f765b5eb..7ebce7df 100644 --- a/web/src/views/Workflow/components/AddChatVariable/index.tsx +++ b/web/src/views/Workflow/components/AddChatVariable/index.tsx @@ -40,7 +40,7 @@ const AddChatVariable = forwardRef(({ } const handleSave = (value: ChatVariable, index?: number) => { const list = [...variables] - if (index && index > -1) { + if (typeof index === 'number' && index > -1) { list[index] = value } else { list.push(value) @@ -75,17 +75,15 @@ const AddChatVariable = forwardRef(({ dataSource={variables} renderItem={(item, index) => ( -
+
{item.name} ({t(`workflow.config.parameter-extractor.${item.type}`)})
- {item.required ? t('workflow.config.parameter-extractor.required') : ''} -
{item.description}
- +
handleEdit(index)} diff --git a/web/src/views/Workflow/components/AddChatVariable/types.ts b/web/src/views/Workflow/components/AddChatVariable/types.ts index ab00ae69..5d9aa7b0 100644 --- a/web/src/views/Workflow/components/AddChatVariable/types.ts +++ b/web/src/views/Workflow/components/AddChatVariable/types.ts @@ -11,8 +11,8 @@ export interface VariableFormData { name: string; type: ChatVariable['type']; description?: string; - required?: boolean; - defaultValue?: any; + defaultValue?: string; + default?: string; } export interface ChatVariableModalRef { diff --git a/web/src/views/Workflow/components/Properties/AssignmentList/index.tsx b/web/src/views/Workflow/components/Properties/AssignmentList/index.tsx index 2ac8397b..97f28668 100644 --- a/web/src/views/Workflow/components/Properties/AssignmentList/index.tsx +++ b/web/src/views/Workflow/components/Properties/AssignmentList/index.tsx @@ -114,6 +114,7 @@ const AssignmentList: FC = ({ ? form.setFieldValue([name, 'value'], value)} /> : operation === 'assign' ? <> diff --git a/web/src/views/Workflow/components/Properties/CaseList/index.tsx b/web/src/views/Workflow/components/Properties/CaseList/index.tsx index 22ac7490..96850911 100644 --- a/web/src/views/Workflow/components/Properties/CaseList/index.tsx +++ b/web/src/views/Workflow/components/Properties/CaseList/index.tsx @@ -348,8 +348,12 @@ const CaseList: FC = ({ popupMatchSelectWidth={false} variant="borderless" /> - : + : form.setFieldValue([name, caseIndex, 'expressions', conditionIndex, 'right'], value)} + /> } diff --git a/web/src/views/Workflow/components/Properties/ConditionList/index.tsx b/web/src/views/Workflow/components/Properties/ConditionList/index.tsx index 6d955647..8fbebeda 100644 --- a/web/src/views/Workflow/components/Properties/ConditionList/index.tsx +++ b/web/src/views/Workflow/components/Properties/ConditionList/index.tsx @@ -169,8 +169,12 @@ const ConditionList: FC = ({ variant="borderless" className="rb:w-full!" /> - : + : form.setFieldValue([parentName, 'expressions', index, 'right'], value)} + /> } diff --git a/web/src/views/Workflow/components/Properties/HttpRequest/index.tsx b/web/src/views/Workflow/components/Properties/HttpRequest/index.tsx index 4e704ca8..80584220 100644 --- a/web/src/views/Workflow/components/Properties/HttpRequest/index.tsx +++ b/web/src/views/Workflow/components/Properties/HttpRequest/index.tsx @@ -194,19 +194,31 @@ const HttpRequest: FC<{ options: Suggestion[]; selectedNode?: any; graphRef?: an name={['timeouts', 'connect_timeout']} label={t('workflow.config.http-request.connect_timeout')} > - + form.setFieldValue(['timeouts', 'connect_timeout'], value)} + /> - + form.setFieldValue(['timeouts', 'read_timeout'], value)} + /> - + form.setFieldValue(['timeouts', 'write_timeout'], value)} + /> @@ -219,13 +231,21 @@ const HttpRequest: FC<{ options: Suggestion[]; selectedNode?: any; graphRef?: an name={['retry', 'max_attempts']} label={t('workflow.config.http-request.max_attempts')} > - + form.setFieldValue(['retry', 'max_attempts'], value)} + /> {t('workflow.config.http-request.retry_interval')} (ms)} > - + form.setFieldValue(['retry', 'retry_interval'], value)} + /> } @@ -254,7 +274,11 @@ const HttpRequest: FC<{ options: Suggestion[]; selectedNode?: any; graphRef?: an name={['error_handle', 'status_code']} label={<>status_code number} > - + form.setFieldValue(['error_handle', 'status_code'], value)} + /> - + form.setFieldValue('top_k', value)} + /> {/* 语义相似度阈值 similarity_threshold */} {values?.retrieve_type === 'semantic' && ( diff --git a/web/src/views/Workflow/components/Properties/Knowledge/KnowledgeGlobalConfigModal.tsx b/web/src/views/Workflow/components/Properties/Knowledge/KnowledgeGlobalConfigModal.tsx index 773fb881..2f349487 100644 --- a/web/src/views/Workflow/components/Properties/Knowledge/KnowledgeGlobalConfigModal.tsx +++ b/web/src/views/Workflow/components/Properties/Knowledge/KnowledgeGlobalConfigModal.tsx @@ -110,7 +110,12 @@ const KnowledgeGlobalConfigModal = forwardRef - + form.setFieldValue('reranker_top_k', value)} + /> } diff --git a/web/src/views/Workflow/components/Properties/ToolConfig/index.tsx b/web/src/views/Workflow/components/Properties/ToolConfig/index.tsx index 0cba5596..2ee192f9 100644 --- a/web/src/views/Workflow/components/Properties/ToolConfig/index.tsx +++ b/web/src/views/Workflow/components/Properties/ToolConfig/index.tsx @@ -197,7 +197,14 @@ const ToolConfig: FC<{ options: Suggestion[]; }> = ({ : parameter.type === 'boolean' ? : parameter.type === 'integer' || parameter.type === 'number' - ? + ? form.setFieldValue(['tool_parameters', parameter.name], value)} + /> : - + form.setFieldValue('max_length', value)} + /> )} {/* 默认值 */} @@ -151,7 +155,13 @@ const VariableEditModal = forwardRef {['string'].includes(values.type) && } - {['number'].includes(values.type) && } + {['number'].includes(values.type) && ( + form.setFieldValue('default', value)} + /> + )} {['boolean'].includes(values.type) &&