chat.ts 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791
  1. import { getMessageTextContent, trimTopic } from "../utils";
  2. import { indexedDBStorage } from "@/app/utils/indexedDB-storage";
  3. import { nanoid } from "nanoid";
  4. import type {
  5. ClientApi,
  6. MultimodalContent,
  7. RequestMessage,
  8. } from "../client/api";
  9. import { getClientApi } from "../client/api";
  10. import { ChatControllerPool } from "../client/controller";
  11. import { showToast } from "../components/ui-lib";
  12. import {
  13. DEFAULT_INPUT_TEMPLATE,
  14. DEFAULT_MODELS,
  15. DEFAULT_SYSTEM_TEMPLATE,
  16. KnowledgeCutOffDate,
  17. StoreKey,
  18. } from "../constant";
  19. import Locale, { getLang } from "../locales";
  20. import { isDalle3, safeLocalStorage } from "../utils";
  21. import { prettyObject } from "../utils/format";
  22. import { createPersistStore } from "../utils/store";
  23. import { estimateTokenLength } from "../utils/token";
  24. import { ModelConfig, ModelType, useAppConfig } from "./config";
  25. import { createEmptyMask, Mask } from "./mask";
  26. const localStorage = safeLocalStorage();
  27. export type ChatMessageTool = {
  28. id: string;
  29. index?: number;
  30. type?: string;
  31. function?: {
  32. name: string;
  33. arguments?: string;
  34. };
  35. content?: string;
  36. isError?: boolean;
  37. errorMsg?: string;
  38. };
  39. export type ChatMessage = RequestMessage & {
  40. date: string;
  41. streaming?: boolean;
  42. isError?: boolean;
  43. id: string;
  44. model?: ModelType;
  45. tools?: ChatMessageTool[];
  46. };
  47. export function createMessage(override: Partial<ChatMessage>): ChatMessage {
  48. return {
  49. id: nanoid(),
  50. date: new Date().toLocaleString(),
  51. role: "user",
  52. content: "",
  53. ...override,
  54. };
  55. }
  56. export interface ChatStat {
  57. tokenCount: number;
  58. wordCount: number;
  59. charCount: number;
  60. }
  61. export interface ChatSession {
  62. id: string;
  63. topic: string;
  64. memoryPrompt: string;
  65. messages: ChatMessage[];
  66. stat: ChatStat;
  67. lastUpdate: number;
  68. lastSummarizeIndex: number;
  69. clearContextIndex?: number;
  70. mask: Mask;
  71. }
  72. export const DEFAULT_TOPIC = Locale.Store.DefaultTopic;
  73. export const BOT_HELLO: ChatMessage = createMessage({
  74. role: "assistant",
  75. content: Locale.Store.BotHello,
  76. });
  77. function createEmptySession(): ChatSession {
  78. return {
  79. id: nanoid(),
  80. topic: DEFAULT_TOPIC,
  81. memoryPrompt: "",
  82. messages: [],
  83. stat: {
  84. tokenCount: 0,
  85. wordCount: 0,
  86. charCount: 0,
  87. },
  88. lastUpdate: Date.now(),
  89. lastSummarizeIndex: 0,
  90. mask: createEmptyMask(),
  91. };
  92. }
  93. function countMessages(msgs: ChatMessage[]) {
  94. return msgs.reduce(
  95. (pre, cur) => pre + estimateTokenLength(getMessageTextContent(cur)),
  96. 0,
  97. );
  98. }
  99. function fillTemplateWith(input: string, modelConfig: ModelConfig) {
  100. const cutoff =
  101. KnowledgeCutOffDate[modelConfig.model] ?? KnowledgeCutOffDate.default;
  102. // Find the model in the DEFAULT_MODELS array that matches the modelConfig.model
  103. const modelInfo = DEFAULT_MODELS.find((m) => m.name === modelConfig.model);
  104. var serviceProvider = "OpenAI";
  105. if (modelInfo) {
  106. // TODO: auto detect the providerName from the modelConfig.model
  107. // Directly use the providerName from the modelInfo
  108. serviceProvider = modelInfo.provider.providerName;
  109. }
  110. const vars = {
  111. ServiceProvider: serviceProvider,
  112. cutoff,
  113. model: modelConfig.model,
  114. time: new Date().toString(),
  115. lang: getLang(),
  116. input: input,
  117. };
  118. let output = modelConfig.template ?? DEFAULT_INPUT_TEMPLATE;
  119. // remove duplicate
  120. if (input.startsWith(output)) {
  121. output = "";
  122. }
  123. // must contains {{input}}
  124. const inputVar = "{{input}}";
  125. if (!output.includes(inputVar)) {
  126. output += "\n" + inputVar;
  127. }
  128. Object.entries(vars).forEach(([name, value]) => {
  129. const regex = new RegExp(`{{${name}}}`, "g");
  130. output = output.replace(regex, value.toString()); // Ensure value is a string
  131. });
  132. return output;
  133. }
  134. const DEFAULT_CHAT_STATE = {
  135. sessions: [createEmptySession()],
  136. currentSessionIndex: 0,
  137. lastInput: "",
  138. };
  139. export const useChatStore = createPersistStore(
  140. DEFAULT_CHAT_STATE,
  141. (set, _get) => {
  142. function get() {
  143. return {
  144. ..._get(),
  145. ...methods,
  146. };
  147. }
  148. const methods = {
  149. forkSession() {
  150. // 获取当前会话
  151. const currentSession = get().currentSession();
  152. if (!currentSession) return;
  153. const newSession = createEmptySession();
  154. newSession.topic = currentSession.topic;
  155. newSession.messages = [...currentSession.messages];
  156. newSession.mask = {
  157. ...currentSession.mask,
  158. modelConfig: {
  159. ...currentSession.mask.modelConfig,
  160. },
  161. };
  162. set((state) => ({
  163. currentSessionIndex: 0,
  164. sessions: [newSession, ...state.sessions],
  165. }));
  166. },
  167. clearSessions() {
  168. set(() => ({
  169. sessions: [createEmptySession()],
  170. currentSessionIndex: 0,
  171. }));
  172. },
  173. selectSession(index: number) {
  174. set({
  175. currentSessionIndex: index,
  176. });
  177. },
  178. moveSession(from: number, to: number) {
  179. set((state) => {
  180. const { sessions, currentSessionIndex: oldIndex } = state;
  181. // move the session
  182. const newSessions = [...sessions];
  183. const session = newSessions[from];
  184. newSessions.splice(from, 1);
  185. newSessions.splice(to, 0, session);
  186. // modify current session id
  187. let newIndex = oldIndex === from ? to : oldIndex;
  188. if (oldIndex > from && oldIndex <= to) {
  189. newIndex -= 1;
  190. } else if (oldIndex < from && oldIndex >= to) {
  191. newIndex += 1;
  192. }
  193. return {
  194. currentSessionIndex: newIndex,
  195. sessions: newSessions,
  196. };
  197. });
  198. },
  199. newSession(mask?: Mask) {
  200. const session = createEmptySession();
  201. if (mask) {
  202. const config = useAppConfig.getState();
  203. const globalModelConfig = config.modelConfig;
  204. session.mask = {
  205. ...mask,
  206. modelConfig: {
  207. ...globalModelConfig,
  208. ...mask.modelConfig,
  209. },
  210. };
  211. session.topic = mask.name;
  212. }
  213. set((state) => ({
  214. currentSessionIndex: 0,
  215. sessions: [session].concat(state.sessions),
  216. }));
  217. },
  218. nextSession(delta: number) {
  219. const n = get().sessions.length;
  220. const limit = (x: number) => (x + n) % n;
  221. const i = get().currentSessionIndex;
  222. get().selectSession(limit(i + delta));
  223. },
  224. deleteSession(index: number) {
  225. const deletingLastSession = get().sessions.length === 1;
  226. const deletedSession = get().sessions.at(index);
  227. if (!deletedSession) return;
  228. const sessions = get().sessions.slice();
  229. sessions.splice(index, 1);
  230. const currentIndex = get().currentSessionIndex;
  231. let nextIndex = Math.min(
  232. currentIndex - Number(index < currentIndex),
  233. sessions.length - 1,
  234. );
  235. if (deletingLastSession) {
  236. nextIndex = 0;
  237. sessions.push(createEmptySession());
  238. }
  239. // for undo delete action
  240. const restoreState = {
  241. currentSessionIndex: get().currentSessionIndex,
  242. sessions: get().sessions.slice(),
  243. };
  244. set(() => ({
  245. currentSessionIndex: nextIndex,
  246. sessions,
  247. }));
  248. showToast(
  249. Locale.Home.DeleteToast,
  250. {
  251. text: Locale.Home.Revert,
  252. onClick() {
  253. set(() => restoreState);
  254. },
  255. },
  256. 5000,
  257. );
  258. },
  259. currentSession() {
  260. let index = get().currentSessionIndex;
  261. const sessions = get().sessions;
  262. if (index < 0 || index >= sessions.length) {
  263. index = Math.min(sessions.length - 1, Math.max(0, index));
  264. set(() => ({ currentSessionIndex: index }));
  265. }
  266. const session = sessions[index];
  267. return session;
  268. },
  269. onNewMessage(message: ChatMessage) {
  270. get().updateCurrentSession((session) => {
  271. session.messages = session.messages.concat();
  272. session.lastUpdate = Date.now();
  273. });
  274. get().updateStat(message);
  275. get().summarizeSession();
  276. },
  277. async onUserInput(content: string, attachImages?: string[]) {
  278. const session = get().currentSession();
  279. const modelConfig = session.mask.modelConfig;
  280. const userContent = fillTemplateWith(content, modelConfig);
  281. console.log("[User Input] after template: ", userContent);
  282. let mContent: string | MultimodalContent[] = userContent;
  283. if (attachImages && attachImages.length > 0) {
  284. mContent = [
  285. {
  286. type: "text",
  287. text: userContent,
  288. },
  289. ];
  290. mContent = mContent.concat(
  291. attachImages.map((url) => {
  292. return {
  293. type: "image_url",
  294. image_url: {
  295. url: url,
  296. },
  297. };
  298. }),
  299. );
  300. }
  301. let userMessage: ChatMessage = createMessage({
  302. role: "user",
  303. content: mContent,
  304. });
  305. const botMessage: ChatMessage = createMessage({
  306. role: "assistant",
  307. streaming: true,
  308. model: modelConfig.model,
  309. });
  310. // get recent messages
  311. const recentMessages = get().getMessagesWithMemory();
  312. const sendMessages = recentMessages.concat(userMessage);
  313. const messageIndex = get().currentSession().messages.length + 1;
  314. // save user's and bot's message
  315. get().updateCurrentSession((session) => {
  316. const savedUserMessage = {
  317. ...userMessage,
  318. content: mContent,
  319. };
  320. session.messages = session.messages.concat([
  321. savedUserMessage,
  322. botMessage,
  323. ]);
  324. });
  325. const api: ClientApi = getClientApi(modelConfig.providerName);
  326. // make request
  327. api.llm.chat({
  328. messages: sendMessages,
  329. config: { ...modelConfig, stream: true },
  330. onUpdate(message) {
  331. botMessage.streaming = true;
  332. if (message) {
  333. botMessage.content = message;
  334. }
  335. get().updateCurrentSession((session) => {
  336. session.messages = session.messages.concat();
  337. });
  338. },
  339. onFinish(message) {
  340. botMessage.streaming = false;
  341. if (message) {
  342. botMessage.content = message;
  343. get().onNewMessage(botMessage);
  344. }
  345. ChatControllerPool.remove(session.id, botMessage.id);
  346. },
  347. onBeforeTool(tool: ChatMessageTool) {
  348. (botMessage.tools = botMessage?.tools || []).push(tool);
  349. get().updateCurrentSession((session) => {
  350. session.messages = session.messages.concat();
  351. });
  352. },
  353. onAfterTool(tool: ChatMessageTool) {
  354. botMessage?.tools?.forEach((t, i, tools) => {
  355. if (tool.id == t.id) {
  356. tools[i] = { ...tool };
  357. }
  358. });
  359. get().updateCurrentSession((session) => {
  360. session.messages = session.messages.concat();
  361. });
  362. },
  363. onError(error) {
  364. const isAborted = error.message?.includes?.("aborted");
  365. botMessage.content +=
  366. "\n\n" +
  367. prettyObject({
  368. error: true,
  369. message: error.message,
  370. });
  371. botMessage.streaming = false;
  372. userMessage.isError = !isAborted;
  373. botMessage.isError = !isAborted;
  374. get().updateCurrentSession((session) => {
  375. session.messages = session.messages.concat();
  376. });
  377. ChatControllerPool.remove(
  378. session.id,
  379. botMessage.id ?? messageIndex,
  380. );
  381. console.error("[Chat] failed ", error);
  382. },
  383. onController(controller) {
  384. // collect controller for stop/retry
  385. ChatControllerPool.addController(
  386. session.id,
  387. botMessage.id ?? messageIndex,
  388. controller,
  389. );
  390. },
  391. });
  392. },
  393. getMemoryPrompt() {
  394. const session = get().currentSession();
  395. if (session.memoryPrompt.length) {
  396. return {
  397. role: "system",
  398. content: Locale.Store.Prompt.History(session.memoryPrompt),
  399. date: "",
  400. } as ChatMessage;
  401. }
  402. },
  403. getMessagesWithMemory() {
  404. const session = get().currentSession();
  405. const modelConfig = session.mask.modelConfig;
  406. const clearContextIndex = session.clearContextIndex ?? 0;
  407. const messages = session.messages.slice();
  408. const totalMessageCount = session.messages.length;
  409. // in-context prompts
  410. const contextPrompts = session.mask.context.slice();
  411. // system prompts, to get close to OpenAI Web ChatGPT
  412. const shouldInjectSystemPrompts =
  413. modelConfig.enableInjectSystemPrompts &&
  414. (session.mask.modelConfig.model.startsWith("gpt-") ||
  415. session.mask.modelConfig.model.startsWith("chatgpt-"));
  416. var systemPrompts: ChatMessage[] = [];
  417. systemPrompts = shouldInjectSystemPrompts
  418. ? [
  419. createMessage({
  420. role: "system",
  421. content: fillTemplateWith("", {
  422. ...modelConfig,
  423. template: DEFAULT_SYSTEM_TEMPLATE,
  424. }),
  425. }),
  426. ]
  427. : [];
  428. if (shouldInjectSystemPrompts) {
  429. console.log(
  430. "[Global System Prompt] ",
  431. systemPrompts.at(0)?.content ?? "empty",
  432. );
  433. }
  434. const memoryPrompt = get().getMemoryPrompt();
  435. // long term memory
  436. const shouldSendLongTermMemory =
  437. modelConfig.sendMemory &&
  438. session.memoryPrompt &&
  439. session.memoryPrompt.length > 0 &&
  440. session.lastSummarizeIndex > clearContextIndex;
  441. const longTermMemoryPrompts =
  442. shouldSendLongTermMemory && memoryPrompt ? [memoryPrompt] : [];
  443. const longTermMemoryStartIndex = session.lastSummarizeIndex;
  444. // short term memory
  445. const shortTermMemoryStartIndex = Math.max(
  446. 0,
  447. totalMessageCount - modelConfig.historyMessageCount,
  448. );
  449. // lets concat send messages, including 4 parts:
  450. // 0. system prompt: to get close to OpenAI Web ChatGPT
  451. // 1. long term memory: summarized memory messages
  452. // 2. pre-defined in-context prompts
  453. // 3. short term memory: latest n messages
  454. // 4. newest input message
  455. const memoryStartIndex = shouldSendLongTermMemory
  456. ? Math.min(longTermMemoryStartIndex, shortTermMemoryStartIndex)
  457. : shortTermMemoryStartIndex;
  458. // and if user has cleared history messages, we should exclude the memory too.
  459. const contextStartIndex = Math.max(clearContextIndex, memoryStartIndex);
  460. const maxTokenThreshold = modelConfig.max_tokens;
  461. // get recent messages as much as possible
  462. const reversedRecentMessages = [];
  463. for (
  464. let i = totalMessageCount - 1, tokenCount = 0;
  465. i >= contextStartIndex && tokenCount < maxTokenThreshold;
  466. i -= 1
  467. ) {
  468. const msg = messages[i];
  469. if (!msg || msg.isError) continue;
  470. tokenCount += estimateTokenLength(getMessageTextContent(msg));
  471. reversedRecentMessages.push(msg);
  472. }
  473. // concat all messages
  474. const recentMessages = [
  475. ...systemPrompts,
  476. ...longTermMemoryPrompts,
  477. ...contextPrompts,
  478. ...reversedRecentMessages.reverse(),
  479. ];
  480. return recentMessages;
  481. },
  482. updateMessage(
  483. sessionIndex: number,
  484. messageIndex: number,
  485. updater: (message?: ChatMessage) => void,
  486. ) {
  487. const sessions = get().sessions;
  488. const session = sessions.at(sessionIndex);
  489. const messages = session?.messages;
  490. updater(messages?.at(messageIndex));
  491. set(() => ({ sessions }));
  492. },
  493. resetSession() {
  494. get().updateCurrentSession((session) => {
  495. session.messages = [];
  496. session.memoryPrompt = "";
  497. });
  498. },
  499. summarizeSession(refreshTitle: boolean = false) {
  500. const config = useAppConfig.getState();
  501. const session = get().currentSession();
  502. const modelConfig = session.mask.modelConfig;
  503. // skip summarize when using dalle3?
  504. if (isDalle3(modelConfig.model)) {
  505. return;
  506. }
  507. const providerName = modelConfig.compressProviderName;
  508. const api: ClientApi = getClientApi(providerName);
  509. // remove error messages if any
  510. const messages = session.messages;
  511. // should summarize topic after chating more than 50 words
  512. const SUMMARIZE_MIN_LEN = 50;
  513. if (
  514. (config.enableAutoGenerateTitle &&
  515. session.topic === DEFAULT_TOPIC &&
  516. countMessages(messages) >= SUMMARIZE_MIN_LEN) ||
  517. refreshTitle
  518. ) {
  519. const startIndex = Math.max(
  520. 0,
  521. messages.length - modelConfig.historyMessageCount,
  522. );
  523. const topicMessages = messages
  524. .slice(
  525. startIndex < messages.length ? startIndex : messages.length - 1,
  526. messages.length,
  527. )
  528. .concat(
  529. createMessage({
  530. role: "user",
  531. content: Locale.Store.Prompt.Topic,
  532. }),
  533. );
  534. api.llm.chat({
  535. messages: topicMessages,
  536. config: {
  537. model: modelConfig.compressModel,
  538. stream: false,
  539. providerName,
  540. },
  541. onFinish(message) {
  542. if (!isValidMessage(message)) return;
  543. get().updateCurrentSession(
  544. (session) =>
  545. (session.topic =
  546. message.length > 0 ? trimTopic(message) : DEFAULT_TOPIC),
  547. );
  548. },
  549. });
  550. }
  551. const summarizeIndex = Math.max(
  552. session.lastSummarizeIndex,
  553. session.clearContextIndex ?? 0,
  554. );
  555. let toBeSummarizedMsgs = messages
  556. .filter((msg) => !msg.isError)
  557. .slice(summarizeIndex);
  558. const historyMsgLength = countMessages(toBeSummarizedMsgs);
  559. if (historyMsgLength > modelConfig?.max_tokens ?? 4000) {
  560. const n = toBeSummarizedMsgs.length;
  561. toBeSummarizedMsgs = toBeSummarizedMsgs.slice(
  562. Math.max(0, n - modelConfig.historyMessageCount),
  563. );
  564. }
  565. const memoryPrompt = get().getMemoryPrompt();
  566. if (memoryPrompt) {
  567. // add memory prompt
  568. toBeSummarizedMsgs.unshift(memoryPrompt);
  569. }
  570. const lastSummarizeIndex = session.messages.length;
  571. console.log(
  572. "[Chat History] ",
  573. toBeSummarizedMsgs,
  574. historyMsgLength,
  575. modelConfig.compressMessageLengthThreshold,
  576. );
  577. if (
  578. historyMsgLength > modelConfig.compressMessageLengthThreshold &&
  579. modelConfig.sendMemory
  580. ) {
  581. /** Destruct max_tokens while summarizing
  582. * this param is just shit
  583. **/
  584. const { max_tokens, ...modelcfg } = modelConfig;
  585. api.llm.chat({
  586. messages: toBeSummarizedMsgs.concat(
  587. createMessage({
  588. role: "system",
  589. content: Locale.Store.Prompt.Summarize,
  590. date: "",
  591. }),
  592. ),
  593. config: {
  594. ...modelcfg,
  595. stream: true,
  596. model: modelConfig.compressModel,
  597. },
  598. onUpdate(message) {
  599. session.memoryPrompt = message;
  600. },
  601. onFinish(message) {
  602. console.log("[Memory] ", message);
  603. get().updateCurrentSession((session) => {
  604. session.lastSummarizeIndex = lastSummarizeIndex;
  605. session.memoryPrompt = message; // Update the memory prompt for stored it in local storage
  606. });
  607. },
  608. onError(err) {
  609. console.error("[Summarize] ", err);
  610. },
  611. });
  612. }
  613. function isValidMessage(message: any): boolean {
  614. return typeof message === "string" && !message.startsWith("```json");
  615. }
  616. },
  617. updateStat(message: ChatMessage) {
  618. get().updateCurrentSession((session) => {
  619. session.stat.charCount += message.content.length;
  620. // TODO: should update chat count and word count
  621. });
  622. },
  623. updateCurrentSession(updater: (session: ChatSession) => void) {
  624. const sessions = get().sessions;
  625. const index = get().currentSessionIndex;
  626. updater(sessions[index]);
  627. set(() => ({ sessions }));
  628. },
  629. async clearAllData() {
  630. await indexedDBStorage.clear();
  631. localStorage.clear();
  632. location.reload();
  633. },
  634. setLastInput(lastInput: string) {
  635. set({
  636. lastInput,
  637. });
  638. },
  639. };
  640. return methods;
  641. },
  642. {
  643. name: StoreKey.Chat,
  644. version: 3.2,
  645. migrate(persistedState, version) {
  646. const state = persistedState as any;
  647. const newState = JSON.parse(
  648. JSON.stringify(state),
  649. ) as typeof DEFAULT_CHAT_STATE;
  650. if (version < 2) {
  651. newState.sessions = [];
  652. const oldSessions = state.sessions;
  653. for (const oldSession of oldSessions) {
  654. const newSession = createEmptySession();
  655. newSession.topic = oldSession.topic;
  656. newSession.messages = [...oldSession.messages];
  657. newSession.mask.modelConfig.sendMemory = true;
  658. newSession.mask.modelConfig.historyMessageCount = 4;
  659. newSession.mask.modelConfig.compressMessageLengthThreshold = 1000;
  660. newState.sessions.push(newSession);
  661. }
  662. }
  663. if (version < 3) {
  664. // migrate id to nanoid
  665. newState.sessions.forEach((s) => {
  666. s.id = nanoid();
  667. s.messages.forEach((m) => (m.id = nanoid()));
  668. });
  669. }
  670. // Enable `enableInjectSystemPrompts` attribute for old sessions.
  671. // Resolve issue of old sessions not automatically enabling.
  672. if (version < 3.1) {
  673. newState.sessions.forEach((s) => {
  674. if (
  675. // Exclude those already set by user
  676. !s.mask.modelConfig.hasOwnProperty("enableInjectSystemPrompts")
  677. ) {
  678. // Because users may have changed this configuration,
  679. // the user's current configuration is used instead of the default
  680. const config = useAppConfig.getState();
  681. s.mask.modelConfig.enableInjectSystemPrompts =
  682. config.modelConfig.enableInjectSystemPrompts;
  683. }
  684. });
  685. }
  686. // add default summarize model for every session
  687. if (version < 3.2) {
  688. newState.sessions.forEach((s) => {
  689. const config = useAppConfig.getState();
  690. s.mask.modelConfig.compressModel = config.modelConfig.compressModel;
  691. s.mask.modelConfig.compressProviderName =
  692. config.modelConfig.compressProviderName;
  693. });
  694. }
  695. return newState as any;
  696. },
  697. },
  698. );