mirror of
https://github.com/PinkSheep27/SBU-Hackathon.git
synced 2026-10-10 23:00:25 -04:00
Merge branch 'main' of https://github.com/PinkSheep27/SBU-Hackathon
This commit is contained in:
@@ -0,0 +1,24 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { chatToGemini } from "@/app/utils/geminiHelper";
|
||||
import { ChatHistory, ChatSetting } from "@/app/exportType/types";
|
||||
|
||||
|
||||
export async function POST(request: Request) {
|
||||
try {
|
||||
const { userMessage, history , settings } = await request.json() as {
|
||||
userMessage :string;
|
||||
history : ChatHistory;
|
||||
settings : ChatSetting;
|
||||
};
|
||||
|
||||
const aiResponse = await chatToGemini(userMessage , history, settings);
|
||||
return NextResponse.json({response : aiResponse});
|
||||
}
|
||||
catch(error){
|
||||
console.error(error);
|
||||
return NextResponse.json(
|
||||
{error: "Error with the model response "},
|
||||
{status : 500}
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { chatToGemini } from "@/app/utils/geminiHelper";
|
||||
import { ChatSetting } from "@/app/exportType/types";
|
||||
|
||||
|
||||
export async function POST(request: Request) {
|
||||
try {
|
||||
const { prompt, settings } = await request.json() as {
|
||||
prompt :string;
|
||||
settings : ChatSetting;
|
||||
};
|
||||
|
||||
const aiResponse = await chatToGemini(prompt , [], settings);
|
||||
return NextResponse.json({response : aiResponse});
|
||||
}
|
||||
catch(error){
|
||||
console.error(error);
|
||||
return NextResponse.json(
|
||||
{error: "Error with the model response "},
|
||||
{status : 500}
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,210 @@
|
||||
"use client";
|
||||
|
||||
import React, { useState, useEffect } from "react";
|
||||
import { motion, useMotionValue, useTransform, useAnimation } from "framer-motion";
|
||||
import { useRouter } from "next/navigation";
|
||||
|
||||
// 1. Updated ColorWay interface
|
||||
interface ColorWay {
|
||||
card: string;
|
||||
text: string;
|
||||
titleColor: string; // Added title color
|
||||
}
|
||||
|
||||
// 2. Updated COLOR_WAYS array
|
||||
const COLOR_WAYS: ColorWay[] = [
|
||||
{ card: "#FEEEDF", text: "#173C46", titleColor: "#173C46" },
|
||||
{ card: "#FEEEDF", text: "#EA627F", titleColor: "#173C46" }, // Example: Title is dark, text is pink
|
||||
{ card: "#DEE5D4", text: "#173C46", titleColor: "#EA627F" },
|
||||
{ card: "#DEE5D4", text: "#EA627F", titleColor: "#173C46" },
|
||||
{ card: "#B8C0AD", text: "#173C46", titleColor: "#173C46" },
|
||||
{ card: "#B8C0AD", text: "#173C46", titleColor: "#EA627F" },
|
||||
];
|
||||
|
||||
interface CardData {
|
||||
id: number;
|
||||
title: string;
|
||||
summary: string;
|
||||
tracks: string[];
|
||||
}
|
||||
|
||||
const SwipeCards: React.FC<{ initialCards: CardData[] }> = ({ initialCards }) => {
|
||||
const [cards, setCards] = useState<CardData[]>(initialCards);
|
||||
const router = useRouter();
|
||||
|
||||
// Update cards state when initialCards prop changes
|
||||
useEffect(() => {
|
||||
setCards(initialCards);
|
||||
}, [initialCards]);
|
||||
|
||||
const removeCard = () => {
|
||||
setCards((prev) => prev.slice(0, prev.length - 1));
|
||||
};
|
||||
|
||||
const handleAccept = (cardData: CardData) => {
|
||||
removeCard();
|
||||
// Redirect to chatbot with card data
|
||||
router.push(`/chatbot?title=${encodeURIComponent(cardData.title)}&summary=${encodeURIComponent(cardData.summary)}`);
|
||||
};
|
||||
|
||||
const handleReject = () => {
|
||||
removeCard();
|
||||
};
|
||||
|
||||
const handleReset = () => {
|
||||
setCards([]); // Reset to initial cards
|
||||
};
|
||||
|
||||
return (
|
||||
<div
|
||||
className="grid h-screen w-full place-items-center bg-orange-100"
|
||||
// -gradient-to-tr from-orange-200 to-orange-100
|
||||
style={{
|
||||
backgroundImage: `url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg'
|
||||
viewBox='0 0 32 32' width='32' height='32' fill='none'
|
||||
stroke-width='2' stroke='%23d4d4d4'%3e%3cpath d='M0 .5H31.5V32'/%3e%3c/svg%3e")`,
|
||||
}}
|
||||
>
|
||||
{cards.length > 0 ? (
|
||||
cards.map((card, index) => {
|
||||
const colorWay = COLOR_WAYS[card.id % COLOR_WAYS.length];
|
||||
return (
|
||||
<Card
|
||||
key={card.id}
|
||||
cardData={card}
|
||||
colorWay={colorWay}
|
||||
isFront={index === cards.length - 1}
|
||||
onAccept={handleAccept}
|
||||
onReject={handleReject}
|
||||
/>
|
||||
);
|
||||
})
|
||||
) : (
|
||||
// ... (empty state)
|
||||
<div className="text-center">
|
||||
<h2 className="text-2xl font-bold text-neutral-700">
|
||||
No more cards!
|
||||
</h2>
|
||||
<p className="mb-4 text-neutral-500">
|
||||
You've swiped through them all.
|
||||
</p>
|
||||
<button
|
||||
onClick={handleReset}
|
||||
className="rounded-md bg-indigo-500 px-4 py-2 font-semibold text-white transition-colors hover:bg-indigo-600"
|
||||
>
|
||||
Reset Deck
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
interface CardProps {
|
||||
cardData: CardData;
|
||||
colorWay: ColorWay;
|
||||
isFront: boolean;
|
||||
onAccept: (cardData: CardData) => void;
|
||||
onReject: () => void;
|
||||
}
|
||||
|
||||
const Card: React.FC<CardProps> = ({ cardData, colorWay, isFront, onAccept, onReject }) => {
|
||||
const { title, summary, tracks } = cardData;
|
||||
|
||||
const x = useMotionValue(0);
|
||||
const rotate = useTransform(x, [-250, 250], [-25, 25]);
|
||||
const opacity = useTransform(
|
||||
x,
|
||||
[-250, -100, 0, 100, 250],
|
||||
[0, 1, 1, 1, 0],
|
||||
);
|
||||
const controls = useAnimation();
|
||||
|
||||
const acceptOpacity = useTransform(x, [50, 150], [0, 1]);
|
||||
const rejectOpacity = useTransform(x, [-150, -50], [1, 0]);
|
||||
const badgeRotate = useTransform(x, [-150, 150], [-15, 15]);
|
||||
|
||||
const handleDragEnd = async (event: MouseEvent | TouchEvent | PointerEvent, info: { offset: { x: number } }) => {
|
||||
if (info.offset.x > 100) {
|
||||
// Card accepted
|
||||
await controls.start({ x: 1000, opacity: 0, transition: { duration: 0.1 } }); // Animate off-screen quickly
|
||||
onAccept(cardData); // Then call onAccept which removes the card and redirects
|
||||
} else if (info.offset.x < -100) {
|
||||
// Card rejected
|
||||
await controls.start({ x: -1000, opacity: 0, transition: { duration: 0.1 } }); // Animate off-screen quickly
|
||||
onReject(); // Then call onReject which removes the card
|
||||
} else {
|
||||
// Card not swiped far enough, snap back to center
|
||||
controls.start({ x: 0, rotate: 0, opacity: 1, transition: { type: "spring", stiffness: 300, damping: 30 } });
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<motion.div
|
||||
className="absolute flex h-[56rem] w-[42rem] flex-col justify-between overflow-hidden rounded-2xl p-6 shadow-2xl hover:cursor-grab active:cursor-grabbing"
|
||||
style={{
|
||||
x,
|
||||
rotate,
|
||||
opacity,
|
||||
backgroundColor: colorWay.card,
|
||||
color: colorWay.text, // This is the default text color
|
||||
zIndex: isFront ? 2 : 1,
|
||||
pointerEvents: isFront ? "auto" : "none",
|
||||
}}
|
||||
animate={controls}
|
||||
transition={{ type: "spring", stiffness: 300, damping: 30 }}
|
||||
drag={isFront ? "x" : false}
|
||||
dragConstraints={{ left: 0, right: 0, top: 0, bottom: 0 }}
|
||||
onDragEnd={handleDragEnd}
|
||||
>
|
||||
{/* Accept/Reject Badges */}
|
||||
<motion.div
|
||||
className="absolute left-10 top-10 z-10 rounded-2xl border-8 border-green-500 px-10 py-4"
|
||||
style={{ opacity: acceptOpacity, rotate: badgeRotate }}
|
||||
>
|
||||
<h3 className="text-5xl font-bold uppercase text-green-500">Accept</h3>
|
||||
</motion.div>
|
||||
<motion.div
|
||||
className="absolute right-10 top-10 z-10 rounded-2xl border-8 border-red-500 px-10 py-4"
|
||||
style={{ opacity: rejectOpacity, rotate: badgeRotate }}
|
||||
>
|
||||
<h3 className="text-5xl font-bold uppercase text-red-500">Reject</h3>
|
||||
</motion.div>
|
||||
|
||||
{/* Card Content */}
|
||||
<div className="relative z-0">
|
||||
{/* 3. Applied the specific titleColor here */}
|
||||
<h2
|
||||
className="mb-4 text-center text-3xl font-bold"
|
||||
style={{ color: colorWay.titleColor }}
|
||||
>
|
||||
{title}
|
||||
</h2>
|
||||
{/* This summary <p> will inherit colorWay.text from the parent */}
|
||||
<p className="text-center text-xl font-light">{summary}</p>
|
||||
</div>
|
||||
|
||||
<div className="relative z-0 flex flex-wrap items-center justify-center gap-2">
|
||||
{tracks.slice(0, 2).map((track, index) => (
|
||||
<span
|
||||
key={track}
|
||||
className="flex items-center justify-center rounded-full px-8 py-3 text-sm font-medium"
|
||||
style={{
|
||||
// This logic now correctly contrasts with the main text color
|
||||
backgroundColor:
|
||||
colorWay.text === "#ffffff"
|
||||
? "rgba(255, 255, 255, 0.2)"
|
||||
: "rgba(0, 0, 0, 0.15)",
|
||||
}}
|
||||
>
|
||||
{track}
|
||||
{index === 0 && tracks.length > 1 && ", "}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
</motion.div>
|
||||
);
|
||||
|
||||
};
|
||||
|
||||
export default SwipeCards;
|
||||
@@ -0,0 +1,135 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useEffect, useRef, useCallback } from "react";
|
||||
import { useSearchParams } from "next/navigation";
|
||||
import ChatInput from "../utils/component/ui/ChatInput";
|
||||
import MessageWindow from "../utils/component/ui/MessageWindow";
|
||||
import { ChatHistory, ChatSetting, Message , MessageRole } from "@/app/exportType/types";
|
||||
|
||||
export default function Home(){
|
||||
const [history, setHistory] = useState<ChatHistory>([])
|
||||
const historyRef = useRef<ChatHistory>([]); // Create a ref for history
|
||||
const [settings] = useState<ChatSetting>({
|
||||
temperature:1,
|
||||
model:"gemini-2.5-pro",
|
||||
sysTemInstructions:"you are a ai helper. Your goal is to expand the project idea and interact with the user on any problem or question they have with the project. You are not allow to code the project for them and stray away from your job"
|
||||
|
||||
});
|
||||
const searchParams = useSearchParams();
|
||||
const initialMessageSent = useRef(false);
|
||||
|
||||
useEffect(() => {
|
||||
historyRef.current = history; // Keep the ref updated with the latest history
|
||||
}, [history]);
|
||||
|
||||
const handleSend = useCallback(async(message:string)=>{
|
||||
const newUserMessage:Message = {
|
||||
role:"user",
|
||||
parts:[{text:message}],
|
||||
};
|
||||
|
||||
setHistory(prevHistory => {
|
||||
const currentHistory = [...prevHistory, newUserMessage];
|
||||
|
||||
const sendApiRequest = async () => {
|
||||
try{
|
||||
const response = await fetch("/api/chat", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
userMessage: message,
|
||||
history: historyRef.current, // Use the ref for history
|
||||
settings: settings,
|
||||
}),
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
if (data.error) {
|
||||
console.error("AI Error:", data.error);
|
||||
return;
|
||||
}
|
||||
|
||||
const aiMessage: Message = {
|
||||
role: "model" as MessageRole,
|
||||
parts: [{ text: data.response }],
|
||||
};
|
||||
|
||||
setHistory(prevHistory => [...prevHistory, aiMessage]);
|
||||
|
||||
}
|
||||
catch (error) {
|
||||
console.error("Request Failed:", error);
|
||||
}
|
||||
};
|
||||
sendApiRequest();
|
||||
|
||||
return currentHistory;
|
||||
});
|
||||
}, [settings]); // Now handleSend only depends on settings
|
||||
|
||||
useEffect(() => {
|
||||
if (!initialMessageSent.current) {
|
||||
const title = searchParams.get('title');
|
||||
const summary = searchParams.get('summary');
|
||||
|
||||
if (title && summary) {
|
||||
const message = `Explain the project titled '${title}' with the summary '${summary}' in detail, and suggest suitable roles for a team working on it.`;
|
||||
|
||||
const newUserMessage: Message = {
|
||||
role: "user",
|
||||
parts: [{ text: message }],
|
||||
};
|
||||
|
||||
setTimeout(() => {
|
||||
setHistory((prevHistory) => [...prevHistory, newUserMessage]); // Add user message to history
|
||||
}, 0);
|
||||
|
||||
const sendInitialApiRequest = async () => {
|
||||
try {
|
||||
const response = await fetch("/api/chat", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
userMessage: message,
|
||||
history: [...historyRef.current, newUserMessage], // Use ref for history
|
||||
settings: settings,
|
||||
}),
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
if (data.error) {
|
||||
console.error("AI Error:", data.error);
|
||||
return;
|
||||
}
|
||||
|
||||
const aiMessage: Message = {
|
||||
role: "model" as MessageRole,
|
||||
parts: [{ text: data.response }],
|
||||
};
|
||||
|
||||
setHistory((prevHistory) => [...prevHistory, aiMessage]);
|
||||
} catch (error) {
|
||||
console.error("Request Failed:", error);
|
||||
}
|
||||
};
|
||||
|
||||
sendInitialApiRequest();
|
||||
initialMessageSent.current = true;
|
||||
}
|
||||
}
|
||||
}, [searchParams, settings]); // Dependencies for this useEffect
|
||||
|
||||
|
||||
return (
|
||||
<div className="flex flex-col py-32">
|
||||
<MessageWindow history={history} />
|
||||
<ChatInput onSend={handleSend} onOpenSettings={() => {}} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
export type MessageRole = "user" | "model";
|
||||
|
||||
export type MessagePart = {
|
||||
text: string;
|
||||
}
|
||||
|
||||
export interface Message{
|
||||
role: MessageRole;
|
||||
parts:MessagePart[];
|
||||
}
|
||||
export type ChatHistory = Message[];
|
||||
|
||||
export interface GenerateConfig{
|
||||
temperature : number;
|
||||
topP : number;
|
||||
responseMimeType : string;
|
||||
}
|
||||
|
||||
export interface ChatSetting{
|
||||
temperature :number;
|
||||
model: string;
|
||||
sysTemInstructions: string;
|
||||
}
|
||||
|
||||
export interface CardData {
|
||||
id: number;
|
||||
title: string;
|
||||
tracks: string[];
|
||||
summary: string;
|
||||
}
|
||||
@@ -0,0 +1,294 @@
|
||||
"use client";
|
||||
|
||||
import React, { useState } from "react";
|
||||
|
||||
import {
|
||||
FormData,
|
||||
PROFICIENCY_LEVELS
|
||||
} from './formTypes'; // Ensure path is correct
|
||||
|
||||
interface FormPageProps {
|
||||
onFormSubmit: (data: FormData) => void;
|
||||
}
|
||||
|
||||
const FormPage: React.FC<FormPageProps> = ({ onFormSubmit }) => {
|
||||
const [formData, setFormData] = useState<FormData>({
|
||||
Hackathon: '',
|
||||
mainTheme: '',
|
||||
tracksStack: [''],
|
||||
students: [{
|
||||
studentName: '',
|
||||
skills: [{ skillName: '', proficiency: PROFICIENCY_LEVELS[1] }]
|
||||
}],
|
||||
});
|
||||
|
||||
const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
|
||||
setFormData({
|
||||
...formData,
|
||||
[event.target.name]: event.target.value,
|
||||
});
|
||||
};
|
||||
|
||||
const handleTracksChange = (event: React.ChangeEvent<HTMLInputElement>, index: number) => {
|
||||
const newTracksStack = [...formData.tracksStack];
|
||||
newTracksStack[index] = event.target.value;
|
||||
|
||||
setFormData({
|
||||
...formData,
|
||||
tracksStack: newTracksStack,
|
||||
});
|
||||
};
|
||||
|
||||
const handleAddTracks = () => {
|
||||
setFormData({
|
||||
...formData,
|
||||
tracksStack: [...formData.tracksStack, ''],
|
||||
});
|
||||
};
|
||||
|
||||
const handleRemoveTracks = (index: number) => {
|
||||
const newTracksStack = formData.tracksStack.filter((_, i) => i !== index);
|
||||
setFormData({
|
||||
...formData,
|
||||
tracksStack: newTracksStack,
|
||||
});
|
||||
};
|
||||
|
||||
const handleStudentNameChange = (e: React.ChangeEvent<HTMLInputElement>, studentIndex: number) => {
|
||||
const newStudents = [...formData.students];
|
||||
newStudents[studentIndex].studentName = e.target.value;
|
||||
setFormData({ ...formData, students: newStudents });
|
||||
};
|
||||
|
||||
const handleAddStudent = () => {
|
||||
setFormData({
|
||||
...formData,
|
||||
students: [...formData.students, { studentName: '', skills: [{ skillName: '', proficiency: PROFICIENCY_LEVELS[1] }] }]
|
||||
});
|
||||
};
|
||||
|
||||
const handleRemoveStudent = (studentIndex: number) => {
|
||||
const newStudents = formData.students.filter((_, i) => i !== studentIndex);
|
||||
setFormData({ ...formData, students: newStudents });
|
||||
};
|
||||
|
||||
const handleSkillChange = (
|
||||
e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>,
|
||||
studentIndex: number,
|
||||
skillIndex: number
|
||||
) => {
|
||||
const newStudents = [...formData.students];
|
||||
const targetName = e.target.name;
|
||||
const targetValue = e.target.value;
|
||||
|
||||
if (targetName === 'skillName') {
|
||||
newStudents[studentIndex].skills[skillIndex].skillName = targetValue;
|
||||
} else if (targetName === 'proficiency') {
|
||||
newStudents[studentIndex].skills[skillIndex].proficiency = targetValue;
|
||||
}
|
||||
|
||||
setFormData({ ...formData, students: newStudents });
|
||||
};
|
||||
|
||||
const handleAddSkill = (studentIndex: number) => {
|
||||
const newStudents = [...formData.students];
|
||||
newStudents[studentIndex].skills.push({ skillName: '', proficiency: PROFICIENCY_LEVELS[1] });
|
||||
setFormData({ ...formData, students: newStudents });
|
||||
};
|
||||
|
||||
const handleRemoveSkill = (studentIndex: number, skillIndex: number) => {
|
||||
const newStudents = [...formData.students];
|
||||
newStudents[studentIndex].skills = newStudents[studentIndex].skills.filter((_, i) => i !== skillIndex);
|
||||
setFormData({ ...formData, students: newStudents });
|
||||
};
|
||||
|
||||
const handleSubmit = (event: React.FormEvent) => {
|
||||
event.preventDefault();
|
||||
onFormSubmit(formData); // Call the prop function with formData
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-50 flex items-start justify-center p-4 sm:p-6 font-inter">
|
||||
<div className="w-full max-w-2xl bg-white p-8 shadow-2xl rounded-xl mt-8">
|
||||
<h1 className="text-3xl font-extrabold text-center text-gray-800 mb-8 tracking-tight">
|
||||
Generate Project Idea
|
||||
</h1>
|
||||
|
||||
<form className="space-y-8" onSubmit={handleSubmit}>
|
||||
<div className="space-y-6 border-b pb-6 border-gray-200">
|
||||
<h2 className="text-xl font-bold text-gray-700">Project Context</h2>
|
||||
<div>
|
||||
<label htmlFor="hackathonName" className="block text-sm font-medium text-gray-700 mb-1">
|
||||
Hackathon Name
|
||||
</label>
|
||||
<input
|
||||
id="hackathonName"
|
||||
required
|
||||
type="text"
|
||||
placeholder="e.g., Google Code Jam"
|
||||
name="Hackathon"
|
||||
value={formData.Hackathon}
|
||||
onChange={handleChange}
|
||||
className="mt-1 block w-full px-4 py-2 border border-gray-300 rounded-lg shadow-sm focus:ring-blue-500 focus:border-blue-500 transition duration-150"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label htmlFor="mainTheme" className="block text-sm font-medium text-gray-700 mb-1">
|
||||
Main Theme
|
||||
</label>
|
||||
<input
|
||||
id="mainTheme"
|
||||
required
|
||||
type="text"
|
||||
placeholder="e.g., Sustainability or AI Ethics"
|
||||
name="mainTheme"
|
||||
value={formData.mainTheme}
|
||||
onChange={handleChange}
|
||||
className="mt-1 block w-full px-4 py-2 border border-gray-300 rounded-lg shadow-sm focus:ring-blue-500 focus:border-blue-500 transition duration-150"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-4 border-b pb-6 border-gray-200">
|
||||
<label className="block text-xl font-bold text-gray-700">
|
||||
Tracks Stack
|
||||
</label>
|
||||
<div className="space-y-3">
|
||||
{formData.tracksStack.map((tracks, index) => (
|
||||
<div key={index} className="flex gap-2 items-center">
|
||||
<input
|
||||
type="text"
|
||||
required
|
||||
placeholder={`Tracks #${index + 1}`}
|
||||
name={`tracksStack-${index}`}
|
||||
value={tracks}
|
||||
onChange={(e) => handleTracksChange(e, index)}
|
||||
className="flex-grow px-4 py-2 border border-gray-300 rounded-lg shadow-sm focus:ring-green-500 focus:border-green-500 transition duration-150"
|
||||
/>
|
||||
{formData.tracksStack.length > 1 && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => handleRemoveTracks(index)}
|
||||
className="text-sm px-3 py-2 bg-red-500 text-white rounded-lg hover:bg-red-600 transition duration-150 flex-shrink-0"
|
||||
aria-label={`Remove tracks ${index + 1}`}
|
||||
>
|
||||
Remove
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleAddTracks}
|
||||
className="flex items-center justify-center gap-1 py-2 px-4 border border-transparent rounded-lg shadow-sm text-sm font-medium text-white bg-green-600 hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-500 transition duration-150"
|
||||
>
|
||||
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6"></path></svg>
|
||||
Add Tracks
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="space-y-4">
|
||||
<h2 className="text-xl font-bold text-gray-700">Team Members and Skills</h2>
|
||||
|
||||
<div className="space-y-6">
|
||||
{formData.students.map((student, studentIndex) => (
|
||||
<div key={studentIndex} className="p-4 border-2 border-indigo-200 rounded-lg bg-indigo-50 shadow-inner space-y-4">
|
||||
|
||||
<div className="flex justify-between items-center pb-2 border-b border-indigo-300">
|
||||
<h4 className="text-lg font-semibold text-indigo-700">Student #{studentIndex + 1}</h4>
|
||||
{formData.students.length > 1 && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => handleRemoveStudent(studentIndex)}
|
||||
className="text-xs px-2 py-1 bg-red-400 text-white rounded-md hover:bg-red-500 transition duration-150"
|
||||
>
|
||||
Remove Student
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-indigo-700 mb-1">Student Name</label>
|
||||
<input
|
||||
type="text"
|
||||
required
|
||||
placeholder="Student Name"
|
||||
value={student.studentName}
|
||||
onChange={(e) => handleStudentNameChange(e, studentIndex)}
|
||||
className="w-full px-4 py-2 border border-indigo-300 rounded-lg shadow-sm focus:ring-indigo-500 focus:border-indigo-500"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-3 p-3 bg-white rounded-lg border border-indigo-100">
|
||||
<h5 className="text-md font-medium text-indigo-700">Skills</h5>
|
||||
{student.skills.map((skill, skillIndex) => (
|
||||
<div key={skillIndex} className="flex gap-2 items-center">
|
||||
<input
|
||||
type="text"
|
||||
required
|
||||
name="skillName"
|
||||
placeholder="Skill (e.g., React, Python)"
|
||||
value={skill.skillName}
|
||||
onChange={(e) => handleSkillChange(e, studentIndex, skillIndex)}
|
||||
className="flex-grow px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-purple-500 focus:border-purple-500"
|
||||
/>
|
||||
<select
|
||||
name="proficiency"
|
||||
value={skill.proficiency}
|
||||
onChange={(e) => handleSkillChange(e, studentIndex, skillIndex)}
|
||||
className="px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-purple-500 focus:border-purple-500 w-1/3"
|
||||
>
|
||||
{PROFICIENCY_LEVELS.map(level => (
|
||||
<option key={level} value={level}>{level}</option>
|
||||
))}
|
||||
</select>
|
||||
{student.skills.length > 1 && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => handleRemoveSkill(studentIndex, skillIndex)}
|
||||
className="text-xs px-2 py-1 bg-red-500 text-white rounded-md hover:bg-red-600 transition duration-150 flex-shrink-0"
|
||||
>
|
||||
X
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => handleAddSkill(studentIndex)}
|
||||
className="mt-2 text-xs flex items-center gap-1 py-1 px-3 border border-transparent rounded-lg text-white bg-purple-600 hover:bg-purple-700 transition duration-150"
|
||||
>
|
||||
+ Add Skill
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleAddStudent}
|
||||
className="mt-4 w-full flex items-center justify-center gap-2 py-2 px-4 border border-transparent rounded-lg shadow-sm font-medium text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 transition duration-150"
|
||||
>
|
||||
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M18 9v3m0 0v3m0-3h3m-3 0h-3m-2-5a4 4 0 11-8 0 4 4 0 018 0zM3 20a6 6 0 0112 0v1H3v-1z"></path></svg>
|
||||
Add Team Member
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<button
|
||||
type="submit"
|
||||
className="w-full flex justify-center py-3 px-4 border border-transparent rounded-lg shadow-lg text-lg font-semibold text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 transition duration-150 mt-6"
|
||||
>
|
||||
Generate Idea
|
||||
</button>
|
||||
</form>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default FormPage;
|
||||
@@ -0,0 +1,21 @@
|
||||
// Define Skill structure
|
||||
export interface Skill {
|
||||
skillName: string;
|
||||
proficiency: string;
|
||||
}
|
||||
|
||||
// Define Student structure
|
||||
export interface Student {
|
||||
studentName: string;
|
||||
skills: Skill[];
|
||||
}
|
||||
|
||||
// Updated main form interface
|
||||
export interface FormData {
|
||||
Hackathon: string;
|
||||
mainTheme: string;
|
||||
tracksStack: string[];
|
||||
students: Student[]; // Array for dynamic students
|
||||
}
|
||||
|
||||
export const PROFICIENCY_LEVELS = ['Beginner', 'Intermediate', 'Expert', 'Master'];
|
||||
@@ -0,0 +1,71 @@
|
||||
import { GoogleGenerativeAI } from "@google/generative-ai";
|
||||
import type { NextApiRequest, NextApiResponse } from 'next';
|
||||
|
||||
// Initialize the Gemini Client with your API Key
|
||||
// IMPORTANT: The GEMINI_API_KEY should be an environment variable.
|
||||
const apiKey = process.env.GEMINI_API_KEY;
|
||||
|
||||
if(!apiKey){
|
||||
throw new Error("api key not found");
|
||||
}
|
||||
const ai = new GoogleGenerativeAI(apiKey);
|
||||
|
||||
|
||||
|
||||
// Define the handler function for the API route
|
||||
export default async function handler(
|
||||
req: NextApiRequest,
|
||||
res: NextApiResponse
|
||||
) {
|
||||
// Only allow POST requests
|
||||
if (req.method !== 'POST') {
|
||||
return res.status(405).json({ error: 'Method Not Allowed' });
|
||||
}
|
||||
|
||||
// Destructure the data sent from the frontend
|
||||
let { prompt, settings } = req.body;
|
||||
|
||||
// Basic validation
|
||||
if (!prompt || typeof prompt !== 'string') {
|
||||
return res.status(400).json({ error: 'Prompt is required' });
|
||||
}
|
||||
|
||||
// Modify the prompt to instruct the AI to generate only the game, concept, and track
|
||||
prompt = `You're going to fill out a card base off the document.
|
||||
you will Generate the project short title.
|
||||
you will list out the track you used ${prompt}`;
|
||||
|
||||
try {
|
||||
// 1. Call the Gemini API using the correct method signature
|
||||
|
||||
const model = settings?.model || 'gemini-2.5-flash-lite';
|
||||
const generativeModel = ai.getGenerativeModel({ model });
|
||||
|
||||
// 1. Define the generation configuration object
|
||||
const generationConfig = {
|
||||
temperature: settings?.temperature || 0.9,
|
||||
// The SDK property name for system instructions is 'systemInstruction'
|
||||
systemInstruction: settings?.sysTemInstructions,
|
||||
};
|
||||
|
||||
// 2. Call generateContent with the single GenerateContentRequest object.
|
||||
const result = await generativeModel.generateContent({
|
||||
// contents must be an array of Content objects
|
||||
contents: [{
|
||||
role: "user",
|
||||
parts: [{ text: prompt }]
|
||||
}],
|
||||
|
||||
// The fixed property name that resolves the TypeScript error
|
||||
generationConfig: generationConfig,
|
||||
});
|
||||
|
||||
// 2. Extract the response text
|
||||
// The result object now contains a property 'text' at the top level for simple text generation
|
||||
const geminiResponseText = result.response.text(); res.status(200).json({ response: geminiResponseText });
|
||||
|
||||
} catch (error) {
|
||||
console.error("Gemini API Error:", error);
|
||||
res.status(500).json({ error: 'Failed to generate idea from AI.' });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
// File: Home.tsx (Renamed from form.tsx for export consistency)
|
||||
|
||||
"use client";
|
||||
import React, { useState, useEffect, useCallback } from "react";
|
||||
import FormPage from './FormPage';
|
||||
import { ChatSetting, CardData } from "@/app/exportType/types";
|
||||
import { FormData, PROFICIENCY_LEVELS } from './formTypes';
|
||||
import SwipeCards from '../cards/page';
|
||||
|
||||
export default function Home() {
|
||||
const [showForm, setShowForm] = useState(true);
|
||||
const [formData, setFormData] = useState<FormData>(() => {
|
||||
if (typeof window !== 'undefined') {
|
||||
const storedFormData = localStorage.getItem('formData');
|
||||
if (storedFormData) {
|
||||
const parsedData: FormData = JSON.parse(storedFormData);
|
||||
return parsedData;
|
||||
}
|
||||
}
|
||||
return {
|
||||
Hackathon: '',
|
||||
mainTheme: '',
|
||||
tracksStack: [''],
|
||||
students: [{
|
||||
studentName: '',
|
||||
skills: [{ skillName: '', proficiency: PROFICIENCY_LEVELS[1] }]
|
||||
}],
|
||||
};
|
||||
});
|
||||
|
||||
const [ideaResponse, setIdeaResponse] = useState<string>("");
|
||||
const [generatedCards, setGeneratedCards] = useState<CardData[]>([]); // New state for parsed cards
|
||||
|
||||
const [settings] = useState<ChatSetting>({
|
||||
temperature: 1,
|
||||
model: "gemini-2.5-flash-lite",
|
||||
sysTemInstructions: `You are an elite hackathon idea generator. Your task is to choose at lease two track and generate five different creative, feasible, and relevant project idea.
|
||||
The output MUST be in Markdown format and strictly follow this structure:
|
||||
### Project Idea Title
|
||||
**Track** [print out the track you used]
|
||||
**Concept:** [A concise, single paragraph description of the product and its primary function.]`,
|
||||
});
|
||||
|
||||
const parseAiResponse = (markdownString: string): CardData[] => {
|
||||
console.log("Raw AI Response:", markdownString);
|
||||
const ideas: CardData[] = [];
|
||||
const ideaBlocks = markdownString.split("### ").filter(block => block.trim() !== "");
|
||||
|
||||
ideaBlocks.forEach((block, index) => {
|
||||
// Match title: anything from the start of the block until the first newline or the start of "**Track**"
|
||||
const titleMatch = block.match(/^(.*?)(?=\n\*\*Track\*\*|$)/s);
|
||||
// Match track: "**Track**" followed by optional whitespace and then capture everything until the next "**Concept**" or end of block/line
|
||||
const trackMatch = block.match(/\*\*Track\*\*\s*:\s*(.*?)(?=\n\*\*Concept\*\*|$)/s); // Added ':' and made whitespace more flexible
|
||||
// Match concept: "**Concept:**" followed by optional whitespace and then capture everything until the end of the block
|
||||
const conceptMatch = block.match(/\*\*Concept:\*\*\s*(.*)/s);
|
||||
|
||||
const title = titleMatch ? titleMatch[1].trim() : `Idea ${index + 1}`;
|
||||
const summary = conceptMatch ? conceptMatch[1].trim() : "No concept provided.";
|
||||
const tracksRaw = trackMatch ? trackMatch[1].trim() : "";
|
||||
console.log("tracksRaw:", tracksRaw); // Added console.log for debugging
|
||||
const tracks = tracksRaw.split(',').map(track => track.trim()).filter(track => track !== '');
|
||||
|
||||
ideas.push({
|
||||
id: index + 1,
|
||||
title,
|
||||
tracks,
|
||||
summary,
|
||||
});
|
||||
});
|
||||
console.log("Parsed Cards:", ideas);
|
||||
return ideas;
|
||||
};
|
||||
|
||||
const handleFormSubmitFromFormPage = (submittedData: FormData) => {
|
||||
setFormData(submittedData);
|
||||
setShowForm(false);
|
||||
generateIdeas(submittedData);
|
||||
};
|
||||
|
||||
// eslint-disable-next-line react-hooks/preserve-manual-memoization
|
||||
const generateIdeas = useCallback(async (dataToProcess: FormData) => {
|
||||
const submissionData: FormData = {
|
||||
...dataToProcess,
|
||||
tracksStack: dataToProcess.tracksStack.filter(tracks => tracks.trim() !== ''),
|
||||
students: dataToProcess.students
|
||||
.map(student => ({
|
||||
...student,
|
||||
skills: student.skills.filter(skill => skill.skillName.trim() !== ''),
|
||||
}))
|
||||
.filter(student => student.studentName.trim() !== '' || student.skills.length > 0),
|
||||
};
|
||||
|
||||
const prompt = `
|
||||
Hackathon: ${submissionData.Hackathon}
|
||||
Main Theme: ${submissionData.mainTheme}
|
||||
Required Tracks Stack: ${submissionData.tracksStack.join(', ')}
|
||||
Team Members and Skills: ${submissionData.students.map(s =>
|
||||
`${s.studentName || 'Unamed Member'} (Skills: ${s.skills.map(sk => `${sk.skillName} - ${sk.proficiency}`).join(', ')})`
|
||||
).join('; ')}
|
||||
|
||||
Using the SYSTEM INSTRUCTIONS, generate 5 project ideas based on the data above.`;
|
||||
|
||||
try {
|
||||
setIdeaResponse("Generating ideas... Please wait.");
|
||||
setGeneratedCards([]); // Clear previous cards
|
||||
const response = await fetch("/api/generate-idea", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
prompt: prompt,
|
||||
settings: settings,
|
||||
}),
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
if (data.error || !response.ok) {
|
||||
console.error("AI Error:", data.error);
|
||||
setIdeaResponse(`Error: Failed to generate idea. ${data.error || response.statusText}`);
|
||||
return;
|
||||
}
|
||||
|
||||
setIdeaResponse(data.response);
|
||||
const parsedCards = parseAiResponse(data.response);
|
||||
setGeneratedCards(parsedCards);
|
||||
|
||||
} catch (error) {
|
||||
console.error("Request Failed:", error);
|
||||
let errorMessage = "An unknown error occurred.";
|
||||
if (error instanceof Error) {
|
||||
errorMessage = error.message;
|
||||
} else if (typeof error === 'string') {
|
||||
errorMessage = error;
|
||||
}
|
||||
setIdeaResponse(`A network error occurred. Please try again. Details: ${errorMessage}`);
|
||||
}
|
||||
}, [setIdeaResponse, setGeneratedCards, settings, parseAiResponse]);
|
||||
|
||||
useEffect(() => {
|
||||
if (typeof window !== 'undefined') {
|
||||
const storedFormData = localStorage.getItem('formData');
|
||||
if (storedFormData) {
|
||||
const parsedData: FormData = JSON.parse(storedFormData);
|
||||
setTimeout(() => setShowForm(false), 0);
|
||||
generateIdeas(parsedData);
|
||||
localStorage.removeItem('formData');
|
||||
}
|
||||
}
|
||||
}, [generateIdeas]);
|
||||
|
||||
return (
|
||||
<main className="min-h-screen bg-gray-50 flex items-start justify-center p-4 sm:p-6 font-inter">
|
||||
<div className="w-full max-w-2xl bg-white p-8 shadow-2xl rounded-xl mt-8">
|
||||
{showForm ? (
|
||||
<FormPage onFormSubmit={handleFormSubmitFromFormPage} />
|
||||
) : (
|
||||
<>
|
||||
{generatedCards.length > 0 ? (
|
||||
<SwipeCards initialCards={generatedCards} />
|
||||
) : (
|
||||
<>
|
||||
<h1 className="text-3xl font-extrabold text-center text-gray-800 mb-8 tracking-tight">
|
||||
Generated Project Idea 💡
|
||||
</h1>
|
||||
<div className="mt-8 p-4 bg-yellow-50 rounded-lg border border-yellow-200">
|
||||
<h2 className="text-xl font-bold text-gray-700 mb-2">Generated Ideas:</h2>
|
||||
<div
|
||||
className="prose max-w-none"
|
||||
dangerouslySetInnerHTML={{ __html: ideaResponse.replace(/\n/g, '<br/>') }}
|
||||
/>
|
||||
{ideaResponse === "" && <p className="text-gray-500">Submit the form to generate project ideas.</p>}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
<button
|
||||
onClick={() => setShowForm(true)}
|
||||
className="mt-6 w-full flex justify-center py-3 px-4 border border-transparent rounded-lg shadow-lg text-lg font-semibold text-white bg-blue-600 hover:bg-blue-700 transition duration-150"
|
||||
>
|
||||
Go Back to Form
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
//geminiclone/src/components/ui/ChatInput.tsx
|
||||
"use client";
|
||||
import { useState } from "react";
|
||||
import { Settings, Send, X } from "lucide-react";
|
||||
|
||||
interface ChatInputProps {
|
||||
onSend: (message: string) => void;
|
||||
onOpenSettings: () => void;
|
||||
}
|
||||
|
||||
export default function ChatInput({ onSend, onOpenSettings }: ChatInputProps) {
|
||||
const [message, setMessage] = useState("");
|
||||
|
||||
const handleChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
|
||||
setMessage(e.target.value);
|
||||
};
|
||||
|
||||
const handleSend = () => {
|
||||
if (message.trim()) {
|
||||
onSend(message.trim());
|
||||
setMessage("");
|
||||
}
|
||||
};
|
||||
|
||||
const handleKeyPress = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
|
||||
if (e.key === "Enter") {
|
||||
handleSend();
|
||||
}
|
||||
};
|
||||
|
||||
const handleClear = () => {
|
||||
setMessage("");
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="fixed bottom-0 left-0 right-0 flex flex-col max-w-4xl mx-auto w-full">
|
||||
<div
|
||||
className={`
|
||||
flex items-center border border-black/10 p-3 mx-4 rounded-t-3xl
|
||||
bg-white
|
||||
shadow-md transition-all duration-200
|
||||
|
||||
`}
|
||||
>
|
||||
|
||||
<div className="relative flex-1 mx-2">
|
||||
<textarea
|
||||
className="w-full px-3 py-2 bg-transparent border-none focus:outline-none"
|
||||
placeholder="Type a message..."
|
||||
value={message}
|
||||
onChange={handleChange}
|
||||
onKeyDown={handleKeyPress}
|
||||
/>
|
||||
|
||||
{message && (
|
||||
<button
|
||||
className="absolute right-0 top-1/2 transform -translate-y-1/2 p-1 text-gray-400 hover:text-gray-600 "
|
||||
onClick={handleClear}
|
||||
aria-label="Clear input"
|
||||
>
|
||||
<X size={16} />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
|
||||
<div className="flex items-center">
|
||||
|
||||
<button
|
||||
className="p-2 text-gray-500 hover:text-purple-600 rounded-full hover:bg-gray-100 0 mr-1"
|
||||
onClick={onOpenSettings}
|
||||
aria-label="Open settings"
|
||||
>
|
||||
<Settings size={20} />
|
||||
</button>
|
||||
|
||||
<button
|
||||
className={`
|
||||
p-2 rounded-full transition-all
|
||||
${
|
||||
message.trim()
|
||||
? "bg-purple-600 text-white hover:bg-purple-700"
|
||||
: "bg-gray-200 text-gray-400 cursor-not-allowed"
|
||||
}
|
||||
`}
|
||||
onClick={handleSend}
|
||||
disabled={!message.trim()}
|
||||
aria-label="Send message"
|
||||
>
|
||||
<Send size={20} />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
"use client";
|
||||
import { useRef, useEffect } from "react";
|
||||
import { ChatHistory } from "@/app/exportType/types";
|
||||
import {User, Bot} from "lucide-react"
|
||||
|
||||
interface MessageWindowProps{
|
||||
history :ChatHistory
|
||||
}
|
||||
|
||||
export default function MessageWindow({history}:MessageWindowProps){
|
||||
const messageEndRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
useEffect(() =>{
|
||||
messageEndRef.current?.scrollIntoView({behavior:"smooth"});
|
||||
}, [history]);
|
||||
|
||||
return(
|
||||
<div className="flex-1 p-3 overflow-y-auto">
|
||||
<div className="max-w-3xl mx-auto">
|
||||
{history.map((msg,index)=>{
|
||||
const isUser = msg.role === "user"
|
||||
|
||||
return (
|
||||
<div
|
||||
key={index}
|
||||
className={`flex ${isUser ? "justify-end" : "justify-start"}`}>
|
||||
{!isUser &&(
|
||||
<div className="mr-2">
|
||||
<div className="flex items-center justify-center w-8 h-8 rounded-full bg-gray">
|
||||
<Bot size={15} className="text-gray-700">
|
||||
</Bot>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className={` px-4 py-2 shadow-sm rounded-lg
|
||||
${isUser ? "bg-purple-600 text-white rounded-br-none" : "bg-white text-gray-800 rounded-bl-none"}
|
||||
max-w-xs sm:max-w-md`}>
|
||||
|
||||
<div className="whitespace-pre-wrap break-words">{msg.parts.map((part, idx) => (
|
||||
<span key={idx}>{part.text}</span>))}
|
||||
</div>
|
||||
</div>
|
||||
{isUser && (
|
||||
<div className="ml-2">
|
||||
<div className="flex items-center justify-center w-8 h-8 rounded-full bg-purple-500">
|
||||
<User size={16} className="text-white" />
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
|
||||
{/* Invisible element to help scroll to bottom */}
|
||||
<div ref={messageEndRef} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
import { GoogleGenerativeAI } from "@google/generative-ai";
|
||||
import { ChatHistory, GenerateConfig,ChatSetting } from "../exportType/types";
|
||||
|
||||
const apiKey = process.env.GEMINI_API_KEY;
|
||||
|
||||
if(!apiKey){
|
||||
throw new Error("api key not found");
|
||||
}
|
||||
|
||||
const genAI = new GoogleGenerativeAI(apiKey);
|
||||
|
||||
export async function chatToGemini(
|
||||
userMessage:string ,
|
||||
history:ChatHistory,
|
||||
settings:ChatSetting
|
||||
):Promise<string>{
|
||||
const model = genAI.getGenerativeModel({
|
||||
model:settings.model || "gemini-2.5-flash",
|
||||
systemInstruction: settings.sysTemInstructions || "you are going to create a project idea, explain it in summery first before going to detail",
|
||||
});
|
||||
|
||||
const generationConfig:GenerateConfig = {
|
||||
temperature : settings.temperature || 1,
|
||||
topP : 0.9,
|
||||
responseMimeType: "text/plain",
|
||||
maxOutputTokens: 1900, // Increased to allow for longer responses
|
||||
}
|
||||
|
||||
const chatSession = model.startChat({
|
||||
generationConfig,
|
||||
history
|
||||
})
|
||||
|
||||
try {
|
||||
const result = await chatSession.sendMessage(userMessage);
|
||||
return result.response.text();
|
||||
}
|
||||
catch(error){
|
||||
console.error(error)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2017",
|
||||
"target": "ES2018",
|
||||
"lib": ["dom", "dom.iterable", "esnext"],
|
||||
"allowJs": true,
|
||||
"skipLibCheck": true,
|
||||
|
||||
Reference in New Issue
Block a user