Skip to content

Commit ce6a7aa

Browse files
committed
Initial commit
0 parents  commit ce6a7aa

File tree

130 files changed

+23425
-0
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

130 files changed

+23425
-0
lines changed

‎.env.example‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
# Get your OpenAI API Key here: https://platform.openai.com/account/api-keys
2+
OPENAI_API_KEY=****
3+
4+
# Generate a random secret: https://generate-secret.vercel.app/32 or `openssl rand -base64 32`
5+
AUTH_SECRET=****
6+
7+
# The following keys below are automatically created and
8+
# added to your environment when you deploy on vercel
9+
10+
# Instructions to create a Vercel Blob Store here: https://vercel.com/docs/storage/vercel-blob
11+
BLOB_READ_WRITE_TOKEN=****
12+
13+
# Instructions to create a database here: https://vercel.com/docs/storage/vercel-postgres/quickstart
14+
POSTGRES_URL=****

‎.eslintrc.json‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
{
2+
"extends": [
3+
"next/core-web-vitals",
4+
"plugin:import/recommended",
5+
"plugin:import/typescript",
6+
"prettier",
7+
"plugin:tailwindcss/recommended"
8+
],
9+
"plugins": ["tailwindcss"],
10+
"rules": {
11+
"tailwindcss/no-custom-classname": "off",
12+
"tailwindcss/classnames-order": "off"
13+
},
14+
"settings": {
15+
"import/resolver": {
16+
"typescript": {
17+
"alwaysTryTypes": true
18+
}
19+
}
20+
},
21+
"ignorePatterns": ["**/components/ui/**"]
22+
}

‎.gitignore‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
2+
3+
# dependencies
4+
node_modules
5+
.pnp
6+
.pnp.js
7+
8+
# testing
9+
coverage
10+
11+
# next.js
12+
.next/
13+
out/
14+
build
15+
16+
# misc
17+
.DS_Store
18+
*.pem
19+
20+
# debug
21+
npm-debug.log*
22+
yarn-debug.log*
23+
yarn-error.log*
24+
.pnpm-debug.log*
25+
26+
# local env files
27+
.env.local
28+
.env.development.local
29+
.env.test.local
30+
.env.production.local
31+
32+
# turbo
33+
.turbo
34+
35+
.env
36+
.vercel
37+
.vscode
38+
.env*.local

‎LICENSE‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
Copyright 2024 Vercel, Inc.
2+
3+
Licensed under the Apache License, Version 2.0 (the "License");
4+
you may not use this file except in compliance with the License.
5+
You may obtain a copy of the License at
6+
7+
http://www.apache.org/licenses/LICENSE-2.0
8+
9+
Unless required by applicable law or agreed to in writing, software
10+
distributed under the License is distributed on an "AS IS" BASIS,
11+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
See the License for the specific language governing permissions and
13+
limitations under the License.

‎README.md‎

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
2+
# Extract.chat
3+
4+
An Open-Source AI Chatbot w/ Firecrawl Integrated - Fork of Vercel's AI Chatbot
5+
6+
## Features
7+
8+
- [Firecrawl](https://firecrawl.dev) Search + Extract
9+
- Feed realtime data to the AI via search
10+
- Extract structured data from multiple websites via extract
11+
- [Next.js](https://nextjs.org) App Router
12+
- Advanced routing for seamless navigation and performance
13+
- React Server Components (RSCs) and Server Actions for server-side rendering and increased performance
14+
- [AI SDK](https://sdk.vercel.ai/docs)
15+
- Unified API for generating text, structured objects, and tool calls with LLMs
16+
- Hooks for building dynamic chat and generative user interfaces
17+
- Supports OpenAI (default), Anthropic, Cohere, and other model providers
18+
- [shadcn/ui](https://ui.shadcn.com)
19+
- Styling with [Tailwind CSS](https://tailwindcss.com)
20+
- Component primitives from [Radix UI](https://radix-ui.com) for accessibility and flexibility
21+
- Data Persistence
22+
- [Vercel Postgres powered by Neon](https://vercel.com/storage/postgres) for saving chat history and user data
23+
- [Vercel Blob](https://vercel.com/storage/blob) for efficient file storage
24+
- [NextAuth.js](https://github.com/nextauthjs/next-auth)
25+
- Simple and secure authentication
26+
27+
## Model Providers
28+
29+
This template ships with OpenAI `gpt-4o` as the default. However, with the [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/), and [many more](https://sdk.vercel.ai/providers/ai-sdk-providers) with just a few lines of code.
30+
31+
## Deploy Your Own
32+
33+
You can deploy your own version of the Next.js AI Chatbot to Vercel with one click:
34+
35+
[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/clone?repository-url=https%3A%2F%2Fgithub.com%2Fvercel%2Fai-chatbot&env=AUTH_SECRET,OPENAI_API_KEY&envDescription=Learn%20more%20about%20how%20to%20get%20the%20API%20Keys%20for%20the%20application&envLink=https%3A%2F%2Fgithub.com%2Fvercel%2Fai-chatbot%2Fblob%2Fmain%2F.env.example&demo-title=AI%20Chatbot&demo-description=An%20Open-Source%20AI%20Chatbot%20Template%20Built%20With%20Next.js%20and%20the%20AI%20SDK%20by%20Vercel.&demo-url=https%3A%2F%2Fchat.vercel.ai&stores=[{%22type%22:%22postgres%22},{%22type%22:%22blob%22}])
36+
37+
## Running locally
38+
39+
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.
40+
41+
> Note: You should not commit your `.env` file or it will expose secrets that will allow others to control access to your various OpenAI and authentication provider accounts.
42+
43+
1. Install Vercel CLI: `npm i -g vercel`
44+
2. Link local instance with Vercel and GitHub accounts (creates `.vercel` directory): `vercel link`
45+
3. Download your environment variables: `vercel env pull`
46+
47+
```bash
48+
pnpm install
49+
pnpm dev
50+
```
51+
52+
Your app template should now be running on [localhost:3000](http://localhost:3000/).

‎app/(auth)/actions.ts‎

Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
'use server';
2+
3+
import { z } from 'zod';
4+
5+
import { createUser, getUser } from '@/lib/db/queries';
6+
7+
import { signIn } from './auth';
8+
9+
const authFormSchema = z.object({
10+
email: z.string().email(),
11+
password: z.string().min(6),
12+
});
13+
14+
export interface LoginActionState {
15+
status: 'idle' | 'in_progress' | 'success' | 'failed' | 'invalid_data';
16+
}
17+
18+
export const login = async (
19+
_: LoginActionState,
20+
formData: FormData,
21+
): Promise<LoginActionState> => {
22+
try {
23+
const validatedData = authFormSchema.parse({
24+
email: formData.get('email'),
25+
password: formData.get('password'),
26+
});
27+
28+
await signIn('credentials', {
29+
email: validatedData.email,
30+
password: validatedData.password,
31+
redirect: false,
32+
});
33+
34+
return { status: 'success' };
35+
} catch (error) {
36+
if (error instanceof z.ZodError) {
37+
return { status: 'invalid_data' };
38+
}
39+
40+
return { status: 'failed' };
41+
}
42+
};
43+
44+
export interface RegisterActionState {
45+
status:
46+
| 'idle'
47+
| 'in_progress'
48+
| 'success'
49+
| 'failed'
50+
| 'user_exists'
51+
| 'invalid_data';
52+
}
53+
54+
export const register = async (
55+
_: RegisterActionState,
56+
formData: FormData,
57+
): Promise<RegisterActionState> => {
58+
try {
59+
const validatedData = authFormSchema.parse({
60+
email: formData.get('email'),
61+
password: formData.get('password'),
62+
});
63+
64+
const [user] = await getUser(validatedData.email);
65+
66+
if (user) {
67+
return { status: 'user_exists' } as RegisterActionState;
68+
}
69+
await createUser(validatedData.email, validatedData.password);
70+
await signIn('credentials', {
71+
email: validatedData.email,
72+
password: validatedData.password,
73+
redirect: false,
74+
});
75+
76+
return { status: 'success' };
77+
} catch (error) {
78+
if (error instanceof z.ZodError) {
79+
return { status: 'invalid_data' };
80+
}
81+
82+
return { status: 'failed' };
83+
}
84+
};
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
export { GET, POST } from '@/app/(auth)/auth';

‎app/(auth)/auth.config.ts‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
import type { NextAuthConfig } from 'next-auth';
2+
3+
export const authConfig = {
4+
pages: {
5+
newUser: '/',
6+
},
7+
providers: [
8+
// added later in auth.ts since it requires bcrypt which is only compatible with Node.js
9+
// while this file is also used in non-Node.js environments
10+
],
11+
callbacks: {
12+
authorized({ auth, request: { nextUrl } }) {
13+
const isLoggedIn = !!auth?.user;
14+
const isOnRegister = nextUrl.pathname.startsWith('/register');
15+
const isOnLogin = nextUrl.pathname.startsWith('/login');
16+
17+
// Redirect authenticated users away from auth pages
18+
if (isLoggedIn && (isOnLogin || isOnRegister)) {
19+
return Response.redirect(new URL('/', nextUrl as unknown as URL));
20+
}
21+
22+
// Allow access to everything
23+
return true;
24+
},
25+
},
26+
} satisfies NextAuthConfig;

‎app/(auth)/auth.ts‎

Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
import { compare } from 'bcrypt-ts';
2+
import NextAuth, { type User, type Session } from 'next-auth';
3+
import Credentials from 'next-auth/providers/credentials';
4+
5+
import { getUser, createUser } from '@/lib/db/queries';
6+
import { authConfig } from './auth.config';
7+
8+
interface ExtendedSession extends Session {
9+
user: User;
10+
}
11+
12+
async function createAnonymousUser() {
13+
const anonymousEmail = `anon_${Date.now()}@anonymous.user`;
14+
const anonymousPassword = `anon_${Date.now()}_${Math.random().toString(36).slice(2)}`;
15+
16+
try {
17+
await createUser(anonymousEmail, anonymousPassword);
18+
const [user] = await getUser(anonymousEmail);
19+
return user;
20+
} catch (error) {
21+
console.error('Failed to create anonymous user:', error);
22+
return null;
23+
}
24+
}
25+
26+
export const {
27+
handlers: { GET, POST },
28+
auth,
29+
signIn,
30+
signOut,
31+
} = NextAuth({
32+
...authConfig,
33+
providers: [
34+
Credentials({
35+
credentials: {},
36+
async authorize({ email, password }: any) {
37+
// Handle anonymous access
38+
if (!email && !password) {
39+
return await createAnonymousUser();
40+
}
41+
42+
// Handle regular authentication
43+
const users = await getUser(email);
44+
if (users.length === 0) return null;
45+
// biome-ignore lint: Forbidden non-null assertion.
46+
const passwordsMatch = await compare(password, users[0].password!);
47+
if (!passwordsMatch) return null;
48+
return users[0] as any;
49+
},
50+
}),
51+
],
52+
callbacks: {
53+
async jwt({ token, user }) {
54+
if (user) {
55+
token.id = user.id;
56+
} else if (!token.id) {
57+
// Create anonymous user if no user exists
58+
const anonymousUser = await createAnonymousUser();
59+
if (anonymousUser) {
60+
token.id = anonymousUser.id;
61+
token.email = anonymousUser.email;
62+
}
63+
}
64+
65+
return token;
66+
},
67+
async session({
68+
session,
69+
token,
70+
}: {
71+
session: ExtendedSession;
72+
token: any;
73+
}) {
74+
if (session.user) {
75+
session.user.id = token.id as string;
76+
session.user.email = token.email as string;
77+
}
78+
79+
return session;
80+
},
81+
},
82+
});

0 commit comments

Comments
 (0)