ChatGPT-Next-Web/app/store.ts

291 lines
7.0 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-11 12:54:24 +00:00
import { requestChat, requestChatStream, requestWithPrompt } from "./requests";
2023-03-10 18:25:33 +00:00
import { trimTopic } from "./utils";
2023-03-09 17:01:40 +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;
2023-03-10 18:25:33 +00:00
};
2023-03-09 17:01:40 +00:00
2023-03-11 17:14:07 +00:00
export enum SubmitKey {
Enter = "Enter",
CtrlEnter = "Ctrl + Enter",
ShiftEnter = "Shift + Enter",
AltEnter = "Alt + Enter",
}
2023-03-12 19:06:21 +00:00
export enum Theme {
Auto = "auto",
Dark = "dark",
Light = "light",
}
2023-03-09 17:01:40 +00:00
interface ChatConfig {
2023-03-11 17:14:07 +00:00
maxToken?: number;
historyMessageCount: number; // -1 means all
sendBotMessages: boolean; // send bot's message or not
submitKey: SubmitKey;
avatar: string;
2023-03-12 19:06:21 +00:00
theme: Theme;
2023-03-12 19:21:48 +00:00
tightBorder: boolean;
2023-03-09 17:01:40 +00:00
}
2023-03-12 19:21:48 +00:00
const DEFAULT_CONFIG: ChatConfig = {
historyMessageCount: 5,
sendBotMessages: false as boolean,
submitKey: SubmitKey.CtrlEnter as SubmitKey,
avatar: "1fae0",
theme: Theme.Auto as Theme,
tightBorder: false,
};
2023-03-10 18:25:33 +00:00
interface ChatStat {
tokenCount: number;
wordCount: number;
charCount: number;
}
interface ChatSession {
2023-03-11 17:14:07 +00:00
id: number;
2023-03-10 18:25:33 +00:00
topic: string;
memoryPrompt: string;
messages: Message[];
stat: ChatStat;
lastUpdate: string;
deleted?: boolean;
}
const DEFAULT_TOPIC = "新的聊天";
function createEmptySession(): ChatSession {
const createDate = new Date().toLocaleString();
return {
2023-03-11 17:14:07 +00:00
id: Date.now(),
2023-03-10 18:25:33 +00:00
topic: DEFAULT_TOPIC,
memoryPrompt: "",
messages: [
{
role: "assistant",
content: "有什么可以帮你的吗",
date: createDate,
},
],
stat: {
tokenCount: 0,
wordCount: 0,
charCount: 0,
},
lastUpdate: createDate,
};
2023-03-09 17:01:40 +00:00
}
2023-03-10 18:25:33 +00:00
interface ChatStore {
2023-03-11 17:14:07 +00:00
config: ChatConfig;
2023-03-10 18:25:33 +00:00
sessions: ChatSession[];
currentSessionIndex: number;
removeSession: (index: number) => void;
selectSession: (index: number) => void;
newSession: () => void;
currentSession: () => ChatSession;
onNewMessage: (message: Message) => void;
onUserInput: (content: string) => Promise<void>;
onBotResponse: (message: Message) => 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,
updater: (message?: Message) => void
) => void;
2023-03-11 17:14:07 +00:00
getConfig: () => ChatConfig;
2023-03-12 19:21:48 +00:00
resetConfig: () => void;
2023-03-11 17:14:07 +00:00
updateConfig: (updater: (config: ChatConfig) => void) => void;
2023-03-09 17:01:40 +00:00
}
2023-03-13 16:25:07 +00:00
const LOCAL_KEY = "chat-next-web-store";
2023-03-10 18:25:33 +00:00
export const useChatStore = create<ChatStore>()(
persist(
(set, get) => ({
sessions: [createEmptySession()],
currentSessionIndex: 0,
2023-03-11 17:14:07 +00:00
config: {
2023-03-12 19:21:48 +00:00
...DEFAULT_CONFIG,
},
resetConfig() {
set(() => ({ config: { ...DEFAULT_CONFIG } }));
2023-03-11 17:14:07 +00:00
},
getConfig() {
return get().config;
},
updateConfig(updater) {
const config = get().config;
updater(config);
set(() => ({ config }));
},
2023-03-10 18:25:33 +00:00
selectSession(index: number) {
set({
currentSessionIndex: index,
});
},
removeSession(index: number) {
set((state) => {
let nextIndex = state.currentSessionIndex;
const sessions = state.sessions;
if (sessions.length === 1) {
return {
currentSessionIndex: 0,
sessions: [createEmptySession()],
};
}
sessions.splice(index, 1);
if (nextIndex === index) {
nextIndex -= 1;
}
return {
currentSessionIndex: nextIndex,
sessions,
};
});
},
newSession() {
set((state) => ({
2023-03-11 08:24:17 +00:00
currentSessionIndex: 0,
sessions: [createEmptySession()].concat(state.sessions),
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) {
get().updateCurrentSession((session) => {
session.messages.push(message);
});
get().updateStat(message);
get().summarizeSession();
},
async onUserInput(content) {
const message: Message = {
role: "user",
content,
date: new Date().toLocaleString(),
};
2023-03-11 17:14:07 +00:00
// get last five messges
2023-03-10 18:25:33 +00:00
const messages = get().currentSession().messages.concat(message);
get().onNewMessage(message);
2023-03-11 12:54:24 +00:00
const botMessage: Message = {
content: "",
role: "assistant",
2023-03-10 18:25:33 +00:00
date: new Date().toLocaleString(),
2023-03-11 12:54:24 +00:00
streaming: true,
};
get().updateCurrentSession((session) => {
session.messages.push(botMessage);
});
2023-03-11 17:14:07 +00:00
const fiveMessages = messages.slice(-5);
requestChatStream(fiveMessages, {
2023-03-11 12:54:24 +00:00
onMessage(content, done) {
if (done) {
2023-03-11 17:14:07 +00:00
botMessage.streaming = false;
get().updateStat(botMessage);
2023-03-11 12:54:24 +00:00
get().summarizeSession();
} else {
botMessage.content = content;
set(() => ({}));
}
},
2023-03-11 17:14:07 +00:00
onError(error) {
2023-03-13 16:34:52 +00:00
botMessage.content += "\n\n出错了稍后重试吧";
2023-03-11 17:14:07 +00:00
botMessage.streaming = false;
set(() => ({}));
},
filterBot: !get().config.sendBotMessages,
2023-03-10 18:25:33 +00:00
});
},
2023-03-11 12:54:24 +00:00
updateMessage(
sessionIndex: number,
messageIndex: number,
updater: (message?: Message) => void
) {
const sessions = get().sessions;
const session = sessions.at(sessionIndex);
const messages = session?.messages;
updater(messages?.at(messageIndex));
set(() => ({ sessions }));
},
2023-03-10 18:25:33 +00:00
onBotResponse(message) {
get().onNewMessage(message);
},
summarizeSession() {
const session = get().currentSession();
2023-03-13 16:25:07 +00:00
if (session.topic === DEFAULT_TOPIC) {
// should summarize topic
2023-03-14 17:56:39 +00:00
requestWithPrompt(
session.messages,
"直接返回这句话的简要主题,不要解释"
).then((res) => {
get().updateCurrentSession(
(session) => (session.topic = trimTopic(res))
);
});
2023-03-13 16:25:07 +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-13 16:25:07 +00:00
{
name: LOCAL_KEY,
}
2023-03-10 18:25:33 +00:00
)
);