feat: Regenerate chat message #2088 (#2166)

### What problem does this PR solve?

feat: Regenerate chat message #2088
### Type of change

- [x] New Feature (non-breaking change which adds functionality)
This commit is contained in:
balibabu 2024-08-29 18:37:18 +08:00 committed by GitHub
parent 742d0f0ea9
commit a82f092dac
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
9 changed files with 157 additions and 28 deletions

View File

@ -8,8 +8,9 @@ import {
SoundOutlined, SoundOutlined,
SyncOutlined, SyncOutlined,
} from '@ant-design/icons'; } from '@ant-design/icons';
import { Radio } from 'antd'; import { Radio, Tooltip } from 'antd';
import { useCallback } from 'react'; import { useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import SvgIcon from '../svg-icon'; import SvgIcon from '../svg-icon';
import FeedbackModal from './feedback-modal'; import FeedbackModal from './feedback-modal';
import { useRemoveMessage, useSendFeedback } from './hooks'; import { useRemoveMessage, useSendFeedback } from './hooks';
@ -33,6 +34,7 @@ export const AssistantGroupButton = ({
hideModal: hidePromptModal, hideModal: hidePromptModal,
showModal: showPromptModal, showModal: showPromptModal,
} = useSetModalState(); } = useSetModalState();
const { t } = useTranslation();
const handleLike = useCallback(() => { const handleLike = useCallback(() => {
onFeedbackOk({ thumbup: true }); onFeedbackOk({ thumbup: true });
@ -45,7 +47,9 @@ export const AssistantGroupButton = ({
<CopyToClipboard text={content}></CopyToClipboard> <CopyToClipboard text={content}></CopyToClipboard>
</Radio.Button> </Radio.Button>
<Radio.Button value="b"> <Radio.Button value="b">
<SoundOutlined /> <Tooltip title={t('chat.read')}>
<SoundOutlined />
</Tooltip>
</Radio.Button> </Radio.Button>
<Radio.Button value="c" onClick={handleLike}> <Radio.Button value="c" onClick={handleLike}>
<LikeOutlined /> <LikeOutlined />
@ -81,27 +85,41 @@ export const AssistantGroupButton = ({
interface UserGroupButtonProps extends IRemoveMessageById { interface UserGroupButtonProps extends IRemoveMessageById {
messageId: string; messageId: string;
content: string; content: string;
regenerateMessage(): void;
sendLoading: boolean;
} }
export const UserGroupButton = ({ export const UserGroupButton = ({
content, content,
messageId, messageId,
sendLoading,
removeMessageById, removeMessageById,
regenerateMessage,
}: UserGroupButtonProps) => { }: UserGroupButtonProps) => {
const { onRemoveMessage, loading } = useRemoveMessage( const { onRemoveMessage, loading } = useRemoveMessage(
messageId, messageId,
removeMessageById, removeMessageById,
); );
const { t } = useTranslation();
return ( return (
<Radio.Group size="small"> <Radio.Group size="small">
<Radio.Button value="a"> <Radio.Button value="a">
<CopyToClipboard text={content}></CopyToClipboard> <CopyToClipboard text={content}></CopyToClipboard>
</Radio.Button> </Radio.Button>
<Radio.Button value="b"> <Radio.Button
<SyncOutlined /> value="b"
onClick={regenerateMessage}
disabled={sendLoading}
>
<Tooltip title={t('chat.regenerate')}>
<SyncOutlined spin={sendLoading} />
</Tooltip>
</Radio.Button> </Radio.Button>
<Radio.Button value="c" onClick={onRemoveMessage} disabled={loading}> <Radio.Button value="c" onClick={onRemoveMessage} disabled={loading}>
<DeleteOutlined spin={loading} /> <Tooltip title={t('common.delete')}>
<DeleteOutlined spin={loading} />
</Tooltip>
</Radio.Button> </Radio.Button>
</Radio.Group> </Radio.Group>
); );

View File

@ -11,7 +11,7 @@ import {
useFetchDocumentInfosByIds, useFetchDocumentInfosByIds,
useFetchDocumentThumbnailsByIds, useFetchDocumentThumbnailsByIds,
} from '@/hooks/document-hooks'; } from '@/hooks/document-hooks';
import { IRemoveMessageById } from '@/hooks/logic-hooks'; import { IRegenerateMessage, IRemoveMessageById } from '@/hooks/logic-hooks';
import { IMessage } from '@/pages/chat/interface'; import { IMessage } from '@/pages/chat/interface';
import MarkdownContent from '@/pages/chat/markdown-content'; import MarkdownContent from '@/pages/chat/markdown-content';
import { getExtension, isImage } from '@/utils/document-util'; import { getExtension, isImage } from '@/utils/document-util';
@ -24,10 +24,11 @@ import styles from './index.less';
const { Text } = Typography; const { Text } = Typography;
interface IProps extends IRemoveMessageById { interface IProps extends IRemoveMessageById, IRegenerateMessage {
item: IMessage; item: IMessage;
reference: IReference; reference: IReference;
loading?: boolean; loading?: boolean;
sendLoading?: boolean;
nickname?: string; nickname?: string;
avatar?: string; avatar?: string;
clickDocumentButton?: (documentId: string, chunk: IChunk) => void; clickDocumentButton?: (documentId: string, chunk: IChunk) => void;
@ -39,9 +40,11 @@ const MessageItem = ({
reference, reference,
loading = false, loading = false,
avatar = '', avatar = '',
sendLoading = false,
clickDocumentButton, clickDocumentButton,
index, index,
removeMessageById, removeMessageById,
regenerateMessage,
}: IProps) => { }: IProps) => {
const isAssistant = item.role === MessageType.Assistant; const isAssistant = item.role === MessageType.Assistant;
const isUser = item.role === MessageType.User; const isUser = item.role === MessageType.User;
@ -73,6 +76,10 @@ const MessageItem = ({
[showModal], [showModal],
); );
const handleRegenerateMessage = useCallback(() => {
regenerateMessage(item);
}, [regenerateMessage, item]);
useEffect(() => { useEffect(() => {
const ids = item?.doc_ids ?? []; const ids = item?.doc_ids ?? [];
if (ids.length) { if (ids.length) {
@ -128,6 +135,8 @@ const MessageItem = ({
content={item.content} content={item.content}
messageId={item.id} messageId={item.id}
removeMessageById={removeMessageById} removeMessageById={removeMessageById}
regenerateMessage={handleRegenerateMessage}
sendLoading={sendLoading}
></UserGroupButton> ></UserGroupButton>
)} )}

View File

@ -2,7 +2,7 @@ import { Authorization } from '@/constants/authorization';
import { LanguageTranslationMap } from '@/constants/common'; import { LanguageTranslationMap } from '@/constants/common';
import { Pagination } from '@/interfaces/common'; import { Pagination } from '@/interfaces/common';
import { ResponseType } from '@/interfaces/database/base'; import { ResponseType } from '@/interfaces/database/base';
import { IAnswer } from '@/interfaces/database/chat'; import { IAnswer, Message } from '@/interfaces/database/chat';
import { IKnowledgeFile } from '@/interfaces/database/knowledge'; import { IKnowledgeFile } from '@/interfaces/database/knowledge';
import { IChangeParserConfigRequestBody } from '@/interfaces/request/document'; import { IChangeParserConfigRequestBody } from '@/interfaces/request/document';
import { IClientConversation } from '@/pages/chat/interface'; import { IClientConversation } from '@/pages/chat/interface';
@ -23,6 +23,7 @@ import {
} from 'react'; } from 'react';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { useDispatch } from 'umi'; import { useDispatch } from 'umi';
import { v4 as uuid } from 'uuid';
import { useSetModalState, useTranslate } from './common-hooks'; import { useSetModalState, useTranslate } from './common-hooks';
import { useSetDocumentParser } from './document-hooks'; import { useSetDocumentParser } from './document-hooks';
import { useSetPaginationParams } from './route-hook'; import { useSetPaginationParams } from './route-hook';
@ -336,6 +337,77 @@ export const useRemoveMessageById = (
return { removeMessageById }; return { removeMessageById };
}; };
export const useRemoveMessagesAfterCurrentMessage = (
setCurrentConversation: (
callback: (state: IClientConversation) => IClientConversation,
) => void,
) => {
const removeMessagesAfterCurrentMessage = useCallback(
(messageId: string) => {
setCurrentConversation((pre) => {
const index = pre.message?.findIndex((x) => x.id === messageId);
if (index !== -1) {
let nextMessages = pre.message?.slice(0, index + 2) ?? [];
const latestMessage = nextMessages.at(-1);
nextMessages = latestMessage
? [
...nextMessages.slice(0, -1),
{
...latestMessage,
content: '',
reference: undefined,
prompt: undefined,
},
]
: nextMessages;
return {
...pre,
message: nextMessages,
};
}
return pre;
});
},
[setCurrentConversation],
);
return { removeMessagesAfterCurrentMessage };
};
export interface IRegenerateMessage {
regenerateMessage(message: Message): void;
}
export const useRegenerateMessage = ({
removeMessagesAfterCurrentMessage,
sendMessage,
messages,
}: {
removeMessagesAfterCurrentMessage(messageId: string): void;
sendMessage({ message }: { message: Message; messages?: Message[] }): void;
messages: Message[];
}) => {
const regenerateMessage = useCallback(
async (message: Message) => {
if (message.id) {
removeMessagesAfterCurrentMessage(message.id);
const index = messages.findIndex((x) => x.id === message.id);
let nextMessages;
if (index !== -1) {
nextMessages = messages.slice(0, index);
}
sendMessage({
message: { ...message, id: uuid() },
messages: nextMessages,
});
}
},
[removeMessagesAfterCurrentMessage, sendMessage, messages],
);
return { regenerateMessage };
};
// #endregion // #endregion
/** /**

View File

@ -425,6 +425,8 @@ The above is the content you need to summarize.`,
parsing: 'Parsing', parsing: 'Parsing',
uploading: 'Uploading', uploading: 'Uploading',
uploadFailed: 'Upload failed', uploadFailed: 'Upload failed',
regenerate: 'Regenerate',
read: 'Read content',
}, },
setting: { setting: {
profile: 'Profile', profile: 'Profile',

View File

@ -395,6 +395,8 @@ export default {
parsing: '解析中', parsing: '解析中',
uploading: '上傳中', uploading: '上傳中',
uploadFailed: '上傳失敗', uploadFailed: '上傳失敗',
regenerate: '重新生成',
read: '朗讀內容',
}, },
setting: { setting: {
profile: '概述', profile: '概述',

View File

@ -412,6 +412,8 @@ export default {
parsing: '解析中', parsing: '解析中',
uploading: '上传中', uploading: '上传中',
uploadFailed: '上传失败', uploadFailed: '上传失败',
regenerate: '重新生成',
read: '朗读内容',
}, },
setting: { setting: {
profile: '概要', profile: '概要',

View File

@ -28,17 +28,20 @@ const ChatContainer = () => {
conversationId, conversationId,
loading, loading,
removeMessageById, removeMessageById,
removeMessagesAfterCurrentMessage,
} = useFetchConversationOnMount(); } = useFetchConversationOnMount();
const { const {
handleInputChange, handleInputChange,
handlePressEnter, handlePressEnter,
value, value,
loading: sendLoading, loading: sendLoading,
regenerateMessage,
} = useSendMessage( } = useSendMessage(
conversation, conversation,
addNewestConversation, addNewestConversation,
removeLatestMessage, removeLatestMessage,
addNewestAnswer, addNewestAnswer,
removeMessagesAfterCurrentMessage,
); );
const { visible, hideModal, documentId, selectedChunk, clickDocumentButton } = const { visible, hideModal, documentId, selectedChunk, clickDocumentButton } =
useClickDrawer(); useClickDrawer();
@ -71,6 +74,8 @@ const ChatContainer = () => {
clickDocumentButton={clickDocumentButton} clickDocumentButton={clickDocumentButton}
index={i} index={i}
removeMessageById={removeMessageById} removeMessageById={removeMessageById}
regenerateMessage={regenerateMessage}
sendLoading={sendLoading}
></MessageItem> ></MessageItem>
); );
})} })}

View File

@ -18,7 +18,9 @@ import {
useTranslate, useTranslate,
} from '@/hooks/common-hooks'; } from '@/hooks/common-hooks';
import { import {
useRegenerateMessage,
useRemoveMessageById, useRemoveMessageById,
useRemoveMessagesAfterCurrentMessage,
useSendMessageWithSse, useSendMessageWithSse,
} from '@/hooks/logic-hooks'; } from '@/hooks/logic-hooks';
import { import {
@ -255,6 +257,8 @@ export const useSelectCurrentConversation = () => {
const { data: dialog } = useFetchNextDialog(); const { data: dialog } = useFetchNextDialog();
const { conversationId, dialogId } = useGetChatSearchParams(); const { conversationId, dialogId } = useGetChatSearchParams();
const { removeMessageById } = useRemoveMessageById(setCurrentConversation); const { removeMessageById } = useRemoveMessageById(setCurrentConversation);
const { removeMessagesAfterCurrentMessage } =
useRemoveMessagesAfterCurrentMessage(setCurrentConversation);
// Show the entered message in the conversation immediately after sending the message // Show the entered message in the conversation immediately after sending the message
const addNewestConversation = useCallback( const addNewestConversation = useCallback(
@ -353,6 +357,7 @@ export const useSelectCurrentConversation = () => {
removeLatestMessage, removeLatestMessage,
addNewestAnswer, addNewestAnswer,
removeMessageById, removeMessageById,
removeMessagesAfterCurrentMessage,
loading, loading,
}; };
}; };
@ -382,6 +387,7 @@ export const useFetchConversationOnMount = () => {
addNewestAnswer, addNewestAnswer,
loading, loading,
removeMessageById, removeMessageById,
removeMessagesAfterCurrentMessage,
} = useSelectCurrentConversation(); } = useSelectCurrentConversation();
const ref = useScrollToBottom(currentConversation); const ref = useScrollToBottom(currentConversation);
@ -394,6 +400,7 @@ export const useFetchConversationOnMount = () => {
conversationId, conversationId,
loading, loading,
removeMessageById, removeMessageById,
removeMessagesAfterCurrentMessage,
}; };
}; };
@ -418,6 +425,7 @@ export const useSendMessage = (
addNewestConversation: (message: Message, answer?: string) => void, addNewestConversation: (message: Message, answer?: string) => void,
removeLatestMessage: () => void, removeLatestMessage: () => void,
addNewestAnswer: (answer: IAnswer) => void, addNewestAnswer: (answer: IAnswer) => void,
removeMessagesAfterCurrentMessage: (messageId: string) => void,
) => { ) => {
const { setConversation } = useSetConversation(); const { setConversation } = useSetConversation();
const { conversationId } = useGetChatSearchParams(); const { conversationId } = useGetChatSearchParams();
@ -427,16 +435,18 @@ export const useSendMessage = (
const { send, answer, done, setDone } = useSendMessageWithSse(); const { send, answer, done, setDone } = useSendMessageWithSse();
const sendMessage = useCallback( const sendMessage = useCallback(
async (message: Message, documentIds: string[], id?: string) => { async ({
message,
currentConversationId,
messages,
}: {
message: Message;
currentConversationId?: string;
messages?: Message[];
}) => {
const res = await send({ const res = await send({
conversation_id: id ?? conversationId, conversation_id: currentConversationId ?? conversationId,
messages: [ messages: [...(messages ?? conversation?.message ?? []), message],
...(conversation?.message ?? []),
{
...message,
doc_ids: documentIds,
},
],
}); });
if (res && (res?.response.status !== 200 || res?.data?.retcode !== 0)) { if (res && (res?.response.status !== 200 || res?.data?.retcode !== 0)) {
@ -445,10 +455,10 @@ export const useSendMessage = (
console.info('removeLatestMessage111'); console.info('removeLatestMessage111');
removeLatestMessage(); removeLatestMessage();
} else { } else {
if (id) { if (currentConversationId) {
console.info('111'); console.info('111');
// new conversation // new conversation
handleClickConversation(id); handleClickConversation(currentConversationId);
} else { } else {
console.info('222'); console.info('222');
// fetchConversation(conversationId); // fetchConversation(conversationId);
@ -466,20 +476,26 @@ export const useSendMessage = (
); );
const handleSendMessage = useCallback( const handleSendMessage = useCallback(
async (message: Message, documentIds: string[]) => { async (message: Message) => {
if (conversationId !== '') { if (conversationId !== '') {
sendMessage(message, documentIds); sendMessage({ message });
} else { } else {
const data = await setConversation(message.content); const data = await setConversation(message.content);
if (data.retcode === 0) { if (data.retcode === 0) {
const id = data.data.id; const id = data.data.id;
sendMessage(message, documentIds, id); sendMessage({ message, currentConversationId: id });
} }
} }
}, },
[conversationId, setConversation, sendMessage], [conversationId, setConversation, sendMessage],
); );
const { regenerateMessage } = useRegenerateMessage({
removeMessagesAfterCurrentMessage,
sendMessage,
messages: conversation.message,
});
useEffect(() => { useEffect(() => {
// #1289 // #1289
if (answer.answer && answer?.conversationId === conversationId) { if (answer.answer && answer?.conversationId === conversationId) {
@ -507,10 +523,12 @@ export const useSendMessage = (
}); });
if (done) { if (done) {
setValue(''); setValue('');
handleSendMessage( handleSendMessage({
{ id, content: value.trim(), role: MessageType.User }, id,
documentIds, content: value.trim(),
); role: MessageType.User,
doc_ids: documentIds,
});
} }
}, },
[addNewestConversation, handleSendMessage, done, setValue, value], [addNewestConversation, handleSendMessage, done, setValue, value],
@ -521,6 +539,7 @@ export const useSendMessage = (
handleInputChange, handleInputChange,
value, value,
setValue, setValue,
regenerateMessage,
loading: !done, loading: !done,
}; };
}; };

View File

@ -16,8 +16,8 @@ export const buildMessageUuid = (message: Partial<Message | IMessage>) => {
return uuid(); return uuid();
}; };
export const getMessagePureId = (id: string) => { export const getMessagePureId = (id?: string) => {
const strings = id.split('_'); const strings = id?.split('_') ?? [];
if (strings.length > 0) { if (strings.length > 0) {
return strings.at(-1); return strings.at(-1);
} }