> ## Documentation Index
> Fetch the complete documentation index at: https://algolia.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Build an AI-powered search experience

> Combine the searchBox, chat, and autocomplete widgets to build an AI-powered search experience with InstantSearch.js.

export const customLabel_0 = "in beta"

<div className="not-prose algolia-flavor-switcher">
  <div className="afs-dropdown">
    <div className="afs-trigger" role="button" tabIndex="0" aria-haspopup="listbox">
      <span className="afs-current">JavaScript</span>

      <svg className="afs-chevron lucide lucide-chevron-down" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
        <path d="m6 9 6 6 6-6" />
      </svg>
    </div>

    <ul className="afs-menu" role="listbox">
      <li role="option" aria-selected="true"><a className="afs-option is-current" href="/doc/guides/building-search-ui/going-further/chat-customization/ai-search-experience/js"><span className="afs-option-name">JavaScript</span><span className="afs-option-lib">InstantSearch.js</span></a></li>
      <li role="option" aria-selected="false"><a className="afs-option" href="/doc/guides/building-search-ui/going-further/chat-customization/ai-search-experience/react"><span className="afs-option-name">React</span><span className="afs-option-lib">React InstantSearch</span></a></li>
    </ul>
  </div>
</div>

<Callout icon="flask-conical" color="#14b8a6">
  This widget is **{customLabel_0 || "experimental"}** and is subject to change in minor versions.
</Callout>

Pair classic InstantSearch widgets with an [Agent Studio](/doc/guides/algolia-ai/agent-studio) chat agent to give users a conversational entry point alongside their search results. This guide wires together:

* An "AI Mode" button on the search box that opens a chat panel loaded with the user's query.
* The `chat` widget itself, with hidden context to share session metadata.
* AI-generated prompt suggestions in the autocomplete drop-down menu.
* Streaming controls so you can stop or resume an in-flight response.

## Prerequisites

* An [Agent Studio agent ID](https://dashboard.algolia.com/generativeAi/agent-studio/agents).
* An `instantsearch` instance with an Algolia search client.
* `instantsearch.js` installed at a version that ships AI Mode (for example, the release from PR [`algolia/instantsearch#6982`](https://github.com/algolia/instantsearch/pull/6982) or later).

<Steps>
  <Step title="Mount the chat widget">
    Add the [`chat`](/doc/api-reference/widgets/chat/js) widget on the same `instantsearch` instance as your search UI. The other widgets in this guide rely on it being present.

    ```js JavaScript icon=code theme={"system"}
    import algoliasearch from "algoliasearch/lite";
    import instantsearch from "instantsearch.js";
    import { chat } from "instantsearch.js/es/widgets";

    const search = instantsearch({
      indexName: "instant_search",
      searchClient: algoliasearch("YourApplicationID", "YourSearchOnlyAPIKey"),
    });

    search.addWidgets([
      chat({
        container: "#chat",
        agentId: "YOUR_AGENT_ID",
      }),
    ]);

    search.start();
    ```

    The `chat` widget renders the chat panel but doesn't open it on its own. In this guide, the AI Mode button you add in the next step is the entry point. If you don't enable AI Mode, add the [`chatTrigger`](/doc/api-reference/widgets/chat-trigger/js) widget instead, or the `chat` widget logs a development warning.
  </Step>

  <Step title="Enable AI Mode on the search box">
    Set [`aiMode`](/doc/api-reference/widgets/search-box/js#param-ai-mode) on `searchBox` to render an AI Mode button next to the input. Clicking it opens the chat widget and forwards the current query. AI Mode is a valid chat entry point, so you don't also need a [`chatTrigger`](/doc/api-reference/widgets/chat-trigger/js) widget.

    ```js JavaScript icon=code theme={"system"}
    import { chat, searchBox } from "instantsearch.js/es/widgets";

    search.addWidgets([
      searchBox({
        container: "#searchbox",
        aiMode: true,
      }),
      chat({
        container: "#chat",
        agentId: "YOUR_AGENT_ID",
      }),
    ]);
    ```
  </Step>

  <Step title="Show prompt suggestions in autocomplete (optional)">
    If you use [`EXPERIMENTAL_autocomplete`](/doc/api-reference/widgets/autocomplete/js), surface AI-generated prompt suggestions alongside hits. See [`showPromptSuggestions`](/doc/api-reference/widgets/autocomplete/js#param-show-prompt-suggestions) for the full configuration surface.

    ```js JavaScript icon=code theme={"system"}
    import { EXPERIMENTAL_autocomplete } from "instantsearch.js/es/widgets";

    search.addWidgets([
      EXPERIMENTAL_autocomplete({
        container: "#autocomplete",
        showPromptSuggestions: {
          indexName: "prompt_suggestions",
        },
        indices: [
          {
            indexName: "instant_search",
            templates: {
              item: ({ item }, { html }) => html`<div>${item.name}</div>`,
            },
          },
        ],
      }),
    ]);
    ```

    Selecting a prompt suggestion opens the chat widget on the same index and sends the suggestion as the first message.
  </Step>

  <Step title="Pass session metadata with hidden context">
    Use the [`context`](/doc/api-reference/widgets/chat/js#param-context) option to share metadata with the agent on every message. The widget serializes the value as JSON and adds it to the user message as a hidden text part. Users don't see it in the chat UI, but the agent does.

    <Warning>
      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.
    </Warning>

    <CodeGroup>
      ```js Static object theme={"system"}
      chat({
        container: "#chat",
        agentId: "YOUR_AGENT_ID",
        context: { locale: "en", segment: "logged-in" },
      });
      ```

      ```js Function theme={"system"}
      chat({
        container: "#chat",
        agentId: "YOUR_AGENT_ID",
        context: () => ({
          locale: navigator.language,
          currentPage: window.location.pathname,
        }),
      });
      ```
    </CodeGroup>
  </Step>

  <Step title="Handle the streaming lifecycle">
    Listen for response completion with [`onFinish`](/doc/api-reference/widgets/chat/js#param-on-finish), and use the [`connectChat`](/doc/api-reference/widgets/chat/js#streaming-and-resumption) connector if you need a custom Stop button or to call `resumeStream()` manually. See [Streaming and resumption](/doc/api-reference/widgets/chat/js#streaming-and-resumption) on the chat widget reference for the full status surface.

    ```js JavaScript icon=code theme={"system"}
    search.addWidgets([
      chat({
        container: "#chat",
        agentId: "YOUR_AGENT_ID",
        resume: true,
        onFinish: ({ message, isError }) => {
          if (!isError) {
            analytics.track("chat_message_completed", { id: message.id });
          }
        },
      }),
    ]);
    ```

    Set [`resume: true`](/doc/api-reference/widgets/chat/js#param-resume) to reconnect to an in-flight assistant response after a page reload.
  </Step>
</Steps>

## End-to-end example

```js JavaScript icon=code expandable theme={"system"}
import algoliasearch from "algoliasearch/lite";
import instantsearch from "instantsearch.js";
import {
  EXPERIMENTAL_autocomplete,
  chat,
  hits,
  searchBox,
} from "instantsearch.js/es/widgets";

const search = instantsearch({
  indexName: "instant_search",
  searchClient: algoliasearch("YourApplicationID", "YourSearchOnlyAPIKey"),
});

search.addWidgets([
  searchBox({
    container: "#searchbox",
    aiMode: true,
  }),
  EXPERIMENTAL_autocomplete({
    container: "#autocomplete",
    showPromptSuggestions: { indexName: "prompt_suggestions" },
    indices: [
      {
        indexName: "instant_search",
        templates: {
          item: ({ item }, { html }) => html`<div>${item.name}</div>`,
        },
      },
    ],
  }),
  hits({
    container: "#hits",
    templates: {
      item: (hit, { html }) => html`<article>${hit.name}</article>`,
    },
  }),
  chat({
    container: "#chat",
    agentId: "YOUR_AGENT_ID",
    resume: true,
    context: () => ({
      locale: navigator.language,
      currentPage: window.location.pathname,
    }),
    onFinish: ({ message, isError }) => {
      if (!isError) {
        analytics.track("chat_message_completed", { id: message.id });
      }
    },
  }),
]);

search.start();
```

## Related

* [searchBox widget reference](/doc/api-reference/widgets/search-box/js)
* [chat widget reference](/doc/api-reference/widgets/chat/js)
* [autocomplete widget reference](/doc/api-reference/widgets/autocomplete/js)
* [Agent Studio](/doc/guides/algolia-ai/agent-studio)
