Skip to content

Commit

Permalink
v4.1 (#183)
Browse files Browse the repository at this point in the history
* chat item table

* perf: chat item save

* docs

* limit

* docs

* docs

* perf: node card

* docs

* docs
  • Loading branch information
c121914yu authored Aug 17, 2023
1 parent ce61ac3 commit 324e4a0
Show file tree
Hide file tree
Showing 49 changed files with 617 additions and 359 deletions.
29 changes: 15 additions & 14 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,14 +27,6 @@ FastGPT 是一个基于 LLM 大语言模型的知识库问答系统,提供开
| ![Demo](./.github/imgs/intro1.png) | ![Demo](./.github/imgs/intro2.png) |
| ![Demo](./.github/imgs/intro3.png) | ![Demo](./.github/imgs/intro4.png) |

## ⚡快速部署

> Sealos 的服务器在国外,不需要额外处理网络问题,无需服务器、无需魔法、无需域名,支持高并发 & 动态伸缩。点击以下按钮即可一键部署 👇
[![](https://cdn.jsdelivr.us/gh/labring-actions/templates@main/Deploy-on-Sealos.svg)](https://cloud.sealos.io/?openapp=system-fastdeploy%3FtemplateName%3Dfastgpt)

由于需要部署数据库,部署完后需要等待 2~4 分钟才能正常访问。默认用了最低配置,首次访问时会有些慢。

## 💡 功能

1. 强大的可视化编排,轻松构建 AI 应用
Expand Down Expand Up @@ -76,12 +68,21 @@ FastGPT 是一个基于 LLM 大语言模型的知识库问答系统,提供开

项目技术栈: NextJs + TS + ChakraUI + Mongo + Postgres(Vector 插件)

- [快开始本地开发](https://doc.fastgpt.run/docs/develop/dev)
- [部署 FastGPT](https://doc.fastgpt.run/docs/category/deploy)
- [系统配置文件说明](https://doc.fastgpt.run/docs/category/data-config)
- [多模型配置](https://doc.fastgpt.run/docs/develop/data_config/chat_models)
- [V3 升级 V4 初始化](https://doc.fastgpt.run/docs/develop/deploy/v4init)
- [API 文档](https://kjqvjse66l.feishu.cn/docx/DmLedTWtUoNGX8xui9ocdUEjnNh?pre_pathname=%2Fdrive%2Fhome%2F)
- **⚡ 快速部署**

> Sealos 的服务器在国外,不需要额外处理网络问题,无需服务器、无需魔法、无需域名,支持高并发 & 动态伸缩。点击以下按钮即可一键部署 👇
[![](https://cdn.jsdelivr.us/gh/labring-actions/templates@main/Deploy-on-Sealos.svg)](https://cloud.sealos.io/?openapp=system-fastdeploy%3FtemplateName%3Dfastgpt)

由于需要部署数据库,部署完后需要等待 2~4 分钟才能正常访问。默认用了最低配置,首次访问时会有些慢。

* [快开始本地开发](https://doc.fastgpt.run/docs/develop/dev)
* [部署 FastGPT](https://doc.fastgpt.run/docs/category/deploy)
* [系统配置文件说明](https://doc.fastgpt.run/docs/category/data-config)
* [多模型配置](https://doc.fastgpt.run/docs/develop/data_config/chat_models)
* [V3 升级 V4 初始化](https://doc.fastgpt.run/docs/develop/deploy/v4init)
* [升级 v4.1 初始化](https://doc.fastgpt.run/docs/develop/deploy/initv4.1)
* [API 文档](https://kjqvjse66l.feishu.cn/docx/DmLedTWtUoNGX8xui9ocdUEjnNh?pre_pathname=%2Fdrive%2Fhome%2F)

## 🏘️ 社区交流群

Expand Down
1 change: 1 addition & 0 deletions client/public/locales/en/common.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
"Confirm Save App Tip": "The application may be in advanced orchestration mode, and the advanced orchestration configuration will be overwritten after saving, please confirm!",
"Connection is invalid": "Connecting is invalid",
"Connection type is different": "Connection type is different",
"Copy Module Config": "Copy config",
"Export Config Successful": "The configuration has been copied. Please check for important data",
"Export Configs": "Export Configs",
"Import Config": "Import Config",
Expand Down
1 change: 1 addition & 0 deletions client/public/locales/zh/common.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
"Confirm Save App Tip": "该应用可能为高级编排模式,保存后将会覆盖高级编排配置,请确认!",
"Connection is invalid": "连接无效",
"Connection type is different": "连接的类型不一致",
"Copy Module Config": "复制配置",
"Export Config Successful": "已复制配置,请注意检查是否有重要数据",
"Export Configs": "导出配置",
"Import Config": "导入配置",
Expand Down
12 changes: 1 addition & 11 deletions client/src/api/chat.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,20 +27,10 @@ export const delChatHistoryById = (chatId: string) => DELETE(`/chat/removeHistor
*/
export const clearChatHistoryByAppId = (appId: string) => DELETE(`/chat/removeHistory`, { appId });

/**
* update history quote status
*/
export const updateHistoryQuote = (params: {
chatId: string;
contentId: string;
quoteId: string;
sourceText: string;
}) => PUT(`/chat/history/updateHistoryQuote`, params);

/**
* 删除一句对话
*/
export const delChatRecordByIndex = (data: { chatId: string; contentId: string }) =>
export const delChatRecordById = (data: { chatId: string; contentId: string }) =>
DELETE(`/chat/delChatRecordByContentId`, data);

/**
Expand Down
19 changes: 11 additions & 8 deletions client/src/components/ChatBox/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ import { useRouter } from 'next/router';
import { useGlobalStore } from '@/store/global';
import { TaskResponseKeyEnum, getDefaultChatVariables } from '@/constants/chat';
import { useTranslation } from 'react-i18next';
import { customAlphabet } from 'nanoid';

import MyIcon from '@/components/Icon';
import Avatar from '@/components/Avatar';
Expand All @@ -51,6 +52,8 @@ const ResponseTags = dynamic(() => import('./ResponseTags'));

import styles from './index.module.scss';

const nanoid = customAlphabet('abcdefghijklmnopqrstuvwxyz1234567890', 24);

const textareaMinH = '22px';
type generatingMessageProps = { text?: string; name?: string; status?: 'running' | 'finish' };
export type StartChatFnProps = {
Expand Down Expand Up @@ -282,13 +285,13 @@ const ChatBox = (
const newChatList: ChatSiteItemType[] = [
...chatHistory,
{
_id: String(new Types.ObjectId()),
dataId: nanoid(),
obj: 'Human',
value: val,
status: 'finish'
},
{
_id: String(new Types.ObjectId()),
dataId: nanoid(),
obj: 'AI',
value: '',
status: 'loading'
Expand Down Expand Up @@ -552,7 +555,7 @@ const ChatBox = (
{chatHistory.map((item, index) => (
<Flex
position={'relative'}
key={item._id}
key={item.dataId}
flexDirection={'column'}
alignItems={item.obj === 'Human' ? 'flex-end' : 'flex-start'}
py={5}
Expand Down Expand Up @@ -583,10 +586,10 @@ const ChatBox = (
_hover={{ color: 'red.600' }}
onClick={() => {
setChatHistory((state) =>
state.filter((chat) => chat._id !== item._id)
state.filter((chat) => chat.dataId !== item.dataId)
);
onDelMessage({
contentId: item._id,
contentId: item.dataId,
index
});
}}
Expand Down Expand Up @@ -630,10 +633,10 @@ const ChatBox = (
_hover={{ color: 'red.600' }}
onClick={() => {
setChatHistory((state) =>
state.filter((chat) => chat._id !== item._id)
state.filter((chat) => chat.dataId !== item.dataId)
);
onDelMessage({
contentId: item._id,
contentId: item.dataId,
index
});
}}
Expand Down Expand Up @@ -682,7 +685,7 @@ const ChatBox = (
/>
<ResponseTags
chatId={chatId}
contentId={item._id}
contentId={item.dataId}
responseData={item.responseData}
/>
</Card>
Expand Down
4 changes: 1 addition & 3 deletions client/src/pages/api/admin/initChat.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,9 +45,7 @@ async function init(limit: number, skip: number) {
chatId: { $exists: false }
},
'_id'
)
.limit(limit)
.skip(skip);
).limit(limit);

await Promise.all(
chats.map((chat) =>
Expand Down
98 changes: 98 additions & 0 deletions client/src/pages/api/admin/initChatItem.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
import type { NextApiRequest, NextApiResponse } from 'next';
import { jsonRes } from '@/service/response';
import { authUser } from '@/service/utils/auth';
import { connectToDatabase, Chat, ChatItem } from '@/service/mongo';
import { customAlphabet } from 'nanoid';
const nanoid = customAlphabet('abcdefghijklmnopqrstuvwxyz1234567890', 24);

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
try {
await authUser({ req, authRoot: true });
await connectToDatabase();

const { limit = 100 } = req.body as { limit: number };
let skip = 0;

const total = await Chat.countDocuments({
content: { $exists: true, $not: { $size: 0 } },
isInit: { $ne: true }
});
const totalChat = await Chat.aggregate([
{
$project: {
contentLength: { $size: '$content' }
}
},
{
$group: {
_id: null,
totalLength: { $sum: '$contentLength' }
}
}
]);

console.log('chatLen:', total, totalChat);

let promise = Promise.resolve();

for (let i = 0; i < total; i += limit) {
const skipVal = skip;
skip += limit;
promise = promise
.then(() => init(limit))
.then(() => {
console.log(skipVal);
});
}

await promise;

jsonRes(res, {});
} catch (error) {
jsonRes(res, {
code: 500,
error
});
}
}

async function init(limit: number) {
// 遍历 app
const chats = await Chat.find(
{
content: { $exists: true, $not: { $size: 0 } },
isInit: { $ne: true }
},
'_id userId appId chatId content'
)
.sort({ updateTime: -1 })
.limit(limit);

await Promise.all(
chats.map(async (chat) => {
const inserts = chat.content
.map((item) => ({
dataId: nanoid(),
chatId: chat.chatId,
userId: chat.userId,
appId: chat.appId,
obj: item.obj,
value: item.value,
responseData: item.responseData
}))
.filter((item) => item.chatId && item.userId && item.appId && item.obj && item.value);

try {
await Promise.all(inserts.map((item) => ChatItem.create(item)));
await Chat.findByIdAndUpdate(chat._id, {
isInit: true
});
} catch (error) {
console.log(error);

await ChatItem.deleteMany({ chatId: chat.chatId });
}
})
);
}
4 changes: 1 addition & 3 deletions client/src/pages/api/admin/initv4.ts
Original file line number Diff line number Diff line change
Expand Up @@ -408,9 +408,7 @@ async function init(limit: number, skip: number) {
// userId: '63f9a14228d2a688d8dc9e1b'
},
'_id chat'
)
.limit(limit)
.skip(skip);
).limit(limit);

return Promise.all(
apps.map(async (app) => {
Expand Down
24 changes: 6 additions & 18 deletions client/src/pages/api/chat/delChatRecordByContentId.ts
Original file line number Diff line number Diff line change
@@ -1,35 +1,23 @@
import type { NextApiRequest, NextApiResponse } from 'next';
import { jsonRes } from '@/service/response';
import { connectToDatabase, Chat } from '@/service/mongo';
import { connectToDatabase, ChatItem } from '@/service/mongo';
import { authUser } from '@/service/utils/auth';

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
try {
const { chatId, contentId } = req.query as { chatId: string; contentId: string };

if (!chatId || !contentId) {
throw new Error('缺少参数');
}

await connectToDatabase();

// 凭证校验
const { userId } = await authUser({ req, authToken: true });

const chatRecord = await Chat.findOne({ chatId });

if (!chatRecord) {
throw new Error('找不到对话');
}

// 删除一条数据库记录
await Chat.updateOne(
{
chatId,
userId
},
{ $pull: { content: { _id: contentId } } }
);
await ChatItem.deleteOne({
dataId: contentId,
chatId,
userId
});

jsonRes(res);
} catch (err) {
Expand Down
57 changes: 0 additions & 57 deletions client/src/pages/api/chat/history/updateHistoryQuote.ts

This file was deleted.

Loading

0 comments on commit 324e4a0

Please sign in to comment.