You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

advanced-prompt-input.tsx 9.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  1. 'use client'
  2. import type { FC } from 'react'
  3. import React from 'react'
  4. import copy from 'copy-to-clipboard'
  5. import cn from 'classnames'
  6. import { useTranslation } from 'react-i18next'
  7. import { useContext } from 'use-context-selector'
  8. import { useBoolean } from 'ahooks'
  9. import produce from 'immer'
  10. import s from './style.module.css'
  11. import MessageTypeSelector from './message-type-selector'
  12. import ConfirmAddVar from './confirm-add-var'
  13. import type { PromptRole, PromptVariable } from '@/models/debug'
  14. import { HelpCircle, Trash03 } from '@/app/components/base/icons/src/vender/line/general'
  15. import { Clipboard, ClipboardCheck } from '@/app/components/base/icons/src/vender/line/files'
  16. import Tooltip from '@/app/components/base/tooltip'
  17. import PromptEditor from '@/app/components/base/prompt-editor'
  18. import ConfigContext from '@/context/debug-configuration'
  19. import { getNewVar, getVars } from '@/utils/var'
  20. import { AppType } from '@/types/app'
  21. import { AlertCircle } from '@/app/components/base/icons/src/vender/solid/alertsAndFeedback'
  22. import { useModalContext } from '@/context/modal-context'
  23. import type { ExternalDataTool } from '@/models/common'
  24. import { useToastContext } from '@/app/components/base/toast'
  25. import { useEventEmitterContextContext } from '@/context/event-emitter'
  26. import { ADD_EXTERNAL_DATA_TOOL } from '@/app/components/app/configuration/config-var'
  27. import { INSERT_VARIABLE_VALUE_BLOCK_COMMAND } from '@/app/components/base/prompt-editor/plugins/variable-block'
  28. type Props = {
  29. type: PromptRole
  30. isChatMode: boolean
  31. value: string
  32. onTypeChange: (value: PromptRole) => void
  33. onChange: (value: string) => void
  34. canDelete: boolean
  35. onDelete: () => void
  36. promptVariables: PromptVariable[]
  37. isContextMissing: boolean
  38. onHideContextMissingTip: () => void
  39. }
  40. const AdvancedPromptInput: FC<Props> = ({
  41. type,
  42. isChatMode,
  43. value,
  44. onChange,
  45. onTypeChange,
  46. canDelete,
  47. onDelete,
  48. promptVariables,
  49. isContextMissing,
  50. onHideContextMissingTip,
  51. }) => {
  52. const { t } = useTranslation()
  53. const { eventEmitter } = useEventEmitterContextContext()
  54. const {
  55. mode,
  56. hasSetBlockStatus,
  57. modelConfig,
  58. setModelConfig,
  59. conversationHistoriesRole,
  60. showHistoryModal,
  61. dataSets,
  62. showSelectDataSet,
  63. externalDataToolsConfig,
  64. } = useContext(ConfigContext)
  65. const { notify } = useToastContext()
  66. const { setShowExternalDataToolModal } = useModalContext()
  67. const handleOpenExternalDataToolModal = () => {
  68. setShowExternalDataToolModal({
  69. payload: {},
  70. onSaveCallback: (newExternalDataTool: ExternalDataTool) => {
  71. eventEmitter?.emit({
  72. type: ADD_EXTERNAL_DATA_TOOL,
  73. payload: newExternalDataTool,
  74. } as any)
  75. eventEmitter?.emit({
  76. type: INSERT_VARIABLE_VALUE_BLOCK_COMMAND,
  77. payload: newExternalDataTool.variable,
  78. } as any)
  79. },
  80. onValidateBeforeSaveCallback: (newExternalDataTool: ExternalDataTool) => {
  81. for (let i = 0; i < promptVariables.length; i++) {
  82. if (promptVariables[i].key === newExternalDataTool.variable) {
  83. notify({ type: 'error', message: t('appDebug.varKeyError.keyAlreadyExists', { key: promptVariables[i].key }) })
  84. return false
  85. }
  86. }
  87. return true
  88. },
  89. })
  90. }
  91. const isChatApp = mode === AppType.chat
  92. const [isCopied, setIsCopied] = React.useState(false)
  93. const promptVariablesObj = (() => {
  94. const obj: Record<string, boolean> = {}
  95. promptVariables.forEach((item) => {
  96. obj[item.key] = true
  97. })
  98. return obj
  99. })()
  100. const [newPromptVariables, setNewPromptVariables] = React.useState<PromptVariable[]>(promptVariables)
  101. const [isShowConfirmAddVar, { setTrue: showConfirmAddVar, setFalse: hideConfirmAddVar }] = useBoolean(false)
  102. const handlePromptChange = (newValue: string) => {
  103. if (value === newValue)
  104. return
  105. onChange(newValue)
  106. }
  107. const handleBlur = () => {
  108. const keys = getVars(value)
  109. const newPromptVariables = keys.filter(key => !(key in promptVariablesObj) && !externalDataToolsConfig.find(item => item.variable === key)).map(key => getNewVar(key, ''))
  110. if (newPromptVariables.length > 0) {
  111. setNewPromptVariables(newPromptVariables)
  112. showConfirmAddVar()
  113. }
  114. }
  115. const handleAutoAdd = (isAdd: boolean) => {
  116. return () => {
  117. if (isAdd) {
  118. const newModelConfig = produce(modelConfig, (draft) => {
  119. draft.configs.prompt_variables = [...draft.configs.prompt_variables, ...newPromptVariables]
  120. })
  121. setModelConfig(newModelConfig)
  122. }
  123. hideConfirmAddVar()
  124. }
  125. }
  126. const editorHeight = isChatMode ? 'h-[200px]' : 'h-[508px]'
  127. const contextMissing = (
  128. <div
  129. className='flex justify-between items-center h-11 pt-2 pr-3 pb-1 pl-4 rounded-tl-xl rounded-tr-xl'
  130. style={{
  131. background: 'linear-gradient(180deg, #FEF0C7 0%, rgba(254, 240, 199, 0) 100%)',
  132. }}
  133. >
  134. <div className='flex items-center pr-2' >
  135. <AlertCircle className='mr-1 w-4 h-4 text-[#F79009]'/>
  136. <div className='leading-[18px] text-[13px] font-medium text-[#DC6803]'>{t('appDebug.promptMode.contextMissing')}</div>
  137. </div>
  138. <div
  139. className='flex items-center h-6 px-2 rounded-md bg-[#fff] border border-gray-200 shadow-xs text-xs font-medium text-primary-600 cursor-pointer'
  140. onClick={onHideContextMissingTip}
  141. >{t('common.operation.ok')}</div>
  142. </div>
  143. )
  144. return (
  145. <div className={`relative ${!isContextMissing ? s.gradientBorder : s.warningBorder}`}>
  146. <div className='rounded-xl bg-white'>
  147. {isContextMissing
  148. ? contextMissing
  149. : (
  150. <div className={cn(s.boxHeader, 'flex justify-between items-center h-11 pt-2 pr-3 pb-1 pl-4 rounded-tl-xl rounded-tr-xl bg-white hover:shadow-xs')}>
  151. {isChatMode
  152. ? (
  153. <MessageTypeSelector value={type} onChange={onTypeChange} />
  154. )
  155. : (
  156. <div className='flex items-center space-x-1'>
  157. <div className='text-sm font-semibold uppercase text-indigo-800'>{t('appDebug.pageTitle.line1')}
  158. </div>
  159. <Tooltip
  160. htmlContent={<div className='w-[180px]'>
  161. {t('appDebug.promptTip')}
  162. </div>}
  163. selector='config-prompt-tooltip'>
  164. <HelpCircle className='w-[14px] h-[14px] text-indigo-400' />
  165. </Tooltip>
  166. </div>)}
  167. <div className={cn(s.optionWrap, 'items-center space-x-1')}>
  168. {canDelete && (
  169. <Trash03 onClick={onDelete} className='h-6 w-6 p-1 text-gray-500 cursor-pointer' />
  170. )}
  171. {!isCopied
  172. ? (
  173. <Clipboard className='h-6 w-6 p-1 text-gray-500 cursor-pointer' onClick={() => {
  174. copy(value)
  175. setIsCopied(true)
  176. }} />
  177. )
  178. : (
  179. <ClipboardCheck className='h-6 w-6 p-1 text-gray-500' />
  180. )}
  181. </div>
  182. </div>
  183. )}
  184. <div className={cn(editorHeight, 'px-4 min-h-[102px] overflow-y-auto text-sm text-gray-700')}>
  185. <PromptEditor
  186. className={editorHeight}
  187. value={value}
  188. contextBlock={{
  189. show: true,
  190. selectable: !hasSetBlockStatus.context,
  191. datasets: dataSets.map(item => ({
  192. id: item.id,
  193. name: item.name,
  194. type: item.data_source_type,
  195. })),
  196. onAddContext: showSelectDataSet,
  197. }}
  198. variableBlock={{
  199. variables: modelConfig.configs.prompt_variables.filter(item => item.type !== 'api').map(item => ({
  200. name: item.name,
  201. value: item.key,
  202. })),
  203. externalTools: modelConfig.configs.prompt_variables.filter(item => item.type === 'api').map(item => ({
  204. name: item.name,
  205. variableName: item.key,
  206. icon: item.icon,
  207. icon_background: item.icon_background,
  208. })),
  209. onAddExternalTool: handleOpenExternalDataToolModal,
  210. }}
  211. historyBlock={{
  212. show: !isChatMode && isChatApp,
  213. selectable: !hasSetBlockStatus.history,
  214. history: {
  215. user: conversationHistoriesRole?.user_prefix,
  216. assistant: conversationHistoriesRole?.assistant_prefix,
  217. },
  218. onEditRole: showHistoryModal,
  219. }}
  220. queryBlock={{
  221. show: !isChatMode && isChatApp,
  222. selectable: !hasSetBlockStatus.query,
  223. }}
  224. onChange={handlePromptChange}
  225. onBlur={handleBlur}
  226. />
  227. </div>
  228. <div className='pl-4 pb-2 flex'>
  229. <div className="h-[18px] leading-[18px] px-1 rounded-md bg-gray-100 text-xs text-gray-500">{value.length}</div>
  230. </div>
  231. </div>
  232. {isShowConfirmAddVar && (
  233. <ConfirmAddVar
  234. varNameArr={newPromptVariables.map(v => v.name)}
  235. onConfrim={handleAutoAdd(true)}
  236. onCancel={handleAutoAdd(false)}
  237. onHide={hideConfirmAddVar}
  238. />
  239. )}
  240. </div>
  241. )
  242. }
  243. export default React.memo(AdvancedPromptInput)