* fix: chat variable sync

* feat: chat save variable config

* fix: target handle hidden

* adapt v1 chat init

* adapt v1 chat init

* adapt v1 chat init

* adapt v1 chat init
This commit is contained in:
Archer
2024-05-08 19:49:17 +08:00
committed by GitHub
parent 7b75a99ba2
commit 3c6e5a6e00
20 changed files with 332 additions and 259 deletions

View File

@@ -105,7 +105,7 @@ export const appWorkflow2Form = ({ nodes }: { nodes: StoreNodeItemType[] }) => {
} else if (node.flowNodeType === FlowNodeTypeEnum.systemConfig) { } else if (node.flowNodeType === FlowNodeTypeEnum.systemConfig) {
const { const {
welcomeText, welcomeText,
variableModules, variableNodes,
questionGuide, questionGuide,
ttsConfig, ttsConfig,
whisperConfig, whisperConfig,
@@ -114,7 +114,7 @@ export const appWorkflow2Form = ({ nodes }: { nodes: StoreNodeItemType[] }) => {
defaultAppForm.userGuide = { defaultAppForm.userGuide = {
welcomeText: welcomeText, welcomeText: welcomeText,
variables: variableModules, variables: variableNodes,
questionGuide: questionGuide, questionGuide: questionGuide,
tts: ttsConfig, tts: ttsConfig,
whisper: whisperConfig, whisper: whisperConfig,

View File

@@ -10,7 +10,7 @@ import {
import { FlowNodeTypeEnum } from '../workflow/node/constant'; import { FlowNodeTypeEnum } from '../workflow/node/constant';
import { NodeOutputKeyEnum } from '../workflow/constants'; import { NodeOutputKeyEnum } from '../workflow/constants';
import { DispatchNodeResponseKeyEnum } from '../workflow/runtime/constants'; import { DispatchNodeResponseKeyEnum } from '../workflow/runtime/constants';
import { AppSchema } from '../app/type'; import { AppSchema, VariableItemType } from '../app/type';
import type { AppSchema as AppType } from '@fastgpt/global/core/app/type.d'; import type { AppSchema as AppType } from '@fastgpt/global/core/app/type.d';
import { DatasetSearchModeEnum } from '../dataset/constants'; import { DatasetSearchModeEnum } from '../dataset/constants';
import { ChatBoxInputType } from '../../../../projects/app/src/components/ChatBox/type'; import { ChatBoxInputType } from '../../../../projects/app/src/components/ChatBox/type';
@@ -27,11 +27,13 @@ export type ChatSchema = {
title: string; title: string;
customTitle: string; customTitle: string;
top: boolean; top: boolean;
variables: Record<string, any>;
source: `${ChatSourceEnum}`; source: `${ChatSourceEnum}`;
shareId?: string; shareId?: string;
outLinkUid?: string; outLinkUid?: string;
content: ChatItemType[];
variableList?: VariableItemType[];
welcomeText?: string;
variables: Record<string, any>;
metadata?: Record<string, any>; metadata?: Record<string, any>;
}; };

View File

@@ -36,13 +36,17 @@ export const checkInputIsReference = (input: FlowNodeInputItemType) => {
/* node */ /* node */
export const getGuideModule = (modules: StoreNodeItemType[]) => export const getGuideModule = (modules: StoreNodeItemType[]) =>
modules.find((item) => item.flowNodeType === FlowNodeTypeEnum.systemConfig); modules.find(
(item) =>
item.flowNodeType === FlowNodeTypeEnum.systemConfig ||
// @ts-ignore (adapt v1)
item.flowType === FlowNodeTypeEnum.systemConfig
);
export const splitGuideModule = (guideModules?: StoreNodeItemType) => { export const splitGuideModule = (guideModules?: StoreNodeItemType) => {
const welcomeText: string = const welcomeText: string =
guideModules?.inputs?.find((item) => item.key === NodeInputKeyEnum.welcomeText)?.value || ''; guideModules?.inputs?.find((item) => item.key === NodeInputKeyEnum.welcomeText)?.value || '';
const variableModules: VariableItemType[] = const variableNodes: VariableItemType[] =
guideModules?.inputs.find((item) => item.key === NodeInputKeyEnum.variables)?.value || []; guideModules?.inputs.find((item) => item.key === NodeInputKeyEnum.variables)?.value || [];
const questionGuide: boolean = const questionGuide: boolean =
@@ -63,13 +67,43 @@ export const splitGuideModule = (guideModules?: StoreNodeItemType) => {
return { return {
welcomeText, welcomeText,
variableModules, variableNodes,
questionGuide, questionGuide,
ttsConfig, ttsConfig,
whisperConfig, whisperConfig,
scheduledTriggerConfig scheduledTriggerConfig
}; };
}; };
export const replaceAppChatConfig = ({
node,
variableList,
welcomeText
}: {
node?: StoreNodeItemType;
variableList?: VariableItemType[];
welcomeText?: string;
}): StoreNodeItemType | undefined => {
if (!node) return;
return {
...node,
inputs: node.inputs.map((input) => {
if (input.key === NodeInputKeyEnum.variables && variableList) {
return {
...input,
value: variableList
};
}
if (input.key === NodeInputKeyEnum.welcomeText && welcomeText) {
return {
...input,
value: welcomeText
};
}
return input;
})
};
};
export const getOrInitModuleInputValue = (input: FlowNodeInputItemType) => { export const getOrInitModuleInputValue = (input: FlowNodeInputItemType) => {
if (input.value !== undefined || !input.valueType) return input.value; if (input.value !== undefined || !input.valueType) return input.value;

View File

@@ -41,6 +41,10 @@ export function reRankRecall({
.then((data) => { .then((data) => {
addLog.info('ReRank finish:', { time: Date.now() - start }); addLog.info('ReRank finish:', { time: Date.now() - start });
if (!data?.results || data?.results?.length === 0) {
addLog.error('ReRank error, empty result', data);
}
return data?.results?.map((item) => ({ return data?.results?.map((item) => ({
id: documents[item.index].id, id: documents[item.index].id,
score: item.relevance_score score: item.relevance_score

View File

@@ -61,7 +61,15 @@ const ChatSchema = new Schema({
outLinkUid: { outLinkUid: {
type: String type: String
}, },
variableList: {
type: Array
},
welcomeText: {
type: String
},
variables: { variables: {
// variable value
type: Object, type: Object,
default: {} default: {}
}, },

View File

@@ -12,7 +12,7 @@ import { ChatSiteItemType } from '@fastgpt/global/core/chat/type';
type useChatStoreType = OutLinkChatAuthProps & { type useChatStoreType = OutLinkChatAuthProps & {
welcomeText: string; welcomeText: string;
variableModules: VariableItemType[]; variableNodes: VariableItemType[];
questionGuide: boolean; questionGuide: boolean;
ttsConfig: AppTTSConfigType; ttsConfig: AppTTSConfigType;
whisperConfig: AppWhisperConfigType; whisperConfig: AppWhisperConfigType;
@@ -41,7 +41,7 @@ type useChatStoreType = OutLinkChatAuthProps & {
}; };
const StateContext = createContext<useChatStoreType>({ const StateContext = createContext<useChatStoreType>({
welcomeText: '', welcomeText: '',
variableModules: [], variableNodes: [],
questionGuide: false, questionGuide: false,
ttsConfig: { ttsConfig: {
type: 'none', type: 'none',
@@ -110,7 +110,7 @@ const Provider = ({
}: ChatProviderProps) => { }: ChatProviderProps) => {
const [chatHistories, setChatHistories] = useState<ChatSiteItemType[]>([]); const [chatHistories, setChatHistories] = useState<ChatSiteItemType[]>([]);
const { welcomeText, variableModules, questionGuide, ttsConfig, whisperConfig } = useMemo( const { welcomeText, variableNodes, questionGuide, ttsConfig, whisperConfig } = useMemo(
() => splitGuideModule(userGuideModule), () => splitGuideModule(userGuideModule),
[userGuideModule] [userGuideModule]
); );
@@ -150,7 +150,7 @@ const Provider = ({
teamId, teamId,
teamToken, teamToken,
welcomeText, welcomeText,
variableModules, variableNodes,
questionGuide, questionGuide,
ttsConfig, ttsConfig,
whisperConfig, whisperConfig,

View File

@@ -1,5 +1,5 @@
import { VariableItemType } from '@fastgpt/global/core/app/type.d'; import { VariableItemType } from '@fastgpt/global/core/app/type.d';
import React, { useEffect, useState } from 'react'; import React from 'react';
import { UseFormReturn } from 'react-hook-form'; import { UseFormReturn } from 'react-hook-form';
import { useTranslation } from 'next-i18next'; import { useTranslation } from 'next-i18next';
import { Box, Button, Card, Input, Textarea } from '@chakra-ui/react'; import { Box, Button, Card, Input, Textarea } from '@chakra-ui/react';
@@ -12,34 +12,19 @@ import { ChatBoxInputFormType } from '../type.d';
const VariableInput = ({ const VariableInput = ({
appAvatar, appAvatar,
variableModules, variableNodes,
variableIsFinish,
chatForm, chatForm,
onSubmitVariables onSubmitVariables
}: { }: {
appAvatar?: string; appAvatar?: string;
variableModules: VariableItemType[]; variableNodes: VariableItemType[];
variableIsFinish: boolean;
onSubmitVariables: (e: Record<string, any>) => void; onSubmitVariables: (e: Record<string, any>) => void;
chatForm: UseFormReturn<ChatBoxInputFormType>; chatForm: UseFormReturn<ChatBoxInputFormType>;
}) => { }) => {
const { t } = useTranslation(); const { t } = useTranslation();
const { register, unregister, setValue, handleSubmit: handleSubmitChat, watch } = chatForm; const { register, setValue, handleSubmit: handleSubmitChat, watch } = chatForm;
const variables = watch('variables'); const variables = watch('variables');
const chatStarted = watch('chatStarted');
useEffect(() => {
// 重新注册所有字段
variableModules.forEach((item) => {
register(`variables.${item.key}`, { required: item.required });
});
return () => {
// 组件卸载时注销所有字段
variableModules.forEach((item) => {
unregister(`variables.${item.key}`);
});
};
}, [register, unregister, variableModules]);
return ( return (
<Box py={3}> <Box py={3}>
@@ -55,7 +40,7 @@ const VariableInput = ({
bg={'white'} bg={'white'}
boxShadow={'0 0 8px rgba(0,0,0,0.15)'} boxShadow={'0 0 8px rgba(0,0,0,0.15)'}
> >
{variableModules.map((item) => ( {variableNodes.map((item) => (
<Box key={item.id} mb={4}> <Box key={item.id} mb={4}>
<Box as={'label'} display={'inline-block'} position={'relative'} mb={1}> <Box as={'label'} display={'inline-block'} position={'relative'} mb={1}>
{item.label} {item.label}
@@ -73,7 +58,6 @@ const VariableInput = ({
</Box> </Box>
{item.type === VariableInputEnum.input && ( {item.type === VariableInputEnum.input && (
<Input <Input
isDisabled={variableIsFinish}
bg={'myWhite.400'} bg={'myWhite.400'}
{...register(`variables.${item.key}`, { {...register(`variables.${item.key}`, {
required: item.required required: item.required
@@ -82,7 +66,6 @@ const VariableInput = ({
)} )}
{item.type === VariableInputEnum.textarea && ( {item.type === VariableInputEnum.textarea && (
<Textarea <Textarea
isDisabled={variableIsFinish}
bg={'myWhite.400'} bg={'myWhite.400'}
{...register(`variables.${item.key}`, { {...register(`variables.${item.key}`, {
required: item.required required: item.required
@@ -94,7 +77,6 @@ const VariableInput = ({
{item.type === VariableInputEnum.select && ( {item.type === VariableInputEnum.select && (
<MySelect <MySelect
width={'100%'} width={'100%'}
isDisabled={variableIsFinish}
list={(item.enums || []).map((item) => ({ list={(item.enums || []).map((item) => ({
label: item.value, label: item.value,
value: item.value value: item.value
@@ -110,7 +92,7 @@ const VariableInput = ({
)} )}
</Box> </Box>
))} ))}
{!variableIsFinish && ( {!chatStarted && (
<Button <Button
leftIcon={<MyIcon name={'core/chat/chatFill'} w={'16px'} />} leftIcon={<MyIcon name={'core/chat/chatFill'} w={'16px'} />}
size={'sm'} size={'sm'}

View File

@@ -58,6 +58,8 @@ import ChatProvider, { useChatProviderStore } from './Provider';
import ChatItem from './components/ChatItem'; import ChatItem from './components/ChatItem';
import dynamic from 'next/dynamic'; import dynamic from 'next/dynamic';
import { useCreation, useUpdateEffect } from 'ahooks';
const ResponseTags = dynamic(() => import('./ResponseTags')); const ResponseTags = dynamic(() => import('./ResponseTags'));
const FeedbackModal = dynamic(() => import('./FeedbackModal')); const FeedbackModal = dynamic(() => import('./FeedbackModal'));
const ReadFeedbackModal = dynamic(() => import('./ReadFeedbackModal')); const ReadFeedbackModal = dynamic(() => import('./ReadFeedbackModal'));
@@ -147,7 +149,7 @@ const ChatBox = (
const { const {
welcomeText, welcomeText,
variableModules, variableNodes,
questionGuide, questionGuide,
startSegmentedAudio, startSegmentedAudio,
finishSegmentedAudio, finishSegmentedAudio,
@@ -171,24 +173,10 @@ const ChatBox = (
const chatStarted = watch('chatStarted'); const chatStarted = watch('chatStarted');
/* variable */ /* variable */
const variables = watch('variables'); const filterVariableNodes = useCreation(
const filterVariableModules = useMemo( () => variableNodes.filter((item) => item.type !== VariableInputEnum.custom),
() => variableModules.filter((item) => item.type !== VariableInputEnum.custom), [variableNodes]
[variableModules]
); );
const variableIsFinish = (() => {
if (!filterVariableModules || filterVariableModules.length === 0 || chatHistories.length > 0)
return true;
for (let i = 0; i < filterVariableModules.length; i++) {
const item = filterVariableModules[i];
if (item.required && !variables[item.key]) {
return false;
}
}
return chatStarted;
})();
// 滚动到底部 // 滚动到底部
const scrollToBottom = (behavior: 'smooth' | 'auto' = 'smooth') => { const scrollToBottom = (behavior: 'smooth' | 'auto' = 'smooth') => {
@@ -379,174 +367,185 @@ const ChatBox = (
autoTTSResponse?: boolean; autoTTSResponse?: boolean;
history?: ChatSiteItemType[]; history?: ChatSiteItemType[];
}) => { }) => {
handleSubmit(async ({ variables }) => { handleSubmit(
if (!onStartChat) return; async ({ variables }) => {
if (isChatting) { if (!onStartChat) return;
toast({ if (isChatting) {
title: '正在聊天中...请等待结束', toast({
status: 'warning' title: '正在聊天中...请等待结束',
}); status: 'warning'
return;
}
abortRequest();
text = text.trim();
if (!text && files.length === 0) {
toast({
title: '内容为空',
status: 'warning'
});
return;
}
const responseChatId = getNanoid(24);
questionGuideController.current?.abort('stop');
// set auto audio playing
if (autoTTSResponse) {
await startSegmentedAudio();
setAudioPlayingChatId(responseChatId);
}
const newChatList: ChatSiteItemType[] = [
...history,
{
dataId: getNanoid(24),
obj: ChatRoleEnum.Human,
value: [
...files.map((file) => ({
type: ChatItemValueTypeEnum.file,
file: {
type: file.type,
name: file.name,
url: file.url || ''
}
})),
...(text
? [
{
type: ChatItemValueTypeEnum.text,
text: {
content: text
}
}
]
: [])
] as UserChatItemValueItemType[],
status: 'finish'
},
{
dataId: responseChatId,
obj: ChatRoleEnum.AI,
value: [
{
type: ChatItemValueTypeEnum.text,
text: {
content: ''
}
}
],
status: 'loading'
}
];
// 插入内容
setChatHistories(newChatList);
// 清空输入内容
resetInputVal({});
setQuestionGuide([]);
setTimeout(() => {
scrollToBottom();
}, 100);
try {
// create abort obj
const abortSignal = new AbortController();
chatController.current = abortSignal;
const messages = chats2GPTMessages({ messages: newChatList, reserveId: true });
const {
responseData,
responseText,
newVariables,
isNewChat = false
} = await onStartChat({
chatList: newChatList,
messages,
controller: abortSignal,
generatingMessage: (e) => generatingMessage({ ...e, autoTTSResponse }),
variables
});
newVariables && setValue('variables', newVariables);
isNewChatReplace.current = isNewChat;
// set finish status
setChatHistories((state) =>
state.map((item, index) => {
if (index !== state.length - 1) return item;
return {
...item,
status: 'finish',
responseData
};
})
);
setTimeout(() => {
createQuestionGuide({
history: newChatList.map((item, i) =>
i === newChatList.length - 1
? {
...item,
value: [
{
type: ChatItemValueTypeEnum.text,
text: {
content: responseText
}
}
]
}
: item
)
}); });
generatingScroll(); return;
isPc && TextareaDom.current?.focus();
}, 100);
// tts audio
autoTTSResponse && splitText2Audio(responseText, true);
} catch (err: any) {
toast({
title: t(getErrText(err, 'core.chat.error.Chat error')),
status: 'error',
duration: 5000,
isClosable: true
});
if (!err?.responseText) {
resetInputVal({ text, files });
setChatHistories(newChatList.slice(0, newChatList.length - 2));
} }
// set finish status abortRequest();
setChatHistories((state) =>
state.map((item, index) => {
if (index !== state.length - 1) return item;
return {
...item,
status: 'finish'
};
})
);
}
autoTTSResponse && finishSegmentedAudio(); text = text.trim();
})();
if (!text && files.length === 0) {
toast({
title: '内容为空',
status: 'warning'
});
return;
}
// delete invalid variables 只保留在 variableNodes 中的变量
const requestVariables: Record<string, any> = {};
variableNodes?.forEach((item) => {
requestVariables[item.key] = variables[item.key] || '';
});
const responseChatId = getNanoid(24);
questionGuideController.current?.abort('stop');
// set auto audio playing
if (autoTTSResponse) {
await startSegmentedAudio();
setAudioPlayingChatId(responseChatId);
}
const newChatList: ChatSiteItemType[] = [
...history,
{
dataId: getNanoid(24),
obj: ChatRoleEnum.Human,
value: [
...files.map((file) => ({
type: ChatItemValueTypeEnum.file,
file: {
type: file.type,
name: file.name,
url: file.url || ''
}
})),
...(text
? [
{
type: ChatItemValueTypeEnum.text,
text: {
content: text
}
}
]
: [])
] as UserChatItemValueItemType[],
status: 'finish'
},
{
dataId: responseChatId,
obj: ChatRoleEnum.AI,
value: [
{
type: ChatItemValueTypeEnum.text,
text: {
content: ''
}
}
],
status: 'loading'
}
];
// 插入内容
setChatHistories(newChatList);
// 清空输入内容
resetInputVal({});
setQuestionGuide([]);
setTimeout(() => {
scrollToBottom();
}, 100);
try {
// create abort obj
const abortSignal = new AbortController();
chatController.current = abortSignal;
const messages = chats2GPTMessages({ messages: newChatList, reserveId: true });
const {
responseData,
responseText,
newVariables,
isNewChat = false
} = await onStartChat({
chatList: newChatList,
messages,
controller: abortSignal,
generatingMessage: (e) => generatingMessage({ ...e, autoTTSResponse }),
variables: requestVariables
});
newVariables && setValue('variables', newVariables);
isNewChatReplace.current = isNewChat;
// set finish status
setChatHistories((state) =>
state.map((item, index) => {
if (index !== state.length - 1) return item;
return {
...item,
status: 'finish',
responseData
};
})
);
setTimeout(() => {
createQuestionGuide({
history: newChatList.map((item, i) =>
i === newChatList.length - 1
? {
...item,
value: [
{
type: ChatItemValueTypeEnum.text,
text: {
content: responseText
}
}
]
}
: item
)
});
generatingScroll();
isPc && TextareaDom.current?.focus();
}, 100);
// tts audio
autoTTSResponse && splitText2Audio(responseText, true);
} catch (err: any) {
toast({
title: t(getErrText(err, 'core.chat.error.Chat error')),
status: 'error',
duration: 5000,
isClosable: true
});
if (!err?.responseText) {
resetInputVal({ text, files });
setChatHistories(newChatList.slice(0, newChatList.length - 2));
}
// set finish status
setChatHistories((state) =>
state.map((item, index) => {
if (index !== state.length - 1) return item;
return {
...item,
status: 'finish'
};
})
);
}
autoTTSResponse && finishSegmentedAudio();
},
(err) => {
console.log(err?.variables);
}
)();
}, },
[ [
abortRequest, abortRequest,
@@ -566,7 +565,8 @@ const ChatBox = (
splitText2Audio, splitText2Audio,
startSegmentedAudio, startSegmentedAudio,
t, t,
toast toast,
variableNodes
] ]
); );
@@ -630,7 +630,7 @@ const ChatBox = (
}); });
}; };
}, },
[onDelMessage] [onDelMessage, setChatHistories]
); );
// admin mark // admin mark
const onMark = useCallback( const onMark = useCallback(
@@ -796,7 +796,19 @@ const ChatBox = (
} }
}; };
}, },
[appId, chatId] [appId, chatId, setChatHistories]
);
const resetVariables = useCallback(
(e: Record<string, any> = {}) => {
const value: Record<string, any> = { ...e };
filterVariableNodes?.forEach((item) => {
value[item.key] = e[item.key] || '';
});
setValue('variables', value);
},
[filterVariableNodes, setValue]
); );
const showEmpty = useMemo( const showEmpty = useMemo(
@@ -804,13 +816,13 @@ const ChatBox = (
feConfigs?.show_emptyChat && feConfigs?.show_emptyChat &&
showEmptyIntro && showEmptyIntro &&
chatHistories.length === 0 && chatHistories.length === 0 &&
!filterVariableModules?.length && !filterVariableNodes?.length &&
!welcomeText, !welcomeText,
[ [
chatHistories.length, chatHistories.length,
feConfigs?.show_emptyChat, feConfigs?.show_emptyChat,
showEmptyIntro, showEmptyIntro,
filterVariableModules?.length, filterVariableNodes?.length,
welcomeText welcomeText
] ]
); );
@@ -869,14 +881,7 @@ const ChatBox = (
// output data // output data
useImperativeHandle(ref, () => ({ useImperativeHandle(ref, () => ({
getChatHistories: () => chatHistories, getChatHistories: () => chatHistories,
resetVariables(e) { resetVariables,
const defaultVal: Record<string, any> = {};
filterVariableModules?.forEach((item) => {
defaultVal[item.key] = '';
});
setValue('variables', e || defaultVal);
},
resetHistory(e) { resetHistory(e) {
abortRequest(); abortRequest();
setValue('chatStarted', e.length > 0); setValue('chatStarted', e.length > 0);
@@ -891,7 +896,7 @@ const ChatBox = (
})); }));
return ( return (
<Flex flexDirection={'column'} h={'100%'}> <Flex flexDirection={'column'} h={'100%'} position={'relative'}>
<Script src="/js/html2pdf.bundle.min.js" strategy="lazyOnload"></Script> <Script src="/js/html2pdf.bundle.min.js" strategy="lazyOnload"></Script>
{/* chat box container */} {/* chat box container */}
<Box ref={ChatBoxRef} flex={'1 0 0'} h={0} w={'100%'} overflow={'overlay'} px={[4, 0]} pb={3}> <Box ref={ChatBoxRef} flex={'1 0 0'} h={0} w={'100%'} overflow={'overlay'} px={[4, 0]} pb={3}>
@@ -899,11 +904,10 @@ const ChatBox = (
{showEmpty && <Empty />} {showEmpty && <Empty />}
{!!welcomeText && <WelcomeBox appAvatar={appAvatar} welcomeText={welcomeText} />} {!!welcomeText && <WelcomeBox appAvatar={appAvatar} welcomeText={welcomeText} />}
{/* variable input */} {/* variable input */}
{!!filterVariableModules?.length && ( {!!filterVariableNodes?.length && (
<VariableInput <VariableInput
appAvatar={appAvatar} appAvatar={appAvatar}
variableModules={filterVariableModules} variableNodes={filterVariableNodes}
variableIsFinish={variableIsFinish}
chatForm={chatForm} chatForm={chatForm}
onSubmitVariables={(data) => { onSubmitVariables={(data) => {
setValue('chatStarted', true); setValue('chatStarted', true);
@@ -995,7 +999,7 @@ const ChatBox = (
</Box> </Box>
</Box> </Box>
{/* message input */} {/* message input */}
{onStartChat && variableIsFinish && active && ( {onStartChat && (chatStarted || filterVariableNodes.length === 0) && active && (
<MessageInput <MessageInput
onSendMessage={sendPrompt} onSendMessage={sendPrompt}
onStop={() => chatController.current?.abort('stop')} onStop={() => chatController.current?.abort('stop')}

View File

@@ -34,11 +34,13 @@ export type ChatTestComponentRef = {
const ChatTest = ( const ChatTest = (
{ {
app, app,
isOpen,
nodes = [], nodes = [],
edges = [], edges = [],
onClose onClose
}: { }: {
app: AppSchema; app: AppSchema;
isOpen: boolean;
nodes?: StoreNodeItemType[]; nodes?: StoreNodeItemType[];
edges?: StoreEdgeItemType[]; edges?: StoreEdgeItemType[];
onClose: () => void; onClose: () => void;
@@ -48,7 +50,6 @@ const ChatTest = (
const { t } = useTranslation(); const { t } = useTranslation();
const ChatBoxRef = useRef<ComponentRef>(null); const ChatBoxRef = useRef<ComponentRef>(null);
const { userInfo } = useUserStore(); const { userInfo } = useUserStore();
const isOpen = useMemo(() => nodes && nodes.length > 0, [nodes]);
const startChat = useCallback( const startChat = useCallback(
async ({ chatList, controller, generatingMessage, variables }: StartChatFnProps) => { async ({ chatList, controller, generatingMessage, variables }: StartChatFnProps) => {

View File

@@ -28,7 +28,7 @@ export const ToolTargetHandle = ({ nodeId }: ToolHandleProps) => {
edges.some((edge) => edge.targetHandle === getHandleId(nodeId, 'target', 'top'))); edges.some((edge) => edge.targetHandle === getHandleId(nodeId, 'target', 'top')));
const Render = useMemo(() => { const Render = useMemo(() => {
return ( return hidden ? null : (
<MyTooltip label={t('core.workflow.tool.Handle')} shouldWrapChildren={false}> <MyTooltip label={t('core.workflow.tool.Handle')} shouldWrapChildren={false}>
<Handle <Handle
style={{ style={{
@@ -49,7 +49,7 @@ export const ToolTargetHandle = ({ nodeId }: ToolHandleProps) => {
border={'4px solid #8774EE'} border={'4px solid #8774EE'}
transform={'translate(0,-30%) rotate(45deg)'} transform={'translate(0,-30%) rotate(45deg)'}
pointerEvents={'none'} pointerEvents={'none'}
visibility={hidden ? 'hidden' : 'visible'} visibility={'visible'}
/> />
</Handle> </Handle>
</MyTooltip> </MyTooltip>

View File

@@ -200,14 +200,19 @@ const MyTargetHandle = React.memo(function MyTargetHandle({
) { ) {
return false; return false;
} }
if (connectingEdge?.handleId && !connectingEdge.handleId?.includes('source')) return false; if (connectingEdge?.handleId && !connectingEdge.handleId?.includes('source')) return false;
// Same source node // From same source node
if (connectedEdges.some((item) => item.target === nodeId && item.targetHandle !== handleId)) if (
connectedEdges.some(
(item) => item.source === connectingEdge?.nodeId && item.target === nodeId
)
)
return false; return false;
return true; return true;
}, [connectedEdges, connectingEdge?.handleId, edges, handleId, node, nodeId]); }, [connectedEdges, connectingEdge?.handleId, connectingEdge?.nodeId, edges, node, nodeId]);
const RenderHandle = useMemo(() => { const RenderHandle = useMemo(() => {
return ( return (

View File

@@ -2,7 +2,7 @@ import type { NextApiRequest, NextApiResponse } from 'next';
import { jsonRes } from '@fastgpt/service/common/response'; import { jsonRes } from '@fastgpt/service/common/response';
import { connectToDatabase } from '@/service/mongo'; import { connectToDatabase } from '@/service/mongo';
import { authApp } from '@fastgpt/service/support/permission/auth/app'; import { authApp } from '@fastgpt/service/support/permission/auth/app';
import { getGuideModule } from '@fastgpt/global/core/workflow/utils'; import { getGuideModule, replaceAppChatConfig } from '@fastgpt/global/core/workflow/utils';
import { getChatModelNameListByModules } from '@/service/core/app/workflow'; import { getChatModelNameListByModules } from '@/service/core/app/workflow';
import type { InitChatProps, InitChatResponse } from '@/global/core/chat/api.d'; import type { InitChatProps, InitChatResponse } from '@/global/core/chat/api.d';
import { MongoChat } from '@fastgpt/service/core/chat/chatSchema'; import { MongoChat } from '@fastgpt/service/core/chat/chatSchema';
@@ -62,7 +62,11 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
variables: chat?.variables || {}, variables: chat?.variables || {},
history, history,
app: { app: {
userGuideModule: getGuideModule(nodes), userGuideModule: replaceAppChatConfig({
node: getGuideModule(nodes),
variableList: chat?.variableList,
welcomeText: chat?.welcomeText
}),
chatModels: getChatModelNameListByModules(nodes), chatModels: getChatModelNameListByModules(nodes),
name: app.name, name: app.name,
avatar: app.avatar, avatar: app.avatar,

View File

@@ -2,7 +2,7 @@ import type { NextApiRequest, NextApiResponse } from 'next';
import { jsonRes } from '@fastgpt/service/common/response'; import { jsonRes } from '@fastgpt/service/common/response';
import { connectToDatabase } from '@/service/mongo'; import { connectToDatabase } from '@/service/mongo';
import type { InitChatResponse, InitOutLinkChatProps } from '@/global/core/chat/api.d'; import type { InitChatResponse, InitOutLinkChatProps } from '@/global/core/chat/api.d';
import { getGuideModule } from '@fastgpt/global/core/workflow/utils'; import { getGuideModule, replaceAppChatConfig } from '@fastgpt/global/core/workflow/utils';
import { getChatModelNameListByModules } from '@/service/core/app/workflow'; import { getChatModelNameListByModules } from '@/service/core/app/workflow';
import { DispatchNodeResponseKeyEnum } from '@fastgpt/global/core/workflow/runtime/constants'; import { DispatchNodeResponseKeyEnum } from '@fastgpt/global/core/workflow/runtime/constants';
import { getChatItems } from '@fastgpt/service/core/chat/controller'; import { getChatItems } from '@fastgpt/service/core/chat/controller';
@@ -72,7 +72,11 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
variables: chat?.variables || {}, variables: chat?.variables || {},
history, history,
app: { app: {
userGuideModule: getGuideModule(nodes), userGuideModule: replaceAppChatConfig({
node: getGuideModule(nodes),
variableList: chat?.variableList,
welcomeText: chat?.welcomeText
}),
chatModels: getChatModelNameListByModules(nodes), chatModels: getChatModelNameListByModules(nodes),
name: app.name, name: app.name,
avatar: app.avatar, avatar: app.avatar,

View File

@@ -1,7 +1,7 @@
import type { NextApiRequest, NextApiResponse } from 'next'; import type { NextApiRequest, NextApiResponse } from 'next';
import { jsonRes } from '@fastgpt/service/common/response'; import { jsonRes } from '@fastgpt/service/common/response';
import { connectToDatabase } from '@/service/mongo'; import { connectToDatabase } from '@/service/mongo';
import { getGuideModule } from '@fastgpt/global/core/workflow/utils'; import { getGuideModule, replaceAppChatConfig } from '@fastgpt/global/core/workflow/utils';
import { getChatModelNameListByModules } from '@/service/core/app/workflow'; import { getChatModelNameListByModules } from '@/service/core/app/workflow';
import { DispatchNodeResponseKeyEnum } from '@fastgpt/global/core/workflow/runtime/constants'; import { DispatchNodeResponseKeyEnum } from '@fastgpt/global/core/workflow/runtime/constants';
import type { InitChatResponse, InitTeamChatProps } from '@/global/core/chat/api.d'; import type { InitChatResponse, InitTeamChatProps } from '@/global/core/chat/api.d';
@@ -73,7 +73,11 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
variables: chat?.variables || {}, variables: chat?.variables || {},
history, history,
app: { app: {
userGuideModule: getGuideModule(nodes), userGuideModule: replaceAppChatConfig({
node: getGuideModule(nodes),
variableList: chat?.variableList,
welcomeText: chat?.welcomeText
}),
chatModels: getChatModelNameListByModules(nodes), chatModels: getChatModelNameListByModules(nodes),
name: app.name, name: app.name,
avatar: app.avatar, avatar: app.avatar,

View File

@@ -246,6 +246,7 @@ async function handler(req: NextApiRequest, res: NextApiResponse) {
appId: app._id, appId: app._id,
teamId, teamId,
tmbId: tmbId, tmbId: tmbId,
nodes,
variables: newVariables, variables: newVariables,
isUpdateUseTime: isOwnerUse && source === ChatSourceEnum.online, // owner update use time isUpdateUseTime: isOwnerUse && source === ChatSourceEnum.online, // owner update use time
shareId, shareId,

View File

@@ -1,4 +1,4 @@
import React, { useCallback, useMemo, useRef, useState } from 'react'; import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { Box, Flex, IconButton, useTheme, useDisclosure, Button } from '@chakra-ui/react'; import { Box, Flex, IconButton, useTheme, useDisclosure, Button } from '@chakra-ui/react';
import { StoreNodeItemType } from '@fastgpt/global/core/workflow/type/index.d'; import { StoreNodeItemType } from '@fastgpt/global/core/workflow/type/index.d';
import { AppSchema } from '@fastgpt/global/core/app/type.d'; import { AppSchema } from '@fastgpt/global/core/app/type.d';
@@ -25,7 +25,7 @@ import MyTooltip from '@fastgpt/web/components/common/MyTooltip';
import { formatTime2HM } from '@fastgpt/global/common/string/time'; import { formatTime2HM } from '@fastgpt/global/common/string/time';
import { useContextSelector } from 'use-context-selector'; import { useContextSelector } from 'use-context-selector';
import { WorkflowContext, getWorkflowStore } from '@/components/core/workflow/context'; import { WorkflowContext, getWorkflowStore } from '@/components/core/workflow/context';
import { useInterval } from 'ahooks'; import { useInterval, useUpdateEffect } from 'ahooks';
const ImportSettings = dynamic(() => import('@/components/core/workflow/Flow/ImportSettings')); const ImportSettings = dynamic(() => import('@/components/core/workflow/Flow/ImportSettings'));
const PublishHistories = dynamic( const PublishHistories = dynamic(
@@ -341,6 +341,11 @@ const Header = (props: Props) => {
nodes: StoreNodeItemType[]; nodes: StoreNodeItemType[];
edges: StoreEdgeItemType[]; edges: StoreEdgeItemType[];
}>(); }>();
const { isOpen: isOpenTest, onOpen: onOpenTest, onClose: onCloseTest } = useDisclosure();
useUpdateEffect(() => {
onOpenTest();
}, [workflowTestData]);
return ( return (
<> <>
@@ -351,9 +356,10 @@ const Header = (props: Props) => {
/> />
<ChatTest <ChatTest
ref={ChatTestRef} ref={ChatTestRef}
isOpen={isOpenTest}
{...workflowTestData} {...workflowTestData}
app={app} app={app}
onClose={() => setWorkflowTestData(undefined)} onClose={onCloseTest}
/> />
</> </>
); );

View File

@@ -99,6 +99,7 @@ const EditForm = ({
const selectLLMModel = watch('aiSettings.model'); const selectLLMModel = watch('aiSettings.model');
const datasetSearchSetting = watch('dataset'); const datasetSearchSetting = watch('dataset');
const variables = watch('userGuide.variables'); const variables = watch('userGuide.variables');
const formatVariables = useMemo( const formatVariables = useMemo(
() => formatEditorVariablePickerIcon([...getSystemVariables(t), ...variables]), () => formatEditorVariablePickerIcon([...getSystemVariables(t), ...variables]),
[t, variables] [t, variables]

View File

@@ -12,6 +12,7 @@ import ChatTest from './ChatTest';
import AppCard from './AppCard'; import AppCard from './AppCard';
import EditForm from './EditForm'; import EditForm from './EditForm';
import { AppSimpleEditFormType } from '@fastgpt/global/core/app/type'; import { AppSimpleEditFormType } from '@fastgpt/global/core/app/type';
import { v1Workflow2V2 } from '@/web/core/workflow/adapt';
const SimpleEdit = ({ appId }: { appId: string }) => { const SimpleEdit = ({ appId }: { appId: string }) => {
const { isPc } = useSystemStore(); const { isPc } = useSystemStore();
@@ -28,6 +29,14 @@ const SimpleEdit = ({ appId }: { appId: string }) => {
// show selected dataset // show selected dataset
useMount(() => { useMount(() => {
loadAllDatasets(); loadAllDatasets();
if (appDetail.version !== 'v2') {
editForm.reset(
appWorkflow2Form({
nodes: v1Workflow2V2((appDetail.modules || []) as any)?.nodes
})
);
}
}); });
return ( return (

View File

@@ -1,8 +1,4 @@
import type { import type { AIChatItemType, UserChatItemType } from '@fastgpt/global/core/chat/type.d';
AIChatItemType,
ChatItemType,
UserChatItemType
} from '@fastgpt/global/core/chat/type.d';
import { MongoApp } from '@fastgpt/service/core/app/schema'; import { MongoApp } from '@fastgpt/service/core/app/schema';
import { ChatSourceEnum } from '@fastgpt/global/core/chat/constants'; import { ChatSourceEnum } from '@fastgpt/global/core/chat/constants';
import { MongoChatItem } from '@fastgpt/service/core/chat/chatItemSchema'; import { MongoChatItem } from '@fastgpt/service/core/chat/chatItemSchema';
@@ -10,12 +6,15 @@ import { MongoChat } from '@fastgpt/service/core/chat/chatSchema';
import { addLog } from '@fastgpt/service/common/system/log'; import { addLog } from '@fastgpt/service/common/system/log';
import { getChatTitleFromChatMessage } from '@fastgpt/global/core/chat/utils'; import { getChatTitleFromChatMessage } from '@fastgpt/global/core/chat/utils';
import { mongoSessionRun } from '@fastgpt/service/common/mongo/sessionRun'; import { mongoSessionRun } from '@fastgpt/service/common/mongo/sessionRun';
import { StoreNodeItemType } from '@fastgpt/global/core/workflow/type';
import { getGuideModule, splitGuideModule } from '@fastgpt/global/core/workflow/utils';
type Props = { type Props = {
chatId: string; chatId: string;
appId: string; appId: string;
teamId: string; teamId: string;
tmbId: string; tmbId: string;
nodes: StoreNodeItemType[];
variables?: Record<string, any>; variables?: Record<string, any>;
isUpdateUseTime: boolean; isUpdateUseTime: boolean;
source: `${ChatSourceEnum}`; source: `${ChatSourceEnum}`;
@@ -30,6 +29,7 @@ export async function saveChat({
appId, appId,
teamId, teamId,
tmbId, tmbId,
nodes,
variables, variables,
isUpdateUseTime, isUpdateUseTime,
source, source,
@@ -72,6 +72,8 @@ export async function saveChat({
chat.variables = variables || {}; chat.variables = variables || {};
await chat.save({ session }); await chat.save({ session });
} else { } else {
const { welcomeText, variableNodes } = splitGuideModule(getGuideModule(nodes));
await MongoChat.create( await MongoChat.create(
[ [
{ {
@@ -79,6 +81,8 @@ export async function saveChat({
teamId, teamId,
tmbId, tmbId,
appId, appId,
variableList: variableNodes,
welcomeText,
variables, variables,
title, title,
source, source,

View File

@@ -288,7 +288,7 @@ export const getWorkflowGlobalVariables = (
t: TFunction t: TFunction
): EditorVariablePickerType[] => { ): EditorVariablePickerType[] => {
const globalVariables = formatEditorVariablePickerIcon( const globalVariables = formatEditorVariablePickerIcon(
splitGuideModule(getGuideModule(nodes))?.variableModules || [] splitGuideModule(getGuideModule(nodes))?.variableNodes || []
).map((item) => ({ ).map((item) => ({
...item, ...item,
valueType: WorkflowIOValueTypeEnum.any valueType: WorkflowIOValueTypeEnum.any