Commit 9a31407a by archer

feat: chat status

parent c7bfd773
...@@ -3,6 +3,7 @@ ...@@ -3,6 +3,7 @@
"Cancel": "No", "Cancel": "No",
"Confirm": "Yes", "Confirm": "Yes",
"Warning": "Warning", "Warning": "Warning",
"Running": "Running",
"app": { "app": {
"App Detail": "App Detail", "App Detail": "App Detail",
"Confirm Del App Tip": "Confirm to delete the app and all its chats", "Confirm Del App Tip": "Confirm to delete the app and all its chats",
......
...@@ -3,6 +3,7 @@ ...@@ -3,6 +3,7 @@
"Cancel": "取消", "Cancel": "取消",
"Confirm": "确认", "Confirm": "确认",
"Warning": "提示", "Warning": "提示",
"Running": "运行中",
"app": { "app": {
"App Detail": "应用详情", "App Detail": "应用详情",
"Confirm Del App Tip": "确认删除该应用及其所有聊天记录?", "Confirm Del App Tip": "确认删除该应用及其所有聊天记录?",
......
...@@ -2,11 +2,12 @@ import { sseResponseEventEnum, TaskResponseKeyEnum } from '@/constants/chat'; ...@@ -2,11 +2,12 @@ import { sseResponseEventEnum, TaskResponseKeyEnum } from '@/constants/chat';
import { getErrText } from '@/utils/tools'; import { getErrText } from '@/utils/tools';
import { parseStreamChunk, SSEParseData } from '@/utils/sse'; import { parseStreamChunk, SSEParseData } from '@/utils/sse';
import type { ChatHistoryItemResType } from '@/types/chat'; import type { ChatHistoryItemResType } from '@/types/chat';
import { StartChatFnProps } from '@/components/ChatBox';
interface StreamFetchProps { interface StreamFetchProps {
url?: string; url?: string;
data: Record<string, any>; data: Record<string, any>;
onMessage: (text: string) => void; onMessage: StartChatFnProps['generatingMessage'];
abortSignal: AbortController; abortSignal: AbortController;
} }
export const streamFetch = ({ export const streamFetch = ({
...@@ -71,9 +72,15 @@ export const streamFetch = ({ ...@@ -71,9 +72,15 @@ export const streamFetch = ({
if (eventName === sseResponseEventEnum.answer && data !== '[DONE]') { if (eventName === sseResponseEventEnum.answer && data !== '[DONE]') {
const answer: string = data?.choices?.[0].delta.content || ''; const answer: string = data?.choices?.[0].delta.content || '';
onMessage(answer); onMessage({ text: answer });
responseText += answer; responseText += answer;
} else if ( } else if (
eventName === sseResponseEventEnum.moduleStatus &&
data?.name &&
data?.status
) {
onMessage(data);
} else if (
eventName === sseResponseEventEnum.appStreamResponse && eventName === sseResponseEventEnum.appStreamResponse &&
Array.isArray(data) Array.isArray(data)
) { ) {
......
...@@ -28,3 +28,16 @@ ...@@ -28,3 +28,16 @@
} }
} }
} }
.statusAnimation {
animation: statusBox 0.8s linear infinite alternate;
}
@keyframes statusBox {
0% {
opacity: 1;
}
100% {
opacity: 0.11;
}
}
...@@ -39,6 +39,7 @@ import { htmlTemplate } from '@/constants/common'; ...@@ -39,6 +39,7 @@ import { htmlTemplate } from '@/constants/common';
import { useRouter } from 'next/router'; import { useRouter } from 'next/router';
import { useGlobalStore } from '@/store/global'; import { useGlobalStore } from '@/store/global';
import { TaskResponseKeyEnum, getDefaultChatVariables } from '@/constants/chat'; import { TaskResponseKeyEnum, getDefaultChatVariables } from '@/constants/chat';
import { useTranslation } from 'react-i18next';
import MyIcon from '@/components/Icon'; import MyIcon from '@/components/Icon';
import Avatar from '@/components/Avatar'; import Avatar from '@/components/Avatar';
...@@ -51,11 +52,12 @@ const ResponseDetailModal = dynamic(() => import('./ResponseDetailModal')); ...@@ -51,11 +52,12 @@ const ResponseDetailModal = dynamic(() => import('./ResponseDetailModal'));
import styles from './index.module.scss'; import styles from './index.module.scss';
const textareaMinH = '22px'; const textareaMinH = '22px';
type generatingMessageProps = { text?: string; name?: string; status?: 'running' | 'finish' };
export type StartChatFnProps = { export type StartChatFnProps = {
messages: MessageItemType[]; messages: MessageItemType[];
controller: AbortController; controller: AbortController;
variables: Record<string, any>; variables: Record<string, any>;
generatingMessage: (text: string) => void; generatingMessage: (e: generatingMessageProps) => void;
}; };
export type ComponentRef = { export type ComponentRef = {
...@@ -153,6 +155,7 @@ const ChatBox = ( ...@@ -153,6 +155,7 @@ const ChatBox = (
const ChatBoxRef = useRef<HTMLDivElement>(null); const ChatBoxRef = useRef<HTMLDivElement>(null);
const theme = useTheme(); const theme = useTheme();
const router = useRouter(); const router = useRouter();
const { t } = useTranslation();
const { copyData } = useCopyData(); const { copyData } = useCopyData();
const { toast } = useToast(); const { toast } = useToast();
const { isPc } = useGlobalStore(); const { isPc } = useGlobalStore();
...@@ -164,7 +167,9 @@ const ChatBox = ( ...@@ -164,7 +167,9 @@ const ChatBox = (
const [chatHistory, setChatHistory] = useState<ChatSiteItemType[]>([]); const [chatHistory, setChatHistory] = useState<ChatSiteItemType[]>([]);
const isChatting = useMemo( const isChatting = useMemo(
() => chatHistory[chatHistory.length - 1]?.status === 'loading', () =>
chatHistory[chatHistory.length - 1] &&
chatHistory[chatHistory.length - 1]?.status !== 'finish',
[chatHistory] [chatHistory]
); );
const variableIsFinish = useMemo(() => { const variableIsFinish = useMemo(() => {
...@@ -209,13 +214,23 @@ const ChatBox = ( ...@@ -209,13 +214,23 @@ const ChatBox = (
); );
// eslint-disable-next-line react-hooks/exhaustive-deps // eslint-disable-next-line react-hooks/exhaustive-deps
const generatingMessage = useCallback( const generatingMessage = useCallback(
(text: string) => { ({ text = '', status, name }: generatingMessageProps) => {
setChatHistory((state) => setChatHistory((state) =>
state.map((item, index) => { state.map((item, index) => {
if (index !== state.length - 1) return item; if (index !== state.length - 1) return item;
return { return {
...item, ...item,
...(text
? {
value: item.value + text value: item.value + text
}
: {}),
...(status && name
? {
status,
moduleName: name
}
: {})
}; };
}) })
); );
...@@ -418,6 +433,21 @@ const ChatBox = ( ...@@ -418,6 +433,21 @@ const ChatBox = (
!welcomeText, !welcomeText,
[chatHistory.length, showEmptyIntro, variableModules, welcomeText] [chatHistory.length, showEmptyIntro, variableModules, welcomeText]
); );
const statusBoxData = useMemo(() => {
const colorMap = {
loading: '#67c13b',
running: '#67c13b',
finish: 'myBlue.600'
};
if (!isChatting) return;
const chatContent = chatHistory[chatHistory.length - 1];
if (!chatContent) return;
return {
bg: colorMap[chatContent.status] || colorMap.loading,
name: t(chatContent.moduleName || 'Running')
};
}, [chatHistory, isChatting, t]);
useEffect(() => { useEffect(() => {
return () => { return () => {
...@@ -595,7 +625,7 @@ const ChatBox = ( ...@@ -595,7 +625,7 @@ const ChatBox = (
)} )}
{item.obj === 'AI' && ( {item.obj === 'AI' && (
<> <>
<Flex w={'100%'} alignItems={'center'}> <Flex w={'100%'} alignItems={'flex-end'}>
<ChatAvatar src={appAvatar} type={'AI'} /> <ChatAvatar src={appAvatar} type={'AI'} />
<Flex {...controlContainerStyle} ml={3}> <Flex {...controlContainerStyle} ml={3}>
<MyTooltip label={'复制'}> <MyTooltip label={'复制'}>
...@@ -635,6 +665,28 @@ const ChatBox = ( ...@@ -635,6 +665,28 @@ const ChatBox = (
</MyTooltip> </MyTooltip>
)} )}
</Flex> </Flex>
{statusBoxData && index === chatHistory.length - 1 && (
<Flex
ml={3}
alignItems={'center'}
px={3}
py={'1px'}
borderRadius="md"
border={theme.borders.base}
>
<Box
className={styles.statusAnimation}
bg={statusBoxData.bg}
w="8px"
h="8px"
borderRadius={'50%'}
mt={'1px'}
></Box>
<Box ml={2} color={'myGray.600'}>
{statusBoxData.name}
</Box>
</Flex>
)}
</Flex> </Flex>
<Box position={'relative'} maxW={messageCardMaxW} mt={['6px', 2]}> <Box position={'relative'} maxW={messageCardMaxW} mt={['6px', 2]}>
<Card bg={'white'} {...MessageCardStyle}> <Card bg={'white'} {...MessageCardStyle}>
......
import React, { useMemo, useRef } from 'react'; import React, { useMemo } from 'react';
import ReactMarkdown from 'react-markdown'; import ReactMarkdown from 'react-markdown';
import RemarkGfm from 'remark-gfm'; import RemarkGfm from 'remark-gfm';
import RemarkMath from 'remark-math'; import RemarkMath from 'remark-math';
......
...@@ -3,9 +3,8 @@ import dayjs from 'dayjs'; ...@@ -3,9 +3,8 @@ import dayjs from 'dayjs';
export enum sseResponseEventEnum { export enum sseResponseEventEnum {
error = 'error', error = 'error',
answer = 'answer', answer = 'answer',
chatResponse = 'chatResponse', // moduleStatus = 'moduleStatus',
appStreamResponse = 'appStreamResponse', // sse response request appStreamResponse = 'appStreamResponse' // sse response request
moduleFetchResponse = 'moduleFetchResponse' // http module sse response
} }
export enum ChatRoleEnum { export enum ChatRoleEnum {
......
...@@ -116,10 +116,12 @@ export default withNextCors(async function handler(req: NextApiRequest, res: Nex ...@@ -116,10 +116,12 @@ export default withNextCors(async function handler(req: NextApiRequest, res: Nex
} }
// 创建响应流 // 创建响应流
if (stream) {
res.setHeader('Content-Type', 'text/event-stream;charset=utf-8'); res.setHeader('Content-Type', 'text/event-stream;charset=utf-8');
res.setHeader('Access-Control-Allow-Origin', '*'); res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('X-Accel-Buffering', 'no'); res.setHeader('X-Accel-Buffering', 'no');
res.setHeader('Cache-Control', 'no-cache, no-transform'); res.setHeader('Cache-Control', 'no-cache, no-transform');
}
/* start process */ /* start process */
const { responseData, answerText } = await dispatchModules({ const { responseData, answerText } = await dispatchModules({
...@@ -320,6 +322,14 @@ export async function dispatchModules({ ...@@ -320,6 +322,14 @@ export async function dispatchModules({
if (res.closed) return Promise.resolve(); if (res.closed) return Promise.resolve();
console.log('run=========', module.flowType); console.log('run=========', module.flowType);
if (stream && module.showStatus) {
responseStatus({
res,
name: module.name,
status: 'running'
});
}
// get fetch params // get fetch params
const params: Record<string, any> = {}; const params: Record<string, any> = {};
module.inputs.forEach((item: any) => { module.inputs.forEach((item: any) => {
...@@ -370,7 +380,9 @@ function loadModules( ...@@ -370,7 +380,9 @@ function loadModules(
return modules.map((module) => { return modules.map((module) => {
return { return {
moduleId: module.moduleId, moduleId: module.moduleId,
name: module.name,
flowType: module.flowType, flowType: module.flowType,
showStatus: module.showStatus,
inputs: module.inputs inputs: module.inputs
.filter((item) => item.connected) // filter unconnected target input .filter((item) => item.connected) // filter unconnected target input
.map((item) => { .map((item) => {
...@@ -401,3 +413,23 @@ function loadModules( ...@@ -401,3 +413,23 @@ function loadModules(
}; };
}); });
} }
function responseStatus({
res,
status,
name
}: {
res: NextApiResponse;
status: 'running' | 'finish';
name?: string;
}) {
if (!name) return;
sseResponse({
res,
event: sseResponseEventEnum.moduleStatus,
data: JSON.stringify({
status,
name
})
});
}
import React, { useMemo } from 'react'; import React, { useMemo } from 'react';
import { Box, Flex } from '@chakra-ui/react'; import { Box, Flex } from '@chakra-ui/react';
import { ModuleTemplates } from '@/constants/flow/ModuleTemplate'; import { ModuleTemplates } from '@/constants/flow/ModuleTemplate';
import { FlowModuleTemplateType } from '@/types/flow'; import { FlowModuleItemType, FlowModuleTemplateType } from '@/types/flow';
import type { Node, XYPosition } from 'reactflow'; import type { Node, XYPosition } from 'reactflow';
import { useGlobalStore } from '@/store/global'; import { useGlobalStore } from '@/store/global';
import type { AppModuleItemType } from '@/types/app';
import Avatar from '@/components/Avatar'; import Avatar from '@/components/Avatar';
import { FlowModuleTypeEnum } from '@/constants/flow'; import { FlowModuleTypeEnum } from '@/constants/flow';
...@@ -14,7 +13,7 @@ const ModuleTemplateList = ({ ...@@ -14,7 +13,7 @@ const ModuleTemplateList = ({
onAddNode, onAddNode,
onClose onClose
}: { }: {
nodes?: Node<AppModuleItemType>[]; nodes?: Node<FlowModuleItemType>[];
isOpen: boolean; isOpen: boolean;
onAddNode: (e: { template: FlowModuleTemplateType; position: XYPosition }) => void; onAddNode: (e: { template: FlowModuleTemplateType; position: XYPosition }) => void;
onClose: () => void; onClose: () => void;
......
...@@ -158,7 +158,9 @@ const AppEdit = ({ app, fullScreen, onFullScreen }: Props) => { ...@@ -158,7 +158,9 @@ const AppEdit = ({ app, fullScreen, onFullScreen }: Props) => {
const flow2AppModules = useCallback(() => { const flow2AppModules = useCallback(() => {
const modules: AppModuleItemType[] = nodes.map((item) => ({ const modules: AppModuleItemType[] = nodes.map((item) => ({
moduleId: item.data.moduleId, moduleId: item.data.moduleId,
name: item.data.name,
flowType: item.data.flowType, flowType: item.data.flowType,
showStatus: item.data.showStatus,
position: item.position, position: item.position,
inputs: item.data.inputs.map((item) => ({ inputs: item.data.inputs.map((item) => ({
...item, ...item,
......
...@@ -34,6 +34,9 @@ export async function dispatchContentExtract({ ...@@ -34,6 +34,9 @@ export async function dispatchContentExtract({
history = [], history = [],
description description
}: Props): Promise<Response> { }: Props): Promise<Response> {
if (!content) {
return Promise.reject('Input is empty');
}
const messages: ChatItemType[] = [ const messages: ChatItemType[] = [
...history, ...history,
{ {
......
...@@ -69,9 +69,11 @@ export type VariableItemType = { ...@@ -69,9 +69,11 @@ export type VariableItemType = {
/* app module */ /* app module */
export type AppModuleItemType = { export type AppModuleItemType = {
name: string;
moduleId: string; moduleId: string;
position?: XYPosition; position?: XYPosition;
flowType: `${FlowModuleTypeEnum}`; flowType: `${FlowModuleTypeEnum}`;
showStatus?: boolean;
inputs: FlowInputItemType[]; inputs: FlowInputItemType[];
outputs: FlowOutputItemType[]; outputs: FlowOutputItemType[];
}; };
...@@ -83,8 +85,11 @@ export type AppItemType = { ...@@ -83,8 +85,11 @@ export type AppItemType = {
}; };
export type RunningModuleItemType = { export type RunningModuleItemType = {
moduleId: string; name: AppModuleItemType['name'];
flowType: `${FlowModuleTypeEnum}`; moduleId: AppModuleItemType['moduleId'];
flowType: AppModuleItemType['flowType'];
showStatus?: AppModuleItemType['showStatus'];
} & {
inputs: { inputs: {
key: string; key: string;
value?: any; value?: any;
......
...@@ -13,7 +13,8 @@ export type ChatItemType = { ...@@ -13,7 +13,8 @@ export type ChatItemType = {
}; };
export type ChatSiteItemType = { export type ChatSiteItemType = {
status: 'loading' | 'finish'; status: 'loading' | 'running' | 'finish';
moduleName?: string;
} & ChatItemType; } & ChatItemType;
export type HistoryItemType = { export type HistoryItemType = {
......
...@@ -55,6 +55,7 @@ export type FlowModuleTemplateType = { ...@@ -55,6 +55,7 @@ export type FlowModuleTemplateType = {
flowType: `${FlowModuleTypeEnum}`; flowType: `${FlowModuleTypeEnum}`;
inputs: FlowInputItemType[]; inputs: FlowInputItemType[];
outputs: FlowOutputItemType[]; outputs: FlowOutputItemType[];
showStatus?: boolean;
}; };
export type FlowModuleItemType = FlowModuleTemplateType & { export type FlowModuleItemType = FlowModuleTemplateType & {
moduleId: string; moduleId: string;
......
...@@ -219,6 +219,7 @@ const welcomeTemplate = (formData: EditFormType): AppModuleItemType[] => ...@@ -219,6 +219,7 @@ const welcomeTemplate = (formData: EditFormType): AppModuleItemType[] =>
formData.guide?.welcome?.text formData.guide?.welcome?.text
? [ ? [
{ {
name: '用户引导',
flowType: FlowModuleTypeEnum.userGuide, flowType: FlowModuleTypeEnum.userGuide,
inputs: [ inputs: [
{ {
...@@ -242,6 +243,7 @@ const variableTemplate = (formData: EditFormType): AppModuleItemType[] => ...@@ -242,6 +243,7 @@ const variableTemplate = (formData: EditFormType): AppModuleItemType[] =>
formData.variables.length > 0 formData.variables.length > 0
? [ ? [
{ {
name: '全局变量',
flowType: FlowModuleTypeEnum.variable, flowType: FlowModuleTypeEnum.variable,
inputs: [ inputs: [
{ {
...@@ -263,6 +265,7 @@ const variableTemplate = (formData: EditFormType): AppModuleItemType[] => ...@@ -263,6 +265,7 @@ const variableTemplate = (formData: EditFormType): AppModuleItemType[] =>
: []; : [];
const simpleChatTemplate = (formData: EditFormType): AppModuleItemType[] => [ const simpleChatTemplate = (formData: EditFormType): AppModuleItemType[] => [
{ {
name: '用户问题(对话入口)',
flowType: FlowModuleTypeEnum.questionInput, flowType: FlowModuleTypeEnum.questionInput,
inputs: [ inputs: [
{ {
...@@ -290,6 +293,7 @@ const simpleChatTemplate = (formData: EditFormType): AppModuleItemType[] => [ ...@@ -290,6 +293,7 @@ const simpleChatTemplate = (formData: EditFormType): AppModuleItemType[] => [
moduleId: 'userChatInput' moduleId: 'userChatInput'
}, },
{ {
name: '聊天记录',
flowType: FlowModuleTypeEnum.historyNode, flowType: FlowModuleTypeEnum.historyNode,
inputs: [ inputs: [
{ {
...@@ -324,6 +328,7 @@ const simpleChatTemplate = (formData: EditFormType): AppModuleItemType[] => [ ...@@ -324,6 +328,7 @@ const simpleChatTemplate = (formData: EditFormType): AppModuleItemType[] => [
moduleId: 'history' moduleId: 'history'
}, },
{ {
name: 'AI 对话',
flowType: FlowModuleTypeEnum.chatNode, flowType: FlowModuleTypeEnum.chatNode,
inputs: chatModelInput(formData), inputs: chatModelInput(formData),
outputs: [ outputs: [
...@@ -352,6 +357,7 @@ const simpleChatTemplate = (formData: EditFormType): AppModuleItemType[] => [ ...@@ -352,6 +357,7 @@ const simpleChatTemplate = (formData: EditFormType): AppModuleItemType[] => [
]; ];
const kbTemplate = (formData: EditFormType): AppModuleItemType[] => [ const kbTemplate = (formData: EditFormType): AppModuleItemType[] => [
{ {
name: '用户问题(对话入口)',
flowType: FlowModuleTypeEnum.questionInput, flowType: FlowModuleTypeEnum.questionInput,
inputs: [ inputs: [
{ {
...@@ -383,6 +389,7 @@ const kbTemplate = (formData: EditFormType): AppModuleItemType[] => [ ...@@ -383,6 +389,7 @@ const kbTemplate = (formData: EditFormType): AppModuleItemType[] => [
moduleId: 'userChatInput' moduleId: 'userChatInput'
}, },
{ {
name: '聊天记录',
flowType: FlowModuleTypeEnum.historyNode, flowType: FlowModuleTypeEnum.historyNode,
inputs: [ inputs: [
{ {
...@@ -417,6 +424,7 @@ const kbTemplate = (formData: EditFormType): AppModuleItemType[] => [ ...@@ -417,6 +424,7 @@ const kbTemplate = (formData: EditFormType): AppModuleItemType[] => [
moduleId: 'history' moduleId: 'history'
}, },
{ {
name: '知识库搜索',
flowType: FlowModuleTypeEnum.kbSearchNode, flowType: FlowModuleTypeEnum.kbSearchNode,
inputs: [ inputs: [
{ {
...@@ -498,6 +506,7 @@ const kbTemplate = (formData: EditFormType): AppModuleItemType[] => [ ...@@ -498,6 +506,7 @@ const kbTemplate = (formData: EditFormType): AppModuleItemType[] => [
...(formData.kb.searchEmptyText ...(formData.kb.searchEmptyText
? [ ? [
{ {
name: '指定回复',
flowType: FlowModuleTypeEnum.answerNode, flowType: FlowModuleTypeEnum.answerNode,
inputs: [ inputs: [
{ {
...@@ -525,6 +534,7 @@ const kbTemplate = (formData: EditFormType): AppModuleItemType[] => [ ...@@ -525,6 +534,7 @@ const kbTemplate = (formData: EditFormType): AppModuleItemType[] => [
] ]
: []), : []),
{ {
name: 'AI 对话',
flowType: FlowModuleTypeEnum.chatNode, flowType: FlowModuleTypeEnum.chatNode,
inputs: chatModelInput(formData), inputs: chatModelInput(formData),
outputs: [ outputs: [
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment