advanced-prompt-input.tsx 9.7 KB

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