Commit ae95a890 by archer

fix: savechat.feat: extract flow

parent 58153306
...@@ -6,7 +6,7 @@ interface Props extends TooltipProps { ...@@ -6,7 +6,7 @@ interface Props extends TooltipProps {
forceShow?: boolean; forceShow?: boolean;
} }
const MyTooltip = ({ children, forceShow = false, ...props }: Props) => { const MyTooltip = ({ children, forceShow = false, shouldWrapChildren = true, ...props }: Props) => {
const { isPc } = useGlobalStore(); const { isPc } = useGlobalStore();
return isPc || forceShow ? ( return isPc || forceShow ? (
<Tooltip <Tooltip
...@@ -21,6 +21,7 @@ const MyTooltip = ({ children, forceShow = false, ...props }: Props) => { ...@@ -21,6 +21,7 @@ const MyTooltip = ({ children, forceShow = false, ...props }: Props) => {
borderRadius={'8px'} borderRadius={'8px'}
whiteSpace={'pre-wrap'} whiteSpace={'pre-wrap'}
boxShadow={'1px 1px 10px rgba(0,0,0,0.2)'} boxShadow={'1px 1px 10px rgba(0,0,0,0.2)'}
shouldWrapChildren={shouldWrapChildren}
{...props} {...props}
> >
{children} {children}
......
...@@ -45,7 +45,7 @@ export enum FlowValueTypeEnum { ...@@ -45,7 +45,7 @@ export enum FlowValueTypeEnum {
'boolean' = 'boolean', 'boolean' = 'boolean',
'chatHistory' = 'chat_history', 'chatHistory' = 'chat_history',
'kbQuote' = 'kb_quote', 'kbQuote' = 'kb_quote',
'other' = 'other' 'any' = 'any'
} }
export const FlowValueTypeStyle: Record<`${FlowValueTypeEnum}`, BoxProps> = { export const FlowValueTypeStyle: Record<`${FlowValueTypeEnum}`, BoxProps> = {
...@@ -64,7 +64,7 @@ export const FlowValueTypeStyle: Record<`${FlowValueTypeEnum}`, BoxProps> = { ...@@ -64,7 +64,7 @@ export const FlowValueTypeStyle: Record<`${FlowValueTypeEnum}`, BoxProps> = {
[FlowValueTypeEnum.kbQuote]: { [FlowValueTypeEnum.kbQuote]: {
background: '#A558C9' background: '#A558C9'
}, },
[FlowValueTypeEnum.other]: { [FlowValueTypeEnum.any]: {
background: '#9CA2A8' background: '#9CA2A8'
} }
}; };
......
...@@ -6,7 +6,7 @@ export const Input_Template_TFSwitch: FlowInputItemType = { ...@@ -6,7 +6,7 @@ export const Input_Template_TFSwitch: FlowInputItemType = {
key: SystemInputEnum.switch, key: SystemInputEnum.switch,
type: FlowInputItemTypeEnum.target, type: FlowInputItemTypeEnum.target,
label: '触发器', label: '触发器',
valueType: FlowValueTypeEnum.boolean valueType: FlowValueTypeEnum.any
}; };
export const Input_Template_History: FlowInputItemType = { export const Input_Template_History: FlowInputItemType = {
......
...@@ -139,7 +139,7 @@ export default withNextCors(async function handler(req: NextApiRequest, res: Nex ...@@ -139,7 +139,7 @@ export default withNextCors(async function handler(req: NextApiRequest, res: Nex
// } // }
// save chat // save chat
if (typeof chatId === 'string') { if (chatId) {
await saveChat({ await saveChat({
chatId, chatId,
appId, appId,
......
...@@ -11,8 +11,7 @@ const NodeAnswer = ({ ...@@ -11,8 +11,7 @@ const NodeAnswer = ({
}: NodeProps<FlowModuleItemType>) => { }: NodeProps<FlowModuleItemType>) => {
return ( return (
<NodeCard minW={'400px'} moduleId={moduleId} {...props}> <NodeCard minW={'400px'} moduleId={moduleId} {...props}>
<Divider text="Input" /> <Container borderTop={'2px solid'} borderTopColor={'myGray.200'}>
<Container>
<RenderInput moduleId={moduleId} onChangeNode={onChangeNode} flowInputList={inputs} /> <RenderInput moduleId={moduleId} onChangeNode={onChangeNode} flowInputList={inputs} />
</Container> </Container>
</NodeCard> </NodeCard>
......
...@@ -55,7 +55,7 @@ const NodeCQNode = ({ ...@@ -55,7 +55,7 @@ const NodeCQNode = ({
onChangeNode({ onChangeNode({
moduleId, moduleId,
type: 'outputs', type: 'outputs',
key: agentKey, key: '',
value: newOutputVal value: newOutputVal
}); });
}} }}
......
...@@ -13,6 +13,8 @@ import RenderOutput from '../render/RenderOutput'; ...@@ -13,6 +13,8 @@ import RenderOutput from '../render/RenderOutput';
import MyIcon from '@/components/Icon'; import MyIcon from '@/components/Icon';
import ExtractFieldModal from '../modules/ExtractFieldModal'; import ExtractFieldModal from '../modules/ExtractFieldModal';
import { ContextExtractEnum } from '@/constants/flow/flowField'; import { ContextExtractEnum } from '@/constants/flow/flowField';
import SourceHandle from '../render/SourceHandle';
import { FlowOutputItemTypeEnum, FlowValueTypeEnum } from '@/constants/flow';
const NodeExtract = ({ const NodeExtract = ({
data: { inputs, outputs, moduleId, onChangeNode, ...props } data: { inputs, outputs, moduleId, onChangeNode, ...props }
...@@ -36,7 +38,22 @@ const NodeExtract = ({ ...@@ -36,7 +38,22 @@ const NodeExtract = ({
key: string; key: string;
value?: ContextExtractAgentItemType[]; value?: ContextExtractAgentItemType[];
}) => ( }) => (
<Box> <Box pt={2}>
<Box position={'absolute'} top={0} right={0}>
<Button
variant={'base'}
leftIcon={<AddIcon fontSize={'10px'} />}
onClick={() =>
setEditExtractField({
desc: '',
key: '',
required: true
})
}
>
新增字段
</Button>
</Box>
<TableContainer> <TableContainer>
<Table> <Table>
<Thead> <Thead>
...@@ -49,10 +66,10 @@ const NodeExtract = ({ ...@@ -49,10 +66,10 @@ const NodeExtract = ({
</Thead> </Thead>
<Tbody> <Tbody>
{extractKeys.map((item, index) => ( {extractKeys.map((item, index) => (
<Tr key={index}> <Tr key={index} position={'relative'}>
<Td>{item.key}</Td> <Td>{item.key}</Td>
<Td whiteSpace={'pre-line'} wordBreak={'break-all'}> <Td whiteSpace={'pre-line'} wordBreak={'break-all'}>
{item.desc}{' '} {item.desc}
</Td> </Td>
<Td>{item.required ? '✔' : ''}</Td> <Td>{item.required ? '✔' : ''}</Td>
<Td whiteSpace={'nowrap'}> <Td whiteSpace={'nowrap'}>
...@@ -70,11 +87,24 @@ const NodeExtract = ({ ...@@ -70,11 +87,24 @@ const NodeExtract = ({
w={'16px'} w={'16px'}
cursor={'pointer'} cursor={'pointer'}
onClick={() => { onClick={() => {
const newInputValue = extractKeys.filter(
(extract) => item.key !== extract.key
);
const newOutputVal = outputs.filter(
(output) => output.key !== item.key
);
onChangeNode({ onChangeNode({
moduleId, moduleId,
type: 'inputs', type: 'inputs',
key: ContextExtractEnum.extractKeys, key: ContextExtractEnum.extractKeys,
value: extractKeys.filter((extract) => item.key !== extract.key) value: newInputValue
});
onChangeNode({
moduleId,
type: 'outputs',
key: '',
value: newOutputVal
}); });
}} }}
/> />
...@@ -84,21 +114,6 @@ const NodeExtract = ({ ...@@ -84,21 +114,6 @@ const NodeExtract = ({
</Tbody> </Tbody>
</Table> </Table>
</TableContainer> </TableContainer>
<Box mt={2} textAlign={'right'}>
<Button
variant={'base'}
leftIcon={<AddIcon fontSize={'10px'} />}
onClick={() =>
setEditExtractField({
desc: '',
key: '',
required: true
})
}
>
新增字段
</Button>
</Box>
</Box> </Box>
) )
}} }}
...@@ -119,21 +134,39 @@ const NodeExtract = ({ ...@@ -119,21 +134,39 @@ const NodeExtract = ({
const exists = extracts.find((item) => item.key === editExtractFiled.key); const exists = extracts.find((item) => item.key === editExtractFiled.key);
if (exists) { const newInputs = exists
? extracts.map((item) => (item.key === editExtractFiled.key ? data : item))
: extracts.concat(data);
const newOutputs = exists
? outputs.map((output) =>
output.key === editExtractFiled.key
? {
...output,
key: data.key,
label: `提取结果-${data.desc}`
}
: output
)
: outputs.concat({
key: data.key,
label: `提取结果-${data.desc}`,
valueType: FlowValueTypeEnum.string,
type: FlowOutputItemTypeEnum.source,
targets: []
});
onChangeNode({ onChangeNode({
moduleId, moduleId,
type: 'inputs', type: 'inputs',
key: ContextExtractEnum.extractKeys, key: ContextExtractEnum.extractKeys,
value: extracts.map((item) => (item.key === editExtractFiled.key ? data : item)) value: newInputs
}); });
} else {
onChangeNode({ onChangeNode({
moduleId, moduleId,
type: 'inputs', type: 'outputs',
key: ContextExtractEnum.extractKeys, key: '',
value: extracts.concat(data) value: newOutputs
}); });
}
setEditExtractField(undefined); setEditExtractField(undefined);
}} }}
......
...@@ -35,7 +35,7 @@ export const Label = ({ ...@@ -35,7 +35,7 @@ export const Label = ({
)} )}
{description && ( {description && (
<MyTooltip label={description} forceShow> <MyTooltip label={description} forceShow>
<QuestionOutlineIcon display={['none', 'inline']} transform={'translateY(-1px)'} ml={1} /> <QuestionOutlineIcon display={['none', 'inline']} ml={1} />
</MyTooltip> </MyTooltip>
)} )}
</Box> </Box>
......
...@@ -17,14 +17,14 @@ const Label = ({ ...@@ -17,14 +17,14 @@ const Label = ({
<Flex as={'label'} justifyContent={'right'} alignItems={'center'} position={'relative'}> <Flex as={'label'} justifyContent={'right'} alignItems={'center'} position={'relative'}>
{description && ( {description && (
<MyTooltip label={description} forceShow> <MyTooltip label={description} forceShow>
<QuestionOutlineIcon display={['none', 'inline']} transform={'translateY(-1px)'} mr={1} /> <QuestionOutlineIcon display={['none', 'inline']} mr={1} />
</MyTooltip> </MyTooltip>
)} )}
{children} {children}
</Flex> </Flex>
); );
const RenderBody = ({ flowOutputList }: { flowOutputList: FlowOutputItemType[] }) => { const RenderOutput = ({ flowOutputList }: { flowOutputList: FlowOutputItemType[] }) => {
return ( return (
<> <>
{flowOutputList.map( {flowOutputList.map(
...@@ -44,4 +44,4 @@ const RenderBody = ({ flowOutputList }: { flowOutputList: FlowOutputItemType[] } ...@@ -44,4 +44,4 @@ const RenderBody = ({ flowOutputList }: { flowOutputList: FlowOutputItemType[] }
); );
}; };
export default React.memo(RenderBody); export default RenderOutput;
...@@ -14,8 +14,8 @@ const SourceHandle = ({ handleKey, valueType, ...props }: Props) => { ...@@ -14,8 +14,8 @@ const SourceHandle = ({ handleKey, valueType, ...props }: Props) => {
() => () =>
valueType valueType
? FlowValueTypeStyle[valueType] ? FlowValueTypeStyle[valueType]
: (FlowValueTypeStyle[FlowValueTypeEnum.other] as any), : (FlowValueTypeStyle[FlowValueTypeEnum.any] as any),
[] [valueType]
); );
return ( return (
......
...@@ -15,7 +15,7 @@ const TargetHandle = ({ handleKey, valueType, onConnect, ...props }: Props) => { ...@@ -15,7 +15,7 @@ const TargetHandle = ({ handleKey, valueType, onConnect, ...props }: Props) => {
() => () =>
valueType valueType
? FlowValueTypeStyle[valueType] ? FlowValueTypeStyle[valueType]
: (FlowValueTypeStyle[FlowValueTypeEnum.other] as any), : (FlowValueTypeStyle[FlowValueTypeEnum.any] as any),
[] []
); );
......
...@@ -132,7 +132,7 @@ const AppEdit = ({ app, fullScreen, onFullScreen }: Props) => { ...@@ -132,7 +132,7 @@ const AppEdit = ({ app, fullScreen, onFullScreen }: Props) => {
connected: item.type !== FlowInputItemTypeEnum.target connected: item.type !== FlowInputItemTypeEnum.target
})), })),
outputs: item.data.outputs.map((item) => ({ outputs: item.data.outputs.map((item) => ({
key: item.key, ...item,
targets: [] as FlowOutputTargetItemType[] targets: [] as FlowOutputTargetItemType[]
})) }))
})); }));
...@@ -254,7 +254,11 @@ const AppEdit = ({ app, fullScreen, onFullScreen }: Props) => { ...@@ -254,7 +254,11 @@ const AppEdit = ({ app, fullScreen, onFullScreen }: Props) => {
title: t('app.Connection is invalid') title: t('app.Connection is invalid')
}); });
} }
if (sourceType !== targetType) { if (
sourceType !== FlowValueTypeEnum.any &&
targetType !== FlowValueTypeEnum.any &&
sourceType !== targetType
) {
return toast({ return toast({
status: 'warning', status: 'warning',
title: t('app.Connection type is different') title: t('app.Connection type is different')
...@@ -280,6 +284,7 @@ const AppEdit = ({ app, fullScreen, onFullScreen }: Props) => { ...@@ -280,6 +284,7 @@ const AppEdit = ({ app, fullScreen, onFullScreen }: Props) => {
const { mutate: onclickSave, isLoading } = useRequest({ const { mutate: onclickSave, isLoading } = useRequest({
mutationFn: () => { mutationFn: () => {
console.log(flow2AppModules(), '====');
return updateAppDetail(app._id, { return updateAppDetail(app._id, {
modules: flow2AppModules() modules: flow2AppModules()
}); });
......
...@@ -96,7 +96,6 @@ export async function dispatchContentExtract({ ...@@ -96,7 +96,6 @@ export async function dispatchContentExtract({
return {}; return {};
} }
})(); })();
console.log(adaptMessages, arg);
// auth fields // auth fields
let success = !extractKeys.find((item) => !arg[item.key]); let success = !extractKeys.find((item) => !arg[item.key]);
...@@ -109,6 +108,7 @@ export async function dispatchContentExtract({ ...@@ -109,6 +108,7 @@ export async function dispatchContentExtract({
} }
} }
} }
console.log(arg, '====');
const tokens = response.data.usage?.total_tokens || 0; const tokens = response.data.usage?.total_tokens || 0;
...@@ -116,6 +116,7 @@ export async function dispatchContentExtract({ ...@@ -116,6 +116,7 @@ export async function dispatchContentExtract({
[ContextExtractEnum.success]: success ? true : undefined, [ContextExtractEnum.success]: success ? true : undefined,
[ContextExtractEnum.failed]: success ? undefined : true, [ContextExtractEnum.failed]: success ? undefined : true,
[ContextExtractEnum.fields]: arg, [ContextExtractEnum.fields]: arg,
...arg,
[TaskResponseKeyEnum.responseData]: { [TaskResponseKeyEnum.responseData]: {
moduleName: ChatModuleEnum.Extract, moduleName: ChatModuleEnum.Extract,
price: userOpenaiAccount?.key ? 0 : countModelPrice({ model: agentModel, tokens }), price: userOpenaiAccount?.key ? 0 : countModelPrice({ model: agentModel, tokens }),
......
...@@ -36,7 +36,7 @@ export async function saveChat({ ...@@ -36,7 +36,7 @@ export async function saveChat({
if (chatHistory) { if (chatHistory) {
promise.push( promise.push(
Chat.findOneAndUpdate( Chat.findOneAndUpdate(
{ chatId }, { chatId, userId },
{ {
$push: { $push: {
content: { content: {
......
...@@ -64,13 +64,12 @@ export type VariableItemType = { ...@@ -64,13 +64,12 @@ export type VariableItemType = {
/* app module */ /* app module */
export type AppModuleInputItemType = { key: string; value?: any; connected?: boolean }; export type AppModuleInputItemType = { key: string; value?: any; connected?: boolean };
export type AppModuleOutputItemType = { key: string; targets: FlowOutputTargetItemType[] };
export type AppModuleItemType = { export type AppModuleItemType = {
moduleId: string; moduleId: string;
position?: XYPosition; position?: XYPosition;
flowType: `${FlowModuleTypeEnum}`; flowType: `${FlowModuleTypeEnum}`;
inputs: AppModuleInputItemType[]; inputs: AppModuleInputItemType[];
outputs: AppModuleOutputItemType[]; outputs: FlowOutputItemType[];
}; };
export type AppItemType = { export type AppItemType = {
......
...@@ -39,10 +39,10 @@ export type FlowOutputTargetItemType = { ...@@ -39,10 +39,10 @@ export type FlowOutputTargetItemType = {
}; };
export type FlowOutputItemType = { export type FlowOutputItemType = {
key: string; // 字段名 key: string; // 字段名
label: string; label?: string;
description?: string; description?: string;
valueType?: `${FlowValueTypeEnum}`; valueType?: `${FlowValueTypeEnum}`;
type: `${FlowOutputItemTypeEnum}`; type?: `${FlowOutputItemTypeEnum}`;
targets: FlowOutputTargetItemType[]; targets: FlowOutputTargetItemType[];
}; };
......
...@@ -73,6 +73,10 @@ export const appModule2FlowNode = ({ ...@@ -73,6 +73,10 @@ export const appModule2FlowNode = ({
const template = const template =
ModuleTemplatesFlat.find((template) => template.flowType === item.flowType) || EmptyModule; ModuleTemplatesFlat.find((template) => template.flowType === item.flowType) || EmptyModule;
const mergeOutputs = item.outputs.concat(
template.outputs.filter((output) => !item.outputs.find((item) => item.key === output.key))
);
// replace item data // replace item data
const moduleItem: FlowModuleItemType = { const moduleItem: FlowModuleItemType = {
...item, ...item,
...@@ -85,14 +89,14 @@ export const appModule2FlowNode = ({ ...@@ -85,14 +89,14 @@ export const appModule2FlowNode = ({
value: itemInput.value value: itemInput.value
}; };
}), }),
outputs: template.outputs.map((templateOutput) => { // 合并 template 和数据库,文案以 template 为准
outputs: mergeOutputs.map((output) => {
// unChange outputs // unChange outputs
const itemOutput = const templateOutput = template.outputs.find((item) => item.key === output.key);
item.outputs.find((item) => item.key === templateOutput.key) || templateOutput;
return { return {
...templateOutput, ...(templateOutput ? templateOutput : output),
targets: itemOutput.targets || [] targets: output.targets || []
}; };
}), }),
onChangeNode, onChangeNode,
...@@ -131,5 +135,6 @@ export const appModule2FlowEdge = ({ ...@@ -131,5 +135,6 @@ export const appModule2FlowEdge = ({
}) })
) )
); );
return edges; return edges;
}; };
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