Skip to content

Commit

Permalink
init
Browse files Browse the repository at this point in the history
  • Loading branch information
liu-ziting committed Dec 28, 2023
1 parent 97f9b4c commit 5623baf
Show file tree
Hide file tree
Showing 82 changed files with 12,380 additions and 1 deletion.
26 changes: 26 additions & 0 deletions .eslintrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
{
"$schema": "https://json.schemastore.org/eslintrc",
"root": true,
"extends": [
"next/core-web-vitals",
"prettier",
"plugin:tailwindcss/recommended"
],
"plugins": ["tailwindcss"],
"rules": {
"tailwindcss/no-custom-classname": "off",
"tailwindcss/classnames-order": "off"
},
"settings": {
"tailwindcss": {
"callees": ["cn", "cva"],
"config": "tailwind.config.js"
}
},
"overrides": [
{
"files": ["*.ts", "*.tsx"],
"parser": "@typescript-eslint/parser"
}
]
}
39 changes: 39 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.

# dependencies
node_modules
.pnp
.pnp.js

# testing
coverage

# next.js
.next/
out/
build

# misc
.DS_Store
*.pem

# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*
.pnpm-debug.log*

# local env files
.env.local
.env.development.local
.env.test.local
.env.production.local

# turbo
.turbo

.env
.vercel
.vscode
.env*.local
node_modules
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2023 sinnedpenguin

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1 +1 @@
# gemini-chat
## GeminiChat
47 changes: 47 additions & 0 deletions app/(chat)/chat/[id]/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import { type Metadata } from 'next'
import { notFound, redirect } from 'next/navigation'

import { auth } from '@/auth'
import { getChat } from '@/app/actions'
import { Chat } from '@/components/chat'

export interface ChatPageProps {
params: {
id: string
}
}

export async function generateMetadata({
params
}: ChatPageProps): Promise<Metadata> {
const session = await auth()

if (!session?.user) {
return {}
}

const chat = await getChat(params.id, session.user.id)
return {
title: chat?.title.toString().slice(0, 50) ?? 'Chat'
}
}

export default async function ChatPage({ params }: ChatPageProps) {
const session = await auth()

if (!session?.user) {
redirect(`/sign-in?next=/chat/${params.id}`)
}

const chat = await getChat(params.id, session.user.id)

if (!chat) {
notFound()
}

if (chat?.userId !== session?.user?.id) {
notFound()
}

return <Chat id={chat.id} initialMessages={chat.messages} />
}
17 changes: 17 additions & 0 deletions app/(chat)/layout.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { SidebarDesktop } from '@/components/sidebar-desktop'

interface ChatLayoutProps {
children: React.ReactNode
}

export default async function ChatLayout({ children }: ChatLayoutProps) {
return (
<div className="relative flex h-[calc(100vh_-_theme(spacing.16))] overflow-hidden">
{/* @ts-ignore */}
<SidebarDesktop />
<div className="group w-full overflow-auto pl-0 animate-in duration-300 ease-in-out peer-[[data-state=open]]:lg:pl-[250px] peer-[[data-state=open]]:xl:pl-[300px]">
{children}
</div>
</div>
)
}
8 changes: 8 additions & 0 deletions app/(chat)/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { nanoid } from '@/lib/utils'
import { Chat } from '@/components/chat'

export default function IndexPage() {
const id = nanoid()

return <Chat id={id} />
}
120 changes: 120 additions & 0 deletions app/actions.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
'use server'

import { revalidatePath } from 'next/cache'
import { redirect } from 'next/navigation'
import { kv } from '@vercel/kv'

import { auth } from '@/auth'
import { type Chat } from '@/lib/types'

export async function getChats(userId?: string | null) {
if (!userId) {
return []
}

try {
const pipeline = kv.pipeline()
const chats: string[] = await kv.zrange(`user:chat:${userId}`, 0, -1, {
rev: true
})

for (const chat of chats) {
pipeline.hgetall(chat)
}

const results = await pipeline.exec()

return results as Chat[]
} catch (error) {
return []
}
}

export async function getChat(id: string, userId: string) {
const chat = await kv.hgetall<Chat>(`chat:${id}`)

if (!chat || (userId && chat.userId !== userId)) {
return null
}

return chat
}

export async function removeChat({ id, path }: { id: string; path: string }) {
const session = await auth()

if (!session) {
return {
error: 'Unauthorized'
}
}

await kv.del(`chat:${id}`)
await kv.zrem(`user:chat:${session.user.id}`, `chat:${id}`)

revalidatePath('/')
return revalidatePath(path)
}

export async function clearChats() {
const session = await auth()

if (!session?.user?.id) {
return {
error: 'Unauthorized'
}
}

const chats: string[] = await kv.zrange(`user:chat:${session.user.id}`, 0, -1)
if (!chats.length) {
return redirect('/')
}
const pipeline = kv.pipeline()

for (const chat of chats) {
pipeline.del(chat)
pipeline.zrem(`user:chat:${session.user.id}`, chat)
}

await pipeline.exec()

revalidatePath('/')
return redirect('/')
}

export async function getSharedChat(id: string) {
const chat = await kv.hgetall<Chat>(`chat:${id}`)

if (!chat || !chat.sharePath) {
return null
}

return chat
}

export async function shareChat(id: string) {
const session = await auth()

if (!session?.user?.id) {
return {
error: 'Unauthorized'
}
}

const chat = await kv.hgetall<Chat>(`chat:${id}`)

if (!chat || chat.userId !== session.user.id) {
return {
error: 'Something went wrong'
}
}

const payload = {
...chat,
sharePath: `/share/${chat.id}`
}

await kv.hmset(`chat:${chat.id}`, payload)

return payload
}
2 changes: 2 additions & 0 deletions app/api/auth/[...nextauth]/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export { GET, POST } from '@/auth'
export const runtime = 'edge'
81 changes: 81 additions & 0 deletions app/api/chat/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
import { auth } from '@/auth';
import { kv } from '@vercel/kv';
import { nanoid } from '@/lib/utils';
import { genAI, generationConfig, safetySettings } from '@/lib/config';

export async function POST(req: Request) {
const json = await req.json();
const { messages } = json;
const userId = (await auth())?.user.id;

if (!userId) {
return new Response('Unauthorized', {
status: 401,
});
}

const model = genAI.getGenerativeModel({ model: process.env.MODEL });

if (messages.length === 0 || messages[messages.length - 1].role !== 'user') {
messages.push({
role: 'user',
content: '',
});
}

const chatHistory = messages.map((message: { role: string; content: string; }) => ({
role: message.role,
parts: [message.content],
}));

const chat = model.startChat({
history: chatHistory.map((entry: { parts: string; responseMessage: string; }) => [
{ role: 'user', parts: entry.parts },
{ role: 'model', parts: entry.responseMessage || '' },
]).flat(),
generationConfig,
safetySettings,
});

const { readable, writable } = new TransformStream();
const writer = writable.getWriter();

(async () => {
let text = '';
const result = await chat.sendMessageStream(messages[messages.length - 1].content);

for await (const chunk of result.stream) {
const chunkText = chunk.text();
text += chunkText;
await writer.write(new TextEncoder().encode(chunkText));
}

const id = json.id ?? nanoid();
const createdAt = new Date().toISOString();
const path = `/chat/${id}`;

const assistantReply = {
content: text,
role: 'model',
};

const payload = {
id,
title: messages[0].content.substring(0, 100),
userId,
createdAt,
path,
messages: [...messages, assistantReply],
};

await kv.hmset(`chat:${id}`, payload);
await kv.zadd(`user:chat:${userId}`, {
score: new Date(createdAt).getTime(),
member: `chat:${id}`,
});

await writer.close();
})();

return new Response(readable);
}
Loading

0 comments on commit 5623baf

Please sign in to comment.