index.tsx 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  1. 'use client'
  2. import type { FC } from 'react'
  3. import React, { useState } from 'react'
  4. import { useTranslation } from 'react-i18next'
  5. import { useBoolean } from 'ahooks'
  6. import type { Timeout } from 'ahooks/lib/useRequest/src/types'
  7. import { useContext } from 'use-context-selector'
  8. import produce from 'immer'
  9. import {
  10. RiDeleteBinLine,
  11. } from '@remixicon/react'
  12. import Panel from '../base/feature-panel'
  13. import EditModal from './config-modal'
  14. import IconTypeIcon from './input-type-icon'
  15. import type { IInputTypeIconProps } from './input-type-icon'
  16. import s from './style.module.css'
  17. import SelectVarType from './select-var-type'
  18. import { BracketsX as VarIcon } from '@/app/components/base/icons/src/vender/line/development'
  19. import Tooltip from '@/app/components/base/tooltip'
  20. import type { PromptVariable } from '@/models/debug'
  21. import { DEFAULT_VALUE_MAX_LEN, getMaxVarNameLength } from '@/config'
  22. import { checkKeys, getNewVar } from '@/utils/var'
  23. import Switch from '@/app/components/base/switch'
  24. import Toast from '@/app/components/base/toast'
  25. import { Settings01 } from '@/app/components/base/icons/src/vender/line/general'
  26. import Confirm from '@/app/components/base/confirm'
  27. import ConfigContext from '@/context/debug-configuration'
  28. import { AppType } from '@/types/app'
  29. import type { ExternalDataTool } from '@/models/common'
  30. import { useModalContext } from '@/context/modal-context'
  31. import { useEventEmitterContextContext } from '@/context/event-emitter'
  32. import type { InputVar } from '@/app/components/workflow/types'
  33. import { InputVarType } from '@/app/components/workflow/types'
  34. export const ADD_EXTERNAL_DATA_TOOL = 'ADD_EXTERNAL_DATA_TOOL'
  35. type ExternalDataToolParams = {
  36. key: string
  37. type: string
  38. index: number
  39. name: string
  40. config?: Record<string, any>
  41. icon?: string
  42. icon_background?: string
  43. }
  44. export type IConfigVarProps = {
  45. promptVariables: PromptVariable[]
  46. readonly?: boolean
  47. onPromptVariablesChange?: (promptVariables: PromptVariable[]) => void
  48. }
  49. let conflictTimer: Timeout
  50. const ConfigVar: FC<IConfigVarProps> = ({ promptVariables, readonly, onPromptVariablesChange }) => {
  51. const { t } = useTranslation()
  52. const {
  53. mode,
  54. dataSets,
  55. } = useContext(ConfigContext)
  56. const { eventEmitter } = useEventEmitterContextContext()
  57. const hasVar = promptVariables.length > 0
  58. const updatePromptVariable = (key: string, updateKey: string, newValue: string | boolean) => {
  59. const newPromptVariables = promptVariables.map((item) => {
  60. if (item.key === key) {
  61. return {
  62. ...item,
  63. [updateKey]: newValue,
  64. }
  65. }
  66. return item
  67. })
  68. onPromptVariablesChange?.(newPromptVariables)
  69. }
  70. const [currIndex, setCurrIndex] = useState<number>(-1)
  71. const currItem = currIndex !== -1 ? promptVariables[currIndex] : null
  72. const currItemToEdit: InputVar | null = (() => {
  73. if (!currItem)
  74. return null
  75. return {
  76. ...currItem,
  77. label: currItem.name,
  78. variable: currItem.key,
  79. type: currItem.type === 'string' ? InputVarType.textInput : currItem.type,
  80. } as InputVar
  81. })()
  82. const updatePromptVariableItem = (payload: InputVar) => {
  83. const newPromptVariables = produce(promptVariables, (draft) => {
  84. const { variable, label, type, ...rest } = payload
  85. draft[currIndex] = {
  86. ...rest,
  87. type: type === InputVarType.textInput ? 'string' : type,
  88. key: variable,
  89. name: label as string,
  90. }
  91. if (payload.type === InputVarType.textInput)
  92. draft[currIndex].max_length = draft[currIndex].max_length || DEFAULT_VALUE_MAX_LEN
  93. if (payload.type !== InputVarType.select)
  94. delete draft[currIndex].options
  95. })
  96. onPromptVariablesChange?.(newPromptVariables)
  97. }
  98. const updatePromptKey = (index: number, newKey: string) => {
  99. clearTimeout(conflictTimer)
  100. const { isValid, errorKey, errorMessageKey } = checkKeys([newKey], true)
  101. if (!isValid) {
  102. Toast.notify({
  103. type: 'error',
  104. message: t(`appDebug.varKeyError.${errorMessageKey}`, { key: errorKey }),
  105. })
  106. return
  107. }
  108. const newPromptVariables = promptVariables.map((item, i) => {
  109. if (i === index) {
  110. return {
  111. ...item,
  112. key: newKey,
  113. }
  114. }
  115. return item
  116. })
  117. conflictTimer = setTimeout(() => {
  118. const isKeyExists = promptVariables.some(item => item.key?.trim() === newKey.trim())
  119. if (isKeyExists) {
  120. Toast.notify({
  121. type: 'error',
  122. message: t('appDebug.varKeyError.keyAlreadyExists', { key: newKey }),
  123. })
  124. }
  125. }, 1000)
  126. onPromptVariablesChange?.(newPromptVariables)
  127. }
  128. const updatePromptNameIfNameEmpty = (index: number, newKey: string) => {
  129. if (!newKey)
  130. return
  131. const newPromptVariables = promptVariables.map((item, i) => {
  132. if (i === index && !item.name) {
  133. return {
  134. ...item,
  135. name: newKey,
  136. }
  137. }
  138. return item
  139. })
  140. onPromptVariablesChange?.(newPromptVariables)
  141. }
  142. const { setShowExternalDataToolModal } = useModalContext()
  143. const handleOpenExternalDataToolModal = (
  144. { key, type, index, name, config, icon, icon_background }: ExternalDataToolParams,
  145. oldPromptVariables: PromptVariable[],
  146. ) => {
  147. setShowExternalDataToolModal({
  148. payload: {
  149. type,
  150. variable: key,
  151. label: name,
  152. config,
  153. icon,
  154. icon_background,
  155. },
  156. onSaveCallback: (newExternalDataTool: ExternalDataTool) => {
  157. const newPromptVariables = oldPromptVariables.map((item, i) => {
  158. if (i === index) {
  159. return {
  160. key: newExternalDataTool.variable as string,
  161. name: newExternalDataTool.label as string,
  162. enabled: newExternalDataTool.enabled,
  163. type: newExternalDataTool.type as string,
  164. config: newExternalDataTool.config,
  165. required: item.required,
  166. icon: newExternalDataTool.icon,
  167. icon_background: newExternalDataTool.icon_background,
  168. }
  169. }
  170. return item
  171. })
  172. onPromptVariablesChange?.(newPromptVariables)
  173. },
  174. onCancelCallback: () => {
  175. if (!key)
  176. onPromptVariablesChange?.(promptVariables.filter((_, i) => i !== index))
  177. },
  178. onValidateBeforeSaveCallback: (newExternalDataTool: ExternalDataTool) => {
  179. for (let i = 0; i < promptVariables.length; i++) {
  180. if (promptVariables[i].key === newExternalDataTool.variable && i !== index) {
  181. Toast.notify({ type: 'error', message: t('appDebug.varKeyError.keyAlreadyExists', { key: promptVariables[i].key }) })
  182. return false
  183. }
  184. }
  185. return true
  186. },
  187. })
  188. }
  189. const handleAddVar = (type: string) => {
  190. const newVar = getNewVar('', type)
  191. const newPromptVariables = [...promptVariables, newVar]
  192. onPromptVariablesChange?.(newPromptVariables)
  193. if (type === 'api') {
  194. handleOpenExternalDataToolModal({
  195. type,
  196. key: newVar.key,
  197. name: newVar.name,
  198. index: promptVariables.length,
  199. }, newPromptVariables)
  200. }
  201. }
  202. eventEmitter?.useSubscription((v: any) => {
  203. if (v.type === ADD_EXTERNAL_DATA_TOOL) {
  204. const payload = v.payload
  205. onPromptVariablesChange?.([
  206. ...promptVariables,
  207. {
  208. key: payload.variable as string,
  209. name: payload.label as string,
  210. enabled: payload.enabled,
  211. type: payload.type as string,
  212. config: payload.config,
  213. required: true,
  214. icon: payload.icon,
  215. icon_background: payload.icon_background,
  216. },
  217. ])
  218. }
  219. })
  220. const [isShowDeleteContextVarModal, { setTrue: showDeleteContextVarModal, setFalse: hideDeleteContextVarModal }] = useBoolean(false)
  221. const [removeIndex, setRemoveIndex] = useState<number | null>(null)
  222. const didRemoveVar = (index: number) => {
  223. onPromptVariablesChange?.(promptVariables.filter((_, i) => i !== index))
  224. }
  225. const handleRemoveVar = (index: number) => {
  226. const removeVar = promptVariables[index]
  227. if (mode === AppType.completion && dataSets.length > 0 && removeVar.is_context_var) {
  228. showDeleteContextVarModal()
  229. setRemoveIndex(index)
  230. return
  231. }
  232. didRemoveVar(index)
  233. }
  234. // const [currKey, setCurrKey] = useState<string | null>(null)
  235. const [isShowEditModal, { setTrue: showEditModal, setFalse: hideEditModal }] = useBoolean(false)
  236. const handleConfig = ({ key, type, index, name, config, icon, icon_background }: ExternalDataToolParams) => {
  237. // setCurrKey(key)
  238. setCurrIndex(index)
  239. if (type !== 'string' && type !== 'paragraph' && type !== 'select' && type !== 'number') {
  240. handleOpenExternalDataToolModal({ key, type, index, name, config, icon, icon_background }, promptVariables)
  241. return
  242. }
  243. showEditModal()
  244. }
  245. return (
  246. <Panel
  247. className="mt-4"
  248. headerIcon={
  249. <VarIcon className='w-4 h-4 text-primary-500' />
  250. }
  251. title={
  252. <div className='flex items-center'>
  253. <div className='mr-1'>{t('appDebug.variableTitle')}</div>
  254. {!readonly && (
  255. <Tooltip
  256. popupContent={
  257. <div className='w-[180px]'>
  258. {t('appDebug.variableTip')}
  259. </div>
  260. }
  261. />
  262. )}
  263. </div>
  264. }
  265. headerRight={!readonly ? <SelectVarType onChange={handleAddVar} /> : null}
  266. >
  267. {!hasVar && (
  268. <div className='pt-2 pb-1 text-xs text-gray-500'>{t('appDebug.notSetVar')}</div>
  269. )}
  270. {hasVar && (
  271. <div className='rounded-lg border border-gray-200 bg-white overflow-x-auto'>
  272. <table className={`${s.table} min-w-[440px] w-full max-w-full border-collapse border-0 rounded-lg text-sm`}>
  273. <thead className="border-b border-gray-200 text-gray-500 text-xs font-medium">
  274. <tr className='uppercase'>
  275. <td>{t('appDebug.variableTable.key')}</td>
  276. <td>{t('appDebug.variableTable.name')}</td>
  277. {!readonly && (
  278. <>
  279. <td>{t('appDebug.variableTable.optional')}</td>
  280. <td>{t('appDebug.variableTable.action')}</td>
  281. </>
  282. )}
  283. </tr>
  284. </thead>
  285. <tbody className="text-gray-700">
  286. {promptVariables.map(({ key, name, type, required, config, icon, icon_background }, index) => (
  287. <tr key={index} className="h-9 leading-9">
  288. <td className="w-[160px] border-b border-gray-100 pl-3">
  289. <div className='flex items-center space-x-1'>
  290. <IconTypeIcon type={type as IInputTypeIconProps['type']} className='text-gray-400' />
  291. {!readonly
  292. ? (
  293. <input
  294. type="text"
  295. placeholder="key"
  296. value={key}
  297. onChange={e => updatePromptKey(index, e.target.value)}
  298. onBlur={e => updatePromptNameIfNameEmpty(index, e.target.value)}
  299. maxLength={getMaxVarNameLength(name)}
  300. className="h-6 leading-6 block w-full rounded-md border-0 py-1.5 text-gray-900 placeholder:text-gray-400 focus:outline-none focus:ring-1 focus:ring-inset focus:ring-gray-200"
  301. />
  302. )
  303. : (
  304. <div className='h-6 leading-6 text-[13px] text-gray-700'>{key}</div>
  305. )}
  306. </div>
  307. </td>
  308. <td className="py-1 border-b border-gray-100">
  309. {!readonly
  310. ? (
  311. <input
  312. type="text"
  313. placeholder={key}
  314. value={name}
  315. onChange={e => updatePromptVariable(key, 'name', e.target.value)}
  316. maxLength={getMaxVarNameLength(name)}
  317. className="h-6 leading-6 block w-full rounded-md border-0 py-1.5 text-gray-900 placeholder:text-gray-400 focus:outline-none focus:ring-1 focus:ring-inset focus:ring-gray-200"
  318. />)
  319. : (
  320. <div className='h-6 leading-6 text-[13px] text-gray-700'>{name}</div>
  321. )}
  322. </td>
  323. {!readonly && (
  324. <>
  325. <td className='w-[84px] border-b border-gray-100'>
  326. <div className='flex items-center h-full'>
  327. <Switch defaultValue={!required} size='md' onChange={value => updatePromptVariable(key, 'required', !value)} />
  328. </div>
  329. </td>
  330. <td className='w-20 border-b border-gray-100'>
  331. <div className='flex h-full items-center space-x-1'>
  332. <div className=' p-1 rounded-md hover:bg-black/5 w-6 h-6 cursor-pointer' onClick={() => handleConfig({ type, key, index, name, config, icon, icon_background })}>
  333. <Settings01 className='w-4 h-4 text-gray-500' />
  334. </div>
  335. <div className=' p-1 rounded-md hover:bg-black/5 w-6 h-6 cursor-pointer' onClick={() => handleRemoveVar(index)} >
  336. <RiDeleteBinLine className='w-4 h-4 text-gray-500' />
  337. </div>
  338. </div>
  339. </td>
  340. </>
  341. )}
  342. </tr>
  343. ))}
  344. </tbody>
  345. </table>
  346. </div>
  347. )}
  348. {isShowEditModal && (
  349. <EditModal
  350. payload={currItemToEdit!}
  351. isShow={isShowEditModal}
  352. onClose={hideEditModal}
  353. onConfirm={(item) => {
  354. updatePromptVariableItem(item)
  355. hideEditModal()
  356. }}
  357. varKeys={promptVariables.map(v => v.key)}
  358. />
  359. )}
  360. {isShowDeleteContextVarModal && (
  361. <Confirm
  362. isShow={isShowDeleteContextVarModal}
  363. title={t('appDebug.feature.dataSet.queryVariable.deleteContextVarTitle', { varName: promptVariables[removeIndex as number]?.name })}
  364. content={t('appDebug.feature.dataSet.queryVariable.deleteContextVarTip')}
  365. onConfirm={() => {
  366. didRemoveVar(removeIndex as number)
  367. hideDeleteContextVarModal()
  368. }}
  369. onCancel={hideDeleteContextVarModal}
  370. />
  371. )}
  372. </Panel>
  373. )
  374. }
  375. export default React.memo(ConfigVar)