chat.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521
  1. import { create } from "zustand";
  2. import { persist } from "zustand/middleware";
  3. import { type ChatCompletionResponseMessage } from "openai";
  4. import {
  5. ControllerPool,
  6. requestChatStream,
  7. requestWithPrompt,
  8. } from "../requests";
  9. import { trimTopic } from "../utils";
  10. import Locale from "../locales";
  11. import { showToast } from "../components/ui-lib";
  12. import { ModelType } from "./config";
  13. import { createEmptyMask, Mask } from "./mask";
  14. import { StoreKey } from "../constant";
  15. export type Message = ChatCompletionResponseMessage & {
  16. date: string;
  17. streaming?: boolean;
  18. isError?: boolean;
  19. id?: number;
  20. model?: ModelType;
  21. };
  22. export function createMessage(override: Partial<Message>): Message {
  23. return {
  24. id: Date.now(),
  25. date: new Date().toLocaleString(),
  26. role: "user",
  27. content: "",
  28. ...override,
  29. };
  30. }
  31. export const ROLES: Message["role"][] = ["system", "user", "assistant"];
  32. export interface ChatStat {
  33. tokenCount: number;
  34. wordCount: number;
  35. charCount: number;
  36. }
  37. export interface ChatSession {
  38. id: number;
  39. topic: string;
  40. memoryPrompt: string;
  41. messages: Message[];
  42. stat: ChatStat;
  43. lastUpdate: number;
  44. lastSummarizeIndex: number;
  45. mask: Mask;
  46. }
  47. export const DEFAULT_TOPIC = Locale.Store.DefaultTopic;
  48. export const BOT_HELLO: Message = createMessage({
  49. role: "assistant",
  50. content: Locale.Store.BotHello,
  51. });
  52. function createEmptySession(): ChatSession {
  53. return {
  54. id: Date.now() + Math.random(),
  55. topic: DEFAULT_TOPIC,
  56. memoryPrompt: "",
  57. messages: [],
  58. stat: {
  59. tokenCount: 0,
  60. wordCount: 0,
  61. charCount: 0,
  62. },
  63. lastUpdate: Date.now(),
  64. lastSummarizeIndex: 0,
  65. mask: createEmptyMask(),
  66. };
  67. }
  68. interface ChatStore {
  69. sessions: ChatSession[];
  70. currentSessionIndex: number;
  71. globalId: number;
  72. clearSessions: () => void;
  73. moveSession: (from: number, to: number) => void;
  74. selectSession: (index: number) => void;
  75. newSession: (mask?: Mask) => void;
  76. deleteSession: (index: number) => void;
  77. currentSession: () => ChatSession;
  78. onNewMessage: (message: Message) => void;
  79. onUserInput: (content: string) => Promise<void>;
  80. summarizeSession: () => void;
  81. updateStat: (message: Message) => void;
  82. updateCurrentSession: (updater: (session: ChatSession) => void) => void;
  83. updateMessage: (
  84. sessionIndex: number,
  85. messageIndex: number,
  86. updater: (message?: Message) => void,
  87. ) => void;
  88. resetSession: () => void;
  89. getMessagesWithMemory: () => Message[];
  90. getMemoryPrompt: () => Message;
  91. clearAllData: () => void;
  92. }
  93. function countMessages(msgs: Message[]) {
  94. return msgs.reduce((pre, cur) => pre + cur.content.length, 0);
  95. }
  96. export const useChatStore = create<ChatStore>()(
  97. persist(
  98. (set, get) => ({
  99. sessions: [createEmptySession()],
  100. currentSessionIndex: 0,
  101. globalId: 0,
  102. clearSessions() {
  103. set(() => ({
  104. sessions: [createEmptySession()],
  105. currentSessionIndex: 0,
  106. }));
  107. },
  108. selectSession(index: number) {
  109. set({
  110. currentSessionIndex: index,
  111. });
  112. },
  113. moveSession(from: number, to: number) {
  114. set((state) => {
  115. const { sessions, currentSessionIndex: oldIndex } = state;
  116. // move the session
  117. const newSessions = [...sessions];
  118. const session = newSessions[from];
  119. newSessions.splice(from, 1);
  120. newSessions.splice(to, 0, session);
  121. // modify current session id
  122. let newIndex = oldIndex === from ? to : oldIndex;
  123. if (oldIndex > from && oldIndex <= to) {
  124. newIndex -= 1;
  125. } else if (oldIndex < from && oldIndex >= to) {
  126. newIndex += 1;
  127. }
  128. return {
  129. currentSessionIndex: newIndex,
  130. sessions: newSessions,
  131. };
  132. });
  133. },
  134. newSession(mask) {
  135. const session = createEmptySession();
  136. set(() => ({ globalId: get().globalId + 1 }));
  137. session.id = get().globalId;
  138. if (mask) {
  139. session.mask = { ...mask };
  140. session.topic = mask.name;
  141. }
  142. set((state) => ({
  143. currentSessionIndex: 0,
  144. sessions: [session].concat(state.sessions),
  145. }));
  146. },
  147. deleteSession(index) {
  148. const deletingLastSession = get().sessions.length === 1;
  149. const deletedSession = get().sessions.at(index);
  150. if (!deletedSession) return;
  151. const sessions = get().sessions.slice();
  152. sessions.splice(index, 1);
  153. const currentIndex = get().currentSessionIndex;
  154. let nextIndex = Math.min(
  155. currentIndex - Number(index < currentIndex),
  156. sessions.length - 1,
  157. );
  158. if (deletingLastSession) {
  159. nextIndex = 0;
  160. sessions.push(createEmptySession());
  161. }
  162. // for undo delete action
  163. const restoreState = {
  164. currentSessionIndex: get().currentSessionIndex,
  165. sessions: get().sessions.slice(),
  166. };
  167. set(() => ({
  168. currentSessionIndex: nextIndex,
  169. sessions,
  170. }));
  171. showToast(
  172. Locale.Home.DeleteToast,
  173. {
  174. text: Locale.Home.Revert,
  175. onClick() {
  176. set(() => restoreState);
  177. },
  178. },
  179. 5000,
  180. );
  181. },
  182. currentSession() {
  183. let index = get().currentSessionIndex;
  184. const sessions = get().sessions;
  185. if (index < 0 || index >= sessions.length) {
  186. index = Math.min(sessions.length - 1, Math.max(0, index));
  187. set(() => ({ currentSessionIndex: index }));
  188. }
  189. const session = sessions[index];
  190. return session;
  191. },
  192. onNewMessage(message) {
  193. get().updateCurrentSession((session) => {
  194. session.lastUpdate = Date.now();
  195. });
  196. get().updateStat(message);
  197. get().summarizeSession();
  198. },
  199. async onUserInput(content) {
  200. const session = get().currentSession();
  201. const modelConfig = session.mask.modelConfig;
  202. const userMessage: Message = createMessage({
  203. role: "user",
  204. content,
  205. });
  206. const botMessage: Message = createMessage({
  207. role: "assistant",
  208. streaming: true,
  209. id: userMessage.id! + 1,
  210. model: modelConfig.model,
  211. });
  212. const systemInfo = createMessage({
  213. role: "system",
  214. content: `IMPRTANT: You are a virtual assistant powered by the ${
  215. modelConfig.model
  216. } model, now time is ${new Date().toLocaleString()}}`,
  217. id: botMessage.id! + 1,
  218. });
  219. // get recent messages
  220. const systemMessages = [systemInfo];
  221. const recentMessages = get().getMessagesWithMemory();
  222. const sendMessages = systemMessages.concat(
  223. recentMessages.concat(userMessage),
  224. );
  225. const sessionIndex = get().currentSessionIndex;
  226. const messageIndex = get().currentSession().messages.length + 1;
  227. // save user's and bot's message
  228. get().updateCurrentSession((session) => {
  229. session.messages.push(userMessage);
  230. session.messages.push(botMessage);
  231. });
  232. // make request
  233. console.log("[User Input] ", sendMessages);
  234. requestChatStream(sendMessages, {
  235. onMessage(content, done) {
  236. // stream response
  237. if (done) {
  238. botMessage.streaming = false;
  239. botMessage.content = content;
  240. get().onNewMessage(botMessage);
  241. ControllerPool.remove(
  242. sessionIndex,
  243. botMessage.id ?? messageIndex,
  244. );
  245. } else {
  246. botMessage.content = content;
  247. set(() => ({}));
  248. }
  249. },
  250. onError(error, statusCode) {
  251. const isAborted = error.message.includes("aborted");
  252. if (statusCode === 401) {
  253. botMessage.content = Locale.Error.Unauthorized;
  254. } else if (!isAborted) {
  255. botMessage.content += "\n\n" + Locale.Store.Error;
  256. }
  257. botMessage.streaming = false;
  258. userMessage.isError = !isAborted;
  259. botMessage.isError = !isAborted;
  260. set(() => ({}));
  261. ControllerPool.remove(sessionIndex, botMessage.id ?? messageIndex);
  262. },
  263. onController(controller) {
  264. // collect controller for stop/retry
  265. ControllerPool.addController(
  266. sessionIndex,
  267. botMessage.id ?? messageIndex,
  268. controller,
  269. );
  270. },
  271. modelConfig: { ...modelConfig },
  272. });
  273. },
  274. getMemoryPrompt() {
  275. const session = get().currentSession();
  276. return {
  277. role: "system",
  278. content:
  279. session.memoryPrompt.length > 0
  280. ? Locale.Store.Prompt.History(session.memoryPrompt)
  281. : "",
  282. date: "",
  283. } as Message;
  284. },
  285. getMessagesWithMemory() {
  286. const session = get().currentSession();
  287. const modelConfig = session.mask.modelConfig;
  288. const messages = session.messages.filter((msg) => !msg.isError);
  289. const n = messages.length;
  290. const context = session.mask.context.slice();
  291. // long term memory
  292. if (
  293. modelConfig.sendMemory &&
  294. session.memoryPrompt &&
  295. session.memoryPrompt.length > 0
  296. ) {
  297. const memoryPrompt = get().getMemoryPrompt();
  298. context.push(memoryPrompt);
  299. }
  300. // get short term and unmemoried long term memory
  301. const shortTermMemoryMessageIndex = Math.max(
  302. 0,
  303. n - modelConfig.historyMessageCount,
  304. );
  305. const longTermMemoryMessageIndex = session.lastSummarizeIndex;
  306. const oldestIndex = Math.max(
  307. shortTermMemoryMessageIndex,
  308. longTermMemoryMessageIndex,
  309. );
  310. const threshold = modelConfig.compressMessageLengthThreshold;
  311. // get recent messages as many as possible
  312. const reversedRecentMessages = [];
  313. for (
  314. let i = n - 1, count = 0;
  315. i >= oldestIndex && count < threshold;
  316. i -= 1
  317. ) {
  318. const msg = messages[i];
  319. if (!msg || msg.isError) continue;
  320. count += msg.content.length;
  321. reversedRecentMessages.push(msg);
  322. }
  323. // concat
  324. const recentMessages = context.concat(reversedRecentMessages.reverse());
  325. return recentMessages;
  326. },
  327. updateMessage(
  328. sessionIndex: number,
  329. messageIndex: number,
  330. updater: (message?: Message) => void,
  331. ) {
  332. const sessions = get().sessions;
  333. const session = sessions.at(sessionIndex);
  334. const messages = session?.messages;
  335. updater(messages?.at(messageIndex));
  336. set(() => ({ sessions }));
  337. },
  338. resetSession() {
  339. get().updateCurrentSession((session) => {
  340. session.messages = [];
  341. session.memoryPrompt = "";
  342. });
  343. },
  344. summarizeSession() {
  345. const session = get().currentSession();
  346. // should summarize topic after chating more than 50 words
  347. const SUMMARIZE_MIN_LEN = 50;
  348. if (
  349. session.topic === DEFAULT_TOPIC &&
  350. countMessages(session.messages) >= SUMMARIZE_MIN_LEN
  351. ) {
  352. requestWithPrompt(session.messages, Locale.Store.Prompt.Topic, {
  353. model: "gpt-3.5-turbo",
  354. }).then((res) => {
  355. get().updateCurrentSession(
  356. (session) =>
  357. (session.topic = res ? trimTopic(res) : DEFAULT_TOPIC),
  358. );
  359. });
  360. }
  361. const modelConfig = session.mask.modelConfig;
  362. let toBeSummarizedMsgs = session.messages.slice(
  363. session.lastSummarizeIndex,
  364. );
  365. const historyMsgLength = countMessages(toBeSummarizedMsgs);
  366. if (historyMsgLength > modelConfig?.max_tokens ?? 4000) {
  367. const n = toBeSummarizedMsgs.length;
  368. toBeSummarizedMsgs = toBeSummarizedMsgs.slice(
  369. Math.max(0, n - modelConfig.historyMessageCount),
  370. );
  371. }
  372. // add memory prompt
  373. toBeSummarizedMsgs.unshift(get().getMemoryPrompt());
  374. const lastSummarizeIndex = session.messages.length;
  375. console.log(
  376. "[Chat History] ",
  377. toBeSummarizedMsgs,
  378. historyMsgLength,
  379. modelConfig.compressMessageLengthThreshold,
  380. );
  381. if (
  382. historyMsgLength > modelConfig.compressMessageLengthThreshold &&
  383. session.mask.modelConfig.sendMemory
  384. ) {
  385. requestChatStream(
  386. toBeSummarizedMsgs.concat({
  387. role: "system",
  388. content: Locale.Store.Prompt.Summarize,
  389. date: "",
  390. }),
  391. {
  392. overrideModel: "gpt-3.5-turbo",
  393. onMessage(message, done) {
  394. session.memoryPrompt = message;
  395. if (done) {
  396. console.log("[Memory] ", session.memoryPrompt);
  397. session.lastSummarizeIndex = lastSummarizeIndex;
  398. }
  399. },
  400. onError(error) {
  401. console.error("[Summarize] ", error);
  402. },
  403. },
  404. );
  405. }
  406. },
  407. updateStat(message) {
  408. get().updateCurrentSession((session) => {
  409. session.stat.charCount += message.content.length;
  410. // TODO: should update chat count and word count
  411. });
  412. },
  413. updateCurrentSession(updater) {
  414. const sessions = get().sessions;
  415. const index = get().currentSessionIndex;
  416. updater(sessions[index]);
  417. set(() => ({ sessions }));
  418. },
  419. clearAllData() {
  420. localStorage.clear();
  421. location.reload();
  422. },
  423. }),
  424. {
  425. name: StoreKey.Chat,
  426. version: 2,
  427. migrate(persistedState, version) {
  428. const state = persistedState as any;
  429. const newState = JSON.parse(JSON.stringify(state)) as ChatStore;
  430. if (version < 2) {
  431. newState.globalId = 0;
  432. newState.sessions = [];
  433. const oldSessions = state.sessions;
  434. for (const oldSession of oldSessions) {
  435. const newSession = createEmptySession();
  436. newSession.topic = oldSession.topic;
  437. newSession.messages = [...oldSession.messages];
  438. newSession.mask.modelConfig.sendMemory = true;
  439. newSession.mask.modelConfig.historyMessageCount = 4;
  440. newSession.mask.modelConfig.compressMessageLengthThreshold = 1000;
  441. newState.sessions.push(newSession);
  442. }
  443. }
  444. return newState;
  445. },
  446. },
  447. ),
  448. );