Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/chatbot error handling #49

Open
wants to merge 16 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 12 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .env.example
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
DATABASE_URL=
NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY=
CLERK_SECRET_KEY=
GEMINI_API_KEY=
NEXT_PUBLIC_UMAMI_WEBSITE_ID
5 changes: 4 additions & 1 deletion .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,5 +10,8 @@
"typescript": "typescriptreact"
},
"javascript.updateImportsOnFileMove.enabled": "always",
"typescript.updateImportsOnFileMove.enabled": "always"
"typescript.updateImportsOnFileMove.enabled": "always",
"[typescriptreact]": {
"editor.defaultFormatter": "vscode.typescript-language-features"
}
}
1,853 changes: 1,282 additions & 571 deletions package-lock.json

Large diffs are not rendered by default.

28 changes: 19 additions & 9 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,25 +13,33 @@
},
"dependencies": {
"@clerk/nextjs": "^5.2.4",
"@mdx-js/loader": "^3.1.0",
"@mdx-js/react": "^3.1.0",
"@google/generative-ai": "^0.21.0",
"@heroicons/react": "^2.1.5",
"@mdx-js/loader": "^3.0.1",
"@mdx-js/react": "^3.0.1",
"@neondatabase/serverless": "^0.9.4",
"@next/mdx": "^14.2.22",
"@prisma/client": "^5.17.0",
"@radix-ui/react-dialog": "^1.1.4",
"@radix-ui/react-dropdown-menu": "^2.1.4",
"@radix-ui/react-popover": "^1.1.4",
"@radix-ui/react-slot": "^1.1.1",
"@radix-ui/react-tabs": "^1.1.2",
"@radix-ui/react-dialog": "^1.1.1",
"@radix-ui/react-dropdown-menu": "^2.1.1",
"@radix-ui/react-popover": "^1.1.2",
"@radix-ui/react-slot": "^1.1.0",
"@radix-ui/react-tabs": "^1.1.0",
"@radix-ui/react-toast": "^1.2.2",
"@types/dompurify": "^3.0.5",
"@types/mdx": "^2.0.13",
"@vercel/analytics": "^1.3.1",
"@vercel/speed-insights": "^1.0.12",
"algoliasearch": "^4.24.0",
"axios": "^1.7.4",
"class-variance-authority": "^0.7.0",
"clsx": "^2.1.1",
"framer-motion": "^11.15.0",
"dompurify": "^3.2.2",
"framer-motion": "^10.18.0",
"geist": "^1.3.1",
"gray-matter": "^4.0.3",
"highlight.js": "^11.10.0",
"html-react-parser": "^5.1.18",
"lucide-react": "^0.416.0",
"mermaid": "^11.0.2",
"next": "^14.2.13",
Expand All @@ -42,7 +50,9 @@
"react-icons": "^5.4.0",
"react-instantsearch-dom": "^6.40.4",
"react-type-animation": "^3.2.0",
"tailwind-merge": "^2.6.0",
"rehype-highlight": "^7.0.0",
"sonner": "^1.7.0",
"tailwind-merge": "^2.4.0",
"tailwindcss-animate": "^1.0.7",
"uuid": "^11.0.3",
"vaul": "^0.9.1",
Expand Down
98 changes: 58 additions & 40 deletions src/app/api/summarize/route.ts
Original file line number Diff line number Diff line change
@@ -1,50 +1,68 @@
import { NextResponse } from "next/server"
import axios from "axios"

const ANTHROPIC_API_KEY = process.env.ANTHROPIC_API_KEY
const ANTHROPIC_API_URL = "https://api.anthropic.com/v1/messages"

import { GenerativeModel, GoogleGenerativeAI, GoogleGenerativeAIError } from "@google/generative-ai";
import { NextResponse } from "next/server";


const GEMINI_API_KEY = process.env.GEMINI_API_KEY;

if (!GEMINI_API_KEY) {
throw new Error("Something went wrong while fetching API Keys.")
}
let model:GenerativeModel;
try {
const genAI = new GoogleGenerativeAI(GEMINI_API_KEY!);
model = genAI.getGenerativeModel({
model: "gemini-1.5-flash",
systemInstruction:
"You're an AI assistant, Who only answers questions related to the blog post that have provided to you in the prompt.\n\n" +
"Try to Answer using numeric points for readability and Bold the title of the point.\n\n" +
"If the user wants help related to the topic mentioned in the blog you can answer that.\n\n" +
"If the question is not related to the blog post or the topic that is mentioned on the blog, Throw error response."
});
} catch (error) {
console.error('Failed to initialize Gemini model:', error);
throw new Error('Failed to initialize AI service. Please try again later.');
}

export async function POST(request: Request) {
const body = await request.json();

if (!body.content || typeof body.content !== 'string' || !body.query || typeof body.query !== 'string') {
return NextResponse.json(
{ error: 'Invalid request: content and query are required and must be strings', success: false },
{ status: 400 }
);
}

const { content, query } = body;

try {
const { content, query } = await request.json()
const prompt = `Here's a blog post:\n\n${content}\n\nQuestion: ${query}`;

const result = await model.generateContent(prompt);
return NextResponse.json({
answer: result.response.text(),
})
}
catch (error: any) {
const isGoogleAIError = error instanceof GoogleGenerativeAIError;

if (!ANTHROPIC_API_KEY) {
throw new Error("ANTHROPIC_API_KEY is not set")
}
console.error('API Error:', {
type: isGoogleAIError ? 'GoogleGenerativeAI' : 'Unknown',
message: error.message,
timestamp: new Date().toISOString()
});

const response = await axios.post(
ANTHROPIC_API_URL,
const clientMessage = isGoogleAIError
? 'The AI service is temporarily unavailable. Please try again later.'
: 'Internal Server Error. Please try again after some time.';

return NextResponse.json(
{
model: "claude-3-sonnet-20240229",
messages: [
{
role: "system",
content:
"You are an AI assistant that answers questions about blog posts.",
},
{
role: "human",
content: `Here's a blog post:\n\n${content}\n\nQuestion: ${query}`,
},
],
max_tokens: 1000,
error: clientMessage
},
{
headers: {
"Content-Type": "application/json",
"x-api-key": ANTHROPIC_API_KEY,
"anthropic-version": "2023-06-01",
},
}
)

const answer = response.data.content[0].text
return NextResponse.json({ answer })
} catch (error: any) {
console.error("Error in API:", error.response?.data || error.message)
return NextResponse.json(
{ error: "Error processing request. Please try again." },
{ status: error.response?.status || 500 }
)
{ status: isGoogleAIError ? 503 : 500 }
);
}
}
1 change: 1 addition & 0 deletions src/app/blog/[slug]/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,7 @@ export default async function BlogPost({
<BlogHeader
slug={params.slug}
title={post.title}
description={post.description}
publishedAt={post.publishedAt}
initialViews={initialViews}
content={post.content}
Expand Down
18 changes: 18 additions & 0 deletions src/app/globals.css
Original file line number Diff line number Diff line change
Expand Up @@ -29,3 +29,21 @@ html {
linear-gradient(to bottom, rgba(0, 0, 0, 0.1) 1px, transparent 1px);
background-size: 20px 20px;
}

.section-divider {
width: 100%;
height: 2px;
background-color: #333;
margin: 40px 0;
}

.ChatArea::-webkit-scrollbar {
width: 6px;
border-radius: 4px;
background-color: #6e6b6b;
}

.ChatArea::-webkit-scrollbar-thumb {
background-color: white;
border-radius: 4px;
}
11 changes: 9 additions & 2 deletions src/app/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ import { SocialMetadata } from "@/components/SocialMetadata"
import { cn } from "@/lib/utils"

import "./globals.css"
import { Toaster } from '@/components/ui/toaster';


export const metadata: Metadata = {
title: {
Expand Down Expand Up @@ -100,8 +102,13 @@ export default function RootLayout({ children }: RootLayoutProps) {
)}
>
<ClerkProvider>
<Navbar />
{children}
<div className="flex flex-col min-h-screen">
<Navbar />
<main className="flex-grow container mx-auto px-4 sm:px-6 lg:px-8 ">
{children}
</main>
</div>
<Toaster></Toaster>
</ClerkProvider>
<Analytics />
</body>
Expand Down
Loading