-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathmain.js
More file actions
94 lines (77 loc) · 2.26 KB
/
Copy pathmain.js
File metadata and controls
94 lines (77 loc) · 2.26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
import { GoogleGenerativeAI } from "@google/generative-ai";
import md from "markdown-it";
// Initialize the model
const genAI = new GoogleGenerativeAI(`${import.meta.env.VITE_API_KEY}`);
const model = genAI.getGenerativeModel({ model: "gemini-pro" });
let history = [];
async function getResponse(prompt) {
const chat = await model.startChat({ history: history });
const result = await chat.sendMessage(prompt);
const response = await result.response;
const text = response.text();
console.log(text);
return text;
}
// user chat div
export const userDiv = (data) => {
return `
<!-- User Chat -->
<div class="flex items-center gap-2 justify-start">
<img
src="user.jpg"
alt="user icon"
class="w-10 h-10 rounded-full"
/>
<p class="bg-gemDeep text-white p-1 rounded-md shadow-md ">
${data}
</p>
</div>
`;
};
// AI Chat div
export const aiDiv = (data) => {
return `
<!-- AI Chat -->
<div class="flex gap-2 justify-end">
<pre class="bg-gemRegular/40 text-gemDeep p-1 rounded-md shadow-md whitespace-pre-wrap">
${data}
</pre>
<img
src="chat-bot.jpg"
alt="user icon"
class="w-10 h-10 rounded-full"
/>
</div>
`;
};
async function handleSubmit(event) {
event.preventDefault();
let userMessage = document.getElementById("prompt");
const chatArea = document.getElementById("chat-container");
var prompt = userMessage.value.trim();
if (prompt === "") {
return;
}
console.log("user message", prompt);
chatArea.innerHTML += userDiv(prompt);
userMessage.value = "";
const aiResponse = await getResponse(prompt);
let md_text = md().render(aiResponse);
chatArea.innerHTML += aiDiv(md_text);
let newUserRole = {
role: "user",
parts: prompt,
};
let newAIRole = {
role: "model",
parts: aiResponse,
};
history.push(newUserRole);
history.push(newAIRole);
console.log(history);
}
const chatForm = document.getElementById("chat-form");
chatForm.addEventListener("submit", handleSubmit);
chatForm.addEventListener("keyup", (event) => {
if (event.keyCode === 13) handleSubmit(event);
});