advanced-prompt-input.tsx 9.6 KB

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