Merge branch 'main' of https://github.com/pBrambi/ChatGPT-Next-Web
@ -0,0 +1,71 @@
|
||||
import { NextRequest } from "next/server";
|
||||
import { getServerSideConfig } from "../config/server";
|
||||
import md5 from "spark-md5";
|
||||
import { ACCESS_CODE_PREFIX } from "../constant";
|
||||
|
||||
const serverConfig = getServerSideConfig();
|
||||
|
||||
function getIP(req: NextRequest) {
|
||||
let ip = req.ip ?? req.headers.get("x-real-ip");
|
||||
const forwardedFor = req.headers.get("x-forwarded-for");
|
||||
|
||||
if (!ip && forwardedFor) {
|
||||
ip = forwardedFor.split(",").at(0) ?? "";
|
||||
}
|
||||
|
||||
return ip;
|
||||
}
|
||||
|
||||
function parseApiKey(bearToken: string) {
|
||||
const token = bearToken.trim().replaceAll("Bearer ", "").trim();
|
||||
const isOpenAiKey = !token.startsWith(ACCESS_CODE_PREFIX);
|
||||
|
||||
return {
|
||||
accessCode: isOpenAiKey ? "" : token.slice(ACCESS_CODE_PREFIX.length),
|
||||
apiKey: isOpenAiKey ? token : "",
|
||||
};
|
||||
}
|
||||
|
||||
export function auth(req: NextRequest) {
|
||||
const authToken = req.headers.get("Authorization") ?? "";
|
||||
|
||||
// check if it is openai api key or user token
|
||||
const { accessCode, apiKey: token } = parseApiKey(authToken);
|
||||
|
||||
const hashedCode = md5.hash(accessCode ?? "").trim();
|
||||
|
||||
console.log("[Auth] allowed hashed codes: ", [...serverConfig.codes]);
|
||||
console.log("[Auth] got access code:", accessCode);
|
||||
console.log("[Auth] hashed access code:", hashedCode);
|
||||
console.log("[User IP] ", getIP(req));
|
||||
console.log("[Time] ", new Date().toLocaleString());
|
||||
|
||||
if (serverConfig.needCode && !serverConfig.codes.has(hashedCode) && !token) {
|
||||
return {
|
||||
error: true,
|
||||
needAccessCode: true,
|
||||
msg: "Please go settings page and fill your access code.",
|
||||
};
|
||||
}
|
||||
|
||||
// if user does not provide an api key, inject system api key
|
||||
if (!token) {
|
||||
const apiKey = serverConfig.apiKey;
|
||||
if (apiKey) {
|
||||
console.log("[Auth] use system api key");
|
||||
req.headers.set("Authorization", `Bearer ${apiKey}`);
|
||||
} else {
|
||||
console.log("[Auth] admin did not provide an api key");
|
||||
return {
|
||||
error: true,
|
||||
msg: "Empty Api Key",
|
||||
};
|
||||
}
|
||||
} else {
|
||||
console.log("[Auth] use user api key");
|
||||
}
|
||||
|
||||
return {
|
||||
error: false,
|
||||
};
|
||||
}
|
@ -1,64 +0,0 @@
|
||||
import { createParser } from "eventsource-parser";
|
||||
import { NextRequest } from "next/server";
|
||||
import { requestOpenai } from "../common";
|
||||
|
||||
async function createStream(req: NextRequest) {
|
||||
const encoder = new TextEncoder();
|
||||
const decoder = new TextDecoder();
|
||||
|
||||
const res = await requestOpenai(req);
|
||||
|
||||
const contentType = res.headers.get("Content-Type") ?? "";
|
||||
if (!contentType.includes("stream")) {
|
||||
const content = await (
|
||||
await res.text()
|
||||
).replace(/provided:.*. You/, "provided: ***. You");
|
||||
console.log("[Stream] error ", content);
|
||||
return "```json\n" + content + "```";
|
||||
}
|
||||
|
||||
const stream = new ReadableStream({
|
||||
async start(controller) {
|
||||
function onParse(event: any) {
|
||||
if (event.type === "event") {
|
||||
const data = event.data;
|
||||
// https://beta.openai.com/docs/api-reference/completions/create#completions/create-stream
|
||||
if (data === "[DONE]") {
|
||||
controller.close();
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const json = JSON.parse(data);
|
||||
const text = json.choices[0].delta.content;
|
||||
const queue = encoder.encode(text);
|
||||
controller.enqueue(queue);
|
||||
} catch (e) {
|
||||
controller.error(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const parser = createParser(onParse);
|
||||
for await (const chunk of res.body as any) {
|
||||
parser.feed(decoder.decode(chunk, { stream: true }));
|
||||
}
|
||||
},
|
||||
});
|
||||
return stream;
|
||||
}
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
try {
|
||||
const stream = await createStream(req);
|
||||
return new Response(stream);
|
||||
} catch (error) {
|
||||
console.error("[Chat Stream]", error);
|
||||
return new Response(
|
||||
["```json\n", JSON.stringify(error, null, " "), "\n```"].join(""),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export const config = {
|
||||
runtime: "edge",
|
||||
};
|
@ -0,0 +1,101 @@
|
||||
import { createParser } from "eventsource-parser";
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { auth } from "../../auth";
|
||||
import { requestOpenai } from "../../common";
|
||||
|
||||
async function createStream(res: Response) {
|
||||
const encoder = new TextEncoder();
|
||||
const decoder = new TextDecoder();
|
||||
|
||||
const stream = new ReadableStream({
|
||||
async start(controller) {
|
||||
function onParse(event: any) {
|
||||
if (event.type === "event") {
|
||||
const data = event.data;
|
||||
// https://beta.openai.com/docs/api-reference/completions/create#completions/create-stream
|
||||
if (data === "[DONE]") {
|
||||
controller.close();
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const json = JSON.parse(data);
|
||||
const text = json.choices[0].delta.content;
|
||||
const queue = encoder.encode(text);
|
||||
controller.enqueue(queue);
|
||||
} catch (e) {
|
||||
controller.error(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const parser = createParser(onParse);
|
||||
for await (const chunk of res.body as any) {
|
||||
parser.feed(decoder.decode(chunk, { stream: true }));
|
||||
}
|
||||
},
|
||||
});
|
||||
return stream;
|
||||
}
|
||||
|
||||
function formatResponse(msg: any) {
|
||||
const jsonMsg = ["```json\n", JSON.stringify(msg, null, " "), "\n```"].join(
|
||||
"",
|
||||
);
|
||||
return new Response(jsonMsg);
|
||||
}
|
||||
|
||||
async function handle(
|
||||
req: NextRequest,
|
||||
{ params }: { params: { path: string[] } },
|
||||
) {
|
||||
console.log("[OpenAI Route] params ", params);
|
||||
|
||||
const authResult = auth(req);
|
||||
if (authResult.error) {
|
||||
return NextResponse.json(authResult, {
|
||||
status: 401,
|
||||
});
|
||||
}
|
||||
|
||||
try {
|
||||
const api = await requestOpenai(req);
|
||||
|
||||
const contentType = api.headers.get("Content-Type") ?? "";
|
||||
|
||||
// streaming response
|
||||
if (contentType.includes("stream")) {
|
||||
const stream = await createStream(api);
|
||||
const res = new Response(stream);
|
||||
res.headers.set("Content-Type", contentType);
|
||||
return res;
|
||||
}
|
||||
|
||||
// try to parse error msg
|
||||
try {
|
||||
const mayBeErrorBody = await api.json();
|
||||
if (mayBeErrorBody.error) {
|
||||
console.error("[OpenAI Response] ", mayBeErrorBody);
|
||||
return formatResponse(mayBeErrorBody);
|
||||
} else {
|
||||
const res = new Response(JSON.stringify(mayBeErrorBody));
|
||||
res.headers.set("Content-Type", "application/json");
|
||||
res.headers.set("Cache-Control", "no-cache");
|
||||
return res;
|
||||
}
|
||||
} catch (e) {
|
||||
console.error("[OpenAI Parse] ", e);
|
||||
return formatResponse({
|
||||
msg: "invalid response from openai server",
|
||||
error: e,
|
||||
});
|
||||
}
|
||||
} catch (e) {
|
||||
console.error("[OpenAI] ", e);
|
||||
return formatResponse(e);
|
||||
}
|
||||
}
|
||||
|
||||
export const GET = handle;
|
||||
export const POST = handle;
|
||||
|
||||
export const runtime = "edge";
|
@ -1,35 +0,0 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { requestOpenai } from "../common";
|
||||
|
||||
async function makeRequest(req: NextRequest) {
|
||||
try {
|
||||
const api = await requestOpenai(req);
|
||||
const res = new NextResponse(api.body);
|
||||
res.headers.set("Content-Type", "application/json");
|
||||
res.headers.set("Cache-Control", "no-cache");
|
||||
return res;
|
||||
} catch (e) {
|
||||
console.error("[OpenAI] ", req.body, e);
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: true,
|
||||
msg: JSON.stringify(e),
|
||||
},
|
||||
{
|
||||
status: 500,
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
return makeRequest(req);
|
||||
}
|
||||
|
||||
export async function GET(req: NextRequest) {
|
||||
return makeRequest(req);
|
||||
}
|
||||
|
||||
export const config = {
|
||||
runtime: "edge",
|
||||
};
|
@ -0,0 +1,28 @@
|
||||
import { useSearchParams } from "react-router-dom";
|
||||
|
||||
type Command = (param: string) => void;
|
||||
interface Commands {
|
||||
fill?: Command;
|
||||
submit?: Command;
|
||||
mask?: Command;
|
||||
}
|
||||
|
||||
export function useCommand(commands: Commands = {}) {
|
||||
const [searchParams, setSearchParams] = useSearchParams();
|
||||
|
||||
if (commands === undefined) return;
|
||||
|
||||
let shouldUpdate = false;
|
||||
searchParams.forEach((param, name) => {
|
||||
const commandName = name as keyof Commands;
|
||||
if (typeof commands[commandName] === "function") {
|
||||
commands[commandName]!(param);
|
||||
searchParams.delete(name);
|
||||
shouldUpdate = true;
|
||||
}
|
||||
});
|
||||
|
||||
if (shouldUpdate) {
|
||||
setSearchParams(searchParams);
|
||||
}
|
||||
}
|
@ -0,0 +1,59 @@
|
||||
import EmojiPicker, {
|
||||
Emoji,
|
||||
EmojiStyle,
|
||||
Theme as EmojiTheme,
|
||||
} from "emoji-picker-react";
|
||||
|
||||
import { ModelType } from "../store";
|
||||
|
||||
import BotIcon from "../icons/bot.svg";
|
||||
import BlackBotIcon from "../icons/black-bot.svg";
|
||||
|
||||
export function getEmojiUrl(unified: string, style: EmojiStyle) {
|
||||
return `https://cdn.staticfile.org/emoji-datasource-apple/14.0.0/img/${style}/64/${unified}.png`;
|
||||
}
|
||||
|
||||
export function AvatarPicker(props: {
|
||||
onEmojiClick: (emojiId: string) => void;
|
||||
}) {
|
||||
return (
|
||||
<EmojiPicker
|
||||
lazyLoadEmojis
|
||||
theme={EmojiTheme.AUTO}
|
||||
getEmojiUrl={getEmojiUrl}
|
||||
onEmojiClick={(e) => {
|
||||
props.onEmojiClick(e.unified);
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export function Avatar(props: { model?: ModelType; avatar?: string }) {
|
||||
if (props.model) {
|
||||
return (
|
||||
<div className="no-dark">
|
||||
{props.model?.startsWith("gpt-4") ? (
|
||||
<BlackBotIcon className="user-avatar" />
|
||||
) : (
|
||||
<BotIcon className="user-avatar" />
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="user-avatar">
|
||||
{props.avatar && <EmojiAvatar avatar={props.avatar} />}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function EmojiAvatar(props: { avatar: string; size?: number }) {
|
||||
return (
|
||||
<Emoji
|
||||
unified={props.avatar}
|
||||
size={props.size ?? 18}
|
||||
getEmojiUrl={getEmojiUrl}
|
||||
/>
|
||||
);
|
||||
}
|
@ -0,0 +1,108 @@
|
||||
@import "../styles/animation.scss";
|
||||
.mask-page {
|
||||
height: 100%;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
|
||||
.mask-page-body {
|
||||
padding: 20px;
|
||||
overflow-y: auto;
|
||||
|
||||
.mask-filter {
|
||||
width: 100%;
|
||||
max-width: 100%;
|
||||
margin-bottom: 20px;
|
||||
animation: slide-in ease 0.3s;
|
||||
height: 40px;
|
||||
|
||||
display: flex;
|
||||
|
||||
.search-bar {
|
||||
flex-grow: 1;
|
||||
max-width: 100%;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.mask-filter-lang {
|
||||
height: 100%;
|
||||
margin-left: 10px;
|
||||
}
|
||||
|
||||
.mask-create {
|
||||
height: 100%;
|
||||
margin-left: 10px;
|
||||
box-sizing: border-box;
|
||||
min-width: 80px;
|
||||
}
|
||||
}
|
||||
|
||||
.mask-item {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
padding: 20px;
|
||||
border: var(--border-in-light);
|
||||
animation: slide-in ease 0.3s;
|
||||
|
||||
&:not(:last-child) {
|
||||
border-bottom: 0;
|
||||
}
|
||||
|
||||
&:first-child {
|
||||
border-top-left-radius: 10px;
|
||||
border-top-right-radius: 10px;
|
||||
}
|
||||
|
||||
&:last-child {
|
||||
border-bottom-left-radius: 10px;
|
||||
border-bottom-right-radius: 10px;
|
||||
}
|
||||
|
||||
.mask-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
|
||||
.mask-icon {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
margin-right: 10px;
|
||||
}
|
||||
|
||||
.mask-title {
|
||||
.mask-name {
|
||||
font-size: 14px;
|
||||
font-weight: bold;
|
||||
}
|
||||
.mask-info {
|
||||
font-size: 12px;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.mask-actions {
|
||||
display: flex;
|
||||
flex-wrap: nowrap;
|
||||
transition: all ease 0.3s;
|
||||
}
|
||||
|
||||
@media screen and (max-width: 600px) {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
padding-bottom: 10px;
|
||||
border-radius: 10px;
|
||||
margin-bottom: 20px;
|
||||
box-shadow: var(--card-shadow);
|
||||
|
||||
&:not(:last-child) {
|
||||
border-bottom: var(--border-in-light);
|
||||
}
|
||||
|
||||
.mask-actions {
|
||||
width: 100%;
|
||||
justify-content: space-between;
|
||||
padding-top: 10px;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,443 @@
|
||||
import { IconButton } from "./button";
|
||||
import { ErrorBoundary } from "./error";
|
||||
|
||||
import styles from "./mask.module.scss";
|
||||
|
||||
import DownloadIcon from "../icons/download.svg";
|
||||
import UploadIcon from "../icons/upload.svg";
|
||||
import EditIcon from "../icons/edit.svg";
|
||||
import AddIcon from "../icons/add.svg";
|
||||
import CloseIcon from "../icons/close.svg";
|
||||
import DeleteIcon from "../icons/delete.svg";
|
||||
import EyeIcon from "../icons/eye.svg";
|
||||
import CopyIcon from "../icons/copy.svg";
|
||||
|
||||
import { DEFAULT_MASK_AVATAR, Mask, useMaskStore } from "../store/mask";
|
||||
import { Message, ModelConfig, ROLES, useChatStore } from "../store";
|
||||
import { Input, List, ListItem, Modal, Popover } from "./ui-lib";
|
||||
import { Avatar, AvatarPicker } from "./emoji";
|
||||
import Locale, { AllLangs, Lang } from "../locales";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
|
||||
import chatStyle from "./chat.module.scss";
|
||||
import { useState } from "react";
|
||||
import { downloadAs, readFromFile } from "../utils";
|
||||
import { Updater } from "../api/openai/typing";
|
||||
import { ModelConfigList } from "./model-config";
|
||||
import { FileName, Path } from "../constant";
|
||||
import { BUILTIN_MASK_STORE } from "../masks";
|
||||
|
||||
export function MaskAvatar(props: { mask: Mask }) {
|
||||
return props.mask.avatar !== DEFAULT_MASK_AVATAR ? (
|
||||
<Avatar avatar={props.mask.avatar} />
|
||||
) : (
|
||||
<Avatar model={props.mask.modelConfig.model} />
|
||||
);
|
||||
}
|
||||
|
||||
export function MaskConfig(props: {
|
||||
mask: Mask;
|
||||
updateMask: Updater<Mask>;
|
||||
extraListItems?: JSX.Element;
|
||||
readonly?: boolean;
|
||||
}) {
|
||||
const [showPicker, setShowPicker] = useState(false);
|
||||
|
||||
const updateConfig = (updater: (config: ModelConfig) => void) => {
|
||||
if (props.readonly) return;
|
||||
|
||||
const config = { ...props.mask.modelConfig };
|
||||
updater(config);
|
||||
props.updateMask((mask) => (mask.modelConfig = config));
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<ContextPrompts
|
||||
context={props.mask.context}
|
||||
updateContext={(updater) => {
|
||||
const context = props.mask.context.slice();
|
||||
updater(context);
|
||||
props.updateMask((mask) => (mask.context = context));
|
||||
}}
|
||||
/>
|
||||
|
||||
<List>
|
||||
<ListItem title={Locale.Mask.Config.Avatar}>
|
||||
<Popover
|
||||
content={
|
||||
<AvatarPicker
|
||||
onEmojiClick={(emoji) => {
|
||||
props.updateMask((mask) => (mask.avatar = emoji));
|
||||
setShowPicker(false);
|
||||
}}
|
||||
></AvatarPicker>
|
||||
}
|
||||
open={showPicker}
|
||||
onClose={() => setShowPicker(false)}
|
||||
>
|
||||
<div
|
||||
onClick={() => setShowPicker(true)}
|
||||
style={{ cursor: "pointer" }}
|
||||
>
|
||||
<MaskAvatar mask={props.mask} />
|
||||
</div>
|
||||
</Popover>
|
||||
</ListItem>
|
||||
<ListItem title={Locale.Mask.Config.Name}>
|
||||
<input
|
||||
type="text"
|
||||
value={props.mask.name}
|
||||
onInput={(e) =>
|
||||
props.updateMask((mask) => (mask.name = e.currentTarget.value))
|
||||
}
|
||||
></input>
|
||||
</ListItem>
|
||||
</List>
|
||||
|
||||
<List>
|
||||
<ModelConfigList
|
||||
modelConfig={{ ...props.mask.modelConfig }}
|
||||
updateConfig={updateConfig}
|
||||
/>
|
||||
{props.extraListItems}
|
||||
</List>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function ContextPromptItem(props: {
|
||||
prompt: Message;
|
||||
update: (prompt: Message) => void;
|
||||
remove: () => void;
|
||||
}) {
|
||||
const [focusingInput, setFocusingInput] = useState(false);
|
||||
|
||||
return (
|
||||
<div className={chatStyle["context-prompt-row"]}>
|
||||
{!focusingInput && (
|
||||
<select
|
||||
value={props.prompt.role}
|
||||
className={chatStyle["context-role"]}
|
||||
onChange={(e) =>
|
||||
props.update({
|
||||
...props.prompt,
|
||||
role: e.target.value as any,
|
||||
})
|
||||
}
|
||||
>
|
||||
{ROLES.map((r) => (
|
||||
<option key={r} value={r}>
|
||||
{r}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
)}
|
||||
<Input
|
||||
value={props.prompt.content}
|
||||
type="text"
|
||||
className={chatStyle["context-content"]}
|
||||
rows={focusingInput ? 5 : 1}
|
||||
onFocus={() => setFocusingInput(true)}
|
||||
onBlur={() => setFocusingInput(false)}
|
||||
onInput={(e) =>
|
||||
props.update({
|
||||
...props.prompt,
|
||||
content: e.currentTarget.value as any,
|
||||
})
|
||||
}
|
||||
/>
|
||||
{!focusingInput && (
|
||||
<IconButton
|
||||
icon={<DeleteIcon />}
|
||||
className={chatStyle["context-delete-button"]}
|
||||
onClick={() => props.remove()}
|
||||
bordered
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function ContextPrompts(props: {
|
||||
context: Message[];
|
||||
updateContext: (updater: (context: Message[]) => void) => void;
|
||||
}) {
|
||||
const context = props.context;
|
||||
|
||||
const addContextPrompt = (prompt: Message) => {
|
||||
props.updateContext((context) => context.push(prompt));
|
||||
};
|
||||
|
||||
const removeContextPrompt = (i: number) => {
|
||||
props.updateContext((context) => context.splice(i, 1));
|
||||
};
|
||||
|
||||
const updateContextPrompt = (i: number, prompt: Message) => {
|
||||
props.updateContext((context) => (context[i] = prompt));
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className={chatStyle["context-prompt"]} style={{ marginBottom: 20 }}>
|
||||
{context.map((c, i) => (
|
||||
<ContextPromptItem
|
||||
key={i}
|
||||
prompt={c}
|
||||
update={(prompt) => updateContextPrompt(i, prompt)}
|
||||
remove={() => removeContextPrompt(i)}
|
||||
/>
|
||||
))}
|
||||
|
||||
<div className={chatStyle["context-prompt-row"]}>
|
||||
<IconButton
|
||||
icon={<AddIcon />}
|
||||
text={Locale.Context.Add}
|
||||
bordered
|
||||
className={chatStyle["context-prompt-button"]}
|
||||
onClick={() =>
|
||||
addContextPrompt({
|
||||
role: "user",
|
||||
content: "",
|
||||
date: "",
|
||||
})
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export function MaskPage() {
|
||||
const navigate = useNavigate();
|
||||
|
||||
const maskStore = useMaskStore();
|
||||
const chatStore = useChatStore();
|
||||
|
||||
const [filterLang, setFilterLang] = useState<Lang>();
|
||||
|
||||
const allMasks = maskStore
|
||||
.getAll()
|
||||
.filter((m) => !filterLang || m.lang === filterLang);
|
||||
|
||||
const [searchMasks, setSearchMasks] = useState<Mask[]>([]);
|
||||
const [searchText, setSearchText] = useState("");
|
||||
const masks = searchText.length > 0 ? searchMasks : allMasks;
|
||||
|
||||
// simple search, will refactor later
|
||||
const onSearch = (text: string) => {
|
||||
setSearchText(text);
|
||||
if (text.length > 0) {
|
||||
const result = allMasks.filter((m) => m.name.includes(text));
|
||||
setSearchMasks(result);
|
||||
} else {
|
||||
setSearchMasks(allMasks);
|
||||
}
|
||||
};
|
||||
|
||||
const [editingMaskId, setEditingMaskId] = useState<number | undefined>();
|
||||
const editingMask =
|
||||
maskStore.get(editingMaskId) ?? BUILTIN_MASK_STORE.get(editingMaskId);
|
||||
const closeMaskModal = () => setEditingMaskId(undefined);
|
||||
|
||||
const downloadAll = () => {
|
||||
downloadAs(JSON.stringify(masks), FileName.Masks);
|
||||
};
|
||||
|
||||
const importFromFile = () => {
|
||||
readFromFile().then((content) => {
|
||||
try {
|
||||
const importMasks = JSON.parse(content);
|
||||
if (Array.isArray(importMasks)) {
|
||||
for (const mask of importMasks) {
|
||||
if (mask.name) {
|
||||
maskStore.create(mask);
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch {}
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<ErrorBoundary>
|
||||
<div className={styles["mask-page"]}>
|
||||
<div className="window-header">
|
||||
<div className="window-header-title">
|
||||
<div className="window-header-main-title">
|
||||
{Locale.Mask.Page.Title}
|
||||
</div>
|
||||
<div className="window-header-submai-title">
|
||||
{Locale.Mask.Page.SubTitle(allMasks.length)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="window-actions">
|
||||
<div className="window-action-button">
|
||||
<IconButton
|
||||
icon={<DownloadIcon />}
|
||||
bordered
|
||||
onClick={downloadAll}
|
||||
/>
|
||||
</div>
|
||||
<div className="window-action-button">
|
||||
<IconButton
|
||||
icon={<UploadIcon />}
|
||||
bordered
|
||||
onClick={() => importFromFile()}
|
||||
/>
|
||||
</div>
|
||||
<div className="window-action-button">
|
||||
<IconButton
|
||||
icon={<CloseIcon />}
|
||||
bordered
|
||||
onClick={() => navigate(-1)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className={styles["mask-page-body"]}>
|
||||
<div className={styles["mask-filter"]}>
|
||||
<input
|
||||
type="text"
|
||||
className={styles["search-bar"]}
|
||||
placeholder={Locale.Mask.Page.Search}
|
||||
autoFocus
|
||||
onInput={(e) => onSearch(e.currentTarget.value)}
|
||||
/>
|
||||
<select
|
||||
className={styles["mask-filter-lang"]}
|
||||
value={filterLang ?? Locale.Settings.Lang.All}
|
||||
onChange={(e) => {
|
||||
const value = e.currentTarget.value;
|
||||
if (value === Locale.Settings.Lang.All) {
|
||||
setFilterLang(undefined);
|
||||
} else {
|
||||
setFilterLang(value as Lang);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<option key="all" value={Locale.Settings.Lang.All}>
|
||||
{Locale.Settings.Lang.All}
|
||||
</option>
|
||||
{AllLangs.map((lang) => (
|
||||
<option value={lang} key={lang}>
|
||||
{Locale.Settings.Lang.Options[lang]}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
|
||||
<IconButton
|
||||
className={styles["mask-create"]}
|
||||
icon={<AddIcon />}
|
||||
text={Locale.Mask.Page.Create}
|
||||
bordered
|
||||
onClick={() => {
|
||||
const createdMask = maskStore.create();
|
||||
setEditingMaskId(createdMask.id);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
{masks.map((m) => (
|
||||
<div className={styles["mask-item"]} key={m.id}>
|
||||
<div className={styles["mask-header"]}>
|
||||
<div className={styles["mask-icon"]}>
|
||||
<MaskAvatar mask={m} />
|
||||
</div>
|
||||
<div className={styles["mask-title"]}>
|
||||
<div className={styles["mask-name"]}>{m.name}</div>
|
||||
<div className={styles["mask-info"] + " one-line"}>
|
||||
{`${Locale.Mask.Item.Info(m.context.length)} / ${
|
||||
Locale.Settings.Lang.Options[m.lang]
|
||||
} / ${m.modelConfig.model}`}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className={styles["mask-actions"]}>
|
||||
<IconButton
|
||||
icon={<AddIcon />}
|
||||
text={Locale.Mask.Item.Chat}
|
||||
onClick={() => {
|
||||
chatStore.newSession(m);
|
||||
navigate(Path.Chat);
|
||||
}}
|
||||
/>
|
||||
{m.builtin ? (
|
||||
<IconButton
|
||||
icon={<EyeIcon />}
|
||||
text={Locale.Mask.Item.View}
|
||||
onClick={() => setEditingMaskId(m.id)}
|
||||
/>
|
||||
) : (
|
||||
<IconButton
|
||||
icon={<EditIcon />}
|
||||
text={Locale.Mask.Item.Edit}
|
||||
onClick={() => setEditingMaskId(m.id)}
|
||||
/>
|
||||
)}
|
||||
{!m.builtin && (
|
||||
<IconButton
|
||||
icon={<DeleteIcon />}
|
||||
text={Locale.Mask.Item.Delete}
|
||||
onClick={() => {
|
||||
if (confirm(Locale.Mask.Item.DeleteConfirm)) {
|
||||
maskStore.delete(m.id);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{editingMask && (
|
||||
<div className="modal-mask">
|
||||
<Modal
|
||||
title={Locale.Mask.EditModal.Title(editingMask?.builtin)}
|
||||
onClose={closeMaskModal}
|
||||
actions={[
|
||||
<IconButton
|
||||
icon={<DownloadIcon />}
|
||||
text={Locale.Mask.EditModal.Download}
|
||||
key="export"
|
||||
bordered
|
||||
onClick={() =>
|
||||
downloadAs(
|
||||
JSON.stringify(editingMask),
|
||||
`${editingMask.name}.json`,
|
||||
)
|
||||
}
|
||||
/>,
|
||||
<IconButton
|
||||
key="copy"
|
||||
icon={<CopyIcon />}
|
||||
bordered
|
||||
text={Locale.Mask.EditModal.Clone}
|
||||
onClick={() => {
|
||||
navigate(Path.Masks);
|
||||
maskStore.create(editingMask);
|
||||
setEditingMaskId(undefined);
|
||||
}}
|
||||
/>,
|
||||
]}
|
||||
>
|
||||
<MaskConfig
|
||||
mask={editingMask}
|
||||
updateMask={(updater) =>
|
||||
maskStore.update(editingMaskId!, updater)
|
||||
}
|
||||
readonly={editingMask.builtin}
|
||||
/>
|
||||
</Modal>
|
||||
</div>
|
||||
)}
|
||||
</ErrorBoundary>
|
||||
);
|
||||
}
|
@ -0,0 +1,140 @@
|
||||
import { ALL_MODELS, ModalConfigValidator, ModelConfig } from "../store";
|
||||
|
||||
import Locale from "../locales";
|
||||
import { InputRange } from "./input-range";
|
||||
import { List, ListItem } from "./ui-lib";
|
||||
|
||||
export function ModelConfigList(props: {
|
||||
modelConfig: ModelConfig;
|
||||
updateConfig: (updater: (config: ModelConfig) => void) => void;
|
||||
}) {
|
||||
return (
|
||||
<>
|
||||
<ListItem title={Locale.Settings.Model}>
|
||||
<select
|
||||
value={props.modelConfig.model}
|
||||
onChange={(e) => {
|
||||
props.updateConfig(
|
||||
(config) =>
|
||||
(config.model = ModalConfigValidator.model(
|
||||
e.currentTarget.value,
|
||||
)),
|
||||
);
|
||||
}}
|
||||
>
|
||||
{ALL_MODELS.map((v) => (
|
||||
<option value={v.name} key={v.name} disabled={!v.available}>
|
||||
{v.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</ListItem>
|
||||
<ListItem
|
||||
title={Locale.Settings.Temperature.Title}
|
||||
subTitle={Locale.Settings.Temperature.SubTitle}
|
||||
>
|
||||
<InputRange
|
||||
value={props.modelConfig.temperature?.toFixed(1)}
|
||||
min="0"
|
||||
max="1" // lets limit it to 0-1
|
||||
step="0.1"
|
||||
onChange={(e) => {
|
||||
props.updateConfig(
|
||||
(config) =>
|
||||
(config.temperature = ModalConfigValidator.temperature(
|
||||
e.currentTarget.valueAsNumber,
|
||||
)),
|
||||
);
|
||||
}}
|
||||
></InputRange>
|
||||
</ListItem>
|
||||
<ListItem
|
||||
title={Locale.Settings.MaxTokens.Title}
|
||||
subTitle={Locale.Settings.MaxTokens.SubTitle}
|
||||
>
|
||||
<input
|
||||
type="number"
|
||||
min={100}
|
||||
max={32000}
|
||||
value={props.modelConfig.max_tokens}
|
||||
onChange={(e) =>
|
||||
props.updateConfig(
|
||||
(config) =>
|
||||
(config.max_tokens = ModalConfigValidator.max_tokens(
|
||||
e.currentTarget.valueAsNumber,
|
||||
)),
|
||||
)
|
||||
}
|
||||
></input>
|
||||
</ListItem>
|
||||
<ListItem
|
||||
title={Locale.Settings.PresencePenlty.Title}
|
||||
subTitle={Locale.Settings.PresencePenlty.SubTitle}
|
||||
>
|
||||
<InputRange
|
||||
value={props.modelConfig.presence_penalty?.toFixed(1)}
|
||||
min="-2"
|
||||
max="2"
|
||||
step="0.1"
|
||||
onChange={(e) => {
|
||||
props.updateConfig(
|
||||
(config) =>
|
||||
(config.presence_penalty =
|
||||
ModalConfigValidator.presence_penalty(
|
||||
e.currentTarget.valueAsNumber,
|
||||
)),
|
||||
);
|
||||
}}
|
||||
></InputRange>
|
||||
</ListItem>
|
||||
|
||||
<ListItem
|
||||
title={Locale.Settings.HistoryCount.Title}
|
||||
subTitle={Locale.Settings.HistoryCount.SubTitle}
|
||||
>
|
||||
<InputRange
|
||||
title={props.modelConfig.historyMessageCount.toString()}
|
||||
value={props.modelConfig.historyMessageCount}
|
||||
min="0"
|
||||
max="32"
|
||||
step="1"
|
||||
onChange={(e) =>
|
||||
props.updateConfig(
|
||||
(config) => (config.historyMessageCount = e.target.valueAsNumber),
|
||||
)
|
||||
}
|
||||
></InputRange>
|
||||
</ListItem>
|
||||
|
||||
<ListItem
|
||||
title={Locale.Settings.CompressThreshold.Title}
|
||||
subTitle={Locale.Settings.CompressThreshold.SubTitle}
|
||||
>
|
||||
<input
|
||||
type="number"
|
||||
min={500}
|
||||
max={4000}
|
||||
value={props.modelConfig.compressMessageLengthThreshold}
|
||||
onChange={(e) =>
|
||||
props.updateConfig(
|
||||
(config) =>
|
||||
(config.compressMessageLengthThreshold =
|
||||
e.currentTarget.valueAsNumber),
|
||||
)
|
||||
}
|
||||
></input>
|
||||
</ListItem>
|
||||
<ListItem title={Locale.Memory.Title} subTitle={Locale.Memory.Send}>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={props.modelConfig.sendMemory}
|
||||
onChange={(e) =>
|
||||
props.updateConfig(
|
||||
(config) => (config.sendMemory = e.currentTarget.checked),
|
||||
)
|
||||
}
|
||||
></input>
|
||||
</ListItem>
|
||||
</>
|
||||
);
|
||||
}
|
@ -0,0 +1,115 @@
|
||||
@import "../styles/animation.scss";
|
||||
|
||||
.new-chat {
|
||||
height: 100%;
|
||||
width: 100%;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
flex-direction: column;
|
||||
|
||||
.mask-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
width: 100%;
|
||||
padding: 10px;
|
||||
box-sizing: border-box;
|
||||
animation: slide-in-from-top ease 0.3s;
|
||||
}
|
||||
|
||||
.mask-cards {
|
||||
display: flex;
|
||||
margin-top: 5vh;
|
||||
margin-bottom: 20px;
|
||||
animation: slide-in ease 0.3s;
|
||||
|
||||
.mask-card {
|
||||
padding: 20px 10px;
|
||||
border: var(--border-in-light);
|
||||
box-shadow: var(--card-shadow);
|
||||
border-radius: 14px;
|
||||
background-color: var(--white);
|
||||
transform: scale(1);
|
||||
|
||||
&:first-child {
|
||||
transform: rotate(-15deg) translateY(5px);
|
||||
}
|
||||
|
||||
&:last-child {
|
||||
transform: rotate(15deg) translateY(5px);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.title {
|
||||
font-size: 32px;
|
||||
font-weight: bolder;
|
||||
margin-bottom: 1vh;
|
||||
animation: slide-in ease 0.35s;
|
||||
}
|
||||
|
||||
.sub-title {
|
||||
animation: slide-in ease 0.4s;
|
||||
}
|
||||
|
||||
.actions {
|
||||
margin-top: 5vh;
|
||||
margin-bottom: 5vh;
|
||||
animation: slide-in ease 0.45s;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
|
||||
.more {
|
||||
font-size: 12px;
|
||||
margin-left: 10px;
|
||||
}
|
||||
}
|
||||
|
||||
.masks {
|
||||
flex-grow: 1;
|
||||
width: 100%;
|
||||
overflow: hidden;
|
||||
align-items: center;
|
||||
padding-top: 20px;
|
||||
|
||||
animation: slide-in ease 0.5s;
|
||||
|
||||
.mask-row {
|
||||
margin-bottom: 10px;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
|
||||
@for $i from 1 to 10 {
|
||||
&:nth-child(#{$i * 2}) {
|
||||
margin-left: 50px;
|
||||
}
|
||||
}
|
||||
|
||||
.mask {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
padding: 10px 14px;
|
||||
border: var(--border-in-light);
|
||||
box-shadow: var(--card-shadow);
|
||||
background-color: var(--white);
|
||||
border-radius: 10px;
|
||||
margin-right: 10px;
|
||||
max-width: 8em;
|
||||
transform: scale(1);
|
||||
cursor: pointer;
|
||||
transition: all ease 0.3s;
|
||||
|
||||
&:hover {
|
||||
transform: translateY(-5px) scale(1.1);
|
||||
z-index: 999;
|
||||
border-color: var(--primary);
|
||||
}
|
||||
|
||||
.mask-name {
|
||||
margin-left: 10px;
|
||||
font-size: 14px;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,197 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { Path, SlotID } from "../constant";
|
||||
import { IconButton } from "./button";
|
||||
import { EmojiAvatar } from "./emoji";
|
||||
import styles from "./new-chat.module.scss";
|
||||
|
||||
import LeftIcon from "../icons/left.svg";
|
||||
import LightningIcon from "../icons/lightning.svg";
|
||||
import EyeIcon from "../icons/eye.svg";
|
||||
|
||||
import { useLocation, useNavigate } from "react-router-dom";
|
||||
import { Mask, useMaskStore } from "../store/mask";
|
||||
import Locale from "../locales";
|
||||
import { useAppConfig, useChatStore } from "../store";
|
||||
import { MaskAvatar } from "./mask";
|
||||
import { useCommand } from "../command";
|
||||
|
||||
function getIntersectionArea(aRect: DOMRect, bRect: DOMRect) {
|
||||
const xmin = Math.max(aRect.x, bRect.x);
|
||||
const xmax = Math.min(aRect.x + aRect.width, bRect.x + bRect.width);
|
||||
const ymin = Math.max(aRect.y, bRect.y);
|
||||
const ymax = Math.min(aRect.y + aRect.height, bRect.y + bRect.height);
|
||||
const width = xmax - xmin;
|
||||
const height = ymax - ymin;
|
||||
const intersectionArea = width < 0 || height < 0 ? 0 : width * height;
|
||||
return intersectionArea;
|
||||
}
|
||||
|
||||
function MaskItem(props: { mask: Mask; onClick?: () => void }) {
|
||||
const domRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const changeOpacity = () => {
|
||||
const dom = domRef.current;
|
||||
const parent = document.getElementById(SlotID.AppBody);
|
||||
if (!parent || !dom) return;
|
||||
|
||||
const domRect = dom.getBoundingClientRect();
|
||||
const parentRect = parent.getBoundingClientRect();
|
||||
const intersectionArea = getIntersectionArea(domRect, parentRect);
|
||||
const domArea = domRect.width * domRect.height;
|
||||
const ratio = intersectionArea / domArea;
|
||||
const opacity = ratio > 0.9 ? 1 : 0.4;
|
||||
dom.style.opacity = opacity.toString();
|
||||
};
|
||||
|
||||
setTimeout(changeOpacity, 30);
|
||||
|
||||
window.addEventListener("resize", changeOpacity);
|
||||
|
||||
return () => window.removeEventListener("resize", changeOpacity);
|
||||
}, [domRef]);
|
||||
|
||||
return (
|
||||
<div className={styles["mask"]} ref={domRef} onClick={props.onClick}>
|
||||
<MaskAvatar mask={props.mask} />
|
||||
<div className={styles["mask-name"] + " one-line"}>{props.mask.name}</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function useMaskGroup(masks: Mask[]) {
|
||||
const [groups, setGroups] = useState<Mask[][]>([]);
|
||||
|
||||
useEffect(() => {
|
||||
const appBody = document.getElementById(SlotID.AppBody);
|
||||
if (!appBody || masks.length === 0) return;
|
||||
|
||||
const rect = appBody.getBoundingClientRect();
|
||||
const maxWidth = rect.width;
|
||||
const maxHeight = rect.height * 0.6;
|
||||
const maskItemWidth = 120;
|
||||
const maskItemHeight = 50;
|
||||
|
||||
const randomMask = () => masks[Math.floor(Math.random() * masks.length)];
|
||||
let maskIndex = 0;
|
||||
const nextMask = () => masks[maskIndex++ % masks.length];
|
||||
|
||||
const rows = Math.ceil(maxHeight / maskItemHeight);
|
||||
const cols = Math.ceil(maxWidth / maskItemWidth);
|
||||
|
||||
const newGroups = new Array(rows)
|
||||
.fill(0)
|
||||
.map((_, _i) =>
|
||||
new Array(cols)
|
||||
.fill(0)
|
||||
.map((_, j) => (j < 1 || j > cols - 2 ? randomMask() : nextMask())),
|
||||
);
|
||||
|
||||
setGroups(newGroups);
|
||||
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, []);
|
||||
|
||||
return groups;
|
||||
}
|
||||
|
||||
export function NewChat() {
|
||||
const chatStore = useChatStore();
|
||||
const maskStore = useMaskStore();
|
||||
|
||||
const masks = maskStore.getAll();
|
||||
const groups = useMaskGroup(masks);
|
||||
|
||||
const navigate = useNavigate();
|
||||
const config = useAppConfig();
|
||||
|
||||
const { state } = useLocation();
|
||||
|
||||
const startChat = (mask?: Mask) => {
|
||||
chatStore.newSession(mask);
|
||||
setTimeout(() => navigate(Path.Chat), 1);
|
||||
};
|
||||
|
||||
useCommand({
|
||||
mask: (id) => {
|
||||
try {
|
||||
const mask = maskStore.get(parseInt(id));
|
||||
startChat(mask ?? undefined);
|
||||
} catch {
|
||||
console.error("[New Chat] failed to create chat from mask id=", id);
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
return (
|
||||
<div className={styles["new-chat"]}>
|
||||
<div className={styles["mask-header"]}>
|
||||
<IconButton
|
||||
icon={<LeftIcon />}
|
||||
text={Locale.NewChat.Return}
|
||||
onClick={() => navigate(Path.Home)}
|
||||
></IconButton>
|
||||
{!state?.fromHome && (
|
||||
<IconButton
|
||||
text={Locale.NewChat.NotShow}
|
||||
onClick={() => {
|
||||
if (confirm(Locale.NewChat.ConfirmNoShow)) {
|
||||
startChat();
|
||||
config.update(
|
||||
(config) => (config.dontShowMaskSplashScreen = true),
|
||||
);
|
||||
}
|
||||
}}
|
||||
></IconButton>
|
||||
)}
|
||||
</div>
|
||||
<div className={styles["mask-cards"]}>
|
||||
<div className={styles["mask-card"]}>
|
||||
<EmojiAvatar avatar="1f606" size={24} />
|
||||
</div>
|
||||
<div className={styles["mask-card"]}>
|
||||
<EmojiAvatar avatar="1f916" size={24} />
|
||||
</div>
|
||||
<div className={styles["mask-card"]}>
|
||||
<EmojiAvatar avatar="1f479" size={24} />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className={styles["title"]}>{Locale.NewChat.Title}</div>
|
||||
<div className={styles["sub-title"]}>{Locale.NewChat.SubTitle}</div>
|
||||
|
||||
<div className={styles["actions"]}>
|
||||
<IconButton
|
||||
text={Locale.NewChat.Skip}
|
||||
onClick={() => startChat()}
|
||||
icon={<LightningIcon />}
|
||||
type="primary"
|
||||
shadow
|
||||
/>
|
||||
|
||||
<IconButton
|
||||
className={styles["more"]}
|
||||
text={Locale.NewChat.More}
|
||||
onClick={() => navigate(Path.Masks)}
|
||||
icon={<EyeIcon />}
|
||||
bordered
|
||||
shadow
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className={styles["masks"]}>
|
||||
{groups.map((masks, i) => (
|
||||
<div key={i} className={styles["mask-row"]}>
|
||||
{masks.map((mask, index) => (
|
||||
<MaskItem
|
||||
key={index}
|
||||
mask={mask}
|
||||
onClick={() => startChat(mask)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
@ -0,0 +1,205 @@
|
||||
import { useEffect, useRef } from "react";
|
||||
|
||||
import styles from "./home.module.scss";
|
||||
|
||||
import { IconButton } from "./button";
|
||||
import SettingsIcon from "../icons/settings.svg";
|
||||
import GithubIcon from "../icons/github.svg";
|
||||
import ChatGptIcon from "../icons/chatgpt.svg";
|
||||
import AddIcon from "../icons/add.svg";
|
||||
import CloseIcon from "../icons/close.svg";
|
||||
import MaskIcon from "../icons/mask.svg";
|
||||
import PluginIcon from "../icons/plugin.svg";
|
||||
|
||||
import Locale from "../locales";
|
||||
|
||||
import { useAppConfig, useChatStore } from "../store";
|
||||
|
||||
import {
|
||||
MAX_SIDEBAR_WIDTH,
|
||||
MIN_SIDEBAR_WIDTH,
|
||||
NARROW_SIDEBAR_WIDTH,
|
||||
Path,
|
||||
REPO_URL,
|
||||
} from "../constant";
|
||||
|
||||
import { Link, useNavigate } from "react-router-dom";
|
||||
import { useMobileScreen } from "../utils";
|
||||
import dynamic from "next/dynamic";
|
||||
import { showToast } from "./ui-lib";
|
||||
|
||||
const ChatList = dynamic(async () => (await import("./chat-list")).ChatList, {
|
||||
loading: () => null,
|
||||
});
|
||||
|
||||
function useHotKey() {
|
||||
const chatStore = useChatStore();
|
||||
|
||||
useEffect(() => {
|
||||
const onKeyDown = (e: KeyboardEvent) => {
|
||||
if (e.metaKey || e.altKey || e.ctrlKey) {
|
||||
const n = chatStore.sessions.length;
|
||||
const limit = (x: number) => (x + n) % n;
|
||||
const i = chatStore.currentSessionIndex;
|
||||
if (e.key === "ArrowUp") {
|
||||
chatStore.selectSession(limit(i - 1));
|
||||
} else if (e.key === "ArrowDown") {
|
||||
chatStore.selectSession(limit(i + 1));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener("keydown", onKeyDown);
|
||||
return () => window.removeEventListener("keydown", onKeyDown);
|
||||
});
|
||||
}
|
||||
|
||||
function useDragSideBar() {
|
||||
const limit = (x: number) => Math.min(MAX_SIDEBAR_WIDTH, x);
|
||||
|
||||
const config = useAppConfig();
|
||||
const startX = useRef(0);
|
||||
const startDragWidth = useRef(config.sidebarWidth ?? 300);
|
||||
const lastUpdateTime = useRef(Date.now());
|
||||
|
||||
const handleMouseMove = useRef((e: MouseEvent) => {
|
||||
if (Date.now() < lastUpdateTime.current + 50) {
|
||||
return;
|
||||
}
|
||||
lastUpdateTime.current = Date.now();
|
||||
const d = e.clientX - startX.current;
|
||||
const nextWidth = limit(startDragWidth.current + d);
|
||||
config.update((config) => (config.sidebarWidth = nextWidth));
|
||||
});
|
||||
|
||||
const handleMouseUp = useRef(() => {
|
||||
startDragWidth.current = config.sidebarWidth ?? 300;
|
||||
window.removeEventListener("mousemove", handleMouseMove.current);
|
||||
window.removeEventListener("mouseup", handleMouseUp.current);
|
||||
});
|
||||
|
||||
const onDragMouseDown = (e: MouseEvent) => {
|
||||
startX.current = e.clientX;
|
||||
|
||||
window.addEventListener("mousemove", handleMouseMove.current);
|
||||
window.addEventListener("mouseup", handleMouseUp.current);
|
||||
};
|
||||
const isMobileScreen = useMobileScreen();
|
||||
const shouldNarrow =
|
||||
!isMobileScreen && config.sidebarWidth < MIN_SIDEBAR_WIDTH;
|
||||
|
||||
useEffect(() => {
|
||||
const barWidth = shouldNarrow
|
||||
? NARROW_SIDEBAR_WIDTH
|
||||
: limit(config.sidebarWidth ?? 300);
|
||||
const sideBarWidth = isMobileScreen ? "100vw" : `${barWidth}px`;
|
||||
document.documentElement.style.setProperty("--sidebar-width", sideBarWidth);
|
||||
}, [config.sidebarWidth, isMobileScreen, shouldNarrow]);
|
||||
|
||||
return {
|
||||
onDragMouseDown,
|
||||
shouldNarrow,
|
||||
};
|
||||
}
|
||||
|
||||
export function SideBar(props: { className?: string }) {
|
||||
const chatStore = useChatStore();
|
||||
|
||||
// drag side bar
|
||||
const { onDragMouseDown, shouldNarrow } = useDragSideBar();
|
||||
const navigate = useNavigate();
|
||||
const config = useAppConfig();
|
||||
|
||||
useHotKey();
|
||||
|
||||
return (
|
||||
<div
|
||||
className={`${styles.sidebar} ${props.className} ${
|
||||
shouldNarrow && styles["narrow-sidebar"]
|
||||
}`}
|
||||
>
|
||||
<div className={styles["sidebar-header"]}>
|
||||
<div className={styles["sidebar-title"]}>ChatGPT Next</div>
|
||||
<div className={styles["sidebar-sub-title"]}>
|
||||
Build your own AI assistant.
|
||||
</div>
|
||||
<div className={styles["sidebar-logo"] + " no-dark"}>
|
||||
<ChatGptIcon />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className={styles["sidebar-header-bar"]}>
|
||||
<IconButton
|
||||
icon={<MaskIcon />}
|
||||
text={shouldNarrow ? undefined : Locale.Mask.Name}
|
||||
className={styles["sidebar-bar-button"]}
|
||||
onClick={() => navigate(Path.NewChat, { state: { fromHome: true } })}
|
||||
shadow
|
||||
/>
|
||||
<IconButton
|
||||
icon={<PluginIcon />}
|
||||
text={shouldNarrow ? undefined : Locale.Plugin.Name}
|
||||
className={styles["sidebar-bar-button"]}
|
||||
onClick={() => showToast(Locale.WIP)}
|
||||
shadow
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div
|
||||
className={styles["sidebar-body"]}
|
||||
onClick={(e) => {
|
||||
if (e.target === e.currentTarget) {
|
||||
navigate(Path.Home);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<ChatList narrow={shouldNarrow} />
|
||||
</div>
|
||||
|
||||
<div className={styles["sidebar-tail"]}>
|
||||
<div className={styles["sidebar-actions"]}>
|
||||
<div className={styles["sidebar-action"] + " " + styles.mobile}>
|
||||
<IconButton
|
||||
icon={<CloseIcon />}
|
||||
onClick={() => {
|
||||
if (confirm(Locale.Home.DeleteChat)) {
|
||||
chatStore.deleteSession(chatStore.currentSessionIndex);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<div className={styles["sidebar-action"]}>
|
||||
<Link to={Path.Settings}>
|
||||
<IconButton icon={<SettingsIcon />} shadow />
|
||||
</Link>
|
||||
</div>
|
||||
<div className={styles["sidebar-action"]}>
|
||||
<a href={REPO_URL} target="_blank">
|
||||
<IconButton icon={<GithubIcon />} shadow />
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<IconButton
|
||||
icon={<AddIcon />}
|
||||
text={shouldNarrow ? undefined : Locale.Home.NewChat}
|
||||
onClick={() => {
|
||||
if (config.dontShowMaskSplashScreen) {
|
||||
chatStore.newSession();
|
||||
navigate(Path.Chat);
|
||||
} else {
|
||||
navigate(Path.NewChat);
|
||||
}
|
||||
}}
|
||||
shadow
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div
|
||||
className={styles["sidebar-drag"]}
|
||||
onMouseDown={(e) => onDragMouseDown(e as any)}
|
||||
></div>
|
||||
</div>
|
||||
);
|
||||
}
|
After Width: | Height: | Size: 4.2 KiB |
Before Width: | Height: | Size: 1.1 KiB After Width: | Height: | Size: 852 B |
Before Width: | Height: | Size: 23 KiB After Width: | Height: | Size: 23 KiB |
After Width: | Height: | Size: 573 B |
Before Width: | Height: | Size: 2.7 KiB After Width: | Height: | Size: 3.0 KiB |
After Width: | Height: | Size: 3.5 KiB |
After Width: | Height: | Size: 2.1 KiB |
After Width: | Height: | Size: 3.5 KiB |
After Width: | Height: | Size: 1.2 KiB |
After Width: | Height: | Size: 11 KiB |
@ -0,0 +1,242 @@
|
||||
import { SubmitKey } from "../store/config";
|
||||
import type { LocaleType } from "./index";
|
||||
|
||||
const vi: LocaleType = {
|
||||
WIP: "Coming Soon...",
|
||||
Error: {
|
||||
Unauthorized:
|
||||
"Truy cập chưa xác thực, vui lòng nhập mã truy cập trong trang cài đặt.",
|
||||
},
|
||||
ChatItem: {
|
||||
ChatItemCount: (count: number) => `${count} tin nhắn`,
|
||||
},
|
||||
Chat: {
|
||||
SubTitle: (count: number) => `${count} tin nhắn với ChatGPT`,
|
||||
Actions: {
|
||||
ChatList: "Xem danh sách chat",
|
||||
CompressedHistory: "Nén tin nhắn trong quá khứ",
|
||||
Export: "Xuất tất cả tin nhắn dưới dạng Markdown",
|
||||
Copy: "Sao chép",
|
||||
Stop: "Dừng",
|
||||
Retry: "Thử lại",
|
||||
Delete: "Xóa",
|
||||
},
|
||||
Rename: "Đổi tên",
|
||||
Typing: "Đang nhập…",
|
||||
Input: (submitKey: string) => {
|
||||
var inputHints = `${submitKey} để gửi`;
|
||||
if (submitKey === String(SubmitKey.Enter)) {
|
||||
inputHints += ", Shift + Enter để xuống dòng";
|
||||
}
|
||||
return inputHints + ", / để tìm kiếm mẫu gợi ý";
|
||||
},
|
||||
Send: "Gửi",
|
||||
Config: {
|
||||
Reset: "Khôi phục cài đặt gốc",
|
||||
SaveAs: "Lưu dưới dạng Mẫu",
|
||||
},
|
||||
},
|
||||
Export: {
|
||||
Title: "Tất cả tin nhắn",
|
||||
Copy: "Sao chép tất cả",
|
||||
Download: "Tải xuống",
|
||||
MessageFromYou: "Tin nhắn của bạn",
|
||||
MessageFromChatGPT: "Tin nhắn từ ChatGPT",
|
||||
},
|
||||
Memory: {
|
||||
Title: "Lịch sử tin nhắn",
|
||||
EmptyContent: "Chưa có tin nhắn",
|
||||
Send: "Gửi tin nhắn trong quá khứ",
|
||||
Copy: "Sao chép tin nhắn trong quá khứ",
|
||||
Reset: "Đặt lại phiên",
|
||||
ResetConfirm:
|
||||
"Đặt lại sẽ xóa toàn bộ lịch sử trò chuyện hiện tại và bộ nhớ. Bạn có chắc chắn muốn đặt lại không?",
|
||||
},
|
||||
Home: {
|
||||
NewChat: "Cuộc trò chuyện mới",
|
||||
DeleteChat: "Xác nhận xóa các cuộc trò chuyện đã chọn?",
|
||||
DeleteToast: "Đã xóa cuộc trò chuyện",
|
||||
Revert: "Khôi phục",
|
||||
},
|
||||
Settings: {
|
||||
Title: "Cài đặt",
|
||||
SubTitle: "Tất cả cài đặt",
|
||||
Actions: {
|
||||
ClearAll: "Xóa toàn bộ dữ liệu",
|
||||
ResetAll: "Khôi phục cài đặt gốc",
|
||||
Close: "Đóng",
|
||||
ConfirmResetAll: "Bạn chắc chắn muốn thiết lập lại tất cả cài đặt?",
|
||||
ConfirmClearAll: "Bạn chắc chắn muốn thiết lập lại tất cả dữ liệu?",
|
||||
},
|
||||
Lang: {
|
||||
Name: "Language", // ATTENTION: if you wanna add a new translation, please do not translate this value, leave it as `Language`
|
||||
All: "Tất cả ngôn ngữ",
|
||||
Options: {
|
||||
cn: "简体中文",
|
||||
en: "English",
|
||||
tw: "繁體中文",
|
||||
es: "Español",
|
||||
it: "Italiano",
|
||||
tr: "Türkçe",
|
||||
jp: "日本語",
|
||||
de: "Deutsch",
|
||||
vi: "Vietnamese",
|
||||
ru: "Русский",
|
||||
},
|
||||
},
|
||||
Avatar: "Ảnh đại diện",
|
||||
FontSize: {
|
||||
Title: "Font chữ",
|
||||
SubTitle: "Thay đổi font chữ của nội dung trò chuyện",
|
||||
},
|
||||
Update: {
|
||||
Version: (x: string) => `Phiên bản: ${x}`,
|
||||
IsLatest: "Phiên bản mới nhất",
|
||||
CheckUpdate: "Kiểm tra bản cập nhật",
|
||||
IsChecking: "Kiểm tra bản cập nhật...",
|
||||
FoundUpdate: (x: string) => `Phát hiện phiên bản mới: ${x}`,
|
||||
GoToUpdate: "Cập nhật",
|
||||
},
|
||||
SendKey: "Phím gửi",
|
||||
Theme: "Theme",
|
||||
TightBorder: "Chế độ không viền",
|
||||
SendPreviewBubble: {
|
||||
Title: "Gửi bong bóng xem trước",
|
||||
SubTitle: "Xem trước nội dung markdown bằng bong bóng",
|
||||
},
|
||||
Mask: {
|
||||
Title: "Mask Splash Screen",
|
||||
SubTitle: "Chớp màn hình khi bắt đầu cuộc trò chuyện mới",
|
||||
},
|
||||
Prompt: {
|
||||
Disable: {
|
||||
Title: "Vô hiệu hóa chức năng tự động hoàn thành",
|
||||
SubTitle: "Nhập / để kích hoạt chức năng tự động hoàn thành",
|
||||
},
|
||||
List: "Danh sách mẫu gợi ý",
|
||||
ListCount: (builtin: number, custom: number) =>
|
||||
`${builtin} có sẵn, ${custom} do người dùng xác định`,
|
||||
Edit: "Chỉnh sửa",
|
||||
Modal: {
|
||||
Title: "Danh sách mẫu gợi ý",
|
||||
Add: "Thêm",
|
||||
Search: "Tìm kiếm mẫu",
|
||||
},
|
||||
EditModal: {
|
||||
Title: "Chỉnh sửa mẫu",
|
||||
},
|
||||
},
|
||||
HistoryCount: {
|
||||
Title: "Số lượng tin nhắn đính kèm",
|
||||
SubTitle: "Số lượng tin nhắn trong quá khứ được gửi kèm theo mỗi yêu cầu",
|
||||
},
|
||||
CompressThreshold: {
|
||||
Title: "Ngưỡng nén lịch sử tin nhắn",
|
||||
SubTitle: "Thực hiện nén nếu số lượng tin nhắn chưa nén vượt quá ngưỡng",
|
||||
},
|
||||
Token: {
|
||||
Title: "API Key",
|
||||
SubTitle: "Sử dụng khóa của bạn để bỏ qua giới hạn mã truy cập",
|
||||
Placeholder: "OpenAI API Key",
|
||||
},
|
||||
Usage: {
|
||||
Title: "Hạn mức tài khoản",
|
||||
SubTitle(used: any, total: any) {
|
||||
return `Đã sử dụng $${used} trong tháng này, hạn mức $${total}`;
|
||||
},
|
||||
IsChecking: "Đang kiểm tra...",
|
||||
Check: "Kiểm tra",
|
||||
NoAccess: "Nhập API Key để kiểm tra hạn mức",
|
||||
},
|
||||
AccessCode: {
|
||||
Title: "Mã truy cập",
|
||||
SubTitle: "Đã bật kiểm soát truy cập",
|
||||
Placeholder: "Nhập mã truy cập",
|
||||
},
|
||||
Model: "Mô hình",
|
||||
Temperature: {
|
||||
Title: "Tính ngẫu nhiên (temperature)",
|
||||
SubTitle: "Giá trị càng lớn, câu trả lời càng ngẫu nhiên",
|
||||
},
|
||||
MaxTokens: {
|
||||
Title: "Giới hạn số lượng token (max_tokens)",
|
||||
SubTitle: "Số lượng token tối đa được sử dụng trong mỗi lần tương tác",
|
||||
},
|
||||
PresencePenlty: {
|
||||
Title: "Chủ đề mới (presence_penalty)",
|
||||
SubTitle: "Giá trị càng lớn tăng khả năng mở rộng sang các chủ đề mới",
|
||||
},
|
||||
},
|
||||
Store: {
|
||||
DefaultTopic: "Cuộc trò chuyện mới",
|
||||
BotHello: "Xin chào! Mình có thể giúp gì cho bạn?",
|
||||
Error: "Có lỗi xảy ra, vui lòng thử lại sau.",
|
||||
Prompt: {
|
||||
History: (content: string) =>
|
||||
"Tóm tắt ngắn gọn cuộc trò chuyện giữa người dùng và AI: " + content,
|
||||
Topic:
|
||||
"Sử dụng 4 đến 5 từ tóm tắt cuộc trò chuyện này mà không có phần mở đầu, dấu chấm câu, dấu ngoặc kép, dấu chấm, ký hiệu hoặc văn bản bổ sung nào. Loại bỏ các dấu ngoặc kép kèm theo.",
|
||||
Summarize:
|
||||
"Tóm tắt cuộc trò chuyện này một cách ngắn gọn trong 200 từ hoặc ít hơn để sử dụng làm gợi ý cho ngữ cảnh tiếp theo.",
|
||||
},
|
||||
},
|
||||
Copy: {
|
||||
Success: "Sao chép vào bộ nhớ tạm",
|
||||
Failed:
|
||||
"Sao chép không thành công, vui lòng cấp quyền truy cập vào bộ nhớ tạm",
|
||||
},
|
||||
Context: {
|
||||
Toast: (x: any) => `Sử dụng ${x} tin nhắn chứa ngữ cảnh`,
|
||||
Edit: "Thiết lập ngữ cảnh và bộ nhớ",
|
||||
Add: "Thêm tin nhắn",
|
||||
},
|
||||
Plugin: {
|
||||
Name: "Plugin",
|
||||
},
|
||||
Mask: {
|
||||
Name: "Mẫu",
|
||||
Page: {
|
||||
Title: "Mẫu trò chuyện",
|
||||
SubTitle: (count: number) => `${count} mẫu`,
|
||||
Search: "Tìm kiếm mẫu",
|
||||
Create: "Tạo",
|
||||
},
|
||||
Item: {
|
||||
Info: (count: number) => `${count} tin nhắn`,
|
||||
Chat: "Chat",
|
||||
View: "Xem trước",
|
||||
Edit: "Chỉnh sửa",
|
||||
Delete: "Xóa",
|
||||
DeleteConfirm: "Xác nhận xóa?",
|
||||
},
|
||||
EditModal: {
|
||||
Title: (readonly: boolean) =>
|
||||
`Chỉnh sửa mẫu ${readonly ? "(chỉ xem)" : ""}`,
|
||||
Download: "Tải xuống",
|
||||
Clone: "Tạo bản sao",
|
||||
},
|
||||
Config: {
|
||||
Avatar: "Ảnh đại diện bot",
|
||||
Name: "Tên bot",
|
||||
},
|
||||
},
|
||||
NewChat: {
|
||||
Return: "Quay lại",
|
||||
Skip: "Bỏ qua",
|
||||
Title: "Chọn 1 biểu tượng",
|
||||
SubTitle: "Bắt đầu trò chuyện ẩn sau lớp mặt nạ",
|
||||
More: "Tìm thêm",
|
||||
NotShow: "Không hiển thị lại",
|
||||
ConfirmNoShow: "Xác nhận tắt? Bạn có thể bật lại trong phần cài đặt.",
|
||||
},
|
||||
|
||||
UI: {
|
||||
Confirm: "Xác nhận",
|
||||
Cancel: "Hủy",
|
||||
Close: "Đóng",
|
||||
Create: "Tạo",
|
||||
Edit: "Chỉnh sửa",
|
||||
},
|
||||
};
|
||||
|
||||
export default vi;
|
@ -0,0 +1,26 @@
|
||||
import { Mask } from "../store/mask";
|
||||
import { CN_MASKS } from "./cn";
|
||||
import { EN_MASKS } from "./en";
|
||||
|
||||
import { type BuiltinMask } from "./typing";
|
||||
export { type BuiltinMask } from "./typing";
|
||||
|
||||
export const BUILTIN_MASK_ID = 100000;
|
||||
|
||||
export const BUILTIN_MASK_STORE = {
|
||||
buildinId: BUILTIN_MASK_ID,
|
||||
masks: {} as Record<number, Mask>,
|
||||
get(id?: number) {
|
||||
if (!id) return undefined;
|
||||
return this.masks[id] as Mask | undefined;
|
||||
},
|
||||
add(m: BuiltinMask) {
|
||||
const mask = { ...m, id: this.buildinId++ };
|
||||
this.masks[mask.id] = mask;
|
||||
return mask;
|
||||
},
|
||||
};
|
||||
|
||||
export const BUILTIN_MASKS: Mask[] = [...CN_MASKS, ...EN_MASKS].map((m) =>
|
||||
BUILTIN_MASK_STORE.add(m),
|
||||
);
|
@ -0,0 +1,3 @@
|
||||
import { type Mask } from "../store/mask";
|
||||
|
||||
export type BuiltinMask = Omit<Mask, "id">;
|
@ -0,0 +1,168 @@
|
||||
import { create } from "zustand";
|
||||
import { persist } from "zustand/middleware";
|
||||
import { StoreKey } from "../constant";
|
||||
|
||||
export enum SubmitKey {
|
||||
Enter = "Enter",
|
||||
CtrlEnter = "Ctrl + Enter",
|
||||
ShiftEnter = "Shift + Enter",
|
||||
AltEnter = "Alt + Enter",
|
||||
MetaEnter = "Meta + Enter",
|
||||
}
|
||||
|
||||
export enum Theme {
|
||||
Auto = "auto",
|
||||
Dark = "dark",
|
||||
Light = "light",
|
||||
}
|
||||
|
||||
export const DEFAULT_CONFIG = {
|
||||
submitKey: SubmitKey.CtrlEnter as SubmitKey,
|
||||
avatar: "1f603",
|
||||
fontSize: 14,
|
||||
theme: Theme.Auto as Theme,
|
||||
tightBorder: false,
|
||||
sendPreviewBubble: true,
|
||||
sidebarWidth: 300,
|
||||
|
||||
disablePromptHint: false,
|
||||
|
||||
dontShowMaskSplashScreen: false, // dont show splash screen when create chat
|
||||
|
||||
modelConfig: {
|
||||
model: "gpt-3.5-turbo" as ModelType,
|
||||
temperature: 0.5,
|
||||
max_tokens: 2000,
|
||||
presence_penalty: 0,
|
||||
sendMemory: true,
|
||||
historyMessageCount: 4,
|
||||
compressMessageLengthThreshold: 1000,
|
||||
},
|
||||
};
|
||||
|
||||
export type ChatConfig = typeof DEFAULT_CONFIG;
|
||||
|
||||
export type ChatConfigStore = ChatConfig & {
|
||||
reset: () => void;
|
||||
update: (updater: (config: ChatConfig) => void) => void;
|
||||
};
|
||||
|
||||
export type ModelConfig = ChatConfig["modelConfig"];
|
||||
|
||||
const ENABLE_GPT4 = true;
|
||||
|
||||
export const ALL_MODELS = [
|
||||
{
|
||||
name: "gpt-4",
|
||||
available: ENABLE_GPT4,
|
||||
},
|
||||
{
|
||||
name: "gpt-4-0314",
|
||||
available: ENABLE_GPT4,
|
||||
},
|
||||
{
|
||||
name: "gpt-4-32k",
|
||||
available: ENABLE_GPT4,
|
||||
},
|
||||
{
|
||||
name: "gpt-4-32k-0314",
|
||||
available: ENABLE_GPT4,
|
||||
},
|
||||
{
|
||||
name: "gpt-3.5-turbo",
|
||||
available: true,
|
||||
},
|
||||
{
|
||||
name: "gpt-3.5-turbo-0301",
|
||||
available: true,
|
||||
},
|
||||
{
|
||||
name: "qwen-v1", // 通义千问
|
||||
available: false,
|
||||
},
|
||||
{
|
||||
name: "ernie", // 文心一言
|
||||
available: false,
|
||||
},
|
||||
{
|
||||
name: "spark", // 讯飞星火
|
||||
available: false,
|
||||
},
|
||||
{
|
||||
name: "llama", // llama
|
||||
available: false,
|
||||
},
|
||||
{
|
||||
name: "chatglm", // chatglm-6b
|
||||
available: false,
|
||||
},
|
||||
] as const;
|
||||
|
||||
export type ModelType = (typeof ALL_MODELS)[number]["name"];
|
||||
|
||||
export function limitNumber(
|
||||
x: number,
|
||||
min: number,
|
||||
max: number,
|
||||
defaultValue: number,
|
||||
) {
|
||||
if (typeof x !== "number" || isNaN(x)) {
|
||||
return defaultValue;
|
||||
}
|
||||
|
||||
return Math.min(max, Math.max(min, x));
|
||||
}
|
||||
|
||||
export function limitModel(name: string) {
|
||||
return ALL_MODELS.some((m) => m.name === name && m.available)
|
||||
? name
|
||||
: ALL_MODELS[4].name;
|
||||
}
|
||||
|
||||
export const ModalConfigValidator = {
|
||||
model(x: string) {
|
||||
return limitModel(x) as ModelType;
|
||||
},
|
||||
max_tokens(x: number) {
|
||||
return limitNumber(x, 0, 32000, 2000);
|
||||
},
|
||||
presence_penalty(x: number) {
|
||||
return limitNumber(x, -2, 2, 0);
|
||||
},
|
||||
temperature(x: number) {
|
||||
return limitNumber(x, 0, 1, 1);
|
||||
},
|
||||
};
|
||||
|
||||
export const useAppConfig = create<ChatConfigStore>()(
|
||||
persist(
|
||||
(set, get) => ({
|
||||
...DEFAULT_CONFIG,
|
||||
|
||||
reset() {
|
||||
set(() => ({ ...DEFAULT_CONFIG }));
|
||||
},
|
||||
|
||||
update(updater) {
|
||||
const config = { ...get() };
|
||||
updater(config);
|
||||
set(() => config);
|
||||
},
|
||||
}),
|
||||
{
|
||||
name: StoreKey.Config,
|
||||
version: 2,
|
||||
migrate(persistedState, version) {
|
||||
if (version === 2) return persistedState as any;
|
||||
|
||||
const state = persistedState as ChatConfig;
|
||||
state.modelConfig.sendMemory = true;
|
||||
state.modelConfig.historyMessageCount = 4;
|
||||
state.modelConfig.compressMessageLengthThreshold = 1000;
|
||||
state.dontShowMaskSplashScreen = false;
|
||||
|
||||
return state;
|
||||
},
|
||||
},
|
||||
),
|
||||
);
|
@ -1,3 +1,4 @@
|
||||
export * from "./app";
|
||||
export * from "./chat";
|
||||
export * from "./update";
|
||||
export * from "./access";
|
||||
export * from "./config";
|
||||
|
@ -0,0 +1,100 @@
|
||||
import { create } from "zustand";
|
||||
import { persist } from "zustand/middleware";
|
||||
import { BUILTIN_MASKS } from "../masks";
|
||||
import { getLang, Lang } from "../locales";
|
||||
import { DEFAULT_TOPIC, Message } from "./chat";
|
||||
import { ModelConfig, ModelType, useAppConfig } from "./config";
|
||||
import { StoreKey } from "../constant";
|
||||
|
||||
export type Mask = {
|
||||
id: number;
|
||||
avatar: string;
|
||||
name: string;
|
||||
context: Message[];
|
||||
modelConfig: ModelConfig;
|
||||
lang: Lang;
|
||||
builtin: boolean;
|
||||
};
|
||||
|
||||
export const DEFAULT_MASK_STATE = {
|
||||
masks: {} as Record<number, Mask>,
|
||||
globalMaskId: 0,
|
||||
};
|
||||
|
||||
export type MaskState = typeof DEFAULT_MASK_STATE;
|
||||
type MaskStore = MaskState & {
|
||||
create: (mask?: Partial<Mask>) => Mask;
|
||||
update: (id: number, updater: (mask: Mask) => void) => void;
|
||||
delete: (id: number) => void;
|
||||
search: (text: string) => Mask[];
|
||||
get: (id?: number) => Mask | null;
|
||||
getAll: () => Mask[];
|
||||
};
|
||||
|
||||
export const DEFAULT_MASK_ID = 1145141919810;
|
||||
export const DEFAULT_MASK_AVATAR = "gpt-bot";
|
||||
export const createEmptyMask = () =>
|
||||
({
|
||||
id: DEFAULT_MASK_ID,
|
||||
avatar: DEFAULT_MASK_AVATAR,
|
||||
name: DEFAULT_TOPIC,
|
||||
context: [],
|
||||
modelConfig: { ...useAppConfig.getState().modelConfig },
|
||||
lang: getLang(),
|
||||
builtin: false,
|
||||
} as Mask);
|
||||
|
||||
export const useMaskStore = create<MaskStore>()(
|
||||
persist(
|
||||
(set, get) => ({
|
||||
...DEFAULT_MASK_STATE,
|
||||
|
||||
create(mask) {
|
||||
set(() => ({ globalMaskId: get().globalMaskId + 1 }));
|
||||
const id = get().globalMaskId;
|
||||
const masks = get().masks;
|
||||
masks[id] = {
|
||||
...createEmptyMask(),
|
||||
...mask,
|
||||
id,
|
||||
builtin: false,
|
||||
};
|
||||
|
||||
set(() => ({ masks }));
|
||||
|
||||
return masks[id];
|
||||
},
|
||||
update(id, updater) {
|
||||
const masks = get().masks;
|
||||
const mask = masks[id];
|
||||
if (!mask) return;
|
||||
const updateMask = { ...mask };
|
||||
updater(updateMask);
|
||||
masks[id] = updateMask;
|
||||
set(() => ({ masks }));
|
||||
},
|
||||
delete(id) {
|
||||
const masks = get().masks;
|
||||
delete masks[id];
|
||||
set(() => ({ masks }));
|
||||
},
|
||||
|
||||
get(id) {
|
||||
return get().masks[id ?? 1145141919810];
|
||||
},
|
||||
getAll() {
|
||||
const userMasks = Object.values(get().masks).sort(
|
||||
(a, b) => b.id - a.id,
|
||||
);
|
||||
return userMasks.concat(BUILTIN_MASKS);
|
||||
},
|
||||
search(text) {
|
||||
return Object.values(get().masks);
|
||||
},
|
||||
}),
|
||||
{
|
||||
name: StoreKey.Mask,
|
||||
version: 2,
|
||||
},
|
||||
),
|
||||
);
|
@ -0,0 +1,38 @@
|
||||
# Cloudflare Pages Deployment Guide
|
||||
|
||||
## How to create a new project
|
||||
Fork this project on GitHub, then log in to dash.cloudflare.com and go to Pages.
|
||||
|
||||
1. Click "Create a project".
|
||||
2. Choose "Connect to Git".
|
||||
3. Connect Cloudflare Pages to your GitHub account.
|
||||
4. Select the forked project.
|
||||
5. Click "Begin setup".
|
||||
6. For "Project name" and "Production branch", use the default values or change them as needed.
|
||||
7. In "Build Settings", choose the "Framework presets" option and select "Next.js".
|
||||
8. Do not use the default "Build command" due to a node:buffer bug. Instead, use the following command:
|
||||
```
|
||||
npx https://prerelease-registry.devprod.cloudflare.dev/next-on-pages/runs/4930842298/npm-package-next-on-pages-230 --experimental-minify
|
||||
```
|
||||
9. For "Build output directory", use the default value and do not modify it.
|
||||
10. Do not modify "Root Directory".
|
||||
11. For "Environment variables", click ">" and then "Add variable". Fill in the following information:
|
||||
- `NODE_VERSION=20.1`
|
||||
- `NEXT_TELEMETRY_DISABLE=1`
|
||||
- `OPENAI_API_KEY=your_own_API_key`
|
||||
- `YARN_VERSION=1.22.19`
|
||||
- `PHP_VERSION=7.4`
|
||||
|
||||
Optionally fill in the following based on your needs:
|
||||
|
||||
- `CODE= Optional, access passwords, multiple passwords can be separated by commas`
|
||||
- `OPENAI_ORG_ID= Optional, specify the organization ID in OpenAI`
|
||||
- `HIDE_USER_API_KEY=1 Optional, do not allow users to enter their own API key`
|
||||
- `DISABLE_GPT4=1 Optional, do not allow users to use GPT-4`
|
||||
|
||||
12. Click "Save and Deploy".
|
||||
13. Click "Cancel deployment" because you need to fill in Compatibility flags.
|
||||
14. Go to "Build settings", "Functions", and find "Compatibility flags".
|
||||
15. Fill in "nodejs_compat" for both "Configure Production compatibility flag" and "Configure Preview compatibility flag".
|
||||
16. Go to "Deployments" and click "Retry deployment".
|
||||
17. Enjoy.
|
Before Width: | Height: | Size: 376 KiB After Width: | Height: | Size: 113 KiB |
Before Width: | Height: | Size: 278 KiB After Width: | Height: | Size: 68 KiB |
Before Width: | Height: | Size: 154 KiB After Width: | Height: | Size: 64 KiB |
@ -1,72 +0,0 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { getServerSideConfig } from "./app/config/server";
|
||||
import md5 from "spark-md5";
|
||||
|
||||
export const config = {
|
||||
matcher: ["/api/openai", "/api/chat-stream"],
|
||||
};
|
||||
|
||||
const serverConfig = getServerSideConfig();
|
||||
|
||||
function getIP(req: NextRequest) {
|
||||
let ip = req.ip ?? req.headers.get("x-real-ip");
|
||||
const forwardedFor = req.headers.get("x-forwarded-for");
|
||||
|
||||
if (!ip && forwardedFor) {
|
||||
ip = forwardedFor.split(",").at(0) ?? "";
|
||||
}
|
||||
|
||||
return ip;
|
||||
}
|
||||
|
||||
export function middleware(req: NextRequest) {
|
||||
const accessCode = req.headers.get("access-code");
|
||||
const token = req.headers.get("token");
|
||||
const hashedCode = md5.hash(accessCode ?? "").trim();
|
||||
|
||||
console.log("[Auth] allowed hashed codes: ", [...serverConfig.codes]);
|
||||
console.log("[Auth] got access code:", accessCode);
|
||||
console.log("[Auth] hashed access code:", hashedCode);
|
||||
console.log("[User IP] ", getIP(req));
|
||||
console.log("[Time] ", new Date().toLocaleString());
|
||||
|
||||
if (serverConfig.needCode && !serverConfig.codes.has(hashedCode) && !token) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: true,
|
||||
needAccessCode: true,
|
||||
msg: "Please go settings page and fill your access code.",
|
||||
},
|
||||
{
|
||||
status: 401,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
// inject api key
|
||||
if (!token) {
|
||||
const apiKey = serverConfig.apiKey;
|
||||
if (apiKey) {
|
||||
console.log("[Auth] set system token");
|
||||
req.headers.set("token", apiKey);
|
||||
} else {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: true,
|
||||
msg: "Empty Api Key",
|
||||
},
|
||||
{
|
||||
status: 401,
|
||||
},
|
||||
);
|
||||
}
|
||||
} else {
|
||||
console.log("[Auth] set user token");
|
||||
}
|
||||
|
||||
return NextResponse.next({
|
||||
request: {
|
||||
headers: req.headers,
|
||||
},
|
||||
});
|
||||
}
|
@ -1,18 +0,0 @@
|
||||
/** @type {import('next').NextConfig} */
|
||||
|
||||
const nextConfig = {
|
||||
experimental: {
|
||||
appDir: true,
|
||||
},
|
||||
webpack(config) {
|
||||
config.module.rules.push({
|
||||
test: /\.svg$/,
|
||||
use: ["@svgr/webpack"],
|
||||
});
|
||||
|
||||
return config;
|
||||
},
|
||||
output: "standalone",
|
||||
};
|
||||
|
||||
module.exports = nextConfig;
|
@ -0,0 +1,39 @@
|
||||
/** @type {import('next').NextConfig} */
|
||||
|
||||
const nextConfig = {
|
||||
experimental: {
|
||||
appDir: true,
|
||||
},
|
||||
async rewrites() {
|
||||
const ret = [
|
||||
{
|
||||
source: "/api/proxy/:path*",
|
||||
destination: "https://api.openai.com/:path*",
|
||||
},
|
||||
];
|
||||
|
||||
const apiUrl = process.env.API_URL;
|
||||
if (apiUrl) {
|
||||
console.log("[Next] using api url ", apiUrl);
|
||||
ret.push({
|
||||
source: "/api/:path*",
|
||||
destination: `${apiUrl}/:path*`,
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
beforeFiles: ret,
|
||||
};
|
||||
},
|
||||
webpack(config) {
|
||||
config.module.rules.push({
|
||||
test: /\.svg$/,
|
||||
use: ["@svgr/webpack"],
|
||||
});
|
||||
|
||||
return config;
|
||||
},
|
||||
output: "standalone",
|
||||
};
|
||||
|
||||
export default nextConfig;
|
@ -1,5 +1,6 @@
|
||||
dir="$(dirname "$0")"
|
||||
config=$dir/proxychains.conf
|
||||
host_ip=$(grep nameserver /etc/resolv.conf | sed 's/nameserver //')
|
||||
echo "proxying to $host_ip"
|
||||
cp $dir/proxychains.template.conf $config
|
||||
sed -i "\$s/.*/http $host_ip 7890/" $config
|
||||
|