refac: @/types/chatstore.ts

This commit is contained in:
2024-10-15 10:18:20 +08:00
parent 04bac03fd7
commit dccf4827c9
19 changed files with 125 additions and 120 deletions

View File

@@ -1,5 +1,5 @@
import { useState } from "preact/hooks"; import { useState } from "preact/hooks";
import { ChatStore } from "@/app"; import { ChatStore } from "@/types/chatstore";
import { MessageDetail } from "@/chatgpt"; import { MessageDetail } from "@/chatgpt";
import { Tr } from "@/translate"; import { Tr } from "@/translate";

View File

@@ -3,89 +3,11 @@ import { useEffect, useState } from "preact/hooks";
import "@/global.css"; import "@/global.css";
import { calculate_token_length } from "@/chatgpt"; import { calculate_token_length } from "@/chatgpt";
import getDefaultParams from "@/getDefaultParam"; import getDefaultParams from "@/utils/getDefaultParam";
import ChatBOX from "@/chatbox"; import ChatBOX from "@/chatbox";
import models, { defaultModel } from "@/models"; import models, { defaultModel } from "@/models";
import { Tr, langCodeContext, LANG_OPTIONS } from "@/translate"; import { Tr, langCodeContext, LANG_OPTIONS } from "@/translate";
import { ChatStore } from "@/types/chatstore"; import { ChatStore, newChatStore } from "@/types/chatstore";
import CHATGPT_API_WEB_VERSION from "@/CHATGPT_API_WEB_VERSION";
export interface TemplateAPI {
name: string;
key: string;
endpoint: string;
}
export interface TemplateTools {
name: string;
toolsString: string;
}
const _defaultAPIEndpoint = "https://api.openai.com/v1/chat/completions";
export const newChatStore = (
apiKey = "",
systemMessageContent = "",
apiEndpoint = _defaultAPIEndpoint,
streamMode = true,
model = defaultModel,
temperature = 0.7,
dev = false,
whisper_api = "https://api.openai.com/v1/audio/transcriptions",
whisper_key = "",
tts_api = "https://api.openai.com/v1/audio/speech",
tts_key = "",
tts_speed = 1.0,
tts_speed_enabled = false,
tts_format = "mp3",
toolsString = "",
image_gen_api = "https://api.openai.com/v1/images/generations",
image_gen_key = "",
json_mode = false,
logprobs = false
): ChatStore => {
return {
chatgpt_api_web_version: CHATGPT_API_WEB_VERSION,
systemMessageContent: getDefaultParams("sys", systemMessageContent),
toolsString,
history: [],
postBeginIndex: 0,
tokenMargin: 1024,
totalTokens: 0,
maxTokens: getDefaultParams(
"max",
models[getDefaultParams("model", model)]?.maxToken ?? 2048
),
maxGenTokens: 2048,
maxGenTokens_enabled: false,
apiKey: getDefaultParams("key", apiKey),
apiEndpoint: getDefaultParams("api", apiEndpoint),
streamMode: getDefaultParams("mode", streamMode),
model: getDefaultParams("model", model),
responseModelName: "",
cost: 0,
temperature: getDefaultParams("temp", temperature),
temperature_enabled: true,
top_p: 1,
top_p_enabled: false,
presence_penalty: 0,
frequency_penalty: 0,
develop_mode: getDefaultParams("dev", dev),
whisper_api: getDefaultParams("whisper-api", whisper_api),
whisper_key: getDefaultParams("whisper-key", whisper_key),
tts_api: getDefaultParams("tts-api", tts_api),
tts_key: getDefaultParams("tts-key", tts_key),
tts_voice: "alloy",
tts_speed: tts_speed,
tts_speed_enabled: tts_speed_enabled,
image_gen_api: image_gen_api,
image_gen_key: image_gen_key,
json_mode: json_mode,
tts_format: tts_format,
logprobs,
contents_for_index: [],
};
};
export const STORAGE_NAME = "chatgpt-api-web"; export const STORAGE_NAME = "chatgpt-api-web";
const STORAGE_NAME_SELECTED = `${STORAGE_NAME}-selected`; const STORAGE_NAME_SELECTED = `${STORAGE_NAME}-selected`;
@@ -106,7 +28,7 @@ export function addTotalCost(cost: number) {
export function getTotalCost(): number { export function getTotalCost(): number {
let totalCost = parseFloat( let totalCost = parseFloat(
localStorage.getItem(STORAGE_NAME_TOTALCOST) ?? "0" localStorage.getItem(STORAGE_NAME_TOTALCOST) ?? "0",
); );
return totalCost; return totalCost;
} }
@@ -144,7 +66,7 @@ export function BuildFiledForSearch(chatStore: ChatStore): string[] {
export function App() { export function App() {
// init selected index // init selected index
const [selectedChatIndex, setSelectedChatIndex] = useState( const [selectedChatIndex, setSelectedChatIndex] = useState(
parseInt(localStorage.getItem(STORAGE_NAME_SELECTED) ?? "1") parseInt(localStorage.getItem(STORAGE_NAME_SELECTED) ?? "1"),
); );
console.log("selectedChatIndex", selectedChatIndex); console.log("selectedChatIndex", selectedChatIndex);
useEffect(() => { useEffect(() => {
@@ -161,7 +83,7 @@ export function App() {
// copy from localStorage to indexedDB // copy from localStorage to indexedDB
const allChatStoreIndexes: number[] = JSON.parse( const allChatStoreIndexes: number[] = JSON.parse(
localStorage.getItem(STORAGE_NAME_INDEXES) ?? "[]" localStorage.getItem(STORAGE_NAME_INDEXES) ?? "[]",
); );
let keyCount = 0; let keyCount = 0;
for (const i of allChatStoreIndexes) { for (const i of allChatStoreIndexes) {
@@ -175,7 +97,7 @@ export function App() {
setSelectedChatIndex(keyCount); setSelectedChatIndex(keyCount);
if (keyCount > 0) { if (keyCount > 0) {
alert( alert(
"v2.0.0 Update: Imported chat history from localStorage to indexedDB. 🎉" "v2.0.0 Update: Imported chat history from localStorage to indexedDB. 🎉",
); );
} }
} }
@@ -183,7 +105,7 @@ export function App() {
if (oldVersion < 11) { if (oldVersion < 11) {
if (oldVersion < 11 && oldVersion >= 1) { if (oldVersion < 11 && oldVersion >= 1) {
alert( alert(
"Start upgrading storage, just a sec... (Click OK to continue)" "Start upgrading storage, just a sec... (Click OK to continue)",
); );
} }
if ( if (
@@ -201,7 +123,7 @@ export function App() {
{ {
multiEntry: true, multiEntry: true,
unique: false, unique: false,
} },
); );
// iter through all chatStore and update contents_for_index // iter through all chatStore and update contents_for_index
@@ -248,7 +170,7 @@ export function App() {
const max = chatStore.maxTokens - chatStore.tokenMargin; const max = chatStore.maxTokens - chatStore.tokenMargin;
let sum = 0; let sum = 0;
chatStore.postBeginIndex = chatStore.history.filter( chatStore.postBeginIndex = chatStore.history.filter(
({ hide }) => !hide ({ hide }) => !hide,
).length; ).length;
for (const msg of chatStore.history for (const msg of chatStore.history
.filter(({ hide }) => !hide) .filter(({ hide }) => !hide)
@@ -263,7 +185,7 @@ export function App() {
// manually estimate token // manually estimate token
chatStore.totalTokens = calculate_token_length( chatStore.totalTokens = calculate_token_length(
chatStore.systemMessageContent chatStore.systemMessageContent,
); );
for (const msg of chatStore.history for (const msg of chatStore.history
.filter(({ hide }) => !hide) .filter(({ hide }) => !hide)
@@ -285,7 +207,7 @@ export function App() {
// all chat store indexes // all chat store indexes
const [allChatStoreIndexes, setAllChatStoreIndexes] = useState<IDBValidKey>( const [allChatStoreIndexes, setAllChatStoreIndexes] = useState<IDBValidKey>(
[] [],
); );
const handleNewChatStoreWithOldOne = async (chatStore: ChatStore) => { const handleNewChatStoreWithOldOne = async (chatStore: ChatStore) => {
@@ -312,8 +234,8 @@ export function App() {
chatStore.image_gen_api, chatStore.image_gen_api,
chatStore.image_gen_key, chatStore.image_gen_key,
chatStore.json_mode, chatStore.json_mode,
false // logprobs default to false false, // logprobs default to false
) ),
); );
setSelectedChatIndex(newKey as number); setSelectedChatIndex(newKey as number);
setAllChatStoreIndexes(await (await db).getAllKeys(STORAGE_NAME)); setAllChatStoreIndexes(await (await db).getAllKeys(STORAGE_NAME));
@@ -399,7 +321,7 @@ export function App() {
return; return;
console.log( console.log(
"remove item", "remove item",
`${STORAGE_NAME}-${selectedChatIndex}` `${STORAGE_NAME}-${selectedChatIndex}`,
); );
(await db).delete(STORAGE_NAME, selectedChatIndex); (await db).delete(STORAGE_NAME, selectedChatIndex);
const newAllChatStoreIndexes = await ( const newAllChatStoreIndexes = await (
@@ -427,7 +349,7 @@ export function App() {
onClick={async () => { onClick={async () => {
if ( if (
!confirm( !confirm(
"Are you sure you want to delete **ALL** chat history?" "Are you sure you want to delete **ALL** chat history?",
) )
) )
return; return;

View File

@@ -15,16 +15,12 @@ import { createRef } from "preact";
import { StateUpdater, useEffect, useState, Dispatch } from "preact/hooks"; import { StateUpdater, useEffect, useState, Dispatch } from "preact/hooks";
import { Tr, langCodeContext, LANG_OPTIONS } from "@/translate"; import { Tr, langCodeContext, LANG_OPTIONS } from "@/translate";
import { import {
ChatStore,
ChatStoreMessage,
STORAGE_NAME_TEMPLATE, STORAGE_NAME_TEMPLATE,
STORAGE_NAME_TEMPLATE_API, STORAGE_NAME_TEMPLATE_API,
STORAGE_NAME_TEMPLATE_API_IMAGE_GEN, STORAGE_NAME_TEMPLATE_API_IMAGE_GEN,
STORAGE_NAME_TEMPLATE_API_TTS, STORAGE_NAME_TEMPLATE_API_TTS,
STORAGE_NAME_TEMPLATE_API_WHISPER, STORAGE_NAME_TEMPLATE_API_WHISPER,
STORAGE_NAME_TEMPLATE_TOOLS, STORAGE_NAME_TEMPLATE_TOOLS,
TemplateAPI,
TemplateTools,
addTotalCost, addTotalCost,
getTotalCost, getTotalCost,
} from "@/app"; } from "@/app";
@@ -37,18 +33,22 @@ import ChatGPT, {
ToolCall, ToolCall,
Logprobs, Logprobs,
} from "@/chatgpt"; } from "@/chatgpt";
import {
ChatStore,
ChatStoreMessage,
TemplateChatStore,
TemplateAPI,
TemplateTools,
} from "./types/chatstore";
import Message from "@/message"; import Message from "@/message";
import models from "@/models"; import models from "@/models";
import Settings from "@/settings"; import Settings from "@/settings";
import getDefaultParams from "@/getDefaultParam"; import getDefaultParams from "@/utils/getDefaultParam";
import { AddImage } from "@/addImage"; import { AddImage } from "@/addImage";
import { ListAPIs } from "@/listAPIs"; import { ListAPIs } from "@/listAPIs";
import { ListToolsTempaltes } from "@/listToolsTemplates"; import { ListToolsTempaltes } from "@/listToolsTemplates";
import { autoHeight } from "@/textarea"; import { autoHeight } from "@/textarea";
import Search from "@/search"; import Search from "@/search";
export interface TemplateChatStore extends ChatStore {
name: string;
}
export default function ChatBOX(props: { export default function ChatBOX(props: {
db: Promise<IDBPDatabase<ChatStore>>; db: Promise<IDBPDatabase<ChatStore>>;

View File

@@ -1,6 +1,6 @@
import { useState, useEffect, StateUpdater, Dispatch } from "preact/hooks"; import { useState, useEffect, StateUpdater, Dispatch } from "preact/hooks";
import { Tr, langCodeContext, LANG_OPTIONS, tr } from "@/translate"; import { Tr, langCodeContext, LANG_OPTIONS, tr } from "@/translate";
import { ChatStore, ChatStoreMessage } from "@/app"; import { ChatStore, ChatStoreMessage } from "@/types/chatstore";
import { EditMessageString } from "@/editMessageString"; import { EditMessageString } from "@/editMessageString";
import { EditMessageDetail } from "@/editMessageDetail"; import { EditMessageDetail } from "@/editMessageDetail";

View File

@@ -1,4 +1,4 @@
import { ChatStore, ChatStoreMessage } from "@/app"; import { ChatStore, ChatStoreMessage } from "@/types/chatstore";
import { calculate_token_length } from "@/chatgpt"; import { calculate_token_length } from "@/chatgpt";
import { Tr } from "@/translate"; import { Tr } from "@/translate";

View File

@@ -1,4 +1,4 @@
import { ChatStore, ChatStoreMessage } from "@/app"; import { ChatStore, ChatStoreMessage } from "@/types/chatstore";
import { isVailedJSON } from "@/message"; import { isVailedJSON } from "@/message";
import { calculate_token_length } from "@/chatgpt"; import { calculate_token_length } from "@/chatgpt";
import { Tr } from "@/translate"; import { Tr } from "@/translate";

View File

@@ -1,4 +1,4 @@
import { ChatStore, TemplateAPI } from "@/app"; import { ChatStore, TemplateAPI } from "@/types/chatstore";
import { Tr } from "@/translate"; import { Tr } from "@/translate";
interface Props { interface Props {

View File

@@ -1,4 +1,4 @@
import { ChatStore, TemplateTools } from "@/app"; import { ChatStore, TemplateTools } from "@/types/chatstore";
import { Tr } from "@/translate"; import { Tr } from "@/translate";
interface Props { interface Props {

View File

@@ -3,7 +3,7 @@ import Markdown from "preact-markdown";
import { useState, useEffect, StateUpdater } from "preact/hooks"; import { useState, useEffect, StateUpdater } from "preact/hooks";
import { Tr, langCodeContext, LANG_OPTIONS } from "@/translate"; import { Tr, langCodeContext, LANG_OPTIONS } from "@/translate";
import { ChatStore, ChatStoreMessage } from "@/app"; import { ChatStore, ChatStoreMessage } from "@/types/chatstore";
import { calculate_token_length, getMessageText } from "@/chatgpt"; import { calculate_token_length, getMessageText } from "@/chatgpt";
import TTSButton, { TTSPlay } from "@/tts"; import TTSButton, { TTSPlay } from "@/tts";
import { MessageHide } from "@/messageHide"; import { MessageHide } from "@/messageHide";

View File

@@ -1,4 +1,4 @@
import { ChatStoreMessage } from "@/app"; import { ChatStoreMessage } from "@/types/chatstore";
interface Props { interface Props {
chat: ChatStoreMessage; chat: ChatStoreMessage;

View File

@@ -1,4 +1,4 @@
import { ChatStoreMessage } from "@/app"; import { ChatStoreMessage } from "@/types/chatstore";
import { getMessageText } from "@/chatgpt"; import { getMessageText } from "@/chatgpt";
interface Props { interface Props {

View File

@@ -1,4 +1,4 @@
import { ChatStoreMessage } from "@/app"; import { ChatStoreMessage } from "@/types/chatstore";
interface Props { interface Props {
chat: ChatStoreMessage; chat: ChatStoreMessage;

View File

@@ -1,4 +1,4 @@
import { ChatStoreMessage } from "@/app"; import { ChatStoreMessage } from "@/types/chatstore";
interface Props { interface Props {
chat: ChatStoreMessage; chat: ChatStoreMessage;

View File

@@ -1,7 +1,7 @@
import { IDBPDatabase } from "idb"; import { IDBPDatabase } from "idb";
import { StateUpdater, useRef, useState, Dispatch } from "preact/hooks"; import { StateUpdater, useRef, useState, Dispatch } from "preact/hooks";
import { ChatStore } from "@/app"; import { ChatStore } from "@/types/chatstore";
interface ChatStoreSearchResult { interface ChatStoreSearchResult {
key: IDBValidKey; key: IDBValidKey;

View File

@@ -1,4 +1,4 @@
import { TemplateAPI } from "@/app"; import { TemplateAPI } from "@/types/chatstore";
import { Tr } from "@/translate"; import { Tr } from "@/translate";
interface Props { interface Props {

View File

@@ -21,20 +21,19 @@ import {
useState, useState,
Dispatch, Dispatch,
} from "preact/hooks"; } from "preact/hooks";
import { clearTotalCost, getTotalCost } from "@/app";
import { import {
ChatStore, ChatStore,
TemplateChatStore,
TemplateAPI, TemplateAPI,
TemplateTools, TemplateTools,
clearTotalCost, } from "@/types/chatstore";
getTotalCost,
} from "@/app";
import models from "@/models"; import models from "@/models";
import { TemplateChatStore } from "@/chatbox";
import { tr, Tr, langCodeContext, LANG_OPTIONS } from "@/translate"; import { tr, Tr, langCodeContext, LANG_OPTIONS } from "@/translate";
import { isVailedJSON } from "@/message"; import { isVailedJSON } from "@/message";
import { SetAPIsTemplate } from "@/setAPIsTemplate"; import { SetAPIsTemplate } from "@/setAPIsTemplate";
import { autoHeight } from "@/textarea"; import { autoHeight } from "@/textarea";
import getDefaultParams from "@/getDefaultParam"; import getDefaultParams from "@/utils/getDefaultParam";
const TTS_VOICES: string[] = [ const TTS_VOICES: string[] = [
"alloy", "alloy",

View File

@@ -1,7 +1,8 @@
import { SpeakerWaveIcon } from "@heroicons/react/24/outline"; import { SpeakerWaveIcon } from "@heroicons/react/24/outline";
import { useMemo, useState } from "preact/hooks"; import { useMemo, useState } from "preact/hooks";
import { ChatStore, ChatStoreMessage, addTotalCost } from "@/app"; import { addTotalCost } from "@/app";
import { ChatStore, ChatStoreMessage } from "@/types/chatstore";
import { Message, getMessageText } from "@/chatgpt"; import { Message, getMessageText } from "@/chatgpt";
interface TTSProps { interface TTSProps {

View File

@@ -1,4 +1,7 @@
import { Logprobs, Message } from "@/chatgpt"; import { Logprobs, Message } from "@/chatgpt";
import models, { defaultModel } from "@/models";
import CHATGPT_API_WEB_VERSION from "@/CHATGPT_API_WEB_VERSION";
import getDefaultParams from "@/utils/getDefaultParam";
/** /**
* ChatStore is the main object of the chatgpt-api-web, * ChatStore is the main object of the chatgpt-api-web,
@@ -44,6 +47,21 @@ export interface ChatStore {
contents_for_index: string[]; contents_for_index: string[];
} }
export interface TemplateChatStore extends ChatStore {
name: string;
}
export interface TemplateAPI {
name: string;
key: string;
endpoint: string;
}
export interface TemplateTools {
name: string;
toolsString: string;
}
/** /**
* ChatStoreMessage extends the Message type defined by OpenAI. * ChatStoreMessage extends the Message type defined by OpenAI.
* It adds more fields to be stored within the ChatStore structure. * It adds more fields to be stored within the ChatStore structure.
@@ -55,3 +73,68 @@ export interface ChatStoreMessage extends Message {
audio: Blob | null; audio: Blob | null;
logprobs: Logprobs | null; logprobs: Logprobs | null;
} }
const _defaultAPIEndpoint = "https://api.openai.com/v1/chat/completions";
export const newChatStore = (
apiKey = "",
systemMessageContent = "",
apiEndpoint = _defaultAPIEndpoint,
streamMode = true,
model = defaultModel,
temperature = 0.7,
dev = false,
whisper_api = "https://api.openai.com/v1/audio/transcriptions",
whisper_key = "",
tts_api = "https://api.openai.com/v1/audio/speech",
tts_key = "",
tts_speed = 1.0,
tts_speed_enabled = false,
tts_format = "mp3",
toolsString = "",
image_gen_api = "https://api.openai.com/v1/images/generations",
image_gen_key = "",
json_mode = false,
logprobs = false,
): ChatStore => {
return {
chatgpt_api_web_version: CHATGPT_API_WEB_VERSION,
systemMessageContent: getDefaultParams("sys", systemMessageContent),
toolsString,
history: [],
postBeginIndex: 0,
tokenMargin: 1024,
totalTokens: 0,
maxTokens: getDefaultParams(
"max",
models[getDefaultParams("model", model)]?.maxToken ?? 2048,
),
maxGenTokens: 2048,
maxGenTokens_enabled: false,
apiKey: getDefaultParams("key", apiKey),
apiEndpoint: getDefaultParams("api", apiEndpoint),
streamMode: getDefaultParams("mode", streamMode),
model: getDefaultParams("model", model),
responseModelName: "",
cost: 0,
temperature: getDefaultParams("temp", temperature),
temperature_enabled: true,
top_p: 1,
top_p_enabled: false,
presence_penalty: 0,
frequency_penalty: 0,
develop_mode: getDefaultParams("dev", dev),
whisper_api: getDefaultParams("whisper-api", whisper_api),
whisper_key: getDefaultParams("whisper-key", whisper_key),
tts_api: getDefaultParams("tts-api", tts_api),
tts_key: getDefaultParams("tts-key", tts_key),
tts_voice: "alloy",
tts_speed: tts_speed,
tts_speed_enabled: tts_speed_enabled,
image_gen_api: image_gen_api,
image_gen_key: image_gen_key,
json_mode: json_mode,
tts_format: tts_format,
logprobs,
contents_for_index: [],
};
};