v22.18.0 release notes

InlineAIAssist

InlineAIAssist rewrites the selected text of a field with AI: improve, fix, shorten, change the tone or follow your own instructions, with the answer streamed into a preview to replace, retry or discard. It works with any model through a small adapter to your own backend, and the replacement is undone with Ctrl+Z.

View as .md
import { InlineAIAssist, InlineAIAssistField } from '@exhaustive-ui/core/inlineaiassist';
import { provideAIAssist } from '@exhaustive-ui/core/aiassist';

The same entry point exports the InlineAIAssistField directive, pInlineAIAssist. The adapter contract, shared with SmartPasteButton and SmartTextarea, comes from @exhaustive-ui/core/aiassist: provideAIAssist, the AI_ASSIST_ADAPTER token, runAIAssist and fakeAIAssistAdapter for demos and tests.

Give the field to for. Select some text, or none to work on the whole field, then press the button, the small button that appears next to a selection, or Ctrl+J (⌘J on a Mac) in the field. Pick an action or type your own instructions: the answer streams into a preview, to Replace the text, Try again or Discard. The replacement is an edit of the field, undone with Ctrl+Z.

The demos of this page answer offline with fakeAIAssistAdapter and canned rewrites; the Adapter section plugs a real model.

The pInlineAIAssist directive adds an assistant to an input, a textarea, a contenteditable element or a component that holds one, such as an Editor, with the adapter given to provideAIAssist. It has no button: the shortcut and the small button next to a selection open it. To configure it, give it an InlineAIAssist: [pInlineAIAssist]="assist".

Notes

We need to finish teh wrok on the dashboard before the demo.

InlineAIAssist sends no request of its own and needs no SDK: an adapter connects it to the model of your choice. Its complete function receives a typed request, with the task (inline here), the selected text, ready-made instructions, a context (the action, the free prompt, the text around the selection) and an AbortSignal. It returns the new text, a promise of it, or a stream of chunks: an Observable or an AsyncIterable of strings, appended to the preview as they arrive.

Give the adapter to one component with adapter, or to all of them with provideAIAssist, in the providers of the application or of a component. The same adapter serves InlineAIAssist, SmartPasteButton and SmartTextarea: switch on request.task if your backend needs to.

Never put the API key of a model provider in the browser. Call an endpoint of your own application, here /api/ai, that holds the key and streams the answer back. The signal cancels the request when the user stops, retries, discards or closes the assistant.

// app.config.ts
import { provideAIAssist } from '@exhaustive-ui/core/aiassist';

export const appConfig: ApplicationConfig = {
    providers: [
        provideAIAssist({
            complete: async function* ({ task, text, instructions, context, signal }) {
                const response = await fetch('/api/ai', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ task, text, instructions, context }),
                    signal
                });
                if (!response.ok || !response.body) {
                    throw new Error(`The server answered ${response.status}`);
                }
                // each chunk of the body is appended to the preview
                const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
                for (let chunk = await reader.read(); !chunk.done; chunk = await reader.read()) {
                    yield chunk.value;
                }
            }
        })
    ]
};

The endpoint sends the instructions and the text to the model and streams its text back, here with plain fetch calls to an OpenAI-compatible chat completions API; adapt it to your provider.

// server.ts (Node.js 20+, Express): the API key stays on the server
app.post('/api/ai', async (req, res) => {
    const { task, text, instructions } = req.body;
    const controller = new AbortController();
    req.on('close', () => controller.abort()); // the user stopped or closed the assistant

    const upstream = await fetch(process.env.MODEL_URL + '/chat/completions', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${process.env.MODEL_API_KEY}` },
        body: JSON.stringify({
            model: process.env.MODEL_NAME,
            stream: task !== 'smart-paste',
            messages: [
                { role: 'system', content: instructions },
                { role: 'user', content: text }
            ]
        }),
        signal: controller.signal
    });

    res.setHeader('Content-Type', 'text/plain; charset=utf-8');
    if (task === 'smart-paste') {
        const answer = await upstream.json();
        return res.end(answer.choices[0].message.content); // a JSON object as text
    }
    // turn the server-sent events of the provider into plain text chunks
    const decoder = new TextDecoder();
    let buffer = '';
    for await (const bytes of upstream.body) {
        buffer += decoder.decode(bytes, { stream: true });
        const lines = buffer.split('\n');
        buffer = lines.pop() ?? '';
        for (const line of lines) {
            const data = line.startsWith('data: ') ? line.slice(6) : '';
            if (data && data !== '[DONE]') {
                res.write(JSON.parse(data).choices[0]?.delta?.content ?? '');
            }
        }
    }
    res.end();
});

In tests and offline demos, fakeAIAssistAdapter answers with canned texts streamed word by word, or throws to simulate an error.

import { fakeAIAssistAdapter } from '@exhaustive-ui/core/aiassist';

const adapter = fakeAIAssistAdapter({
    latency: 300, // before the first chunk
    chunkDelay: 40, // between two words
    respond: (request) => (request.task === 'inline' ? request.text.toUpperCase() : '')
});

actions lists the actions, in order: the identifiers of the built-in ones, improve, fix, shorten, expand, simplify, professional and friendly, and your own actions with an id, a label, the instructions sent to the model and optional search keywords. freePrompt allows typed instructions, shortcut changes the keyboard shortcut (Mod is Ctrl, or ⌘ on Apple devices; null disables it), iconOnly, variant and size style the button, and labels translates the texts.

Or press Alt+Shift+A in the field.
provideExhaustive({
    translation: {
        aria: {
            aiAssist: 'Demander à l’IA',
            aiAssistant: 'Assistant IA',
            aiPrompt: 'Demander à l’IA de modifier ou d’écrire'
        }
    }
});

Screen Reader

The button is a native button named by its text, "Ask AI", which becomes its aria-label with iconOnly; aria-expanded and aria-controls tell that it opens the assistant. The field gets an aria-keyshortcuts attribute with the shortcut, so that screen readers can announce it. The small button shown next to a selection is a pointer shortcut only: it is hidden from assistive technologies and out of the tab order, and the keyboard shortcut does the same.

The assistant is a non-modal dialog named "AI assistant". Its prompt is a combobox that controls a listbox of actions: the active action is given by aria-activedescendant, so the focus stays in the prompt while the arrows move through the list, and typing filters it. While the answer is written, the result region is aria-busy and the focus is on the stop button; once it is ready, the focus moves to the replace button, which is described by the preview, and a polite live region announces "Suggestion ready". The replacement, the discard and the stop are announced the same way, without moving the focus.

Closing the assistant gives the focus back to the field with the same selection, and after a replacement the new text is selected. The replacement is a native edit of the field, so Ctrl+Z undoes it. The texts are translated with labels, and the aiAssist, aiAssistant and aiPrompt keys of the aria translation.

Field Keyboard Support

KeyFunction
ctrl + j (⌘ + j on Apple devices)Opens the assistant on the selection, or on the whole field when nothing is selected. The shortcut property changes it.
ctrl + zUndoes a replacement.

Assistant Keyboard Support

KeyFunction
down arrow / up arrowMoves to the next or previous action of the list, wrapping around.
page down / page upMoves to the last or first action.
enterRuns the active action, or the typed instructions.
tabMoves through the prompt, the preview and the buttons of the result.
escapeStops the request, closes the assistant without changing the text and gives the focus back to the field.