advanced-prompt-input.tsx 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  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 Button from '@/app/components/base/button'
  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. <Button
  149. size='small'
  150. variant='secondary-accent'
  151. onClick={onHideContextMissingTip}
  152. >{t('common.operation.ok')}</Button>
  153. </div>
  154. )
  155. return (
  156. <div className={`bg-gradient-to-r from-components-input-border-active-prompt-1 to-components-input-border-active-prompt-2 rounded-xl p-0.5 shadow-xs ${!isContextMissing ? '' : s.warningBorder}`}>
  157. <div className='rounded-xl bg-background-default'>
  158. {isContextMissing
  159. ? contextMissing
  160. : (
  161. <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-background-default hover:shadow-xs')}>
  162. {isChatMode
  163. ? (
  164. <MessageTypeSelector value={type} onChange={onTypeChange} />
  165. )
  166. : (
  167. <div className='flex items-center space-x-1'>
  168. <div className='text-sm font-semibold uppercase text-indigo-800'>{t('appDebug.pageTitle.line1')}
  169. </div>
  170. <Tooltip
  171. popupContent={
  172. <div className='w-[180px]'>
  173. {t('appDebug.promptTip')}
  174. </div>
  175. }
  176. />
  177. </div>)}
  178. <div className={cn(s.optionWrap, 'items-center space-x-1')}>
  179. {canDelete && (
  180. <RiDeleteBinLine onClick={onDelete} className='h-6 w-6 p-1 text-text-tertiary cursor-pointer' />
  181. )}
  182. {!isCopied
  183. ? (
  184. <Clipboard className='h-6 w-6 p-1 text-text-tertiary cursor-pointer' onClick={() => {
  185. copy(value)
  186. setIsCopied(true)
  187. }} />
  188. )
  189. : (
  190. <ClipboardCheck className='h-6 w-6 p-1 text-text-tertiary' />
  191. )}
  192. </div>
  193. </div>
  194. )}
  195. <PromptEditorHeightResizeWrap
  196. className='px-4 min-h-[102px] overflow-y-auto text-sm text-text-secondary'
  197. height={editorHeight}
  198. minHeight={minHeight}
  199. onHeightChange={setEditorHeight}
  200. footer={(
  201. <div className='pl-4 pb-2 flex'>
  202. <div className="h-[18px] leading-[18px] px-1 rounded-md bg-divider-regular text-xs text-text-tertiary">{value.length}</div>
  203. </div>
  204. )}
  205. hideResize={noResize}
  206. >
  207. <PromptEditor
  208. className='min-h-[84px]'
  209. value={value}
  210. contextBlock={{
  211. show: true,
  212. selectable: !hasSetBlockStatus.context,
  213. datasets: dataSets.map(item => ({
  214. id: item.id,
  215. name: item.name,
  216. type: item.data_source_type,
  217. })),
  218. onAddContext: showSelectDataSet,
  219. }}
  220. variableBlock={{
  221. show: true,
  222. variables: modelConfig.configs.prompt_variables.filter(item => item.type !== 'api').map(item => ({
  223. name: item.name,
  224. value: item.key,
  225. })),
  226. }}
  227. externalToolBlock={{
  228. externalTools: modelConfig.configs.prompt_variables.filter(item => item.type === 'api').map(item => ({
  229. name: item.name,
  230. variableName: item.key,
  231. icon: item.icon,
  232. icon_background: item.icon_background,
  233. })),
  234. onAddExternalTool: handleOpenExternalDataToolModal,
  235. }}
  236. historyBlock={{
  237. show: !isChatMode && isChatApp,
  238. selectable: !hasSetBlockStatus.history,
  239. history: {
  240. user: conversationHistoriesRole?.user_prefix,
  241. assistant: conversationHistoriesRole?.assistant_prefix,
  242. },
  243. onEditRole: showHistoryModal,
  244. }}
  245. queryBlock={{
  246. show: !isChatMode && isChatApp,
  247. selectable: !hasSetBlockStatus.query,
  248. }}
  249. onChange={handlePromptChange}
  250. onBlur={handleBlur}
  251. />
  252. </PromptEditorHeightResizeWrap>
  253. </div>
  254. {isShowConfirmAddVar && (
  255. <ConfirmAddVar
  256. varNameArr={newPromptVariables.map(v => v.name)}
  257. onConfirm={handleAutoAdd(true)}
  258. onCancel={handleAutoAdd(false)}
  259. onHide={hideConfirmAddVar}
  260. />
  261. )}
  262. </div>
  263. )
  264. }
  265. export default React.memo(AdvancedPromptInput)