feat: finish basic functions

This commit is contained in:
Yidadaa
2023-03-11 02:25:33 +08:00
parent 9912762157
commit 2c9baa4e2c
17 changed files with 2234 additions and 189 deletions

12
app/404.tsx Normal file
View File

@@ -0,0 +1,12 @@
import Link from "next/link";
export default function FourOhFour() {
return (
<>
<h1>404 - Page Not Found</h1>
<Link href="/">
<a>Go back home</a>
</Link>
</>
);
}

12
app/500.tsx Normal file
View File

@@ -0,0 +1,12 @@
import Link from "next/link";
export default function FourOhFour() {
return (
<>
<h1>500 - Page Not Found</h1>
<Link href="/">
<a>Go back home</a>
</Link>
</>
);
}

View File

@@ -1,5 +1,6 @@
import { OpenAIApi, Configuration } from "openai";
import { apiKey } from "./config";
import { ChatRequest } from "./typing";
// set up openai api client
const config = new Configuration({
@@ -7,17 +8,12 @@ const config = new Configuration({
});
const openai = new OpenAIApi(config);
export async function GET(req: Request) {
export async function POST(req: Request) {
try {
const requestBody = (await req.json()) as ChatRequest;
const completion = await openai.createChatCompletion(
{
messages: [
{
role: "user",
content: "hello",
},
],
model: "gpt-3.5-turbo",
...requestBody,
},
{
proxy: {

View File

@@ -1,3 +0,0 @@
export async function GET(request: Request) {
return new Response('Hello, Next.js!')
}

View File

@@ -15,6 +15,7 @@ export function IconButton(props: {
styles["icon-button"] +
` ${props.bordered && styles.border} ${props.className ?? ""}`
}
onClick={props.onClick}
>
<div className={styles["icon-button-icon"]}>{props.icon}</div>
{props.text && (

View File

@@ -1,7 +1,7 @@
.container {
max-width: 1080px;
max-height: 780px;
min-width: 600px;
min-height: 480px;
width: 90vw;
height: 90vh;
background-color: var(--white);
@@ -19,7 +19,7 @@
background-color: var(--second);
display: flex;
flex-direction: column;
box-shadow:inset -2px 0px 2px 0px rgb(0, 0, 0, 0.05);
box-shadow: inset -2px 0px 2px 0px rgb(0, 0, 0, 0.05);
}
.sidebar-header {
@@ -40,7 +40,7 @@
}
.sidebar-sub-title {
font-size: 12px;
font-size: 12px;
font-weight: 400px;
}
@@ -59,9 +59,23 @@
border-radius: 10px;
margin-bottom: 10px;
box-shadow: var(--card-shadow);
transition: all .3s ease;
transition: all 0.3s ease;
cursor: pointer;
user-select: none;
border: 2px solid transparent;
position: relative;
overflow: hidden;
}
@keyframes slide-in {
from {
opacity: 0;
transform: translateY(20px);
}
to {
opacity: 1;
transform: translateY(0px);
}
}
.chat-item:hover {
@@ -69,12 +83,34 @@
}
.chat-item-selected {
border: 2px solid var(--primary);
border-color: var(--primary);
}
.chat-item-title {
font-size: 14px;
font-weight: bolder;
display: block;
width: 200px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.chat-item-delete {
position: absolute;
top: 10px;
right: -20px;
transition: all ease 0.3s;
opacity: 0;
}
.chat-item:hover > .chat-item-delete {
opacity: 0.5;
right: 10px;
}
.chat-item:hover > .chat-item-delete:hover {
opacity: 1;
}
.chat-item-info {
@@ -85,8 +121,11 @@
margin-top: 8px;
}
.chat-item-count {}
.chat-item-date {}
.chat-item-count {
}
.chat-item-date {
}
.sidebar-tail {
display: flex;
@@ -97,6 +136,7 @@
.sidebar-actions {
display: inline-flex;
}
.sidebar-action:last-child {
margin-left: 15px;
}
@@ -116,17 +156,26 @@
justify-content: space-between;
align-items: center;
}
.chat-header-title {
font-size: 20px;
font-weight: bolder;
overflow: hidden;
text-overflow: ellipsis;
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
}
.chat-header-sub-title {
font-size: 14px;
margin-top: 5px;
}
.chat-actions {
display: inline-flex;
}
.chat-action-button {
margin-left: 10px;
}
@@ -137,9 +186,10 @@
padding: 20px;
margin-bottom: 100px;
}
.chat-message {
display: flex;
flex-direction: row;
flex-direction: row;
}
.chat-message-user {
@@ -148,42 +198,68 @@
}
.chat-message-container {
width: 60%;
max-width: 60%;
display: flex;
flex-direction: column;
align-items: flex-start;
animation: slide-in ease 0.3s;
}
.chat-message-user > .chat-message-container {
align-items: flex-end;
}
.chat-message-avtar {}
.chat-message-avatar {
margin-top: 20px;
}
.chat-message-status {
font-size: 12px;
color: #aaa;
line-height: 1.5;
margin-top: 5px;
}
.user-avtar {
height: 30px;
width: 30px;
display: flex;
align-items: center;
justify-content: center;
border: var(--border-in-light);
box-shadow: var(--card-shadow);
border-radius: 10px;
}
.chat-message-item {
margin-top: 5px;
border-radius: 10px;
background-color: rgba(0, 0, 0, 0.05);
padding: 10px;
font-size: 14px;
margin-top: 5px;
user-select: text;
word-break: break-all;
}
.chat-message-user > .chat-message-container > .chat-message-item {
background-color: var(--second);
}
.chat-message-actions{
.chat-message-actions {
display: flex;
flex-direction: row-reverse;
width: 100%;
padding: 5px 10px;
padding-top: 5px;
box-sizing: border-box;
}
.chat-message-action-date{
.chat-message-action-date {
font-size: 12px;
color: #aaa;
}
.chat-message-action-button{}
.chat-message-action-button {
}
.chat-input-panel {
position: absolute;
@@ -199,7 +275,9 @@
flex: 1;
}
.chat-input-panel-multi {}
.chat-input-panel-multi {
}
.chat-input {
height: 100%;
width: 100%;
@@ -217,11 +295,11 @@
border: 1px solid var(--primary);
}
.chat-input-send{
.chat-input-send {
background-color: var(--primary);
color: white;
position: absolute;
right: 30px;
bottom: 10px;
}
}

View File

@@ -1,5 +1,8 @@
"use client";
import { useState, useRef, useLayoutEffect, useEffect } from "react";
import ReactMarkdown from "react-markdown";
import { IconButton } from "./button";
import styles from "./home.module.css";
@@ -10,11 +13,23 @@ import SendWhiteIcon from "../icons/send-white.svg";
import BrainIcon from "../icons/brain.svg";
import ExportIcon from "../icons/export.svg";
import BotIcon from "../icons/bot.svg";
import UserIcon from "../icons/user.svg";
import AddIcon from "../icons/add.svg";
import DeleteIcon from "../icons/delete.svg";
import LoadingIcon from "../icons/three-dots.svg";
import { Message, useChatStore } from "../store";
export function Avatar(props: { role: Message["role"] }) {
if (props.role === "assistant") {
return <BotIcon className={styles["user-avtar"]} />;
}
return <div className={styles["user-avtar"]}>🤣</div>;
}
export function ChatItem(props: {
onClick?: () => void;
onDelete?: () => void;
title: string;
count: number;
time: string;
@@ -25,58 +40,106 @@ export function ChatItem(props: {
className={`${styles["chat-item"]} ${
props.selected && styles["chat-item-selected"]
}`}
onClick={props.onClick}
>
<div className={styles["chat-item-title"]}>{props.title}</div>
<div className={styles["chat-item-info"]}>
<div className={styles["chat-item-count"]}>{props.count} </div>
<div className={styles["chat-item-date"]}>{props.time}</div>
</div>
<div className={styles["chat-item-delete"]} onClick={props.onDelete}>
<DeleteIcon />
</div>
</div>
);
}
export function ChatList() {
const listData = new Array(5).fill({
title: "这是一个标题",
count: 10,
time: new Date().toLocaleString(),
});
const selectedIndex = 0;
const [sessions, selectedIndex, selectSession, removeSession] = useChatStore(
(state) => [
state.sessions,
state.currentSessionIndex,
state.selectSession,
state.removeSession,
]
);
return (
<div className={styles["chat-list"]}>
{listData.map((item, i) => (
<ChatItem {...item} key={i} selected={i === selectedIndex} />
{sessions.map((item, i) => (
<ChatItem
title={item.topic}
time={item.lastUpdate}
count={item.messages.length}
key={i}
selected={i === selectedIndex}
onClick={() => selectSession(i)}
onDelete={() => removeSession(i)}
/>
))}
</div>
);
}
export function Chat() {
const messages = [
{
role: "user",
content: "这是一条消息",
date: new Date().toLocaleString(),
},
{
role: "bot",
content: "这是一条回复".repeat(10),
date: new Date().toLocaleString(),
},
];
type RenderMessage = Message & { preview?: boolean };
const title = "这是一个标题";
const count = 10;
const session = useChatStore((state) => state.currentSession());
const [userInput, setUserInput] = useState("");
const [isLoading, setIsLoading] = useState(false);
const onUserInput = useChatStore((state) => state.onUserInput);
const onUserSubmit = () => {
if (userInput.length <= 0) return;
setIsLoading(true);
onUserInput(userInput).then(() => setIsLoading(false));
setUserInput("");
};
const onInputKeyDown = (e: KeyboardEvent) => {
if (e.key === "Enter" && (e.shiftKey || e.ctrlKey || e.metaKey)) {
onUserSubmit();
e.preventDefault();
}
};
const latestMessageRef = useRef<HTMLDivElement>(null);
const messages = (session.messages as RenderMessage[])
.concat(
isLoading
? [
{
role: "assistant",
content: "……",
date: new Date().toLocaleString(),
preview: true,
},
]
: []
)
.concat(
userInput.length > 0
? [
{
role: "user",
content: userInput,
date: new Date().toLocaleString(),
preview: true,
},
]
: []
);
useEffect(() => {
latestMessageRef.current?.scrollIntoView(false);
});
return (
<div className={styles.chat}>
<div className={styles["chat-header"]}>
<div>
<div className={styles["chat-header-title"]}>{title}</div>
<div className={styles["chat-header-title"]}>{session.topic}</div>
<div className={styles["chat-header-sub-title"]}>
ChatGPT {count}
ChatGPT {session.messages.length}
</div>
</div>
<div className={styles["chat-actions"]}>
@@ -101,16 +164,25 @@ export function Chat() {
}
>
<div className={styles["chat-message-container"]}>
<div className={styles["chat-message-avtar"]}>
{message.role === "user" ? <UserIcon /> : <BotIcon />}
<div className={styles["chat-message-avatar"]}>
<Avatar role={message.role} />
</div>
{message.preview && (
<div className={styles["chat-message-status"]}></div>
)}
<div className={styles["chat-message-item"]}>
{message.content}
{message.preview && !isUser ? (
<LoadingIcon />
) : (
<div className="markdown-body">
<ReactMarkdown>{message.content}</ReactMarkdown>
</div>
)}
</div>
{!isUser && (
{!isUser && !message.preview && (
<div className={styles["chat-message-actions"]}>
<div className={styles["chat-message-action-date"]}>
{message.date}
{message.date.toLocaleString()}
</div>
</div>
)}
@@ -118,19 +190,26 @@ export function Chat() {
</div>
);
})}
<span ref={latestMessageRef} style={{ opacity: 0 }}>
-
</span>
</div>
<div className={styles["chat-input-panel"]}>
<div className={styles["chat-input-panel-inner"]}>
<textarea
className={styles["chat-input"]}
placeholder="输入消息"
placeholder="输入消息Ctrl + Enter 发送"
rows={3}
onInput={(e) => setUserInput(e.currentTarget.value)}
value={userInput}
onKeyDown={(e) => onInputKeyDown(e as any)}
/>
<IconButton
icon={<SendWhiteIcon />}
text={"发送"}
className={styles["chat-input-send"]}
onClick={onUserSubmit}
/>
</div>
</div>
@@ -139,6 +218,8 @@ export function Chat() {
}
export function Home() {
const [createNewSession] = useChatStore((state) => [state.newSession]);
return (
<div className={styles.container}>
<div className={styles.sidebar}>
@@ -162,11 +243,17 @@ export function Home() {
<IconButton icon={<SettingsIcon />} />
</div>
<div className={styles["sidebar-action"]}>
<IconButton icon={<GithubIcon />} />
<a href="https://github.com/Yidadaa" target="_blank">
<IconButton icon={<GithubIcon />} />
</a>
</div>
</div>
<div>
<IconButton icon={<AddIcon />} text={"新的聊天"} />
<IconButton
icon={<AddIcon />}
text={"新的聊天"}
onClick={createNewSession}
/>
</div>
</div>
</div>

View File

@@ -8,11 +8,10 @@
/* shadow */
--shadow: 50px 50px 100px 10px rgb(0, 0, 0, 0.1);
--card-shadow:0px 2px 4px 0px rgb(0, 0, 0, 0.05);
--card-shadow: 0px 2px 4px 0px rgb(0, 0, 0, 0.05);
/* stroke */
--border-in-light: 1px solid rgb(222, 222, 222);
--border-in-light: 1px solid rgb(222, 222, 222);
}
body {
@@ -40,4 +39,4 @@ body {
border-radius: 20px;
border: 6px solid transparent;
background-clip: content-box;
}
}

12
app/icons/delete.svg Normal file

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 23 KiB

33
app/icons/three-dots.svg Normal file
View File

@@ -0,0 +1,33 @@
<!-- By Sam Herbert (@sherb), for everyone. More @ http://goo.gl/7AJzbL -->
<svg width="30" height="14" viewBox="0 0 120 30" xmlns="http://www.w3.org/2000/svg" fill="#fff">
<circle cx="15" cy="15" r="15" fill="var(--primary, red)">
<animate attributeName="r" from="15" to="15"
begin="0s" dur="0.8s"
values="15;9;15" calcMode="linear"
repeatCount="indefinite" />
<animate attributeName="fill-opacity" from="1" to="1"
begin="0s" dur="0.8s"
values="1;.5;1" calcMode="linear"
repeatCount="indefinite" />
</circle>
<circle cx="60" cy="15" r="9" fill-opacity="0.3" fill="var(--primary, red)">
<animate attributeName="r" from="9" to="9"
begin="0s" dur="0.8s"
values="9;15;9" calcMode="linear"
repeatCount="indefinite" />
<animate attributeName="fill-opacity" from="0.5" to="0.5"
begin="0s" dur="0.8s"
values=".5;1;.5" calcMode="linear"
repeatCount="indefinite" />
</circle>
<circle cx="105" cy="15" r="15" fill="var(--primary, red)">
<animate attributeName="r" from="15" to="15"
begin="0s" dur="0.8s"
values="15;9;15" calcMode="linear"
repeatCount="indefinite" />
<animate attributeName="fill-opacity" from="1" to="1"
begin="0s" dur="0.8s"
values="1;.5;1" calcMode="linear"
repeatCount="indefinite" />
</circle>
</svg>

After

Width:  |  Height:  |  Size: 1.5 KiB

View File

@@ -1,4 +1,5 @@
import "./globals.css";
import "./markdown.css";
export const metadata = {
title: "ChatGPT Next Web",

1103
app/markdown.css Normal file

File diff suppressed because it is too large Load Diff

38
app/requests.ts Normal file
View File

@@ -0,0 +1,38 @@
import type { ChatRequest, ChatReponse } from "./api/chat/typing";
import { Message } from "./store";
export async function requestChat(messages: Message[]) {
const req: ChatRequest = {
model: "gpt-3.5-turbo",
messages: messages
.map((v) => ({
role: v.role,
content: v.content,
}))
.filter((m) => m.role !== "assistant"),
};
const res = await fetch("/api/chat", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(req),
});
return (await res.json()) as ChatReponse;
}
export async function requestWithPrompt(messages: Message[], prompt: string) {
messages = messages.concat([
{
role: "system",
content: prompt,
date: new Date().toLocaleString(),
},
]);
const res = await requestChat(messages);
return res.choices.at(0)?.message?.content ?? "";
}

View File

@@ -1,40 +1,187 @@
import { type ChatCompletionResponseMessage } from "openai";
import { create } from "zustand";
import { persist } from "zustand/middleware";
export type Message = ChatCompletionResponseMessage;
import { type ChatCompletionResponseMessage } from "openai";
import { requestChat, requestWithPrompt } from "./requests";
import { trimTopic } from "./utils";
export type Message = ChatCompletionResponseMessage & {
date: string;
};
interface ChatConfig {
maxToken: number;
}
class ChatSession {
constructor(private id: string) {}
public async onChatMessage(message: Message) {
if (message.role === "assistant") {
// do nothing
} else if (message.role === "user") {
// TODO: request open chat
this.makeRequest();
} else throw Error("Only assistant or users message allowed here.");
this.historyMessages.push(message);
this.summarize();
this.save();
}
public async summarize() {}
public save() {}
public delete() {}
private makeRequest() {}
private topic = "";
private memoryPrompt = "";
private historyMessages: Message[] = [];
private messageWordCount = 0;
interface ChatStat {
tokenCount: number;
wordCount: number;
charCount: number;
}
class ChatSessionManager {
private entryId = "chatgpt-next-web-sessions";
interface ChatSession {
topic: string;
memoryPrompt: string;
messages: Message[];
stat: ChatStat;
lastUpdate: string;
deleted?: boolean;
}
export const store = {};
const DEFAULT_TOPIC = "新的聊天";
function createEmptySession(): ChatSession {
const createDate = new Date().toLocaleString();
return {
topic: DEFAULT_TOPIC,
memoryPrompt: "",
messages: [
{
role: "assistant",
content: "有什么可以帮你的吗",
date: createDate,
},
],
stat: {
tokenCount: 0,
wordCount: 0,
charCount: 0,
},
lastUpdate: createDate,
};
}
interface ChatStore {
sessions: ChatSession[];
currentSessionIndex: number;
removeSession: (index: number) => void;
selectSession: (index: number) => void;
newSession: () => void;
currentSession: () => ChatSession;
onNewMessage: (message: Message) => void;
onUserInput: (content: string) => Promise<void>;
onBotResponse: (message: Message) => void;
summarizeSession: () => void;
updateStat: (message: Message) => void;
updateCurrentSession: (updater: (session: ChatSession) => void) => void;
}
export const useChatStore = create<ChatStore>()(
persist(
(set, get) => ({
sessions: [createEmptySession()],
currentSessionIndex: 0,
selectSession(index: number) {
set({
currentSessionIndex: index,
});
},
removeSession(index: number) {
set((state) => {
let nextIndex = state.currentSessionIndex;
const sessions = state.sessions;
if (sessions.length === 1) {
return {
currentSessionIndex: 0,
sessions: [createEmptySession()],
};
}
sessions.splice(index, 1);
if (nextIndex === index) {
nextIndex -= 1;
}
return {
currentSessionIndex: nextIndex,
sessions,
};
});
},
newSession() {
set((state) => ({
currentSessionIndex: state.sessions.length,
sessions: state.sessions.concat([createEmptySession()]),
}));
},
currentSession() {
let index = get().currentSessionIndex;
const sessions = get().sessions;
if (index < 0 || index >= sessions.length) {
index = Math.min(sessions.length - 1, Math.max(0, index));
set(() => ({ currentSessionIndex: index }));
}
return sessions[index];
},
onNewMessage(message) {
get().updateCurrentSession((session) => {
session.messages.push(message);
});
get().updateStat(message);
get().summarizeSession();
},
async onUserInput(content) {
const message: Message = {
role: "user",
content,
date: new Date().toLocaleString(),
};
const messages = get().currentSession().messages.concat(message);
get().onNewMessage(message);
const res = await requestChat(messages);
get().onNewMessage({
...res.choices[0].message!,
date: new Date().toLocaleString(),
});
},
onBotResponse(message) {
get().onNewMessage(message);
},
summarizeSession() {
const session = get().currentSession();
if (session.topic !== DEFAULT_TOPIC) return;
requestWithPrompt(
session.messages,
"简明扼要地 10 字以内总结主题"
).then((res) => {
get().updateCurrentSession(
(session) => (session.topic = trimTopic(res))
);
});
},
updateStat(message) {
get().updateCurrentSession((session) => {
session.stat.charCount += message.content.length;
// TODO: should update chat count and word count
});
},
updateCurrentSession(updater) {
const sessions = get().sessions;
const index = get().currentSessionIndex;
updater(sessions[index]);
set(() => ({ sessions }));
},
}),
{ name: "chat-next-web-store" }
)
);

11
app/utils.ts Normal file
View File

@@ -0,0 +1,11 @@
export function trimTopic(topic: string) {
const s = topic.split("").slice(0, 20);
let lastChar = s.at(-1); // 获取 s 的最后一个字符
let pattern = /[,。!?、]/; // 定义匹配中文标点符号的正则表达式
while (lastChar && pattern.test(lastChar!)) {
s.pop();
lastChar = s.at(-1);
}
return s.join("");
}