-
Notifications
You must be signed in to change notification settings - Fork 35
Expand file tree
/
Copy pathEmbeddedChatbot.tsx
More file actions
414 lines (383 loc) · 14.6 KB
/
Copy pathEmbeddedChatbot.tsx
File metadata and controls
414 lines (383 loc) · 14.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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
import { useEffect, useRef, useState, FunctionComponent, MouseEvent } from 'react';
import {
Bullseye,
Brand,
DropdownList,
DropdownItem,
Page,
Masthead,
MastheadMain,
MastheadBrand,
MastheadLogo,
PageSidebarBody,
PageSidebar,
MastheadToggle,
PageToggleButton,
SkipToContent
} from '@patternfly/react-core';
import Chatbot, { ChatbotDisplayMode } from '@patternfly/chatbot/dist/dynamic/Chatbot';
import ChatbotContent from '@patternfly/chatbot/dist/dynamic/ChatbotContent';
import ChatbotWelcomePrompt from '@patternfly/chatbot/dist/dynamic/ChatbotWelcomePrompt';
import ChatbotFooter, { ChatbotFootnote } from '@patternfly/chatbot/dist/dynamic/ChatbotFooter';
import MessageBar from '@patternfly/chatbot/dist/dynamic/MessageBar';
import MessageBox from '@patternfly/chatbot/dist/dynamic/MessageBox';
import Message, { MessageProps } from '@patternfly/chatbot/dist/dynamic/Message';
import ChatbotConversationHistoryNav, {
Conversation
} from '@patternfly/chatbot/dist/dynamic/ChatbotConversationHistoryNav';
import ChatbotHeader, {
ChatbotHeaderMenu,
ChatbotHeaderMain,
ChatbotHeaderTitle,
ChatbotHeaderActions,
ChatbotHeaderSelectorDropdown
} from '@patternfly/chatbot/dist/dynamic/ChatbotHeader';
import PFHorizontalLogoColor from '../UI/PF-HorizontalLogo-Color.svg';
import PFHorizontalLogoReverse from '../UI/PF-HorizontalLogo-Reverse.svg';
import { RhUiMenuBarsIcon } from '@patternfly/react-icons';
import userAvatar from '../Messages/user_avatar.svg';
import '@patternfly/react-core/dist/styles/base.css';
import '@patternfly/chatbot/dist/css/main.css';
const footnoteProps = {
label: 'Always review AI-generated content prior to use.'
};
const markdown = `A paragraph with *emphasis* and **strong importance**.
> A block quote with ~strikethrough~ and a URL: https://reactjs.org.
Here is an inline code - \`() => void\`
Here is some YAML code:
~~~yaml
apiVersion: helm.openshift.io/v1beta1/
kind: HelmChartRepository
metadata:
name: azure-sample-repo0oooo00ooo
spec:
connectionConfig:
url: https://raw.githubusercontent.com/Azure-Samples/helm-charts/master/docs
~~~
Here is some JavaScript code:
~~~js
const MessageLoading = () => (
<div className="pf-chatbot__message-loading">
<span className="pf-chatbot__message-loading-dots">
<span className="pf-v6-screen-reader">Loading message</span>
</span>
</div>
);
export default MessageLoading;
~~~
`;
// It's important to set a date and timestamp prop since the Message components re-render.
// The timestamps re-render with them.
const date = new Date();
const initialMessages: MessageProps[] = [
{
id: '1',
role: 'user',
content: 'Hello, can you give me an example of what you can do?',
name: 'User',
avatar: userAvatar,
timestamp: date.toLocaleString(),
avatarProps: { isBordered: true }
},
{
id: '2',
role: 'bot',
content: markdown,
name: 'Bot',
timestamp: date.toLocaleString(),
actions: {
// eslint-disable-next-line no-console
positive: { onClick: () => console.log('Good response') },
// eslint-disable-next-line no-console
negative: { onClick: () => console.log('Bad response') },
// eslint-disable-next-line no-console
copy: { onClick: () => console.log('Copy') },
// eslint-disable-next-line no-console
download: { onClick: () => console.log('Download') },
// eslint-disable-next-line no-console
listen: { onClick: () => console.log('Listen') }
}
}
];
const welcomePrompts = [
{
title: 'Set up account',
message: 'Choose the necessary settings and preferences for your account.'
},
{
title: 'Troubleshoot issue',
message: 'Find documentation and instructions to resolve your issue.'
}
];
const initialConversations = {
Today: [{ id: '1', text: 'Hello, can you give me an example of what you can do?' }],
'This month': [
{
id: '2',
text: 'Enterprise Linux installation and setup'
},
{ id: '3', text: 'Troubleshoot system crash' }
],
March: [
{ id: '4', text: 'Ansible security and updates' },
{ id: '5', text: 'Red Hat certification' },
{ id: '6', text: 'Lightspeed user documentation' }
],
February: [
{ id: '7', text: 'Crashing pod assistance' },
{ id: '8', text: 'OpenShift AI pipelines' },
{ id: '9', text: 'Updating subscription plan' },
{ id: '10', text: 'Red Hat licensing options' }
],
January: [
{ id: '11', text: 'RHEL system performance' },
{ id: '12', text: 'Manage user accounts' }
]
};
export const EmbeddedChatbotDemo: FunctionComponent = () => {
const [messages, setMessages] = useState<MessageProps[]>(initialMessages);
const [selectedModel, setSelectedModel] = useState('Granite 7B');
const [isSendButtonDisabled, setIsSendButtonDisabled] = useState(false);
const [isDrawerOpen, setIsDrawerOpen] = useState(false);
const [conversations, setConversations] = useState<Conversation[] | { [key: string]: Conversation[] }>(
initialConversations
);
const [isSidebarOpen, setIsSidebarOpen] = useState(false);
const [announcement, setAnnouncement] = useState<string>();
const scrollToBottomRef = useRef<HTMLDivElement>(null);
const historyRef = useRef<HTMLButtonElement>(null);
const displayMode = ChatbotDisplayMode.embedded;
// Auto-scrolls to the latest message
useEffect(() => {
// don't scroll the first load - in this demo, we know we start with two messages
if (messages.length > 2) {
scrollToBottomRef.current?.scrollIntoView({ behavior: 'smooth' });
}
}, [messages]);
const onSelectModel = (_event: MouseEvent<Element, MouseEvent> | undefined, value: string | number | undefined) => {
setSelectedModel(value as string);
};
// you will likely want to come up with your own unique id function; this is for demo purposes only
const generateId = () => {
const id = Date.now() + Math.random();
return id.toString();
};
const handleSend = (message: string) => {
setIsSendButtonDisabled(true);
const newMessages: MessageProps[] = [];
// We can't use structuredClone since messages contains functions, but we can't mutate
// items that are going into state or the UI won't update correctly
messages.forEach((message) => newMessages.push(message));
// It's important to set a timestamp prop since the Message components re-render.
// The timestamps re-render with them.
const date = new Date();
newMessages.push({
id: generateId(),
role: 'user',
content: message,
name: 'User',
avatar: userAvatar,
timestamp: date.toLocaleString(),
avatarProps: { isBordered: true }
});
newMessages.push({
id: generateId(),
role: 'bot',
content: 'API response goes here',
name: 'Bot',
isLoading: true,
timestamp: date.toLocaleString()
});
setMessages(newMessages);
// make announcement to assistive devices that new messages have been added
setAnnouncement(`Message from User: ${message}. Message from Bot is loading.`);
// this is for demo purposes only; in a real situation, there would be an API response we would wait for
setTimeout(() => {
const loadedMessages: MessageProps[] = [];
// we can't use structuredClone since messages contains functions, but we can't mutate
// items that are going into state or the UI won't update correctly
newMessages.forEach((message) => loadedMessages.push(message));
loadedMessages.pop();
loadedMessages.push({
id: generateId(),
role: 'bot',
content: 'API response goes here',
name: 'Bot',
isLoading: false,
actions: {
// eslint-disable-next-line no-console
positive: { onClick: () => console.log('Good response') },
// eslint-disable-next-line no-console
negative: { onClick: () => console.log('Bad response') },
// eslint-disable-next-line no-console
copy: { onClick: () => console.log('Copy') },
// eslint-disable-next-line no-console
download: { onClick: () => console.log('Download') },
// eslint-disable-next-line no-console
listen: { onClick: () => console.log('Listen') }
},
timestamp: date.toLocaleString()
});
setMessages(loadedMessages);
// make announcement to assistive devices that new message has loaded
setAnnouncement(`Message from Bot: API response goes here`);
setIsSendButtonDisabled(false);
}, 5000);
};
const findMatchingItems = (targetValue: string) => {
let filteredConversations = Object.entries(initialConversations).reduce((acc, [key, items]) => {
const filteredItems = items.filter((item) => item.text.toLowerCase().includes(targetValue.toLowerCase()));
if (filteredItems.length > 0) {
acc[key] = filteredItems;
}
return acc;
}, {});
// append message if no items are found
if (Object.keys(filteredConversations).length === 0) {
filteredConversations = [{ id: '13', noIcon: true, text: 'No results found' }];
}
return filteredConversations;
};
const horizontalLogo = (
<Bullseye>
<Brand className="show-light" src={PFHorizontalLogoColor} alt="PatternFly" />
<Brand className="show-dark" src={PFHorizontalLogoReverse} alt="PatternFly" />
</Bullseye>
);
const masthead = (
<Masthead>
<MastheadMain>
<MastheadToggle>
<PageToggleButton
variant="plain"
aria-label="Global navigation"
isSidebarOpen={isSidebarOpen}
onSidebarToggle={() => setIsSidebarOpen(!isSidebarOpen)}
id="fill-nav-toggle"
>
<RhUiMenuBarsIcon />
</PageToggleButton>
</MastheadToggle>
<MastheadBrand>
<MastheadLogo href="https://patternfly.org" target="_blank">
Logo
</MastheadLogo>
</MastheadBrand>
</MastheadMain>
</Masthead>
);
const sidebar = (
<PageSidebar isSidebarOpen={isSidebarOpen} id="fill-sidebar">
<PageSidebarBody>Navigation</PageSidebarBody>
</PageSidebar>
);
const skipToChatbot = (event: MouseEvent) => {
event.preventDefault();
if (historyRef.current) {
historyRef.current.focus();
}
};
const skipToContent = (
/* You can also add a SkipToContent for your main content here */
<SkipToContent href="#" onClick={skipToChatbot}>
Skip to chatbot
</SkipToContent>
);
return (
<Page skipToContent={skipToContent} masthead={masthead} sidebar={sidebar} isContentFilled>
<Chatbot displayMode={displayMode}>
<ChatbotConversationHistoryNav
displayMode={displayMode}
onDrawerToggle={() => {
setIsDrawerOpen(!isDrawerOpen);
setConversations(initialConversations);
}}
isDrawerOpen={isDrawerOpen}
setIsDrawerOpen={setIsDrawerOpen}
activeItemId="1"
// eslint-disable-next-line no-console
onSelectActiveItem={(e, selectedItem) => console.log(`Selected history item with id ${selectedItem}`)}
conversations={conversations}
onNewChat={() => {
setIsDrawerOpen(!isDrawerOpen);
setMessages([]);
setConversations(initialConversations);
}}
handleTextInputChange={(value: string) => {
if (value === '') {
setConversations(initialConversations);
}
// this is where you would perform search on the items in the drawer
// and update the state
const newConversations: { [key: string]: Conversation[] } = findMatchingItems(value);
setConversations(newConversations);
}}
drawerContent={
<>
<ChatbotHeader>
<ChatbotHeaderMain>
<ChatbotHeaderMenu
ref={historyRef}
aria-expanded={isDrawerOpen}
onMenuToggle={() => setIsDrawerOpen(!isDrawerOpen)}
/>
<ChatbotHeaderTitle>{horizontalLogo}</ChatbotHeaderTitle>
</ChatbotHeaderMain>
<ChatbotHeaderActions>
<ChatbotHeaderSelectorDropdown value={selectedModel} onSelect={onSelectModel}>
<DropdownList>
<DropdownItem value="Granite 7B" key="granite">
Granite 7B
</DropdownItem>
<DropdownItem value="Llama 3.0" key="llama">
Llama 3.0
</DropdownItem>
<DropdownItem value="Mistral 3B" key="mistral">
Mistral 3B
</DropdownItem>
</DropdownList>
</ChatbotHeaderSelectorDropdown>
</ChatbotHeaderActions>
</ChatbotHeader>
<ChatbotContent>
{/* Update the announcement prop on MessageBox whenever a new message is sent
so that users of assistive devices receive sufficient context */}
<MessageBox announcement={announcement}>
<ChatbotWelcomePrompt
title="Hi, ChatBot User!"
description="How can I help you today?"
prompts={welcomePrompts}
/>
{/* This code block enables scrolling to the top of the last message.
You can instead choose to move the div with scrollToBottomRef on it below
the map of messages, so that users are forced to scroll to the bottom.
If you are using streaming, you will want to take a different approach;
see: https://github.com/patternfly/chatbot/issues/201#issuecomment-2400725173 */}
{messages.map((message, index) => {
if (index === messages.length - 1) {
return (
<>
<div ref={scrollToBottomRef}></div>
<Message key={message.id} {...message} />
</>
);
}
return <Message key={message.id} {...message} />;
})}
</MessageBox>
</ChatbotContent>
<ChatbotFooter>
<MessageBar
onSendMessage={handleSend}
hasMicrophoneButton
isSendButtonDisabled={isSendButtonDisabled}
/>
<ChatbotFootnote {...footnoteProps} />
</ChatbotFooter>
</>
}
></ChatbotConversationHistoryNav>
</Chatbot>
</Page>
);
};