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

# Ask AI

> AI-powered conversational search for your documentation

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

<Info>
  Ask AI requires an assistant ID from Algolia and is available on compatible plans.
</Info>

## Enabling Ask AI

<Steps>
  <Step title="Get an Assistant ID">
    Contact Algolia or configure an assistant in your dashboard to get your assistant ID.
  </Step>

  <Step title="Add to DocSearch Config">
    Pass the assistant ID to enable Ask AI features.
  </Step>

  <Step title="Configure Search Parameters">
    Optionally customize which content the AI searches.
  </Step>
</Steps>

### React Integration

```tsx theme={null}
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

```javascript theme={null}
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:

```tsx theme={null}
<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,
  }}
/>
```

<Accordion title="Configuration Reference">
  | Property             | Type      | Description                                               |
  | -------------------- | --------- | --------------------------------------------------------- |
  | `assistantId`        | `string`  | Your Algolia assistant ID (required)                      |
  | `indexName`          | `string`  | Index to search for AI responses (defaults to main index) |
  | `apiKey`             | `string`  | API key for AI searches (defaults to main API key)        |
  | `appId`              | `string`  | App ID for AI searches (defaults to main app ID)          |
  | `searchParameters`   | `object`  | Algolia search parameters for AI queries                  |
  | `suggestedQuestions` | `boolean` | Show suggested questions on empty state                   |
</Accordion>

## Search Parameters

Control what content the AI can search:

<CodeGroup>
  ```tsx Facet Filters theme={null}
  <DocSearch
    askAi={{
      assistantId: "YOUR_ASSISTANT_ID",
      searchParameters: {
        // Only search latest version docs
        facetFilters: ['version:latest'],
      },
    }}
  />
  ```

  ```tsx Attribute Filtering theme={null}
  <DocSearch
    askAi={{
      assistantId: "YOUR_ASSISTANT_ID",
      searchParameters: {
        // Search specific attributes
        restrictSearchableAttributes: ['content', 'hierarchy.lvl1', 'hierarchy.lvl2'],
        // Retrieve specific fields
        attributesToRetrieve: ['hierarchy', 'content', 'url', 'anchor'],
      },
    }}
  />
  ```

  ```tsx Custom Filters theme={null}
  <DocSearch
    askAi={{
      assistantId: "YOUR_ASSISTANT_ID",
      searchParameters: {
        // Complex filtering logic
        filters: 'language:en AND (version:v4 OR version:v3)',
        // Deduplicate results
        distinct: true,
      },
    }}
  />
  ```
</CodeGroup>

<Warning>
  Be careful with filters - overly restrictive parameters may prevent the AI from finding relevant content.
</Warning>

## 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

```tsx theme={null}
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

<Steps>
  <Step title="User asks a question">
    Natural language query like "How do I style the search modal?"
  </Step>

  <Step title="AI searches your docs">
    The assistant queries your Algolia index for relevant content.
  </Step>

  <Step title="AI generates answer">
    Streams a response synthesized from your documentation.
  </Step>

  <Step title="Sources are cited">
    Links to source pages appear below the answer.
  </Step>

  <Step title="Follow-up questions">
    Users can ask additional questions in context.
  </Step>
</Steps>

## Ask AI Screen Component

The Ask AI interface is built with the `AskAiScreen` component:

```typescript theme={null}
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:

```typescript theme={null}
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:

```typescript theme={null}
interface Exchange {
  id: string;
  userMessage: AIMessage;
  assistantMessage: AIMessage | null;
}
```

## useAskAi Hook

The `useAskAi` hook manages AI chat state:

```tsx theme={null}
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>
  );
}
```

<Info>
  The hook uses the AI SDK for streaming responses and automatically handles conversation state.
</Info>

## Customizing Translations

Customize AI interface text:

```tsx theme={null}
<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:

```typescript theme={null}
// 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

<Accordion title="Experimental Agent Studio Backend">
  Agent Studio is an experimental backend for Ask AI:

  ```tsx theme={null}
  <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',
        },
      },
    }}
  />
  ```

  <Warning>
    Agent Studio is experimental and its API may change in future releases.
  </Warning>
</Accordion>

## Intercepting Ask AI Events

Handle Ask AI activation in custom ways:

```tsx theme={null}
<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:

```typescript theme={null}
// 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:

```typescript theme={null}
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)

<Note>
  Thread depth errors occur after many consecutive follow-up questions. Start a new conversation to continue.
</Note>

## Best Practices

<CardGroup cols={2}>
  <Card title="Clear Documentation" icon="book-open">
    Well-written docs produce better AI answers. Use clear headings and concise explanations.
  </Card>

  <Card title="Filter Strategically" icon="filter">
    Use search parameters to focus AI on relevant content without being too restrictive.
  </Card>

  <Card title="Monitor Feedback" icon="chart-line">
    Track user feedback to identify documentation gaps or confusing sections.
  </Card>

  <Card title="Test Questions" icon="flask">
    Try common questions to ensure the AI provides accurate, helpful answers.
  </Card>
</CardGroup>

## Styling Ask AI

Customize the appearance:

```css theme={null}
/* Customize Ask AI components */
.DocSearch-AskAiScreen {
  /* Your styles */
}

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

.DocSearch-AskAiScreen-RelatedSources {
  /* Source links */
}
```

See the [Styling guide](/concepts/styling) for complete customization options.

## Next Steps

<Card title="Styling Guide" icon="palette" href="/concepts/styling">
  Learn how to customize DocSearch appearance including Ask AI components
</Card>
