Skip to content

Commit 5b70413

Browse files
authored
Merge pull request #113 from zhujunsan/messageHistoryInMongy
聊天历史由 MongoDB 中获取
2 parents 6c14af8 + 27103b6 commit 5b70413

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed

service/src/chatgpt/index.ts

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import { getCacheConfig, getOriginConfig } from '../storage/config'
1212
import { sendResponse } from '../utils'
1313
import { isNotEmptyString } from '../utils/is'
1414
import type { ChatContext, ChatGPTUnofficialProxyAPIOptions, ModelConfig } from '../types'
15+
import { getChatByMessageId } from '../storage/mongo'
1516
import type { RequestOptions } from './types'
1617

1718
const { HttpsProxyAgent } = httpsProxyAgent
@@ -45,6 +46,8 @@ export async function initApi() {
4546
apiKey: config.apiKey,
4647
completionParams: { model },
4748
debug: !config.apiDisableDebug,
49+
messageStore: undefined,
50+
getMessageById,
4851
}
4952
// increase max token limit if use gpt-4
5053
if (model.toLowerCase().includes('gpt-4')) {
@@ -261,6 +264,33 @@ async function setupProxy(options: ChatGPTAPIOptions | ChatGPTUnofficialProxyAPI
261264
}
262265
}
263266

267+
async function getMessageById(id: string): Promise<ChatMessage | undefined> {
268+
const isPrompt = id.startsWith('prompt_')
269+
const chatInfo = await getChatByMessageId(isPrompt ? id.substring(7) : id)
270+
271+
if (chatInfo) {
272+
if (isPrompt) { // prompt
273+
return {
274+
id,
275+
conversationId: chatInfo.options.conversationId,
276+
parentMessageId: chatInfo.options.parentMessageId,
277+
role: 'user',
278+
text: chatInfo.prompt,
279+
}
280+
}
281+
else {
282+
return { // completion
283+
id,
284+
conversationId: chatInfo.options.conversationId,
285+
parentMessageId: `prompt_${id}`, // parent message is the prompt
286+
role: 'assistant',
287+
text: chatInfo.response,
288+
}
289+
}
290+
}
291+
else { return undefined }
292+
}
293+
264294
initApi()
265295

266296
export type { ChatContext, ChatMessage }

service/src/storage/mongo.ts

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ const usageCol = client.db('chatgpt').collection('chat_usage')
1515

1616
/**
1717
* 插入聊天信息
18+
* @param uuid
1819
* @param text 内容 prompt or response
1920
* @param roomId
2021
* @param options
@@ -30,6 +31,10 @@ export async function getChat(roomId: number, uuid: number) {
3031
return await chatCol.findOne({ roomId, uuid }) as ChatInfo
3132
}
3233

34+
export async function getChatByMessageId(messageId: string) {
35+
return await chatCol.findOne({ 'options.messageId': messageId }) as ChatInfo
36+
}
37+
3338
export async function updateChat(chatId: string, response: string, messageId: string, usage: UsageResponse, previousResponse?: []) {
3439
const query = { _id: new ObjectId(chatId) }
3540
const update = {

0 commit comments

Comments
 (0)