Merge branch 'feat/plugins' of https://github.com/langgenius/dify into feat/plugins

This commit is contained in:
Yi 2024-12-26 17:40:42 +08:00
commit b4e9dddbca
15 changed files with 255 additions and 78 deletions

View File

@ -275,7 +275,10 @@ function Form<
if (formSchema.type === FormTypeEnum.toolSelector) {
const {
variable, label, required,
variable,
label,
required,
scope,
} = formSchema as (CredentialFormSchemaTextInput | CredentialFormSchemaSecretInput)
return (
@ -288,6 +291,7 @@ function Form<
{tooltipContent}
</div>
<ToolSelector
scope={scope}
disabled={readonly}
value={value[variable]}
onSelect={item => handleFormChange(variable, item as any)} />

View File

@ -7,6 +7,7 @@ import ActionList from './action-list'
import ModelList from './model-list'
import AgentStrategyList from './agent-strategy-list'
import Drawer from '@/app/components/base/drawer'
import ToolSelector from '@/app/components/plugins/plugin-detail-panel/tool-selector'
import type { PluginDetail } from '@/app/components/plugins/types'
import cn from '@/utils/classnames'
@ -27,6 +28,12 @@ const PluginDetailPanel: FC<Props> = ({
onUpdate()
}
const [value, setValue] = React.useState<any>(undefined)
const testChange = (val: any) => {
console.log('tool change', val)
setValue(val)
}
if (!detail)
return null
@ -52,6 +59,14 @@ const PluginDetailPanel: FC<Props> = ({
{!!detail.declaration.agent_strategy && <AgentStrategyList detail={detail} />}
{!!detail.declaration.endpoint && <EndpointList detail={detail} />}
{!!detail.declaration.model && <ModelList detail={detail} />}
{false && (
<div className='px-4 py-2'>
<ToolSelector
value={value}
onSelect={item => testChange(item)}
/>
</div>
)}
</div>
</>
)}

View File

@ -2,6 +2,9 @@
import type { FC } from 'react'
import React, { useMemo, useState } from 'react'
import { useTranslation } from 'react-i18next'
import {
RiArrowRightUpLine,
} from '@remixicon/react'
import {
PortalToFollowElem,
PortalToFollowElemContent,
@ -13,6 +16,10 @@ import Button from '@/app/components/base/button'
import Indicator from '@/app/components/header/indicator'
import ToolCredentialForm from '@/app/components/plugins/plugin-detail-panel/tool-selector/tool-credentials-form'
import Toast from '@/app/components/base/toast'
import Textarea from '@/app/components/base/textarea'
import Divider from '@/app/components/base/divider'
import Form from '@/app/components/header/account-setting/model-provider-page/model-modal/Form'
import { addDefaultValue, toolParametersToFormSchemas } from '@/app/components/tools/utils/to-form-schema'
import { useAppContext } from '@/context/app-context'
import {
@ -34,6 +41,8 @@ type Props = {
value?: {
provider: string
tool_name: string
description?: string
parameters?: Record<string, any>
}
disabled?: boolean
placement?: Placement
@ -41,15 +50,19 @@ type Props = {
onSelect: (tool: {
provider: string
tool_name: string
description?: string
parameters?: Record<string, any>
}) => void
supportAddCustomTool?: boolean
scope?: string
}
const ToolSelector: FC<Props> = ({
value,
disabled,
placement = 'bottom',
placement = 'left',
offset = 4,
onSelect,
scope,
}) => {
const { t } = useTranslation()
const [isShow, onShowChange] = useState(false)
@ -62,23 +75,52 @@ const ToolSelector: FC<Props> = ({
const { data: customTools } = useAllCustomTools()
const { data: workflowTools } = useAllWorkflowTools()
const invalidateAllBuiltinTools = useInvalidateAllBuiltInTools()
const currentProvider = useMemo(() => {
const mergedTools = [...(buildInTools || []), ...(customTools || []), ...(workflowTools || [])]
return mergedTools.find((toolWithProvider) => {
return toolWithProvider.id === value?.provider && toolWithProvider.tools.some(tool => tool.name === value?.tool_name)
})
}, [value, buildInTools, customTools, workflowTools])
const [isShowChooseTool, setIsShowChooseTool] = useState(false)
const handleSelectTool = (tool: ToolDefaultValue) => {
const paramValues = addDefaultValue(tool.params, toolParametersToFormSchemas(tool.paramSchemas as any))
const toolValue = {
provider: tool.provider_id,
tool_name: tool.tool_name,
description: '',
parameters: paramValues,
}
onSelect(toolValue)
setIsShowChooseTool(false)
if (tool.provider_type === CollectionType.builtIn && tool.is_team_authorization)
onShowChange(false)
// if (tool.provider_type === CollectionType.builtIn && tool.is_team_authorization)
// onShowChange(false)
}
const handleDescriptionChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
onSelect({
...value,
description: e.target.value || '',
} as any)
}
const currentToolParams = useMemo(() => {
if (!currentProvider) return []
return currentProvider.tools.find(tool => tool.name === value?.tool_name)?.parameters || []
}, [currentProvider, value])
const formSchemas = useMemo(() => toolParametersToFormSchemas(currentToolParams), [currentToolParams])
const handleFormChange = (v: Record<string, any>) => {
const toolValue = {
...value,
parameters: v,
}
onSelect(toolValue as any)
}
// authorization
const { isCurrentWorkspaceManager } = useAppContext()
const [isShowSettingAuth, setShowSettingAuth] = useState(false)
const handleCredentialSettingUpdate = () => {
@ -108,32 +150,79 @@ const ToolSelector: FC<Props> = ({
onClick={handleTriggerClick}
>
<ToolTrigger
isConfigure
open={isShow}
value={value}
provider={currentProvider}
/>
</PortalToFollowElemTrigger>
<PortalToFollowElemContent className='z-[1000]'>
<div className="relative w-[389px] min-h-20 rounded-xl bg-components-panel-bg-blur border-[0.5px] border-components-panel-border shadow-lg">
<div className='px-4 py-3 flex flex-col gap-1'>
<div className='h-6 flex items-center system-sm-semibold text-text-secondary'>{t('tools.toolSelector.label')}</div>
<ToolPicker
placement='bottom'
offset={offset}
trigger={
<ToolTrigger
open={isShowChooseTool}
value={value}
provider={currentProvider}
/>
}
isShow={isShowChooseTool}
onShowChange={setIsShowChooseTool}
disabled={false}
supportAddCustomTool
onSelect={handleSelectTool}
/>
<div className="relative w-[361px] min-h-20 max-h-[642px] overflow-y-auto pb-2 rounded-xl backdrop-blur-sm bg-components-panel-bg-blur border-[0.5px] border-components-panel-border shadow-lg">
<div className='px-4 pt-3.5 pb-1 text-text-primary system-xl-semibold'>{t('plugin.detailPanel.toolSelector.title')}</div>
{/* base form */}
<div className='px-4 py-2 flex flex-col gap-3'>
<div className='flex flex-col gap-1'>
<div className='h-6 flex items-center system-sm-semibold text-text-secondary'>{t('plugin.detailPanel.toolSelector.toolLabel')}</div>
<ToolPicker
placement='bottom'
offset={offset}
trigger={
<ToolTrigger
open={isShowChooseTool}
value={value}
provider={currentProvider}
/>
}
isShow={isShowChooseTool}
onShowChange={setIsShowChooseTool}
disabled={false}
supportAddCustomTool
onSelect={handleSelectTool}
scope={scope}
/>
</div>
<div className='flex flex-col gap-1'>
<div className='h-6 flex items-center system-sm-semibold text-text-secondary'>{t('plugin.detailPanel.toolSelector.descriptionLabel')}</div>
<Textarea
className='resize-none'
placeholder={t('plugin.detailPanel.toolSelector.descriptionPlaceholder')}
value={value?.description || ''}
onChange={handleDescriptionChange}
/>
</div>
</div>
{/* authorization */}
{!isShowSettingAuth && currentProvider && currentProvider.type === CollectionType.builtIn && currentProvider.allow_delete && (
<div className='px-4 pt-3 flex flex-col'>
<div className='flex items-center gap-2'>
<div className='text-text-tertiary system-xs-medium-uppercase'>{t('plugin.detailPanel.toolSelector.auth')}</div>
<Divider bgStyle='gradient' className='grow' />
</div>
<div className='py-2'>
{!currentProvider.is_team_authorization && (
<Button
variant='primary'
className={cn('shrink-0 w-full')}
onClick={() => setShowSettingAuth(true)}
disabled={!isCurrentWorkspaceManager}
>
{t('tools.auth.unauthorized')}
</Button>
)}
{currentProvider.is_team_authorization && (
<Button
variant='secondary'
className={cn('shrink-0 w-full')}
onClick={() => setShowSettingAuth(true)}
disabled={!isCurrentWorkspaceManager}
>
<Indicator className='mr-2' color={'green'} />
{t('tools.auth.authorized')}
</Button>
)}
</div>
</div>
)}
{/* authorization panel */}
{isShowSettingAuth && currentProvider && (
<div className='px-4 pb-4 border-t border-divider-subtle'>
@ -147,31 +236,34 @@ const ToolSelector: FC<Props> = ({
/>
</div>
)}
{!isShowSettingAuth && currentProvider && currentProvider.type === CollectionType.builtIn && currentProvider.is_team_authorization && currentProvider.allow_delete && (
<div className='px-4 py-3 flex items-center border-t border-divider-subtle'>
<div className='grow mr-3 h-6 flex items-center system-sm-semibold text-text-secondary'>{t('tools.toolSelector.auth')}</div>
{isCurrentWorkspaceManager && (
<Button
variant='secondary'
size='small'
onClick={() => {}}
>
<Indicator className='mr-2' color={'green'} />
{t('tools.auth.authorized')}
</Button>
)}
</div>
)}
{!isShowSettingAuth && currentProvider && currentProvider.type === CollectionType.builtIn && !currentProvider.is_team_authorization && currentProvider.allow_delete && (
<div className='px-4 py-3 flex items-center border-t border-divider-subtle'>
<Button
variant='primary'
className={cn('shrink-0 w-full')}
onClick={() => setShowSettingAuth(true)}
disabled={!isCurrentWorkspaceManager}
>
{t('tools.auth.unauthorized')}
</Button>
{/* tool settings */}
{currentToolParams.length > 0 && currentProvider?.is_team_authorization && (
<div className='px-4 pt-3'>
<div className='flex items-center gap-2'>
<div className='text-text-tertiary system-xs-medium-uppercase'>{t('plugin.detailPanel.toolSelector.settings')}</div>
<Divider bgStyle='gradient' className='grow' />
</div>
<div className='py-2'>
<Form
value={value?.parameters || {}}
onChange={handleFormChange}
formSchemas={formSchemas as any}
isEditMode={true}
showOnVariableMap={{}}
validating={false}
inputClassName='bg-components-input-bg-normal hover:bg-components-input-bg-hover'
fieldMoreInfo={item => item.url
? (<a
href={item.url}
target='_blank' rel='noopener noreferrer'
className='inline-flex items-center text-xs text-text-accent'
>
{t('tools.howToGet')}
<RiArrowRightUpLine className='ml-1 w-3 h-3' />
</a>)
: null}
/>
</div>
</div>
)}
</div>

View File

@ -3,6 +3,7 @@ import React from 'react'
import { useTranslation } from 'react-i18next'
import {
RiArrowDownSLine,
RiEqualizer2Line,
} from '@remixicon/react'
import BlockIcon from '@/app/components/workflow/block-icon'
import { BlockEnum } from '@/app/components/workflow/types'
@ -16,21 +17,23 @@ type Props = {
provider: string
tool_name: string
}
isConfigure?: boolean
}
const ToolTrigger = ({
open,
provider,
value,
isConfigure,
}: Props) => {
const { t } = useTranslation()
return (
<div className={cn(
'group flex items-center p-2 pl-3 bg-components-input-bg-normal rounded-lg cursor-pointer hover:bg-state-base-hover-alt',
open && 'bg-state-base-hover-alt',
value && 'pl-1.5 py-1.5',
value?.provider && 'pl-1.5 py-1.5',
)}>
{value && provider && (
{value?.provider && provider && (
<div className='shrink-0 mr-1 p-px rounded-lg bg-components-panel-bg border border-components-panel-border'>
<BlockIcon
className='!w-4 !h-4'
@ -39,13 +42,20 @@ const ToolTrigger = ({
/>
</div>
)}
{value && (
{value?.tool_name && (
<div className='grow system-sm-medium text-components-input-text-filled'>{value.tool_name}</div>
)}
{!value && (
<div className='grow text-components-input-text-placeholder system-sm-regular'>{t('tools.toolSelector.placeholder')}</div>
{!value?.provider && (
<div className='grow text-components-input-text-placeholder system-sm-regular'>
{!isConfigure ? t('plugin.detailPanel.toolSelector.placeholder') : t('plugin.detailPanel.configureTool')}
</div>
)}
{isConfigure && (
<RiEqualizer2Line className={cn('shrink-0 ml-0.5 w-4 h-4 text-text-quaternary group-hover:text-text-secondary', open && 'text-text-secondary')} />
)}
{!isConfigure && (
<RiArrowDownSLine className={cn('shrink-0 ml-0.5 w-4 h-4 text-text-quaternary group-hover:text-text-secondary', open && 'text-text-secondary')} />
)}
<RiArrowDownSLine className={cn('shrink-0 ml-0.5 w-4 h-4 text-text-quaternary group-hover:text-text-secondary', open && 'text-text-secondary')} />
</div>
)
}

View File

@ -1,7 +1,7 @@
'use client'
import type { FC } from 'react'
import React from 'react'
import { useState } from 'react'
import { useMemo, useState } from 'react'
import {
PortalToFollowElem,
PortalToFollowElemContent,
@ -34,6 +34,7 @@ type Props = {
onShowChange: (isShow: boolean) => void
onSelect: (tool: ToolDefaultValue) => void
supportAddCustomTool?: boolean
scope?: string
}
const ToolPicker: FC<Props> = ({
@ -45,6 +46,7 @@ const ToolPicker: FC<Props> = ({
onShowChange,
onSelect,
supportAddCustomTool,
scope = 'all',
}) => {
const { t } = useTranslation()
const [searchText, setSearchText] = useState('')
@ -55,6 +57,35 @@ const ToolPicker: FC<Props> = ({
const invalidateCustomTools = useInvalidateAllCustomTools()
const { data: workflowTools } = useAllWorkflowTools()
const { builtinToolList, customToolList, workflowToolList } = useMemo(() => {
if (scope === 'plugins') {
return {
builtinToolList: buildInTools,
customToolList: [],
workflowToolList: [],
}
}
if (scope === 'custom') {
return {
builtinToolList: [],
customToolList: customTools,
workflowToolList: [],
}
}
if (scope === 'workflow') {
return {
builtinToolList: [],
customToolList: [],
workflowToolList: workflowTools,
}
}
return {
builtinToolList: buildInTools,
customToolList: customTools,
workflowToolList: workflowTools,
}
}, [scope, buildInTools, customTools, workflowTools])
const handleAddedCustomTool = invalidateCustomTools
const handleTriggerClick = () => {
@ -122,9 +153,9 @@ const ToolPicker: FC<Props> = ({
tags={tags}
searchText={searchText}
onSelect={handleSelect}
buildInTools={buildInTools || []}
customTools={customTools || []}
workflowTools={workflowTools || []}
buildInTools={builtinToolList || []}
customTools={customToolList || []}
workflowTools={workflowToolList || []}
supportAddCustomTool={supportAddCustomTool}
onAddedCustomTool={handleAddedCustomTool}
onShowAddCustomCollectionModal={showEditCustomCollectionModal}

View File

@ -59,6 +59,7 @@ const ToolItem: FC<Props> = ({
title: payload.label[language],
is_team_authorization: provider.is_team_authorization,
output_schema: payload.output_schema,
paramSchemas: payload.parameters,
params,
})
}}

View File

@ -27,5 +27,6 @@ export type ToolDefaultValue = {
title: string
is_team_authorization: boolean
params: Record<string, any>
paramSchemas: Record<string, any>
output_schema: Record<string, any>
}

View File

@ -8,6 +8,7 @@ import Form from '@/app/components/header/account-setting/model-provider-page/mo
import { Agent } from '@/app/components/base/icons/src/vender/workflow'
import { InputNumber } from '@/app/components/base/input-number'
import Slider from '@/app/components/base/slider'
import ToolSelector from '@/app/components/plugins/plugin-detail-panel/tool-selector'
import Field from './field'
import type { ComponentProps } from 'react'
@ -29,9 +30,10 @@ export type AgentStrategyProps = {
type CustomSchema<Type, Field = {}> = Omit<CredentialFormSchema, 'type'> & { type: Type } & Field
type MaxIterFormSchema = CustomSchema<'max-iter'>
type ToolSelectorSchema = CustomSchema<'array[tools]'>
type ToolSelectorSchema = CustomSchema<'tool-selector'>
type MultipleToolSelectorSchema = CustomSchema<'array[tools]'>
type CustomField = MaxIterFormSchema | ToolSelectorSchema
type CustomField = MaxIterFormSchema | ToolSelectorSchema | MultipleToolSelectorSchema
export const AgentStrategy = (props: AgentStrategyProps) => {
const { strategy, onStrategyChange, formSchema, formValue, onFormValueChange } = props
@ -61,9 +63,23 @@ export const AgentStrategy = (props: AgentStrategyProps) => {
</div>
</Field>
}
case 'tool-selector': {
const value = props.value[schema.variable]
const onChange = (value: any) => {
props.onChange({ ...props.value, [schema.variable]: value })
}
return (
<Field title={'tool selector'} tooltip={'tool selector'}>
<ToolSelector
value={value}
onSelect={item => onChange(item)}
/>
</Field>
)
}
case 'array[tools]': {
return <Field title={'tool selector'} tooltip={'tool selector'}>
tool selector
multiple tool selector TODO
</Field>
}
}

View File

@ -4,7 +4,6 @@ import type { AgentNodeType } from './types'
const nodeDefault: NodeDefault<AgentNodeType> = {
defaultValue: {
max_iterations: 3,
},
getAvailablePrevNodes(isChatMode) {
return isChatMode

View File

@ -9,12 +9,6 @@ import { useTranslation } from 'react-i18next'
const AgentPanel: FC<NodePanelProps<AgentNodeType>> = (props) => {
const { inputs, setInputs, currentStrategy } = useConfig(props.id, props.data)
const { t } = useTranslation()
const [iter, setIter] = [inputs.max_iterations, (value: number) => {
setInputs({
...inputs,
max_iterations: value,
})
}]
return <div className='space-y-2 my-2'>
<Field title={t('workflow.nodes.agent.strategy.label')} className='px-4' >
<AgentStrategy

View File

@ -2,7 +2,6 @@ import type { CommonNodeType } from '@/app/components/workflow/types'
import type { ToolVarInputs } from '../tool/types'
export type AgentNodeType = CommonNodeType & {
max_iterations: number
agent_strategy_provider_name?: string
agent_strategy_name?: string
agent_strategy_label?: string

View File

@ -65,6 +65,18 @@ const translation = {
serviceOk: 'Service OK',
disabled: 'Disabled',
modelNum: '{{num}} MODELS INCLUDED',
toolSelector: {
title: 'Add tool',
toolLabel: 'Tool',
descriptionLabel: 'Tool description',
descriptionPlaceholder: 'Brief description of the tool\'s purpose, e.g., get the temperature for a specific location.',
placeholder: 'Select a tool...',
auth: 'AUTHORIZATION',
settings: 'TOOL SETTINGS',
},
configureApp: 'Configure App',
configureModel: 'Configure model',
configureTool: 'Configure tool',
},
install: '{{num}} installs',
installAction: 'Install',

View File

@ -152,11 +152,6 @@ const translation = {
openInStudio: 'Open in Studio',
toolNameUsageTip: 'Tool call name for agent reasoning and prompting',
copyToolName: 'Copy Name',
toolSelector: {
label: 'TOOL',
placeholder: 'Select a tool...',
auth: 'AUTHORIZATION',
},
noTools: 'No tools found',
}

View File

@ -65,6 +65,18 @@ const translation = {
serviceOk: '服务正常',
disabled: '停用',
modelNum: '{{num}} 模型已包含',
toolSelector: {
title: '添加工具',
toolLabel: '工具',
descriptionLabel: '工具描述',
descriptionPlaceholder: '简要描述工具目的,例如,获取特定位置的温度。',
placeholder: '选择工具',
auth: '授权',
settings: '工具设置',
},
configureApp: '应用设置',
configureModel: '模型设置',
configureTool: '工具设置',
},
install: '{{num}} 次安装',
installAction: '安装',

View File

@ -152,10 +152,6 @@ const translation = {
openInStudio: '在工作室中打开',
toolNameUsageTip: '工具调用名称,用于 Agent 推理和提示词',
copyToolName: '复制名称',
toolSelector: {
label: '工具',
placeholder: '选择一个工具...',
},
noTools: '没有工具',
}