Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
SVG-campus committed Jul 12, 2024
0 parents commit cf297df
Show file tree
Hide file tree
Showing 124 changed files with 13,827 additions and 0 deletions.
16 changes: 16 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
# Then get your Google Gemini API Key here: https://cloud.google.com/vertex-ai
GOOGLE_GENERATIVE_AI_API_KEY=XXXXXXXX

# Generate a random secret: https://generate-secret.vercel.app/32 or `openssl rand -base64 32`
AUTH_SECRET=XXXXXXXX

# Instructions to create kv database here: https://vercel.com/docs/storage/vercel-kv/quickstart and
KV_URL=XXXXXXXX
KV_REST_API_URL=XXXXXXXX
KV_REST_API_TOKEN=XXXXXXXX
KV_REST_API_READ_ONLY_TOKEN=XXXXXXXX

# Get your kasada configurations here: https://kasada.io
KASADA_API_ENDPOINT=XXXXXXXX
KASADA_API_VERSION=XXXXXXXX
KASADA_HEADER_HOST=XXXXXXXX
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"
}
]
}
38 changes: 38 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
# 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
13 changes: 13 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
Copyright 2023 Vercel, Inc.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
66 changes: 66 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
<a href="https://chat.vercel.ai/">
<img alt="Next.js 14 and App Router-ready AI chatbot." src="https://gemini-chatbot.vercel.rocks/og.png">
<h1 align="center">Next.js AI Chatbot</h1>
</a>

<p align="center">
An open-source AI chatbot app template built with Next.js, the Vercel AI SDK, Google Gemini, and Vercel KV.
</p>

<p align="center">
<a href="#features"><strong>Features</strong></a> ·
<a href="#model-providers"><strong>Model Providers</strong></a> ·
<a href="#deploy-your-own"><strong>Deploy Your Own</strong></a> ·
<a href="#running-locally"><strong>Running locally</strong></a> ·
<a href="#authors"><strong>Authors</strong></a>
</p>
<br/>

## Features

- [Next.js](https://nextjs.org) App Router
- React Server Components (RSCs), Suspense, and Server Actions
- [Vercel AI SDK](https://sdk.vercel.ai/docs) for streaming chat UI
- Support for Google Gemini (default), OpenAI, Anthropic, Cohere, Hugging Face, or custom AI chat models and/or LangChain
- [shadcn/ui](https://ui.shadcn.com)
- Styling with [Tailwind CSS](https://tailwindcss.com)
- [Radix UI](https://radix-ui.com) for headless component primitives
- Icons from [Phosphor Icons](https://phosphoricons.com)
- Chat History, rate limiting, and session storage with [Vercel KV](https://vercel.com/storage/kv)
- [NextAuth.js](https://github.com/nextauthjs/next-auth) for authentication

## Model Providers

This template ships with Google Gemini `models/gemini-1.0-pro-001` as the default. However, thanks to the [Vercel AI SDK](https://sdk.vercel.ai/docs), you can switch LLM providers to [OpenAI](https://openai.com), [Anthropic](https://anthropic.com), [Cohere](https://cohere.com/), [Hugging Face](https://huggingface.co), or using [LangChain](https://js.langchain.com) with just a few lines of code.

## Deploy Your Own

You can deploy your own version of the Next.js AI Chatbot to Vercel with one click:

[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/clone?demo-title=Next.js+Chat&demo-description=A+full-featured%2C+hackable+Next.js+AI+chatbot+built+by+Vercel+Labs&demo-url=https%3A%2F%2Fchat.vercel.ai%2F&demo-image=%2F%2Fimages.ctfassets.net%2Fe5382hct74si%2F4aVPvWuTmBvzM5cEdRdqeW%2F4234f9baf160f68ffb385a43c3527645%2FCleanShot_2023-06-16_at_17.09.21.png&project-name=Next.js+Chat&repository-name=nextjs-chat&repository-url=https%3A%2F%2Fgithub.com%2Fvercel-labs%2Fgemini-chatbot&from=templates&skippable-integrations=1&env=GOOGLE_GENERATIVE_AI_API_KEY%2CAUTH_SECRET&envDescription=How+to+get+these+env+vars&envLink=https%3A%2F%2Fgithub.com%2Fvercel-labs%2Fgemini-chatbot%2Fblob%2Fmain%2F.env.example&teamCreateStatus=hidden&stores=[{%22type%22:%22kv%22}])

## Running locally

You will need to use the environment variables [defined in `.env.example`](.env.example) to run Next.js AI Chatbot. It's recommended you use [Vercel Environment Variables](https://vercel.com/docs/projects/environment-variables) for this, but a `.env` file is all that is necessary.

> Note: You should not commit your `.env` file or it will expose secrets that will allow others to control access to your various Google Cloud and authentication provider accounts.
1. Install Vercel CLI: `npm i -g vercel`
2. Link local instance with Vercel and GitHub accounts (creates `.vercel` directory): `vercel link`
3. Download your environment variables: `vercel env pull`

```bash
pnpm install
pnpm dev
```

Your app template should now be running on [localhost:3000](http://localhost:3000/).

## Authors

This library is created by [Vercel](https://vercel.com) and [Next.js](https://nextjs.org) team members, with contributions from:

- Jared Palmer ([@jaredpalmer](https://twitter.com/jaredpalmer)) - [Vercel](https://vercel.com)
- Shu Ding ([@shuding\_](https://twitter.com/shuding_)) - [Vercel](https://vercel.com)
- shadcn ([@shadcn](https://twitter.com/shadcn)) - [Vercel](https://vercel.com)
- Jeremy Philemon ([@jrmyphlmn](https://twitter.com/jrmyphlmn)) - [Vercel](https://vercel.com)
66 changes: 66 additions & 0 deletions app/(chat)/chat/[id]/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import { type Metadata } from 'next'
import { notFound, redirect } from 'next/navigation'

import { auth } from '@/auth'
import { getChat, getMissingKeys } from '@/app/actions'
import { Chat } from '@/components/chat'
import { AI } from '@/lib/chat/actions'
import { Session } from '@/lib/types'

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()) as Session
const missingKeys = await getMissingKeys()

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

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

if (!chat) {
redirect('/')
}

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

return (
<AI
initialAIState={{
chatId: chat.id,
messages: chat.messages,
interactions: []
}}
>
<Chat
id={chat.id}
session={session}
initialMessages={chat.messages}
missingKeys={missingKeys}
/>
</AI>
)
}
19 changes: 19 additions & 0 deletions app/(chat)/error.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
'use client'

export default function Error({
error
}: {
error: Error & { digest?: string }
}) {
return (
<div className="container mx-auto px-4 py-8 text-center">
<h1 className="text-lg font-semibold mb-2">
Oops, something went wrong!
</h1>
<p>
{error.message || 'The AI got rate limited, please try again later.'}
</p>
<p>Digest: {error.digest}</p>
</div>
)
}
14 changes: 14 additions & 0 deletions app/(chat)/layout.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
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">
<SidebarDesktop />
{children}
</div>
)
}
22 changes: 22 additions & 0 deletions app/(chat)/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { nanoid } from '@/lib/utils'
import { Chat } from '@/components/chat'
import { AI } from '@/lib/chat/actions'
import { auth } from '@/auth'
import { Session } from '@/lib/types'
import { getMissingKeys } from '../actions'

export const metadata = {
title: 'Next.js AI Chatbot'
}

export default async function IndexPage() {
const id = nanoid()
const session = (await auth()) as Session
const missingKeys = await getMissingKeys()

return (
<AI initialAIState={{ chatId: id, interactions: [], messages: [] }}>
<Chat id={id} session={session} missingKeys={missingKeys} />
</AI>
)
}
10 changes: 10 additions & 0 deletions app/(chat)/waiting-room/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
'use client'

export default function Page() {
return (
<div className="container mx-auto px-4 py-8 text-center">
<h1 className="text-lg font-semibold mb-2">You are in the queue</h1>
<p>Please try again in a few minutes.</p>
</div>
)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
export const runtime = 'edge'
export const dynamic = 'force-dynamic'
export const maxDuration = 3

async function handler(request: Request) {
const url = new URL(request.url)

url.protocol = 'https:'
url.host = process.env.KASADA_API_ENDPOINT || ''
url.port = ''
url.searchParams.delete('restpath')

const headers = new Headers(request.headers)
headers.set('X-Forwarded-Host', process.env.KASADA_HEADER_HOST || '')
headers.delete('host')
const r = await fetch(url.toString(), {
method: request.method,
body: request.body,
headers,
mode: request.mode,
redirect: 'manual',
// @ts-expect-error
duplex: 'half'
})
const responseHeaders = new Headers(r.headers)
responseHeaders.set('cdn-cache-control', 'no-cache')
return new Response(r.body, {
status: r.status,
statusText: r.statusText,
headers: responseHeaders
})
}

export const GET = handler
export const POST = handler
export const OPTIONS = handler
export const PUT = handler
Loading

0 comments on commit cf297df

Please sign in to comment.