-
Notifications
You must be signed in to change notification settings - Fork 225
Expand file tree
/
Copy pathChatView.jsx
More file actions
220 lines (198 loc) · 6.6 KB
/
ChatView.jsx
File metadata and controls
220 lines (198 loc) · 6.6 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
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
import { useState, useRef, useEffect, useContext } from 'react';
import Message from './Message';
import { ChatContext } from '../context/chatContext';
import Thinking from './Thinking';
import { MdSend } from 'react-icons/md';
import { replaceProfanities } from 'no-profanity';
import { davinci } from '../utils/davinci';
import { dalle } from '../utils/dalle';
import Modal from './Modal';
import Setting from './Setting';
import { AiPayClient } from 'ai-pay';
const options = ['ChatGPT', 'DALL·E'];
const gptModel = ['gpt-3.5-turbo', 'gpt-4'];
const template = [
{
title: 'Plan a trip',
prompt: 'I want to plan a trip to New York City.',
},
{
title: 'how to make a cake',
prompt: 'How to make a cake with chocolate and strawberries?',
},
{
title: 'Business ideas',
prompt: 'Generate 5 business ideas for a new startup company.',
},
{
title: 'What is recursion?',
prompt: 'What is recursion? show me an example in python.',
},
];
/**
* A chat view component that displays a list of messages and a form for sending new messages.
*/
const ChatView = () => {
const messagesEndRef = useRef();
const inputRef = useRef();
const [formValue, setFormValue] = useState('');
const [thinking, setThinking] = useState(false);
const [selected, setSelected] = useState(options[0]);
const [gpt, setGpt] = useState(gptModel[0]);
const [messages, addMessage] = useContext(ChatContext);
const [modalOpen, setModalOpen] = useState(false);
const [streamedResponse, setStreamedResponse] = useState(undefined);
/**
* Scrolls the chat area to the bottom.
*/
const scrollToBottom = () => {
messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
};
/**
* Adds a new message to the chat.
*
* @param {string} newValue - The text of the new message.
* @param {boolean} [ai=false] - Whether the message was sent by an AI or the user.
*/
const updateMessage = (newValue, ai = false, selected) => {
const id = Date.now() + Math.floor(Math.random() * 1000000);
const newMsg = {
id: id,
createdAt: Date.now(),
text: newValue,
ai: ai,
selected: `${selected}`,
};
addMessage(newMsg);
};
/**
* Sends our prompt to our API and get response to our request from openai.
*
* @param {Event} e - The submit event of the form.
*/
const sendMessage = async (e) => {
e.preventDefault();
const key = window.localStorage.getItem('api-key');
const sessionId = AiPayClient.getInstance().getClientSessionId();
if (!key && !sessionId) {
setModalOpen(true);
return;
}
const cleanPrompt = replaceProfanities(formValue);
const newMsg = cleanPrompt;
const aiModel = selected;
const gptVersion = gpt;
setThinking(true);
setFormValue('');
updateMessage(newMsg, false, aiModel);
console.log(gptVersion);
console.log(selected);
try {
if (aiModel === options[0]) {
const LLMresponse = await davinci(cleanPrompt, key, gptVersion, (streamedResponse) => {
setStreamedResponse(streamedResponse);
});
setStreamedResponse(undefined);
LLMresponse && updateMessage(LLMresponse, true, aiModel);
} else {
const responseUrl = await dalle(cleanPrompt, key);
responseUrl && updateMessage(responseUrl, true, aiModel);
}
} catch (err) {
window.alert(`Error: ${err} please try again later`);
}
setThinking(false);
};
const handleKeyDown = (e) => {
if (e.key === 'Enter') {
// 👇 Get input value
sendMessage(e);
}
};
/**
* Scrolls the chat area to the bottom when the messages array is updated.
*/
useEffect(() => {
scrollToBottom();
}, [messages, thinking]);
/**
* Focuses the TextArea input to when the component is first rendered.
*/
useEffect(() => {
inputRef.current.focus();
}, []);
return (
<main className='relative flex flex-col h-screen p-1 overflow-hidden dark:bg-light-grey'>
<div className='mx-auto my-4 tabs tabs-boxed w-fit'>
<a
onClick={() => setGpt(gptModel[0])}
className={`${gpt == gptModel[0] && 'tab-active'} tab`}>
GPT-3.5
</a>
<a
onClick={() => setGpt(gptModel[1])}
className={`${gpt == gptModel[1] && 'tab-active'} tab`}>
GPT-4
</a>
</div>
<section className='flex flex-col flex-grow w-full px-4 overflow-y-scroll sm:px-10 md:px-32'>
{messages.length ? (
messages.map((message, index) => (
<Message key={index} message={{ ...message }} />
))
) : (
<div className='flex my-2'>
<div className='w-screen overflow-hidden'>
<ul className='grid grid-cols-2 gap-2 mx-10'>
{template.map((item, index) => (
<li
onClick={() => setFormValue(item.prompt)}
key={index}
className='p-6 border rounded-lg border-slate-300 hover:border-slate-500'>
<p className='text-base font-semibold'>{item.title}</p>
<p className='text-sm'>{item.prompt}</p>
</li>
))}
</ul>
</div>
</div>
)}
{thinking && !streamedResponse && <Thinking />}
{streamedResponse && <Message message={{
id: "stream",
text: streamedResponse,
ai: true,
selected: options[0],
}} />}
<span ref={messagesEndRef}></span>
</section>
<form
className='flex flex-col px-10 mb-2 md:px-32 join sm:flex-row'
onSubmit={sendMessage}>
<select
value={selected}
onChange={(e) => setSelected(e.target.value)}
className='w-full sm:w-40 select select-bordered join-item'>
<option>{options[0]}</option>
<option>{options[1]}</option>
</select>
<div className='flex items-stretch justify-between w-full'>
<textarea
ref={inputRef}
className='w-full grow input input-bordered join-item max-h-[20rem] min-h-[3rem]'
value={formValue}
onKeyDown={handleKeyDown}
onChange={(e) => setFormValue(e.target.value)}
/>
<button type='submit' className='join-item btn' disabled={!formValue}>
<MdSend size={30} />
</button>
</div>
</form>
<Modal title='AI Provider' modalOpen={modalOpen} setModalOpen={setModalOpen}>
<Setting modalOpen={modalOpen} setModalOpen={setModalOpen} />
</Modal>
</main>
);
};
export default ChatView;