-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
173 lines (136 loc) · 4.98 KB
/
main.js
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
import { BedrockRuntimeClient, ConverseCommand } from "@aws-sdk/client-bedrock-runtime";
import Papa from 'papaparse';
const modelIds = {
mistral: 'mistral.mistral-large-2402-v1:0',
claude: 'anthropic.claude-3-haiku-20240307-v1:0',
};
let affirmations = [];
const modelId = modelIds.claude;
const systemPrompt = `If the user requests an affirmation, return only the affirmation text, omitting any additional commentary or prompts.`;
let client = null;
let conversationHistory = [];
async function fetchResponseFromModel(conversation) {
try {
const response = await client.send(new ConverseCommand({
modelId,
messages: conversation,
}));
return response;
} catch (err) {
console.error(err);
throw new Error('Unable to fetch response');
}
}
async function sendMessage() {
const userInput = document.querySelector("#userInput").value.trim();
const tag = userInput.split(' ').pop(); // Assuming the last word is the tag
const retrievedAffirmations = retrieveAffirmations(tag);
let userMessageContent = [{ text: userInput }];
if (retrievedAffirmations.length > 0) {
userMessageContent.push({ text: "RAG - Here are some related affirmations:" });
retrievedAffirmations.forEach(a => {
userMessageContent.push({ text: a.affirmation });
});
userMessageContent.push({ text: "Give me an affirmation to boost motivation today, referencing plants, animals, or flowers by adding emoji. Don't show the prompt, only the quote. Do not add anything like Here is an affirmation... just return the affirmation alone" });
}
if (userInput) {
// alert(`You said: ${userInput}`);
addChatBubble(userInput, 'user');
document.querySelector("#userInput").value = '';
const userMessage = {
role: "user",
system: systemPrompt,
content: userMessageContent,
};
conversationHistory.push(userMessage);
try {
const response = await fetchResponseFromModel(conversationHistory);
const botMessage = response.output.message.content[0].text;
addChatBubble(botMessage, 'bot'); // Display bot response
// Add bot message to the conversation history
const botMessageObj = {
role: "assistant",
content: [{ text: botMessage }],
};
conversationHistory.push(botMessageObj);
} catch (err) {
console.error(err);
addChatBubble('Error: Unable to fetch response', 'bot');
}
}
}
async function loadAffirmations() {
const response = await fetch('/dev/possitive_affirmation.csv');
const text = await response.text();
Papa.parse(text, {
header: false, // Since we are not using a header in this case
complete: (results) => {
results.data.forEach(row => {
if (row.length >= 2) {
const affirmation = row[0].trim();
const tag = row[1].trim();
affirmations.push({ affirmation, tag });
}
});
},
error: (error) => {
console.error('Error parsing CSV:', error);
}
});
}
function retrieveAffirmations(tag) {
if (!Array.isArray(affirmations) || affirmations.length === 0) {
console.warn("Affirmations have not been loaded yet.");
return [];
}
return affirmations.filter(affirmation => affirmation.tag.toLowerCase() === tag.toLowerCase());
}
function addChatBubble(text, type) {
const chatbox = document.querySelector("#chatbox");
const chat = document.createElement('div');
const bubble = document.createElement('div');
bubble.classList.add('chat-bubble');
bubble.textContent = text;
if ('bot' === type) {
chat.classList.add('chat','chat-start');
bubble.classList.add('chat-bubble-info');
} else {
chat.classList.add('chat','chat-end');
bubble.classList.add('chat-bubble-primary');
}
chat.appendChild(bubble)
chatbox.appendChild(chat);
chatbox.scrollTop = chatbox.scrollHeight; // Auto-scroll to bottom
}
async function init() {
try {
await loadAffirmations();
const creds = await fetchCredentials();
client = await createBedrockClient(creds);
} catch (err) {
console.error(err);
addChatBubble('Error: Unable to initialize chat', 'assistant');
}
const sendButton = document.querySelector("#sendMessage");
sendButton.addEventListener("click", sendMessage);
document.querySelector("#userInput").addEventListener("keypress", function(e) {
if (e.key === "Enter") sendMessage();
});
}
async function createBedrockClient(creds) {
return new BedrockRuntimeClient({
credentials: creds.credentials,
region: creds.region
});
}
async function fetchCredentials() {
return {
region: "us-west-2",
credentials: {
accessKeyId: import.meta.env.VITE_AWS_ACCESS_KEY_ID,
secretAccessKey: import.meta.env.VITE_AWS_SECRET_ACCESS_KEY,
sessionToken: import.meta.env.VITE_AWS_SESSION_TOKEN,
},
};
}
init();