Skip to main content
Ask AI transforms DocSearch into an intelligent documentation assistant. Instead of just searching for keywords, users can ask questions in natural language and receive contextual answers with citations.

Overview

Ask AI uses large language models to:
  • Understand natural language questions
  • Search your documentation index
  • Generate accurate, contextual answers
  • Cite sources with links to your docs
  • Support follow-up questions in context
Ask AI requires an assistant ID from Algolia and is available on compatible plans.

Enabling Ask AI

1

Get an Assistant ID

Contact Algolia or configure an assistant in your dashboard to get your assistant ID.
2

Add to DocSearch Config

Pass the assistant ID to enable Ask AI features.
3

Configure Search Parameters

Optionally customize which content the AI searches.

React Integration

import { DocSearch } from '@docsearch/react';
import '@docsearch/css';

function App() {
  return (
    <DocSearch
      appId="YOUR_APP_ID"
      apiKey="YOUR_SEARCH_API_KEY"
      indexName="YOUR_INDEX_NAME"
      askAi={{
        assistantId: "YOUR_ASSISTANT_ID",
      }}
    />
  );
}

JavaScript Integration

import docsearch from '@docsearch/js';
import '@docsearch/css';

docsearch({
  container: '#docsearch',
  appId: 'YOUR_APP_ID',
  apiKey: 'YOUR_SEARCH_API_KEY',
  indexName: 'YOUR_INDEX_NAME',
  askAi: {
    assistantId: 'YOUR_ASSISTANT_ID',
  },
});

Configuration Options

Customize Ask AI behavior with additional options:
<DocSearch
  appId="YOUR_APP_ID"
  apiKey="YOUR_SEARCH_API_KEY"
  indexName="YOUR_INDEX_NAME"
  askAi={{
    assistantId: "YOUR_ASSISTANT_ID",
    // Search a different index for AI responses
    indexName: "docs_ai_optimized",
    // Use separate API credentials
    apiKey: "YOUR_AI_SEARCH_KEY",
    appId: "YOUR_AI_APP_ID",
    // Filter search results for AI
    searchParameters: {
      facetFilters: ['version:v4', 'language:en'],
      distinct: true,
      attributesToRetrieve: ['hierarchy', 'content', 'url'],
    },
    // Show suggested questions
    suggestedQuestions: true,
  }}
/>
PropertyTypeDescription
assistantIdstringYour Algolia assistant ID (required)
indexNamestringIndex to search for AI responses (defaults to main index)
apiKeystringAPI key for AI searches (defaults to main API key)
appIdstringApp ID for AI searches (defaults to main app ID)
searchParametersobjectAlgolia search parameters for AI queries
suggestedQuestionsbooleanShow suggested questions on empty state

Search Parameters

Control what content the AI can search:
<DocSearch
  askAi={{
    assistantId: "YOUR_ASSISTANT_ID",
    searchParameters: {
      // Only search latest version docs
      facetFilters: ['version:latest'],
    },
  }}
/>
Be careful with filters - overly restrictive parameters may prevent the AI from finding relevant content.

User Experience

Opening Ask AI

Users can activate Ask AI in several ways:
  1. Search Modal: Click the AI button in the search interface
  2. Direct Button: Click an “Ask AI” button you add to your site
  3. Keyboard Shortcut: Configurable shortcut (e.g., Cmd+Shift+K)
  4. Programmatic: Call the API from your code
import { DocSearch } from '@docsearch/react';
import { useRef } from 'react';
import type { DocSearchRef } from '@docsearch/core';

function DocsLayout() {
  const searchRef = useRef<DocSearchRef>(null);

  return (
    <>
      <button onClick={() => searchRef.current?.openAskAi()}>
        Ask AI
      </button>
      <DocSearch
        ref={searchRef}
        appId="YOUR_APP_ID"
        apiKey="YOUR_SEARCH_API_KEY"
        indexName="YOUR_INDEX_NAME"
        askAi={{ assistantId: "YOUR_ASSISTANT_ID" }}
      />
    </>
  );
}

Conversation Flow

1

User asks a question

Natural language query like “How do I style the search modal?”
2

AI searches your docs

The assistant queries your Algolia index for relevant content.
3

AI generates answer

Streams a response synthesized from your documentation.
4

Sources are cited

Links to source pages appear below the answer.
5

Follow-up questions

Users can ask additional questions in context.

Ask AI Screen Component

The Ask AI interface is built with the AskAiScreen component:
import { AskAiScreen } from '@docsearch/react';
import type { AIMessage } from '@docsearch/react';

interface AskAiScreenProps {
  messages: AIMessage[];
  status: 'ready' | 'streaming' | 'submitted' | 'error';
  askAiError?: Error;
  translations?: AskAiScreenTranslations;
  onNewConversation: () => void;
}

Message Structure

Conversations consist of user and assistant messages:
interface AIMessage {
  id: string;
  role: 'user' | 'assistant';
  parts?: Array<{
    type: 'text' | 'tool-searchIndex' | 'reasoning';
    text?: string;
    state?: 'streaming' | 'complete';
  }>;
  metadata?: {
    stopped?: boolean;
    feedback?: 'like' | 'dislike';
  };
}

Exchanges

Messages are grouped into user-assistant exchanges:
interface Exchange {
  id: string;
  userMessage: AIMessage;
  assistantMessage: AIMessage | null;
}

useAskAi Hook

The useAskAi hook manages AI chat state:
import { useAskAi } from '@docsearch/react';

function AskAiComponent() {
  const {
    messages,
    status,
    sendMessage,
    stopAskAiStreaming,
    askAiError,
    conversations,
  } = useAskAi({
    assistantId: 'YOUR_ASSISTANT_ID',
    apiKey: 'YOUR_SEARCH_API_KEY',
    appId: 'YOUR_APP_ID',
    indexName: 'YOUR_INDEX_NAME',
    searchParameters: {
      facetFilters: ['version:latest'],
    },
  });

  return (
    <div>
      {messages.map((msg) => (
        <div key={msg.id}>{/* Render message */}</div>
      ))}
      {status === 'streaming' && <button onClick={stopAskAiStreaming}>Stop</button>}
    </div>
  );
}
The hook uses the AI SDK for streaming responses and automatically handles conversation state.

Customizing Translations

Customize AI interface text:
<DocSearch
  appId="YOUR_APP_ID"
  apiKey="YOUR_SEARCH_API_KEY"
  indexName="YOUR_INDEX_NAME"
  askAi={{ assistantId: "YOUR_ASSISTANT_ID" }}
  translations={{
    modal: {
      askAi: {
        disclaimerText: "AI answers may contain errors. Always verify.",
        thinkingText: "Processing your question...",
        relatedSourcesText: "Sources",
        copyButtonText: "Copy answer",
        copyButtonCopiedText: "Copied!",
        likeButtonTitle: "Helpful answer",
        dislikeButtonTitle: "Not helpful",
        thanksForFeedbackText: "Thank you!",
        errorTitleText: "Error generating answer",
        stoppedStreamingText: "Response stopped",
      },
    },
  }}
/>

Feedback System

Users can provide feedback on answers:
// Feedback is stored and sent to Algolia
const sendFeedback = async (messageId: string, thumbs: 0 | 1) => {
  await postFeedback({
    assistantId,
    thumbs, // 1 = like, 0 = dislike
    messageId,
    appId,
  });
};
Feedback helps improve answer quality over time.

Advanced: Agent Studio

Agent Studio is an experimental backend for Ask AI:
<DocSearch
  appId="YOUR_APP_ID"
  apiKey="YOUR_SEARCH_API_KEY"
  indexName="YOUR_INDEX_NAME"
  askAi={{
    assistantId: "YOUR_ASSISTANT_ID",
    agentStudio: true,
    searchParameters: {
      // Parameters keyed by index name for Agent Studio
      "docs_index": {
        distinct: false,
        filters: 'version:latest',
      },
    },
  }}
/>
Agent Studio is experimental and its API may change in future releases.

Intercepting Ask AI Events

Handle Ask AI activation in custom ways:
<DocSearch
  appId="YOUR_APP_ID"
  apiKey="YOUR_SEARCH_API_KEY"
  indexName="YOUR_INDEX_NAME"
  askAi={{ assistantId: "YOUR_ASSISTANT_ID" }}
  interceptAskAiEvent={(initialMessage) => {
    // Custom handling (e.g., open in sidepanel)
    console.log('Ask AI triggered:', initialMessage);
    // Return true to prevent default behavior
    return true;
  }}
/>

Conversation History

Recent conversations are stored locally:
// Conversations are stored in localStorage
const conversations = createStoredConversations({
  key: `__DOCSEARCH_ASKAI_CONVERSATIONS__${indexName}`,
  limit: 10, // Keep last 10 conversations
});
Users can revisit previous questions and answers.

Error Handling

Handle errors gracefully:
if (status === 'error' && askAiError) {
  // Display error message
  console.error('Ask AI error:', askAiError.message);
}
Common errors:
  • Invalid assistant ID
  • Network issues
  • Rate limiting
  • Thread depth exceeded (too many follow-ups)
Thread depth errors occur after many consecutive follow-up questions. Start a new conversation to continue.

Best Practices

Clear Documentation

Well-written docs produce better AI answers. Use clear headings and concise explanations.

Filter Strategically

Use search parameters to focus AI on relevant content without being too restrictive.

Monitor Feedback

Track user feedback to identify documentation gaps or confusing sections.

Test Questions

Try common questions to ensure the AI provides accurate, helpful answers.

Styling Ask AI

Customize the appearance:
/* Customize Ask AI components */
.DocSearch-AskAiScreen {
  /* Your styles */
}

.DocSearch-AskAiScreen-Response {
  /* Message bubbles */
}

.DocSearch-AskAiScreen-RelatedSources {
  /* Source links */
}
See the Styling guide for complete customization options.

Next Steps

Styling Guide

Learn how to customize DocSearch appearance including Ask AI components

Build docs developers (and LLMs) love