Skip to content

Commit

Permalink
fix: system prompt concat
Browse files Browse the repository at this point in the history
  • Loading branch information
c121914yu committed Jul 4, 2024
1 parent a3d381e commit 9daa3cf
Show file tree
Hide file tree
Showing 8 changed files with 43 additions and 24 deletions.
3 changes: 2 additions & 1 deletion docSite/content/zh-cn/docs/development/upgrading/486.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,4 +40,5 @@ curl --location --request POST 'https://{{host}}/api/admin/initv486' \
5. 优化 - Read file 默认选中从节点,实现 MongoDB 读写分离,减轻主节点压力
6. 优化 - 知识库导入接口,返回值对齐
7. 修复 - 工作流中团队插件加载异常
8. 修复 - 知识库集合目录导航失效
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
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
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
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
10 changes: 6 additions & 4 deletions projects/app/src/pages/api/v1/chat/completions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import requestIp from 'request-ip';
import { getUsageSourceByAuthType } from '@fastgpt/global/support/wallet/usage/tools';
import { authTeamSpaceToken } from '@/service/support/permission/auth/team';
import {
concatHistories,
filterPublicNodeResponseData,
removeEmptyUserInput
} from '@fastgpt/global/core/chat/utils';
Expand Down Expand Up @@ -119,6 +120,7 @@ async function handler(req: NextApiRequest, res: NextApiResponse) {

let startTime = Date.now();

// Web chat params: [Human, AI]
const chatMessages = GPTMessages2Chats(messages);
if (chatMessages[chatMessages.length - 1].obj !== ChatRoleEnum.Human) {
chatMessages.pop();
Expand Down Expand Up @@ -170,7 +172,7 @@ async function handler(req: NextApiRequest, res: NextApiResponse) {

// 1. get and concat history; 2. get app workflow
const limit = getMaxHistoryLimitFromNodes(app.modules);
const [{ history }, { nodes, edges, chatConfig }] = await Promise.all([
const [{ histories }, { nodes, edges, chatConfig }] = await Promise.all([
getChatItems({
appId: app._id,
chatId,
Expand All @@ -179,7 +181,7 @@ async function handler(req: NextApiRequest, res: NextApiResponse) {
}),
getAppLatestVersion(app._id, app)
]);
const concatHistories = history.concat(chatMessages);
const newHistories = concatHistories(histories, chatMessages);
const responseChatItemId: string | undefined = messages[messages.length - 1].dataId;

/* start flow controller */
Expand All @@ -198,7 +200,7 @@ async function handler(req: NextApiRequest, res: NextApiResponse) {
runtimeEdges: initWorkflowEdgeStatus(edges),
variables,
query: removeEmptyUserInput(question.value),
histories: concatHistories,
histories: newHistories,
stream,
detail,
maxRunTimes: 200
Expand All @@ -217,7 +219,7 @@ async function handler(req: NextApiRequest, res: NextApiResponse) {
modules: setEntryEntries(app.modules),
variables,
inputFiles: files,
histories: concatHistories,
histories: newHistories,
startParams: {
userChatInput: text
},
Expand Down

0 comments on commit 9daa3cf

Please sign in to comment.