completion.tsx 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  1. import { ChatContext } from '@/app/chat-context';
  2. import { apiInterceptors, getChatFeedBackSelect } from '@/client/api';
  3. import useSummary from '@/hooks/use-summary';
  4. import { FeedBack, IChatDialogueMessageSchema } from '@/types/chat';
  5. import { STORAGE_INIT_MESSAGE_KET, getInitMessage } from '@/utils';
  6. import { CopyOutlined, RedoOutlined } from '@ant-design/icons';
  7. import { Button, IconButton } from '@mui/joy';
  8. import { useAsyncEffect } from 'ahooks';
  9. import { Modal, Tooltip, message } from 'antd';
  10. import classNames from 'classnames';
  11. import copy from 'copy-to-clipboard';
  12. import { cloneDeep } from 'lodash';
  13. import { useSearchParams } from 'next/navigation';
  14. import { useContext, useEffect, useMemo, useRef, useState } from 'react';
  15. import { useTranslation } from 'react-i18next';
  16. import MyEmpty from '../common/MyEmpty';
  17. import CompletionInput from '../common/completion-input';
  18. import AgentContent from './agent-content';
  19. import ChatContent from './chat-content';
  20. import ChatFeedback from './chat-feedback';
  21. import { renderModelIcon } from './header/model-selector';
  22. import MonacoEditor from './monaco-editor';
  23. type Props = {
  24. messages: IChatDialogueMessageSchema[];
  25. onSubmit: (message: string, otherQueryBody?: Record<string, any>) => Promise<void>;
  26. };
  27. const Completion = ({ messages, onSubmit }: Props) => {
  28. const { dbParam, currentDialogue, scene, model, refreshDialogList, chatId, agent, docId } = useContext(ChatContext);
  29. const { t } = useTranslation();
  30. const searchParams = useSearchParams();
  31. const flowSelectParam = (searchParams && searchParams.get('select_param')) ?? '';
  32. const spaceNameOriginal = (searchParams && searchParams.get('spaceNameOriginal')) ?? '';
  33. const [isLoading, setIsLoading] = useState(false);
  34. const [jsonModalOpen, setJsonModalOpen] = useState(false);
  35. const [showMessages, setShowMessages] = useState(messages);
  36. const [jsonValue, setJsonValue] = useState<string>('');
  37. const [select_param, setSelectParam] = useState<FeedBack>();
  38. const scrollableRef = useRef<HTMLDivElement>(null);
  39. // const incremental = useMemo(() => scene === 'chat_flow', [scene]);
  40. const isChartChat = useMemo(() => scene === 'chat_dashboard', [scene]);
  41. const summary = useSummary();
  42. const selectParam = useMemo(() => {
  43. switch (scene) {
  44. case 'chat_agent':
  45. return agent;
  46. case 'chat_excel':
  47. return currentDialogue?.select_param;
  48. case 'chat_flow':
  49. return flowSelectParam;
  50. default:
  51. return spaceNameOriginal || dbParam;
  52. }
  53. }, [scene, agent, currentDialogue, dbParam, spaceNameOriginal, flowSelectParam]);
  54. const handleChat = async (content: string) => {
  55. if (isLoading || !content.trim()) return;
  56. if (scene === 'chat_agent' && !agent) {
  57. message.warning(t('choice_agent_tip'));
  58. return;
  59. }
  60. try {
  61. setIsLoading(true);
  62. await onSubmit(content, {
  63. select_param: selectParam ?? '',
  64. // incremental,
  65. });
  66. } finally {
  67. setIsLoading(false);
  68. }
  69. };
  70. const handleJson2Obj = (jsonStr: string) => {
  71. try {
  72. return JSON.parse(jsonStr);
  73. } catch {
  74. return jsonStr;
  75. }
  76. };
  77. const [messageApi, contextHolder] = message.useMessage();
  78. const onCopyContext = async (context: any) => {
  79. const pureStr = context?.replace(/\trelations:.*/g, '');
  80. const result = copy(pureStr);
  81. if (result) {
  82. if (pureStr) {
  83. messageApi.open({ type: 'success', content: t('copy_success') });
  84. } else {
  85. messageApi.open({ type: 'warning', content: t('copy_nothing') });
  86. }
  87. } else {
  88. messageApi.open({ type: 'error', content: t('copy_failed') });
  89. }
  90. };
  91. const handleRetry = async () => {
  92. if (isLoading || !docId) {
  93. return;
  94. }
  95. setIsLoading(true);
  96. await summary(docId);
  97. setIsLoading(false);
  98. };
  99. useAsyncEffect(async () => {
  100. const initMessage = getInitMessage();
  101. if (initMessage && initMessage.id === chatId) {
  102. await handleChat(initMessage.message);
  103. refreshDialogList();
  104. localStorage.removeItem(STORAGE_INIT_MESSAGE_KET);
  105. }
  106. }, [chatId]);
  107. useEffect(() => {
  108. let tempMessage: IChatDialogueMessageSchema[] = messages;
  109. if (isChartChat) {
  110. tempMessage = cloneDeep(messages).map(item => {
  111. if (item?.role === 'view' && typeof item?.context === 'string') {
  112. item.context = handleJson2Obj(item?.context);
  113. }
  114. return item;
  115. });
  116. }
  117. setShowMessages(tempMessage.filter(item => ['view', 'human'].includes(item.role)));
  118. }, [isChartChat, messages]);
  119. useEffect(() => {
  120. apiInterceptors(getChatFeedBackSelect())
  121. .then(res => {
  122. setSelectParam(res[1] ?? {});
  123. })
  124. .catch(err => {
  125. console.log(err);
  126. });
  127. }, []);
  128. useEffect(() => {
  129. setTimeout(() => {
  130. scrollableRef.current?.scrollTo(0, scrollableRef.current.scrollHeight);
  131. }, 50);
  132. }, [messages]);
  133. return (
  134. <>
  135. {contextHolder}
  136. <div ref={scrollableRef} className='flex flex-1 overflow-y-auto pb-8 w-full flex-col'>
  137. <div className='flex items-center flex-1 flex-col text-sm leading-6 text-slate-900 dark:text-slate-300 sm:text-base sm:leading-7'>
  138. {showMessages.length ? (
  139. showMessages.map((content, index) => {
  140. if (scene === 'chat_agent') {
  141. return <AgentContent key={index} content={content} />;
  142. }
  143. return (
  144. <ChatContent
  145. key={index}
  146. content={content}
  147. isChartChat={isChartChat}
  148. onLinkClick={() => {
  149. setJsonModalOpen(true);
  150. setJsonValue(JSON.stringify(content?.context, null, 2));
  151. }}
  152. >
  153. {content.role === 'view' && (
  154. <div className='flex w-full border-t border-gray-200 dark:border-theme-dark'>
  155. {scene === 'chat_knowledge' && content.retry ? (
  156. <Button
  157. onClick={handleRetry}
  158. slots={{ root: IconButton }}
  159. slotProps={{ root: { variant: 'plain', color: 'primary' } }}
  160. >
  161. <RedoOutlined />
  162. &nbsp;<span className='text-sm'>{t('Retry')}</span>
  163. </Button>
  164. ) : null}
  165. <div className='flex w-full flex-row-reverse'>
  166. <ChatFeedback
  167. select_param={select_param}
  168. conv_index={Math.ceil((index + 1) / 2)}
  169. question={
  170. showMessages?.filter(e => e?.role === 'human' && e?.order === content.order)[0]?.context
  171. }
  172. knowledge_space={spaceNameOriginal || dbParam || ''}
  173. />
  174. <Tooltip title={t('Copy_Btn')}>
  175. <Button
  176. onClick={() => onCopyContext(content?.context)}
  177. slots={{ root: IconButton }}
  178. slotProps={{ root: { variant: 'plain', color: 'primary' } }}
  179. sx={{ borderRadius: 40 }}
  180. >
  181. <CopyOutlined />
  182. </Button>
  183. </Tooltip>
  184. </div>
  185. </div>
  186. )}
  187. </ChatContent>
  188. );
  189. })
  190. ) : (
  191. <MyEmpty description='Start a conversation' />
  192. )}
  193. </div>
  194. </div>
  195. <div
  196. className={classNames(
  197. 'relative after:absolute after:-top-8 after:h-8 after:w-full after:bg-gradient-to-t after:from-theme-light after:to-transparent dark:after:from-theme-dark',
  198. {
  199. 'cursor-not-allowed': scene === 'chat_excel' && !currentDialogue?.select_param,
  200. },
  201. )}
  202. >
  203. <div className='flex flex-wrap w-full py-2 sm:pt-6 sm:pb-10 items-center'>
  204. {model && <div className='mr-2 flex'>{renderModelIcon(model)}</div>}
  205. <CompletionInput loading={isLoading} onSubmit={handleChat} handleFinish={setIsLoading} />
  206. </div>
  207. </div>
  208. <Modal
  209. title='JSON Editor'
  210. open={jsonModalOpen}
  211. width='60%'
  212. cancelButtonProps={{
  213. hidden: true,
  214. }}
  215. onOk={() => {
  216. setJsonModalOpen(false);
  217. }}
  218. onCancel={() => {
  219. setJsonModalOpen(false);
  220. }}
  221. >
  222. <MonacoEditor className='w-full h-[500px]' language='json' value={jsonValue} />
  223. </Modal>
  224. </>
  225. );
  226. };
  227. export default Completion;