Merge branch 'develop' of github.com:SuanmoSuanyangTechnology/MemoryBear into develop

This commit is contained in:
Mark
2026-01-06 13:58:52 +08:00
42 changed files with 1209 additions and 519 deletions

View File

@@ -117,7 +117,7 @@ async def get_prompt_opt(
user_require=data.message user_require=data.message
): ):
# chunk 是 prompt 的增量内容 # chunk 是 prompt 的增量内容
yield f"event:'message'\ndata: {json.dumps(chunk)}\n\n" yield f"event:message\ndata: {json.dumps(chunk)}\n\n"
return StreamingResponse( return StreamingResponse(
event_generator(), event_generator(),

View File

@@ -29,7 +29,7 @@ class WorkflowState(TypedDict):
# Set of loop node IDs, used for assigning values in loop nodes # Set of loop node IDs, used for assigning values in loop nodes
cycle_nodes: list cycle_nodes: list
looping: bool looping: Annotated[bool, lambda x, y: x and y]
# Input variables (passed from configured variables) # Input variables (passed from configured variables)
# Uses a deep merge function, supporting nested dict updates (e.g., conv.xxx) # Uses a deep merge function, supporting nested dict updates (e.g., conv.xxx)

View File

@@ -208,17 +208,12 @@ class HttpRequestNode(BaseNode):
retries -= 1 retries -= 1
if retries > 0: if retries > 0:
await asyncio.sleep(self.typed_config.retry.retry_interval / 1000) 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: else:
match self.typed_config.error_handle.method: 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: case HttpErrorHandle.DEFAULT:
logger.warning( logger.warning(
f"Node {self.node_id}: HTTP request failed, returning default result" 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" f"Node {self.node_id}: HTTP request failed, switching to error handling branch"
) )
return "ERROR" return "ERROR"
raise RuntimeError("http request failed")

View File

@@ -203,15 +203,16 @@ class KnowledgeRetrievalNode(BaseNode):
rs2 = vector_service.search_by_full_text(query=query, top_k=kb_config.top_k, rs2 = vector_service.search_by_full_text(query=query, top_k=kb_config.top_k,
indices=indices, indices=indices,
score_threshold=kb_config.similarity_threshold) score_threshold=kb_config.similarity_threshold)
# Deduplicate hybrid retrieval results # Deduplicate hy brid retrieval results
unique_rs = self._deduplicate_docs(rs1, rs2) unique_rs = self._deduplicate_docs(rs1, rs2)
vector_service.reranker = self.get_reranker_model() vector_service.reranker = self.get_reranker_model()
rs.extend(vector_service.rerank(query=query, docs=unique_rs, top_k=kb_config.top_k)) rs.extend(vector_service.rerank(query=query, docs=unique_rs, top_k=kb_config.top_k))
case _: case _:
raise RuntimeError("Unknown retrieval type") raise RuntimeError("Unknown retrieval type")
vector_service.reranker = self.get_reranker_model() 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) final_rs = vector_service.rerank(query=query, docs=rs, top_k=self.typed_config.reranker_top_k)
logger.info( logger.info(
f"Node {self.node_id}: knowledge base retrieval completed, results count: {len(final_rs)}" 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]

View File

@@ -1,5 +1,7 @@
"""LLM 节点配置""" """LLM 节点配置"""
from typing import Any
from pydantic import BaseModel, Field, field_validator from pydantic import BaseModel, Field, field_validator
from app.core.workflow.nodes.base_config import BaseNodeConfig, VariableDefinition, VariableType from app.core.workflow.nodes.base_config import BaseNodeConfig, VariableDefinition, VariableType
@@ -41,6 +43,11 @@ class LLMNodeConfig(BaseNodeConfig):
description="模型配置 ID" description="模型配置 ID"
) )
context: Any = Field(
default="",
description="上下文"
)
# 简单模式 # 简单模式
prompt: str | None = Field( prompt: str | None = Field(
default=None, default=None,

View File

@@ -5,11 +5,13 @@ LLM 节点实现
""" """
import logging import logging
import re
from typing import Any from typing import Any
from langchain_core.messages import AIMessage, SystemMessage, HumanMessage from langchain_core.messages import AIMessage, SystemMessage, HumanMessage
from app.core.workflow.nodes.base_node import BaseNode, WorkflowState from app.core.workflow.nodes.base_node import BaseNode, WorkflowState
from app.core.models import RedBearLLM, RedBearModelConfig 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.db import get_db_context
from app.models import ModelType from app.models import ModelType
from app.services.model_service import ModelConfigService from app.services.model_service import ModelConfigService
@@ -63,8 +65,15 @@ class LLMNode(BaseNode):
- user/human: 用户消息HumanMessage - user/human: 用户消息HumanMessage
- ai/assistant: AI 消息AIMessage - ai/assistant: AI 消息AIMessage
""" """
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 _prepare_llm(self, state: WorkflowState,stream:bool = False) -> tuple[RedBearLLM, list | str]: def _render_context(self, message,state):
context = f"<context>{self._render_template(self.typed_config.context, state)}</context>"
return re.sub(r"{{context}}", context, message)
def _prepare_llm(self, state: WorkflowState, stream: bool = False) -> tuple[RedBearLLM, list | str]:
"""准备 LLM 实例(公共逻辑) """准备 LLM 实例(公共逻辑)
Args: Args:
@@ -83,6 +92,7 @@ class LLMNode(BaseNode):
for msg_config in messages_config: for msg_config in messages_config:
role = msg_config.get("role", "user").lower() role = msg_config.get("role", "user").lower()
content_template = msg_config.get("content", "") content_template = msg_config.get("content", "")
content_template = self._render_context(content_template, state)
content = self._render_template(content_template, state) content = self._render_template(content_template, state)
# 根据角色创建对应的消息对象 # 根据角色创建对应的消息对象
@@ -153,7 +163,7 @@ class LLMNode(BaseNode):
Returns: Returns:
LLM 响应消息 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 调用(非流式)") logger.info(f"节点 {self.node_id} 开始执行 LLM 调用(非流式)")

View File

@@ -24,7 +24,7 @@ class MemoryReadNode(BaseNode):
return await MemoryAgentService().read_memory( return await MemoryAgentService().read_memory(
group_id=end_user_id, 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, config_id=self.typed_config.config_id,
search_switch=self.typed_config.search_switch, search_switch=self.typed_config.search_switch,
history=[], history=[],
@@ -51,7 +51,7 @@ class MemoryWriteNode(BaseNode):
return await MemoryAgentService().write_memory( return await MemoryAgentService().write_memory(
group_id=end_user_id, 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, config_id=self.typed_config.config_id,
db=db, db=db,
storage_type="neo4j", storage_type="neo4j",

View File

@@ -65,7 +65,7 @@ class QuestionClassifierNode(BaseNode):
category_map[category_name] = case_tag category_map[category_name] = case_tag
return category_map return category_map
async def execute(self, state: WorkflowState) -> str: async def execute(self, state: WorkflowState) -> dict:
"""执行问题分类""" """执行问题分类"""
question = self.typed_config.input_variable question = self.typed_config.input_variable
supplement_prompt = self.typed_config.user_supplement_prompt or "" supplement_prompt = self.typed_config.user_supplement_prompt or ""
@@ -79,7 +79,15 @@ class QuestionClassifierNode(BaseNode):
f"(默认分支:{DEFAULT_EMPTY_QUESTION_CASE},分类总数:{category_count}" f"(默认分支:{DEFAULT_EMPTY_QUESTION_CASE},分类总数:{category_count}"
) )
# 若分类列表为空返回默认unknown分支否则返回CASE1 # 若分类列表为空返回默认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: try:
llm = self._get_llm_instance() llm = self._get_llm_instance()
@@ -111,7 +119,10 @@ class QuestionClassifierNode(BaseNode):
log_supplement = supplement_prompt if supplement_prompt else "" log_supplement = supplement_prompt if supplement_prompt else ""
logger.info(f"节点 {self.node_id} 分类结果: {category}, 用户补充提示词:{log_supplement}") 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: except Exception as e:
logger.error( logger.error(
f"节点 {self.node_id} 分类执行异常:{str(e)}", f"节点 {self.node_id} 分类执行异常:{str(e)}",
@@ -119,5 +130,11 @@ class QuestionClassifierNode(BaseNode):
) )
# 异常时返回默认分支,保证工作流容错性 # 异常时返回默认分支,保证工作流容错性
if category_count > 0: if category_count > 0:
return DEFAULT_EMPTY_QUESTION_CASE return {
return "unknown" "class_name": category_names[0],
"output": DEFAULT_EMPTY_QUESTION_CASE
}
return {
"class_name": "unknown",
"output": DEFAULT_EMPTY_QUESTION_CASE
}

View File

@@ -1,4 +1,6 @@
from pydantic import Field from pydantic import Field
from typing import Any
from app.core.workflow.nodes.base_config import BaseNodeConfig from app.core.workflow.nodes.base_config import BaseNodeConfig
@@ -6,4 +8,4 @@ class ToolNodeConfig(BaseNodeConfig):
"""工具节点配置""" """工具节点配置"""
tool_id: str = Field(..., description="工具ID") 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="工具参数映射,支持工作流变量")

View File

@@ -1,5 +1,5 @@
import logging import logging
import uuid import re
from typing import Any from typing import Any
from app.core.workflow.nodes.base_node import BaseNode, WorkflowState 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__) logger = logging.getLogger(__name__)
TEMPLATE_PATTERN = re.compile(r"\{\{.*?\}\}")
class ToolNode(BaseNode): class ToolNode(BaseNode):
"""工具节点""" """工具节点"""
@@ -25,25 +27,33 @@ class ToolNode(BaseNode):
# 如果没有租户ID尝试从工作流ID获取 # 如果没有租户ID尝试从工作流ID获取
if not tenant_id: if not tenant_id:
workflow_id = self.get_variable("sys.workflow_id", state) workspace_id = self.get_variable("sys.workspace_id", state)
if workflow_id: if workspace_id:
from app.repositories.tool_repository import ToolRepository from app.repositories.tool_repository import ToolRepository
with get_db_read() as db: 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: if not tenant_id:
tenant_id = uuid.UUID("6c2c91b0-3f49-4489-9157-2208aa56a097") logger.error(f"节点 {self.node_id} 缺少租户ID")
# logger.error(f"节点 {self.node_id} 缺少租户ID") return {
# return {"error": "缺少租户ID"} "success": False,
"data": "缺少租户ID"
}
# 渲染工具参数 # 渲染工具参数
rendered_parameters = {} rendered_parameters = {}
for param_name, param_template in self.typed_config.tool_parameters.items(): 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 rendered_parameters[param_name] = rendered_value
logger.info(f"节点 {self.node_id} 执行工具 {self.typed_config.tool_id},参数: {rendered_parameters}") 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: with get_db_read() as db:
@@ -54,7 +64,7 @@ class ToolNode(BaseNode):
tenant_id=tenant_id, tenant_id=tenant_id,
user_id=user_id user_id=user_id
) )
print(result)
if result.success: if result.success:
logger.info(f"节点 {self.node_id} 工具执行成功") logger.info(f"节点 {self.node_id} 工具执行成功")
return { return {
@@ -66,7 +76,7 @@ class ToolNode(BaseNode):
logger.error(f"节点 {self.node_id} 工具执行失败: {result.error}") logger.error(f"节点 {self.node_id} 工具执行失败: {result.error}")
return { return {
"success": False, "success": False,
"error": result.error, "data": result.error,
"error_code": result.error_code, "error_code": result.error_code,
"execution_time": result.execution_time "execution_time": result.execution_time
} }

View File

@@ -87,10 +87,11 @@ class WorkflowValidator:
return graphs return graphs
@classmethod @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: Args:
publish: 发布验证标识
workflow_config: 工作流配置字典或 WorkflowConfig Pydantic 模型 workflow_config: 工作流配置字典或 WorkflowConfig Pydantic 模型
Returns: Returns:
@@ -114,7 +115,7 @@ class WorkflowValidator:
graphs = cls.get_subgraph(workflow_config) graphs = cls.get_subgraph(workflow_config)
logger.info(graphs) logger.info(graphs)
for graph in graphs: for index, graph in enumerate(graphs):
nodes = graph.get("nodes", []) nodes = graph.get("nodes", [])
edges = graph.get("edges", []) edges = graph.get("edges", [])
variables = graph.get("variables", []) variables = graph.get("variables", [])
@@ -125,10 +126,11 @@ class WorkflowValidator:
elif len(start_nodes) > 1: elif len(start_nodes) > 1:
errors.append(f"工作流只能有一个 start 节点,当前有 {len(start_nodes)}") errors.append(f"工作流只能有一个 start 节点,当前有 {len(start_nodes)}")
# 2. 验证 end 节点(至少一个) if index == len(graphs) - 1:
end_nodes = [n for n in nodes if n.get("type") == NodeType.END] # 2. 验证 主图end 节点(至少一个)
if len(end_nodes) == 0: end_nodes = [n for n in nodes if n.get("type") == NodeType.END]
errors.append("工作流必须至少有一个 end 节点") if len(end_nodes) == 0:
errors.append("工作流必须至少有一个 end 节点")
# 3. 验证节点 ID 唯一性 # 3. 验证节点 ID 唯一性
node_ids = [n.get("id") for n in nodes] node_ids = [n.get("id") for n in nodes]
@@ -159,15 +161,17 @@ class WorkflowValidator:
elif target not in node_id_set: elif target not in node_id_set:
errors.append(f"边 #{i} 的 target 节点不存在: {target}") errors.append(f"边 #{i} 的 target 节点不存在: {target}")
# 6. 验证所有节点可达(从 start 节点出发) if publish:
if start_nodes and not errors: # 只有在前面验证通过时才检查可达 # 仅在发布时验证所有节点可达
reachable = WorkflowValidator._get_reachable_nodes( # 6. 验证所有节点可达(从 start 节点出发)
start_nodes[0]["id"], if start_nodes and not errors: # 只有在前面验证通过时才检查可达性
edges reachable = WorkflowValidator._get_reachable_nodes(
) start_nodes[0]["id"],
unreachable = node_id_set - reachable edges
if unreachable: )
errors.append(f"以下节点无法从 start 节点到达: {unreachable}") unreachable = node_id_set - reachable
if unreachable:
errors.append(f"以下节点无法从 start 节点到达: {unreachable}")
# 7. 检测循环依赖(非 loop 节点) # 7. 检测循环依赖(非 loop 节点)
if not errors: # 只有在前面验证通过时才检查循环 if not errors: # 只有在前面验证通过时才检查循环
@@ -288,7 +292,7 @@ class WorkflowValidator:
(is_valid, errors): 是否有效和错误列表 (is_valid, errors): 是否有效和错误列表
""" """
# 先执行基础验证 # 先执行基础验证
is_valid, errors = WorkflowValidator.validate(workflow_config) is_valid, errors = WorkflowValidator.validate(workflow_config, publish=True)
if not is_valid: if not is_valid:
return False, errors return False, errors

View File

@@ -38,6 +38,33 @@ class ToolRepository:
return result[0] if result else None 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 @staticmethod
def find_by_tenant( def find_by_tenant(
db: Session, db: Session,

View File

@@ -231,9 +231,9 @@ class PromptOptimizerService:
if m: if m:
prompt_index = m.start() prompt_index = m.start()
prompt_finished = True prompt_finished = True
yield {"type": "delta", "content": buffer[idx:prompt_index]} yield {"content": buffer[idx:prompt_index]}
else: else:
yield {"type": "delta", "content": cache[idx:]} yield {"content": cache[idx:]}
if len(cache) != 0: if len(cache) != 0:
idx = len(cache) idx = len(cache)
@@ -249,8 +249,8 @@ class PromptOptimizerService:
role=RoleType.ASSISTANT, role=RoleType.ASSISTANT,
content=desc content=desc
) )
variables = self.parser_prompt_variables(optim_result.get("prompt"))
yield {"type": "done", "desc": optim_result.get("desc")} yield {"desc": optim_result.get("desc"), "variables": variables}
@staticmethod @staticmethod
def parser_prompt_variables(prompt: str): def parser_prompt_variables(prompt: str):

View File

@@ -344,14 +344,16 @@ class ToolService:
break break
if operation_param: if operation_param:
# 有多个操作 # 有多个操作,为每个操作生成具体参数
methods = [] methods = []
for operation in operation_param.enum: for operation in operation_param.enum:
# 获取该操作的具体参数
operation_params = self._get_operation_specific_params(tool_instance, operation)
methods.append({ methods.append({
"method_id": f"{config.name}_{operation}", "method_id": f"{config.name}_{operation}",
"name": operation, "name": operation,
"description": f"{config.description} - {operation}", "description": f"{config.description} - {operation}",
"parameters": [p for p in tool_instance.parameters if p.name != "operation"] "parameters": operation_params
}) })
return methods return methods
else: else:
@@ -363,6 +365,243 @@ class ToolService:
"parameters": [p for p in tool_instance.parameters if p.name != "operation"] "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]]: async def _get_custom_tool_methods(self, config: ToolConfig) -> List[Dict[str, Any]]:
"""获取自定义工具的方法""" """获取自定义工具的方法"""
custom_config = self.custom_repo.find_by_tool_id(self.db, config.id) custom_config = self.custom_repo.find_by_tool_id(self.db, config.id)

View File

@@ -296,3 +296,13 @@ export const getKnowledgeGraphEntityTypes = async (query: any) => {
const response = await request.get(`${apiPrefix}/knowledges/knowledge_graph_entity_types`,query); const response = await request.get(`${apiPrefix}/knowledges/knowledge_graph_entity_types`,query);
return response ; return response ;
}; };
// 删除图谱
export const deleteKnowledgeGraph = async (kb_id: string) => {
const response = await request.delete(`${apiPrefix}/knowledges/${kb_id}/knowledge_graph`);
return response;
};
// 知识库图谱重建
export const rebuildKnowledgeGraph = async (kb_id: string) => {
const response = await request.post(`${apiPrefix}/knowledges/${kb_id}/knowledge_graph`);
return response;
};

Binary file not shown.

After

Width:  |  Height:  |  Size: 936 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 568 B

View File

@@ -726,6 +726,11 @@ export const en = {
graphTips: 'Explore the entity nodes in the knowledge base and their relationship networks', graphTips: 'Explore the entity nodes in the knowledge base and their relationship networks',
sourceDocuments: 'Source Documents', sourceDocuments: 'Source Documents',
rebuildGraph: 'Rebuild Graph', rebuildGraph: 'Rebuild Graph',
rebuildConfirmTitle: 'Confirm the rebuild graph',
rebuildConfirmContent: 'The rebuild graph will erase the existing map data and rebuild it from scratch. This operation is irreversible. Are you sure you want to proceed?',
deleteGraphSuccess: 'Knowledge graph deletion successful',
deleteGraphFailed:'Knowledge graph deletion failed',
graphEmpty: 'At the foot of the mountain of books, the journey begins.',
createForm:{ createForm:{
name: 'Name', name: 'Name',
embedding_id: 'Embedding', embedding_id: 'Embedding',
@@ -1793,12 +1798,20 @@ Memory Bear: After the rebellion, regional warlordism intensified for several re
"not_contains": 'Does Not Contain', "not_contains": 'Does Not Contain',
"startwith": 'Starts With', "startwith": 'Starts With',
"endwith": 'Ends With', "endwith": 'Ends With',
"eq": '==', "eq": 'Equals',
"ne": '!=', "ne": 'Not Equals',
"lt": '<', num: {
"le": '<=', "eq": '=',
"gt": '>', "ne": '',
"ge": '>=', "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.' else_desc: 'Used to define the logic that should be executed when the if condition is not met.'
}, },
'http-request': { 'http-request': {
@@ -1839,12 +1852,17 @@ Memory Bear: After the rebellion, regional warlordism intensified for several re
loop: { loop: {
cycle_vars: 'Loop Variables', cycle_vars: 'Loop Variables',
condition: 'Loop Termination Condition', condition: 'Loop Termination Condition',
max_loop: 'Maximum Loop Count',
}, },
assigner: { assigner: {
assignments: 'Variables', assignments: 'Variables',
cover: 'Overwrite', cover: 'Override',
assign: 'Set', assign: 'Set',
clear: 'Clear' clear: 'Clear',
add: '+=',
subtract: '-=',
multiply: '*=',
divide: '/=',
}, },
iteration: { iteration: {
input: 'Input Variable', input: 'Input Variable',

View File

@@ -336,6 +336,11 @@ export const zh = {
graphTitle: '知识图谱:实体、关系与属性的关联网络', graphTitle: '知识图谱:实体、关系与属性的关联网络',
graphTips: '探索知识库中的实体节点及其关系脉络', graphTips: '探索知识库中的实体节点及其关系脉络',
rebuildGraph: '重建图谱', rebuildGraph: '重建图谱',
rebuildConfirmTitle: '确认重建图谱',
rebuildConfirmContent: '重建图谱将清除现有的图谱数据并重新构建,此操作不可逆。确定要继续吗?',
deleteGraphSuccess: '删除知识图谱成功',
deleteGraphFailed:'删除知识图谱失败',
graphEmpty: '书山有路,此处为始',
createForm: { createForm: {
name: '名称', name: '名称',
embedding_id: '嵌入模型', embedding_id: '嵌入模型',
@@ -1893,12 +1898,20 @@ export const zh = {
"not_contains": '不包含', "not_contains": '不包含',
"startwith": '开始是', "startwith": '开始是',
"endwith": '结束是', "endwith": '结束是',
"eq": '==', "eq": '',
"ne": '!=', "ne": '不是',
"lt": '<', num: {
"le": '<=', "eq": '=',
"gt": '>', "ne": '',
"ge": '>=', "lt": '<',
"le": '≤',
"gt": '>',
"ge": '≥',
},
boolean: {
"eq": '是',
"ne": '不是',
},
else_desc: '用于定义当 if 条件不满足时应执行的逻辑。' else_desc: '用于定义当 if 条件不满足时应执行的逻辑。'
}, },
'http-request': { 'http-request': {
@@ -1939,12 +1952,17 @@ export const zh = {
loop: { loop: {
cycle_vars: '循环变量', cycle_vars: '循环变量',
condition: '循环终止条件', condition: '循环终止条件',
max_loop: '最大循环次数',
}, },
assigner: { assigner: {
assignments: '变量', assignments: '变量',
cover: '覆盖', cover: '覆盖',
assign: '设置', assign: '设置',
clear: '清空' clear: '清空',
add: '+=',
subtract: '-=',
multiply: '*=',
divide: '/=',
}, },
iteration: { iteration: {
input: '输入变量', input: '输入变量',

View File

@@ -657,6 +657,7 @@ const Private: FC = () => {
const handleRefreshTable = () => { const handleRefreshTable = () => {
// 刷新表格数据 // 刷新表格数据
fetchKnowledgeBaseDetail(knowledgeBase.id)
tableRef.current?.loadData(); tableRef.current?.loadData();
} }
return ( return (

View File

@@ -7,7 +7,9 @@ import {
getModelList, getModelList,
createKnowledgeBase, createKnowledgeBase,
updateKnowledgeBase, updateKnowledgeBase,
getKnowledgeGraphEntityTypes getKnowledgeGraphEntityTypes,
deleteKnowledgeGraph,
rebuildKnowledgeGraph
} from '@/api/knowledgeBase' } from '@/api/knowledgeBase'
import RbModal from '@/components/RbModal' import RbModal from '@/components/RbModal'
const { TextArea } = Input; const { TextArea } = Input;
@@ -31,6 +33,7 @@ const CreateModal = forwardRef<CreateModalRef, CreateModalRefProps>(({
const [activeTab, setActiveTab] = useState('basic'); const [activeTab, setActiveTab] = useState('basic');
const [generatingEntityTypes, setGeneratingEntityTypes] = useState(false); const [generatingEntityTypes, setGeneratingEntityTypes] = useState(false);
const [isRebuildMode, setIsRebuildMode] = useState(false); const [isRebuildMode, setIsRebuildMode] = useState(false);
const [originalType, setOriginalType] = useState<string>(''); // 保存原始的 type 参数
// 监听 parser_config.graphrag 相关字段的变化 // 监听 parser_config.graphrag 相关字段的变化
const parserConfig = Form.useWatch('parser_config', form); const parserConfig = Form.useWatch('parser_config', form);
@@ -47,6 +50,7 @@ const CreateModal = forwardRef<CreateModalRef, CreateModalRefProps>(({
setLoading(false); setLoading(false);
setActiveTab('basic'); setActiveTab('basic');
setIsRebuildMode(false); // 重置重建模式标识 setIsRebuildMode(false); // 重置重建模式标识
setOriginalType(''); // 重置原始 type
setVisible(false); setVisible(false);
}; };
@@ -224,9 +228,12 @@ const CreateModal = forwardRef<CreateModalRef, CreateModalRefProps>(({
const handleOpen = (record?: KnowledgeBaseListItem | null, type?: string) => { const handleOpen = (record?: KnowledgeBaseListItem | null, type?: string) => {
setDatasets(record || null); setDatasets(record || null);
const nextType = type || currentType;
setCurrentType(nextType as any); // 如果是重建模式,使用记录的实际类型,否则使用传入的类型
const actualType = type === 'rebuild' ? (record?.type || 'General') : (type || currentType);
setCurrentType(actualType as any);
setIsRebuildMode(type === 'rebuild'); // 设置重建模式标识 setIsRebuildMode(type === 'rebuild'); // 设置重建模式标识
setOriginalType(type || ''); // 保存原始的 type 参数
// 如果是重建模式,默认切换到知识图谱标签页 // 如果是重建模式,默认切换到知识图谱标签页
if (type === 'rebuild') { if (type === 'rebuild') {
@@ -235,7 +242,7 @@ const CreateModal = forwardRef<CreateModalRef, CreateModalRefProps>(({
setActiveTab('basic'); setActiveTab('basic');
} }
setBaseFields(record || null, nextType); setBaseFields(record || null, actualType);
getTypeList(record || null); getTypeList(record || null);
setVisible(true); setVisible(true);
}; };
@@ -260,6 +267,39 @@ const CreateModal = forwardRef<CreateModalRef, CreateModalRefProps>(({
// 封装保存方法,添加提交逻辑 // 封装保存方法,添加提交逻辑
const handleSave = () => { const handleSave = () => {
// 获取当前表单中的知识图谱开启状态
const currentFormValues = form.getFieldsValue();
const isGraphragEnabled = currentFormValues?.parser_config?.graphrag?.use_graphrag || false;
// 如果原始 type 是 'rebuild' 并且知识图谱开启为true显示确认弹框
if (originalType === 'rebuild' && isGraphragEnabled) {
confirm({
title: t('knowledgeBase.rebuildConfirmTitle'),
content: t('knowledgeBase.rebuildConfirmContent'),
onOk: async() => {
handleDeleteGraph()
performSave();
await rebuildKnowledgeGraph(datasets?.id || '')
},
onCancel: () => {
// 用户取消,不执行任何操作
},
});
} else {
// 非重建模式或知识图谱未开启,直接保存
performSave();
}
};
const handleDeleteGraph = () => {
try{
deleteKnowledgeGraph(datasets?.id || '')
console.log(t('knowledgeBase.deleteGraphSuccess'))
}catch(e){
messageApi.error(t('knowledgeBase.deleteGraphFailed'))
}
};
// 实际的保存逻辑
const performSave = () => {
form form
.validateFields() .validateFields()
.then(() => { .then(() => {
@@ -276,9 +316,12 @@ const CreateModal = forwardRef<CreateModalRef, CreateModalRefProps>(({
formValues.parser_config.graphrag.entity_types = entityTypesArray; formValues.parser_config.graphrag.entity_types = entityTypesArray;
} }
// 确保保存时使用正确的类型(不是 'rebuild'
const saveType = originalType === 'rebuild' ? currentType : (formValues.type || currentType);
const payload: KnowledgeBaseFormData = { const payload: KnowledgeBaseFormData = {
...formValues, ...formValues,
type: formValues.type || currentType, type: saveType,
permission_id: formValues.permission_id || 'Private', permission_id: formValues.permission_id || 'Private',
parent_id: datasets?.parent_id || undefined, parent_id: datasets?.parent_id || undefined,
}; };

View File

@@ -4,7 +4,7 @@
* @Author: yujiangping * @Author: yujiangping
* @Date: 2025-12-30 15:07:37 * @Date: 2025-12-30 15:07:37
* @LastEditors: yujiangping * @LastEditors: yujiangping
* @LastEditTime: 2026-01-05 16:18:53 * @LastEditTime: 2026-01-05 20:28:51
*/ */
import React, { useState, useEffect } from 'react' import React, { useState, useEffect } from 'react'
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
@@ -38,7 +38,13 @@ const KnowledgeGraphCard: React.FC<KnowledgeGraphCardProps> = ({ knowledgeBase,
setLoading(true) setLoading(true)
try { try {
const res = await getKnowledgeGraph(knowledgeBase?.id) const res = await getKnowledgeGraph(knowledgeBase?.id)
setData(res as KnowledgeGraphResponse) // 判断 res.graph 是否为空对象或不存在
const graphResponse = res as KnowledgeGraphResponse;
if (!graphResponse || !graphResponse.graph || Object.keys(graphResponse.graph).length === 0) {
setData(undefined) // 设置为 undefined 以显示 empty 状态
} else {
setData(graphResponse)
}
} catch (error) { } catch (error) {
console.error('获取知识图谱数据失败:', error) console.error('获取知识图谱数据失败:', error)
} finally { } finally {
@@ -68,7 +74,10 @@ const KnowledgeGraphCard: React.FC<KnowledgeGraphCardProps> = ({ knowledgeBase,
</div> </div>
</div> </div>
<div className='rb:p-4 rb:pt-0'> <div className='rb:p-4 rb:pt-0'>
{knowledgeBase?.parser_config?.graphrag?.use_graphrag ? (<KnowledgeGraph data={data} loading={loading} />) : <Empty />} {knowledgeBase?.parser_config?.graphrag?.use_graphrag ?
(<KnowledgeGraph data={data} loading={loading} />)
:
<Empty title={t('knowledgeBase.graphEmpty')}/>}
</div> </div>
</div> </div>

View File

@@ -4,10 +4,9 @@ import {
Col, Col,
Tag, Tag,
List, List,
Space Flex
} from 'antd'; } from 'antd';
import { EyeOutlined } from '@ant-design/icons'; import { EyeOutlined } from '@ant-design/icons';
import clsx from 'clsx'
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import dayjs, { type Dayjs } from 'dayjs' import dayjs, { type Dayjs } from 'dayjs'
@@ -103,9 +102,9 @@ const Inner: React.FC<{ getStatusTag: (status: string) => ReactNode }> = ({ getS
<div className="rb:h-full rb:flex rb:flex-col rb:justify-between"> <div className="rb:h-full rb:flex rb:flex-col rb:justify-between">
<div className="rb:text-[12px] rb:leading-4 rb:font-regular rb:text-[#5B6167]"> <div className="rb:text-[12px] rb:leading-4 rb:font-regular rb:text-[#5B6167]">
{t(`tool.${item.config_data.tool_class}_features`)} <br /> {t(`tool.${item.config_data.tool_class}_features`)} <br />
<Space size={4} className="rb:mt-2"> <Flex gap={4} wrap className="rb:mt-2 rb:w-full">
{InnerConfigData[item.config_data.tool_class].features.map(vo => <Tag key={vo} color="default">{ t(`tool.${vo}`) }</Tag>) } {InnerConfigData[item.config_data.tool_class].features.map(vo => <Tag key={vo} color="default">{ t(`tool.${vo}`) }</Tag>) }
</Space> </Flex>
{item.config_data.tool_class === 'DateTimeTool' {item.config_data.tool_class === 'DateTimeTool'
? <div className="rb:mt-3 rb:bg-[#F0F3F8] rb:px-3 rb:py-2.5 rb:rounded-md"> ? <div className="rb:mt-3 rb:bg-[#F0F3F8] rb:px-3 rb:py-2.5 rb:rounded-md">

View File

@@ -26,7 +26,6 @@ const ChatVariableModal = forwardRef<ChatVariableModalRef, ChatVariableModalProp
const [form] = Form.useForm<ChatVariable>(); const [form] = Form.useForm<ChatVariable>();
const [loading, setLoading] = useState(false) const [loading, setLoading] = useState(false)
const [editIndex, setEditIndex] = useState<number | undefined>(undefined) const [editIndex, setEditIndex] = useState<number | undefined>(undefined)
const typeValue = Form.useWatch('type', form);
// 封装取消方法,添加关闭弹窗逻辑 // 封装取消方法,添加关闭弹窗逻辑
const handleClose = () => { const handleClose = () => {

View File

@@ -14,18 +14,23 @@ const CharacterCountPlugin = ({ setCount, onChange }: { setCount: (count: number
let serializedContent = ''; let serializedContent = '';
// Traverse all nodes and serialize properly // Traverse all nodes and serialize properly
const paragraphs: string[] = [];
root.getChildren().forEach(child => { root.getChildren().forEach(child => {
if ($isParagraphNode(child)) { if ($isParagraphNode(child)) {
let paragraphContent = '';
child.getChildren().forEach(node => { child.getChildren().forEach(node => {
if ($isVariableNode(node)) { if ($isVariableNode(node)) {
serializedContent += node.getTextContent(); paragraphContent += node.getTextContent();
} else { } else {
serializedContent += node.getTextContent(); paragraphContent += node.getTextContent();
} }
}); });
paragraphs.push(paragraphContent);
} }
}); });
serializedContent = paragraphs.join('\n');
setCount(serializedContent.length); setCount(serializedContent.length);
onChange?.(serializedContent); onChange?.(serializedContent);
}); });

View File

@@ -26,6 +26,7 @@ const InitialValuePlugin: React.FC<InitialValuePluginProps> = ({ value, options
parts.forEach(part => { parts.forEach(part => {
const match = part.match(/^\{\{([^.]+)\.([^}]+)\}\}$/); const match = part.match(/^\{\{([^.]+)\.([^}]+)\}\}$/);
const contextMatch = part.match(/^\{\{context\}\}$/); const contextMatch = part.match(/^\{\{context\}\}$/);
const conversationMatch = part.match(/^\{\{conv\.([^}]+)\}\}$/);
// 匹配{{context}}格式 // 匹配{{context}}格式
if (contextMatch) { if (contextMatch) {
@@ -38,6 +39,20 @@ const InitialValuePlugin: React.FC<InitialValuePluginProps> = ({ value, options
return 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}}格式 // 匹配普通变量{{nodeId.label}}格式
if (match) { if (match) {
const [_, nodeId, label] = match; const [_, nodeId, label] = match;

View File

@@ -14,12 +14,14 @@ const AddNode: ReactShapeConfig['component'] = ({ node, graph }) => {
const parentBBox = node.getBBox(); const parentBBox = node.getBBox();
const cycleId = data.cycle; const cycleId = data.cycle;
const id = `${selectedNodeType.type.replace(/-/g, '_') }_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
const newNode = graph.addNode({ const newNode = graph.addNode({
...(graphNodeLibrary[selectedNodeType.type] || graphNodeLibrary.default), ...(graphNodeLibrary[selectedNodeType.type] || graphNodeLibrary.default),
x: parentBBox.x, x: parentBBox.x,
y: parentBBox.y, y: parentBBox.y,
id,
data: { data: {
id: `${selectedNodeType.type}_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`, id,
type: selectedNodeType.type, type: selectedNodeType.type,
icon: selectedNodeType.icon, icon: selectedNodeType.icon,
name: t(`workflow.${selectedNodeType.type}`), name: t(`workflow.${selectedNodeType.type}`),

View File

@@ -76,11 +76,14 @@ const LoopNode: ReactShapeConfig['component'] = ({ node, graph }) => {
const centerX = parentBBox.x + 24; // 默认节点宽度的一半 const centerX = parentBBox.x + 24; // 默认节点宽度的一半
const centerY = parentBBox.y + 50; // 默认节点高度的一半 const centerY = parentBBox.y + 50; // 默认节点高度的一半
const cycleStartNodeId = `cycle_start_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
const cycleStartNode = graph.addNode({ const cycleStartNode = graph.addNode({
...graphNodeLibrary.cycleStart, ...graphNodeLibrary.cycleStart,
x: centerX, x: centerX,
y: centerY, y: centerY,
id: cycleStartNodeId,
data: { data: {
id: cycleStartNodeId,
type: 'cycle-start', type: 'cycle-start',
parentId: node.id, parentId: node.id,
isDefault: true, // 标记为默认节点,不可删除 isDefault: true, // 标记为默认节点,不可删除

View File

@@ -43,12 +43,14 @@ const PortClickHandler: React.FC<PortClickHandlerProps> = ({ graph }) => {
const newY = sourceBBox.y; const newY = sourceBBox.y;
// 创建新节点 // 创建新节点
const id = `${selectedNodeType.type.replace(/-/g, '_')}_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
const newNode = graph.addNode({ const newNode = graph.addNode({
...(graphNodeLibrary[selectedNodeType.type] || graphNodeLibrary.default), ...(graphNodeLibrary[selectedNodeType.type] || graphNodeLibrary.default),
x: newX, x: newX,
y: newY, y: newY,
id,
data: { data: {
id: `${selectedNodeType.type}_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`, id,
type: selectedNodeType.type, type: selectedNodeType.type,
icon: selectedNodeType.icon, icon: selectedNodeType.icon,
name: t(`workflow.${selectedNodeType.type}`), name: t(`workflow.${selectedNodeType.type}`),

View File

@@ -1,6 +1,6 @@
import { type FC } from 'react' import { type FC } from 'react'
import { useTranslation } from 'react-i18next'; 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 { MinusCircleOutlined, PlusOutlined } from '@ant-design/icons';
import type { Suggestion } from '../../Editor/plugin/AutocompletePlugin' import type { Suggestion } from '../../Editor/plugin/AutocompletePlugin'
import VariableSelect from '../VariableSelect' import VariableSelect from '../VariableSelect'
@@ -11,6 +11,23 @@ interface AssignmentListProps {
options: Suggestion[]; 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<AssignmentListProps> = ({ const AssignmentList: FC<AssignmentListProps> = ({
parentName, parentName,
options = [], options = [],
@@ -27,6 +44,11 @@ const AssignmentList: FC<AssignmentListProps> = ({
<PlusOutlined onClick={() => add({ operation: 'cover'})} /> <PlusOutlined onClick={() => add({ operation: 'cover'})} />
</div> </div>
{fields.map(({ key, name, ...restField }) => { {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 ( return (
<div key={key} className="rb:mb-4"> <div key={key} className="rb:mb-4">
<Row gutter={12} className="rb:mb-2!"> <Row gutter={12} className="rb:mb-2!">
@@ -50,11 +72,10 @@ const AssignmentList: FC<AssignmentListProps> = ({
noStyle noStyle
> >
<Select <Select
options={[ options={operationOptions.map(op => ({
{ value: 'cover', label: t('workflow.config.assigner.cover') }, ...op,
{ value: 'clear', label: t('workflow.config.assigner.clear') }, label: t(op.label)
{ value: 'assign', label: t('workflow.config.assigner.assign') }, }))}
]}
popupMatchSelectWidth={false} popupMatchSelectWidth={false}
onChange={() => { onChange={() => {
form.setFieldValue([parentName, name, 'value'], undefined); form.setFieldValue([parentName, name, 'value'], undefined);
@@ -77,20 +98,31 @@ const AssignmentList: FC<AssignmentListProps> = ({
{...restField} {...restField}
name={[name, 'value']} name={[name, 'value']}
noStyle noStyle
rules={[{ required: true, message: 'Missing last name' }]}
> >
{operation === 'assign' ? ( {operation === 'assign'
<Input.TextArea ? <>
placeholder={t('common.pleaseEnter')} {dataType === 'number'
rows={3} ? <InputNumber
/> placeholder={t('common.pleaseEnter')}
) : ( className="rb:w-full!"
<VariableSelect />
: dataType === 'boolean'
? <Radio.Group block>
<Radio.Button value={true}>True</Radio.Button>
<Radio.Button value={false}>False</Radio.Button>
</Radio.Group>
: <Input.TextArea
placeholder={t('common.pleaseEnter')}
rows={3}
/>
}
</>
: <VariableSelect
placeholder={t('common.pleaseSelect')} placeholder={t('common.pleaseSelect')}
options={options} options={dataType ? options.filter(vo => vo.dataType === dataType) : options}
popupMatchSelectWidth={false} popupMatchSelectWidth={false}
/> />
)} }
</Form.Item> </Form.Item>
); );
}} }}

View File

@@ -1,7 +1,7 @@
import { type FC } from 'react' import { type FC } from 'react'
import clsx from 'clsx' import clsx from 'clsx'
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { Form, Button, Select, Space, Row, Col, Divider } from 'antd' import { Form, Button, Select, Space, Row, Col, Divider, InputNumber, Radio, type SelectProps } from 'antd'
import { DeleteOutlined } from '@ant-design/icons'; import { DeleteOutlined } from '@ant-design/icons';
import type { Suggestion } from '../../Editor/plugin/AutocompletePlugin' import type { Suggestion } from '../../Editor/plugin/AutocompletePlugin'
@@ -9,37 +9,48 @@ import VariableSelect from '../VariableSelect'
import Editor from '../../Editor' import Editor from '../../Editor'
interface CaseListProps { interface CaseListProps {
value?: Array<{ logical_operator: 'and' | 'or'; expressions: { left: string; comparison_operator: string; right: string; }[] }>; value?: Array<{ logical_operator: 'and' | 'or'; expressions: { left: string; comparison_operator: string; right: string; input_type?: string; }[] }>;
onChange?: (value: Array<{ logical_operator: 'and' | 'or'; expressions: { left: string; comparison_operator: string; right: string; }[] }>) => void; onChange?: (value: Array<{ logical_operator: 'and' | 'or'; expressions: { left: string; comparison_operator: string; right: string; }[] }>) => void;
options: Suggestion[]; options: Suggestion[];
name: string; name: string;
selectedNode?: any; selectedNode?: any;
graphRef?: any; graphRef?: any;
} }
const operatorList = [ const operatorsObj: { [key: string]: SelectProps['options'] } = {
"empty", default: [
"not_empty", { value: 'empty', label: 'workflow.config.if-else.empty' },
"contains", { value: 'not_empty', label: 'workflow.config.if-else.not_empty' },
"not_contains", { value: 'contains', label: 'workflow.config.if-else.contains' },
"startwith", { value: 'not_contains', label: 'workflow.config.if-else.not_contains' },
"endwith", { value: 'startwith', label: 'workflow.config.if-else.startwith' },
"eq", { value: 'endwith', label: 'workflow.config.if-else.endwith' },
"ne", { value: 'eq', label: 'workflow.config.if-else.eq' },
"lt", { value: 'ne', label: 'workflow.config.if-else.ne' },
"le", ],
"gt", number: [
"ge" { value: 'eq', label: 'workflow.config.if-else.num.eq' },
] { value: 'ne', label: 'workflow.config.if-else.num.ne' },
{ value: 'lt', label: 'workflow.config.if-else.num.lt' },
{ value: 'le', label: 'workflow.config.if-else.num.le' },
{ value: 'gt', label: 'workflow.config.if-else.num.gt' },
{ value: 'ge', label: 'workflow.config.if-else.num.ge' },
{ value: 'empty', label: 'workflow.config.if-else.empty' },
{ value: 'not_empty', label: 'workflow.config.if-else.not_empty' },
],
boolean: [
{ value: 'eq', label: 'workflow.config.if-else.boolean.eq' },
{ value: 'ne', label: 'workflow.config.if-else.boolean.ne' },
]
}
const CaseList: FC<CaseListProps> = ({ const CaseList: FC<CaseListProps> = ({
value = [],
options, options,
name, name,
onChange,
selectedNode, selectedNode,
graphRef graphRef
}) => { }) => {
const { t } = useTranslation(); const { t } = useTranslation();
const form = Form.useFormInstance();
const updateNodePorts = (caseCount: number, removedCaseIndex?: number) => { const updateNodePorts = (caseCount: number, removedCaseIndex?: number) => {
if (!selectedNode || !graphRef?.current) return; if (!selectedNode || !graphRef?.current) return;
@@ -175,29 +186,49 @@ const CaseList: FC<CaseListProps> = ({
}); });
}, 50); }, 50);
}; };
const handleChangeLogicalOperator = (index: number) => { const handleChangeLogicalOperator = (index: number) => {
const newValue = [...value] const currentValue = form.getFieldValue([name, index, 'logical_operator']);
newValue[index] = { form.setFieldValue([name, index, 'logical_operator'], currentValue === 'and' ? 'or' : 'and');
...newValue[index], };
logical_operator: newValue[index].logical_operator === 'and' ? 'or' : 'and'
} const handleLeftFieldChange = (caseIndex: number, conditionIndex: number, newValue: string) => {
onChange && onChange(newValue) form.setFieldsValue({
} [name]: {
[caseIndex]: {
expressions: {
[conditionIndex]: {
left: newValue,
comparison_operator: undefined,
right: undefined,
input_type: undefined
}
}
}
}
});
};
const handleAddCase = (addCaseFunc: Function) => { const handleAddCase = (addCaseFunc: Function) => {
addCaseFunc({ logical_operator: 'and', expressions: [] }); addCaseFunc({ logical_operator: 'and', expressions: [] });
setTimeout(() => { setTimeout(() => {
updateNodePorts((value?.length || 0) + 1); const currentCases = form.getFieldValue(name) || [];
updateNodePorts(currentCases.length);
}, 100); }, 100);
}; };
const handleRemoveCase = (removeCaseFunc: Function, fieldName: number, caseIndex: number) => { const handleRemoveCase = (removeCaseFunc: Function, fieldName: number, caseIndex: number) => {
removeCaseFunc(fieldName); removeCaseFunc(fieldName);
setTimeout(() => { setTimeout(() => {
updateNodePorts((value?.length || 1) - 1, caseIndex); const currentCases = form.getFieldValue(name) || [];
updateNodePorts(currentCases.length, caseIndex);
}, 100); }, 100);
}; };
const handleInputTypeChange = (caseIndex: number, conditionIndex: number) => {
form.setFieldValue([name, caseIndex, 'expressions', conditionIndex, 'right'], undefined);
};
return ( return (
<> <>
<Form.List name={name}> <Form.List name={name}>
@@ -218,7 +249,7 @@ const CaseList: FC<CaseListProps> = ({
<Space> <Space>
<Button <Button
type="dashed" type="dashed"
onClick={() => addCondition()} onClick={() => addCondition({})}
size="small" size="small"
> >
+ {t('workflow.config.addCase')} + {t('workflow.config.addCase')}
@@ -234,15 +265,23 @@ const CaseList: FC<CaseListProps> = ({
<div className="rb:absolute rb:w-3 rb:left-2 rb:top-15 rb:bottom-6 rb:z-10 rb:border rb:border-[#DFE4ED] rb:rounded-l-md rb:border-r-0"></div> <div className="rb:absolute rb:w-3 rb:left-2 rb:top-15 rb:bottom-6 rb:z-10 rb:border rb:border-[#DFE4ED] rb:rounded-l-md rb:border-r-0"></div>
<div className="rb:absolute rb:z-10 rb:left-0 rb:top-[50%] rb:transform-[translateY(-50%)]]"> <div className="rb:absolute rb:z-10 rb:left-0 rb:top-[50%] rb:transform-[translateY(-50%)]]">
<Form.Item name={[caseField.name, 'logical_operator']} noStyle > <Form.Item name={[caseField.name, 'logical_operator']} noStyle >
<Button size="small" className="rb:cursor-pointer" onClick={() => handleChangeLogicalOperator(caseIndex)}>{value?.[caseIndex].logical_operator}</Button> <Button size="small" className="rb:cursor-pointer" onClick={() => handleChangeLogicalOperator(caseIndex)}>{logicalOperator}</Button>
</Form.Item> </Form.Item>
</div> </div>
</> </>
} }
{conditionFields.map((conditionField, conditionIndex) => { {conditionFields.map((conditionField, conditionIndex) => {
const currentOperator = value?.[caseIndex]?.expressions?.[conditionIndex]?.comparison_operator; const cases = form.getFieldValue(name) || [];
const currentCase = cases[caseIndex] || {};
const currentExpression = currentCase.expressions?.[conditionIndex] || {};
const currentOperator = currentExpression.comparison_operator;
const hideRightField = currentOperator === 'empty' || currentOperator === 'not_empty'; const hideRightField = currentOperator === 'empty' || currentOperator === 'not_empty';
const leftFieldValue = currentExpression.left;
const leftFieldOption = options.find(option => `{{${option.value}}}` === leftFieldValue);
const leftFieldType = leftFieldOption?.dataType;
const operatorList = operatorsObj[leftFieldType || 'default'] || operatorsObj.default || [];
const inputType = leftFieldType === 'number' ? currentExpression.input_type : undefined;
const logicalOperator = currentCase.logical_operator;
return ( return (
<div key={conditionField.key} className={clsx({ <div key={conditionField.key} className={clsx({
"rb:mb-3": conditionIndex !== conditionFields.length - 1 "rb:mb-3": conditionIndex !== conditionFields.length - 1
@@ -257,18 +296,20 @@ const CaseList: FC<CaseListProps> = ({
size="small" size="small"
allowClear={false} allowClear={false}
popupMatchSelectWidth={false} popupMatchSelectWidth={false}
onChange={(val) => handleLeftFieldChange(caseIndex, conditionIndex, val)}
/> />
</Form.Item> </Form.Item>
</Col> </Col>
<Col span={8}> <Col span={8}>
<Form.Item name={[conditionField.name, 'comparison_operator']} noStyle> <Form.Item name={[conditionField.name, 'comparison_operator']} noStyle>
<Select <Select
options={operatorList.map(key => ({ options={operatorList.map(vo => ({
value: key, ...vo,
label: t(`workflow.config.if-else.${key}`) label: t(String(vo?.label || ''))
}))} }))}
size="small" size="small"
popupMatchSelectWidth={false} popupMatchSelectWidth={false}
placeholder={t('common.pleaseSelect')}
/> />
</Form.Item> </Form.Item>
</Col> </Col>
@@ -280,11 +321,48 @@ const CaseList: FC<CaseListProps> = ({
</Col> </Col>
</Row> </Row>
{!hideRightField && ( {!hideRightField && <>
<Form.Item name={[conditionField.name, 'right']} noStyle> {leftFieldType === 'number'
<Editor options={options} /> ? <Row>
</Form.Item> <Col span={12}>
)} <Form.Item name={[conditionField.name, 'input_type']} noStyle>
<Select
placeholder={t('common.pleaseSelect')}
options={[{ value: 'Variable', label: 'Variable' }, { value: 'Constant', label: 'Constant' }]}
popupMatchSelectWidth={false}
variant="borderless"
onChange={() => handleInputTypeChange(caseIndex, conditionIndex)}
/>
</Form.Item>
</Col>
<Col span={12}>
<Form.Item name={[conditionField.name, 'right']} noStyle>
{inputType === 'Variable'
?
<VariableSelect
placeholder={t('common.pleaseSelect')}
options={options.filter(vo => vo.dataType === 'number')}
allowClear={false}
popupMatchSelectWidth={false}
variant="borderless"
/>
: <InputNumber placeholder={t('common.pleaseEnter')}
variant="borderless" className="rb:w-full!" />
}
</Form.Item>
</Col>
</Row>
: <Form.Item name={[conditionField.name, 'right']} noStyle>
{leftFieldType === 'boolean'
? <Radio.Group block>
<Radio.Button value={true}>True</Radio.Button>
<Radio.Button value={false}>False</Radio.Button>
</Radio.Group>
: <Editor options={options} />
}
</Form.Item>
}
</>}
</div> </div>
</div> </div>
) )

View File

@@ -1,7 +1,6 @@
import { type FC } from 'react' import { type FC } from 'react'
import clsx from 'clsx'
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { Form, Button, Select, Space, Row, Col, Divider } from 'antd' import { Form, Button, Select, Row, Col, InputNumber, Radio, type SelectProps } from 'antd'
import { DeleteOutlined } from '@ant-design/icons'; import { DeleteOutlined } from '@ant-design/icons';
import type { Suggestion } from '../../Editor/plugin/AutocompletePlugin' import type { Suggestion } from '../../Editor/plugin/AutocompletePlugin'
@@ -10,7 +9,7 @@ import Editor from '../../Editor'
interface Case { interface Case {
logical_operator: 'and' | 'or'; logical_operator: 'and' | 'or';
expressions: Array<{ left: string; comparison_operator: string; right: string; }> expressions: Array<{ left: string; comparison_operator: string; right: string; input_type: string; }>
} }
interface CaseListProps { interface CaseListProps {
@@ -22,36 +21,63 @@ interface CaseListProps {
graphRef?: any; graphRef?: any;
addBtnText?: string; addBtnText?: string;
} }
const operatorList = [ const operatorsObj: { [key: string]: SelectProps['options'] } = {
"empty", default: [
"not_empty", { value: 'empty', label: 'workflow.config.if-else.empty' },
"contains", { value: 'not_empty', label: 'workflow.config.if-else.not_empty' },
"not_contains", { value: 'contains', label: 'workflow.config.if-else.contains' },
"startwith", { value: 'not_contains', label: 'workflow.config.if-else.not_contains' },
"endwith", { value: 'startwith', label: 'workflow.config.if-else.startwith' },
"eq", { value: 'endwith', label: 'workflow.config.if-else.endwith' },
"ne", { value: 'eq', label: 'workflow.config.if-else.eq' },
"lt", { value: 'ne', label: 'workflow.config.if-else.ne' },
"le", ],
"gt", number: [
"ge" { value: 'eq', label: 'workflow.config.if-else.num.eq' },
] { value: 'ne', label: 'workflow.config.if-else.num.ne' },
{ value: 'lt', label: 'workflow.config.if-else.num.lt' },
{ value: 'le', label: 'workflow.config.if-else.num.le' },
{ value: 'gt', label: 'workflow.config.if-else.num.gt' },
{ value: 'ge', label: 'workflow.config.if-else.num.ge' },
{ value: 'empty', label: 'workflow.config.if-else.empty' },
{ value: 'not_empty', label: 'workflow.config.if-else.not_empty' },
],
boolean: [
{ value: 'eq', label: 'workflow.config.if-else.boolean.eq' },
{ value: 'ne', label: 'workflow.config.if-else.boolean.ne' },
]
}
const ConditionList: FC<CaseListProps> = ({ const ConditionList: FC<CaseListProps> = ({
value,
options, options,
parentName, parentName,
onChange,
}) => { }) => {
const { t } = useTranslation(); const { t } = useTranslation();
const form = Form.useFormInstance();
const handleLeftFieldChange = (index: number, newValue: string) => {
form.setFieldsValue({
[parentName]: {
expressions: {
[index]: {
left: newValue,
comparison_operator: undefined,
right: undefined,
input_type: undefined
}
}
}
});
};
const handleInputTypeChange = (index: number) => {
form.setFieldValue([parentName, 'expressions', index, 'right'], undefined);
};
const handleChangeLogicalOperator = () => { const handleChangeLogicalOperator = () => {
if (!value) return; const currentValue = form.getFieldValue([parentName, 'logical_operator']);
onChange && onChange({ form.setFieldValue([parentName, 'logical_operator'], currentValue === 'and' ? 'or' : 'and');
logical_operator: value.logical_operator === 'and' ? 'or' : 'and', };
expressions: value.expressions || []
})
}
return ( return (
<> <>
<Form.List name={[parentName, 'expressions']}> <Form.List name={[parentName, 'expressions']}>
@@ -59,8 +85,16 @@ const ConditionList: FC<CaseListProps> = ({
<div> <div>
<div className="rb:relative"> <div className="rb:relative">
{fields.map((field, index) => { {fields.map((field, index) => {
const currentOperator = value?.expressions?.[index]?.comparison_operator; const expressions = form.getFieldValue([parentName, 'expressions']) || [];
const currentExpression = expressions[index] || {};
const currentOperator = currentExpression.comparison_operator;
const hideRightField = currentOperator === 'empty' || currentOperator === 'not_empty'; const hideRightField = currentOperator === 'empty' || currentOperator === 'not_empty';
const leftFieldValue = currentExpression.left;
const leftFieldOption = options.find(option => `{{${option.value}}}` === leftFieldValue);
const leftFieldType = leftFieldOption?.dataType;
const operatorList = operatorsObj[leftFieldType || 'default'] || operatorsObj.default || [];
const inputType = leftFieldType === 'number' ? currentExpression.input_type : undefined;
const logicalOperator = form.getFieldValue([parentName, 'logical_operator']);
return ( return (
<div key={field.key} className="rb:mb-3"> <div key={field.key} className="rb:mb-3">
@@ -68,7 +102,7 @@ const ConditionList: FC<CaseListProps> = ({
<div className="rb:absolute rb:w-3 rb:left-2 rb:top-3.75 rb:bottom-3.75 rb:z-10 rb:border rb:border-[#DFE4ED] rb:rounded-l-md rb:border-r-0"></div> <div className="rb:absolute rb:w-3 rb:left-2 rb:top-3.75 rb:bottom-3.75 rb:z-10 rb:border rb:border-[#DFE4ED] rb:rounded-l-md rb:border-r-0"></div>
<div className="rb:absolute rb:z-10 rb:left-0 rb:top-[50%] rb:transform-[translateY(-50%)]]"> <div className="rb:absolute rb:z-10 rb:left-0 rb:top-[50%] rb:transform-[translateY(-50%)]]">
<Form.Item name={[parentName, 'logical_operator']} noStyle > <Form.Item name={[parentName, 'logical_operator']} noStyle >
<Button size="small" className="rb:cursor-pointer" onClick={handleChangeLogicalOperator}>{value?.logical_operator}</Button> <Button size="small" className="rb:cursor-pointer" onClick={handleChangeLogicalOperator}>{logicalOperator}</Button>
</Form.Item> </Form.Item>
</div> </div>
</>)} </>)}
@@ -82,6 +116,7 @@ const ConditionList: FC<CaseListProps> = ({
size="small" size="small"
allowClear={false} allowClear={false}
popupMatchSelectWidth={false} popupMatchSelectWidth={false}
onChange={(val) => handleLeftFieldChange(index, val)}
/> />
</Form.Item> </Form.Item>
</Col> </Col>
@@ -89,9 +124,9 @@ const ConditionList: FC<CaseListProps> = ({
<Col span={8}> <Col span={8}>
<Form.Item name={[field.name, 'comparison_operator']} noStyle> <Form.Item name={[field.name, 'comparison_operator']} noStyle>
<Select <Select
options={operatorList.map(key => ({ options={operatorList.map(vo => ({
value: key, ...vo,
label: t(`workflow.config.if-else.${key}`) label: t(String(vo?.label || ''))
}))} }))}
size="small" size="small"
popupMatchSelectWidth={false} popupMatchSelectWidth={false}
@@ -105,13 +140,52 @@ const ConditionList: FC<CaseListProps> = ({
/> />
</Col> </Col>
{!hideRightField && ( {!hideRightField && <>
<Col span={24}> {leftFieldType === 'number'
<Form.Item name={[field.name, 'right']} noStyle> ? <Col span={24}><Row>
<Editor options={options} /> <Col span={12}>
</Form.Item> <Form.Item name={[field.name, 'input_type']} noStyle>
</Col> <Select
)} placeholder={t('common.pleaseSelect')}
options={[{ value: 'Variable', label: 'Variable' }, { value: 'Constant', label: 'Constant' }]}
popupMatchSelectWidth={false}
variant="borderless"
className="rb:w-full!"
onChange={() => handleInputTypeChange(index)}
/>
</Form.Item>
</Col>
<Col span={12}>
<Form.Item name={[field.name, 'right']} noStyle>
{inputType === 'Variable'
?
<VariableSelect
placeholder={t('common.pleaseSelect')}
options={options.filter(vo => vo.dataType === 'number')}
allowClear={false}
popupMatchSelectWidth={false}
variant="borderless"
className="rb:w-full!"
/>
: <InputNumber placeholder={t('common.pleaseEnter')}
variant="borderless" className="rb:w-full!" />
}
</Form.Item>
</Col>
</Row></Col>
: <Col span={24}>
<Form.Item name={[field.name, 'right']} noStyle>
{leftFieldType === 'boolean'
? <Radio.Group block>
<Radio.Button value={true}>True</Radio.Button>
<Radio.Button value={false}>False</Radio.Button>
</Radio.Group>
: <Editor options={options} />
}
</Form.Item>
</Col>
}
</>}
</Row> </Row>
</div> </div>

View File

@@ -65,7 +65,7 @@ const CycleVarsList: FC<CycleVarsListProps> = ({
label: `${childData.name || childData.type}.${key}`, label: `${childData.name || childData.type}.${key}`,
type: 'output', type: 'output',
dataType: 'string', dataType: 'string',
value: `{{${childData.id}.${key}}}`, value: `${childData.id}.${key}`,
nodeData: childData nodeData: childData
}); });
} }

View File

@@ -25,7 +25,6 @@ const GroupVariableList: FC<GroupVariableListProps> = ({
<Row gutter={12} className="rb:mb-2!"> <Row gutter={12} className="rb:mb-2!">
<Col span={12}> <Col span={12}>
<Form.Item <Form.Item
name={[name,0, 'key']}
noStyle noStyle
> >
{t('workflow.config.var-aggregator.variable')} {t('workflow.config.var-aggregator.variable')}
@@ -34,9 +33,8 @@ const GroupVariableList: FC<GroupVariableListProps> = ({
</Row> </Row>
<Form.Item <Form.Item
name={[name, 0, 'value']} name={name}
noStyle noStyle
rules={[{ required: true, message: 'Missing last name' }]}
> >
<VariableSelect <VariableSelect
placeholder={t('common.pleaseSelect')} placeholder={t('common.pleaseSelect')}
@@ -76,7 +74,6 @@ const GroupVariableList: FC<GroupVariableListProps> = ({
{...restField} {...restField}
name={[name, 'value']} name={[name, 'value']}
noStyle noStyle
rules={[{ required: true, message: 'Missing last name' }]}
> >
<VariableSelect <VariableSelect
placeholder={t('common.pleaseSelect')} placeholder={t('common.pleaseSelect')}

View File

@@ -1,4 +1,4 @@
import { useState, useEffect } from 'react'; import { useState, useEffect, useMemo } from 'react';
import { useTranslation } from 'react-i18next' import { useTranslation } from 'react-i18next'
import { Button, Select, Table } from 'antd'; import { Button, Select, Table } from 'antd';
import { PlusOutlined, DeleteOutlined } from '@ant-design/icons'; import { PlusOutlined, DeleteOutlined } from '@ant-design/icons';
@@ -33,104 +33,90 @@ const EditableTable: React.FC<EditableTableProps> = ({
const [rows, setRows] = useState<TableRow[]>([]); const [rows, setRows] = useState<TableRow[]>([]);
useEffect(() => { useEffect(() => {
console.log('EditableTable value', value)
if (Array.isArray(value)) { if (Array.isArray(value)) {
setRows([...value]) setRows([...value])
} else if (value && Object.keys(value).length > 0) { } else if (value && Object.keys(value).length > 0) {
// Only update if rows are empty or significantly different setRows(Object.entries(value).map(([key, val], index) => ({
const valueEntries = Object.entries(value) key: index.toString(),
if (rows.length === 0 || rows.length !== valueEntries.length) { name: key || '',
setRows(valueEntries.map(([key, val], index) => { value: val || '',
console.log('val', val) type: typeOptions.length > 0 ? typeOptions[0].value : undefined
return { })))
key: index.toString(),
name: key || '',
value: val || '',
type: typeOptions.length > 0 ? typeOptions[0].value : undefined
}
}))
}
} else { } else {
setRows([]) setRows([])
} }
}, [JSON.stringify(value), typeOptions.length]) }, [value, typeOptions])
const handleChange = (key: string, field: 'name' | 'value' | 'type', val: string) => { const handleChange = (key: string, field: 'name' | 'value' | 'type', val: string) => {
const newRows = [...rows.map(row => const newRows = rows.map(row =>
row.key === key ? { ...row, [field]: val } : row row.key === key ? { ...row, [field]: val } : row
)]; );
setRows(newRows); setRows(newRows);
onChange?.(newRows); onChange?.(newRows);
}; };
const handleAdd = () => { const handleAdd = () => {
const newKey = Date.now().toString(); const newRow: TableRow = {
if (typeOptions.length) { key: Date.now().toString(),
setRows([...rows, { key: newKey, name: '', value: '', type: typeOptions[0].value }]); name: '',
} else { value: '',
setRows([...rows, { key: newKey, name: '', value: '' }]); ...(typeOptions.length > 0 && { type: typeOptions[0].value })
} };
const newRows = [...rows, newRow];
setRows(newRows);
onChange?.(newRows);
}; };
const handleDelete = (key: string, index: number) => { const handleDelete = (key: string) => {
console.log('index', index) const newRows = rows.filter(row => row.key !== key);
setRows(newRows);
if (rows.length === 1) { onChange?.(newRows);
setRows([]);
onChange?.([]);
} else {
const newRows = rows.filter(row => row.key !== key);
setRows(newRows);
onChange?.(newRows);
}
}; };
const columns = typeOptions?.length > 0 ? [ const columns = useMemo(() => {
{ const baseColumns = [
title: t('workflow.config.name'), {
dataIndex: 'name', title: typeOptions.length > 0 ? t('workflow.config.name') : '键',
width: '45%', dataIndex: 'name',
render: (text: string, record: TableRow) => ( width: typeOptions.length > 0 ? '35%' : '45%',
<Editor render: (text: string, record: TableRow) => (
options={options} <Editor
value={text} options={options}
height={32} value={text}
variant="outlined" height={32}
onChange={(value) => handleChange(record.key, 'name', value)} variant="outlined"
/> onChange={(value) => handleChange(record.key, 'name', value || '')}
), />
}, ),
{ }
title: t('workflow.config.type'), ];
dataIndex: 'type',
width: '20%', if (typeOptions.length > 0) {
render: (text: string, record: TableRow) => ( baseColumns.push({
<Select title: t('workflow.config.type'),
value={text} dataIndex: 'type',
options={typeOptions} width: '20%',
onChange={(value) => { render: (text: string, record: TableRow) => (
console.log('value record', value) <Select
handleChange(record.key, 'type', value) value={text}
}} options={typeOptions}
/> onChange={(value) => handleChange(record.key, 'type', value)}
), />
}, ),
{ });
title: t('workflow.config.value'), }
baseColumns.push({
title: typeOptions.length > 0 ? t('workflow.config.value') : '值',
dataIndex: 'value', dataIndex: 'value',
width: '45%', width: typeOptions.length > 0 ? '35%' : '45%',
render: (text: string, record: TableRow) => { render: (text: string, record: TableRow) => {
if (record.type === 'file') { if (record.type === 'file') {
return ( return (
<VariableSelect <VariableSelect
options={options} options={options}
value={text} value={text}
onChange={(value) => { onChange={(value) => handleChange(record.key, 'value', value || '')}
console.log('value record', value)
handleChange(record.key, 'value', value)
}}
/> />
) )
} }
@@ -140,78 +126,41 @@ const EditableTable: React.FC<EditableTableProps> = ({
value={text} value={text}
height={32} height={32}
variant="outlined" variant="outlined"
onChange={(value) => { onChange={(value) => handleChange(record.key, 'value', value || '')}
console.log('value record', value)
handleChange(record.key, 'value', value)
}}
/> />
) )
}, },
}, });
{
baseColumns.push({
title: '', title: '',
dataIndex: 'actions',
width: '10%', width: '10%',
render: (_: any, record: TableRow, index: number) => ( render: (_: any, record: TableRow) => (
<Button <Button
type="text" type="text"
icon={<DeleteOutlined />} icon={<DeleteOutlined />}
onClick={() => handleDelete(record.key, index)} onClick={() => handleDelete(record.key)}
/> />
), ),
}, });
] : [
{ return baseColumns;
title: '键', }, [typeOptions, options, t]);
dataIndex: 'name',
width: '45%',
render: (text: string, record: TableRow) => (
<Editor
options={options}
value={text}
height={32}
variant="outlined"
onChange={(value) => handleChange(record.key, 'name', value)}
/>
),
},
{
title: '值',
dataIndex: 'value',
width: '45%',
render: (text: string, record: TableRow) => (
<Editor
options={options}
value={text}
height={32}
variant="outlined"
onChange={(value) => handleChange(record.key, 'value', value)}
/>
),
},
{
title: '',
width: '10%',
render: (_: any, record: TableRow, index: number) => (
<Button
type="text"
icon={<DeleteOutlined />}
onClick={() => handleDelete(record.key, index)}
/>
),
},
];
return ( return (
<div className="rb:mb-4"> <div className="rb:mb-4">
{title && <div className="rb:flex rb:items-center rb:mb-2 rb:justify-between"> {title && (
<div className="rb:font-medium">{title}</div> <div className="rb:flex rb:items-center rb:mb-2 rb:justify-between">
<Button <div className="rb:font-medium">{title}</div>
type="text" <Button
icon={<PlusOutlined />} type="text"
onClick={handleAdd} icon={<PlusOutlined />}
size="small" onClick={handleAdd}
/> size="small"
</div>} />
</div>
)}
<Table <Table
columns={columns} columns={columns}
dataSource={rows} dataSource={rows}
@@ -220,11 +169,11 @@ const EditableTable: React.FC<EditableTableProps> = ({
locale={{ emptyText: <Empty size={88} /> }} locale={{ emptyText: <Empty size={88} /> }}
scroll={{ x: 'max-content' }} scroll={{ x: 'max-content' }}
/> />
{!title && {!title && (
<Button type="dashed" onClick={handleAdd} block className='rb:mt-1'> <Button type="dashed" onClick={handleAdd} block className='rb:mt-1'>
+{t('common.add')} +{t('common.add')}
</Button> </Button>
} )}
</div> </div>
); );
}; };

View File

@@ -1,6 +1,6 @@
import { type FC, useEffect, useRef } from "react"; import { type FC, useRef } from "react";
import { useTranslation } from 'react-i18next' import { useTranslation } from 'react-i18next'
import { Form, Row, Col, Select, Button, Divider, InputNumber, Switch, Input, Slider } from 'antd' import { Form, Row, Col, Select, Button, Divider, InputNumber, Switch, Input } from 'antd'
import Editor from '../../Editor' import Editor from '../../Editor'
import type { Suggestion } from '../../Editor/plugin/AutocompletePlugin' import type { Suggestion } from '../../Editor/plugin/AutocompletePlugin'
import AuthConfigModal from './AuthConfigModal' import AuthConfigModal from './AuthConfigModal'

View File

@@ -128,29 +128,32 @@ const Knowledge: FC<{value?: KnowledgeConfig; onChange?: (config: KnowledgeConfi
<List <List
grid={{ gutter: 12, column: 1 }} grid={{ gutter: 12, column: 1 }}
dataSource={knowledgeList} dataSource={knowledgeList}
renderItem={(item) => ( renderItem={(item) => {
<List.Item> if (!item.id) return null
<div key={item.id} className="rb:flex rb:items-center rb:justify-between rb:p-[12px_16px] rb:bg-[#FBFDFF] rb:border rb:border-[#DFE4ED] rb:rounded-lg"> return (
<div className="rb:font-medium rb:leading-4"> <List.Item>
{item.name} <div key={item.id} className="rb:flex rb:items-center rb:justify-between rb:p-[12px_16px] rb:bg-[#FBFDFF] rb:border rb:border-[#DFE4ED] rb:rounded-lg">
<Tag color={item.status === 1 ? 'success' : item.status === 0 ? 'default' : 'error'} className="rb:ml-2"> <div className="rb:font-medium rb:leading-4">
{item.status === 1 ? t('common.enable') : item.status === 0 ? t('common.disabled') : t('common.deleted')} {item.name}
</Tag> <Tag color={item.status === 1 ? 'success' : item.status === 0 ? 'default' : 'error'} className="rb:ml-2">
<div className="rb:mt-1 rb:text-[12px] rb:text-[#5B6167] rb:font-regular rb:leading-5">{t('application.contains', {include_count: item.doc_num})}</div> {item.status === 1 ? t('common.enable') : item.status === 0 ? t('common.disabled') : t('common.deleted')}
</Tag>
<div className="rb:mt-1 rb:text-[12px] rb:text-[#5B6167] rb:font-regular rb:leading-5">{t('application.contains', {include_count: item.doc_num})}</div>
</div>
<Space size={12}>
<div
className="rb:w-6 rb:h-6 rb:cursor-pointer rb:bg-[url('@/assets/images/editBorder.svg')] rb:hover:bg-[url('@/assets/images/editBg.svg')]"
onClick={() => handleEditKnowledge(item)}
></div>
<div
className="rb:w-6 rb:h-6 rb:cursor-pointer rb:bg-[url('@/assets/images/deleteBorder.svg')] rb:hover:bg-[url('@/assets/images/deleteBg.svg')]"
onClick={() => handleDeleteKnowledge(item.id)}
></div>
</Space>
</div> </div>
<Space size={12}> </List.Item>
<div )
className="rb:w-6 rb:h-6 rb:cursor-pointer rb:bg-[url('@/assets/images/editBorder.svg')] rb:hover:bg-[url('@/assets/images/editBg.svg')]" }}
onClick={() => handleEditKnowledge(item)}
></div>
<div
className="rb:w-6 rb:h-6 rb:cursor-pointer rb:bg-[url('@/assets/images/deleteBorder.svg')] rb:hover:bg-[url('@/assets/images/deleteBg.svg')]"
onClick={() => handleDeleteKnowledge(item.id)}
></div>
</Space>
</div>
</List.Item>
)}
/> />
} }
{/* 全局设置 */} {/* 全局设置 */}

View File

@@ -1,12 +1,15 @@
import React from 'react'; import React from 'react';
import { useTranslation } from 'react-i18next' import { useTranslation } from 'react-i18next'
import { MinusCircleOutlined } from '@ant-design/icons'; import { MinusCircleOutlined } from '@ant-design/icons';
import { Button, Form, Input, Space } from 'antd'; import { Button, Form, Input, Space, Row, Col } from 'antd';
import type { Suggestion } from '../../Editor/plugin/AutocompletePlugin'
import VariableSelect from '../VariableSelect'
interface MappingListProps { interface MappingListProps {
name: string; name: string;
options: Suggestion[];
} }
const MappingList: React.FC<MappingListProps> = ({ name }) => { const MappingList: React.FC<MappingListProps> = ({ name, options }) => {
const { t } = useTranslation() const { t } = useTranslation()
return ( return (
<> <>
@@ -14,23 +17,33 @@ const MappingList: React.FC<MappingListProps> = ({ name }) => {
{(fields, { add, remove }) => ( {(fields, { add, remove }) => (
<> <>
{fields.map(({ key, name, ...restField }) => ( {fields.map(({ key, name, ...restField }) => (
<Space key={key} style={{ display: 'flex', marginBottom: 8 }} align="baseline"> <Row gutter={12} className="rb:mb-2">
<Form.Item <Col span={10}>
{...restField} <Form.Item
name={[name, 'name']} {...restField}
noStyle name={[name, 'name']}
> noStyle
<Input placeholder={t('common.pleaseEnter')} /> >
</Form.Item> <Input placeholder={t('common.pleaseEnter')} />
<Form.Item </Form.Item>
{...restField} </Col>
name={[name, 'value']} <Col span={12}>
noStyle <Form.Item
> {...restField}
<Input placeholder={t('common.pleaseEnter')} /> name={[name, 'value']}
</Form.Item> noStyle
<MinusCircleOutlined onClick={() => remove(name)} /> >
</Space> <VariableSelect
placeholder={t('common.pleaseSelect')}
options={options}
popupMatchSelectWidth={false}
/>
</Form.Item>
</Col>
<Col span={2}>
<MinusCircleOutlined onClick={() => remove(name)} />
</Col>
</Row>
))} ))}
<Form.Item> <Form.Item>
<Button type="dashed" onClick={() => add()} block> <Button type="dashed" onClick={() => add()} block>

View File

@@ -29,15 +29,15 @@ const MessageEditor: FC<TextareaProps> = ({
}) => { }) => {
const { t } = useTranslation() const { t } = useTranslation()
const form = Form.useFormInstance(); const form = Form.useFormInstance();
const values = form.getFieldsValue() const values = Form.useWatch([], form);
// 检查是否已经使用了context变量将已使用的context设置为disabled // 检查是否已经使用了context变量将已使用的context设置为disabled
const processedOptions = useMemo(() => { const processedOptions = useMemo(() => {
if (!isArray || !values[parentName]) return options; if (!isArray || !values?.[parentName]) return options;
// 获取所有消息内容 // 获取所有消息内容
const allContents = values[parentName] const allContents = values[parentName]
.map((msg: any) => msg.content || '') .map((msg: any) => msg?.content || '')
.join(' '); .join(' ');
// 将已使用的context变量标记为disabled // 将已使用的context变量标记为disabled
@@ -50,83 +50,74 @@ const MessageEditor: FC<TextareaProps> = ({
}, [options, values, parentName, isArray]); }, [options, values, parentName, isArray]);
const handleAdd = (add: FormListOperation['add']) => { const handleAdd = (add: FormListOperation['add']) => {
const list = values[parentName]; const list = values?.[parentName] || [];
const lastRole = list[list.length - 1].role const lastRole = list.length > 0 ? list[list.length - 1]?.role : 'ASSISTANT';
add({ add({
role: lastRole === 'USER' ? 'ASSISTANT' : 'USER', role: lastRole === 'USER' ? 'ASSISTANT' : 'USER',
content: undefined content: ''
}) });
};
if (!isArray) {
return (
<Space size={12} direction="vertical" className="rb:w-full rb:border rb:border-[#DFE4ED] rb:rounded-md rb:px-2 rb:py-1.5 rb:bg-white">
<Row>
<Col span={12}>
{title ?? t('workflow.answerDesc')}
</Col>
</Row>
<Form.Item name={parentName} noStyle>
<Editor placeholder={placeholder} options={processedOptions} />
</Form.Item>
</Space>
);
} }
return ( return (
<div> <Form.List name={parentName}>
{isArray {(fields, { add, remove }) => (
? <Form.List name={parentName}> <Space size={12} direction="vertical" className="rb:w-full">
{(fields, { add, remove }) => ( {fields.map(({ key, name, ...restField }) => {
<Space size={12} direction="vertical" className="rb:w-full"> const currentRole = (values?.[parentName]?.[name]?.role || 'USER').toUpperCase();
{fields.map(({ key, name, ...restField }) => {
const currentRole = (values[parentName]?.[key].role || 'USER').toUpperCase()
return ( return (
<Space key={key} size={12} direction="vertical" className="rb:w-full rb:border rb:border-[#DFE4ED] rb:rounded-md rb:px-2 rb:py-1.5 rb:bg-white"> <Space key={key} size={12} direction="vertical" className="rb:w-full rb:border rb:border-[#DFE4ED] rb:rounded-md rb:px-2 rb:py-1.5 rb:bg-white">
<Row> <Row>
<Col span={12}> <Col span={12}>
<Form.Item <Form.Item {...restField} name={[name, 'role']} noStyle>
{...restField} {currentRole === 'SYSTEM' ? (
name={[name, 'role']} <Input disabled />
noStyle ) : (
> <Select
{currentRole === 'SYSTEM' options={roleOptions}
? <Input disabled /> disabled={currentRole === 'SYSTEM'}
: />
<Select )}
options={roleOptions}
disabled={currentRole === 'SYSTEM'}
/>
}
</Form.Item>
</Col>
{currentRole !== 'SYSTEM' && <Col span={12}>
<div className="rb:h-full rb:flex rb:justify-end rb:items-center">
<MinusCircleOutlined onClick={() => remove(name)} />
</div>
</Col>}
</Row>
<Form.Item
{...restField}
name={[name, 'content']}
noStyle
>
<Editor placeholder={placeholder} options={processedOptions} />
</Form.Item> </Form.Item>
</Space> </Col>
) {currentRole !== 'SYSTEM' && (
})} <Col span={12}>
<Form.Item> <div className="rb:h-full rb:flex rb:justify-end rb:items-center">
<Button type="dashed" onClick={() => handleAdd(add)} block> <MinusCircleOutlined onClick={() => remove(name)} />
+{t('workflow.addMessage')} </div>
</Button> </Col>
</Form.Item> )}
</Space > </Row>
)} <Form.Item {...restField} name={[name, 'content']} noStyle>
</Form.List> <Editor placeholder={placeholder} options={processedOptions} />
: </Form.Item>
<Space size={12} direction="vertical" className="rb:w-full rb:border rb:border-[#DFE4ED] rb:rounded-md rb:px-2 rb:py-1.5 rb:bg-white"> </Space>
<Row> );
<Col span={12}> })}
{title ?? t('workflow.answerDesc')} <Form.Item>
</Col> <Button type="dashed" onClick={() => handleAdd(add)} block>
</Row> +{t('workflow.addMessage')}
<Form.Item </Button>
name={parentName}
noStyle
>
<Editor placeholder={placeholder} options={processedOptions} />
</Form.Item> </Form.Item>
</Space> </Space>
} )}
</div> </Form.List>
); );
}; };

View File

@@ -85,15 +85,6 @@ const Properties: FC<PropertiesProps> = ({
const { id, knowledge_retrieval, group, group_names, ...rest } = values const { id, knowledge_retrieval, group, group_names, ...rest } = values
const { knowledge_bases = [], ...restKnowledgeConfig } = (knowledge_retrieval as any) || {} const { knowledge_bases = [], ...restKnowledgeConfig } = (knowledge_retrieval as any) || {}
let groupNames: Record<string, string[]> | string[] = {}
if (group && group_names?.length) {
group_names.forEach(vo => {
(groupNames as Record<string, string[]>)[vo.key] = vo.value
})
} else if (!group) {
groupNames = group_names?.[0]?.value || []
}
let allRest = { let allRest = {
...rest, ...rest,
...restKnowledgeConfig, ...restKnowledgeConfig,
@@ -107,7 +98,14 @@ const Properties: FC<PropertiesProps> = ({
Object.keys(values).forEach(key => { Object.keys(values).forEach(key => {
if (selectedNode.data?.config?.[key]) { if (selectedNode.data?.config?.[key]) {
selectedNode.data.config[key].defaultValue = values[key] // Create a deep copy to avoid reference sharing between nodes
if (!selectedNode.data.config[key]) {
selectedNode.data.config[key] = {};
}
selectedNode.data.config[key] = {
...selectedNode.data.config[key],
defaultValue: values[key]
};
} }
}) })
@@ -194,7 +192,7 @@ const Properties: FC<PropertiesProps> = ({
const allPreviousNodeIds = getAllPreviousNodes(selectedNode.id); const allPreviousNodeIds = getAllPreviousNodes(selectedNode.id);
const childNodeIds = getChildNodes(selectedNode.id); const childNodeIds = getChildNodes(selectedNode.id);
console.log('childNodeIds', childNodeIds) console.log('childNodeIds', selectedNode, childNodeIds)
const allRelevantNodeIds = [...allPreviousNodeIds, ...childNodeIds]; const allRelevantNodeIds = [...allPreviousNodeIds, ...childNodeIds];
allRelevantNodeIds.forEach(nodeId => { allRelevantNodeIds.forEach(nodeId => {
@@ -219,7 +217,7 @@ const Properties: FC<PropertiesProps> = ({
label: variable.name, label: variable.name,
type: 'variable', type: 'variable',
dataType: variable.type, dataType: variable.type,
value: `{{${nodeId}.${variable.name}}}`, value: `${node.getData().id}.${variable.name}`,
nodeData: nodeData, nodeData: nodeData,
}); });
} }
@@ -249,7 +247,7 @@ const Properties: FC<PropertiesProps> = ({
label: 'output', label: 'output',
type: 'variable', type: 'variable',
dataType: 'String', dataType: 'String',
value: `${nodeId}.output`, value: `${node.getData().id}.output`,
nodeData: nodeData, nodeData: nodeData,
}); });
} }
@@ -263,7 +261,104 @@ const Properties: FC<PropertiesProps> = ({
label: 'message', label: 'message',
type: 'variable', type: 'variable',
dataType: 'array[object]', dataType: 'array[object]',
value: `${nodeId}.message`, value: `${node.getData().id}.message`,
nodeData: nodeData,
});
}
break
case 'parameter-extractor':
const successKey = `${nodeId}___is_success`;
const reasonKey = `${nodeId}___reason`;
if (!addedKeys.has(successKey)) {
addedKeys.add(successKey);
variableList.push({
key: successKey,
label: '__is_success',
type: 'variable',
dataType: 'number',
value: `${node.getData().id}.__is_success`,
nodeData: nodeData,
});
}
if (!addedKeys.has(reasonKey)) {
addedKeys.add(reasonKey);
variableList.push({
key: reasonKey,
label: '__reason',
type: 'variable',
dataType: 'string',
value: `${node.getData().id}.__reason`,
nodeData: nodeData,
});
}
// Add params variables
const paramsList = nodeData.config?.params?.defaultValue || [];
paramsList.forEach((param: any) => {
if (!param || !param?.name) return;
const paramKey = `${nodeId}_${param.name}`;
if (!addedKeys.has(paramKey)) {
addedKeys.add(paramKey);
variableList.push({
key: paramKey,
label: param.name,
type: 'variable',
dataType: param.type || 'string',
value: `${node.getData().id}.${param.name}`,
nodeData: nodeData,
});
}
});
break
case 'var-aggregator':
const varAggregatorKey = `${nodeId}_output`;
if (!addedKeys.has(varAggregatorKey)) {
addedKeys.add(varAggregatorKey);
variableList.push({
key: varAggregatorKey,
label: 'output',
type: 'variable',
dataType: 'string',
value: `${node.getData().id}.output`,
nodeData: nodeData,
});
}
break
case 'http-request':
const httpBodyKey = `${nodeId}_body`;
const httpStatusKey = `${nodeId}_status_code`;
if (!addedKeys.has(httpBodyKey)) {
addedKeys.add(httpBodyKey);
variableList.push({
key: httpBodyKey,
label: 'body',
type: 'variable',
dataType: 'string',
value: `${node.getData().id}.body`,
nodeData: nodeData,
});
}
if (!addedKeys.has(httpStatusKey)) {
addedKeys.add(httpStatusKey);
variableList.push({
key: httpStatusKey,
label: 'status_code',
type: 'variable',
dataType: 'number',
value: `${node.getData().id}.status_code`,
nodeData: nodeData,
});
}
break
case 'jinja-render':
const jinjaOutputKey = `${nodeId}_output`;
if (!addedKeys.has(jinjaOutputKey)) {
addedKeys.add(jinjaOutputKey);
variableList.push({
key: jinjaOutputKey,
label: 'output',
type: 'variable',
dataType: 'string',
value: `${node.getData().id}.output`,
nodeData: nodeData, nodeData: nodeData,
}); });
} }
@@ -283,7 +378,7 @@ const Properties: FC<PropertiesProps> = ({
label: variable.name, label: variable.name,
type: 'variable', type: 'variable',
dataType: variable.type, dataType: variable.type,
value: `conversation.${variable.name}`, value: `conv.${variable.name}`,
nodeData: { type: 'CONVERSATION', name: 'CONVERSATION', icon: '' }, nodeData: { type: 'CONVERSATION', name: 'CONVERSATION', icon: '' },
group: 'CONVERSATION' group: 'CONVERSATION'
}); });
@@ -387,7 +482,7 @@ const Properties: FC<PropertiesProps> = ({
label: 'context', label: 'context',
type: 'variable', type: 'variable',
dataType: 'String', dataType: 'String',
value: `{{context}}`, value: `context`,
nodeData: selectedNode.getData(), nodeData: selectedNode.getData(),
isContext: true, isContext: true,
}); });
@@ -476,7 +571,7 @@ const Properties: FC<PropertiesProps> = ({
<Form.Item key={key} name={key} <Form.Item key={key} name={key}
label={t(`workflow.config.${selectedNode?.data?.type}.${key}`)} label={t(`workflow.config.${selectedNode?.data?.type}.${key}`)}
> >
<MappingList name={key} /> <MappingList name={key} options={variableList} />
</Form.Item> </Form.Item>
) )
@@ -583,7 +678,7 @@ const Properties: FC<PropertiesProps> = ({
? <Input.TextArea placeholder={t('common.pleaseEnter')} /> ? <Input.TextArea placeholder={t('common.pleaseEnter')} />
: config.type === 'select' : config.type === 'select'
? <Select ? <Select
options={config.needTranslation ? config.options?.map(vo => ({ ...vo, label: t(vo.label) })) : config.options} options={config.needTranslation ? config.options?.map(vo => ({ ...vo, label: t(vo.label) })) : config.options}
placeholder={t('common.pleaseSelect')} placeholder={t('common.pleaseSelect')}
/> />
: config.type === 'inputNumber' : config.type === 'inputNumber'
@@ -635,7 +730,7 @@ const Properties: FC<PropertiesProps> = ({
} }
/> />
: config.type === 'switch' : config.type === 'switch'
? <Switch /> ? <Switch onChange={key === 'group' ? () => { form.setFieldValue('group_names', []) } : undefined} />
: config.type === 'categoryList' : config.type === 'categoryList'
? <CategoryList parentName={key} selectedNode={selectedNode} graphRef={graphRef} /> ? <CategoryList parentName={key} selectedNode={selectedNode} graphRef={graphRef} />
: config.type === 'conditionList' : config.type === 'conditionList'

View File

@@ -39,6 +39,9 @@ import processEvolutionIcon from '@/assets/images/workflow/process_evolution.png
import questionClassifierIcon from '@/assets/images/workflow/question-classifier.png' import questionClassifierIcon from '@/assets/images/workflow/question-classifier.png'
import breakIcon from '@/assets/images/workflow/break.png' import breakIcon from '@/assets/images/workflow/break.png'
import assignerIcon from '@/assets/images/workflow/assigner.png' import assignerIcon from '@/assets/images/workflow/assigner.png'
import memoryReadIcon from '@/assets/images/workflow/memory-read.png'
import memoryWriteIcon from '@/assets/images/workflow/memory-write.png'
import { memoryConfigListUrl } from '@/api/memory' import { memoryConfigListUrl } from '@/api/memory'
import { getModelListUrl } from '@/api/models' import { getModelListUrl } from '@/api/models'
@@ -159,6 +162,7 @@ export const nodeLibrary: NodeLibrary[] = [
}, },
text: { text: {
type: 'variableList', type: 'variableList',
filterLoopIterationVars: true
}, },
params: { params: {
type: 'paramList', type: 'paramList',
@@ -174,8 +178,7 @@ export const nodeLibrary: NodeLibrary[] = [
{ {
category: "cognitiveUpgrading", category: "cognitiveUpgrading",
nodes: [ nodes: [
{ { type: "memory-read", icon: memoryReadIcon,
type: "memory-read", icon: memoryEnhancementIcon,
config: { config: {
message: { message: {
type: 'messageEditor', type: 'messageEditor',
@@ -198,7 +201,7 @@ export const nodeLibrary: NodeLibrary[] = [
} }
} }
}, },
{ type: "memory-write", icon: memoryEnhancementIcon, { type: "memory-write", icon: memoryWriteIcon,
config: { config: {
message: { message: {
type: 'messageEditor', type: 'messageEditor',
@@ -272,6 +275,7 @@ export const nodeLibrary: NodeLibrary[] = [
}, },
parallel: { parallel: {
type: 'switch', type: 'switch',
defaultValue: false
}, },
parallel_count: { parallel_count: {
type: 'slider', type: 'slider',
@@ -284,6 +288,7 @@ export const nodeLibrary: NodeLibrary[] = [
}, },
flatten: { // 扁平化输出 flatten: { // 扁平化输出
type: 'switch', type: 'switch',
defaultValue: false
}, },
output: { output: {
type: 'variableList', type: 'variableList',
@@ -304,6 +309,13 @@ export const nodeLibrary: NodeLibrary[] = [
expressions: [] expressions: []
} }
}, },
max_loop: {
type: 'slider',
min: 1,
max: 100,
step: 1,
defaultValue: 10
},
} }
}, },
{ type: "cycle-start", icon: loopIcon }, { type: "cycle-start", icon: loopIcon },
@@ -317,7 +329,7 @@ export const nodeLibrary: NodeLibrary[] = [
}, },
group_names: { group_names: {
type: 'groupVariableList', type: 'groupVariableList',
defaultValue: [{ key: 'Group1', value: []}] defaultValue: [],
} }
} }
}, },

View File

@@ -94,9 +94,7 @@ export const useWorkflowGraph = ({
const { group_names, group } = config const { group_names, group } = config
nodeLibraryConfig.config[key].defaultValue = group nodeLibraryConfig.config[key].defaultValue = group
? Object.entries(group_names as Record<string, any>).map(([key, value]) => ({ key, value })) ? Object.entries(group_names as Record<string, any>).map(([key, value]) => ({ key, value }))
: [{ key: 'Group1', value: group_names }] : group_names
console.log('group_names', nodeLibraryConfig.config)
} else if (nodeLibraryConfig.config && nodeLibraryConfig.config[key] && config[key]) { } else if (nodeLibraryConfig.config && nodeLibraryConfig.config[key] && config[key]) {
nodeLibraryConfig.config[key].defaultValue = config[key] nodeLibraryConfig.config[key].defaultValue = config[key]
} }
@@ -832,7 +830,7 @@ export const useWorkflowGraph = ({
// 创建干净的节点数据,只保留必要的字段 // 创建干净的节点数据,只保留必要的字段
const cleanNodeData = { const cleanNodeData = {
id: `${dragData.type}_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`, id: `${dragData.type.replace(/-/g, '_')}_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
name: t(`workflow.${dragData.type}`), name: t(`workflow.${dragData.type}`),
...nodeLibraryConfig ...nodeLibraryConfig
}; };
@@ -842,6 +840,7 @@ export const useWorkflowGraph = ({
...graphNodeLibrary[dragData.type], ...graphNodeLibrary[dragData.type],
x: point.x - 150, x: point.x - 150,
y: point.y - 100, y: point.y - 100,
id: cleanNodeData.id,
data: { ...cleanNodeData, isGroup: true }, data: { ...cleanNodeData, isGroup: true },
}); });
} else if (dragData.type === 'if-else') { } else if (dragData.type === 'if-else') {
@@ -850,6 +849,7 @@ export const useWorkflowGraph = ({
...graphNodeLibrary[dragData.type], ...graphNodeLibrary[dragData.type],
x: point.x - 100, x: point.x - 100,
y: point.y - 60, y: point.y - 60,
id: cleanNodeData.id,
data: { ...cleanNodeData }, data: { ...cleanNodeData },
}); });
} else { } else {
@@ -858,6 +858,7 @@ export const useWorkflowGraph = ({
...(graphNodeLibrary[dragData.type] || graphNodeLibrary.default), ...(graphNodeLibrary[dragData.type] || graphNodeLibrary.default),
x: point.x - 60, x: point.x - 60,
y: point.y - 20, y: point.y - 20,
id: cleanNodeData.id,
data: { ...cleanNodeData }, data: { ...cleanNodeData },
}); });
} }
@@ -881,7 +882,15 @@ export const useWorkflowGraph = ({
if (data.config) { if (data.config) {
Object.keys(data.config).forEach(key => { Object.keys(data.config).forEach(key => {
if (data.config[key] && 'defaultValue' in data.config[key] && key !== 'knowledge_retrieval') { if (data.config[key] && 'defaultValue' in data.config[key] && key === 'group_names') {
let group_names = data.config.group.defaultValue ? {} : data.config[key].defaultValue
if (data.config.group.defaultValue) {
data.config[key].defaultValue.map((vo: any) => {
group_names[vo.key] = vo.value
})
}
itemConfig[key] = group_names
} else if (data.config[key] && 'defaultValue' in data.config[key] && key !== 'knowledge_retrieval') {
itemConfig[key] = data.config[key].defaultValue itemConfig[key] = data.config[key].defaultValue
} else if (key === 'knowledge_retrieval' && data.config[key] && 'defaultValue' in data.config[key]) { } else if (key === 'knowledge_retrieval' && data.config[key] && 'defaultValue' in data.config[key]) {
const { knowledge_bases } = data.config[key].defaultValue const { knowledge_bases } = data.config[key].defaultValue