ChatGPT-Next-Web/app/store/chat.ts

522 lines
14 KiB
TypeScript
Raw Normal View History

2023-03-10 18:25:33 +00:00
import { create } from "zustand";
import { persist } from "zustand/middleware";
2023-03-09 17:01:40 +00:00
import { type ChatCompletionResponseMessage } from "openai";
2023-03-26 10:59:09 +00:00
import {
ControllerPool,
requestChatStream,
requestWithPrompt,
} from "../requests";
import { trimTopic } from "../utils";
2023-03-09 17:01:40 +00:00
import Locale from "../locales";
2023-04-06 16:14:27 +00:00
import { showToast } from "../components/ui-lib";
import { ModelType } from "./config";
2023-04-24 16:49:27 +00:00
import { createEmptyMask, Mask } from "./mask";
2023-04-26 18:00:22 +00:00
import { StoreKey } from "../constant";
2023-03-20 16:17:45 +00:00
2023-03-10 18:25:33 +00:00
export type Message = ChatCompletionResponseMessage & {
date: string;
2023-03-11 12:54:24 +00:00
streaming?: boolean;
isError?: boolean;
2023-04-05 19:19:33 +00:00
id?: number;
model?: ModelType;
2023-03-10 18:25:33 +00:00
};
2023-03-09 17:01:40 +00:00
2023-04-05 19:19:33 +00:00
export function createMessage(override: Partial<Message>): Message {
return {
id: Date.now(),
date: new Date().toLocaleString(),
role: "user",
content: "",
...override,
};
}
export const ROLES: Message["role"][] = ["system", "user", "assistant"];
2023-03-19 16:09:30 +00:00
export interface ChatStat {
2023-03-10 18:25:33 +00:00
tokenCount: number;
wordCount: number;
charCount: number;
}
2023-03-19 16:09:30 +00:00
export interface ChatSession {
2023-03-11 17:14:07 +00:00
id: number;
2023-04-24 16:49:27 +00:00
2023-03-10 18:25:33 +00:00
topic: string;
2023-04-24 16:49:27 +00:00
2023-03-10 18:25:33 +00:00
memoryPrompt: string;
messages: Message[];
stat: ChatStat;
2023-04-25 18:02:46 +00:00
lastUpdate: number;
2023-03-19 15:13:10 +00:00
lastSummarizeIndex: number;
2023-04-22 17:27:15 +00:00
2023-04-24 16:49:27 +00:00
mask: Mask;
2023-03-10 18:25:33 +00:00
}
2023-04-22 17:27:15 +00:00
export const DEFAULT_TOPIC = Locale.Store.DefaultTopic;
2023-04-05 19:19:33 +00:00
export const BOT_HELLO: Message = createMessage({
2023-04-02 13:56:34 +00:00
role: "assistant",
content: Locale.Store.BotHello,
2023-04-05 19:19:33 +00:00
});
2023-03-10 18:25:33 +00:00
function createEmptySession(): ChatSession {
return {
2023-04-27 17:54:57 +00:00
id: Date.now() + Math.random(),
2023-03-10 18:25:33 +00:00
topic: DEFAULT_TOPIC,
memoryPrompt: "",
2023-04-02 13:56:34 +00:00
messages: [],
2023-03-10 18:25:33 +00:00
stat: {
tokenCount: 0,
wordCount: 0,
charCount: 0,
},
2023-04-25 18:02:46 +00:00
lastUpdate: Date.now(),
2023-03-19 15:13:10 +00:00
lastSummarizeIndex: 0,
2023-04-24 16:49:27 +00:00
mask: createEmptyMask(),
2023-03-10 18:25:33 +00:00
};
2023-03-09 17:01:40 +00:00
}
2023-03-10 18:25:33 +00:00
interface ChatStore {
sessions: ChatSession[];
currentSessionIndex: number;
2023-04-25 18:02:46 +00:00
globalId: number;
2023-04-02 05:42:47 +00:00
clearSessions: () => void;
2023-04-05 17:34:46 +00:00
moveSession: (from: number, to: number) => void;
2023-03-10 18:25:33 +00:00
selectSession: (index: number) => void;
2023-04-25 18:02:46 +00:00
newSession: (mask?: Mask) => void;
2023-05-01 15:21:28 +00:00
deleteSession: (index: number) => void;
2023-03-10 18:25:33 +00:00
currentSession: () => ChatSession;
onNewMessage: (message: Message) => void;
onUserInput: (content: string) => Promise<void>;
summarizeSession: () => void;
updateStat: (message: Message) => void;
updateCurrentSession: (updater: (session: ChatSession) => void) => void;
2023-03-11 12:54:24 +00:00
updateMessage: (
sessionIndex: number,
messageIndex: number,
2023-04-18 03:44:15 +00:00
updater: (message?: Message) => void,
2023-03-11 12:54:24 +00:00
) => void;
resetSession: () => void;
2023-03-19 15:13:10 +00:00
getMessagesWithMemory: () => Message[];
2023-03-21 16:20:32 +00:00
getMemoryPrompt: () => Message;
2023-03-11 17:14:07 +00:00
2023-03-19 15:13:10 +00:00
clearAllData: () => void;
2023-03-09 17:01:40 +00:00
}
2023-03-29 16:02:50 +00:00
function countMessages(msgs: Message[]) {
return msgs.reduce((pre, cur) => pre + cur.content.length, 0);
}
2023-03-10 18:25:33 +00:00
export const useChatStore = create<ChatStore>()(
persist(
(set, get) => ({
sessions: [createEmptySession()],
currentSessionIndex: 0,
2023-04-25 18:02:46 +00:00
globalId: 0,
2023-03-12 19:21:48 +00:00
clearSessions() {
2023-04-02 05:42:47 +00:00
set(() => ({
sessions: [createEmptySession()],
currentSessionIndex: 0,
}));
},
2023-03-10 18:25:33 +00:00
selectSession(index: number) {
set({
currentSessionIndex: index,
});
},
2023-04-05 17:34:46 +00:00
moveSession(from: number, to: number) {
set((state) => {
const { sessions, currentSessionIndex: oldIndex } = state;
// move the session
const newSessions = [...sessions];
const session = newSessions[from];
newSessions.splice(from, 1);
newSessions.splice(to, 0, session);
// modify current session id
let newIndex = oldIndex === from ? to : oldIndex;
if (oldIndex > from && oldIndex <= to) {
newIndex -= 1;
} else if (oldIndex < from && oldIndex >= to) {
newIndex += 1;
}
return {
currentSessionIndex: newIndex,
sessions: newSessions,
};
});
},
2023-04-25 18:02:46 +00:00
newSession(mask) {
const session = createEmptySession();
set(() => ({ globalId: get().globalId + 1 }));
session.id = get().globalId;
if (mask) {
session.mask = { ...mask };
session.topic = mask.name;
}
2023-03-10 18:25:33 +00:00
set((state) => ({
2023-03-11 08:24:17 +00:00
currentSessionIndex: 0,
2023-04-25 18:02:46 +00:00
sessions: [session].concat(state.sessions),
2023-03-10 18:25:33 +00:00
}));
},
2023-05-01 15:21:28 +00:00
deleteSession(index) {
const deletingLastSession = get().sessions.length === 1;
const deletedSession = get().sessions.at(index);
if (!deletedSession) return;
const sessions = get().sessions.slice();
sessions.splice(index, 1);
const currentIndex = get().currentSessionIndex;
2023-05-01 15:21:28 +00:00
let nextIndex = Math.min(
currentIndex - Number(index < currentIndex),
2023-05-01 15:21:28 +00:00
sessions.length - 1,
);
if (deletingLastSession) {
nextIndex = 0;
sessions.push(createEmptySession());
2023-04-06 16:14:27 +00:00
}
2023-05-01 15:21:28 +00:00
// for undo delete action
const restoreState = {
currentSessionIndex: get().currentSessionIndex,
sessions: get().sessions.slice(),
};
set(() => ({
currentSessionIndex: nextIndex,
sessions,
}));
showToast(
Locale.Home.DeleteToast,
{
text: Locale.Home.Revert,
onClick() {
set(() => restoreState);
},
},
5000,
);
2023-04-06 16:14:27 +00:00
},
2023-03-10 18:25:33 +00:00
currentSession() {
let index = get().currentSessionIndex;
const sessions = get().sessions;
if (index < 0 || index >= sessions.length) {
index = Math.min(sessions.length - 1, Math.max(0, index));
set(() => ({ currentSessionIndex: index }));
}
2023-03-11 17:14:07 +00:00
const session = sessions[index];
return session;
2023-03-10 18:25:33 +00:00
},
onNewMessage(message) {
2023-03-21 16:20:32 +00:00
get().updateCurrentSession((session) => {
2023-04-25 18:02:46 +00:00
session.lastUpdate = Date.now();
2023-03-21 16:20:32 +00:00
});
2023-03-10 18:25:33 +00:00
get().updateStat(message);
get().summarizeSession();
},
async onUserInput(content) {
const session = get().currentSession();
const modelConfig = session.mask.modelConfig;
2023-04-05 19:19:33 +00:00
const userMessage: Message = createMessage({
2023-03-10 18:25:33 +00:00
role: "user",
content,
2023-04-05 19:19:33 +00:00
});
2023-03-10 18:25:33 +00:00
2023-04-05 19:19:33 +00:00
const botMessage: Message = createMessage({
2023-03-11 12:54:24 +00:00
role: "assistant",
streaming: true,
id: userMessage.id! + 1,
model: modelConfig.model,
2023-04-05 19:19:33 +00:00
});
2023-03-11 12:54:24 +00:00
const systemInfo = createMessage({
role: "system",
content: `IMPRTANT: You are a virtual assistant powered by the ${
modelConfig.model
} model, now time is ${new Date().toLocaleString()}}`,
id: botMessage.id! + 1,
});
2023-03-21 16:20:32 +00:00
// get recent messages
const systemMessages = [systemInfo];
2023-03-21 16:20:32 +00:00
const recentMessages = get().getMessagesWithMemory();
const sendMessages = systemMessages.concat(
recentMessages.concat(userMessage),
);
2023-03-26 10:59:09 +00:00
const sessionIndex = get().currentSessionIndex;
const messageIndex = get().currentSession().messages.length + 1;
2023-03-19 16:09:30 +00:00
// save user's and bot's message
2023-03-11 12:54:24 +00:00
get().updateCurrentSession((session) => {
2023-03-19 16:09:30 +00:00
session.messages.push(userMessage);
2023-03-11 12:54:24 +00:00
session.messages.push(botMessage);
});
2023-03-26 10:59:09 +00:00
// make request
2023-03-21 16:20:32 +00:00
console.log("[User Input] ", sendMessages);
2023-03-19 16:09:30 +00:00
requestChatStream(sendMessages, {
2023-03-11 12:54:24 +00:00
onMessage(content, done) {
2023-03-26 10:59:09 +00:00
// stream response
2023-03-11 12:54:24 +00:00
if (done) {
2023-03-11 17:14:07 +00:00
botMessage.streaming = false;
botMessage.content = content;
2023-03-21 16:20:32 +00:00
get().onNewMessage(botMessage);
2023-04-05 19:19:33 +00:00
ControllerPool.remove(
sessionIndex,
2023-04-18 03:44:15 +00:00
botMessage.id ?? messageIndex,
2023-04-05 19:19:33 +00:00
);
2023-03-11 12:54:24 +00:00
} else {
botMessage.content = content;
set(() => ({}));
}
},
onError(error, statusCode) {
const isAborted = error.message.includes("aborted");
if (statusCode === 401) {
botMessage.content = Locale.Error.Unauthorized;
} else if (!isAborted) {
botMessage.content += "\n\n" + Locale.Store.Error;
}
2023-03-11 17:14:07 +00:00
botMessage.streaming = false;
userMessage.isError = !isAborted;
botMessage.isError = !isAborted;
2023-03-11 17:14:07 +00:00
set(() => ({}));
2023-04-05 19:19:33 +00:00
ControllerPool.remove(sessionIndex, botMessage.id ?? messageIndex);
2023-03-26 10:59:09 +00:00
},
onController(controller) {
// collect controller for stop/retry
ControllerPool.addController(
sessionIndex,
2023-04-05 19:19:33 +00:00
botMessage.id ?? messageIndex,
2023-04-18 03:44:15 +00:00
controller,
2023-03-26 10:59:09 +00:00
);
2023-03-11 17:14:07 +00:00
},
modelConfig: { ...modelConfig },
2023-03-10 18:25:33 +00:00
});
},
2023-03-19 16:29:09 +00:00
getMemoryPrompt() {
2023-03-21 16:20:32 +00:00
const session = get().currentSession();
2023-03-19 16:29:09 +00:00
return {
2023-03-21 16:20:32 +00:00
role: "system",
content:
session.memoryPrompt.length > 0
? Locale.Store.Prompt.History(session.memoryPrompt)
: "",
2023-03-21 16:20:32 +00:00
date: "",
} as Message;
2023-03-19 16:29:09 +00:00
},
2023-03-19 15:13:10 +00:00
getMessagesWithMemory() {
2023-03-21 16:20:32 +00:00
const session = get().currentSession();
const modelConfig = session.mask.modelConfig;
const messages = session.messages.filter((msg) => !msg.isError);
const n = messages.length;
2023-03-19 15:13:10 +00:00
2023-04-24 16:49:27 +00:00
const context = session.mask.context.slice();
2023-03-19 15:13:10 +00:00
// long term memory
if (
modelConfig.sendMemory &&
session.memoryPrompt &&
session.memoryPrompt.length > 0
) {
const memoryPrompt = get().getMemoryPrompt();
context.push(memoryPrompt);
2023-03-19 15:13:10 +00:00
}
// get short term and unmemoried long term memory
const shortTermMemoryMessageIndex = Math.max(
0,
n - modelConfig.historyMessageCount,
);
2023-04-18 03:44:15 +00:00
const longTermMemoryMessageIndex = session.lastSummarizeIndex;
const oldestIndex = Math.max(
shortTermMemoryMessageIndex,
2023-04-18 03:44:15 +00:00
longTermMemoryMessageIndex,
);
const threshold = modelConfig.compressMessageLengthThreshold;
// get recent messages as many as possible
const reversedRecentMessages = [];
for (
let i = n - 1, count = 0;
i >= oldestIndex && count < threshold;
i -= 1
) {
const msg = messages[i];
if (!msg || msg.isError) continue;
count += msg.content.length;
reversedRecentMessages.push(msg);
}
// concat
const recentMessages = context.concat(reversedRecentMessages.reverse());
2023-03-21 16:20:32 +00:00
return recentMessages;
2023-03-19 15:13:10 +00:00
},
2023-03-11 12:54:24 +00:00
updateMessage(
sessionIndex: number,
messageIndex: number,
2023-04-18 03:44:15 +00:00
updater: (message?: Message) => void,
2023-03-11 12:54:24 +00:00
) {
const sessions = get().sessions;
const session = sessions.at(sessionIndex);
const messages = session?.messages;
updater(messages?.at(messageIndex));
set(() => ({ sessions }));
},
resetSession() {
get().updateCurrentSession((session) => {
session.messages = [];
session.memoryPrompt = "";
});
},
2023-03-10 18:25:33 +00:00
summarizeSession() {
const session = get().currentSession();
2023-03-29 16:02:50 +00:00
// should summarize topic after chating more than 50 words
const SUMMARIZE_MIN_LEN = 50;
if (
session.topic === DEFAULT_TOPIC &&
countMessages(session.messages) >= SUMMARIZE_MIN_LEN
) {
requestWithPrompt(session.messages, Locale.Store.Prompt.Topic, {
model: "gpt-3.5-turbo",
}).then((res) => {
get().updateCurrentSession(
(session) =>
(session.topic = res ? trimTopic(res) : DEFAULT_TOPIC),
);
});
2023-03-13 16:25:07 +00:00
}
2023-03-19 15:13:10 +00:00
const modelConfig = session.mask.modelConfig;
2023-03-21 16:20:32 +00:00
let toBeSummarizedMsgs = session.messages.slice(
2023-04-18 03:44:15 +00:00
session.lastSummarizeIndex,
2023-03-21 16:20:32 +00:00
);
2023-03-29 16:02:50 +00:00
const historyMsgLength = countMessages(toBeSummarizedMsgs);
2023-03-19 16:29:09 +00:00
if (historyMsgLength > modelConfig?.max_tokens ?? 4000) {
const n = toBeSummarizedMsgs.length;
2023-03-21 16:20:32 +00:00
toBeSummarizedMsgs = toBeSummarizedMsgs.slice(
Math.max(0, n - modelConfig.historyMessageCount),
2023-03-21 16:20:32 +00:00
);
2023-03-19 16:29:09 +00:00
}
// add memory prompt
2023-03-21 16:20:32 +00:00
toBeSummarizedMsgs.unshift(get().getMemoryPrompt());
2023-03-19 16:29:09 +00:00
2023-03-21 16:20:32 +00:00
const lastSummarizeIndex = session.messages.length;
2023-03-19 16:09:30 +00:00
2023-03-21 16:20:32 +00:00
console.log(
"[Chat History] ",
toBeSummarizedMsgs,
historyMsgLength,
modelConfig.compressMessageLengthThreshold,
2023-03-21 16:20:32 +00:00
);
2023-03-19 16:09:30 +00:00
if (
historyMsgLength > modelConfig.compressMessageLengthThreshold &&
2023-04-24 16:49:27 +00:00
session.mask.modelConfig.sendMemory
) {
2023-03-21 16:20:32 +00:00
requestChatStream(
toBeSummarizedMsgs.concat({
role: "system",
content: Locale.Store.Prompt.Summarize,
date: "",
}),
{
overrideModel: "gpt-3.5-turbo",
2023-03-21 16:20:32 +00:00
onMessage(message, done) {
session.memoryPrompt = message;
if (done) {
console.log("[Memory] ", session.memoryPrompt);
session.lastSummarizeIndex = lastSummarizeIndex;
}
},
onError(error) {
console.error("[Summarize] ", error);
},
2023-04-18 03:44:15 +00:00
},
2023-03-21 16:20:32 +00:00
);
2023-03-19 15:13:10 +00:00
}
2023-03-10 18:25:33 +00:00
},
updateStat(message) {
get().updateCurrentSession((session) => {
session.stat.charCount += message.content.length;
// TODO: should update chat count and word count
});
},
updateCurrentSession(updater) {
const sessions = get().sessions;
const index = get().currentSessionIndex;
updater(sessions[index]);
set(() => ({ sessions }));
},
2023-03-19 15:13:10 +00:00
clearAllData() {
localStorage.clear();
location.reload();
2023-03-19 15:13:10 +00:00
},
2023-03-10 18:25:33 +00:00
}),
2023-03-13 16:25:07 +00:00
{
2023-04-26 18:00:22 +00:00
name: StoreKey.Chat,
2023-04-22 17:37:47 +00:00
version: 2,
migrate(persistedState, version) {
2023-04-26 18:00:22 +00:00
const state = persistedState as any;
const newState = JSON.parse(JSON.stringify(state)) as ChatStore;
2023-04-22 17:37:47 +00:00
if (version < 2) {
2023-04-26 18:00:22 +00:00
newState.globalId = 0;
newState.sessions = [];
const oldSessions = state.sessions;
for (const oldSession of oldSessions) {
const newSession = createEmptySession();
newSession.topic = oldSession.topic;
newSession.messages = [...oldSession.messages];
newSession.mask.modelConfig.sendMemory = true;
newSession.mask.modelConfig.historyMessageCount = 4;
newSession.mask.modelConfig.compressMessageLengthThreshold = 1000;
newState.sessions.push(newSession);
}
}
2023-04-26 18:00:22 +00:00
return newState;
},
2023-04-18 03:44:15 +00:00
},
),
2023-03-10 18:25:33 +00:00
);