Skip to content

Commit

Permalink
Merge pull request #62 from ArhanAnsari/ArhanAnsari-patch-1
Browse files Browse the repository at this point in the history
Update askQuestions.ts
  • Loading branch information
ArhanAnsari authored Sep 29, 2024
2 parents b4b12a4 + bd83b71 commit 6ccdb7c
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 46 deletions.
67 changes: 31 additions & 36 deletions actions/askQuestions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { adminDb } from "@/firebaseAdmin";
const PRO_LIMIT = 500;
const FREE_LIMIT = 50;

// Function to handle storing questions and generating AI content
// Function to handle storing questions and answers
export async function askQuestion({
userId,
question,
Expand All @@ -27,7 +27,6 @@ export async function askQuestion({
const userRef = await adminDb.collection("users").doc(userId).get();
const userData = userRef.data();

// Enforce limits for free and PRO users
if (!userData?.hasActiveMembership && userMessages.length >= FREE_LIMIT) {
return {
success: false,
Expand All @@ -42,39 +41,33 @@ export async function askQuestion({
};
}

// Generate AI content via absolute URL for /api/generate
try {
const response = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/generate`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ prompt: question }),
});

if (!response.ok) {
const errorData = await response.json();
return {
success: false,
message: errorData.error || "Error generating AI content.",
};
}

const data = await response.json();
const reply = data.generatedContent; // AI-generated content from Google Gemini
// Call the API to generate the response from Google Gemini
const response = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/generate`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
prompt: question,
}),
});

const data = await response.json();
if (!response.ok || !data.generatedContent) {
return {
success: false,
message: "Error generating AI content.",
};
}

// Save the question and AI-generated response to Firestore
await generatedContentRef.add({
question,
response: reply,
createdAt: new Date(),
});
// Save the question and response to generatedContent
await generatedContentRef.add({
question,
response: data.generatedContent,
createdAt: new Date(),
});

return { success: true, message: reply };
} catch (error) {
console.error("Error generating AI content:", error);
return { success: false, message: "Error generating AI content." };
}
return { success: true, message: data.generatedContent };
}

// Function to fetch previously generated content
Expand All @@ -92,10 +85,12 @@ export async function fetchGeneratedContent(userId: string) {
return [];
}

// Map through documents to extract data
// Ensure serializable data by mapping Firestore documents to plain JavaScript objects
const generatedContent = snapshot.docs.map((doc) => ({
id: doc.id,
...doc.data(),
id: doc.id, // Firestore document ID
question: doc.data().question || "", // The question asked
response: doc.data().response || "", // The AI-generated response
createdAt: doc.data().createdAt.toMillis(), // Convert Firestore Timestamp to milliseconds
}));

return generatedContent;
Expand Down
26 changes: 16 additions & 10 deletions app/dashboard/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ export default function Dashboard() {
if (session?.user?.email) {
try {
const content = await fetchGeneratedContent(session.user.email);
setPreviousContent(content);
setPreviousContent(content); // Update state with serialized content
} catch (error) {
console.error("Error fetching previous content:", error);
toast.error("Failed to load previous content.");
Expand Down Expand Up @@ -92,8 +92,11 @@ export default function Dashboard() {
}
}

// Generate AI content using Google Gemini
const result = await askQuestion({ userId: session.user.email, question: input });
// Generate AI content
const result = await askQuestion({
userId: session.user.email,
question: input,
});

if (!result.success) {
toast.error(result.message);
Expand Down Expand Up @@ -156,20 +159,23 @@ export default function Dashboard() {

{/* Display previously generated content */}
<div className="mt-6">
<h2 className="text-xl font-semibold mb-4">Your Previous Content</h2>
{previousContent.length > 0 ? (
<ul className="list-disc list-inside space-y-2">
<h2 className="text-xl font-semibold mb-4">Previously Generated Content</h2>
{previousContent.length ? (
<ul className="space-y-4">
{previousContent.map((content) => (
<li key={content.id}>
<li key={content.id} className="border p-4 rounded">
<h3 className="font-semibold">{content.question}</h3>
<MarkdownRenderer content={content.response} />
<p className="text-sm text-gray-500">
Generated on {new Date(content.createdAt).toLocaleString()}
</p>
</li>
))}
</ul>
) : (
<p className="text-gray-500">No previously generated content found.</p>
<p>No previous content found.</p>
)}
</div>

{/* Star us on GitHub Button */}
<div className="mt-8">
<a
Expand All @@ -182,7 +188,7 @@ export default function Dashboard() {
Star us on GitHub
</a>
</div>

<ToastContainer />
</div>
);
Expand Down

0 comments on commit 6ccdb7c

Please sign in to comment.