1 Commits

Author SHA1 Message Date
7b00a6ea7f wenker custom params 2024-02-28 12:25:25 +08:00
31 changed files with 1298 additions and 2506 deletions

View File

@@ -1,27 +0,0 @@
name: Build static content
on:
# Runs on pushes targeting the default branch
push:
branches: ["master"]
# Allows you to run this workflow manually from the Actions tab
workflow_dispatch:
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Use Node.js 18.x
uses: actions/setup-node@v3
with:
node-version: 18.x
cache: 'npm'
- run: npm install
- run: npm run build
- name: Upload artifact
uses: actions/upload-artifact@v3
with:
name: dist-files
path: './dist/'

View File

@@ -1,5 +1,5 @@
<!DOCTYPE html>
<html data-theme="cupcake" lang="en">
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta

View File

@@ -9,22 +9,19 @@
"preview": "vite preview"
},
"dependencies": {
"@heroicons/react": "^2.1.5",
"@types/ungap__structured-clone": "^1.2.0",
"@types/ungap__structured-clone": "^0.3.1",
"@ungap/structured-clone": "^1.2.0",
"autoprefixer": "^10.4.20",
"idb": "^8.0.0",
"postcss": "^8.4.47",
"preact": "^10.24.3",
"autoprefixer": "^10.4.16",
"idb": "^7.1.1",
"postcss": "^8.4.31",
"preact": "^10.18.1",
"preact-markdown": "^2.1.0",
"sakura.css": "^1.5.0",
"tailwindcss": "^3.4.13"
"tailwindcss": "^3.3.4"
},
"devDependencies": {
"@preact/preset-vite": "^2.9.1",
"daisyui": "^4.12.13",
"theme-change": "^2.5.0",
"typescript": "^5.6.3",
"vite": "^5.4.8"
"@preact/preset-vite": "^2.6.0",
"typescript": "^5.2.2",
"vite": "^4.5.0"
}
}

View File

@@ -1,7 +1,7 @@
import { useState } from "preact/hooks";
import { ChatStore } from "@/app";
import { MessageDetail } from "@/chatgpt";
import { Tr } from "@/translate";
import { ChatStore } from "./app";
import { MessageDetail } from "./chatgpt";
import { Tr } from "./translate";
interface Props {
chatStore: ChatStore;
@@ -41,25 +41,15 @@ export function AddImage({
}}
>
<div
className="bg-base-200 p-2 z-20"
className="bg-white rounded p-2 z-20"
onClick={(event) => {
event.stopPropagation();
}}
>
<div className="flex justify-between items-center p-1">
<h3>Add Images</h3>
<h2>Add Images</h2>
<span>
<button
className="btn btn-sm btn-neutral"
onClick={() => {
setShowAddImage(false);
}}
>
Done
</button>
</div>
<span className="">
<button
className="btn btn-secondary btn-sm disabled:btn-disabled"
className="disabled:line-through disabled:bg-slate-500 rounded m-1 p-1 border-2 bg-cyan-400 hover:bg-cyan-600"
onClick={() => {
const image_url = prompt("Image URL");
if (!image_url) {
@@ -80,7 +70,7 @@ export function AddImage({
Add from URL
</button>
<button
className="btn btn-primary btn-sm disabled:btn-disabled"
className="disabled:line-through disabled:bg-slate-500 rounded m-1 p-1 border-2 bg-cyan-400 hover:bg-cyan-600"
onClick={() => {
// select file and load it to base64 image URL format
const input = document.createElement("input");
@@ -121,24 +111,23 @@ export function AddImage({
<input type="checkbox" checked={enableHighResolution} />
</span>
</span>
<div className="divider"></div>
{chatStore.image_gen_api && chatStore.image_gen_key && (
<div className="flex flex-col">
<hr className="my-2" />
<h3>Generate Image</h3>
<span className="flex flex-col justify-between m-1 p-1">
<span className="flex flex-row justify-between m-1 p-1">
<label>Prompt: </label>
<textarea
className="textarea textarea-sm textarea-bordered"
className="border rounded border-gray-400"
value={imageGenPrompt}
onChange={(e: any) => {
setImageGenPrompt(e.target.value);
}}
/>
</span>
<span className="flex flex-row justify-between items-center m-1 p-1">
<span className="flex flex-row justify-between m-1 p-1">
<label>Model: </label>
<select
className="select select-sm select-bordered"
value={imageGenModel}
onChange={(e: any) => {
setImageGenModel(e.target.value);
@@ -148,10 +137,9 @@ export function AddImage({
<option value="dall-e-2">DALL-E 2</option>
</select>
</span>
<span className="flex flex-row justify-between items-center m-1 p-1">
<span className="flex flex-row justify-between m-1 p-1">
<label>n: </label>
<input
className="input input-sm input-bordered"
value={imageGenN}
type="number"
min={1}
@@ -159,10 +147,9 @@ export function AddImage({
onChange={(e: any) => setImageGenN(parseInt(e.target.value))}
/>
</span>
<span className="flex flex-row justify-between items-center m-1 p-1">
<span className="flex flex-row justify-between m-1 p-1">
<label>Quality: </label>
<select
className="select select-sm select-bordered"
value={imageGenQuality}
onChange={(e: any) => setImageGEnQuality(e.target.value)}
>
@@ -170,10 +157,9 @@ export function AddImage({
<option value="standard">Standard</option>
</select>
</span>
<span className="flex flex-row justify-between items-center m-1 p-1">
<span className="flex flex-row justify-between m-1 p-1">
<label>Response Format: </label>
<select
className="select select-sm select-bordered"
value={imageGenResponseFormat}
onChange={(e: any) => setImageGenResponseFormat(e.target.value)}
>
@@ -181,10 +167,9 @@ export function AddImage({
<option value="url">url</option>
</select>
</span>
<span className="flex flex-row justify-between items-center m-1 p-1">
<span className="flex flex-row justify-between m-1 p-1">
<label>Size: </label>
<select
className="select select-sm select-bordered"
value={imageGenSize}
onChange={(e: any) => setImageGenSize(e.target.value)}
>
@@ -195,10 +180,9 @@ export function AddImage({
<option value="1024x1792">1024x1792 (dall-e-3)</option>
</select>
</span>
<span className="flex flex-row justify-between items-center m-1 p-1">
<span className="flex flex-row justify-between m-1 p-1">
<label>Style (only dall-e-3): </label>
<select
className="select select-sm select-bordered"
value={imageGenStyle}
onChange={(e: any) => setImageGenStyle(e.target.value)}
>
@@ -206,9 +190,9 @@ export function AddImage({
<option value="natural">natural</option>
</select>
</span>
<span className="flex flex-row justify-between items-center m-1 p-1">
<span className="flex flex-row justify-between m-1 p-1">
<button
className="btn btn-primary btn-sm"
className="bg-sky-400 m-1 p-1 rounded disabled:bg-slate-500"
disabled={imageGenGenerating}
onClick={async () => {
try {

View File

@@ -1,14 +1,14 @@
import { IDBPDatabase, openDB } from "idb";
import { useEffect, useState } from "preact/hooks";
import "@/global.css";
import "./global.css";
import { calculate_token_length, Logprobs, Message } from "@/chatgpt";
import getDefaultParams from "@/getDefaultParam";
import ChatBOX from "@/chatbox";
import models, { defaultModel } from "@/models";
import { Tr, langCodeContext, LANG_OPTIONS } from "@/translate";
import { calculate_token_length, Logprobs, Message } from "./chatgpt";
import getDefaultParams from "./getDefaultParam";
import ChatBOX from "./chatbox";
import models, { defaultModel } from "./models";
import { Tr, langCodeContext, LANG_OPTIONS } from "./translate";
import CHATGPT_API_WEB_VERSION from "@/CHATGPT_API_WEB_VERSION";
import CHATGPT_API_WEB_VERSION from "./CHATGPT_API_WEB_VERSION";
export interface ChatStoreMessage extends Message {
hide: boolean;
@@ -65,10 +65,9 @@ export interface ChatStore {
image_gen_key: string;
json_mode: boolean;
logprobs: boolean;
contents_for_index: string[];
}
const _defaultAPIEndpoint = "https://api.openai.com/v1/chat/completions";
const _defaultAPIEndpoint = "/v1/chat/completions";
export const newChatStore = (
apiKey = "",
systemMessageContent = "",
@@ -88,7 +87,7 @@ export const newChatStore = (
image_gen_api = "https://api.openai.com/v1/images/generations",
image_gen_key = "",
json_mode = false,
logprobs = false,
logprobs = true
): ChatStore => {
return {
chatgpt_api_web_version: CHATGPT_API_WEB_VERSION,
@@ -100,10 +99,10 @@ export const newChatStore = (
totalTokens: 0,
maxTokens: getDefaultParams(
"max",
models[getDefaultParams("model", model)]?.maxToken ?? 2048,
models[getDefaultParams("model", model)]?.maxToken ?? 2048
),
maxGenTokens: 2048,
maxGenTokens_enabled: false,
maxGenTokens_enabled: true,
apiKey: getDefaultParams("key", apiKey),
apiEndpoint: getDefaultParams("api", apiEndpoint),
streamMode: getDefaultParams("mode", streamMode),
@@ -129,7 +128,6 @@ export const newChatStore = (
json_mode: json_mode,
tts_format: tts_format,
logprobs,
contents_for_index: [],
};
};
@@ -152,7 +150,7 @@ export function addTotalCost(cost: number) {
export function getTotalCost(): number {
let totalCost = parseFloat(
localStorage.getItem(STORAGE_NAME_TOTALCOST) ?? "0",
localStorage.getItem(STORAGE_NAME_TOTALCOST) ?? "0"
);
return totalCost;
}
@@ -161,36 +159,10 @@ export function clearTotalCost() {
localStorage.setItem(STORAGE_NAME_TOTALCOST, `0`);
}
export function BuildFiledForSearch(chatStore: ChatStore): string[] {
const contents_for_index: string[] = [];
if (chatStore.systemMessageContent.trim()) {
contents_for_index.push(chatStore.systemMessageContent.trim());
}
for (const msg of chatStore.history) {
if (typeof msg.content === "string") {
contents_for_index.push(msg.content);
continue;
}
for (const chunk of msg.content) {
if (chunk.type === "text") {
const text = chunk.text;
if (text?.trim()) {
contents_for_index.push(text);
}
}
}
}
return contents_for_index;
}
export function App() {
// init selected index
const [selectedChatIndex, setSelectedChatIndex] = useState(
parseInt(localStorage.getItem(STORAGE_NAME_SELECTED) ?? "1"),
parseInt(localStorage.getItem(STORAGE_NAME_SELECTED) ?? "1")
);
console.log("selectedChatIndex", selectedChatIndex);
useEffect(() => {
@@ -198,67 +170,30 @@ export function App() {
localStorage.setItem(STORAGE_NAME_SELECTED, `${selectedChatIndex}`);
}, [selectedChatIndex]);
const db = openDB<ChatStore>(STORAGE_NAME, 11, {
async upgrade(db, oldVersion, newVersion, transaction) {
if (oldVersion < 1) {
const store = db.createObjectStore(STORAGE_NAME, {
autoIncrement: true,
});
const db = openDB<ChatStore>(STORAGE_NAME, 1, {
upgrade(db) {
const store = db.createObjectStore(STORAGE_NAME, {
autoIncrement: true,
});
// copy from localStorage to indexedDB
const allChatStoreIndexes: number[] = JSON.parse(
localStorage.getItem(STORAGE_NAME_INDEXES) ?? "[]",
);
let keyCount = 0;
for (const i of allChatStoreIndexes) {
console.log("importing chatStore from localStorage", i);
const key = `${STORAGE_NAME}-${i}`;
const val = localStorage.getItem(key);
if (val === null) continue;
store.add(JSON.parse(val));
keyCount += 1;
}
setSelectedChatIndex(keyCount);
if (keyCount > 0) {
alert(
"v2.0.0 Update: Imported chat history from localStorage to indexedDB. 🎉",
);
}
// copy from localStorage to indexedDB
const allChatStoreIndexes: number[] = JSON.parse(
localStorage.getItem(STORAGE_NAME_INDEXES) ?? "[]"
);
let keyCount = 0;
for (const i of allChatStoreIndexes) {
console.log("importing chatStore from localStorage", i);
const key = `${STORAGE_NAME}-${i}`;
const val = localStorage.getItem(key);
if (val === null) continue;
store.add(JSON.parse(val));
keyCount += 1;
}
if (oldVersion < 11) {
if (oldVersion < 11 && oldVersion >= 1) {
alert(
"Start upgrading storage, just a sec... (Click OK to continue)",
);
}
if (
transaction
.objectStore(STORAGE_NAME)
.indexNames.contains("contents_for_index")
) {
transaction
.objectStore(STORAGE_NAME)
.deleteIndex("contents_for_index");
}
transaction.objectStore(STORAGE_NAME).createIndex(
"contents_for_index", // name
"contents_for_index", // keyPath
{
multiEntry: true,
unique: false,
},
setSelectedChatIndex(keyCount);
if (keyCount > 0) {
alert(
"v2.0.0 Update: Imported chat history from localStorage to indexedDB. 🎉"
);
// iter through all chatStore and update contents_for_index
const store = transaction.objectStore(STORAGE_NAME);
const allChatStoreIndexes = await store.getAllKeys();
for (const i of allChatStoreIndexes) {
const chatStore: ChatStore = await store.get(i);
chatStore.contents_for_index = BuildFiledForSearch(chatStore);
await store.put(chatStore, i);
}
}
},
});
@@ -287,14 +222,11 @@ export function App() {
const [chatStore, _setChatStore] = useState(newChatStore());
const setChatStore = async (chatStore: ChatStore) => {
// building field for search
chatStore.contents_for_index = BuildFiledForSearch(chatStore);
console.log("recalculate postBeginIndex");
const max = chatStore.maxTokens - chatStore.tokenMargin;
let sum = 0;
chatStore.postBeginIndex = chatStore.history.filter(
({ hide }) => !hide,
({ hide }) => !hide
).length;
for (const msg of chatStore.history
.filter(({ hide }) => !hide)
@@ -309,7 +241,7 @@ export function App() {
// manually estimate token
chatStore.totalTokens = calculate_token_length(
chatStore.systemMessageContent,
chatStore.systemMessageContent
);
for (const msg of chatStore.history
.filter(({ hide }) => !hide)
@@ -331,7 +263,7 @@ export function App() {
// all chat store indexes
const [allChatStoreIndexes, setAllChatStoreIndexes] = useState<IDBValidKey>(
[],
[]
);
const handleNewChatStoreWithOldOne = async (chatStore: ChatStore) => {
@@ -358,8 +290,8 @@ export function App() {
chatStore.image_gen_api,
chatStore.image_gen_key,
chatStore.json_mode,
false, // logprobs default to false
),
chatStore.logprobs
)
);
setSelectedChatIndex(newKey as number);
setAllChatStoreIndexes(await (await db).getAllKeys(STORAGE_NAME));
@@ -403,16 +335,16 @@ export function App() {
}, []);
return (
<div className="flex text-sm h-full">
<div className="flex flex-col h-full p-2 bg-primary">
<div className="flex text-sm h-full bg-slate-200 dark:bg-slate-800 dark:text-white">
<div className="flex flex-col h-full p-2 border-r-indigo-500 border-2 dark:border-slate-800 dark:border-r-indigo-500 dark:text-black">
<div className="grow overflow-scroll">
<button
className="btn btn-sm btn-info p-1 my-1 w-full"
className="bg-violet-300 p-1 rounded hover:bg-violet-400"
onClick={handleNewChatStore}
>
{Tr("NEW")}
</button>
<ul className="pt-2">
<ul>
{(allChatStoreIndexes as number[])
.slice()
.reverse()
@@ -421,8 +353,8 @@ export function App() {
return (
<li>
<button
className={`w-full my-1 p-1 btn btn-sm ${
i === selectedChatIndex ? "btn-accent" : "btn-secondary"
className={`w-full my-1 p-1 rounded hover:bg-blue-500 ${
i === selectedChatIndex ? "bg-blue-500" : "bg-blue-200"
}`}
onClick={() => {
setSelectedChatIndex(i);
@@ -435,62 +367,54 @@ export function App() {
})}
</ul>
</div>
<div>
<button
className="rounded bg-rose-400 p-1 my-1 w-full"
onClick={async () => {
if (!confirm("Are you sure you want to delete this chat history?"))
return;
console.log("remove item", `${STORAGE_NAME}-${selectedChatIndex}`);
(await db).delete(STORAGE_NAME, selectedChatIndex);
const newAllChatStoreIndexes = await (
await db
).getAllKeys(STORAGE_NAME);
if (newAllChatStoreIndexes.length === 0) {
handleNewChatStore();
return;
}
// find nex selected chat index
const next =
newAllChatStoreIndexes[newAllChatStoreIndexes.length - 1];
console.log("next is", next);
setSelectedChatIndex(next as number);
setAllChatStoreIndexes(newAllChatStoreIndexes);
}}
>
{Tr("DEL")}
</button>
{chatStore.develop_mode && (
<button
className="btn btn-warning btn-sm p-1 my-1 w-full"
className="rounded bg-rose-800 p-1 my-1 w-full text-white"
onClick={async () => {
if (
!confirm("Are you sure you want to delete this chat history?")
!confirm(
"Are you sure you want to delete **ALL** chat history?"
)
)
return;
console.log(
"remove item",
`${STORAGE_NAME}-${selectedChatIndex}`,
);
(await db).delete(STORAGE_NAME, selectedChatIndex);
const newAllChatStoreIndexes = await (
await db
).getAllKeys(STORAGE_NAME);
if (newAllChatStoreIndexes.length === 0) {
handleNewChatStore();
return;
}
// find nex selected chat index
const next =
newAllChatStoreIndexes[newAllChatStoreIndexes.length - 1];
console.log("next is", next);
setSelectedChatIndex(next as number);
setAllChatStoreIndexes(newAllChatStoreIndexes);
await (await db).clear(STORAGE_NAME);
setAllChatStoreIndexes([]);
setSelectedChatIndex(1);
window.location.reload();
}}
>
{Tr("DEL")}
{Tr("CLS")}
</button>
{chatStore.develop_mode && (
<button
className="btn btn-sm btn-warning p-1 my-1 w-full"
onClick={async () => {
if (
!confirm(
"Are you sure you want to delete **ALL** chat history?",
)
)
return;
await (await db).clear(STORAGE_NAME);
setAllChatStoreIndexes([]);
setSelectedChatIndex(1);
window.location.reload();
}}
>
{Tr("CLS")}
</button>
)}
</div>
)}
</div>
<ChatBOX
db={db}
chatStore={chatStore}
setChatStore={setChatStore}
selectedChatIndex={selectedChatIndex}

View File

@@ -1,19 +1,7 @@
import {
MagnifyingGlassIcon,
CubeIcon,
BanknotesIcon,
DocumentTextIcon,
ChatBubbleLeftEllipsisIcon,
ScissorsIcon,
SwatchIcon,
SparklesIcon,
} from "@heroicons/react/24/outline";
import { IDBPDatabase } from "idb";
import { Tr, langCodeContext, LANG_OPTIONS } from "./translate";
import structuredClone from "@ungap/structured-clone";
import { createRef } from "preact";
import { StateUpdater, useEffect, useState, Dispatch } from "preact/hooks";
import { Tr, langCodeContext, LANG_OPTIONS } from "@/translate";
import { StateUpdater, useEffect, useState } from "preact/hooks";
import {
ChatStore,
ChatStoreMessage,
@@ -26,8 +14,7 @@ import {
TemplateAPI,
TemplateTools,
addTotalCost,
getTotalCost,
} from "@/app";
} from "./app";
import ChatGPT, {
calculate_token_length,
ChunkMessage,
@@ -36,26 +23,25 @@ import ChatGPT, {
MessageDetail,
ToolCall,
Logprobs,
} from "@/chatgpt";
import Message from "@/message";
import models from "@/models";
import Settings from "@/settings";
import getDefaultParams from "@/getDefaultParam";
import { AddImage } from "@/addImage";
import { ListAPIs } from "@/listAPIs";
import { ListToolsTempaltes } from "@/listToolsTemplates";
import { autoHeight } from "@/textarea";
import Search from "@/search";
} from "./chatgpt";
import Message from "./message";
import models from "./models";
import Settings from "./settings";
import getDefaultParams from "./getDefaultParam";
import { AddImage } from "./addImage";
import { ListAPIs } from "./listAPIs";
import { ListToolsTempaltes } from "./listToolsTemplates";
import { autoHeight } from "./textarea";
export interface TemplateChatStore extends ChatStore {
name: string;
}
export default function ChatBOX(props: {
db: Promise<IDBPDatabase<ChatStore>>;
chatStore: ChatStore;
setChatStore: (cs: ChatStore) => void;
selectedChatIndex: number;
setSelectedChatIndex: Dispatch<StateUpdater<number>>;
setSelectedChatIndex: StateUpdater<number>;
}) {
const { chatStore, setChatStore } = props;
// prevent error
@@ -70,25 +56,11 @@ export default function ChatBOX(props: {
const [showAddToolMsg, setShowAddToolMsg] = useState(false);
const [newToolCallID, setNewToolCallID] = useState("");
const [newToolContent, setNewToolContent] = useState("");
const [showSearch, setShowSearch] = useState(false);
let default_follow = localStorage.getItem("follow");
if (default_follow === null) {
default_follow = "true";
}
const [follow, _setFollow] = useState(default_follow === "true");
const mediaRef = createRef();
const setFollow = (follow: boolean) => {
console.log("set follow", follow);
localStorage.setItem("follow", follow.toString());
_setFollow(follow);
};
const messagesEndRef = createRef();
useEffect(() => {
if (follow) {
messagesEndRef.current.scrollIntoView({ behavior: "smooth" });
}
messagesEndRef.current.scrollIntoView({ behavior: "smooth" });
}, [showRetry, showGenerating, generatingMessage]);
const client = new ChatGPT(chatStore.apiKey);
@@ -96,7 +68,7 @@ export default function ChatBOX(props: {
const update_total_tokens = () => {
// manually estimate token
client.total_tokens = calculate_token_length(
chatStore.systemMessageContent,
chatStore.systemMessageContent
);
for (const msg of chatStore.history
.filter(({ hide }) => !hide)
@@ -126,14 +98,14 @@ export default function ChatBOX(props: {
const logprob = c?.logprobs?.content[0]?.logprob;
if (logprob !== undefined) {
logprobs.content.push({
token: c?.delta?.content ?? "",
token: c.delta.content ?? "",
logprob,
});
console.log(c?.delta?.content, logprob);
console.log(c.delta.content, logprob);
}
allChunkMessage.push(c?.delta?.content ?? "");
const tool_calls = c?.delta?.tool_calls;
allChunkMessage.push(c.delta.content ?? "");
const tool_calls = c.delta.tool_calls;
if (tool_calls) {
for (const tool_call of tool_calls) {
// init
@@ -152,7 +124,7 @@ export default function ChatBOX(props: {
// update tool call arguments
const tool = allChunkTool.find(
(tool) => tool.index === tool_call.index,
(tool) => tool.index === tool_call.index
);
if (!tool) {
@@ -167,7 +139,7 @@ export default function ChatBOX(props: {
allChunkMessage.join("") +
allChunkTool.map((tool) => {
return `Tool Call ID: ${tool.id}\nType: ${tool.type}\nFunction: ${tool.function.name}\nArguments: ${tool.function.arguments}`;
}),
})
);
}
setShowGenerating(false);
@@ -305,7 +277,7 @@ export default function ChatBOX(props: {
setShowGenerating(true);
const response = await client._fetch(
chatStore.streamMode,
chatStore.logprobs,
chatStore.logprobs
);
const contentType = response.headers.get("content-type");
if (contentType?.startsWith("text/event-stream")) {
@@ -375,33 +347,33 @@ export default function ChatBOX(props: {
const [templates, _setTemplates] = useState(
JSON.parse(
localStorage.getItem(STORAGE_NAME_TEMPLATE) || "[]",
) as TemplateChatStore[],
localStorage.getItem(STORAGE_NAME_TEMPLATE) || "[]"
) as TemplateChatStore[]
);
const [templateAPIs, _setTemplateAPIs] = useState(
JSON.parse(
localStorage.getItem(STORAGE_NAME_TEMPLATE_API) || "[]",
) as TemplateAPI[],
localStorage.getItem(STORAGE_NAME_TEMPLATE_API) || "[]"
) as TemplateAPI[]
);
const [templateAPIsWhisper, _setTemplateAPIsWhisper] = useState(
JSON.parse(
localStorage.getItem(STORAGE_NAME_TEMPLATE_API_WHISPER) || "[]",
) as TemplateAPI[],
localStorage.getItem(STORAGE_NAME_TEMPLATE_API_WHISPER) || "[]"
) as TemplateAPI[]
);
const [templateAPIsTTS, _setTemplateAPIsTTS] = useState(
JSON.parse(
localStorage.getItem(STORAGE_NAME_TEMPLATE_API_TTS) || "[]",
) as TemplateAPI[],
localStorage.getItem(STORAGE_NAME_TEMPLATE_API_TTS) || "[]"
) as TemplateAPI[]
);
const [templateAPIsImageGen, _setTemplateAPIsImageGen] = useState(
JSON.parse(
localStorage.getItem(STORAGE_NAME_TEMPLATE_API_IMAGE_GEN) || "[]",
) as TemplateAPI[],
localStorage.getItem(STORAGE_NAME_TEMPLATE_API_IMAGE_GEN) || "[]"
) as TemplateAPI[]
);
const [toolsTemplates, _setToolsTemplates] = useState(
JSON.parse(
localStorage.getItem(STORAGE_NAME_TEMPLATE_TOOLS) || "[]",
) as TemplateTools[],
localStorage.getItem(STORAGE_NAME_TEMPLATE_TOOLS) || "[]"
) as TemplateTools[]
);
const setTemplates = (templates: TemplateChatStore[]) => {
localStorage.setItem(STORAGE_NAME_TEMPLATE, JSON.stringify(templates));
@@ -410,42 +382,42 @@ export default function ChatBOX(props: {
const setTemplateAPIs = (templateAPIs: TemplateAPI[]) => {
localStorage.setItem(
STORAGE_NAME_TEMPLATE_API,
JSON.stringify(templateAPIs),
JSON.stringify(templateAPIs)
);
_setTemplateAPIs(templateAPIs);
};
const setTemplateAPIsWhisper = (templateAPIWhisper: TemplateAPI[]) => {
localStorage.setItem(
STORAGE_NAME_TEMPLATE_API_WHISPER,
JSON.stringify(templateAPIWhisper),
JSON.stringify(templateAPIWhisper)
);
_setTemplateAPIsWhisper(templateAPIWhisper);
};
const setTemplateAPIsTTS = (templateAPITTS: TemplateAPI[]) => {
localStorage.setItem(
STORAGE_NAME_TEMPLATE_API_TTS,
JSON.stringify(templateAPITTS),
JSON.stringify(templateAPITTS)
);
_setTemplateAPIsTTS(templateAPITTS);
};
const setTemplateAPIsImageGen = (templateAPIImageGen: TemplateAPI[]) => {
localStorage.setItem(
STORAGE_NAME_TEMPLATE_API_IMAGE_GEN,
JSON.stringify(templateAPIImageGen),
JSON.stringify(templateAPIImageGen)
);
_setTemplateAPIsImageGen(templateAPIImageGen);
};
const setTemplateTools = (templateTools: TemplateTools[]) => {
localStorage.setItem(
STORAGE_NAME_TEMPLATE_TOOLS,
JSON.stringify(templateTools),
JSON.stringify(templateTools)
);
_setToolsTemplates(templateTools);
};
const userInputRef = createRef();
return (
<div className="grow flex flex-col p-2 w-full">
<div className="grow flex flex-col p-2 dark:text-black">
{showSettings && (
<Settings
chatStore={chatStore}
@@ -466,261 +438,52 @@ export default function ChatBOX(props: {
setTemplateTools={setTemplateTools}
/>
)}
{showSearch && (
<Search
setSelectedChatIndex={props.setSelectedChatIndex}
db={props.db}
chatStore={chatStore}
setShow={setShowSearch}
/>
)}
<div className="navbar bg-base-100 p-0">
<div className="navbar-start">
<div className="dropdown lg:hidden">
<div
tabindex={0}
role="button"
className="btn btn-ghost btn-circle"
>
<svg
xmlns="http://www.w3.org/2000/svg"
className="h-6 w-6"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M4 6h16M4 12h16M4 18h7"
/>
</svg>
</div>
<ul
tabindex={0}
className="menu menu-sm dropdown-content bg-base-100 rounded-box z-[1] mt-3 w-52 p-2 shadow"
>
<li>
<p>
<ChatBubbleLeftEllipsisIcon className="h-4 w-4" />
Tokens: {chatStore.totalTokens}/{chatStore.maxTokens}
</p>
</li>
<li>
<p>
<ScissorsIcon className="h-4 w-4" />
Cut:
{chatStore.postBeginIndex}/
{chatStore.history.filter(({ hide }) => !hide).length}
</p>
</li>
<li>
<p>
<BanknotesIcon className="h-4 w-4" />
Cost: ${chatStore.cost.toFixed(4)}
</p>
</li>
</ul>
</div>
</div>
<div
className="navbar-center cursor-pointer py-1"
onClick={() => {
setShowSettings(true);
}}
>
{/* the long staus bar */}
<div className="stats shadow hidden lg:inline-grid">
<div className="stat">
<div className="stat-figure text-secondary">
<CubeIcon className="h-10 w-10" />
</div>
<div className="stat-title">Model</div>
<div className="stat-value text-base">{chatStore.model}</div>
<div className="stat-desc">
{models[chatStore.model]?.price?.prompt * 1000 * 1000} $/M
tokens
</div>
</div>
<div className="stat">
<div className="stat-figure text-secondary">
<SwatchIcon className="h-10 w-10" />
</div>
<div className="stat-title">Mode</div>
<div className="stat-value text-base">
{chatStore.streamMode ? Tr("STREAM") : Tr("FETCH")}
</div>
<div className="stat-desc">STREAM/FETCH</div>
</div>
<div className="stat">
<div className="stat-figure text-secondary">
<ChatBubbleLeftEllipsisIcon className="h-10 w-10" />
</div>
<div className="stat-title">Tokens</div>
<div className="stat-value text-base">
{chatStore.totalTokens}
</div>
<div className="stat-desc">Max: {chatStore.maxTokens}</div>
</div>
<div className="stat">
<div className="stat-figure text-secondary">
<ScissorsIcon className="h-10 w-10" />
</div>
<div className="stat-title">Cut</div>
<div className="stat-value text-base">
{chatStore.postBeginIndex}
</div>
<div className="stat-desc">
Max: {chatStore.history.filter(({ hide }) => !hide).length}
</div>
</div>
<div className="stat">
<div className="stat-figure text-secondary">
<BanknotesIcon className="h-10 w-10" />
</div>
<div className="stat-title">Cost</div>
<div className="stat-value text-base">
${chatStore.cost.toFixed(4)}
</div>
<div className="stat-desc">
Accumulated: ${getTotalCost().toFixed(2)}
</div>
</div>
</div>
{/* the short status bar */}
<div className="indicator lg:hidden">
{chatStore.totalTokens !== 0 && (
<span className="indicator-item badge badge-primary">
Tokens: {chatStore.totalTokens}
</span>
)}
<a className="btn btn-ghost text-base sm:text-xl p-0">
<SparklesIcon className="h-4 w-4 hidden sm:block" />
{chatStore.model}
</a>
</div>
</div>
<div className="navbar-end">
<button
className="btn btn-ghost btn-circle"
onClick={(event) => {
// stop propagation to parent
event.stopPropagation();
setShowSearch(true);
}}
>
<svg
xmlns="http://www.w3.org/2000/svg"
className="h-6 w-6"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"
/>
</svg>
</button>
<button
className="btn btn-ghost btn-circle hidden sm:block"
onClick={() => setShowSettings(true)}
>
<div className="indicator">
<svg
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
stroke-width="1.5"
stroke="currentColor"
className="h-6 w-6"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
d="M9.594 3.94c.09-.542.56-.94 1.11-.94h2.593c.55 0 1.02.398 1.11.94l.213 1.281c.063.374.313.686.645.87.074.04.147.083.22.127.325.196.72.257 1.075.124l1.217-.456a1.125 1.125 0 0 1 1.37.49l1.296 2.247a1.125 1.125 0 0 1-.26 1.431l-1.003.827c-.293.241-.438.613-.43.992a7.723 7.723 0 0 1 0 .255c-.008.378.137.75.43.991l1.004.827c.424.35.534.955.26 1.43l-1.298 2.247a1.125 1.125 0 0 1-1.369.491l-1.217-.456c-.355-.133-.75-.072-1.076.124a6.47 6.47 0 0 1-.22.128c-.331.183-.581.495-.644.869l-.213 1.281c-.09.543-.56.94-1.11.94h-2.594c-.55 0-1.019-.398-1.11-.94l-.213-1.281c-.062-.374-.312-.686-.644-.87a6.52 6.52 0 0 1-.22-.127c-.325-.196-.72-.257-1.076-.124l-1.217.456a1.125 1.125 0 0 1-1.369-.49l-1.297-2.247a1.125 1.125 0 0 1 .26-1.431l1.004-.827c.292-.24.437-.613.43-.991a6.932 6.932 0 0 1 0-.255c.007-.38-.138-.751-.43-.992l-1.004-.827a1.125 1.125 0 0 1-.26-1.43l1.297-2.247a1.125 1.125 0 0 1 1.37-.491l1.216.456c.356.133.751.072 1.076-.124.072-.044.146-.086.22-.128.332-.183.582-.495.644-.869l.214-1.28Z"
/>
<path
stroke-linecap="round"
stroke-linejoin="round"
d="M15 12a3 3 0 1 1-6 0 3 3 0 0 1 6 0Z"
/>
</svg>
<span className="badge badge-xs badge-primary indicator-item"></span>
</div>
</button>
</div>
</div>
{/* <div
className="relative cursor-pointer rounded p-2"
<div
className="cursor-pointer rounded bg-cyan-300 dark:text-white p-1 dark:bg-cyan-800"
onClick={() => setShowSettings(true)}
>
<button
className="absolute right-1 rounded p-1 m-1"
onClick={(event) => {
// stop propagation to parent
event.stopPropagation();
setShowSearch(true);
}}
>
<MagnifyingGlassIcon className="w-5 h-5" />
</button>
<div className="hidden lg:inline-grid"></div>
<div className="lg:hidden">
<div>
<button className="underline">
{chatStore.systemMessageContent.length > 16
? chatStore.systemMessageContent.slice(0, 16) + ".."
: chatStore.systemMessageContent}
</button>{" "}
<button className="underline">
{chatStore.streamMode ? Tr("STREAM") : Tr("FETCH")}
</button>{" "}
{chatStore.toolsString.trim() && (
<button className="underline">TOOL</button>
)}
</div>
<div className="text-xs">
<span className="underline">{chatStore.model}</span>{" "}
<span>
Tokens:{" "}
<span className="underline">
{chatStore.totalTokens}/{chatStore.maxTokens}
</span>
</span>{" "}
<span>
{Tr("Cut")}:{" "}
<span className="underline">
{chatStore.postBeginIndex}/
{chatStore.history.filter(({ hide }) => !hide).length}
</span>{" "}
</span>{" "}
<span>
{Tr("Cost")}:{" "}
<span className="underline">${chatStore.cost.toFixed(4)}</span>
</span>
</div>
<div>
<button className="underline">
{chatStore.systemMessageContent.length > 16
? chatStore.systemMessageContent.slice(0, 16) + ".."
: chatStore.systemMessageContent}
</button>{" "}
<button className="underline">
{chatStore.streamMode ? Tr("STREAM") : Tr("FETCH")}
</button>{" "}
{chatStore.toolsString.trim() && (
<button className="underline">TOOL</button>
)}
</div>
</div> */}
<div className="text-xs">
<span className="underline">{chatStore.model}</span>{" "}
<span>
Tokens:{" "}
<span className="underline">
{chatStore.totalTokens}/{chatStore.maxTokens}
</span>
</span>{" "}
<span>
{Tr("Cut")}:{" "}
<span className="underline">
{chatStore.postBeginIndex}/
{chatStore.history.filter(({ hide }) => !hide).length}
</span>{" "}
</span>{" "}
<span>
{Tr("Cost")}:{" "}
<span className="underline">${chatStore.cost.toFixed(4)}</span>
</span>
</div>
</div>
<div className="grow overflow-scroll">
{!chatStore.apiKey && (
<p className="bg-base-200 p-6 rounded my-3 text-left">
<p className="opacity-60 p-6 rounded bg-white my-3 text-left dark:text-black">
{Tr("Please click above to set")} (OpenAI) API KEY
</p>
)}
{!chatStore.apiEndpoint && (
<p className="bg-base-200 p-6 rounded my-3 text-left">
<p className="opacity-60 p-6 rounded bg-white my-3 text-left dark:text-black">
{Tr("Please click above to set")} API Endpoint
</p>
)}
@@ -782,7 +545,7 @@ export default function ChatBOX(props: {
)}
{chatStore.history.filter((msg) => !msg.example).length == 0 && (
<div className="bg-base-200 break-all p-3 my-3 text-left">
<div className="break-all opacity-80 p-3 rounded bg-white my-3 text-left dark:text-black">
<h2>
<span>{Tr("Saved prompt templates")}</span>
<button
@@ -797,7 +560,7 @@ export default function ChatBOX(props: {
{Tr("Reset Current")}
</button>
</h2>
<div className="divider"></div>
<hr className="my-2" />
<div className="flex flex-wrap">
{templates.map((t, index) => (
<div
@@ -809,49 +572,49 @@ export default function ChatBOX(props: {
if (!newChatStore.apiEndpoint) {
newChatStore.apiEndpoint = getDefaultParams(
"api",
chatStore.apiEndpoint,
chatStore.apiEndpoint
);
}
if (!newChatStore.apiKey) {
newChatStore.apiKey = getDefaultParams(
"key",
chatStore.apiKey,
chatStore.apiKey
);
}
if (!newChatStore.whisper_api) {
newChatStore.whisper_api = getDefaultParams(
"whisper-api",
chatStore.whisper_api,
chatStore.whisper_api
);
}
if (!newChatStore.whisper_key) {
newChatStore.whisper_key = getDefaultParams(
"whisper-key",
chatStore.whisper_key,
chatStore.whisper_key
);
}
if (!newChatStore.tts_api) {
newChatStore.tts_api = getDefaultParams(
"tts-api",
chatStore.tts_api,
chatStore.tts_api
);
}
if (!newChatStore.tts_key) {
newChatStore.tts_key = getDefaultParams(
"tts-key",
chatStore.tts_key,
chatStore.tts_key
);
}
if (!newChatStore.image_gen_api) {
newChatStore.image_gen_api = getDefaultParams(
"image-gen-api",
chatStore.image_gen_api,
chatStore.image_gen_api
);
}
if (!newChatStore.image_gen_key) {
newChatStore.image_gen_key = getDefaultParams(
"image-gen-key",
chatStore.image_gen_key,
chatStore.image_gen_key
);
}
newChatStore.cost = 0;
@@ -908,23 +671,11 @@ export default function ChatBOX(props: {
<br />{Tr("Click the conor to create a new chat")}
<br />
{Tr(
"All chat history and settings are stored in the local browser",
"All chat history and settings are stored in the local browser"
)}
<br />
</p>
)}
{chatStore.systemMessageContent.trim() && (
<div className="chat chat-start">
<div className="chat-header">Prompt</div>
<div
className="chat-bubble chat-bubble-accent cursor-pointer message-content"
onClick={() => setShowSettings(true)}
>
{chatStore.systemMessageContent}
</div>
</div>
)}
{chatStore.history.map((_, messageIndex) => (
<Message
chatStore={chatStore}
@@ -934,7 +685,7 @@ export default function ChatBOX(props: {
/>
))}
{showGenerating && (
<p className="p-2 my-2 animate-pulse message-content">
<p className="p-2 my-2 animate-pulse dark:text-white message-content">
{generatingMessage || Tr("Generating...")}
...
</p>
@@ -942,7 +693,7 @@ export default function ChatBOX(props: {
<p className="text-center">
{chatStore.history.length > 0 && (
<button
className="btn btn-sm btn-warning disabled:line-through disabled:btn-neutral disabled:text-white m-2 p-2"
className="disabled:line-through disabled:bg-slate-500 rounded m-2 p-2 border-2 bg-teal-500 hover:bg-teal-600"
disabled={showGenerating}
onClick={async () => {
const messageIndex = chatStore.history.length - 1;
@@ -962,7 +713,7 @@ export default function ChatBOX(props: {
)}
{chatStore.develop_mode && chatStore.history.length > 0 && (
<button
className="btn btn-outline btn-sm btn-warning disabled:line-through disabled:bg-neural"
className="disabled:line-through disabled:bg-slate-500 rounded m-2 p-2 border-2 bg-yellow-500 hover:bg-yellow-600"
disabled={showGenerating}
onClick={async () => {
await complete();
@@ -1053,29 +804,19 @@ export default function ChatBOX(props: {
</div>
)}
{generatingMessage && (
<span
className="p-2 m-2 rounded bg-white dark:text-black dark:bg-white dark:bg-opacity-50"
style={{ textAlign: "right" }}
onClick={() => {
setFollow(!follow);
}}
>
<label>Follow</label>
<input type="checkbox" checked={follow} />
</span>
)}
<div className="flex justify-between my-1">
<button
className="btn btn-primary disabled:line-through disabled:text-white disabled:bg-neutral m-1 p-1"
disabled={showGenerating || !chatStore.apiKey}
onClick={() => {
setShowAddImage(!showAddImage);
}}
>
Image
</button>
<div className="flex justify-between">
{(chatStore.model.match("vision") ||
(chatStore.image_gen_api && chatStore.image_gen_key)) && (
<button
className="disabled:line-through disabled:bg-slate-500 rounded m-1 p-1 border-2 bg-cyan-400 hover:bg-cyan-600"
disabled={showGenerating || !chatStore.apiKey}
onClick={() => {
setShowAddImage(!showAddImage);
}}
>
Img
</button>
)}
{showAddImage && (
<AddImage
chatStore={chatStore}
@@ -1105,14 +846,11 @@ export default function ChatBOX(props: {
autoHeight(event.target);
setInputMsg(event.target.value);
}}
className="textarea textarea-bordered textarea-sm grow w-0"
style={{
lineHeight: "1.39",
}}
className="rounded grow m-1 p-1 border-2 border-gray-400 w-0"
placeholder="Type here..."
></textarea>
<button
className="btn btn-primary disabled:btn-neutral disabled:line-through m-1 p-1"
className="disabled:line-through disabled:bg-slate-500 rounded m-1 p-1 border-2 bg-cyan-400 hover:bg-cyan-600"
disabled={showGenerating}
onClick={() => {
send(inputMsg, true);
@@ -1126,8 +864,10 @@ export default function ChatBOX(props: {
chatStore.whisper_key &&
(chatStore.whisper_key || chatStore.apiKey) && (
<button
className={`btn disabled:line-through disabled:btn-neutral disabled:text-white m-1 p-1 ${
isRecording === "Recording" ? "btn-error" : "btn-success"
className={`disabled:line-through disabled:bg-slate-500 rounded m-1 p-1 border-2 ${
isRecording === "Recording"
? "bg-red-400 hover:bg-red-600"
: "bg-cyan-400 hover:bg-cyan-600"
} ${isRecording !== "Mic" ? "animate-pulse" : ""}`}
disabled={isRecording === "Transcribing"}
ref={mediaRef}
@@ -1151,7 +891,7 @@ export default function ChatBOX(props: {
} else {
return content.map((c) => c?.text).join(" ");
}
}),
})
)
.concat([inputMsg])
.join(" ");
@@ -1165,7 +905,7 @@ export default function ChatBOX(props: {
await navigator.mediaDevices.getUserMedia({
audio: true,
}),
{ audioBitsPerSecond: 64 * 1000 },
{ audioBitsPerSecond: 64 * 1000 }
);
// mount mediaRecorder to ref
@@ -1242,7 +982,7 @@ export default function ChatBOX(props: {
)}
{chatStore.develop_mode && (
<button
className="btn disabled:line-through disabled:btn-neutral disabled:text-white m-1 p-1"
className="disabled:line-through disabled:bg-slate-500 rounded m-1 p-1 border-2 bg-cyan-400 hover:bg-cyan-600"
disabled={showGenerating || !chatStore.apiKey}
onClick={() => {
chatStore.history.push({
@@ -1266,7 +1006,7 @@ export default function ChatBOX(props: {
)}
{chatStore.develop_mode && (
<button
className="btn disabled:line-through disabled:btn-neutral disabled:text-white m-1 p-1"
className="disabled:line-through disabled:bg-slate-500 rounded m-1 p-1 border-2 bg-cyan-400 hover:bg-cyan-600"
disabled={showGenerating || !chatStore.apiKey}
onClick={() => {
send(inputMsg, false);
@@ -1277,7 +1017,7 @@ export default function ChatBOX(props: {
)}
{chatStore.develop_mode && (
<button
className="btn disabled:line-through disabled:btn-neutral disabled:text-white m-1 p-1"
className="disabled:line-through disabled:bg-slate-500 rounded m-1 p-1 border-2 bg-cyan-400 hover:bg-cyan-600"
disabled={showGenerating || !chatStore.apiKey}
onClick={() => {
setShowAddToolMsg(true);
@@ -1325,7 +1065,7 @@ export default function ChatBOX(props: {
</span>
<span className={`flex justify-between p-2`}>
<button
className="btn btn-info m-1 p-1"
className="rounded m-1 p-1 border-2 bg-red-400 hover:bg-red-600"
onClick={() => setShowAddToolMsg(false)}
>
{Tr("Cancle")}

View File

@@ -1,5 +1,3 @@
import { defaultModel } from "@/models";
export interface ImageURL {
url: string;
detail: "low" | "high";
@@ -110,7 +108,7 @@ function calculate_token_length_from_text(text: string): number {
}
// https://help.openai.com/en/articles/4936856-what-are-tokens-and-how-to-count-them
export function calculate_token_length(
content: string | MessageDetail[],
content: string | MessageDetail[]
): number {
if (typeof content === "string") {
return calculate_token_length_from_text(content);
@@ -157,7 +155,7 @@ class Chat {
enable_max_gen_tokens = true,
tokens_margin = 1024,
apiEndPoint = "https://api.openai.com/v1/chat/completions",
model = defaultModel,
model = "gpt-3.5-turbo",
temperature = 0.7,
enable_temperature = true,
top_p = 1,
@@ -165,7 +163,7 @@ class Chat {
presence_penalty = 0,
frequency_penalty = 0,
json_mode = false,
} = {},
} = {}
) {
this.OPENAI_API_KEY = OPENAI_API_KEY ?? "";
this.messages = [];
@@ -200,14 +198,14 @@ class Chat {
}
if (msg.role === "system") {
console.log(
"Warning: detected system message in the middle of history",
"Warning: detected system message in the middle of history"
);
}
}
for (const msg of this.messages) {
if (msg.name && msg.role !== "system") {
console.log(
"Warning: detected message where name field set but role is system",
"Warning: detected message where name field set but role is system"
);
}
}

View File

@@ -1,13 +1,15 @@
import { useState, useEffect, StateUpdater, Dispatch } from "preact/hooks";
import { Tr, langCodeContext, LANG_OPTIONS, tr } from "@/translate";
import { ChatStore, ChatStoreMessage } from "@/app";
import { EditMessageString } from "@/editMessageString";
import { EditMessageDetail } from "@/editMessageDetail";
import { Tr, langCodeContext, LANG_OPTIONS, tr } from "./translate";
import { useState, useEffect, StateUpdater } from "preact/hooks";
import { ChatStore, ChatStoreMessage } from "./app";
import { calculate_token_length, getMessageText } from "./chatgpt";
import { isVailedJSON } from "./message";
import { EditMessageString } from "./editMessageString";
import { EditMessageDetail } from "./editMessageDetail";
interface EditMessageProps {
chat: ChatStoreMessage;
chatStore: ChatStore;
setShowEdit: Dispatch<StateUpdater<boolean>>;
setShowEdit: StateUpdater<boolean>;
setChatStore: (cs: ChatStore) => void;
}
export function EditMessage(props: EditMessageProps) {
@@ -42,29 +44,17 @@ export function EditMessage(props: EditMessageProps) {
/>
)}
<div className={"w-full flex justify-center"}>
{chatStore.develop_mode && (
<button
className="w-full m-2 p-1 rounded bg-red-500"
onClick={() => {
const confirm = window.confirm(
"Change message type will clear the content, are you sure?",
);
if (!confirm) return;
if (typeof chat.content === "string") {
chat.content = [];
} else {
chat.content = "";
}
setChatStore({ ...chatStore });
}}
>
Switch to{" "}
{typeof chat.content === "string"
? "media message"
: "string message"}
</button>
)}
{chatStore.develop_mode && <button
className="w-full m-2 p-1 rounded bg-red-500"
onClick={() => {
if (typeof chat.content === "string") {
chat.content = []
} else {
chat.content = ''
}
setChatStore({ ...chatStore })
}}
>Switch to {typeof chat.content === 'string' ? "media message" : "string message"}</button>}
<button
className={"w-full m-2 p-1 rounded bg-purple-500"}
onClick={() => {

View File

@@ -1,6 +1,6 @@
import { ChatStore, ChatStoreMessage } from "@/app";
import { calculate_token_length } from "@/chatgpt";
import { Tr } from "@/translate";
import { ChatStore, ChatStoreMessage } from "./app";
import { calculate_token_length } from "./chatgpt";
import { Tr } from "./translate";
interface Props {
chat: ChatStoreMessage;
@@ -22,10 +22,10 @@ export function EditMessageDetail({
>
{chat.content.map((mdt, index) => (
<div className={"w-full p-2 px-4"}>
<div className="flex justify-center">
<div className="flex justify-between">
{mdt.type === "text" ? (
<textarea
className={"w-full border p-1 rounded"}
className={"w-full"}
value={mdt.text}
onChange={(event: any) => {
if (typeof chat.content === "string") return;
@@ -41,16 +41,16 @@ export function EditMessageDetail({
}}
></textarea>
) : (
<div className="border p-1 rounded">
<>
<img
className="max-h-32 max-w-xs cursor-pointer m-2"
className="max-h-32 max-w-xs cursor-pointer"
src={mdt.image_url?.url}
onClick={() => {
window.open(mdt.image_url?.url, "_blank");
}}
/>
<button
className="bg-blue-300 p-1 rounded m-1"
className="bg-blue-300 p-1 rounded"
onClick={() => {
const image_url = prompt("image url", mdt.image_url?.url);
if (image_url) {
@@ -65,7 +65,7 @@ export function EditMessageDetail({
{Tr("Edit URL")}
</button>
<button
className="bg-blue-300 p-1 rounded m-1"
className="bg-blue-300 p-1 rounded"
onClick={() => {
// select file and load it to base64 image URL format
const input = document.createElement("input");
@@ -95,7 +95,7 @@ export function EditMessageDetail({
{Tr("Upload")}
</button>
<span
className="bg-blue-300 p-1 rounded m-1"
className="bg-blue-300 p-1 rounded"
onClick={() => {
if (typeof chat.content === "string") return;
const obj = chat.content[index].image_url;
@@ -111,7 +111,7 @@ export function EditMessageDetail({
checked={mdt.image_url?.detail === "high"}
/>
</span>
</div>
</>
)}
<button

View File

@@ -1,7 +1,7 @@
import { ChatStore, ChatStoreMessage } from "@/app";
import { isVailedJSON } from "@/message";
import { calculate_token_length } from "@/chatgpt";
import { Tr } from "@/translate";
import { ChatStore, ChatStoreMessage } from "./app";
import { isVailedJSON } from "./message";
import { calculate_token_length } from "./chatgpt";
import { Tr } from "./translate";
interface Props {
chat: ChatStoreMessage;
@@ -69,7 +69,7 @@ export function EditMessageString({
onClick={() => {
if (!chat.tool_calls) return;
chat.tool_calls = chat.tool_calls.filter(
(tc) => tc.id !== tool_call.id,
(tc) => tc.id !== tool_call.id
);
setChatStore({ ...chatStore });
}}

View File

@@ -30,7 +30,6 @@ body::-webkit-scrollbar {
.message-content {
white-space: pre-wrap;
word-wrap: anywhere;
}
.markup > h2 {
@@ -79,14 +78,8 @@ body::-webkit-scrollbar {
white-space: break-space;
background-color: rgba(175, 184, 193, 0.2);
border-radius: 6px;
font-family:
ui-monospace,
SFMono-Regular,
SF Mono,
Menlo,
Consolas,
Liberation Mono,
monospace;
font-family: ui-monospace, SFMono-Regular, SF Mono, Menlo, Consolas,
Liberation Mono, monospace;
}
.markup > pre {
@@ -145,7 +138,3 @@ body::-webkit-scrollbar {
background-color: #f5f5f5;
z-index: -1;
}
.stat {
padding: 0.39rem;
}

View File

@@ -1,5 +1,5 @@
import { ChatStore, TemplateAPI } from "@/app";
import { Tr } from "@/translate";
import { ChatStore, TemplateAPI } from "./app";
import { Tr } from "./translate";
interface Props {
chatStore: ChatStore;
@@ -20,7 +20,7 @@ export function ListAPIs({
keyField,
}: Props) {
return (
<div className="break-all opacity-80 p-3 rounded base-200 my-3 text-left">
<div className="break-all opacity-80 p-3 rounded bg-white my-3 text-left dark:text-black">
<h2>{Tr(`Saved ${label} templates`)}</h2>
<hr className="my-2" />
<div className="flex flex-wrap">
@@ -31,8 +31,8 @@ export function ListAPIs({
chatStore[apiField] === t.endpoint &&
// @ts-ignore
chatStore[keyField] === t.key
? "bg-info"
: "bg-base-300"
? "bg-red-600"
: "bg-red-400"
} w-fit p-2 m-1 flex flex-col`}
onClick={() => {
// @ts-ignore
@@ -43,9 +43,9 @@ export function ListAPIs({
}}
>
<span className="w-full text-center">{t.name}</span>
<span className="flex justify-between gap-x-2">
<hr className="mt-2" />
<span className="flex justify-between">
<button
className="link"
onClick={() => {
const name = prompt(`Give **${label}** template a name`);
if (!name) {
@@ -55,14 +55,13 @@ export function ListAPIs({
setTmps(structuredClone(tmps));
}}
>
Edit
🖋
</button>
<button
className="link"
onClick={() => {
if (
!confirm(
`Are you sure to delete this **${label}** template?`,
`Are you sure to delete this **${label}** template?`
)
) {
return;
@@ -71,7 +70,7 @@ export function ListAPIs({
setTmps(structuredClone(tmps));
}}
>
Delete
</button>
</span>
</div>

View File

@@ -1,5 +1,5 @@
import { ChatStore, TemplateTools } from "@/app";
import { Tr } from "@/translate";
import { ChatStore, TemplateTools } from "./app";
import { Tr } from "./translate";
interface Props {
templateTools: TemplateTools[];
@@ -33,8 +33,8 @@ export function ListToolsTempaltes({
<div
className={`cursor-pointer rounded ${
chatStore.toolsString === t.toolsString
? "bg-info"
: "bg-base-300"
? "bg-red-600"
: "bg-red-400"
} w-fit p-2 m-1 flex flex-col`}
onClick={() => {
chatStore.toolsString = t.toolsString;
@@ -42,9 +42,9 @@ export function ListToolsTempaltes({
}}
>
<span className="w-full text-center">{t.name}</span>
<span className="flex justify-between gap-x-2">
<hr className="mt-2" />
<span className="flex justify-between">
<button
className="link"
onClick={() => {
const name = prompt(`Give **tools** template a name`);
if (!name) {
@@ -54,10 +54,9 @@ export function ListToolsTempaltes({
setTemplateTools(structuredClone(templateTools));
}}
>
Edit
🖋
</button>
<button
className="link"
onClick={() => {
if (
!confirm(`Are you sure to delete this **tools** template?`)
@@ -68,7 +67,7 @@ export function ListToolsTempaltes({
setTemplateTools(structuredClone(templateTools));
}}
>
Delete
</button>
</span>
</div>

View File

@@ -6,7 +6,7 @@ const logprobToColor = (logprob: number) => {
// 绿色的RGB值为(0, 255, 0)红色的RGB值为(255, 0, 0)
const red = Math.round(255 * (1 - percent / 100));
const green = Math.round(255 * (percent / 100));
const color = `rgba(${red}, ${green}, 0, 0.5)`;
const color = `rgb(${red}, ${green}, 0)`;
return color;
};

View File

@@ -1,29 +1,27 @@
import { themeChange } from "theme-change";
import { render } from "preact";
import { App } from "./app";
import { useState, useEffect } from "preact/hooks";
import { App } from "@/app";
import { Tr, langCodeContext, LANG_OPTIONS } from "@/translate";
import { Tr, langCodeContext, LANG_OPTIONS } from "./translate";
function Base() {
const [langCode, _setLangCode] = useState("en-US");
const setLangCode = (langCode: string) => {
_setLangCode(langCode);
if (!localStorage) return;
_setLangCode(langCode)
if (!localStorage) return
localStorage.setItem("chatgpt-api-web-lang", langCode);
};
localStorage.setItem('chatgpt-api-web-lang', langCode)
}
// select language
useEffect(() => {
themeChange(false);
// query localStorage
if (localStorage) {
const lang = localStorage.getItem("chatgpt-api-web-lang");
const lang = localStorage.getItem('chatgpt-api-web-lang')
if (lang) {
console.log(`query langCode ${lang} from localStorage`);
_setLangCode(lang);
return;
console.log(`query langCode ${lang} from localStorage`)
_setLangCode(lang)
return
}
}

View File

@@ -1,17 +1,15 @@
import { XMarkIcon } from "@heroicons/react/24/outline";
import Markdown from "preact-markdown";
import { Tr, langCodeContext, LANG_OPTIONS } from "./translate";
import { useState, useEffect, StateUpdater } from "preact/hooks";
import { Tr, langCodeContext, LANG_OPTIONS } from "@/translate";
import { ChatStore, ChatStoreMessage } from "@/app";
import { calculate_token_length, getMessageText } from "@/chatgpt";
import TTSButton, { TTSPlay } from "@/tts";
import { MessageHide } from "@/messageHide";
import { MessageDetail } from "@/messageDetail";
import { MessageToolCall } from "@/messageToolCall";
import { MessageToolResp } from "@/messageToolResp";
import { EditMessage } from "@/editMessage";
import logprobToColor from "@/logprob";
import { ChatStore, ChatStoreMessage } from "./app";
import { calculate_token_length, getMessageText } from "./chatgpt";
import Markdown from "preact-markdown";
import TTSButton, { TTSPlay } from "./tts";
import { MessageHide } from "./messageHide";
import { MessageDetail } from "./messageDetail";
import { MessageToolCall } from "./messageToolCall";
import { MessageToolResp } from "./messageToolResp";
import { EditMessage } from "./editMessage";
import logprobToColor from "./logprob";
export const isVailedJSON = (str: string): boolean => {
try {
@@ -53,26 +51,17 @@ export default function Message(props: Props) {
setChatStore({ ...chatStore });
}}
>
Delete
🗑
</button>
);
const CopiedHint = () => (
<div role="alert" className="alert">
<svg
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
className="stroke-info h-6 w-6 shrink-0"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"
></path>
</svg>
<span>{Tr("Message copied to clipboard!")}</span>
</div>
<span
className={
"bg-purple-400 p-1 rounded shadow-md absolute z-20 left-1/2 top-3/4 transform -translate-x-1/2 -translate-y-1/2"
}
>
{Tr("Message copied to clipboard!")}
</span>
);
const copyToClipboard = (text: string) => {
@@ -89,7 +78,7 @@ export default function Message(props: Props) {
copyToClipboard(textToCopy);
}}
>
Copy
📋
</button>
</>
);
@@ -103,8 +92,8 @@ export default function Message(props: Props) {
chatStore.history.slice(0, messageIndex).filter(({ hide }) => !hide)
.length && (
<div className="flex items-center relative justify-center">
<hr className="w-full h-px my-4 border-0" />
<span className="absolute px-3 rounded p-1">
<hr className="w-full h-px my-4 border-0 bg-slate-800 dark:bg-white" />
<span className="absolute px-3 bg-slate-800 text-white rounded p-1 dark:bg-white dark:text-black">
Above messages are "forgotten"
</span>
</div>
@@ -114,66 +103,53 @@ export default function Message(props: Props) {
chat.role === "assistant" ? "justify-start" : "justify-end"
}`}
>
<div className={`w-full`}>
<div>
<div
className={`chat min-w-16 p-2 my-2 ${
chat.role === "assistant" ? "chat-start" : "chat-end"
className={`w-fit p-2 rounded my-2 ${
chat.role === "assistant"
? "bg-white dark:bg-gray-700 dark:text-white"
: "bg-green-400"
} ${chat.hide ? "opacity-50" : ""}`}
>
<div
className={`chat-bubble max-w-full ${
chat.role === "assistant"
? renderColor
? "chat-bubble-neutral"
: "chat-bubble-secondary"
: "chat-bubble-primary"
}`}
>
{chat.hide ? (
<MessageHide chat={chat} />
) : typeof chat.content !== "string" ? (
<MessageDetail chat={chat} renderMarkdown={renderMarkdown} />
) : chat.tool_calls ? (
<MessageToolCall
chat={chat}
copyToClipboard={copyToClipboard}
/>
) : chat.role === "tool" ? (
<MessageToolResp
chat={chat}
copyToClipboard={copyToClipboard}
/>
) : renderMarkdown ? (
// @ts-ignore
<Markdown markdown={getMessageText(chat)} />
) : (
<div className="message-content">
{
// only show when content is string or list of message
// this check is used to avoid rendering tool call
chat.content &&
(chat.logprobs && renderColor
? chat.logprobs.content
.filter((c) => c.token)
.map((c) => (
<div
style={{
backgroundColor: logprobToColor(c.logprob),
display: "inline",
}}
>
{c.token}
</div>
))
: getMessageText(chat))
}
</div>
)}
</div>
<div className="chat-footer opacity-50 flex gap-x-2">
{chat.hide ? (
<MessageHide chat={chat} />
) : typeof chat.content !== "string" ? (
<MessageDetail chat={chat} renderMarkdown={renderMarkdown} />
) : chat.tool_calls ? (
<MessageToolCall chat={chat} copyToClipboard={copyToClipboard} />
) : chat.role === "tool" ? (
<MessageToolResp chat={chat} copyToClipboard={copyToClipboard} />
) : renderMarkdown ? (
// @ts-ignore
<Markdown markdown={getMessageText(chat)} />
) : (
<div className="message-content">
{
// only show when content is string or list of message
// this check is used to avoid rendering tool call
chat.content &&
(chat.logprobs && renderColor
? chat.logprobs.content
.filter((c) => c.token)
.map((c) => (
<div
style={{
color: logprobToColor(c.logprob),
display: "inline",
}}
>
{c.token}
</div>
))
: getMessageText(chat))
}
</div>
)}
<hr className="mt-2" />
<TTSPlay chat={chat} />
<div className="w-full flex justify-between">
<DeleteIcon />
<button onClick={() => setShowEdit(true)}>Edit</button>
<CopyIcon textToCopy={getMessageText(chat)} />
<button onClick={() => setShowEdit(true)}>🖋</button>
{chatStore.tts_api && chatStore.tts_key && (
<TTSButton
chatStore={chatStore}
@@ -181,7 +157,7 @@ export default function Message(props: Props) {
setChatStore={setChatStore}
/>
)}
<TTSPlay chat={chat} />
<CopyIcon textToCopy={getMessageText(chat)} />
</div>
</div>
{showEdit && (
@@ -194,15 +170,11 @@ export default function Message(props: Props) {
)}
{showCopiedHint && <CopiedHint />}
{chatStore.develop_mode && (
<div
className={`gap-1 chat-end flex ${
chat.role === "assistant" ? "justify-start" : "justify-end"
}`}
>
<span className="">token</span>
<div>
<span className="dark:text-white">token</span>
<input
value={chat.token}
className="input input-bordered input-xs w-16"
className="w-20"
onChange={(event: any) => {
chat.token = parseInt(event.target.value);
props.update_total_tokens();
@@ -214,7 +186,7 @@ export default function Message(props: Props) {
chatStore.history.splice(messageIndex, 1);
chatStore.postBeginIndex = Math.max(
chatStore.postBeginIndex - 1,
0,
0
);
//chatStore.totalTokens =
chatStore.totalTokens = 0;
@@ -227,7 +199,7 @@ export default function Message(props: Props) {
setChatStore({ ...chatStore });
}}
>
<XMarkIcon className="w-4 h-4" />
</button>
<span
onClick={(event: any) => {
@@ -235,17 +207,17 @@ export default function Message(props: Props) {
setChatStore({ ...chatStore });
}}
>
<label className="">{Tr("example")}</label>
<label className="dark:text-white">{Tr("example")}</label>
<input type="checkbox" checked={chat.example} />
</span>
<span
onClick={(event: any) => setRenderWorkdown(!renderMarkdown)}
>
<label className="">{Tr("render")}</label>
<label className="dark:text-white">{Tr("render")}</label>
<input type="checkbox" checked={renderMarkdown} />
</span>
<span onClick={(event: any) => setRenderColor(!renderColor)}>
<label className="">{Tr("color")}</label>
<label className="dark:text-white">{Tr("color")}</label>
<input type="checkbox" checked={renderColor} />
</span>
</div>

View File

@@ -1,4 +1,4 @@
import { ChatStoreMessage } from "@/app";
import { ChatStoreMessage } from "./app";
interface Props {
chat: ChatStoreMessage;
@@ -13,7 +13,7 @@ export function MessageDetail({ chat, renderMarkdown }: Props) {
{chat.content.map((mdt) =>
mdt.type === "text" ? (
chat.hide ? (
mdt.text?.split("\n")[0].slice(0, 16) + " ..."
mdt.text?.split("\n")[0].slice(0, 16) + "... (deleted)"
) : renderMarkdown ? (
// @ts-ignore
<Markdown markdown={mdt.text} />
@@ -22,13 +22,13 @@ export function MessageDetail({ chat, renderMarkdown }: Props) {
)
) : (
<img
className="my-2 rounded-md max-w-64 max-h-64"
className="cursor-pointer max-w-xs max-h-32 p-1"
src={mdt.image_url?.url}
onClick={() => {
window.open(mdt.image_url?.url, "_blank");
}}
/>
),
)
)}
</div>
);

View File

@@ -1,10 +1,12 @@
import { ChatStoreMessage } from "@/app";
import { getMessageText } from "@/chatgpt";
import { ChatStoreMessage } from "./app";
import { getMessageText } from "./chatgpt";
interface Props {
chat: ChatStoreMessage;
}
export function MessageHide({ chat }: Props) {
return <div>{getMessageText(chat).split("\n")[0].slice(0, 18)} ...</div>;
return (
<div>{getMessageText(chat).split("\n")[0].slice(0, 18)} ... (deleted)</div>
);
}

View File

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

View File

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

View File

@@ -7,26 +7,6 @@ interface Model {
}
const models: Record<string, Model> = {
"gpt-4o": {
maxToken: 128000,
price: { prompt: 0.005 / 1000, completion: 0.015 / 1000 },
},
"gpt-4o-2024-08-06": {
maxToken: 128000,
price: { prompt: 0.0025 / 1000, completion: 0.01 / 1000 },
},
"gpt-4o-2024-05-13": {
maxToken: 128000,
price: { prompt: 0.005 / 1000, completion: 0.015 / 1000 },
},
"gpt-4o-mini": {
maxToken: 128000,
price: { prompt: 0.15 / 1000 / 1000, completion: 0.6 / 1000 / 1000 },
},
"gpt-4o-mini-2024-07-18": {
maxToken: 128000,
price: { prompt: 0.15 / 1000 / 1000, completion: 0.6 / 1000 / 1000 },
},
"gpt-3.5-turbo-0125": {
maxToken: 16385,
price: { prompt: 0.0005 / 1000, completion: 0.0015 / 1000 },
@@ -35,52 +15,12 @@ const models: Record<string, Model> = {
maxToken: 16385,
price: { prompt: 0.001 / 1000, completion: 0.002 / 1000 },
},
"gpt-3.5-turbo": {
maxToken: 4096,
price: { prompt: 0.0015 / 1000, completion: 0.002 / 1000 },
},
"gpt-3.5-turbo-16k": {
maxToken: 16385,
price: { prompt: 0.003 / 1000, completion: 0.004 / 1000 },
},
"gpt-4-turbo": {
maxToken: 128000,
price: { prompt: 0.01 / 1000, completion: 0.03 / 1000 },
},
"gpt-4-turbo-2024-04-09": {
maxToken: 128000,
price: { prompt: 0.01 / 1000, completion: 0.03 / 1000 },
},
"gpt-4-turbo-preview": {
maxToken: 128000,
price: { prompt: 0.01 / 1000, completion: 0.03 / 1000 },
},
"gpt-4-0125-preview": {
maxToken: 128000,
price: { prompt: 0.01 / 1000, completion: 0.03 / 1000 },
},
"gpt-4-1106-preview": {
maxToken: 128000,
price: { prompt: 0.01 / 1000, completion: 0.03 / 1000 },
},
"gpt-4-vision-preview": {
maxToken: 128000,
price: { prompt: 0.01 / 1000, completion: 0.03 / 1000 },
},
"gpt-4-1106-vision-preview": {
maxToken: 128000,
price: { prompt: 0.01 / 1000, completion: 0.03 / 1000 },
},
"gpt-4": {
maxToken: 8192,
price: { prompt: 0.03 / 1000, completion: 0.06 / 1000 },
},
"gpt-4-32k": {
maxToken: 8192,
price: { prompt: 0.06 / 1000, completion: 0.12 / 1000 },
},
};
export const defaultModel = "gpt-4o-mini";
export const defaultModel = "gpt-3.5-turbo-0125";
export default models;

View File

@@ -1,180 +0,0 @@
import { IDBPDatabase } from "idb";
import { StateUpdater, useRef, useState, Dispatch } from "preact/hooks";
import { ChatStore } from "@/app";
interface ChatStoreSearchResult {
key: IDBValidKey;
cs: ChatStore;
query: string;
preview: string;
}
export default function Search(props: {
db: Promise<IDBPDatabase<ChatStore>>;
setSelectedChatIndex: Dispatch<StateUpdater<number>>;
chatStore: ChatStore;
setShow: (show: boolean) => void;
}) {
const [searchResult, setSearchResult] = useState<ChatStoreSearchResult[]>([]);
const [searching, setSearching] = useState<boolean>(false);
const [searchingNow, setSearchingNow] = useState<number>(0);
const [pageIndex, setPageIndex] = useState<number>(0);
const searchAbortRef = useRef<AbortController | null>(null);
return (
<div
onClick={() => props.setShow(false)}
className="left-0 top-0 overflow-scroll flex justify-center absolute w-screen h-full bg-black bg-opacity-50 z-10"
>
<div
onClick={(event: any) => {
event.stopPropagation();
}}
className="m-2 p-2 bg-base-300 rounded-lg h-fit w-2/3 z-20"
>
<div className="flex justify-between">
<span className="m-1 p-1 font-bold">Search</span>
<button
className="m-1 p-1 btn btn-sm btn-secondary"
onClick={() => props.setShow(false)}
>
Close
</button>
</div>
<div>
<input
autoFocus
className="input input-bordered w-full border"
type="text"
placeholder="Type Something..."
onInput={async (event: any) => {
const query = event.target.value.trim().toLowerCase();
if (!query) {
setSearchResult([]);
return;
}
// abort previous search
if (searchAbortRef.current) {
searchAbortRef.current.abort();
}
// Create a new AbortController for the new operation
const abortController = new AbortController();
searchAbortRef.current = abortController;
const signal = abortController.signal;
setSearching(true);
const db = await props.db;
const resultKeys = await db.getAllKeys("chatgpt-api-web");
const result: ChatStoreSearchResult[] = [];
for (const key of resultKeys) {
// abort the operation if the signal is set
if (signal.aborted) {
return;
}
const now = Math.floor(
(result.length / resultKeys.length) * 100,
);
if (now !== searchingNow) setSearchingNow(now);
const value: ChatStore = await db.get("chatgpt-api-web", key);
const content = value.contents_for_index
.join(" ")
.toLowerCase();
if (content.includes(query)) {
const beginIndex: number = content.indexOf(query);
const preview = content.slice(
Math.max(0, beginIndex - 100),
Math.min(content.length, beginIndex + 239),
);
result.push({
key,
cs: value,
query: query,
preview: preview,
});
}
}
// sort by key desc
result.sort((a, b) => {
if (a.key < b.key) {
return 1;
}
if (a.key > b.key) {
return -1;
}
return 0;
});
console.log(result);
setPageIndex(0);
setSearchResult(result);
setSearching(false);
}}
/>
</div>
{searching && <div>Searching {searchingNow}%...</div>}
<div>
{searchResult
.slice(pageIndex * 10, (pageIndex + 1) * 10)
.map((result: ChatStoreSearchResult) => {
return (
<div
className="flex justify-start p-1 m-1 rounded border bg-base-200 cursor-pointer"
key={result.key}
onClick={() => {
props.setSelectedChatIndex(parseInt(result.key.toString()));
props.setShow(false);
}}
>
<div className="m-1 p-1 font-bold">{result.key}</div>
<div className="m-1 p-1">{result.preview}</div>
</div>
);
})}
</div>
{searchResult.length > 0 && (
<div className="flex justify-center my-2">
<div className="join">
<button
className="join-item btn btn-sm"
disabled={pageIndex === 0}
onClick={() => {
if (pageIndex === 0) {
return;
}
setPageIndex(pageIndex - 1);
}}
>
«
</button>
<button className="join-item btn btn-sm">
Page {pageIndex + 1} /{" "}
{Math.floor(searchResult.length / 10) + 1}
</button>
<button
className="join-item btn btn-sm"
disabled={pageIndex === Math.floor(searchResult.length / 10)}
onClick={() => {
if (pageIndex === Math.floor(searchResult.length / 10)) {
return;
}
setPageIndex(pageIndex + 1);
}}
>
»
</button>
</div>
</div>
)}
</div>
</div>
);
}

View File

@@ -1,5 +1,5 @@
import { TemplateAPI } from "@/app";
import { Tr } from "@/translate";
import { TemplateAPI } from "./app";
import { Tr } from "./translate";
interface Props {
tmps: TemplateAPI[];
@@ -17,7 +17,7 @@ export function SetAPIsTemplate({
}: Props) {
return (
<button
className="btn btn-primary btn-sm mt-3"
className="p-1 m-1 rounded bg-blue-300"
onClick={() => {
const name = prompt(`Give this **${label}** template a name:`);
if (!name) {

File diff suppressed because it is too large Load Diff

View File

@@ -3,7 +3,7 @@ export const autoHeight = (target: any) => {
// max 70% of screen height
target.style.height = `${Math.min(
target.scrollHeight,
window.innerHeight * 0.7,
window.innerHeight * 0.7
)}px`;
console.log("set auto height", target.style.height);
};

View File

@@ -1,5 +1,5 @@
import { createContext } from "preact";
import MAP_zh_CN from "@/translate/zh_CN";
import MAP_zh_CN from "./zh_CN";
interface LangOption {
name: string;

View File

@@ -1,8 +1,6 @@
import { SpeakerWaveIcon } from "@heroicons/react/24/outline";
import { useMemo, useState } from "preact/hooks";
import { ChatStore, ChatStoreMessage, addTotalCost } from "@/app";
import { Message, getMessageText } from "@/chatgpt";
import { ChatStore, ChatStoreMessage, addTotalCost } from "./app";
import { Message, getMessageText } from "./chatgpt";
interface TTSProps {
chatStore: ChatStore;
@@ -80,11 +78,7 @@ export default function TTSButton(props: TTSProps) {
});
}}
>
{generating ? (
<span className="loading loading-dots loading-xs"></span>
) : (
<SpeakerWaveIcon className="h-4 w-4" />
)}
{generating ? "🤔" : "🔈"}
</button>
);
}

View File

@@ -1,42 +1,8 @@
/** @type {import('tailwindcss').Config} */
module.exports = {
content: ["./index.html", "./src/**/*.{js,ts,jsx,tsx}"],
daisyui: {
themes: ["light",
"dark",
"cupcake",
"bumblebee",
"emerald",
"corporate",
"synthwave",
"retro",
"cyberpunk",
"valentine",
"halloween",
"garden",
"forest",
"aqua",
"lofi",
"pastel",
"fantasy",
"wireframe",
"black",
"luxury",
"dracula",
"cmyk",
"autumn",
"business",
"acid",
"lemonade",
"night",
"coffee",
"winter",
"dim",
"nord",
"sunset",],
},
theme: {
extend: {},
},
plugins: [require('daisyui')],
plugins: [],
};

View File

@@ -1,9 +1,5 @@
{
"compilerOptions": {
"baseUrl": "src",
"paths": {
"@/*": ["*"]
},
"target": "ESNext",
"useDefineForClassFields": true,
"lib": ["DOM", "DOM.Iterable", "ESNext"],

View File

@@ -1,14 +1,8 @@
import { defineConfig } from 'vite'
import preact from '@preact/preset-vite'
import path from 'path'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [preact()],
base: './',
resolve: {
alias: {
'@': path.resolve(__dirname, 'src')
}
}
})

983
yarn.lock

File diff suppressed because it is too large Load Diff