Skip to main content

Documentation Index

Fetch the complete documentation index at: https://algolia.com/llms.txt

Use this file to discover all available pages before exploring further.

This widget is and is subject to change in minor versions.
For more information, see Agent Studio.
Signature
chat({
  container: string | HTMLElement,
  // Required parameter, either one of
  agentId?: string,
  transport?: object,
  // Optional parameters (agentId only)
  feedback?: boolean,
  // Optional parameters
  getSearchPageURL?: function,
  tools?: object,
  context?: object | function,
  initialMessages?: array,
  initialUserMessage?: string,
  resume?: boolean,
  onFinish?: function,
  templates?: object,
  cssClasses?: object,
});

Import

import { chat } from 'instantsearch.js/es/widgets';

About this widget

Use the chat widget to display a chat interface that interacts with a generative AI assistant. See also: Agent Studio

Examples

JavaScript
chat({
  container: '#chat',
  agentId: '8f7c4a2d-3b1e-4d5f-9a6c-e2b1f5d0c3e9',
});

Options

container
string | HTMLElement
required
The CSS Selector or HTMLElement to insert the widget into.
chat({
  container: '#chat',
});
agentId
string
The unique identifier of the agent to connect to. You can find the agentId in the Agent Studio dashboard.
JavaScript
chat({
  // ...
  agentId: '8f7c4a2d-3b1e-4d5f-9a6c-e2b1f5d0c3e9',
});
feedback
boolean
Whether to enable feedback (thumbs up/down) on assistant messages. Only available when using agentId.
JavaScript
chat({
  // ...
  agentId: '8f7c4a2d-3b1e-4d5f-9a6c-e2b1f5d0c3e9',
  feedback: true,
});
transport
object
A custom transport object to handle the communication between the chat widget and the agent. The API endpoint must be compatible with Vercel AI SDK 5.
JavaScript
chat({
  // ...
  transport: {
    api: 'https://chatapi.example.com/api/v1/chat',
    headers: {
      'X-Session-Id': '8f7c4a2d-3b1e-4d5f-9a6c-e2b1f5d0c3e9',
      'X-Api-Version': '2025-01-01',
    },
  },
});
getSearchPageURL
function
A function to return the URL of the main search page with the nextUiState. This is used to navigate to the main search page when the user clicks on “View all” in the search tool.
JavaScript
chat({
  // ...
  getSearchPageURL: (nextUiState) => `/search?${qs.stringify(nextUiState)}`,
});
tools
object
An object that defines the client-side tools the agent can use to interact with your app. The object keys must match the tool names you defined in the Agent Studio dashboard.The widget has built-in renderers for the following tool types. Import and use the exported constants as keys to customize the default rendering:
  • SearchIndexToolType ('algolia_search_index'). Displays search results from an Algolia index in a carousel.
  • RecommendToolType ('algolia_recommend'). Displays recommendations in a carousel.
  • DisplayResultsToolType ('algolia_display_results'). Displays search results streamed directly from the agent in a carousel.
JavaScript
import {
  SearchIndexToolType,
  RecommendToolType,
  DisplayResultsToolType,
} from 'instantsearch.js/es/widgets/chat/chat';
Each tool is an object with the following properties:
  • templates. An object containing template functions for the tool.
    • layout. A tagged template function for rendering the tool call in the chat. It receives:
      • message. The tool call message. It contains input (parameters from the agent) and output (the result you provide with addToolResult). For more information on the message structure, see the Vercel AI SDK documentation.
      • indexUiState. The current InstantSearch UI state.
      • setIndexUiState. Updates the InstantSearch UI state (for example, to refine filters or update the query based on the tool call).
      • applyFilters. Applies filters to the InstantSearch UI state from the tool call.
      • addToolResult. Sends the tool’s output back to the agent. You must call this at least once before the next message. For more information, see the Vercel AI SDK documentation.
      • onClose. Dismisses the tool’s UI in the chat.
      • sendEvent. Sends click or conversion events related to the tool call. For more information, see the insights middleware documentation.
  • onToolCall. Optional handler invoked when the agent calls the tool. Receives a parameter object with:
    • input. The parameters the agent passed to the tool.
    • addToolResult. Sends the tool’s output back to the agent. For more information, see the Vercel AI SDK documentation.
    • toolCallId. The unique identifier of the tool call.
    • toolName. The name of the tool being invoked.
    • dynamic. Whether the tool is dynamically registered.
  • streamInput. Optional boolean. When true, the default loader is suppressed as the tool’s input is streamed from the agent. Use the partial input in your layout template to render the streaming state as input chunks arrive.
JavaScript
chat({
  // ...
  tools: {
    addToCart: {
      templates: {
        layout: ({ message, addToolResult }, { html }) => html`
          <div>
            <p>Add ${message.input.objectID} to the cart?</p>
            <button
              onClick=${async () => {
                // add the product to the cart
                await addProductToCart(message.input.objectID);
                // notify the agent that the tool has been used
                addToolResult({
                  output: {
                    text: `added ${message.input.objectID} to cart`,
                    done: true,
                  },
                });
              }}
            >
              Add to cart
            </button>
          </div>
        `,
      },
      onToolCall: ({ addToolResult }) => addToolResult({ output: {} }),
    },
    viewProduct: {
      templates: {
        layout: ({ message, addToolResult }, { html }) => {
          if (!message.output) {
            return html`<span>Loading product...</span>`;
          }

          return html`
            <div>
              <h2>${message.output.productName}</h2>
              <p>${message.output.brand}</p>
              <img src="${message.output.imageUrl}" />
            </div>
          `;
        },
      },
      onToolCall: async ({ input, addToolResult }) => {
        addToolResult({
          // fetch product details from your index
          output: await fetchProductDetails(input.objectID),
        });
      },
    },
  },
});
context
object | function
Extra context to send with each user message (for example, the current page or selected locale). The widget sends this context with every message, but doesn’t show it in the chat UI.context can be a static object or a function that returns an object at send time. The widget serializes the context as JSON and adds it to the user message as a hidden text part of the form <context>{"key":"value"}</context>.
The widget sends context to the agent in plain text. Don’t put secrets, access tokens, or personally identifiable information you don’t intend to share with the model in this field.
chat({
  // ...
  context: {
    locale: 'en',
    currentPage: '/products',
  },
});
initialMessages
array
Messages to pre-populate the chat with when it’s initialized. These messages are added without triggering an AI response.initialMessages only applies when the chat has no existing messages. When resume is enabled, initialMessages is ignored.
JavaScript
chat({
  // ...
  initialMessages: [
    {
      id: 'welcome',
      role: 'assistant',
      parts: [{ type: 'text', text: 'Hi! How can I help you today?' }],
    },
  ],
});
initialUserMessage
string
A message to send automatically when the chat is initialized.initialUserMessage is only sent when the chat has no existing messages. It’s sent after initialMessages are applied. When resume is enabled, this message isn’t sent.
JavaScript
chat({
  // ...
  initialUserMessage: 'Show me a few popular products to get started.',
});
resume
boolean
default:false
Whether to resume an ongoing chat generation stream when the widget mounts. Use this when restoring a chat session after a page reload to continue receiving an in-flight assistant response.
JavaScript
chat({
  // ...
  resume: true,
});
onFinish
function
A callback called when the assistant response has finished streaming, including when the stream is aborted, disconnected, or fails.The callback receives an object with:
  • message: the final assistant message.
  • messages: the full message list including the new message.
  • isAbort: true if the stream was stopped with stop().
  • isDisconnect: true if the connection was lost.
  • isError: true if the stream finished with an error.
JavaScript
chat({
  // ...
  onFinish: ({ message, isAbort, isError }) => {
    if (isError) {
      console.error('Chat stream failed', message);
      return;
    }
    if (!isAbort) {
      analytics.track('chat_message_completed', { messageId: message.id });
    }
  },
});
templates
object
The templates to use for the widget.
JavaScript
chat({
  // ...
  templates: {
    // ...
  },
});
cssClasses
object
The CSS classes you can override:
  • root. The root element of the widget.
  • container. The container element.
  • header. The header section of the widget.
    • root. The root element.
    • clear. The clear button.
    • close. The close button.
    • maximize. The maximize button.
    • title. The title element.
    • titleIcon. The title icon element.
  • messages. The messages section of the widget.
    • root. The root element.
    • content. The scrollable content.
    • scroll. The scroll container.
    • scrollToBottom. The scroll to bottom button.
    • scrollToBottomHidden. The hidden state of the scroll to bottom button.
  • message. The message in the messages section.
    • root. The root element.
    • container. The message container.
    • leading. The leading element (e.g., avatar).
    • content. The content element.
    • message. The message text element.
    • actions. The action buttons container.
    • footer. The footer element.
  • prompt. The prompt section of the widget.
    • root. The root element.
    • actions. The actions container.
    • body. The body element.
    • footer. The footer element.
    • header. The header element.
    • submit. The submit button.
    • textarea. The textarea element.
  • toggleButton. The toggle button of the widget.
    • root. The root element.
JavaScript
chat({
  // ...
  cssClasses: {
    root: 'MyCustomChat',
    container: 'MyCustomChatContainer MyCustomChatContainer--subclass',
    header: {
      root: 'MyCustomChatHeader',
      title: ['MyCustomChatHeaderTitle', 'MyCustomChatHeaderTitle--subclass'],
      // ...
    },
    // ...
  },
});

Templates

You can customize parts of a widget’s UI using the Templates API. Each template includes an html function, which you can use as a tagged template. This function safely renders templates as HTML strings and works directly in the browser—no build step required. For details, see Templating your UI.
The html function is available in InstantSearch.js version 4.46.0 or later.
layout
function
A template to customize the overall layout of the chat widget. Use instantsearch.templates.chatInlineLayout() for an inline (non-overlay) layout, or provide a custom function.
JavaScript
import instantsearch from 'instantsearch.js';

chat({
  // ...
  templates: {
    layout: instantsearch.templates.chatInlineLayout(),
  },
});
item
string | function
The template to use for each result. This template receives an object containing a single record. You can use Algolia’s highlighting feature with the highlight function, directly from the template system.
JavaScript
chat({
  // ...
  templates: {
    item(hit, { html, components }) {
      return html`
        <h2>${components.Highlight({ attribute: 'name', hit })}</h2>
        <p>${hit.description}</p>
      `;
    },
  },
});
header
object
Templates to use for the header section of the widget.
  • clearLabelText. Accessible label for the clear button.
  • closeIcon. The close icon template.
  • closeLabel. Accessible label for the close button.
  • maximizeIcon. The maximize icon template. Receives a parameter containing { maximized: boolean } for conditional rendering.
  • maximizeLabelText. Accessible label for the maximize button.
  • minimizeIcon. The minimize icon template.
  • minimizeLabelText. Accessible label for the minimize button.
  • titleIcon. The title icon template (defaults to sparkles).
  • titleText. The title text to display.
JavaScript
chat({
  // ...
  templates: {
    // ...
    header: {
      maximizeIcon({ maximized }, { html }) => html`
        <span>${maximized ? '🔽' : '🔼'}</span>
      `,
      titleIcon(_, { html }) => html`<span>✨</span>`,
      titleText: 'My AI shopping assistant',
    },
  },
})
messages
object
Templates to use for the messages section of the widget.
  • copyToClipboardLabelText. Accessible label for the copy to clipboard action.
  • error. Custom template when there is an error loading messages.
  • regenerateLabelText. Accessible label for the regenerate action.
  • scrollToBottomLabelText. Accessible label for the scroll to bottom button.
JavaScript
chat({
  // ...
  templates: {
    // ...
    messages: {
      error(_, { html }) => html`<span>Couldn't load messages.</span>`,
      // ...
    },
  },
});
loader
function
A template to customize the loader shown while waiting for an assistant response.
JavaScript
chat({
  // ...
  templates: {
    // ...
    loader(_, { html }) => html`<span>Thinking...</span>`,
  },
});
loaderText
string
Text to display in the default loader.
JavaScript
chat({
  // ...
  templates: {
    // ...
    loaderText: 'Thinking...',
  },
});
message
object
Templates to use for an individual message in the messages section of the widget.
  • messageLabelText. Accessible label for the message.
  • actionsLabelText. Accessible label for the actions container.
JavaScript
chat({
  // ...
  templates: {
    // ...
    message: {
      messageLabelText: 'Chat message',
      actionsLabelText: 'Message actions',
    },
  },
});
assistantMessage
object
Templates to use for messages that come from the chat assistant.
  • leading. The leading element (e.g., avatar).
  • footer. The footer element of the message.
JavaScript
chat({
  // ...
  templates: {
    // ...
    assistantMessage: {
      leading(_, { html }) => html`<img src="assistant-avatar.png" alt="Assistant avatar" />`,
      footer(_, { html }) => html`<span>Sent by AI Assistant</span>`,
    },
  },
});
userMessage
object
Templates to use for messages that come from the user.
  • leading. The leading element (e.g., avatar).
  • footer. The footer element of the message.
JavaScript
chat({
  // ...
  templates: {
    // ...
    userMessage: {
      leading(_, { html }) => html`<img src="user-avatar.png" alt="User avatar" />`,
      footer(_, { html }) => html`<span>Sent by You</span>`,
    },
  },
});
prompt
object
Templates to use for the prompt section of the widget.
  • disclaimerText. Disclaimer text shown in the prompt footer.
  • emptyMessageTooltipText. Tooltip for the submit button when message is empty.
  • footer. Custom footer template.
  • header. Custom header template.
  • sendMessageTooltipText. Tooltip for the send button.
  • stopResponseTooltipText. Tooltip for the stop button.
  • textareaLabelText. Accessible label for the textarea.
  • textareaPlaceholderText. Placeholder text for the textarea.
JavaScript
chat({
  // ...
  templates: {
    // ...
    prompt: {
      header(_, { html }) => html`<span>Ask me anything</span>`,
      footer(_, { html }) => html`
        <a href="https://example.com/privacy-policy">
          Privacy policy
        </a>
      `,
      // ...
    },
  },
});
suggestions
string | function
The template to use for prompt suggestions. This template receives an object containing the list of suggestions and a onSuggestionClick function to call when the suggestion is clicked.
JavaScript
chat({
  // ...
  templates: {
    // ...
    suggestions({ suggestions, onSuggestionClick }, { html }) {
      return html`
        <ul>
          ${suggestions.map(
            (suggestion) =>
              html`<li>
                <button onClick=${() => onSuggestionClick(suggestion)}>
                  ${suggestion}
                </button>
              </li>`,
          )}
        </ul>
      `;
    },
  },
});
toggleButton
object
Templates to use for the toggle button of the widget.
  • icon. Custom icon template. Receives a parameter containing { isOpen: boolean } for conditional rendering.
JavaScript
chat({
  // ...
  templates: {
    // ...
    toggleButton: {
      icon({ isOpen }, { html }) => html`<span>${isOpen ? '×' : '+'}</span>`,
    },
  },
});

HTML output

HTML
<div class="ais-Chat">
  <div class="ais-Chat-container">
    <div class="ais-ChatHeader">
      <span class="ais-ChatHeader-title">
        <span class="ais-ChatHeader-titleIcon"></span>
      </span>
      <div class="ais-ChatHeader-actions">
        <button class="ais-ChatHeader-clear"></button>
        <button class="ais-ChatHeader-maximize"></button>
        <button class="ais-ChatHeader-close" title="Close chat"></button>
      </div>
    </div>
    <div class="ais-ChatMessages">
      <div class="ais-ChatMessages-scroll ais-Scrollbar">
        <div class="ais-ChatMessages-content">...</div>
      </div>
      <button
        class="ais-ChatMessages-scrollToBottom ais-ChatMessages-scrollToBottom--hidden"
      ></button>
    </div>
    <form class="ais-ChatPrompt">
      <div class="ais-ChatPrompt-body">
        <textarea class="ais-ChatPrompt-textarea ais-Scrollbar"></textarea>
        <div class="ais-ChatPrompt-actions">
          <button class="ais-ChatPrompt-submit"></button>
        </div>
      </div>
      <div class="ais-ChatPrompt-footer">
        <div class="ais-ChatPrompt-disclaimer"></div>
      </div>
    </form>
  </div>
  <button class="ais-ChatToggleButton"></button>
</div>

Streaming and resumption

Assistant responses stream over Server-Sent Events. The chat widget exposes the streaming lifecycle through its connector render state if you want to drive a custom UI.

Status values

The render state exposes status, which can be one of:
  • 'ready'. The chat is idle and ready to accept a new message.
  • 'submitted'. A user message was submitted and the assistant hasn’t started responding yet.
  • 'streaming'. The assistant is streaming a response.
  • 'error'. The last response finished with an error. Call clearError() before sending a new message.
Each message part also carries a state of 'streaming' or 'done' while the response streams.

Stop and resume

The render state exposes two methods:
  • stop(). Aborts the current streaming response. The onFinish callback runs with isAbort: true.
  • resumeStream(). Reconnects to an in-flight stream. Call this on mount, or pass resume: true to do it automatically.
To customize the stop behavior with connectChat, read status and stop from the render options:
JavaScript
const renderChat = (renderOptions, isFirstRender) => {
  const { status, stop } = renderOptions;

  if (isFirstRender) {
    const button = document.createElement('button');
    button.textContent = 'Stop';
    button.addEventListener('click', () => stop());
    document.querySelector('#chat').appendChild(button);
  }

  document.querySelector('#chat button').hidden = status !== 'streaming';
};
To resume an ongoing stream after a reload, set resume: true on the widget, or call resumeStream() from a custom render function.
Last modified on May 7, 2026