App.js
5.41 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
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
import './normal.css';
import './App.css';
import './color_theme_1.css';
import { useState, useEffect } from 'react';
import SideMenu from './SideMenu'
import ChatBox from './ChatBox'
function App() {
useEffect(() => {
getEngines();
}, [])
const [chatInput, setChatInput] = useState("");
const [models, setModels] = useState([]);
const [temperature, setTemperature] = useState(0.7);
const [currentModel, setCurrentModel] = useState("text-davinci-003");
const [chatLog, setChatLog] = useState([{
user: "gpt",
message: "Welcome to AI-PRO... How can I help you?"
}]);
function clearChat(){
setChatLog([]);
setChatInput("");
setStartedInteraction(false);
}
function getEngines(){
fetch(process.env.REACT_APP_SERVER_URL + "/models")
.then(res => res.json())
.then(data => {
data.models.data.sort((a, b) => {
if(a.id < b.id) { return -1; }
if(a.id > b.id) { return 1; }
return 0;
})
setModels(data.models.data)
})
}
async function handleSubmit(e){
e.preventDefault();
const userInput = ['what', 'why', 'when', 'where' , 'which', 'did', 'do', 'how', 'can', 'are', 'who'];
const userInputRegex = new RegExp(`\\b(${userInput.join('|')})\\b`, 'gi');
const inputMatches = chatInput.match(userInputRegex);
const userPunctuation = ['.', '?', '!', ':', ';', ','];
const userPunctuationRegex = new RegExp(`[${userPunctuation.join('')}]$`);
const punctuationMatches = chatInput.match(userPunctuationRegex);
var userModifiedInput = chatInput
if (!punctuationMatches) {
if (!inputMatches) {
userModifiedInput = chatInput + ".";
} else {
userModifiedInput = chatInput + "?";
}
}
let chatLogNew = [...chatLog, { user: "me", message: `${userModifiedInput}`} ]
setChatInput("");
setChatLog(chatLogNew)
const userMessage = { user: "gpt", message: "..." };
setChatLog(prevChatLog => [...prevChatLog, userMessage]);
const messages = chatLogNew.map((message) => message.message).join("\n")
let intervalId = startInterval();
try {
const response = await fetch(process.env.REACT_APP_SERVER_URL + "/api", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
message: messages,
currentModel,
})
});
const data = await response.json();
const parsedData = data.message.trim();
clearInterval(intervalId);
const programmingKeywords = ['code', 'application', 'controller', 'rails' , 'PHP', 'java', 'javascript', 'script', 'console', 'python', 'programming', 'table'];
const regex = new RegExp(`\\b(${programmingKeywords.join('|')})\\b`, 'gi');
const matches = parsedData.match(regex);
if (!matches) {
var replaceTags = (parsedData.replace(/(?:\r\n|\r|\n)/g, '<br>').replace(/\./g, '. '))
} else {
replaceTags = (parsedData.replace(':',':<code>').replace('<?','<?').replace('?>','?>').replace(/\n/g, '<br>'))
}
for (let i = 0; i < replaceTags.length; i++) {
setTimeout(() => {
const parsedMsg = replaceTags.slice(0, i + 1);
updateLastMessage(parsedMsg);
var scrollToTheBottomChatLog = document.getElementsByClassName("chat-log")[0];
scrollToTheBottomChatLog.scrollTop = scrollToTheBottomChatLog.scrollHeight;
}, i * 5);
}
function updateLastMessage(parsedMsg) {
setChatLog(prevChatLog => {
const lastMsg = prevChatLog[prevChatLog.length - 1];
if (lastMsg && lastMsg.user === "gpt") {
return [...prevChatLog.slice(0, prevChatLog.length - 1), { user: lastMsg.user, message: parsedMsg }];
} else {
return [...prevChatLog, { user: "gpt", message: parsedMsg }];
}
});
}
} catch (error) {
const errorMsg = "We apologize for any inconvenience caused due to the delay in the response time. Please try again.";
setChatLog([...chatLogNew, { user: "gpt", message: `<div class="errormsg"><span>i</span><div class="msg">${errorMsg}</div></div>`} ])
}
function startInterval() {
return setInterval(function() {
if (userMessage.message.length === 3) {
userMessage.message = ".";
} else if (userMessage.message.length === 1) {
userMessage.message = "..";
} else {
userMessage.message = "...";
}
var thinkingDots = document.getElementsByClassName("message");
var thinkingDot = thinkingDots[thinkingDots.length - 1];
thinkingDot.innerHTML = userMessage.message;
}, 500);
}
}
function handleTemp(temp) {
if(temp > 1){
setTemperature(1)
} else if (temp < 0){
setTemperature(0)
} else {
setTemperature(temp)
}
}
const [startedInteraction, setStartedInteraction] = useState(false);
return (
<div className="App">
<SideMenu
currentModel={currentModel}
setCurrentModel={setCurrentModel}
models={models}
setTemperature={handleTemp}
temperature={temperature}
clearChat={clearChat}
/>
<ChatBox
chatInput={chatInput}
chatLog={chatLog}
setChatInput={setChatInput}
startedInteraction={startedInteraction}
setStartedInteraction={setStartedInteraction}
handleSubmit={handleSubmit} />
</div>
);
}
export default App;