Skip to main content
Version: v2.x

AI Chat Component

The AiChat component is the main UI component of the NLUX AI assistant. It is responsible for rendering the user and the AI messages, the prompt composer, error message, and the markdown received from the AI.

The JSX component for rendering the chat UI is:
<AiChat />

Installation

npm install @nlux/react

Usage

import {AiChat} from '@nlux/react';
import {useChatAdapter} from '@nlux/[Your Adapter Of Choice]';

export default App = () => {
const adapter = useChatAdapter({
// The adapter config depends on the adapter you use
url: 'https://<Your Adapter Endpoint Url>',
});

// The adapter is the only required prop
// Other props available to customize the chat but are optional
return <AiChat adapter={adapter} />;
};

Configuration

The React JS config options are provided as props to the <AiChat /> JSX component.


AI Response Type

By default, NLUX expects a string message to be received as response from the AI system.
However, for advanced use cases where an object is expected, a generic type can be provided to the AiChat component.

Default
(Without Generic Type)
Advanced
(With Generic Type)
JSX Syntax<AiChat ... /><AiChat<AiResponseType> ... />
where AiResponseType is a custom type defined by the user
AI Reponse ExpectedstringObject matching the AiResponseType type
Use CaseWhen the LLM only generates plain text or markdownFor AI systems that generate an object or a stream of objects
RenderingThe string response will be parsed as markdownFor standard adapters provided by NLUX, the library handles converting objects to markdown, or offers adapter config for that purpose. For custom adapters, custom renderers is required.

For most of the use cases, the default behavior is sufficient.
The advanced use case is for custom components with complex AI responses.
Visit the custom renders section to learn more about rendering custom AI responses.


Adapter

The adapter is a required property.
It's responsible for connecting NLUX to the AI backend of your choice.

The value can be:

  • A StandardChatAdapter — one of NLUX's standard adapters, imported from @nlux/[adapter]-react packages.
  • An AdapterBuilder — the result of calling an adaptor creator function like createChatAdapter().
  • A custom adapter — that implements the ChatAdapter interface.
  • Required
  • Type: ChatAdapter | StandardChatAdapter | ChatAdapterBuilder
  • Usage:
import {AiChat, ChatAdapter} from '@nlux/react';
import {useChatAdapter} from '@nlux/[Your Preferred Standard Adapter]-react';

// Usage with standard adapters
const standardAdapter = useChatAdapter();
<AiChat adapter={standardAdapter} />
// Usage with custom adapters
const customAdapter: ChatAdapter<AiMsg> = {
// Implement the required methods
};
<AiChat adapter={customAdapter} />

Class Name

The className is an optional property.
It can be used to provide a CSS class name to the AiChat component to apply custom styles.
The new CSS class will be added to the root element of the AiChat component.

  • Type: string
  • Usage:
import {AiChat} from '@nlux/react';

<AiChat className="my-class" />

Chat Personas

The personaOptions configuration object allows you to give the conversation participants a name and an avatar. And for the case of the assistant, you can also specify a tagline that will be displayed below the assistant's name in the initial screen.

  • Type: PersonaOptions
interface PersonaOptions {
assistant?: AssistantPersona,
user?: UserPersona,
}

interface AssistantPersona {
name: string;
avatar: string | JSX.Element;
tagline?: string;
}

interface UserPersona {
name: string;
avatar: string | JSX.Element;
}
  • Usage:
import {AiChat, AssistantPersona, UserPersona, PersonaOptions} from '@nlux/react';

const assistantPersona: AssistantPersona = {
name: 'HarryBotter',
avatar: 'https://docs.nlkit.com/nlux/images/personas/harry-botter.png',
tagline: 'Mischievously Making Magic With Mirthful AI!',
};

const userPersona: UserPersona = {
name: 'Marissa',
avatar: <span>👩</span>
};

const personaOptions: PersonaOptions = {
assistant: assistantPersona,
user: userPersona
};

<AiChat personaOptions={personaOptions} />

Initial Conversation

The initialConversation(chatItems) property is used to enable loading of conversation history before rendering the AiChat component. This is useful if you want the user to resume a conversation from a previous session.

  • Type: initialConversation: ChatItem[]
type ChatItem<AiMsg = string> = {
role: ParticipantRole;
message: AiMsg;
};

type ParticipantRole = 'user' | 'system' | 'assistant';
  • Usage:
import {AiChat, ChatItem} from '@nlux/react';

const initialConversation: ChatItem[] = [
{
role: 'user',
message: 'I need help with my order'
},
{
role: 'assistant',
message: 'Sure! What is your order number?'
}
];
<AiChat initialConversation={initialConversation} />
  • Reactivity: This property is not reactive. When it changes after the component is mounted, it will be ignored.

Conversation Options

The conversationOptions property is used to configure the conversation's behavior. If provided, it should be an object with properties from the table listed below.

  • Type: ConversationOptions
type ConversationOptions = {
layout?: ConversationLayout;
autoScroll?: boolean;
historyPayloadSize?: HistoryPayloadSize;
showWelcomeMessage?: boolean;
};

type HistoryPayloadSize = number | 'max';

type ConversationLayout = 'bubbles' | 'list';
PropertyTypeDefaultDescription
layout'bubbles' | 'list''list'The layout of the messages when displayed in the conversation. Use bubbles for a chat app layout and list for simple layout with messages stacked on top of each other.
autoScrollbooleantrueIf true, the conversation will scroll to the bottom when a new message is being added.
historyPayloadSizenumber | 'max''max'The number of messages from the conversation history to be sent to the backend whenver a message is submitted. If set to 0, no messages will be sent to the server. If set to 'max', all the conversation messages will be sent to the server everytime time a prompt is submitted.
showWelcomeMessagebooleantrueIf true, the assistant's logo and tagline will be displayed when the conversation starts. The NLUX will be shown is no assistant persona is provided. Set to false to hide the welcome message.
conversationStartersConversationStarter[][]An array of conversation starters to be displayed to initiate the conversation.
  • Usage:
import {AiChat, ConversationOptions} from '@nlux/react';

const conversationOptions: ConversationOptions = {
layout: 'bubbles',
autoScroll: false,
historyPayloadSize: 10
};
<AiChat conversationOptions={conversationOptions} />

Message Options

The messageOptions property is used to configure what goes into the messages in the conversation, which could be prompts from the user or responses from the AI. The options object should have properties from the table listed below.

  • Type: MessageOptions
type MessageOptions<AiMsg = string> = {
responseRenderer?: ResponseRenderer<AiMsg>;
promptRenderer?: PromptRenderer;
editableUserMessages?: boolean;
syntaxHighlighter?: HighlighterExtension;
htmlSanitizer?: SanitizerExtension;
markdownLinkTarget?: 'blank' | 'self';
showCodeBlockCopyButton?: boolean;
skipStreamingAnimation?: boolean;
streamingAnimationSpeed?: number;
waitTimeBeforeStreamCompletion?: number | 'never';
};

// Refer to custom renderers API documentation for more information
type ResponseRenderer<AiMsg> = (
FC<StreamResponseComponentProps<AiMsg>> | // React component to render a streamed AI response
FC<BatchResponseComponentProps<AiMsg>> // React component to render a response in batch mode
);
type PromptRenderer = FC<PromptRendererProps>;
PropertyTypeDefaultDescription
responseRendererResponseRenderer<AiMsg>-A custom renderer for AI responses. API documentation for custom renderers can be found here.
promptRendererPromptRenderer-A custom renderer for user prompts. API documentation for custom renderers can be found here.
editableUserMessagesbooleanfalseIf true, user messages can be edited and re-submitted.
syntaxHighlighterHighlighterExtension-A custom syntax highlighter for code blocks within messages.
htmlSanitizerSanitizerExtension-A custom HTML sanitizer for HTML and parsed markdown. It does not apply to preformatted code blocks. Use a syntax highlighter for code blocks.
markdownLinkTarget'blank' | 'self''blank'The target attribute for markdown links. Use self to open links in the same tab and blank to open links in a new tab.
showCodeBlockCopyButtonbooleantrueIf true, a copy button will be displayed on code blocks created withing messages.
streamingAnimationSpeednumber10The interval in milliseconds between streamed AI responses.
skipStreamingAnimationbooleanfalseIf true, streamed AI responses will be displayed instantly without any animation.
waitTimeBeforeStreamCompletionnumber|'never'2000Sets the wait time in milliseconds after the last data chunk; 'never' requires manual completion.
  • Usage:
import {AiChat, MessageOptions} from '@nlux/react';
import {highlighter} from '@nlux/highlighter';

const messageOptions: MessageOptions = {
// Markdown parsing options
markdownLinkTarget: 'self',
showCodeBlockCopyButton: false,
skipStreamingAnimation: true,
streamingAnimationSpeed: 100,
waitTimeBeforeStreamCompletion: 5000,

// Renfer to Custom Renderers API doc for futher details and usage examples
responseRenderer: ({content}) => <p>The AI said: {content}</p>,
promptRenderer: ({content}) => <p>The user said: {content}</p>,

// Refer to sytax Syntax Highlighter API doc for details
syntaxHighlighter: highlighter,
};
<AiChat conversationOptions={messageOptions} />

Display Options

The displayOptions property is used to configure the display, theme, and layout of the component. If provided, it should be an object properties from the table listed below.

  • Type: DisplayOptions
type DisplayOptions = {
themeId?: string;
colorScheme?: 'light' | 'dark' | 'auto';
width?: number | string;
height?: number | string;
};
PropertyTypeDefaultDescription
themeId'nova' | 'luna' | string'nova'The theme ID of the component. If you're using a standard NLUX theme, you should also import the theme CSS file.
colorScheme'light' | 'dark' | 'auto''auto'The color scheme of the component.
Set to 'auto' to use the system color scheme.
widthnumber | string'100%'The CSS width of the component.
By default, the width is set to '100%' of the parent container.
heightnumber | string'100%'The CSS height of the component.
By default, the height is set to '100%' of the parent container.
  • Usage:
import {AiChat, DisplayOptions} from '@nlux/react';
import '@themes/luna.css'; // Or any other theme

const displayOptions: DisplayOptions = {
themeId: 'luna',
colorScheme: 'dark',
width: 920,
height: 400
};
<AiChat displayOptions={displayOptions} />

Composer Options

The composerOptions property is responsible for configuring the prompt input area and submit button. If provided, it should be an object properties from the table listed below.

  • Type: ComposerOptions
type ComposerOptions = {
placeholder?: string;
autoFocus?: boolean;
disableSubmitButton?: boolean;
submitShortcut?: 'Enter' | 'CommandEnter';
}
PropertyTypeDefaultDescription
placeholderstring-The placeholder message to be displayed in the prompt input field when empty.
autoFocusbooleanfalseIf true, the composer input will be focused when AiChat is mounted.
disableSubmitButtonbooleanfalseThis will override the disabled state of the submit button when the composer is in typing status. It will not have any impact in the composer submitting and waiting statuses, as the submit button is always disabled in these statuses.
submitShortcut'Enter' | 'CommandEnter''Enter'The keyboard shortcut to submit the prompt message.
Enter: The user can submit the prompt message by pressing the Enter key. In order to add a new line, the user can press Shift + Enter.
CommandEnter: When this is used, the user can submit the prompt message by pressing Ctrl + Enter on Windows/Linux or Cmd + Enter on macOS. In order to add a new line, the user can press Enter.
hideStopButtonbooleanfalseIf true, the stop button will not be shown when a prompt is in progress, and the loading spinner will be shown instead.
  • Usage:
import {AiChat, ComposerOptions} from '@nlux/react';

const composerOptions: ComposerOptions = {
autoFocus: true,
disableSubmitButton: false,
placeholder: 'Type your message here',
submitShortcut: 'CommandEnter'
};
<AiChat composerOptions={composerOptions} />

Syntax Highlighter

The syntax highlighter is an optional extension that can be used to highlight the source code blocks that are generated by the LLM. When no syntax highlighter is provided, the source code blocks will be rendered as plain text, with mono-spaced font, and minimum styling.

If you expect your AI assistant to be used to generate source code examples, you should consider using a syntax highlighter.

NLUX provides a syntax highlighter that uses Highlight.js.
You can use it by installing @nlux/highlighter and passing it to the syntaxHighlighter prop as shown below.

You can also use your own syntax highlighter by implementing the HighlighterExtension interface.

  • Type: HighlighterExtension
  • Usage:
import {AiChat} from '@nlux/react';
import {highlighter} from '@nlux/highlighter';
<AiChat messageOptions={{syntaxHighlighter: highlighter}} />