Skip to content

Commit

Permalink
feat: Fetch mind map in search page infiniflow#2247
Browse files Browse the repository at this point in the history
  • Loading branch information
cike8899 committed Sep 6, 2024
1 parent 7e0b3d1 commit 66a903f
Show file tree
Hide file tree
Showing 11 changed files with 102 additions and 127 deletions.
6 changes: 4 additions & 2 deletions web/src/components/indented-tree/indented-tree.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import {
} from '@antv/g6';
import { TreeData } from '@antv/g6/lib/types';
import isEmpty from 'lodash/isEmpty';
import { useCallback, useEffect, useRef } from 'react';
import React, { useCallback, useEffect, useRef } from 'react';

const rootId = 'root';

Expand Down Expand Up @@ -294,9 +294,10 @@ register(
interface IProps {
data: TreeData;
show: boolean;
style?: React.CSSProperties;
}

const IndentedTree = ({ data, show }: IProps) => {
const IndentedTree = ({ data, show, style = {} }: IProps) => {
const containerRef = useRef<HTMLDivElement>(null);
const graphRef = useRef<Graph | null>(null);

Expand Down Expand Up @@ -388,6 +389,7 @@ const IndentedTree = ({ data, show }: IProps) => {
width: '90vw',
height: '80vh',
display: show ? 'block' : 'none',
...style,
}}
/>
);
Expand Down
21 changes: 20 additions & 1 deletion web/src/hooks/chat-hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -490,13 +490,32 @@ export const useFetchMindMap = () => {
mutateAsync,
} = useMutation({
mutationKey: ['fetchMindMap'],
gcTime: 0,
mutationFn: async (params: IAskRequestBody) => {
const { data } = await chatService.getMindMap(params);

return data;
return data?.data ?? [];
},
});

return { data, loading, fetchMindMap: mutateAsync };
};

export const useFetchRelatedQuestions = () => {
const {
data,
isPending: loading,
mutateAsync,
} = useMutation({
mutationKey: ['fetchRelatedQuestions'],
gcTime: 0,
mutationFn: async (question: string): Promise<string[]> => {
const { data } = await chatService.getRelatedQuestions({ question });

return data?.data ?? [];
},
});

return { data, loading, fetchRelatedQuestions: mutateAsync };
};
//#endregion
2 changes: 1 addition & 1 deletion web/src/interfaces/request/chat.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,6 @@ export interface IFeedbackRequestBody {
}

export interface IAskRequestBody {
questionkb_ids: string;
question: string;
kb_ids: string[];
}
4 changes: 2 additions & 2 deletions web/src/layouts/components/header/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import { useLocation } from 'umi';
import Toolbar from '../right-toolbar';

import { useFetchAppConf } from '@/hooks/logic-hooks';
import { MessageOutlined } from '@ant-design/icons';
import { MessageOutlined, SearchOutlined } from '@ant-design/icons';
import styles from './index.less';

const { Header } = Layout;
Expand All @@ -27,7 +27,7 @@ const RagHeader = () => {
() => [
{ path: '/knowledge', name: t('knowledgeBase'), icon: KnowledgeBaseIcon },
{ path: '/chat', name: t('chat'), icon: MessageOutlined },
// { path: '/search', name: t('search'), icon: SearchOutlined },
{ path: '/search', name: t('search'), icon: SearchOutlined },
{ path: '/flow', name: t('flow'), icon: GraphIcon },
{ path: '/file', name: t('fileManager'), icon: FileIcon },
],
Expand Down
109 changes: 0 additions & 109 deletions web/src/pages/force-graph/index.tsx
Original file line number Diff line number Diff line change
@@ -1,112 +1,3 @@
import { Graph } from '@antv/g6';
import { useSize } from 'ahooks';
import { useEffect, useRef } from 'react';
import { graphData } from './constant';
import InputWithUpload from './input-upload';

import styles from './index.less';
import { Converter } from './util';

const converter = new Converter();

const nextData = converter.buildNodesAndCombos(
graphData.nodes,
graphData.edges,
);
console.log('🚀 ~ nextData:', nextData);

const finalData = { ...graphData, ...nextData };

const ForceGraph = () => {
const containerRef = useRef<HTMLDivElement>(null);
const size = useSize(containerRef);
let graph: Graph;

const render = () => {
graph = new Graph({
container: containerRef.current!,
autoFit: 'view',
behaviors: [
'drag-element',
'drag-canvas',
'zoom-canvas',
'collapse-expand',
{
type: 'hover-activate',
degree: 1, // 👈🏻 Activate relations.
},
],
plugins: [
{
type: 'tooltip',
getContent: (e, items) => {
if (items.every((x) => x?.description)) {
let result = ``;
items.forEach((item) => {
if (item?.description) {
result += `<p>${item?.description}</p>`;
}
});
return result;
}
return undefined;
},
},
],
layout: {
type: 'combo-combined',
preventOverlap: true,
comboPadding: 1,
spacing: 20,
},
node: {
style: {
size: 20,
labelText: (d) => d.id,
labelPadding: 30,
// labelOffsetX: 20,
// labelOffsetY: 5,
labelPlacement: 'center',
labelWordWrap: true,
},
palette: {
type: 'group',
field: (d) => d.combo,
},
// state: {
// highlight: {
// fill: '#D580FF',
// halo: true,
// lineWidth: 0,
// },
// dim: {
// fill: '#99ADD1',
// },
// },
},
edge: {
style: (model) => {
const { size, color } = model.data;
return {
stroke: color || '#99ADD1',
lineWidth: size || 1,
};
},
},
// data: graphData,
});

graph.setData(finalData);

graph.render();
};

useEffect(() => {
console.info('rendered');
render();
}, []);

return <div ref={containerRef} className={styles.container} />;
};

export default InputWithUpload;
25 changes: 23 additions & 2 deletions web/src/pages/search/hooks.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { useFetchMindMap, useFetchRelatedQuestions } from '@/hooks/chat-hooks';
import { useTestChunkRetrieval } from '@/hooks/knowledge-hooks';
import { useSendMessageWithSse } from '@/hooks/logic-hooks';
import { IAnswer } from '@/interfaces/database/chat';
Expand All @@ -10,15 +11,27 @@ export const useSendQuestion = (kbIds: string[]) => {
const { testChunk, loading } = useTestChunkRetrieval();
const [sendingLoading, setSendingLoading] = useState(false);
const [currentAnswer, setCurrentAnswer] = useState({} as IAnswer);
const { fetchRelatedQuestions, data: relatedQuestions } =
useFetchRelatedQuestions();
const {
fetchMindMap,
data: mindMap,
loading: mindMapLoading,
} = useFetchMindMap();

const sendQuestion = useCallback(
(question: string) => {
setCurrentAnswer({} as IAnswer);
setSendingLoading(true);
send({ kb_ids: kbIds, question });
testChunk({ kb_id: kbIds, highlight: true, question });
fetchMindMap({
question,
kb_ids: kbIds,
});
fetchRelatedQuestions(question);
},
[send, testChunk, kbIds],
[send, testChunk, kbIds, fetchRelatedQuestions, fetchMindMap],
);

useEffect(() => {
Expand All @@ -33,5 +46,13 @@ export const useSendQuestion = (kbIds: string[]) => {
}
}, [done]);

return { sendQuestion, loading, sendingLoading, answer: currentAnswer };
return {
sendQuestion,
loading,
sendingLoading,
answer: currentAnswer,
relatedQuestions: relatedQuestions?.slice(0, 5) ?? [],
mindMap,
mindMapLoading,
};
};
6 changes: 5 additions & 1 deletion web/src/pages/search/index.less
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@
.card {
width: 100%;
}
.tag {
padding: 4px 8px;
font-size: 14px;
}
}

.searchSide {
Expand Down Expand Up @@ -49,6 +53,6 @@

.graph {
width: 40%;
background-color: bisque;
padding-right: 10px;
}
}
35 changes: 32 additions & 3 deletions web/src/pages/search/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,13 @@ import HightLightMarkdown from '@/components/highlight-markdown';
import { ImageWithPopover } from '@/components/image';
import { useSelectTestingResult } from '@/hooks/knowledge-hooks';
import { IReference } from '@/interfaces/database/chat';
import { Card, Flex, Input, Layout, List, Space } from 'antd';
import { Card, Flex, Input, Layout, List, Skeleton, Space, Tag } from 'antd';
import { useState } from 'react';
import MarkdownContent from '../chat/markdown-content';
import { useSendQuestion } from './hooks';
import SearchSidebar from './sidebar';

import IndentedTree from '@/components/indented-tree/indented-tree';
import styles from './index.less';

const { Content } = Layout;
Expand All @@ -16,7 +17,14 @@ const { Search } = Input;
const SearchPage = () => {
const [checkedList, setCheckedList] = useState<string[]>([]);
const list = useSelectTestingResult();
const { sendQuestion, answer, sendingLoading } = useSendQuestion(checkedList);
const {
sendQuestion,
answer,
sendingLoading,
relatedQuestions,
mindMap,
mindMapLoading,
} = useSendQuestion(checkedList);

return (
<Layout className={styles.searchPage}>
Expand Down Expand Up @@ -56,8 +64,29 @@ const SearchPage = () => {
</List.Item>
)}
/>
{relatedQuestions?.length > 0 && (
<Card>
<Flex wrap="wrap" gap={'10px 0'}>
{relatedQuestions?.map((x, idx) => (
<Tag key={idx} className={styles.tag}>
{x}
</Tag>
))}
</Flex>
</Card>
)}
</section>
<section className={styles.graph}>
{mindMapLoading ? (
<Skeleton active />
) : (
<IndentedTree
data={mindMap}
show
style={{ width: '100%', height: '100%' }}
></IndentedTree>
)}
</section>
<section className={styles.graph}></section>
</Flex>
</Content>
</Layout>
Expand Down
15 changes: 9 additions & 6 deletions web/src/pages/search/sidebar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -30,20 +30,23 @@ const SearchSidebar = ({ checkedList, setCheckedList }: IProps) => {
const indeterminate =
checkedList.length > 0 && checkedList.length < list.length;

const onChange = useCallback((list: CheckboxValueType[]) => {
setCheckedList(list as string[]);
}, []);
const onChange = useCallback(
(list: CheckboxValueType[]) => {
setCheckedList(list as string[]);
},
[setCheckedList],
);

const onCheckAllChange: CheckboxProps['onChange'] = useCallback(
(e: CheckboxChangeEvent) => {
setCheckedList(e.target.checked ? ids : []);
},
[ids],
[ids, setCheckedList],
);

useEffect(() => {
setCheckedList(ids);
}, [ids]);
}, [ids, setCheckedList]);

return (
<Sider className={styles.searchSide} theme={'light'} width={240}>
Expand All @@ -53,7 +56,7 @@ const SearchSidebar = ({ checkedList, setCheckedList }: IProps) => {
onChange={onCheckAllChange}
checked={checkAll}
>
Check all
All
</Checkbox>
<Checkbox.Group
className={styles.checkGroup}
Expand Down
5 changes: 5 additions & 0 deletions web/src/services/chat-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ const {
tts,
ask,
mindmap,
getRelatedQuestions,
} = api;

const methods = {
Expand Down Expand Up @@ -116,6 +117,10 @@ const methods = {
url: mindmap,
method: 'post',
},
getRelatedQuestions: {
url: getRelatedQuestions,
method: 'post',
},
} as const;

const chatService = registerServer<keyof typeof methods>(methods, request);
Expand Down
1 change: 1 addition & 0 deletions web/src/utils/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ export default {
tts: `${api_host}/conversation/tts`,
ask: `${api_host}/conversation/ask`,
mindmap: `${api_host}/conversation/mindmap`,
getRelatedQuestions: `${api_host}/conversation/related_questions`,
// chat for external
createToken: `${api_host}/api/new_token`,
listToken: `${api_host}/api/token_list`,
Expand Down

0 comments on commit 66a903f

Please sign in to comment.