Assistant
Hi! I am a demo assistant: my answers are written in advance and streamed token by token. Ask me anything.
Chat is an accessible conversation UI for AI assistants: answers streamed as Markdown with a stop button, a composer with attachments and suggestions, copy, regenerate, feedback and edit actions, older messages loaded on scroll, and screen reader announcements of each complete answer. It works with any model or backend.
import { Chat } from '@exhaustive-ui/core/chat';Chat has no dependency and does not call any API: it renders the messages you give it and emits send, stop and the actions of the messages, so it works with any model or backend. The answers are rendered with the Markdown component and the older messages are loaded with the InfiniteScroll directive, both part of ExhaustiveUI.
Chat displays the messages, each with a unique id, a role (user, assistant or system) and a Markdown content. When the user sends a message, send emits its text: add it to the messages with an empty assistant message whose status is streaming, then append the tokens of the answer to its content and set its status to done at the end. This demo streams a fake answer, without network.
While a message has the streaming status, or while generating is set, the send button becomes a stop button that emits stop: cancel the request there, keep the text received so far and set the status to done. The conversation is aria-busy and the answer shows a caret. Enter does not send another message until the answer is complete.
A request that fails sets the error status, with an optional error text: the answer shows the error and a Retry button that emits retry. The conversation stays at its newest message while the answer grows, only if the reader is already there: scroll up during an answer and a Jump to latest button appears instead.
suggestions are prompts shown above the composer while the conversation is empty. A suggestion is a text, or an object with a visible label and the text to send. Choosing one emits send right away. Use maxLength to limit the length of a message: a counter appears in the composer.
With allowAttachments, the composer has an attach button that opens the file picker, filtered by accept; files can also be pasted in the textarea. The files to send are listed as chips with a labelled remove button, up to maxAttachments, and send emits them with the text, each with its file. A message can then show its attachments, with a link when they have a url. draftAttachments holds the files to send, to validate or add them from the application.
Every complete message has a copy button, hidden with copyButton false: it copies the Markdown of the message, shows Copied, announces it and emits messageCopy. The last answer has a regenerate button that emits retry, hidden with retryButton false.
With feedback, the answers have thumbs up and down toggle buttons: feedbackChange emits the new value, store it in the feedback of the message. With editable, the last user message has an edit button that opens it in a textarea: Enter saves and emits edit with the new text, Escape cancels.
A long conversation can be loaded page by page. With hasMoreHistory, scrolling to the start of the conversation emits loadHistory with the oldest message shown: set loadingHistory while older messages load, prepend them, and turn hasMoreHistory off at the start of the conversation. The messages in view keep their position while older ones are inserted above them.
The list is built on the InfiniteScroll directive: screen readers hear when older messages load and when the start is reached, and Page Up and Page Down move the focus from message to message. The messages loaded this way are not announced as new answers.
The header and footer templates frame the conversation, and the empty template replaces the empty state; it receives a send function. The avatar template receives the message, its role and the name of its author, and is shown for the roles of avatars.
The message template replaces the content of the messages: it receives the message, its index, last and streaming. The composerActions template adds buttons to the toolbar of the composer, with the text being written and an insert function that inserts a text at the caret.
Chat does not talk to a model itself: wire send, stop and retry to your backend. Keep the API key of the model provider on the server: the browser calls an endpoint of your application, here /api/chat, that forwards the conversation to the model and streams the answer back, for example as plain text chunks or server-sent events.
In the browser, fetch reads the response body as a stream and each chunk is appended to the content of the streaming message. An AbortController cancels the request when the stop button is pressed, and a failed request sets the error status so that the answer offers to retry. This example is not run on this page: it needs your own endpoint.
import { Component, signal } from '@angular/core';
import { ChatMessage, ChatMessageEvent, ChatModule, ChatSendEvent } from '@exhaustive-ui/core/chat';
@Component({
selector: 'assistant-chat',
standalone: true,
imports: [ChatModule],
template: `
<p-chat
[messages]="messages()"
placeholder="Ask anything"
(send)="onSend($event)"
(stop)="controller?.abort()"
(retry)="onRetry($event)"
/>
`
})
export class AssistantChat {
messages = signal<ChatMessage[]>([]);
controller: AbortController | null = null;
onSend({ text }: ChatSendEvent) {
this.messages.update((messages) => [...messages, { id: crypto.randomUUID(), role: 'user', content: text }]);
this.ask();
}
onRetry({ message }: ChatMessageEvent) {
this.messages.update((messages) => messages.filter((item) => item.id !== message.id));
this.ask();
}
private async ask() {
const id = crypto.randomUUID();
const history = this.messages().map(({ role, content }) => ({ role, content }));
this.messages.update((messages) => [...messages, { id, role: 'assistant', content: '', status: 'streaming' }]);
this.controller = new AbortController();
try {
const response = await fetch('/api/chat', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ messages: history }),
signal: this.controller.signal
});
if (!response.ok || !response.body) {
throw new Error(`The server answered ${response.status}`);
}
const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
for (let chunk = await reader.read(); !chunk.done; chunk = await reader.read()) {
this.update(id, (message) => ({ content: message.content + chunk.value }));
}
this.update(id, () => ({ status: 'done' }));
} catch (error) {
const aborted = (error as Error).name === 'AbortError';
// stopped: keep the text received so far
this.update(id, () => (aborted ? { status: 'done' } : { status: 'error', error: 'The answer could not be generated. Retry?' }));
} finally {
this.controller = null;
}
}
private update(id: string, changes: (message: ChatMessage) => Partial<ChatMessage>) {
this.messages.update((messages) => messages.map((message) => (message.id === id ? { ...message, ...changes(message) } : message)));
}
}The endpoint can stream the text of the model as it arrives, for example with Node.js and the SDK of the provider of your choice:
// server.ts (Node.js, Express): the API key stays on the server
app.post('/api/chat', async (req, res) => {
res.setHeader('Content-Type', 'text/plain; charset=utf-8');
const stream = await provider.streamText({ messages: req.body.messages }); // the SDK of your model provider
req.on('close', () => stream.abort?.()); // the user pressed stop
for await (const text of stream) {
res.write(text);
}
res.end();
});The conversation is a scrollable group named "Conversation" that can be focused to scroll it with the keyboard; it is not a landmark, so that a page can hold several chats. Each message is an article named by its author, "You" or "Assistant" by default or the author.name of the message; the name of the user is visually hidden. Avatars are decorative and hidden from screen readers. The answers are rendered with Markdown: headings, lists, tables and code blocks keep their native semantics.
The text of an answer is not announced token by token. A visually hidden log region, polite, receives each answer once it is complete, as plain text: an answer whose status leaves streaming, or a complete answer added at the end of the conversation. The messages present at start and the older messages loaded with the history are not announced, and an answer in error is announced with its error. announceMessages turns this off. While an answer is generated, the conversation and the answer are aria-busy and a polite status announces "Generating an answer"; stopping it announces "Generation stopped".
The textarea of the composer is named "Message" and described by the character counter when maxLength is set. The send button is named "Send"; it keeps the focus and becomes "Stop generating" while an answer is generated. It is never disabled while it has the focus: when there is nothing to send it is aria-disabled. The icon buttons of the messages are named "Copy", "Regenerate", "Good response", "Bad response" and "Edit"; the thumbs are toggle buttons with aria-pressed, and a copy announces "Copied". The actions of a message are grouped and named "Message actions". The suggestions and the attachments are lists named "Suggestions" and "Attached files", and each remove button is named "Remove" followed by the file name.
Every text, announcements included, can be translated with labels.
<p-chat [messages]="messages()" [labels]="{ messages: 'Conversation avec l’assistant', input: 'Votre message', send: 'Envoyer', stop: 'Arrêter', user: 'Vous' }" />| Key | Function |
|---|---|
| enter | In the composer, sends the message. With sendOnEnter false, adds a line. |
| shift + enter | In the composer, adds a line. |
| ctrl + enter / ⌘ + enter | In the composer, sends the message, whatever sendOnEnter. |
| tab | Moves the focus through the conversation, the actions of the messages, the jump to latest button, the suggestions, the attachments and the composer. |
| page down / page up | On a message or one of its actions, moves the focus to the next or the previous message. Page Up on the first message loads older messages. |
| ctrl + home / ctrl + end | On a message, moves the focus to the element before or after the conversation. |
| arrow keys | On the focused conversation, scroll it. |
| enter / escape | In the edit textarea of a message, save or cancel the edit. Cancelling moves the focus back to the edit button. |