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
  // Required prop, either one of
  agentId={string}
  transport={object}
  // Optional props (agentId only)
  feedback={boolean}
  // Optional props
  getSearchPageURL={function}
  tools={object}
  context={object | function}
  initialMessages={array}
  initialUserMessage={string}
  resume={boolean}
  onFinish={function}
  classNames={object}
  translations={object}
  layoutComponent={function}
  // Optional component props
  itemComponent={function}
  headerCloseIconComponent={function}
  headerMaximizeIconComponent={function}
  headerMinimizeIconComponent={function}
  headerTitleIconComponent={function}
  messagesErrorComponent={function}
  loaderComponent={function}
  promptFooterComponent={function}
  promptHeaderComponent={function}
  toggleButtonIconComponent={function}
  suggestionsComponent={function}

  ...props={ComponentProps<'div'>}
/>

Import

JavaScript
import { Chat } from "react-instantsearch";

About this widget

<Chat> is a widget to display a chat interface that interacts with a generative AI assistant. See also: Agent Studio

Examples

JavaScript
import React from "react";
import { liteClient as algoliasearch } from "algoliasearch/lite";
import { InstantSearch, Chat } from "react-instantsearch";

const searchClient = algoliasearch("YourApplicationID", "YourSearchOnlyAPIKey");

function App() {
  return (
    <InstantSearch indexName="instant_search" searchClient={searchClient}>
      <Chat agentId="8f7c4a2d-3b1e-4d5f-9a6c-e2b1f5d0c3e9" />
    </InstantSearch>
  );
}

Props

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
HttpChatTransportInitOptions
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.
<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
(nextUiState: object) => string
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) => {
    return `/search?${qs.stringify(nextUiState)}`;
  }}
/>
tools
Record<string, Tool>
An object defining the client-side tools that the agent can use to interact with your application. The object’s keys are tool names that must match the tools 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 'react-instantsearch';
Each tool is an object with the following properties:
  • layoutComponent. A React component that renders the tool call in the chat. Receives the following props:
    • 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. 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.
<Chat tools={{
  addToCart: {
    layoutComponent: ({ message, addToolResult }) => <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: {
    layoutComponent: ({ message }) => {
      if (!message.output) {
        return <span>Loading product...</span>;
      }

      return <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
Record<string, unknown> | () => Record<string, unknown>
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
  agentId="YOUR_AGENT_ID"
  context={{ locale: "en", currentPage: "/products" }}
/>
initialMessages
UIMessage[]
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
  agentId="YOUR_AGENT_ID"
  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
  agentId="YOUR_AGENT_ID"
  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 agentId="YOUR_AGENT_ID" resume />
onFinish
(options: { message, messages, isAbort, isDisconnect, isError }) => void
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
  agentId="YOUR_AGENT_ID"
  onFinish={({ message, isAbort, isError }) => {
    if (isError) {
      console.error("Chat stream failed", message);
      return;
    }
    if (!isAbort) {
      analytics.track("chat_message_completed", { messageId: message.id });
    }
  }}
/>
layoutComponent
(props: ChatLayoutOwnProps) => JSX.Element
A component to customize the overall layout of the chat widget. Use ChatInlineLayout for an inline (non-overlay) layout, or ChatOverlayLayout for the default floating overlay. To display a custom welcome screen before the first message, see Show starter prompts on the chat welcome screen.
JavaScript
import { Chat, ChatInlineLayout } from "react-instantsearch";

<Chat
  agentId="8f7c4a2d-3b1e-4d5f-9a6c-e2b1f5d0c3e9"
  layoutComponent={ChatInlineLayout}
/>
loaderComponent
(props) => JSX.Element
A component to customize the loader shown while waiting for an AI response. Import the built-in ChatMessageLoader component from react-instantsearch to render the default loader, or provide your own component.
JavaScript
import { Chat, ChatMessageLoader } from "react-instantsearch";

<Chat
  agentId="8f7c4a2d-3b1e-4d5f-9a6c-e2b1f5d0c3e9"
  loaderComponent={(props) => (
    <ChatMessageLoader
      {...props}
      translations={{ loaderText: "Thinking..." }}
    />
  )}
/>
To replace the loading state, see Customize the chat loading message.
components props
() => JSX.Element
Components to customize the rendering of the widget.
  • itemComponent. Custom component for each result. Receives an object containing a single record.
  • headerCloseIconComponent. Header: close icon component.
  • headerMaximizeIconComponent. Header: maximize icon component. Receives a prop containing { maximized: boolean } for conditional rendering.
  • headerMinimizeIconComponent. Header: minimize icon component.
  • headerTitleIconComponent. Header: title icon component (defaults to sparkles).
  • messagesErrorComponent. Messages: custom error component.
  • assistantMessageLeadingComponent. Assistant message: custom leading component (e.g. avatar).
  • assistantMessageFooterComponent. Assistant message: custom footer component.
  • userMessageLeadingComponent. User message: custom leading component (e.g. avatar).
  • userMessageFooterComponent. User message: custom footer component.
  • promptFooterComponent. Prompt: custom footer component.
  • promptHeaderComponent. Prompt: custom header component.
  • toggleButtonIconComponent. Toggle button: custom icon component. Receives a prop containing { isOpen: boolean } for conditional rendering.
  • suggestionsComponent. Custom component to render prompt suggestions. Receives a prop containing { suggestions: string[], onSuggestionClick: (str: string) => void }.
To add a disclaimer or policy notice, see Add a legal notice to the chat widget.
JavaScript
<Chat
  // ...
  headerTitleIconComponent={() => <span></span>}
  headerMaximizeIconComponent={({ maximized }) => (
    <span>{maximized ? "🔽" : "🔼"}</span>
  )}
  promptFooterComponent={() => (
    <a href="https://example.com/privacy-policy">Privacy policy</a>
  )}
/>
classNames
Partial<ChatClassNames>
The CSS classes you can override and pass to the widget’s elements. It’s useful to style widgets with class-based CSS frameworks like Bootstrap or Tailwind CSS.
  • 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
  classNames={{
    root: "MyCustomChat",
    container: "MyCustomChatContainer MyCustomChatContainer--subclass",
    header: {
      root: "MyCustomChatHeader",
      title: ["MyCustomChatHeaderTitle", "MyCustomChatHeaderTitle--subclass"],
      // ...
    },
    // ...
  }}
/>
translations
Partial<ChatTranslations>
A dictionary of translations to customize the UI text and support internationalization.
  • header. The header section of the widget.
    • clearLabel. Accessible label for the clear button.
    • closeLabel. Accessible label for the close button.
    • maximizeLabel. Accessible label for the maximize button.
    • minimizeLabel. Accessible label for the minimize button.
    • title. Title to display.
  • messages. The messages section of the widget.
    • copyToClipboardLabel. Accessible label for the copy to clipboard action.
    • feedbackThankYouText. Text shown after feedback is submitted (default: 'Thanks for your feedback!').
    • loaderText. Text to display in the loader.
    • regenerateLabel. Accessible label for the regenerate action.
    • scrollToBottomLabel. Accessible label for the scroll to bottom button.
    • sendingFeedbackLabel. Accessible label for the feedback spinner (default: 'Sending feedback...').
    • thumbsDownLabel. Accessible label for the thumbs down button (default: 'Dislike').
    • thumbsUpLabel. Accessible label for the thumbs up button (default: 'Like').
  • message. Individual message in the messages section.
    • messageLabel. Accessible label for the message.
    • actionsLabel. Accessible label for the actions container.
  • prompt. The prompt section of the widget.
    • disclaimer. Disclaimer text shown in the prompt footer.
    • emptyMessageTooltip. Tooltip for the submit button when message is empty.
    • sendMessageTooltip. Tooltip for the send button.
    • stopResponseTooltip. Tooltip for the stop button.
    • textareaLabel. Accessible label for the textarea.
    • textareaPlaceholder. Placeholder text for the textarea.
To add richer prompt or message notices, see Add a legal notice to the chat widget.
JavaScript
<Chat
  translations={{
    header: {
      title: "My AI shopping assistant",
      closeLabel: "Close chat",
      // ...
    },
    // ...
  }}
/>
...props
React.ComponentProps<'div'>
Any <div> prop to forward to the root element of the widget.
JavaScript
<Chat className="MyCustomChat" title="My custom title" />

Streaming and resumption

Assistant responses stream over Server-Sent Events. The useChat hook exposes the streaming lifecycle if you want to drive a custom UI.

Status values

useChat returns a status value, 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

useChat also returns:
  • 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 to <Chat> to do it automatically.
JavaScript
import { useChat } from "react-instantsearch";

function StopButton() {
  const { status, stop } = useChat({ agentId: "YOUR_AGENT_ID" });

  if (status !== "streaming") {
    return null;
  }

  return <button onClick={() => stop()}>Stop</button>;
}
To resume an ongoing stream after a reload, set resume on <Chat>, or call resumeStream() from a custom component.
Last modified on May 7, 2026