Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
<!-- default badges list -->
![](https://img.shields.io/endpoint?url=https://codecentral.devexpress.com/api/v1/VersionRange/1057257433/25.1.2%2B)
[![](https://img.shields.io/badge/Open_in_DevExpress_Support_Center-FF7200?style=flat-square&logo=DevExpress&logoColor=white)](https://supportcenter.devexpress.com/ticket/details/T1307369)
[![](https://img.shields.io/badge/📖_How_to_use_DevExpress_Examples-e9f6fc?style=flat-square)](https://docs.devexpress.com/GeneralInformation/403183)
[![](https://img.shields.io/badge/💬_Leave_Feedback-feecdd?style=flat-square)](#does-this-example-address-your-development-requirementsobjectives)
Expand Down
5 changes: 5 additions & 0 deletions Vue/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,11 @@
"dependencies": {
"devextreme": "25.1.3",
"devextreme-vue": "25.1.3",
"openai": "^6.3.0",
"rehype-stringify": "^10.0.1",
"remark-parse": "^11.0.0",
"remark-rehype": "^11.1.2",
"unified": "^11.0.5",
"vue": "^3.2.45",
"vue-router": "^4.1.6"
},
Expand Down
31 changes: 28 additions & 3 deletions Vue/src/App.vue
Original file line number Diff line number Diff line change
@@ -1,9 +1,34 @@
<script setup lang="ts">
import { RouterView } from 'vue-router';
import Chat from './components/ChartInterface.vue';
import 'devextreme/dist/css/dx.fluent.blue.light.css';
</script>

<template>
<div class="main">
<RouterView/>
<div class="app-container">
<div class="chat-wrapper">
<Chat/>
</div>
</div>
</template>
<style scoped>
.app-container {
display: flex;
justify-content: center;
padding: 50px;
}

.chat-wrapper {
width: 100%;
max-width: 900px;
height: 710px;
background: white;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
overflow: hidden;
}

:deep(.chat-disabled .dx-chat-messagebox) {
opacity: 0.5;
pointer-events: none;
}
</style>
202 changes: 202 additions & 0 deletions Vue/src/chat.helpers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,202 @@
import { ref } from 'vue';
import { CustomStore, DataSource } from 'devextreme-vue/common/data';
import { unified } from 'unified';
import remarkParse from 'remark-parse';
import remarkRehype from 'remark-rehype';
import rehypeStringify from 'rehype-stringify';
import { loadMessages } from 'devextreme/localization';
import type { DxChatTypes } from 'devextreme-vue/chat';

const ALERT_TIMEOUT = 10000;

const assistant: DxChatTypes.User = { id: 'assistant', name: 'Virtual Assistant' };

export function useChatLogic() {
const sessionId: string = Math.random().toString(36).substring(7);
let lastMessageText: string = '';
const dataSource = ref<DataSource | null>(null);
const user = ref({ id: 'user' });
const typingUsers = ref<Array<DxChatTypes.User>>([]);
const alerts = ref<Array<DxChatTypes.Alert>>([]);
const regenerationText = ref('Regeneration...');
const copyButtonIcon = ref('copy');
const isDisabled = ref(false);
const store = ref([]);
const messages = ref<Array<{ role: 'user' | 'assistant' | 'system'; content: string }>>([]);

const loadMessage = () => {
loadMessages({
en: {
'dxChat-emptyListMessage': 'Chat is Empty',
'dxChat-emptyListPrompt': 'AI Assistant is ready to answer your questions.',
'dxChat-textareaPlaceholder': 'Ask AI Assistant...'
}
});
};

const initDataSource = () => {
const customStore = new CustomStore({
key: 'id',
load: () => Promise.resolve([...store.value]),
insert: (message) => {
store.value.push(message);
return Promise.resolve(message);
}
});

dataSource.value = new DataSource({ store: customStore, paginate: false });
};

const getAIResponse = async(text: string | undefined) => {
let id = sessionId;
const response = await fetch('http://localhost:3000/webhook', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ message: text, sessionId: id }),
});

const data: { response: string } = await response.json();

return data.response;
};

const processMessageSending = async(e: DxChatTypes.MessageEnteredEvent) => {
let { message } = e;
toggleDisabledState(true);
(e.event?.target as HTMLElement).blur();
typingUsers.value = [assistant];

try {
const aiResponse = await getAIResponse(message.text);
setTimeout(() => {
typingUsers.value = [];
renderAssistantMessage(aiResponse ?? '');
}, 200);
} catch(error) {
(e.event?.target as HTMLElement).focus();
typingUsers.value = [];
alertLimitReached(error);
} finally {
(e.event?.target as HTMLElement).focus();
toggleDisabledState(false);
}
};

const updateLastMessage = (text?: string | null | undefined) => {
let items = dataSource.value?.items();
const lastMessage = items?.slice(-1)[0];
const data = {
text: text ?? regenerationText
};
lastMessageText = text ? '' : lastMessage.text;

dataSource.value?.store().push([{
type: 'update',
key: lastMessage.id,
data: data
}]);
};

const renderAssistantMessage = (text: string | null) => {
const message = {
id: Date.now(),
timestamp: new Date(),
author: assistant,
text
};

dataSource.value?.store().push([{ type: 'insert', data: message }]);
};

const alertLimitReached = (error: any) => {
setAlerts([{ message: error.message }]);
setTimeout(() => setAlerts([]), ALERT_TIMEOUT);
};

const setAlerts = (newAlerts: DxChatTypes.Alert[]) => {
alerts.value = newAlerts;
};

const regenerate = async() => {
try {
const aiResponse = await getAIResponse(lastMessageText);
updateLastMessage(aiResponse);
const lastMsg = messages.value.slice(-1)[0];
if (lastMsg) {
lastMsg.content = aiResponse ?? '';
messages.value = [...messages.value];
}
} catch(error) {
const lastMsg = messages.value.slice(-1)[0];
if (lastMsg) updateLastMessage(lastMsg.content);
alertLimitReached(error);
}
};

const convertToHtml = (message: {text: string}) => {
return unified()
.use(remarkParse)
.use(remarkRehype)
.use(rehypeStringify)
.processSync(message.text || '')
.toString();
};

const toggleDisabledState = (disabled: boolean, event?: { target?: EventTarget } | undefined) => {
const element = event?.target as HTMLElement;
isDisabled.value = disabled;

if (element) {
if (disabled) {
element.blur();
} else {
element.focus();
}
}
};

const onMessageEntered = async(e: DxChatTypes.MessageEnteredEvent) => {
let { message } = e;
dataSource.value?.store().push([{
type: 'insert',
data: { id: Date.now(), ...message }
}]);

messages.value.push({ role: 'user', content: message?.text ?? '' });
await processMessageSending(e);
};

const onCopyButtonClick = (message: {text: string}) => {
navigator.clipboard?.writeText(message.text ?? '');
copyButtonIcon.value = 'check';
setTimeout(() => copyButtonIcon.value = 'copy', 2500);
};

const onRegenerateButtonClick = async() => {
updateLastMessage();
toggleDisabledState(true);
try {
await regenerate();
} finally {
toggleDisabledState(false);
}
};

return {
dataSource,
user,
typingUsers,
alerts,
regenerationText,
copyButtonIcon,
loadMessage,
initDataSource,
convertToHtml,
onMessageEntered,
onCopyButtonClick,
onRegenerateButtonClick,
isDisabled
};
}
134 changes: 134 additions & 0 deletions Vue/src/components/ChartInterface.vue
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
<template>
<div :class="['demo-container', { 'chat-disabled': isDisabled }]">
<DxChat
:data-source="dataSource"
:reload-on-change="false"
:show-avatar="false"
:show-day-headers="false"
:user="user"
height="710"
v-model:typing-users="typingUsers"
v-model:alerts="alerts"
@message-entered="onMessageEntered"
message-template="messageTemplate"
>
<template #messageTemplate="{ data }">
<div v-if="data.message.text === regenerationText">
<span>{{ regenerationText }}</span>
</div>
<div v-else>
<div
class="dx-chat-messagebubble-text"
v-html="convertToHtml(data.message)"
/>
<div class="dx-bubble-button-container">
<DxButton
:icon="copyButtonIcon"
styling-mode="text"
hint="Copy"
@click="onCopyButtonClick(data.message)"
/>
<DxButton
icon="refresh"
styling-mode="text"
hint="Regenerate"
@click="onRegenerateButtonClick"
/>
</div>
</div>
</template>
</DxChat>
</div>
</template>

<script setup lang="ts">
import { onMounted } from 'vue';
import { DxChat } from 'devextreme-vue/chat';
import { DxButton } from 'devextreme-vue/button';
import { useChatLogic } from '@/chat.helpers';

const {
dataSource,
user,
typingUsers,
alerts,
regenerationText,
copyButtonIcon,
loadMessage,
initDataSource,
convertToHtml,
onMessageEntered,
onCopyButtonClick,
onRegenerateButtonClick,
isDisabled
} = useChatLogic();

// Initialize component
onMounted(() => {
loadMessage();
initDataSource();
});
</script>
<style scoped>
:deep(.demo-container) {
display: flex;
justify-content: center;
}

:deep(.dx-chat) {
max-width: 900px;
}

:deep(.dx-chat-messagelist-empty-image) {
display: none;
}

:deep(.dx-chat-messagelist-empty-message) {
font-size: var(--dx-font-size-heading-5);
}

:deep(.dx-chat-messagebubble-content),
:deep(.dx-chat-messagebubble-text) {
display: flex;
flex-direction: column;
}

:deep(.dx-bubble-button-container) {
display: none;
}

:deep(.dx-button) {
display: inline-block;
color: var(--dx-color-icon);
}

:deep(.dx-chat-messagegroup-alignment-start:last-child .dx-chat-messagebubble:last-child .dx-bubble-button-container) {
display: flex;
gap: 4px;
margin-top: 8px;
}

:deep(.dx-chat-messagebubble-content > div > div > p:first-child) {
margin-top: 0;
}

:deep(.dx-chat-messagebubble-content > div > div > p:last-child) {
margin-bottom: 0;
}

:deep(.dx-chat-messagebubble-content ol),
:deep(.dx-chat-messagebubble-content ul) {
white-space: normal;
}

:deep(.dx-chat-messagebubble-content h1),
:deep(.dx-chat-messagebubble-content h2),
:deep(.dx-chat-messagebubble-content h3),
:deep(.dx-chat-messagebubble-content h4),
:deep(.dx-chat-messagebubble-content h5),
:deep(.dx-chat-messagebubble-content h6) {
font-size: revert;
font-weight: revert;
}

</style>
Loading