Skip to content

Commit

Permalink
Commit my changes to GitHub
Browse files Browse the repository at this point in the history
  • Loading branch information
git-create-devben committed Aug 2, 2024
1 parent 935fd0a commit b0ff9c1
Show file tree
Hide file tree
Showing 59 changed files with 1,886 additions and 1,058 deletions.
2 changes: 1 addition & 1 deletion .idx/integrations.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,4 @@
"gemini_api": {},
"google_maps_platform": {},
"secrets_manager": {}
}
}
3 changes: 3 additions & 0 deletions .prettierignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# Ignore artifacts:
build
coverage
1 change: 1 addition & 0 deletions .prettierrc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{}
38 changes: 19 additions & 19 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -1,20 +1,20 @@
{
"cSpell.words": [
"admindb",
"autosize",
"Bookingaction",
"chatpage",
"Deafultchatpage",
"firstvisitpopup",
"geocode",
"googlemaps",
"Horizonal",
"Jsons",
"Loca",
"Superjson",
"vertexai",
"viewmore"
],
"IDX.aI.enableInlineCompletion": true,
"IDX.aI.enableCodebaseIndexing": true
}
"cSpell.words": [
"admindb",
"autosize",
"Bookingaction",
"chatpage",
"Deafultchatpage",
"firstvisitpopup",
"geocode",
"googlemaps",
"Horizonal",
"Jsons",
"Loca",
"Superjson",
"vertexai",
"viewmore"
],
"IDX.aI.enableInlineCompletion": true,
"IDX.aI.enableCodebaseIndexing": true
}
12 changes: 6 additions & 6 deletions app/api/debug/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@
import { NextRequest, NextResponse } from "next/server";

export async function GET(req: NextRequest, res: NextResponse) {
const test = {
PROJECT_GOOGLE:JSON.parse( JSON.stringify(process.env.GOOGLE_APPLICATION_CREDENTIALS_JSON)),

}
return NextResponse.json({HELLO: "HELLO WORLD", DEBUG: test})
const test = {
PROJECT_GOOGLE: JSON.parse(
JSON.stringify(process.env.GOOGLE_APPLICATION_CREDENTIALS_JSON),
),
};
return NextResponse.json({ HELLO: "HELLO WORLD", DEBUG: test });
}
51 changes: 41 additions & 10 deletions app/api/gemini/route.ts
Original file line number Diff line number Diff line change
@@ -1,67 +1,98 @@
import { NextRequest } from "next/server";
import { GoogleGenerativeAI } from "@google/generative-ai";
import { getLocalServices } from "@/lib/getLocationServices";
import { keyword } from "@/lib/keywords";

// Initialize the Google Generative AI with the provided API key
const genAI = new GoogleGenerativeAI(process.env.GEMINI_API_KEY || "");

// Handle POST requests
export async function POST(req: NextRequest) {
// Parse the request body to get userMessage, latitude, and longitude
const { userMessage, latitude, longitude } = await req.json();

// Validate the required fields
if (!userMessage || !latitude || !longitude) {
return new Response(
JSON.stringify({ error: "----- Missing required fields: userMessage, latitude, or longitude -----" }),
{ status: 400 }
JSON.stringify({
error:
"----- Missing required fields: userMessage, latitude, or longitude -----",
}),
{ status: 400 },
);
}

// Initialize the encoder and stream for sending responses
const encoder = new TextEncoder();
const stream = new TransformStream();
const writer = stream.writable.getWriter();

// Function to write chunks of data to the stream
const writeChunk = async (chunk: { type: string; data: any }) => {
await writer.write(encoder.encode(JSON.stringify(chunk) + '\n'));
await writer.write(encoder.encode(JSON.stringify(chunk) + "\n"));
};

// Asynchronous function to handle the main logic
(async () => {
try {
// Extract service keywords from the user message
const serviceKeywords = extractServiceKeywords(userMessage);
let services = [];
if (serviceKeywords) {
// Fetch local services based on the extracted keywords and location
services = await getLocalServices(serviceKeywords, latitude, longitude);
await writeChunk({ type: 'services', data: services });
await writeChunk({ type: "services", data: services });
}

// Get the generative model from Google Generative AI
const model = genAI.getGenerativeModel({ model: "gemini-1.5-pro" });

// Create a prompt for the AI model
const prompt = `You are Loca, a local AI service finder. ${
services.length > 0
? `Here are some available services: ${JSON.stringify(services)}. Provide a helpful response based on this information, highlighting the best options.`
: `Provide a general response about "${userMessage}". If the user is asking about local services, suggest how they might find them.`
}`;

// Generate content stream from the AI model based on the prompt
const result = await model.generateContentStream(prompt);

// Write the generated content to the stream
for await (const chunk of result.stream) {
const chunkText = chunk.text();
await writeChunk({ type: 'text', data: chunkText });
await writeChunk({ type: "text", data: chunkText });
}

// Send services again at the end to ensure they're not missed
if (services.length > 0) {
await writeChunk({ type: "services", data: services });
}
} catch (error) {
// Handle errors and write an error message to the stream
console.error(" ---- Server Error:", error);
await writeChunk({ type: 'error', data: "An error occurred while processing your request." });
await writeChunk({
type: "error",
data: "An error occurred while processing your request.",
});
} finally {
// Close the writer
writer.close();
}
})();

// Return the readable stream as the response
return new Response(stream.readable, {
headers: { "Content-Type": "text/plain; charset=utf-8" },
});
}

// Function to extract service keywords from the input string
function extractServiceKeywords(input: string): string | null {
const keywords = ["plumber", "nearby", 'downtown', 'near me', "any", "electrician", "mechanic", "restaurant", "dentist"];
// Import keywords from @lib/keywords
const keywords = keyword;
const lowercaseInput = input.toLowerCase();


// Check if the input contains any of the keywords
for (const keyword of keywords) {
if (lowercaseInput.includes(keyword)) {
const words = lowercaseInput.split(/\s+/);
Expand All @@ -73,6 +104,6 @@ function extractServiceKeywords(input: string): string | null {
return `${keyword} near me`;
}
}

return null;
}
}
12 changes: 0 additions & 12 deletions app/chat/booking/page.tsx

This file was deleted.

38 changes: 0 additions & 38 deletions app/chat/layout.tsx

This file was deleted.

52 changes: 50 additions & 2 deletions app/chat/page.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,60 @@
"use client";
import Main from "@/components/main";
import Sidebar from "@/components/sidebar";
import { onAuthStateChanged } from "firebase/auth";
import { useEffect, useState } from "react";
import { auth } from "@/lib/firebase";
import local from "@/public/png/logo-black.png";
import Image from "next/image";
import FirstVisitPopup from "@/components/firstvisitpopup";
import { SignOut } from "@/lib/signIn";
import { LogOut } from "lucide-react";
export default function Chat() {
const [user, setUser] = useState(auth.currentUser);
const image = user?.photoURL || local;

useEffect(() => {
const unsubscribe = onAuthStateChanged(auth, (currentUser) => {
setUser(currentUser);
});

return () => unsubscribe();
});
return (
<main className=" bg-black">
<main className=" flex bg-black">
<FirstVisitPopup />
<div className=" bg-[#1212] min-h-[100vh] pb-[15vh] relative ">
<div className=" hidden lg:block">
<Sidebar />
</div>
<div className=" bg-[#1212] min-h-[100vh] pb-[15vh] relative flex-1 ">
<div className="flex flex-col max-h-[830px] overflow-y-scroll scroll-m-1">
<div className="sticky top-0 w-full shadow-lg">
<nav className="flex justify-between p-4 ">
<span
className="text-[#caccce] font-medium text-3xl cursor-pointer"
onClick={() => (window.location.href = "/")}
>
Loca
</span>
<div className="flex gap-6 items-center">
<div
className="flex gap-1 cursor-pointer text-[#ccc] lg:hidden"
onClick={SignOut}
>
<LogOut />
<span className="animate-fadeIn xs:hidden">LogOut</span>
</div>
<Image
src={image}
alt="user"
className="rounded-full"
width={50}
height={50}
/>
</div>
</nav>
</div>

<div className="self-center max-w-[900px] m-auto h-screen px-4">
<Main />
</div>
Expand Down
Loading

0 comments on commit b0ff9c1

Please sign in to comment.