index.tsx 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409
  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. RiQuestionLine,
  12. } from '@remixicon/react'
  13. import Panel from '../base/feature-panel'
  14. import EditModal from './config-modal'
  15. import IconTypeIcon from './input-type-icon'
  16. import type { IInputTypeIconProps } from './input-type-icon'
  17. import s from './style.module.css'
  18. import SelectVarType from './select-var-type'
  19. import { BracketsX as VarIcon } from '@/app/components/base/icons/src/vender/line/development'
  20. import Tooltip from '@/app/components/base/tooltip'
  21. import type { PromptVariable } from '@/models/debug'
  22. import { DEFAULT_VALUE_MAX_LEN, getMaxVarNameLength } from '@/config'
  23. import { checkKeys, getNewVar } from '@/utils/var'
  24. import Switch from '@/app/components/base/switch'
  25. import Toast from '@/app/components/base/toast'
  26. import { Settings01 } from '@/app/components/base/icons/src/vender/line/general'
  27. import ConfirmModal from '@/app/components/base/confirm/common'
  28. import ConfigContext from '@/context/debug-configuration'
  29. import { AppType } from '@/types/app'
  30. import type { ExternalDataTool } from '@/models/common'
  31. import { useModalContext } from '@/context/modal-context'
  32. import { useEventEmitterContextContext } from '@/context/event-emitter'
  33. import type { InputVar } from '@/app/components/workflow/types'
  34. import { InputVarType } from '@/app/components/workflow/types'
  35. export const ADD_EXTERNAL_DATA_TOOL = 'ADD_EXTERNAL_DATA_TOOL'
  36. type ExternalDataToolParams = {
  37. key: string
  38. type: string
  39. index: number
  40. name: string
  41. config?: Record<string, any>
  42. icon?: string
  43. icon_background?: string
  44. }
  45. export type IConfigVarProps = {
  46. promptVariables: PromptVariable[]
  47. readonly?: boolean
  48. onPromptVariablesChange?: (promptVariables: PromptVariable[]) => void
  49. }
  50. let conflictTimer: Timeout
  51. const ConfigVar: FC<IConfigVarProps> = ({ promptVariables, readonly, onPromptVariablesChange }) => {
  52. const { t } = useTranslation()
  53. const {
  54. mode,
  55. dataSets,
  56. } = useContext(ConfigContext)
  57. const { eventEmitter } = useEventEmitterContextContext()
  58. const hasVar = promptVariables.length > 0
  59. const updatePromptVariable = (key: string, updateKey: string, newValue: string | boolean) => {
  60. const newPromptVariables = promptVariables.map((item) => {
  61. if (item.key === key) {
  62. return {
  63. ...item,
  64. [updateKey]: newValue,
  65. }
  66. }
  67. return item
  68. })
  69. onPromptVariablesChange?.(newPromptVariables)
  70. }
  71. const [currIndex, setCurrIndex] = useState<number>(-1)
  72. const currItem = currIndex !== -1 ? promptVariables[currIndex] : null
  73. const currItemToEdit: InputVar | null = (() => {
  74. if (!currItem)
  75. return null
  76. return {
  77. ...currItem,
  78. label: currItem.name,
  79. variable: currItem.key,
  80. type: currItem.type === 'string' ? InputVarType.textInput : currItem.type,
  81. } as InputVar
  82. })()
  83. const updatePromptVariableItem = (payload: InputVar) => {
  84. console.log(payload)
  85. const newPromptVariables = produce(promptVariables, (draft) => {
  86. const { variable, label, type, ...rest } = payload
  87. draft[currIndex] = {
  88. ...rest,
  89. type: type === InputVarType.textInput ? 'string' : type,
  90. key: variable,
  91. name: label as string,
  92. }
  93. if (payload.type === InputVarType.textInput)
  94. draft[currIndex].max_length = draft[currIndex].max_length || DEFAULT_VALUE_MAX_LEN
  95. if (payload.type !== InputVarType.select)
  96. delete draft[currIndex].options
  97. })
  98. onPromptVariablesChange?.(newPromptVariables)
  99. }
  100. const updatePromptKey = (index: number, newKey: string) => {
  101. clearTimeout(conflictTimer)
  102. const { isValid, errorKey, errorMessageKey } = checkKeys([newKey], true)
  103. if (!isValid) {
  104. Toast.notify({
  105. type: 'error',
  106. message: t(`appDebug.varKeyError.${errorMessageKey}`, { key: errorKey }),
  107. })
  108. return
  109. }
  110. const newPromptVariables = promptVariables.map((item, i) => {
  111. if (i === index) {
  112. return {
  113. ...item,
  114. key: newKey,
  115. }
  116. }
  117. return item
  118. })
  119. conflictTimer = setTimeout(() => {
  120. const isKeyExists = promptVariables.some(item => item.key?.trim() === newKey.trim())
  121. if (isKeyExists) {
  122. Toast.notify({
  123. type: 'error',
  124. message: t('appDebug.varKeyError.keyAlreadyExists', { key: newKey }),
  125. })
  126. }
  127. }, 1000)
  128. onPromptVariablesChange?.(newPromptVariables)
  129. }
  130. const updatePromptNameIfNameEmpty = (index: number, newKey: string) => {
  131. if (!newKey)
  132. return
  133. const newPromptVariables = promptVariables.map((item, i) => {
  134. if (i === index && !item.name) {
  135. return {
  136. ...item,
  137. name: newKey,
  138. }
  139. }
  140. return item
  141. })
  142. onPromptVariablesChange?.(newPromptVariables)
  143. }
  144. const { setShowExternalDataToolModal } = useModalContext()
  145. const handleOpenExternalDataToolModal = (
  146. { key, type, index, name, config, icon, icon_background }: ExternalDataToolParams,
  147. oldPromptVariables: PromptVariable[],
  148. ) => {
  149. setShowExternalDataToolModal({
  150. payload: {
  151. type,
  152. variable: key,
  153. label: name,
  154. config,
  155. icon,
  156. icon_background,
  157. },
  158. onSaveCallback: (newExternalDataTool: ExternalDataTool) => {
  159. const newPromptVariables = oldPromptVariables.map((item, i) => {
  160. if (i === index) {
  161. return {
  162. key: newExternalDataTool.variable as string,
  163. name: newExternalDataTool.label as string,
  164. enabled: newExternalDataTool.enabled,
  165. type: newExternalDataTool.type as string,
  166. config: newExternalDataTool.config,
  167. required: item.required,
  168. icon: newExternalDataTool.icon,
  169. icon_background: newExternalDataTool.icon_background,
  170. }
  171. }
  172. return item
  173. })
  174. onPromptVariablesChange?.(newPromptVariables)
  175. },
  176. onCancelCallback: () => {
  177. if (!key)
  178. onPromptVariablesChange?.(promptVariables.filter((_, i) => i !== index))
  179. },
  180. onValidateBeforeSaveCallback: (newExternalDataTool: ExternalDataTool) => {
  181. for (let i = 0; i < promptVariables.length; i++) {
  182. if (promptVariables[i].key === newExternalDataTool.variable && i !== index) {
  183. Toast.notify({ type: 'error', message: t('appDebug.varKeyError.keyAlreadyExists', { key: promptVariables[i].key }) })
  184. return false
  185. }
  186. }
  187. return true
  188. },
  189. })
  190. }
  191. const handleAddVar = (type: string) => {
  192. const newVar = getNewVar('', type)
  193. const newPromptVariables = [...promptVariables, newVar]
  194. onPromptVariablesChange?.(newPromptVariables)
  195. if (type === 'api') {
  196. handleOpenExternalDataToolModal({
  197. type,
  198. key: newVar.key,
  199. name: newVar.name,
  200. index: promptVariables.length,
  201. }, newPromptVariables)
  202. }
  203. }
  204. eventEmitter?.useSubscription((v: any) => {
  205. if (v.type === ADD_EXTERNAL_DATA_TOOL) {
  206. const payload = v.payload
  207. onPromptVariablesChange?.([
  208. ...promptVariables,
  209. {
  210. key: payload.variable as string,
  211. name: payload.label as string,
  212. enabled: payload.enabled,
  213. type: payload.type as string,
  214. config: payload.config,
  215. required: true,
  216. icon: payload.icon,
  217. icon_background: payload.icon_background,
  218. },
  219. ])
  220. }
  221. })
  222. const [isShowDeleteContextVarModal, { setTrue: showDeleteContextVarModal, setFalse: hideDeleteContextVarModal }] = useBoolean(false)
  223. const [removeIndex, setRemoveIndex] = useState<number | null>(null)
  224. const didRemoveVar = (index: number) => {
  225. onPromptVariablesChange?.(promptVariables.filter((_, i) => i !== index))
  226. }
  227. const handleRemoveVar = (index: number) => {
  228. const removeVar = promptVariables[index]
  229. if (mode === AppType.completion && dataSets.length > 0 && removeVar.is_context_var) {
  230. showDeleteContextVarModal()
  231. setRemoveIndex(index)
  232. return
  233. }
  234. didRemoveVar(index)
  235. }
  236. // const [currKey, setCurrKey] = useState<string | null>(null)
  237. const [isShowEditModal, { setTrue: showEditModal, setFalse: hideEditModal }] = useBoolean(false)
  238. const handleConfig = ({ key, type, index, name, config, icon, icon_background }: ExternalDataToolParams) => {
  239. // setCurrKey(key)
  240. setCurrIndex(index)
  241. if (type !== 'string' && type !== 'paragraph' && type !== 'select' && type !== 'number') {
  242. handleOpenExternalDataToolModal({ key, type, index, name, config, icon, icon_background }, promptVariables)
  243. return
  244. }
  245. showEditModal()
  246. }
  247. return (
  248. <Panel
  249. className="mt-4"
  250. headerIcon={
  251. <VarIcon className='w-4 h-4 text-primary-500' />
  252. }
  253. title={
  254. <div className='flex items-center'>
  255. <div className='mr-1'>{t('appDebug.variableTitle')}</div>
  256. {!readonly && (
  257. <Tooltip htmlContent={<div className='w-[180px]'>
  258. {t('appDebug.variableTip')}
  259. </div>} selector='config-var-tooltip'>
  260. <RiQuestionLine className='w-[14px] h-[14px] text-gray-400' />
  261. </Tooltip>
  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. <ConfirmModal
  362. isShow={isShowDeleteContextVarModal}
  363. title={t('appDebug.feature.dataSet.queryVariable.deleteContextVarTitle', { varName: promptVariables[removeIndex as number]?.name })}
  364. desc={t('appDebug.feature.dataSet.queryVariable.deleteContextVarTip') as string}
  365. confirmBtnClassName='bg-[#B42318] hover:bg-[#B42318]'
  366. onConfirm={() => {
  367. didRemoveVar(removeIndex as number)
  368. hideDeleteContextVarModal()
  369. }}
  370. onCancel={hideDeleteContextVarModal}
  371. />
  372. )}
  373. </Panel>
  374. )
  375. }
  376. export default React.memo(ConfigVar)