Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

perf: collection created response #1947

Merged
merged 7 commits into from
Jul 5, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion docSite/content/zh-cn/docs/development/openapi/dataset.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ weight: 853



## 创建训练订单(4.6.9地址发生改动)
## 创建训练订单

{{< tabs tabTotal="2" >}}
{{< tab tabName="请求示例" >}}
Expand All @@ -26,6 +26,7 @@ curl --location --request POST 'https://api.fastgpt.in/api/support/wallet/usage/
--header 'Authorization: Bearer {{apikey}}' \
--header 'Content-Type: application/json' \
--data-raw '{
"datasetId": "知识库 ID",
"name": "可选,自定义订单名称,例如:文档训练-fastgpt.docx"
}'
```
Expand Down
6 changes: 4 additions & 2 deletions docSite/content/zh-cn/docs/development/upgrading/486.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,5 +38,7 @@ curl --location --request POST 'https://{{host}}/api/admin/initv486' \
3. 新增 - 网页抓取和数学计算器系统插件
4. 新增 - 移动文本加工和自定义反馈到基础节点中
5. 优化 - Read file 默认选中从节点,实现 MongoDB 读写分离,减轻主节点压力
6. 修复 - 工作流中团队插件加载异常
7. 修复 - 知识库集合目录导航失效
6. 优化 - 知识库导入接口,返回值对齐
7. 修复 - 工作流中团队插件加载异常
8. 修复 - 知识库集合目录导航失效
9. 修复 - 通过 API 调用 chat 接口,传递 System 异常
11 changes: 11 additions & 0 deletions packages/global/core/chat/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,17 @@ import { FlowNodeTypeEnum } from '../workflow/node/constant';
import { ChatItemValueTypeEnum, ChatRoleEnum } from './constants';
import { ChatHistoryItemResType, ChatItemType, UserChatItemValueItemType } from './type.d';

// Concat 2 -> 1, and sort by role
export const concatHistories = (histories1: ChatItemType[], histories2: ChatItemType[]) => {
const newHistories = [...histories1, ...histories2];
return newHistories.sort((a, b) => {
if (a.obj === ChatRoleEnum.System) {
return -1;
}
return 1;
});
};

export const getChatTitleFromChatMessage = (message?: ChatItemType, defaultValue = '新对话') => {
// @ts-ignore
const textMsg = message?.value.find((item) => item.type === ChatItemValueTypeEnum.text);
Expand Down
2 changes: 1 addition & 1 deletion packages/plugins/src/fetchUrl/template.json
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@
"x": 1050.9890727421412,
"y": -415.2085119990912
},
"version": "486",
"version": "481",
"inputs": [
{
"key": "system_addInputParam",
Expand Down
12 changes: 6 additions & 6 deletions packages/service/core/chat/controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,24 +13,24 @@ export async function getChatItems({
chatId?: string;
limit?: number;
field: string;
}): Promise<{ history: ChatItemType[] }> {
}): Promise<{ histories: ChatItemType[] }> {
if (!chatId) {
return { history: [] };
return { histories: [] };
}

const history = await MongoChatItem.find({ appId, chatId }, field)
const histories = await MongoChatItem.find({ appId, chatId }, field)
.sort({ _id: -1 })
.limit(limit)
.lean();

history.reverse();
histories.reverse();

history.forEach((item) => {
histories.forEach((item) => {
// @ts-ignore
item.value = adaptStringValue(item.value);
});

return { history };
return { histories };
}
/* 临时适配旧的对话记录 */
export const adaptStringValue = (value: any): ChatItemValueItemType[] => {
Expand Down
45 changes: 0 additions & 45 deletions packages/service/core/dataset/collection/controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,54 +75,9 @@ export async function createOneCollection({
{ session }
);

// create default collection
if (type === DatasetCollectionTypeEnum.folder) {
await createDefaultCollection({
datasetId,
parentId: collection._id,
teamId,
tmbId,
session
});
}

return collection;
}

// create default collection
export function createDefaultCollection({
name = '手动录入',
datasetId,
parentId,
teamId,
tmbId,
session
}: {
name?: '手动录入' | '手动标注';
datasetId: string;
parentId?: string;
teamId: string;
tmbId: string;
session?: ClientSession;
}) {
return MongoDatasetCollection.create(
[
{
name,
teamId,
tmbId,
datasetId,
parentId,
type: DatasetCollectionTypeEnum.virtual,
trainingType: TrainingModeEnum.chunk,
chunkSize: 0,
updateTime: new Date('2099')
}
],
{ session }
);
}

/* delete collection related images/files */
export const delCollectionRelatedSource = async ({
collections,
Expand Down
14 changes: 11 additions & 3 deletions packages/service/core/dataset/collection/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {
} from '@fastgpt/global/core/dataset/constants';
import { hashStr } from '@fastgpt/global/common/string/tools';
import { ClientSession } from '../../../common/mongo';
import { PushDatasetDataResponse } from '@fastgpt/global/core/dataset/api';

/**
* get all collection by top collectionId
Expand Down Expand Up @@ -138,7 +139,7 @@ export const reloadCollectionChunks = async ({
billId?: string;
rawText?: string;
session: ClientSession;
}) => {
}): Promise<PushDatasetDataResponse> => {
const {
title,
rawText: newRawText,
Expand All @@ -149,7 +150,10 @@ export const reloadCollectionChunks = async ({
newRawText: rawText
});

if (isSameRawText) return;
if (isSameRawText)
return {
insertLen: 0
};

// split data
const { chunks } = splitText2Chunks({
Expand All @@ -164,7 +168,7 @@ export const reloadCollectionChunks = async ({
return Promise.reject('Training model error');
})();

await MongoDatasetTraining.insertMany(
const result = await MongoDatasetTraining.insertMany(
chunks.map((item, i) => ({
teamId: col.teamId,
tmbId,
Expand All @@ -191,4 +195,8 @@ export const reloadCollectionChunks = async ({
},
{ session }
);

return {
insertLen: result.length
};
};
15 changes: 10 additions & 5 deletions packages/service/core/workflow/dispatch/utils.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
import { getErrText } from '@fastgpt/global/common/error/utils';
import { replaceSensitiveText } from '@fastgpt/global/common/string/tools';
import { ChatRoleEnum } from '@fastgpt/global/core/chat/constants';
import type { ChatItemType } from '@fastgpt/global/core/chat/type.d';
import {
WorkflowIOValueTypeEnum,
NodeOutputKeyEnum
} from '@fastgpt/global/core/workflow/constants';
import { RuntimeEdgeItemType } from '@fastgpt/global/core/workflow/runtime/type';
import { FlowNodeInputItemType } from '@fastgpt/global/core/workflow/type/io';

export const filterToolNodeIdByEdges = ({
nodeId,
Expand Down Expand Up @@ -45,10 +44,16 @@ export const filterToolNodeIdByEdges = ({

export const getHistories = (history?: ChatItemType[] | number, histories: ChatItemType[] = []) => {
if (!history) return [];
if (typeof history === 'number') return histories.slice(-(history * 2));
if (Array.isArray(history)) return history;

return [];
const systemHistories = histories.filter((item) => item.obj === ChatRoleEnum.System);

const filterHistories = (() => {
if (typeof history === 'number') return histories.slice(-(history * 2));
if (Array.isArray(history)) return history;
return [];
})();

return [...systemHistories, ...filterHistories];
};

/* value type format */
Expand Down
1 change: 0 additions & 1 deletion projects/app/src/components/ChatBox/hooks/useChatBox.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,6 @@ export const useChatBox = () => {

const map: Record<ExportChatType, () => void> = {
md: () => {
console.log(history);
fileDownload({
text: history
.map((item) => {
Expand Down
9 changes: 8 additions & 1 deletion projects/app/src/global/core/dataset/api.d.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
import { PushDatasetDataChunkProps } from '@fastgpt/global/core/dataset/api';
import {
PushDatasetDataChunkProps,
PushDatasetDataResponse
} from '@fastgpt/global/core/dataset/api';
import {
DatasetSearchModeEnum,
DatasetSourceReadTypeEnum,
Expand Down Expand Up @@ -31,6 +34,10 @@ export type RebuildEmbeddingProps = {
};

/* ================= collection ===================== */
export type CreateCollectionResponse = Promise<{
collectionId: string;
results: PushDatasetDataResponse;
}>;

/* ================= data ===================== */
export type InsertOneDatasetDataProps = PushDatasetDataChunkProps & {
Expand Down
8 changes: 4 additions & 4 deletions projects/app/src/pages/api/core/app/update.ts
Original file line number Diff line number Diff line change
Expand Up @@ -154,10 +154,8 @@ async function handler(req: ApiRequestProps<AppUpdateParams, { appId: string }>)

return onUpdate(session);
});
}

// Update default permission
if (isDefaultPermissionChanged) {
} else if (isDefaultPermissionChanged) {
// Update default permission
await mongoSessionRun(async (session) => {
if (isFolder) {
// Sync children default permission
Expand Down Expand Up @@ -193,6 +191,8 @@ async function handler(req: ApiRequestProps<AppUpdateParams, { appId: string }>)

return onUpdate(session, defaultPermission);
});
} else {
return onUpdate();
}
}

Expand Down
4 changes: 2 additions & 2 deletions projects/app/src/pages/api/core/chat/init.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ async function handler(
}

// get app and history
const [{ history }, { nodes }] = await Promise.all([
const [{ histories }, { nodes }] = await Promise.all([
getChatItems({
appId,
chatId,
Expand All @@ -60,7 +60,7 @@ async function handler(
title: chat?.title || '新对话',
userAvatar: undefined,
variables: chat?.variables || {},
history,
history: histories,
app: {
chatConfig: getAppChatConfig({
chatConfig: app.chatConfig,
Expand Down
6 changes: 3 additions & 3 deletions projects/app/src/pages/api/core/chat/outLink/init.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
throw new Error(ChatErrEnum.unAuthChat);
}

const [{ history }, { nodes }] = await Promise.all([
const [{ histories }, { nodes }] = await Promise.all([
getChatItems({
appId: app._id,
chatId,
Expand All @@ -56,7 +56,7 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
]);

// pick share response field
history.forEach((item) => {
histories.forEach((item) => {
if (item.obj === ChatRoleEnum.AI) {
item.responseData = filterPublicNodeResponseData({ flowResponses: item.responseData });
}
Expand All @@ -70,7 +70,7 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
//@ts-ignore
userAvatar: tmb?.userId?.avatar,
variables: chat?.variables || {},
history,
history: histories,
app: {
chatConfig: getAppChatConfig({
chatConfig: app.chatConfig,
Expand Down
6 changes: 3 additions & 3 deletions projects/app/src/pages/api/core/chat/team/init.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
}

// get app and history
const [{ history }, { nodes }] = await Promise.all([
const [{ histories }, { nodes }] = await Promise.all([
getChatItems({
appId,
chatId,
Expand All @@ -58,7 +58,7 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
]);

// pick share response field
history.forEach((item) => {
histories.forEach((item) => {
if (item.obj === ChatRoleEnum.AI) {
item.responseData = filterPublicNodeResponseData({ flowResponses: item.responseData });
}
Expand All @@ -71,7 +71,7 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
title: chat?.title || '新对话',
userAvatar: team?.avatar,
variables: chat?.variables || {},
history,
history: histories,
app: {
chatConfig: getAppChatConfig({
chatConfig: app.chatConfig,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,9 @@ import { getLLMModel, getVectorModel } from '@fastgpt/service/core/ai/model';
import { rawText2Chunks } from '@fastgpt/service/core/dataset/read';
import { WritePermissionVal } from '@fastgpt/global/support/permission/constant';
import { NextAPI } from '@/service/middleware/entry';
import { CreateCollectionResponse } from '@/global/core/dataset/api';

async function handler(req: NextApiRequest) {
async function handler(req: NextApiRequest): CreateCollectionResponse {
const { datasetId, parentId, fileId } = req.body as FileIdCreateDatasetCollectionParams;
const trainingType = TrainingModeEnum.chunk;
const { teamId, tmbId, dataset } = await authDataset({
Expand Down Expand Up @@ -50,7 +51,7 @@ async function handler(req: NextApiRequest) {
insertLen: predictDataLimitLength(trainingType, chunks)
});

await mongoSessionRun(async (session) => {
return mongoSessionRun(async (session) => {
// 4. create collection
const { _id: collectionId } = await createOneCollection({
teamId,
Expand Down Expand Up @@ -80,7 +81,7 @@ async function handler(req: NextApiRequest) {
});

// 6. insert to training queue
await pushDataListToTrainingQueue({
const insertResult = await pushDataListToTrainingQueue({
teamId,
tmbId,
datasetId: dataset._id,
Expand All @@ -97,7 +98,7 @@ async function handler(req: NextApiRequest) {
session
});

return collectionId;
return { collectionId, results: insertResult };
});
}
export default NextAPI(handler);
Loading
Loading