Feat: upgrade variable assigner (#11285)
Signed-off-by: -LAN- <laipz8200@outlook.com> Co-authored-by: -LAN- <laipz8200@outlook.com>pull/11286/head
parent
e79eac688a
commit
e135ffc2c1
@ -1,8 +0,0 @@
|
||||
from .node import VariableAssignerNode
|
||||
from .node_data import VariableAssignerData, WriteMode
|
||||
|
||||
__all__ = [
|
||||
"VariableAssignerData",
|
||||
"VariableAssignerNode",
|
||||
"WriteMode",
|
||||
]
|
||||
@ -0,0 +1,4 @@
|
||||
class VariableOperatorNodeError(Exception):
|
||||
"""Base error type, don't use directly."""
|
||||
|
||||
pass
|
||||
@ -0,0 +1,19 @@
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from core.variables import Variable
|
||||
from core.workflow.nodes.variable_assigner.common.exc import VariableOperatorNodeError
|
||||
from extensions.ext_database import db
|
||||
from models import ConversationVariable
|
||||
|
||||
|
||||
def update_conversation_variable(conversation_id: str, variable: Variable):
|
||||
stmt = select(ConversationVariable).where(
|
||||
ConversationVariable.id == variable.id, ConversationVariable.conversation_id == conversation_id
|
||||
)
|
||||
with Session(db.engine) as session:
|
||||
row = session.scalar(stmt)
|
||||
if not row:
|
||||
raise VariableOperatorNodeError("conversation variable not found in the database")
|
||||
row.data = variable.model_dump_json()
|
||||
session.commit()
|
||||
@ -1,2 +0,0 @@
|
||||
class VariableAssignerNodeError(Exception):
|
||||
pass
|
||||
@ -0,0 +1,3 @@
|
||||
from .node import VariableAssignerNode
|
||||
|
||||
__all__ = ["VariableAssignerNode"]
|
||||
@ -0,0 +1,3 @@
|
||||
from .node import VariableAssignerNode
|
||||
|
||||
__all__ = ["VariableAssignerNode"]
|
||||
@ -0,0 +1,11 @@
|
||||
from core.variables import SegmentType
|
||||
|
||||
EMPTY_VALUE_MAPPING = {
|
||||
SegmentType.STRING: "",
|
||||
SegmentType.NUMBER: 0,
|
||||
SegmentType.OBJECT: {},
|
||||
SegmentType.ARRAY_ANY: [],
|
||||
SegmentType.ARRAY_STRING: [],
|
||||
SegmentType.ARRAY_NUMBER: [],
|
||||
SegmentType.ARRAY_OBJECT: [],
|
||||
}
|
||||
@ -0,0 +1,20 @@
|
||||
from collections.abc import Sequence
|
||||
from typing import Any
|
||||
|
||||
from pydantic import BaseModel
|
||||
|
||||
from core.workflow.nodes.base import BaseNodeData
|
||||
|
||||
from .enums import InputType, Operation
|
||||
|
||||
|
||||
class VariableOperationItem(BaseModel):
|
||||
variable_selector: Sequence[str]
|
||||
input_type: InputType
|
||||
operation: Operation
|
||||
value: Any | None = None
|
||||
|
||||
|
||||
class VariableAssignerNodeData(BaseNodeData):
|
||||
version: str = "2"
|
||||
items: Sequence[VariableOperationItem]
|
||||
@ -0,0 +1,18 @@
|
||||
from enum import StrEnum
|
||||
|
||||
|
||||
class Operation(StrEnum):
|
||||
OVER_WRITE = "over-write"
|
||||
CLEAR = "clear"
|
||||
APPEND = "append"
|
||||
EXTEND = "extend"
|
||||
SET = "set"
|
||||
ADD = "+="
|
||||
SUBTRACT = "-="
|
||||
MULTIPLY = "*="
|
||||
DIVIDE = "/="
|
||||
|
||||
|
||||
class InputType(StrEnum):
|
||||
VARIABLE = "variable"
|
||||
CONSTANT = "constant"
|
||||
@ -0,0 +1,31 @@
|
||||
from collections.abc import Sequence
|
||||
from typing import Any
|
||||
|
||||
from core.workflow.nodes.variable_assigner.common.exc import VariableOperatorNodeError
|
||||
|
||||
from .enums import InputType, Operation
|
||||
|
||||
|
||||
class OperationNotSupportedError(VariableOperatorNodeError):
|
||||
def __init__(self, *, operation: Operation, varialbe_type: str):
|
||||
super().__init__(f"Operation {operation} is not supported for type {varialbe_type}")
|
||||
|
||||
|
||||
class InputTypeNotSupportedError(VariableOperatorNodeError):
|
||||
def __init__(self, *, input_type: InputType, operation: Operation):
|
||||
super().__init__(f"Input type {input_type} is not supported for operation {operation}")
|
||||
|
||||
|
||||
class VariableNotFoundError(VariableOperatorNodeError):
|
||||
def __init__(self, *, variable_selector: Sequence[str]):
|
||||
super().__init__(f"Variable {variable_selector} not found")
|
||||
|
||||
|
||||
class InvalidInputValueError(VariableOperatorNodeError):
|
||||
def __init__(self, *, value: Any):
|
||||
super().__init__(f"Invalid input value {value}")
|
||||
|
||||
|
||||
class ConversationIDNotFoundError(VariableOperatorNodeError):
|
||||
def __init__(self):
|
||||
super().__init__("conversation_id not found")
|
||||
@ -0,0 +1,91 @@
|
||||
from typing import Any
|
||||
|
||||
from core.variables import SegmentType
|
||||
|
||||
from .enums import Operation
|
||||
|
||||
|
||||
def is_operation_supported(*, variable_type: SegmentType, operation: Operation):
|
||||
match operation:
|
||||
case Operation.OVER_WRITE | Operation.CLEAR:
|
||||
return True
|
||||
case Operation.SET:
|
||||
return variable_type in {SegmentType.OBJECT, SegmentType.STRING, SegmentType.NUMBER}
|
||||
case Operation.ADD | Operation.SUBTRACT | Operation.MULTIPLY | Operation.DIVIDE:
|
||||
# Only number variable can be added, subtracted, multiplied or divided
|
||||
return variable_type == SegmentType.NUMBER
|
||||
case Operation.APPEND | Operation.EXTEND:
|
||||
# Only array variable can be appended or extended
|
||||
return variable_type in {
|
||||
SegmentType.ARRAY_ANY,
|
||||
SegmentType.ARRAY_OBJECT,
|
||||
SegmentType.ARRAY_STRING,
|
||||
SegmentType.ARRAY_NUMBER,
|
||||
SegmentType.ARRAY_FILE,
|
||||
}
|
||||
case _:
|
||||
return False
|
||||
|
||||
|
||||
def is_variable_input_supported(*, operation: Operation):
|
||||
if operation in {Operation.SET, Operation.ADD, Operation.SUBTRACT, Operation.MULTIPLY, Operation.DIVIDE}:
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def is_constant_input_supported(*, variable_type: SegmentType, operation: Operation):
|
||||
match variable_type:
|
||||
case SegmentType.STRING | SegmentType.OBJECT:
|
||||
return operation in {Operation.OVER_WRITE, Operation.SET}
|
||||
case SegmentType.NUMBER:
|
||||
return operation in {
|
||||
Operation.OVER_WRITE,
|
||||
Operation.SET,
|
||||
Operation.ADD,
|
||||
Operation.SUBTRACT,
|
||||
Operation.MULTIPLY,
|
||||
Operation.DIVIDE,
|
||||
}
|
||||
case _:
|
||||
return False
|
||||
|
||||
|
||||
def is_input_value_valid(*, variable_type: SegmentType, operation: Operation, value: Any):
|
||||
if operation == Operation.CLEAR:
|
||||
return True
|
||||
match variable_type:
|
||||
case SegmentType.STRING:
|
||||
return isinstance(value, str)
|
||||
|
||||
case SegmentType.NUMBER:
|
||||
if not isinstance(value, int | float):
|
||||
return False
|
||||
if operation == Operation.DIVIDE and value == 0:
|
||||
return False
|
||||
return True
|
||||
|
||||
case SegmentType.OBJECT:
|
||||
return isinstance(value, dict)
|
||||
|
||||
# Array & Append
|
||||
case SegmentType.ARRAY_ANY if operation == Operation.APPEND:
|
||||
return isinstance(value, str | float | int | dict)
|
||||
case SegmentType.ARRAY_STRING if operation == Operation.APPEND:
|
||||
return isinstance(value, str)
|
||||
case SegmentType.ARRAY_NUMBER if operation == Operation.APPEND:
|
||||
return isinstance(value, int | float)
|
||||
case SegmentType.ARRAY_OBJECT if operation == Operation.APPEND:
|
||||
return isinstance(value, dict)
|
||||
|
||||
# Array & Extend / Overwrite
|
||||
case SegmentType.ARRAY_ANY if operation in {Operation.EXTEND, Operation.OVER_WRITE}:
|
||||
return isinstance(value, list) and all(isinstance(item, str | float | int | dict) for item in value)
|
||||
case SegmentType.ARRAY_STRING if operation in {Operation.EXTEND, Operation.OVER_WRITE}:
|
||||
return isinstance(value, list) and all(isinstance(item, str) for item in value)
|
||||
case SegmentType.ARRAY_NUMBER if operation in {Operation.EXTEND, Operation.OVER_WRITE}:
|
||||
return isinstance(value, list) and all(isinstance(item, int | float) for item in value)
|
||||
case SegmentType.ARRAY_OBJECT if operation in {Operation.EXTEND, Operation.OVER_WRITE}:
|
||||
return isinstance(value, list) and all(isinstance(item, dict) for item in value)
|
||||
|
||||
case _:
|
||||
return False
|
||||
@ -0,0 +1,159 @@
|
||||
import json
|
||||
from typing import Any
|
||||
|
||||
from core.variables import SegmentType, Variable
|
||||
from core.workflow.constants import CONVERSATION_VARIABLE_NODE_ID
|
||||
from core.workflow.entities.node_entities import NodeRunResult
|
||||
from core.workflow.nodes.base import BaseNode
|
||||
from core.workflow.nodes.enums import NodeType
|
||||
from core.workflow.nodes.variable_assigner.common import helpers as common_helpers
|
||||
from core.workflow.nodes.variable_assigner.common.exc import VariableOperatorNodeError
|
||||
from models.workflow import WorkflowNodeExecutionStatus
|
||||
|
||||
from . import helpers
|
||||
from .constants import EMPTY_VALUE_MAPPING
|
||||
from .entities import VariableAssignerNodeData
|
||||
from .enums import InputType, Operation
|
||||
from .exc import (
|
||||
ConversationIDNotFoundError,
|
||||
InputTypeNotSupportedError,
|
||||
InvalidInputValueError,
|
||||
OperationNotSupportedError,
|
||||
VariableNotFoundError,
|
||||
)
|
||||
|
||||
|
||||
class VariableAssignerNode(BaseNode[VariableAssignerNodeData]):
|
||||
_node_data_cls = VariableAssignerNodeData
|
||||
_node_type = NodeType.VARIABLE_ASSIGNER
|
||||
|
||||
def _run(self) -> NodeRunResult:
|
||||
inputs = self.node_data.model_dump()
|
||||
process_data = {}
|
||||
# NOTE: This node has no outputs
|
||||
updated_variables: list[Variable] = []
|
||||
|
||||
try:
|
||||
for item in self.node_data.items:
|
||||
variable = self.graph_runtime_state.variable_pool.get(item.variable_selector)
|
||||
|
||||
# ==================== Validation Part
|
||||
|
||||
# Check if variable exists
|
||||
if not isinstance(variable, Variable):
|
||||
raise VariableNotFoundError(variable_selector=item.variable_selector)
|
||||
|
||||
# Check if operation is supported
|
||||
if not helpers.is_operation_supported(variable_type=variable.value_type, operation=item.operation):
|
||||
raise OperationNotSupportedError(operation=item.operation, varialbe_type=variable.value_type)
|
||||
|
||||
# Check if variable input is supported
|
||||
if item.input_type == InputType.VARIABLE and not helpers.is_variable_input_supported(
|
||||
operation=item.operation
|
||||
):
|
||||
raise InputTypeNotSupportedError(input_type=InputType.VARIABLE, operation=item.operation)
|
||||
|
||||
# Check if constant input is supported
|
||||
if item.input_type == InputType.CONSTANT and not helpers.is_constant_input_supported(
|
||||
variable_type=variable.value_type, operation=item.operation
|
||||
):
|
||||
raise InputTypeNotSupportedError(input_type=InputType.CONSTANT, operation=item.operation)
|
||||
|
||||
# Get value from variable pool
|
||||
if (
|
||||
item.input_type == InputType.VARIABLE
|
||||
and item.operation != Operation.CLEAR
|
||||
and item.value is not None
|
||||
):
|
||||
value = self.graph_runtime_state.variable_pool.get(item.value)
|
||||
if value is None:
|
||||
raise VariableNotFoundError(variable_selector=item.value)
|
||||
# Skip if value is NoneSegment
|
||||
if value.value_type == SegmentType.NONE:
|
||||
continue
|
||||
item.value = value.value
|
||||
|
||||
# If set string / bytes / bytearray to object, try convert string to object.
|
||||
if (
|
||||
item.operation == Operation.SET
|
||||
and variable.value_type == SegmentType.OBJECT
|
||||
and isinstance(item.value, str | bytes | bytearray)
|
||||
):
|
||||
try:
|
||||
item.value = json.loads(item.value)
|
||||
except json.JSONDecodeError:
|
||||
raise InvalidInputValueError(value=item.value)
|
||||
|
||||
# Check if input value is valid
|
||||
if not helpers.is_input_value_valid(
|
||||
variable_type=variable.value_type, operation=item.operation, value=item.value
|
||||
):
|
||||
raise InvalidInputValueError(value=item.value)
|
||||
|
||||
# ==================== Execution Part
|
||||
|
||||
updated_value = self._handle_item(
|
||||
variable=variable,
|
||||
operation=item.operation,
|
||||
value=item.value,
|
||||
)
|
||||
variable = variable.model_copy(update={"value": updated_value})
|
||||
updated_variables.append(variable)
|
||||
except VariableOperatorNodeError as e:
|
||||
return NodeRunResult(
|
||||
status=WorkflowNodeExecutionStatus.FAILED,
|
||||
inputs=inputs,
|
||||
process_data=process_data,
|
||||
error=str(e),
|
||||
)
|
||||
|
||||
# Update variables
|
||||
for variable in updated_variables:
|
||||
self.graph_runtime_state.variable_pool.add(variable.selector, variable)
|
||||
process_data[variable.name] = variable.value
|
||||
|
||||
if variable.selector[0] == CONVERSATION_VARIABLE_NODE_ID:
|
||||
conversation_id = self.graph_runtime_state.variable_pool.get(["sys", "conversation_id"])
|
||||
if not conversation_id:
|
||||
raise ConversationIDNotFoundError
|
||||
else:
|
||||
conversation_id = conversation_id.value
|
||||
common_helpers.update_conversation_variable(
|
||||
conversation_id=conversation_id,
|
||||
variable=variable,
|
||||
)
|
||||
|
||||
return NodeRunResult(
|
||||
status=WorkflowNodeExecutionStatus.SUCCEEDED,
|
||||
inputs=inputs,
|
||||
process_data=process_data,
|
||||
)
|
||||
|
||||
def _handle_item(
|
||||
self,
|
||||
*,
|
||||
variable: Variable,
|
||||
operation: Operation,
|
||||
value: Any,
|
||||
):
|
||||
match operation:
|
||||
case Operation.OVER_WRITE:
|
||||
return value
|
||||
case Operation.CLEAR:
|
||||
return EMPTY_VALUE_MAPPING[variable.value_type]
|
||||
case Operation.APPEND:
|
||||
return variable.value + [value]
|
||||
case Operation.EXTEND:
|
||||
return variable.value + value
|
||||
case Operation.SET:
|
||||
return value
|
||||
case Operation.ADD:
|
||||
return variable.value + value
|
||||
case Operation.SUBTRACT:
|
||||
return variable.value - value
|
||||
case Operation.MULTIPLY:
|
||||
return variable.value * value
|
||||
case Operation.DIVIDE:
|
||||
return variable.value / value
|
||||
case _:
|
||||
raise OperationNotSupportedError(operation=operation, varialbe_type=variable.value_type)
|
||||
@ -0,0 +1,24 @@
|
||||
import pytest
|
||||
|
||||
from core.variables import SegmentType
|
||||
from core.workflow.nodes.variable_assigner.v2.enums import Operation
|
||||
from core.workflow.nodes.variable_assigner.v2.helpers import is_input_value_valid
|
||||
|
||||
|
||||
def test_is_input_value_valid_overwrite_array_string():
|
||||
# Valid cases
|
||||
assert is_input_value_valid(
|
||||
variable_type=SegmentType.ARRAY_STRING, operation=Operation.OVER_WRITE, value=["hello", "world"]
|
||||
)
|
||||
assert is_input_value_valid(variable_type=SegmentType.ARRAY_STRING, operation=Operation.OVER_WRITE, value=[])
|
||||
|
||||
# Invalid cases
|
||||
assert not is_input_value_valid(
|
||||
variable_type=SegmentType.ARRAY_STRING, operation=Operation.OVER_WRITE, value="not an array"
|
||||
)
|
||||
assert not is_input_value_valid(
|
||||
variable_type=SegmentType.ARRAY_STRING, operation=Operation.OVER_WRITE, value=[1, 2, 3]
|
||||
)
|
||||
assert not is_input_value_valid(
|
||||
variable_type=SegmentType.ARRAY_STRING, operation=Operation.OVER_WRITE, value=["valid", 123, "invalid"]
|
||||
)
|
||||
@ -0,0 +1,21 @@
|
||||
type HorizontalLineProps = {
|
||||
className?: string
|
||||
}
|
||||
const HorizontalLine = ({
|
||||
className,
|
||||
}: HorizontalLineProps) => {
|
||||
return (
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="240" height="2" viewBox="0 0 240 2" fill="none" className={className}>
|
||||
<path d="M0 1H240" stroke="url(#paint0_linear_8619_59125)"/>
|
||||
<defs>
|
||||
<linearGradient id="paint0_linear_8619_59125" x1="240" y1="9.99584" x2="3.95539e-05" y2="9.88094" gradientUnits="userSpaceOnUse">
|
||||
<stop stopColor="white" stopOpacity="0.01"/>
|
||||
<stop offset="0.9031" stopColor="#101828" stopOpacity="0.04"/>
|
||||
<stop offset="1" stopColor="white" stopOpacity="0.01"/>
|
||||
</linearGradient>
|
||||
</defs>
|
||||
</svg>
|
||||
)
|
||||
}
|
||||
|
||||
export default HorizontalLine
|
||||
@ -0,0 +1,35 @@
|
||||
import React from 'react'
|
||||
import { Variable02 } from '../icons/src/vender/solid/development'
|
||||
import VerticalLine from './vertical-line'
|
||||
import HorizontalLine from './horizontal-line'
|
||||
|
||||
type ListEmptyProps = {
|
||||
title?: string
|
||||
description?: React.ReactNode
|
||||
}
|
||||
|
||||
const ListEmpty = ({
|
||||
title,
|
||||
description,
|
||||
}: ListEmptyProps) => {
|
||||
return (
|
||||
<div className='flex w-[320px] p-4 flex-col items-start gap-2 rounded-[10px] bg-workflow-process-bg'>
|
||||
<div className='flex w-10 h-10 justify-center items-center gap-2 rounded-[10px]'>
|
||||
<div className='flex relative p-1 justify-center items-center gap-2 grow self-stretch rounded-[10px]
|
||||
border-[0.5px] border-components-card-border bg-components-card-bg shadow-lg'>
|
||||
<Variable02 className='w-5 h-5 shrink-0 text-text-accent' />
|
||||
<VerticalLine className='absolute -right-[1px] top-1/2 -translate-y-1/4'/>
|
||||
<VerticalLine className='absolute -left-[1px] top-1/2 -translate-y-1/4'/>
|
||||
<HorizontalLine className='absolute top-0 left-3/4 -translate-x-1/4 -translate-y-1/2'/>
|
||||
<HorizontalLine className='absolute top-full left-3/4 -translate-x-1/4 -translate-y-1/2' />
|
||||
</div>
|
||||
</div>
|
||||
<div className='flex flex-col items-start gap-1 self-stretch'>
|
||||
<div className='text-text-secondary system-sm-medium'>{title}</div>
|
||||
{description}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default ListEmpty
|
||||
@ -0,0 +1,21 @@
|
||||
type VerticalLineProps = {
|
||||
className?: string
|
||||
}
|
||||
const VerticalLine = ({
|
||||
className,
|
||||
}: VerticalLineProps) => {
|
||||
return (
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="2" height="132" viewBox="0 0 2 132" fill="none" className={className}>
|
||||
<path d="M1 0L1 132" stroke="url(#paint0_linear_8619_59128)"/>
|
||||
<defs>
|
||||
<linearGradient id="paint0_linear_8619_59128" x1="-7.99584" y1="132" x2="-7.96108" y2="6.4974e-07" gradientUnits="userSpaceOnUse">
|
||||
<stop stopColor="white" stopOpacity="0.01"/>
|
||||
<stop offset="0.877606" stopColor="#101828" stopOpacity="0.04"/>
|
||||
<stop offset="1" stopColor="white" stopOpacity="0.01"/>
|
||||
</linearGradient>
|
||||
</defs>
|
||||
</svg>
|
||||
)
|
||||
}
|
||||
|
||||
export default VerticalLine
|
||||
@ -0,0 +1,39 @@
|
||||
'use client'
|
||||
import type { FC } from 'react'
|
||||
import React from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import VarReferenceVars from './var-reference-vars'
|
||||
import type { NodeOutPutVar, ValueSelector, Var } from '@/app/components/workflow/types'
|
||||
import ListEmpty from '@/app/components/base/list-empty'
|
||||
|
||||
type Props = {
|
||||
vars: NodeOutPutVar[]
|
||||
onChange: (value: ValueSelector, varDetail: Var) => void
|
||||
itemWidth?: number
|
||||
}
|
||||
const AssignedVarReferencePopup: FC<Props> = ({
|
||||
vars,
|
||||
onChange,
|
||||
itemWidth,
|
||||
}) => {
|
||||
const { t } = useTranslation()
|
||||
// max-h-[300px] overflow-y-auto todo: use portal to handle long list
|
||||
return (
|
||||
<div className='p-1 bg-components-panel-bg-bur rounded-lg border-[0.5px] border-components-panel-border shadow-lg w-[352px]' >
|
||||
{(!vars || vars.length === 0)
|
||||
? <ListEmpty
|
||||
title={t('workflow.nodes.assigner.noAssignedVars') || ''}
|
||||
description={t('workflow.nodes.assigner.assignedVarsDescription')}
|
||||
/>
|
||||
: <VarReferenceVars
|
||||
searchBoxClassName='mt-1'
|
||||
vars={vars}
|
||||
onChange={onChange}
|
||||
itemWidth={itemWidth}
|
||||
isSupportFileVar
|
||||
/>
|
||||
}
|
||||
</div >
|
||||
)
|
||||
}
|
||||
export default React.memo(AssignedVarReferencePopup)
|
||||
@ -0,0 +1,128 @@
|
||||
import type { FC } from 'react'
|
||||
import { useState } from 'react'
|
||||
import {
|
||||
RiArrowDownSLine,
|
||||
RiCheckLine,
|
||||
} from '@remixicon/react'
|
||||
import classNames from 'classnames'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import type { WriteMode } from '../types'
|
||||
import { getOperationItems } from '../utils'
|
||||
import {
|
||||
PortalToFollowElem,
|
||||
PortalToFollowElemContent,
|
||||
PortalToFollowElemTrigger,
|
||||
} from '@/app/components/base/portal-to-follow-elem'
|
||||
import type { VarType } from '@/app/components/workflow/types'
|
||||
import Divider from '@/app/components/base/divider'
|
||||
|
||||
type Item = {
|
||||
value: string | number
|
||||
name: string
|
||||
}
|
||||
|
||||
type OperationSelectorProps = {
|
||||
value: string | number
|
||||
onSelect: (value: Item) => void
|
||||
placeholder?: string
|
||||
disabled?: boolean
|
||||
className?: string
|
||||
popupClassName?: string
|
||||
assignedVarType?: VarType
|
||||
writeModeTypes?: WriteMode[]
|
||||
writeModeTypesArr?: WriteMode[]
|
||||
writeModeTypesNum?: WriteMode[]
|
||||
}
|
||||
|
||||
const i18nPrefix = 'workflow.nodes.assigner'
|
||||
|
||||
const OperationSelector: FC<OperationSelectorProps> = ({
|
||||
value,
|
||||
onSelect,
|
||||
disabled = false,
|
||||
className,
|
||||
popupClassName,
|
||||
assignedVarType,
|
||||
writeModeTypes,
|
||||
writeModeTypesArr,
|
||||
writeModeTypesNum,
|
||||
}) => {
|
||||
const { t } = useTranslation()
|
||||
const [open, setOpen] = useState(false)
|
||||
|
||||
const items = getOperationItems(assignedVarType, writeModeTypes, writeModeTypesArr, writeModeTypesNum)
|
||||
|
||||
const selectedItem = items.find(item => item.value === value)
|
||||
|
||||
return (
|
||||
<PortalToFollowElem
|
||||
open={open}
|
||||
onOpenChange={setOpen}
|
||||
placement='bottom-start'
|
||||
offset={4}
|
||||
>
|
||||
<PortalToFollowElemTrigger
|
||||
onClick={() => !disabled && setOpen(v => !v)}
|
||||
>
|
||||
<div
|
||||
className={classNames(
|
||||
'flex items-center px-2 py-1 gap-0.5 rounded-lg bg-components-input-bg-normal',
|
||||
disabled ? 'cursor-not-allowed !bg-components-input-bg-disabled' : 'cursor-pointer hover:bg-state-base-hover-alt',
|
||||
open && 'bg-state-base-hover-alt',
|
||||
className,
|
||||
)}
|
||||
>
|
||||
<div className='flex p-1 items-center'>
|
||||
<span
|
||||
className={`truncate overflow-hidden text-ellipsis system-sm-regular
|
||||
${selectedItem ? 'text-components-input-text-filled' : 'text-components-input-text-disabled'}`}
|
||||
>
|
||||
{selectedItem?.name ? t(`${i18nPrefix}.operations.${selectedItem?.name}`) : t(`${i18nPrefix}.operations.title`)}
|
||||
</span>
|
||||
</div>
|
||||
<RiArrowDownSLine className={`h-4 w-4 text-text-quaternary ${disabled && 'text-components-input-text-placeholder'} ${open && 'text-text-secondary'}`} />
|
||||
</div>
|
||||
</PortalToFollowElemTrigger>
|
||||
|
||||
<PortalToFollowElemContent className={`z-20 ${popupClassName}`}>
|
||||
<div className='flex w-[140px] flex-col items-start rounded-xl border-[0.5px] border-components-panel-border bg-components-panel-bg-blur shadow-lg'>
|
||||
<div className='flex p-1 flex-col items-start self-stretch'>
|
||||
<div className='flex px-3 pt-1 pb-0.5 items-start self-stretch'>
|
||||
<div className='flex grow text-text-tertiary system-xs-medium-uppercase'>{t(`${i18nPrefix}.operations.title`)}</div>
|
||||
</div>
|
||||
{items.map(item => (
|
||||
item.value === 'divider'
|
||||
? (
|
||||
<Divider key="divider" className="my-1" />
|
||||
)
|
||||
: (
|
||||
<div
|
||||
key={item.value}
|
||||
className={classNames(
|
||||
'flex items-center px-2 py-1 gap-1 self-stretch rounded-lg',
|
||||
'cursor-pointer hover:bg-state-base-hover',
|
||||
)}
|
||||
onClick={() => {
|
||||
onSelect(item)
|
||||
setOpen(false)
|
||||
}}
|
||||
>
|
||||
<div className='flex min-h-5 px-1 items-center gap-1 grow'>
|
||||
<span className={'flex flex-grow text-text-secondary system-sm-medium'}>{t(`${i18nPrefix}.operations.${item.name}`)}</span>
|
||||
</div>
|
||||
{item.value === value && (
|
||||
<div className='flex justify-center items-center'>
|
||||
<RiCheckLine className='h-4 w-4 text-text-accent' />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</PortalToFollowElemContent>
|
||||
</PortalToFollowElem>
|
||||
)
|
||||
}
|
||||
|
||||
export default OperationSelector
|
||||
@ -0,0 +1,227 @@
|
||||
'use client'
|
||||
import type { FC } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import React, { useCallback } from 'react'
|
||||
import produce from 'immer'
|
||||
import { RiDeleteBinLine } from '@remixicon/react'
|
||||
import OperationSelector from '../operation-selector'
|
||||
import { AssignerNodeInputType, WriteMode } from '../../types'
|
||||
import type { AssignerNodeOperation } from '../../types'
|
||||
import ListNoDataPlaceholder from '@/app/components/workflow/nodes/_base/components/list-no-data-placeholder'
|
||||
import VarReferencePicker from '@/app/components/workflow/nodes/_base/components/variable/var-reference-picker'
|
||||
import type { ValueSelector, Var, VarType } from '@/app/components/workflow/types'
|
||||
import { CodeLanguage } from '@/app/components/workflow/nodes/code/types'
|
||||
import ActionButton from '@/app/components/base/action-button'
|
||||
import Input from '@/app/components/base/input'
|
||||
import Textarea from '@/app/components/base/textarea'
|
||||
import CodeEditor from '@/app/components/workflow/nodes/_base/components/editor/code-editor'
|
||||
|
||||
type Props = {
|
||||
readonly: boolean
|
||||
nodeId: string
|
||||
list: AssignerNodeOperation[]
|
||||
onChange: (list: AssignerNodeOperation[], value?: ValueSelector) => void
|
||||
onOpen?: (index: number) => void
|
||||
filterVar?: (payload: Var, valueSelector: ValueSelector) => boolean
|
||||
filterToAssignedVar?: (payload: Var, assignedVarType: VarType, write_mode: WriteMode) => boolean
|
||||
getAssignedVarType?: (valueSelector: ValueSelector) => VarType
|
||||
getToAssignedVarType?: (assignedVarType: VarType, write_mode: WriteMode) => VarType
|
||||
writeModeTypes?: WriteMode[]
|
||||
writeModeTypesArr?: WriteMode[]
|
||||
writeModeTypesNum?: WriteMode[]
|
||||
}
|
||||
|
||||
const VarList: FC<Props> = ({
|
||||
readonly,
|
||||
nodeId,
|
||||
list,
|
||||
onChange,
|
||||
onOpen = () => { },
|
||||
filterVar,
|
||||
filterToAssignedVar,
|
||||
getAssignedVarType,
|
||||
getToAssignedVarType,
|
||||
writeModeTypes,
|
||||
writeModeTypesArr,
|
||||
writeModeTypesNum,
|
||||
}) => {
|
||||
const { t } = useTranslation()
|
||||
const handleAssignedVarChange = useCallback((index: number) => {
|
||||
return (value: ValueSelector | string) => {
|
||||
const newList = produce(list, (draft) => {
|
||||
draft[index].variable_selector = value as ValueSelector
|
||||
draft[index].operation = WriteMode.overwrite
|
||||
draft[index].value = undefined
|
||||
})
|
||||
onChange(newList, value as ValueSelector)
|
||||
}
|
||||
}, [list, onChange])
|
||||
|
||||
const handleOperationChange = useCallback((index: number) => {
|
||||
return (item: { value: string | number }) => {
|
||||
const newList = produce(list, (draft) => {
|
||||
draft[index].operation = item.value as WriteMode
|
||||
draft[index].value = '' // Clear value when operation changes
|
||||
if (item.value === WriteMode.set || item.value === WriteMode.increment || item.value === WriteMode.decrement
|
||||
|| item.value === WriteMode.multiply || item.value === WriteMode.divide)
|
||||
draft[index].input_type = AssignerNodeInputType.constant
|
||||
else
|
||||
draft[index].input_type = AssignerNodeInputType.variable
|
||||
})
|
||||
onChange(newList)
|
||||
}
|
||||
}, [list, onChange])
|
||||
|
||||
const handleToAssignedVarChange = useCallback((index: number) => {
|
||||
return (value: ValueSelector | string | number) => {
|
||||
const newList = produce(list, (draft) => {
|
||||
draft[index].value = value as ValueSelector
|
||||
})
|
||||
onChange(newList, value as ValueSelector)
|
||||
}
|
||||
}, [list, onChange])
|
||||
|
||||
const handleVarRemove = useCallback((index: number) => {
|
||||
return () => {
|
||||
const newList = produce(list, (draft) => {
|
||||
draft.splice(index, 1)
|
||||
})
|
||||
onChange(newList)
|
||||
}
|
||||
}, [list, onChange])
|
||||
|
||||
const handleOpen = useCallback((index: number) => {
|
||||
return () => onOpen(index)
|
||||
}, [onOpen])
|
||||
|
||||
const handleFilterToAssignedVar = useCallback((index: number) => {
|
||||
return (payload: Var, valueSelector: ValueSelector) => {
|
||||
const item = list[index]
|
||||
const assignedVarType = item.variable_selector ? getAssignedVarType?.(item.variable_selector) : undefined
|
||||
|
||||
if (!filterToAssignedVar || !item.variable_selector || !assignedVarType || !item.operation)
|
||||
return true
|
||||
|
||||
return filterToAssignedVar(
|
||||
payload,
|
||||
assignedVarType,
|
||||
item.operation,
|
||||
)
|
||||
}
|
||||
}, [list, filterToAssignedVar, getAssignedVarType])
|
||||
|
||||
if (list.length === 0) {
|
||||
return (
|
||||
<ListNoDataPlaceholder>
|
||||
{t('workflow.nodes.assigner.noVarTip')}
|
||||
</ListNoDataPlaceholder>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className='flex flex-col items-start gap-4 self-stretch'>
|
||||
{list.map((item, index) => {
|
||||
const assignedVarType = item.variable_selector ? getAssignedVarType?.(item.variable_selector) : undefined
|
||||
const toAssignedVarType = (assignedVarType && item.operation && getToAssignedVarType)
|
||||
? getToAssignedVarType(assignedVarType, item.operation)
|
||||
: undefined
|
||||
|
||||
return (
|
||||
<div className='flex items-start gap-1 self-stretch' key={index}>
|
||||
<div className='flex flex-col items-start gap-1 flex-grow'>
|
||||
<div className='flex items-center gap-1 self-stretch'>
|
||||
<VarReferencePicker
|
||||
readonly={readonly}
|
||||
nodeId={nodeId}
|
||||
isShowNodeName
|
||||
value={item.variable_selector || []}
|
||||
onChange={handleAssignedVarChange(index)}
|
||||
onOpen={handleOpen(index)}
|
||||
filterVar={filterVar}
|
||||
placeholder={t('workflow.nodes.assigner.selectAssignedVariable') as string}
|
||||
minWidth={352}
|
||||
popupFor='assigned'
|
||||
className='w-full'
|
||||
/>
|
||||
<OperationSelector
|
||||
value={item.operation}
|
||||
placeholder='Operation'
|
||||
disabled={!item.variable_selector || item.variable_selector.length === 0}
|
||||
onSelect={handleOperationChange(index)}
|
||||
assignedVarType={assignedVarType}
|
||||
writeModeTypes={writeModeTypes}
|
||||
writeModeTypesArr={writeModeTypesArr}
|
||||
writeModeTypesNum={writeModeTypesNum}
|
||||
/>
|
||||
</div>
|
||||
{item.operation !== WriteMode.clear && item.operation !== WriteMode.set
|
||||
&& !writeModeTypesNum?.includes(item.operation)
|
||||
&& (
|
||||
<VarReferencePicker
|
||||
readonly={readonly || !item.variable_selector || !item.operation}
|
||||
nodeId={nodeId}
|
||||
isShowNodeName
|
||||
value={item.value}
|
||||
onChange={handleToAssignedVarChange(index)}
|
||||
filterVar={handleFilterToAssignedVar(index)}
|
||||
valueTypePlaceHolder={toAssignedVarType}
|
||||
placeholder={t('workflow.nodes.assigner.setParameter') as string}
|
||||
minWidth={352}
|
||||
popupFor='toAssigned'
|
||||
className='w-full'
|
||||
/>
|
||||
)
|
||||
}
|
||||
{item.operation === WriteMode.set && assignedVarType && (
|
||||
<>
|
||||
{assignedVarType === 'number' && (
|
||||
<Input
|
||||
type="number"
|
||||
value={item.value as number}
|
||||
onChange={e => handleToAssignedVarChange(index)(Number(e.target.value))}
|
||||
className='w-full'
|
||||
/>
|
||||
)}
|
||||
{assignedVarType === 'string' && (
|
||||
<Textarea
|
||||
value={item.value as string}
|
||||
onChange={e => handleToAssignedVarChange(index)(e.target.value)}
|
||||
className='w-full'
|
||||
/>
|
||||
)}
|
||||
{assignedVarType === 'object' && (
|
||||
<CodeEditor
|
||||
value={item.value as string}
|
||||
language={CodeLanguage.json}
|
||||
onChange={value => handleToAssignedVarChange(index)(value)}
|
||||
className='w-full'
|
||||
readOnly={readonly}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
{writeModeTypesNum?.includes(item.operation)
|
||||
&& <Input
|
||||
type="number"
|
||||
value={item.value as number}
|
||||
onChange={e => handleToAssignedVarChange(index)(Number(e.target.value))}
|
||||
placeholder="Enter number value..."
|
||||
className='w-full'
|
||||
/>
|
||||
}
|
||||
</div>
|
||||
<ActionButton
|
||||
size='l'
|
||||
className='flex-shrink-0 group hover:!bg-state-destructive-hover'
|
||||
onClick={handleVarRemove(index)}
|
||||
>
|
||||
<RiDeleteBinLine className='text-text-tertiary w-4 h-4 group-hover:text-text-destructive' />
|
||||
</ActionButton>
|
||||
</div>
|
||||
)
|
||||
},
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
export default React.memo(VarList)
|
||||
@ -0,0 +1,39 @@
|
||||
import { useCallback } from 'react'
|
||||
import produce from 'immer'
|
||||
import type { AssignerNodeOperation, AssignerNodeType } from '../../types'
|
||||
import { AssignerNodeInputType, WriteMode } from '../../types'
|
||||
|
||||
type Params = {
|
||||
id: string
|
||||
inputs: AssignerNodeType
|
||||
setInputs: (newInputs: AssignerNodeType) => void
|
||||
}
|
||||
function useVarList({
|
||||
inputs,
|
||||
setInputs,
|
||||
}: Params) {
|
||||
const handleVarListChange = useCallback((newList: AssignerNodeOperation[]) => {
|
||||
const newInputs = produce(inputs, (draft) => {
|
||||
draft.items = newList
|
||||
})
|
||||
setInputs(newInputs)
|
||||
}, [inputs, setInputs])
|
||||
|
||||
const handleAddVariable = useCallback(() => {
|
||||
const newInputs = produce(inputs, (draft) => {
|
||||
draft.items.push({
|
||||
variable_selector: [],
|
||||
input_type: AssignerNodeInputType.constant,
|
||||
operation: WriteMode.overwrite,
|
||||
value: '',
|
||||
})
|
||||
})
|
||||
setInputs(newInputs)
|
||||
}, [inputs, setInputs])
|
||||
return {
|
||||
handleVarListChange,
|
||||
handleAddVariable,
|
||||
}
|
||||
}
|
||||
|
||||
export default useVarList
|
||||
@ -0,0 +1,70 @@
|
||||
import { useCallback } from 'react'
|
||||
import {
|
||||
useNodes,
|
||||
} from 'reactflow'
|
||||
import { uniqBy } from 'lodash-es'
|
||||
import {
|
||||
useIsChatMode,
|
||||
useWorkflow,
|
||||
useWorkflowVariables,
|
||||
} from '../../hooks'
|
||||
import type {
|
||||
Node,
|
||||
Var,
|
||||
} from '../../types'
|
||||
import { AssignerNodeInputType, WriteMode } from './types'
|
||||
|
||||
export const useGetAvailableVars = () => {
|
||||
const nodes: Node[] = useNodes()
|
||||
const { getBeforeNodesInSameBranchIncludeParent } = useWorkflow()
|
||||
const { getNodeAvailableVars } = useWorkflowVariables()
|
||||
const isChatMode = useIsChatMode()
|
||||
const getAvailableVars = useCallback((nodeId: string, handleId: string, filterVar: (v: Var) => boolean, hideEnv = false) => {
|
||||
const availableNodes: Node[] = []
|
||||
const currentNode = nodes.find(node => node.id === nodeId)!
|
||||
|
||||
if (!currentNode)
|
||||
return []
|
||||
|
||||
const beforeNodes = getBeforeNodesInSameBranchIncludeParent(nodeId)
|
||||
availableNodes.push(...beforeNodes)
|
||||
const parentNode = nodes.find(node => node.id === currentNode.parentId)
|
||||
|
||||
if (hideEnv) {
|
||||
return getNodeAvailableVars({
|
||||
parentNode,
|
||||
beforeNodes: uniqBy(availableNodes, 'id').filter(node => node.id !== nodeId),
|
||||
isChatMode,
|
||||
hideEnv,
|
||||
hideChatVar: hideEnv,
|
||||
filterVar,
|
||||
})
|
||||
.map(node => ({
|
||||
...node,
|
||||
vars: node.isStartNode ? node.vars.filter(v => !v.variable.startsWith('sys.')) : node.vars,
|
||||
}))
|
||||
.filter(item => item.vars.length > 0)
|
||||
}
|
||||
|
||||
return getNodeAvailableVars({
|
||||
parentNode,
|
||||
beforeNodes: uniqBy(availableNodes, 'id').filter(node => node.id !== nodeId),
|
||||
isChatMode,
|
||||
filterVar,
|
||||
})
|
||||
}, [nodes, getBeforeNodesInSameBranchIncludeParent, getNodeAvailableVars, isChatMode])
|
||||
|
||||
return getAvailableVars
|
||||
}
|
||||
|
||||
export const useHandleAddOperationItem = () => {
|
||||
return useCallback((list: any[]) => {
|
||||
const newItem = {
|
||||
variable_selector: [],
|
||||
write_mode: WriteMode.overwrite,
|
||||
input_type: AssignerNodeInputType.variable,
|
||||
value: '',
|
||||
}
|
||||
return [...list, newItem]
|
||||
}, [])
|
||||
}
|
||||
@ -1,13 +1,30 @@
|
||||
import type { CommonNodeType, ValueSelector } from '@/app/components/workflow/types'
|
||||
|
||||
export enum WriteMode {
|
||||
Overwrite = 'over-write',
|
||||
Append = 'append',
|
||||
Clear = 'clear',
|
||||
overwrite = 'over-write',
|
||||
clear = 'clear',
|
||||
append = 'append',
|
||||
extend = 'extend',
|
||||
set = 'set',
|
||||
increment = '+=',
|
||||
decrement = '-=',
|
||||
multiply = '*=',
|
||||
divide = '/=',
|
||||
}
|
||||
|
||||
export enum AssignerNodeInputType {
|
||||
variable = 'variable',
|
||||
constant = 'constant',
|
||||
}
|
||||
|
||||
export type AssignerNodeOperation = {
|
||||
variable_selector: ValueSelector
|
||||
input_type: AssignerNodeInputType
|
||||
operation: WriteMode
|
||||
value: any
|
||||
}
|
||||
|
||||
export type AssignerNodeType = CommonNodeType & {
|
||||
assigned_variable_selector: ValueSelector
|
||||
write_mode: WriteMode
|
||||
input_variable_selector: ValueSelector
|
||||
version?: '1' | '2'
|
||||
items: AssignerNodeOperation[]
|
||||
}
|
||||
|
||||
@ -1,5 +1,83 @@
|
||||
import type { AssignerNodeType } from './types'
|
||||
import { AssignerNodeInputType, WriteMode } from './types'
|
||||
|
||||
export const checkNodeValid = (payload: AssignerNodeType) => {
|
||||
return true
|
||||
}
|
||||
|
||||
export const formatOperationName = (type: string) => {
|
||||
if (type === 'over-write')
|
||||
return 'Overwrite'
|
||||
return type.charAt(0).toUpperCase() + type.slice(1)
|
||||
}
|
||||
|
||||
type Item = {
|
||||
value: string | number
|
||||
name: string
|
||||
}
|
||||
|
||||
export const getOperationItems = (
|
||||
assignedVarType?: string,
|
||||
writeModeTypes?: WriteMode[],
|
||||
writeModeTypesArr?: WriteMode[],
|
||||
writeModeTypesNum?: WriteMode[],
|
||||
): Item[] => {
|
||||
if (assignedVarType?.startsWith('array') && writeModeTypesArr) {
|
||||
return writeModeTypesArr.map(type => ({
|
||||
value: type,
|
||||
name: type,
|
||||
}))
|
||||
}
|
||||
|
||||
if (assignedVarType === 'number' && writeModeTypes && writeModeTypesNum) {
|
||||
return [
|
||||
...writeModeTypes.map(type => ({
|
||||
value: type,
|
||||
name: type,
|
||||
})),
|
||||
{ value: 'divider', name: 'divider' } as Item,
|
||||
...writeModeTypesNum.map(type => ({
|
||||
value: type,
|
||||
name: type,
|
||||
})),
|
||||
]
|
||||
}
|
||||
|
||||
if (writeModeTypes && ['string', 'object'].includes(assignedVarType || '')) {
|
||||
return writeModeTypes.map(type => ({
|
||||
value: type,
|
||||
name: type,
|
||||
}))
|
||||
}
|
||||
|
||||
return []
|
||||
}
|
||||
|
||||
const convertOldWriteMode = (oldMode: string): WriteMode => {
|
||||
switch (oldMode) {
|
||||
case 'over-write':
|
||||
return WriteMode.overwrite
|
||||
case 'append':
|
||||
return WriteMode.append
|
||||
case 'clear':
|
||||
return WriteMode.clear
|
||||
default:
|
||||
return WriteMode.overwrite
|
||||
}
|
||||
}
|
||||
|
||||
export const convertV1ToV2 = (payload: any): AssignerNodeType => {
|
||||
if (payload.version === '2' && payload.items)
|
||||
return payload as AssignerNodeType
|
||||
|
||||
return {
|
||||
version: '2',
|
||||
items: [{
|
||||
variable_selector: payload.assigned_variable_selector || [],
|
||||
input_type: AssignerNodeInputType.variable,
|
||||
operation: convertOldWriteMode(payload.write_mode),
|
||||
value: payload.input_variable_selector || [],
|
||||
}],
|
||||
...payload,
|
||||
}
|
||||
}
|
||||
|
||||
Loading…
Reference in New Issue