This commit is contained in:
2025-12-01 17:21:38 +08:00
parent 32fee2b8ab
commit fab8c13cb3
7511 changed files with 996300 additions and 0 deletions

View File

@@ -0,0 +1,82 @@
'use client'
import type { FC } from 'react'
import React from 'react'
import { useTranslation } from 'react-i18next'
import MemoryConfig from '../../_base/components/memory-config'
import Editor from '@/app/components/workflow/nodes/_base/components/prompt/editor'
import type { Memory, Node, NodeOutPutVar } from '@/app/components/workflow/types'
import Tooltip from '@/app/components/base/tooltip'
const i18nPrefix = 'workflow.nodes.questionClassifiers'
type Props = {
instruction: string
onInstructionChange: (instruction: string) => void
hideMemorySetting: boolean
memory?: Memory
onMemoryChange: (memory?: Memory) => void
readonly?: boolean
isChatModel: boolean
isChatApp: boolean
hasSetBlockStatus?: {
context: boolean
history: boolean
query: boolean
}
nodesOutputVars: NodeOutPutVar[]
availableNodes: Node[]
}
const AdvancedSetting: FC<Props> = ({
instruction,
onInstructionChange,
hideMemorySetting,
memory,
onMemoryChange,
readonly,
isChatModel,
isChatApp,
hasSetBlockStatus,
nodesOutputVars,
availableNodes,
}) => {
const { t } = useTranslation()
return (
<>
<Editor
title={
<div className='flex items-center space-x-1'>
<span className='uppercase'>{t(`${i18nPrefix}.instruction`)}</span>
<Tooltip
popupContent={
<div className='w-[120px]'>
{t(`${i18nPrefix}.instructionTip`)}
</div>
}
triggerClassName='w-3.5 h-3.5 ml-0.5'
/>
</div>
}
value={instruction}
onChange={onInstructionChange}
readOnly={readonly}
isChatModel={isChatModel}
isChatApp={isChatApp}
isShowContext={false}
hasSetBlockStatus={hasSetBlockStatus}
nodesOutputVars={nodesOutputVars}
availableNodes={availableNodes}
/>
{!hideMemorySetting && (
<MemoryConfig
className='mt-4'
readonly={false}
config={{ data: memory }}
onChange={onMemoryChange}
canSetRoleName={false}
/>
)}
</>
)
}
export default React.memo(AdvancedSetting)

View File

@@ -0,0 +1,73 @@
'use client'
import type { FC } from 'react'
import React, { useCallback, useEffect, useState } from 'react'
import { useTranslation } from 'react-i18next'
import type { Topic } from '../types'
import Editor from '@/app/components/workflow/nodes/_base/components/prompt/editor'
import useAvailableVarList from '@/app/components/workflow/nodes/_base/hooks/use-available-var-list'
import type { ValueSelector, Var } from '@/app/components/workflow/types'
import { uniqueId } from 'lodash-es'
const i18nPrefix = 'workflow.nodes.questionClassifiers'
type Props = {
className?: string
headerClassName?: string
nodeId: string
payload: Topic
onChange: (payload: Topic) => void
onRemove: () => void
index: number
readonly?: boolean
filterVar: (payload: Var, valueSelector: ValueSelector) => boolean
}
const ClassItem: FC<Props> = ({
className,
headerClassName,
nodeId,
payload,
onChange,
onRemove,
index,
readonly,
filterVar,
}) => {
const { t } = useTranslation()
const [instanceId, setInstanceId] = useState(() => uniqueId())
useEffect(() => {
setInstanceId(`${nodeId}-${uniqueId()}`)
}, [nodeId])
const handleNameChange = useCallback((value: string) => {
onChange({ ...payload, name: value })
}, [onChange, payload])
const { availableVars, availableNodesWithParent } = useAvailableVarList(nodeId, {
onlyLeafNodeVar: false,
hideChatVar: false,
hideEnv: false,
filterVar,
})
return (
<Editor
className={className}
headerClassName={headerClassName}
title={`${t(`${i18nPrefix}.class`)} ${index}`}
placeholder={t(`${i18nPrefix}.topicPlaceholder`)!}
value={payload.name}
onChange={handleNameChange}
showRemove
onRemove={onRemove}
nodesOutputVars={availableVars}
availableNodes={availableNodesWithParent}
readOnly={readonly} // ?
instanceId={instanceId}
justVar // ?
isSupportFileVar // ?
/>
)
}
export default React.memo(ClassItem)

View File

@@ -0,0 +1,174 @@
'use client'
import type { FC } from 'react'
import React, { useCallback, useEffect, useRef, useState } from 'react'
import { produce } from 'immer'
import { useTranslation } from 'react-i18next'
import { useEdgesInteractions } from '../../../hooks'
import AddButton from '../../_base/components/add-button'
import Item from './class-item'
import type { Topic } from '@/app/components/workflow/nodes/question-classifier/types'
import type { ValueSelector, Var } from '@/app/components/workflow/types'
import { ReactSortable } from 'react-sortablejs'
import { noop } from 'lodash-es'
import cn from '@/utils/classnames'
import { RiDraggable } from '@remixicon/react'
import { ArrowDownRoundFill } from '@/app/components/base/icons/src/vender/solid/general'
const i18nPrefix = 'workflow.nodes.questionClassifiers'
// Layout constants
const HANDLE_SIDE_WIDTH = 3 // Width offset for drag handle spacing
type Props = {
nodeId: string
list: Topic[]
onChange: (list: Topic[]) => void
readonly?: boolean
filterVar: (payload: Var, valueSelector: ValueSelector) => boolean
handleSortTopic?: (newTopics: (Topic & { id: string })[]) => void
}
const ClassList: FC<Props> = ({
nodeId,
list,
onChange,
readonly,
filterVar,
handleSortTopic = noop,
}) => {
const { t } = useTranslation()
const { handleEdgeDeleteByDeleteBranch } = useEdgesInteractions()
const listContainerRef = useRef<HTMLDivElement>(null)
const [shouldScrollToEnd, setShouldScrollToEnd] = useState(false)
const prevListLength = useRef(list.length)
const [collapsed, setCollapsed] = useState(false)
const handleClassChange = useCallback((index: number) => {
return (value: Topic) => {
const newList = produce(list, (draft) => {
draft[index] = value
})
onChange(newList)
}
}, [list, onChange])
const handleAddClass = useCallback(() => {
const newList = produce(list, (draft) => {
draft.push({ id: `${Date.now()}`, name: '' })
})
onChange(newList)
setShouldScrollToEnd(true)
if (collapsed)
setCollapsed(false)
}, [list, onChange, collapsed])
const handleRemoveClass = useCallback((index: number) => {
return () => {
handleEdgeDeleteByDeleteBranch(nodeId, list[index].id)
const newList = produce(list, (draft) => {
draft.splice(index, 1)
})
onChange(newList)
}
}, [list, onChange, handleEdgeDeleteByDeleteBranch, nodeId])
const topicCount = list.length
// Scroll to the newly added item after the list updates
useEffect(() => {
if (shouldScrollToEnd && list.length > prevListLength.current)
setShouldScrollToEnd(false)
prevListLength.current = list.length
}, [list.length, shouldScrollToEnd])
const handleCollapse = useCallback(() => {
setCollapsed(!collapsed)
}, [collapsed])
return (
<>
<div className='mb-2 flex items-center justify-between' onClick={handleCollapse}>
<div className='flex cursor-pointer items-center text-xs font-semibold uppercase text-text-secondary'>
{t(`${i18nPrefix}.class`)} <span className='text-text-destructive'>*</span>
{list.length > 0 && (
<ArrowDownRoundFill
className={cn(
'h-4 w-4 text-text-quaternary transition-transform duration-200',
collapsed && '-rotate-90',
)}
/>
)}
</div>
</div>
{!collapsed && (
<div
ref={listContainerRef}
className={cn('overflow-y-visible', `pl-${HANDLE_SIDE_WIDTH}`)}
>
<ReactSortable
list={list.map(item => ({ ...item }))}
setList={handleSortTopic}
handle='.handle'
ghostClass='bg-components-panel-bg'
animation={150}
disabled={readonly}
className='space-y-2'
>
{
list.map((item, index) => {
const canDrag = (() => {
if (readonly)
return false
return topicCount >= 2
})()
return (
<div
key={item.id}
className={cn(
'group relative rounded-[10px] bg-components-panel-bg',
`-ml-${HANDLE_SIDE_WIDTH} min-h-[40px] px-0 py-0`,
)}
style={{
// Performance hint for browser
contain: 'layout style paint',
}}
>
<div>
{canDrag && <RiDraggable className={cn(
'handle absolute left-2 top-3 hidden h-3 w-3 cursor-pointer text-text-tertiary',
'group-hover:block',
)} />}
<Item
className={cn(canDrag && 'handle')}
headerClassName={cn(canDrag && 'cursor-grab group-hover:pl-5')}
nodeId={nodeId}
key={list[index].id}
payload={item}
onChange={handleClassChange(index)}
onRemove={handleRemoveClass(index)}
index={index + 1}
readonly={readonly}
filterVar={filterVar}
/>
</div>
</div>
)
})
}
</ReactSortable>
</div>
)}
{!readonly && !collapsed && (
<div className='mt-2'>
<AddButton
onClick={handleAddClass}
text={t(`${i18nPrefix}.addClass`)}
/>
</div>
)}
</>
)
}
export default React.memo(ClassList)

View File

@@ -0,0 +1,74 @@
import type { NodeDefault } from '../../types'
import type { QuestionClassifierNodeType } from './types'
import { genNodeMetaData } from '@/app/components/workflow/utils'
import { BlockEnum } from '@/app/components/workflow/types'
import { BlockClassificationEnum } from '@/app/components/workflow/block-selector/types'
import { AppModeEnum } from '@/types/app'
const i18nPrefix = 'workflow'
const metaData = genNodeMetaData({
classification: BlockClassificationEnum.QuestionUnderstand,
sort: 1,
type: BlockEnum.QuestionClassifier,
})
const nodeDefault: NodeDefault<QuestionClassifierNodeType> = {
metaData,
defaultValue: {
query_variable_selector: [],
model: {
provider: '',
name: '',
mode: AppModeEnum.CHAT,
completion_params: {
temperature: 0.7,
},
},
classes: [
{
id: '1',
name: '',
},
{
id: '2',
name: '',
},
],
_targetBranches: [
{
id: '1',
name: '',
},
{
id: '2',
name: '',
},
],
vision: {
enabled: false,
},
},
checkValid(payload: QuestionClassifierNodeType, t: any) {
let errorMessages = ''
if (!errorMessages && (!payload.query_variable_selector || payload.query_variable_selector.length === 0))
errorMessages = t(`${i18nPrefix}.errorMsg.fieldRequired`, { field: t(`${i18nPrefix}.nodes.questionClassifiers.inputVars`) })
if (!errorMessages && !payload.model.provider)
errorMessages = t(`${i18nPrefix}.errorMsg.fieldRequired`, { field: t(`${i18nPrefix}.nodes.questionClassifiers.model`) })
if (!errorMessages && (!payload.classes || payload.classes.length === 0))
errorMessages = t(`${i18nPrefix}.errorMsg.fieldRequired`, { field: t(`${i18nPrefix}.nodes.questionClassifiers.class`) })
if (!errorMessages && (payload.classes.some(item => !item.name)))
errorMessages = t(`${i18nPrefix}.errorMsg.fieldRequired`, { field: t(`${i18nPrefix}.nodes.questionClassifiers.topicName`) })
if (!errorMessages && payload.vision?.enabled && !payload.vision.configs?.variable_selector?.length)
errorMessages = t(`${i18nPrefix}.errorMsg.fieldRequired`, { field: t(`${i18nPrefix}.errorMsg.fields.visionVariable`) })
return {
isValid: !errorMessages,
errorMessage: errorMessages,
}
},
}
export default nodeDefault

View File

@@ -0,0 +1,119 @@
import type { FC } from 'react'
import React from 'react'
import { useTranslation } from 'react-i18next'
import type { TFunction } from 'i18next'
import type { NodeProps } from 'reactflow'
import { NodeSourceHandle } from '../_base/components/node-handle'
import type { QuestionClassifierNodeType } from './types'
import {
useTextGenerationCurrentProviderAndModelAndModelList,
} from '@/app/components/header/account-setting/model-provider-page/hooks'
import ModelSelector from '@/app/components/header/account-setting/model-provider-page/model-selector'
import ReadonlyInputWithSelectVar from '../_base/components/readonly-input-with-select-var'
import Tooltip from '@/app/components/base/tooltip'
const i18nPrefix = 'workflow.nodes.questionClassifiers'
const MAX_CLASS_TEXT_LENGTH = 50
type TruncatedClassItemProps = {
topic: { id: string; name: string }
index: number
nodeId: string
t: TFunction
}
const TruncatedClassItem: FC<TruncatedClassItemProps> = ({ topic, index, nodeId, t }) => {
const truncatedText = topic.name.length > MAX_CLASS_TEXT_LENGTH
? `${topic.name.slice(0, MAX_CLASS_TEXT_LENGTH)}...`
: topic.name
const shouldShowTooltip = topic.name.length > MAX_CLASS_TEXT_LENGTH
const content = (
<div className='system-xs-regular truncate text-text-tertiary'>
<ReadonlyInputWithSelectVar
value={truncatedText}
nodeId={nodeId}
className='truncate'
/>
</div>
)
return (
<div className='flex flex-col gap-y-0.5 rounded-md bg-workflow-block-parma-bg px-[5px] py-[3px]'>
<div className='system-2xs-semibold-uppercase uppercase text-text-secondary'>
{`${t(`${i18nPrefix}.class`)} ${index + 1}`}
</div>
{shouldShowTooltip
? (<Tooltip
popupContent={
<div className='max-w-[300px] break-words'>
<ReadonlyInputWithSelectVar value={topic.name} nodeId={nodeId}/>
</div>
}
>
{content}
</Tooltip>
)
: content}
</div>
)
}
const Node: FC<NodeProps<QuestionClassifierNodeType>> = (props) => {
const { t } = useTranslation()
const { data, id } = props
const { provider, name: modelId } = data.model
// const tempTopics = data.topics
const topics = data.classes
const {
textGenerationModelList,
} = useTextGenerationCurrentProviderAndModelAndModelList()
const hasSetModel = provider && modelId
if (!hasSetModel && !topics.length)
return null
return (
<div className='mb-1 px-3 py-1'>
{hasSetModel && (
<ModelSelector
defaultModel={{ provider, model: modelId }}
triggerClassName='!h-6 !rounded-md'
modelList={textGenerationModelList}
readonly
/>
)}
{
!!topics.length && (
<div className='mt-2 space-y-0.5'>
<div className='space-y-0.5'>
{topics.map((topic, index) => (
<div
key={topic.id}
className='relative'
>
<TruncatedClassItem
topic={topic}
index={index}
nodeId={id}
t={t}
/>
<NodeSourceHandle
{...props}
handleId={topic.id}
handleClassName='!top-1/2 !-translate-y-1/2 !-right-[21px]'
/>
</div>
))}
</div>
</div>
)
}
</div>
)
}
export default React.memo(Node)

View File

@@ -0,0 +1,140 @@
import type { FC } from 'react'
import React from 'react'
import { useTranslation } from 'react-i18next'
import VarReferencePicker from '../_base/components/variable/var-reference-picker'
import ConfigVision from '../_base/components/config-vision'
import useConfig from './use-config'
import ClassList from './components/class-list'
import AdvancedSetting from './components/advanced-setting'
import type { QuestionClassifierNodeType } from './types'
import Field from '@/app/components/workflow/nodes/_base/components/field'
import ModelParameterModal from '@/app/components/header/account-setting/model-provider-page/model-parameter-modal'
import type { NodePanelProps } from '@/app/components/workflow/types'
import Split from '@/app/components/workflow/nodes/_base/components/split'
import OutputVars, { VarItem } from '@/app/components/workflow/nodes/_base/components/output-vars'
import { FieldCollapse } from '@/app/components/workflow/nodes/_base/components/collapse'
const i18nPrefix = 'workflow.nodes.questionClassifiers'
const Panel: FC<NodePanelProps<QuestionClassifierNodeType>> = ({
id,
data,
}) => {
const { t } = useTranslation()
const {
readOnly,
inputs,
handleModelChanged,
isChatMode,
isChatModel,
handleCompletionParamsChange,
handleQueryVarChange,
handleTopicsChange,
hasSetBlockStatus,
availableVars,
availableNodesWithParent,
handleInstructionChange,
handleMemoryChange,
isVisionModel,
handleVisionResolutionChange,
handleVisionResolutionEnabledChange,
filterVar,
handleSortTopic,
} = useConfig(id, data)
const model = inputs.model
return (
<div className='pt-2'>
<div className='space-y-4 px-4'>
<Field
title={t(`${i18nPrefix}.model`)}
required
>
<ModelParameterModal
popupClassName='!w-[387px]'
isInWorkflow
isAdvancedMode={true}
provider={model?.provider}
completionParams={model.completion_params}
modelId={model.name}
setModel={handleModelChanged}
onCompletionParamsChange={handleCompletionParamsChange}
hideDebugWithMultipleModel
debugWithMultipleModel={false}
readonly={readOnly}
/>
</Field>
<Field
title={t(`${i18nPrefix}.inputVars`)}
required
>
<VarReferencePicker
readonly={readOnly}
isShowNodeName
nodeId={id}
value={inputs.query_variable_selector}
onChange={handleQueryVarChange}
filterVar={filterVar}
/>
</Field>
<Split />
<ConfigVision
nodeId={id}
readOnly={readOnly}
isVisionModel={isVisionModel}
enabled={inputs.vision?.enabled}
onEnabledChange={handleVisionResolutionEnabledChange}
config={inputs.vision?.configs}
onConfigChange={handleVisionResolutionChange}
/>
<ClassList
nodeId={id}
list={inputs.classes}
onChange={handleTopicsChange}
readonly={readOnly}
filterVar={filterVar}
handleSortTopic={handleSortTopic}
/>
<Split />
</div>
<FieldCollapse
title={t(`${i18nPrefix}.advancedSetting`)}
>
<AdvancedSetting
hideMemorySetting={!isChatMode}
instruction={inputs.instruction}
onInstructionChange={handleInstructionChange}
memory={inputs.memory}
onMemoryChange={handleMemoryChange}
readonly={readOnly}
isChatApp={isChatMode}
isChatModel={isChatModel}
hasSetBlockStatus={hasSetBlockStatus}
nodesOutputVars={availableVars}
availableNodes={availableNodesWithParent}
/>
</FieldCollapse>
<Split />
<div>
<OutputVars>
<>
<VarItem
name='class_name'
type='string'
description={t(`${i18nPrefix}.outputVars.className`)}
/>
<VarItem
name='usage'
type='object'
description={t(`${i18nPrefix}.outputVars.usage`)}
/>
</>
</OutputVars>
</div>
</div>
)
}
export default React.memo(Panel)

View File

@@ -0,0 +1,18 @@
import type { CommonNodeType, Memory, ModelConfig, ValueSelector, VisionSetting } from '@/app/components/workflow/types'
export type Topic = {
id: string
name: string
}
export type QuestionClassifierNodeType = CommonNodeType & {
query_variable_selector: ValueSelector
model: ModelConfig
classes: Topic[]
instruction: string
memory?: Memory
vision: {
enabled: boolean
configs?: VisionSetting
}
}

View File

@@ -0,0 +1,204 @@
import { useCallback, useEffect, useRef, useState } from 'react'
import { produce } from 'immer'
import { BlockEnum, VarType } from '../../types'
import type { Memory, ValueSelector, Var } from '../../types'
import {
useIsChatMode, useNodesReadOnly,
useWorkflow,
} from '../../hooks'
import { useStore } from '../../store'
import useAvailableVarList from '../_base/hooks/use-available-var-list'
import useConfigVision from '../../hooks/use-config-vision'
import type { QuestionClassifierNodeType, Topic } from './types'
import useNodeCrud from '@/app/components/workflow/nodes/_base/hooks/use-node-crud'
import { useModelListAndDefaultModelAndCurrentProviderAndModel } from '@/app/components/header/account-setting/model-provider-page/hooks'
import { ModelTypeEnum } from '@/app/components/header/account-setting/model-provider-page/declarations'
import { checkHasQueryBlock } from '@/app/components/base/prompt-editor/constants'
import { useUpdateNodeInternals } from 'reactflow'
import { AppModeEnum } from '@/types/app'
const useConfig = (id: string, payload: QuestionClassifierNodeType) => {
const updateNodeInternals = useUpdateNodeInternals()
const { nodesReadOnly: readOnly } = useNodesReadOnly()
const isChatMode = useIsChatMode()
const defaultConfig = useStore(s => s.nodesDefaultConfigs)?.[payload.type]
const { getBeforeNodesInSameBranch } = useWorkflow()
const startNode = getBeforeNodesInSameBranch(id).find(node => node.data.type === BlockEnum.Start)
const startNodeId = startNode?.id
const { inputs, setInputs } = useNodeCrud<QuestionClassifierNodeType>(id, payload)
const inputRef = useRef(inputs)
useEffect(() => {
inputRef.current = inputs
}, [inputs])
const [modelChanged, setModelChanged] = useState(false)
const {
currentProvider,
currentModel,
} = useModelListAndDefaultModelAndCurrentProviderAndModel(ModelTypeEnum.textGeneration)
const model = inputs.model
const modelMode = inputs.model?.mode
const isChatModel = modelMode === AppModeEnum.CHAT
const {
isVisionModel,
handleVisionResolutionEnabledChange,
handleVisionResolutionChange,
handleModelChanged: handleVisionConfigAfterModelChanged,
} = useConfigVision(model, {
payload: inputs.vision,
onChange: (newPayload) => {
const newInputs = produce(inputs, (draft) => {
draft.vision = newPayload
})
setInputs(newInputs)
},
})
const handleModelChanged = useCallback((model: { provider: string; modelId: string; mode?: string }) => {
const newInputs = produce(inputRef.current, (draft) => {
draft.model.provider = model.provider
draft.model.name = model.modelId
draft.model.mode = model.mode!
})
setInputs(newInputs)
setModelChanged(true)
}, [setInputs])
useEffect(() => {
if (currentProvider?.provider && currentModel?.model && !model.provider) {
handleModelChanged({
provider: currentProvider?.provider,
modelId: currentModel?.model,
mode: currentModel?.model_properties?.mode as string,
})
}
}, [model.provider, currentProvider, currentModel, handleModelChanged])
const handleCompletionParamsChange = useCallback((newParams: Record<string, any>) => {
const newInputs = produce(inputs, (draft) => {
draft.model.completion_params = newParams
})
setInputs(newInputs)
}, [inputs, setInputs])
// change to vision model to set vision enabled, else disabled
useEffect(() => {
if (!modelChanged)
return
setModelChanged(false)
handleVisionConfigAfterModelChanged()
}, [isVisionModel, modelChanged])
const handleQueryVarChange = useCallback((newVar: ValueSelector | string) => {
const newInputs = produce(inputs, (draft) => {
draft.query_variable_selector = newVar as ValueSelector
})
setInputs(newInputs)
}, [inputs, setInputs])
useEffect(() => {
const isReady = defaultConfig && Object.keys(defaultConfig).length > 0
if (isReady) {
let query_variable_selector: ValueSelector = []
if (isChatMode && inputs.query_variable_selector.length === 0 && startNodeId)
query_variable_selector = [startNodeId, 'sys.query']
setInputs({
...inputs,
...defaultConfig,
query_variable_selector: inputs.query_variable_selector.length > 0 ? inputs.query_variable_selector : query_variable_selector,
})
}
}, [defaultConfig])
const handleClassesChange = useCallback((newClasses: any) => {
const newInputs = produce(inputs, (draft) => {
draft.classes = newClasses
draft._targetBranches = newClasses
})
setInputs(newInputs)
}, [inputs, setInputs])
const filterInputVar = useCallback((varPayload: Var) => {
return [VarType.number, VarType.string].includes(varPayload.type)
}, [])
const filterVisionInputVar = useCallback((varPayload: Var) => {
return [VarType.file, VarType.arrayFile].includes(varPayload.type)
}, [])
const {
availableVars,
availableNodesWithParent,
} = useAvailableVarList(id, {
onlyLeafNodeVar: false,
filterVar: filterInputVar,
})
const {
availableVars: availableVisionVars,
} = useAvailableVarList(id, {
onlyLeafNodeVar: false,
filterVar: filterVisionInputVar,
})
const hasSetBlockStatus = {
history: false,
query: isChatMode ? checkHasQueryBlock(inputs.instruction) : false,
context: false,
}
const handleInstructionChange = useCallback((instruction: string) => {
const newInputs = produce(inputs, (draft) => {
draft.instruction = instruction
})
setInputs(newInputs)
}, [inputs, setInputs])
const handleMemoryChange = useCallback((memory?: Memory) => {
const newInputs = produce(inputs, (draft) => {
draft.memory = memory
})
setInputs(newInputs)
}, [inputs, setInputs])
const filterVar = useCallback((varPayload: Var) => {
return varPayload.type === VarType.string
}, [])
const handleSortTopic = useCallback((newTopics: (Topic & { id: string })[]) => {
const newInputs = produce(inputs, (draft) => {
draft.classes = newTopics.filter(Boolean).map(item => ({
id: item.id,
name: item.name,
}))
})
setInputs(newInputs)
updateNodeInternals(id)
}, [id, inputs, setInputs, updateNodeInternals])
return {
readOnly,
inputs,
handleModelChanged,
isChatMode,
isChatModel,
handleCompletionParamsChange,
handleQueryVarChange,
filterVar,
handleTopicsChange: handleClassesChange,
hasSetBlockStatus,
availableVars,
availableNodesWithParent,
availableVisionVars,
handleInstructionChange,
handleMemoryChange,
isVisionModel,
handleVisionResolutionEnabledChange,
handleVisionResolutionChange,
handleSortTopic,
}
}
export default useConfig

View File

@@ -0,0 +1,152 @@
import type { RefObject } from 'react'
import { useTranslation } from 'react-i18next'
import type { Props as FormProps } from '@/app/components/workflow/nodes/_base/components/before-run-form/form'
import type { InputVar, Var, Variable } from '@/app/components/workflow/types'
import { InputVarType, VarType } from '@/app/components/workflow/types'
import type { QuestionClassifierNodeType } from './types'
import useNodeCrud from '../_base/hooks/use-node-crud'
import { useCallback } from 'react'
import useConfigVision from '../../hooks/use-config-vision'
import { noop } from 'lodash-es'
import { findVariableWhenOnLLMVision } from '../utils'
import useAvailableVarList from '../_base/hooks/use-available-var-list'
const i18nPrefix = 'workflow.nodes.questionClassifiers'
type Params = {
id: string,
payload: QuestionClassifierNodeType,
runInputData: Record<string, any>
runInputDataRef: RefObject<Record<string, any>>
getInputVars: (textList: string[]) => InputVar[]
setRunInputData: (data: Record<string, any>) => void
toVarInputs: (variables: Variable[]) => InputVar[]
}
const useSingleRunFormParams = ({
id,
payload,
runInputData,
runInputDataRef,
getInputVars,
setRunInputData,
}: Params) => {
const { t } = useTranslation()
const { inputs } = useNodeCrud<QuestionClassifierNodeType>(id, payload)
const model = inputs.model
const {
isVisionModel,
} = useConfigVision(model, {
payload: inputs.vision,
onChange: noop,
})
const visionFiles = runInputData['#files#']
const setVisionFiles = useCallback((newFiles: any[]) => {
setRunInputData?.({
...runInputDataRef.current,
'#files#': newFiles,
})
}, [runInputDataRef, setRunInputData])
const varInputs = getInputVars([inputs.instruction])
const inputVarValues = (() => {
const vars: Record<string, any> = {}
Object.keys(runInputData)
.filter(key => !['#files#'].includes(key))
.forEach((key) => {
vars[key] = runInputData[key]
})
return vars
})()
const setInputVarValues = useCallback((newPayload: Record<string, any>) => {
const newVars = {
...newPayload,
'#files#': runInputDataRef.current['#files#'],
}
setRunInputData?.(newVars)
}, [runInputDataRef, setRunInputData])
const filterVisionInputVar = useCallback((varPayload: Var) => {
return [VarType.file, VarType.arrayFile].includes(varPayload.type)
}, [])
const {
availableVars: availableVisionVars,
} = useAvailableVarList(id, {
onlyLeafNodeVar: false,
filterVar: filterVisionInputVar,
})
const forms = (() => {
const forms: FormProps[] = []
forms.push(
{
label: t('workflow.nodes.llm.singleRun.variable')!,
inputs: [{
label: t(`${i18nPrefix}.inputVars`)!,
variable: 'query',
type: InputVarType.paragraph,
required: true,
}, ...varInputs],
values: inputVarValues,
onChange: setInputVarValues,
},
)
if (isVisionModel && payload.vision?.enabled && payload.vision?.configs?.variable_selector) {
const currentVariable = findVariableWhenOnLLMVision(payload.vision.configs.variable_selector, availableVisionVars)
forms.push(
{
label: t('workflow.nodes.llm.vision')!,
inputs: [{
label: currentVariable?.variable as any,
variable: '#files#',
type: currentVariable?.formType as any,
required: false,
}],
values: { '#files#': visionFiles },
onChange: keyValue => setVisionFiles(keyValue['#files#']),
},
)
}
return forms
})()
const getDependentVars = () => {
const promptVars = varInputs.map((item) => {
// Guard against null/undefined variable to prevent app crash
if (!item.variable || typeof item.variable !== 'string')
return []
return item.variable.slice(1, -1).split('.')
}).filter(arr => arr.length > 0)
const vars = [payload.query_variable_selector, ...promptVars]
if (isVisionModel && payload.vision?.enabled && payload.vision?.configs?.variable_selector) {
const visionVar = payload.vision.configs.variable_selector
vars.push(visionVar)
}
return vars
}
const getDependentVar = (variable: string) => {
if(variable === 'query')
return payload.query_variable_selector
if(variable === '#files#')
return payload.vision.configs?.variable_selector
return false
}
return {
forms,
getDependentVars,
getDependentVar,
}
}
export default useSingleRunFormParams

View File

@@ -0,0 +1,3 @@
export const checkNodeValid = () => {
return true
}