<div class="demo-container">
<dx-chat
[class.chat-disabled]="isDisabled"
[dataSource]="dataSource"
[reloadOnChange]="false"
[showAvatar]="false"
[showDayHeaders]="false"
[user]="user"
height="710"
[typingUsers]="typingUsers$ | async"
[alerts]="alerts$ | async"
(onMessageEntered)="onMessageEntered($event)"
messageTemplate="messageTemplate"
[speechToTextEnabled]="true"
>
<div *dxTemplate="let data of 'messageTemplate'">
@if (data.message.text === regenerationText) {
<ng-container>
<span>{{ regenerationText }}</span>
</ng-container>
} @if (data.message.text !== regenerationText) {
<ng-container>
<div
class="chat-messagebubble-text"
[innerHTML]="convertToHtml(data.message)"
>
</div>
<div class="bubble-button-container">
<dx-button
[icon]="copyButtonIcon"
stylingMode="text"
hint="Copy"
(onClick)="onCopyButtonClick(data.message)"
>
</dx-button>
<dx-button
icon="refresh"
stylingMode="text"
hint="Regenerate"
(onClick)="onRegenerateButtonClick()"
>
</dx-button>
</div>
</ng-container>
}
</div>
</dx-chat>
</div>
import { bootstrapApplication } from '@angular/platform-browser';
import {
ChangeDetectorRef, Component, enableProdMode, provideZoneChangeDetection,
} from '@angular/core';
import { AsyncPipe } from '@angular/common';
import { DxChatModule, DxButtonModule } from 'devextreme-angular';
import type { DxChatTypes } from 'devextreme-angular/ui/chat';
import { Observable } from 'rxjs';
import { loadMessages } from 'devextreme-angular/common/core/localization';
import { DataSource } from 'devextreme-angular/common/data';
import { AppService } from './app.service';
import { AiService } from './ai/ai.service';
if (!/localhost/.test(document.location.host)) {
enableProdMode();
}
@Component({
selector: 'demo-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
imports: [
DxChatModule,
DxButtonModule,
AsyncPipe,
],
})
export class AppComponent {
dataSource: DataSource;
user: DxChatTypes.User;
typingUsers$: Observable<DxChatTypes.User[]>;
alerts$: Observable<DxChatTypes.Alert[]>;
regenerationText: string;
copyButtonIcon: string;
isDisabled: boolean;
constructor(
private readonly appService: AppService,
private readonly changeDetectorRef: ChangeDetectorRef,
) {
loadMessages(this.appService.getDictionary());
this.dataSource = this.appService.dataSource;
this.user = this.appService.user;
this.alerts$ = this.appService.alerts$;
this.typingUsers$ = this.appService.typingUsers$;
this.regenerationText = this.appService.REGENERATION_TEXT;
this.copyButtonIcon = 'copy';
this.isDisabled = false;
}
convertToHtml(message: DxChatTypes.Message): string {
return this.appService.convertToHtml(message.text);
}
toggleDisabledState(disabled: boolean, event = undefined) {
this.isDisabled = disabled;
if (disabled) {
event?.target.blur();
} else {
event?.target.focus();
}
this.changeDetectorRef.detectChanges();
}
async onMessageEntered(e: DxChatTypes.MessageEnteredEvent) {
if (!this.appService.alerts.length) {
this.toggleDisabledState(true, e.event);
}
try {
await this.appService.onMessageEntered(e);
} finally {
this.toggleDisabledState(false, e.event);
}
}
onCopyButtonClick(message: DxChatTypes.Message) {
navigator.clipboard?.writeText(message.text);
this.copyButtonIcon = 'check';
setTimeout(() => {
this.copyButtonIcon = 'copy';
this.changeDetectorRef.detectChanges();
}, 2500);
}
async onRegenerateButtonClick() {
this.appService.updateLastMessage();
this.toggleDisabledState(true);
try {
await this.appService.regenerate();
} finally {
this.toggleDisabledState(false);
}
}
}
bootstrapApplication(AppComponent, {
providers: [
provideZoneChangeDetection({ eventCoalescing: true, runCoalescing: true }),
AppService,
AiService,
],
});
.demo-container {
display: flex;
justify-content: center;
}
::ng-deep .dx-chat {
max-width: 900px;
}
::ng-deep .dx-chat-messagelist-empty-image {
display: none;
}
::ng-deep .dx-chat-messagelist-empty-message {
font-size: var(--dx-font-size-heading-5);
}
::ng-deep .dx-chat-messagebubble-content,
::ng-deep .chat-messagebubble-text {
display: flex;
flex-direction: column;
}
::ng-deep .bubble-button-container {
display: none;
}
::ng-deep .dx-button {
display: inline-block;
color: var(--dx-color-icon);
}
::ng-deep .dx-chat-messagegroup-alignment-start:last-child .dx-chat-messagebubble:last-child .bubble-button-container {
display: flex;
gap: 4px;
margin-top: 8px;
}
::ng-deep .dx-template-wrapper > div > p:first-child {
margin-top: 0;
}
::ng-deep .dx-template-wrapper > div > p:last-child {
margin-bottom: 0;
}
::ng-deep .dx-chat-messagebubble-content h1,
::ng-deep .dx-chat-messagebubble-content h2,
::ng-deep .dx-chat-messagebubble-content h3,
::ng-deep .dx-chat-messagebubble-content h4,
::ng-deep .dx-chat-messagebubble-content h5,
::ng-deep .dx-chat-messagebubble-content h6 {
font-size: revert;
font-weight: revert;
}
::ng-deep .chat-disabled .dx-chat-messagebox {
opacity: 0.5;
pointer-events: none;
}
import { Injectable } from '@angular/core';
import { Observable, BehaviorSubject } from 'rxjs';
import { unified } from 'unified';
import remarkParse from 'remark-parse';
import remarkRehype from 'remark-rehype';
import rehypeStringify from 'rehype-stringify';
import rehypeMinifyWhitespace from 'rehype-minify-whitespace';
import { type DxChatTypes } from 'devextreme-angular/ui/chat';
import { DataSource, CustomStore } from 'devextreme-angular/common/data';
import { AiService, type AIMessage } from './ai/ai.service';
@Injectable({
providedIn: 'root',
})
export class AppService {
aiService: AiService;
REGENERATION_TEXT = 'Regeneration...';
ALERT_TIMEOUT = 1000 * 60;
user: DxChatTypes.User = {
id: 'user',
};
assistant: DxChatTypes.User = {
id: 'assistant',
name: 'Virtual Assistant',
};
store: any[] = [];
messages: AIMessage[] = [];
alerts: DxChatTypes.Alert[] = [];
customStore: CustomStore;
dataSource: DataSource;
typingUsersSubject: BehaviorSubject<DxChatTypes.User[]> = new BehaviorSubject([]);
alertsSubject: BehaviorSubject<DxChatTypes.Alert[]> = new BehaviorSubject([]);
constructor(aiService: AiService) {
this.aiService = aiService;
this.initDataSource();
this.typingUsersSubject.next([]);
this.alertsSubject.next([]);
}
get typingUsers$(): Observable<DxChatTypes.User[]> {
return this.typingUsersSubject.asObservable();
}
get alerts$(): Observable<DxChatTypes.Alert[]> {
return this.alertsSubject.asObservable();
}
getDictionary() {
return {
en: {
'dxChat-emptyListMessage': 'Chat is Empty',
'dxChat-emptyListPrompt': 'AI Assistant is ready to answer your questions.',
'dxChat-textareaPlaceholder': 'Ask AI Assistant...',
},
};
}
initDataSource() {
this.customStore = new CustomStore({
key: 'id',
load: () => new Promise((resolve) => {
setTimeout(() => {
resolve([...this.store]);
}, 0);
}),
insert: (message) => new Promise((resolve) => {
setTimeout(() => {
this.store.push(message);
resolve(message);
});
}),
});
this.dataSource = new DataSource({
store: this.customStore,
paginate: false,
});
}
getAIResponse(messages: AIMessage[]): Promise<string> {
return this.aiService.getAIResponse(messages) as Promise<string>;
}
async processMessageSending(message: DxChatTypes.Message) {
this.messages.push({ role: 'user', content: message.text });
this.typingUsersSubject.next([this.assistant]);
try {
const aiResponse = await this.getAIResponse(this.messages);
setTimeout(() => {
this.typingUsersSubject.next([]);
this.messages.push({ role: 'assistant', content: aiResponse });
this.renderAssistantMessage(aiResponse);
}, 200);
} catch {
this.typingUsersSubject.next([]);
this.messages.pop();
this.alertLimitReached();
}
}
updateLastMessage(text = this.REGENERATION_TEXT) {
const items = this.dataSource.items();
const lastMessage = items.at(-1);
this.dataSource.store().push([{
type: 'update',
key: lastMessage.id,
data: { text },
}]);
}
renderAssistantMessage(text: string) {
const message = {
id: Date.now(),
timestamp: new Date(),
author: this.assistant,
text,
};
this.dataSource.store().push([{ type: 'insert', data: message }]);
}
alertLimitReached() {
this.setAlerts([{
message: 'Request limit reached, try again in a minute.',
}]);
setTimeout(() => {
this.setAlerts([]);
}, this.ALERT_TIMEOUT);
}
setAlerts(alerts: DxChatTypes.Alert[]) {
this.alerts = alerts;
this.alertsSubject.next(alerts);
}
async regenerate() {
try {
const aiResponse = await this.getAIResponse(this.messages.slice(0, -1));
this.updateLastMessage(aiResponse);
this.messages.at(-1).content = aiResponse;
} catch {
this.updateLastMessage(this.messages.at(-1).content);
this.alertLimitReached();
}
}
convertToHtml(value: string) {
const result = unified()
.use(remarkParse)
.use(remarkRehype)
.use(rehypeMinifyWhitespace)
.use(rehypeStringify)
.processSync(value)
.toString();
return result;
}
async onMessageEntered({ message, event }: DxChatTypes.MessageEnteredEvent) {
this.dataSource.store().push([{ type: 'insert', data: { id: Date.now(), ...message } }]);
if (!this.alerts.length) {
await this.processMessageSending(message, event);
}
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>DevExtreme Demo</title>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0" />
<link rel="stylesheet" type="text/css" href="https://cdn3.devexpress.com/jslib/26.1.5/css/dx.light.css" />
</head>
<body class="dx-viewport">
<div class="demo-container">
<demo-app>Loading...</demo-app>
</div>
<script src="https://cdn.jsdelivr.net/npm/zone.js@0.16.2/bundles/zone.umd.js"></script>
<script src="./bundle.js" type="module"></script>
</body>
</html>
import { Injectable } from '@angular/core';
import { AzureOpenAI, OpenAI } from 'openai';
import { type AIResponse } from 'devextreme-angular/common/ai-integration';
export type AIMessage = (
OpenAI.ChatCompletionUserMessageParam
| OpenAI.ChatCompletionSystemMessageParam
| OpenAI.ChatCompletionAssistantMessageParam) & {
content: string;
};
const AzureOpenAIConfig = {
dangerouslyAllowBrowser: true,
deployment: 'demo-mini',
apiVersion: '2024-02-01',
endpoint: 'https://public-api.devexpress.com/demo-openai',
apiKey: 'DEMO',
};
@Injectable()
export class AiService {
chatService: AzureOpenAI;
constructor() {
this.chatService = new AzureOpenAI(AzureOpenAIConfig);
}
async getAIResponse(messages: AIMessage[]): Promise<AIResponse> {
const params = {
messages,
model: AzureOpenAIConfig.deployment,
max_completion_tokens: 1000,
temperature: 0.7,
};
const response = await this.chatService.chat.completions.create(params);
const data = { choices: response.choices };
return data.choices[0].message?.content;
}
}