Files
mintlify__docs/guides/assistant-embed.mdx
Ethan Palm 017d7c7377 Fix Vale warnings (#6378)
* fix: reduce Vale false positives via vocab and config updates

- Make English-word vocab entries case-insensitive so sentence-start
  capitalization and normal prose usage stop flagging (agents, rest,
  cursor, setup, endpoints, etc.)
- Add vocab entries for filenames and code identifiers that appear in
  frontmatter and JSX contexts (docs.json, llms.txt, CLAUDE.md, etc.)
- Ignore openapi frontmatter lines, filenames, JSX attributes, email
  addresses, and internal link targets via TokenIgnores
- Skip inline code scope and indented code fences
- Add Headings exceptions for proper nouns (Claude Code, GitHub
  Actions, Route 53, GA4, etc.)
- Disable linting for the all-code vercel-json-generator snippet

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix: resolve all Vale warnings and errors across docs

Content fixes:
- Reword sentences using 'will', first person, spaced em dashes,
  'e.g.', Latin abbreviations, and hyphenated adverbs
- Sentence-case headings that started with dotted filenames
- Backtick literal API values instead of bolding them
- Move periods inside quotation marks
- Fix Oxford comma rule misfires by restructuring sentences

False-positive suppression:
- Vale toggles around example user questions, keyboard shortcut keys
  (Cmd+I), UI labels, and code samples in JSX contexts that Vale
  misparses
- Exclude vale toggle comments from the brace Token/BlockIgnores so
  in-document commands actually reach Vale (the greedy brace pattern
  was also silently swallowing large regions; now lazy)
- Vocab entries for code identifiers (internal_id, handleSubmit, etc.)
- Per-file rule disables for component docs with dotted JSX names and
  files where link-target linting ignores in-document toggles

Result: vale --minAlertLevel warning is clean repo-wide; only
suggestion-level items (Passive, Semicolons, Acronyms) remain.
mint broken-links passes.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix: correct WordList rule instead of degrading prose

- Restore sentence-start "Email" in advanced-support; the rule now
  only flags hyphenated e-mail/E-mail forms
- Restore the idiom "above all else"; the above->preceding swap now
  exempts "above all"

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix: restore deliberate prose flagged by blunt rules

- Restore spatial 'above the navbar' / 'above a page title' in
  custom-scripts; the above->preceding swap now exempts 'above
  the/a/an'
- Restore the '= ...' in the react-components named-export example
  (the ellipsis is inside inline code) with an Ellipses toggle
- Restore SLA phrasing 'will use commercially reasonable efforts'
  with a Will toggle
- Restore the quoted developer question in the GEO guide intro with a
  FirstPerson toggle, matching the file's other example questions

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix: remove WordList swaps that flag legitimate English

- Drop tablet->device and firewalls->firewall rules; both words are
  correct in ordinary prose
- Narrow touch->tap to UI-instruction phrasing (touch the/a) so
  'keep in touch' and 'touch devices' stop flagging

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix: reposition vale toggles to wrap whole blocks

Toggle comments placed between list items split the lists (restarting
ol numbering in deployments) and comments flush against tables risked
breaking GFM table parsing. Wrap entire lists/tables with blank-line
separation instead. Verified rendering with mint dev: single ol with
two items, tables intact, no comments in visible DOM.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* refactor: prune accept.txt to load-bearing entries

Empirically removed 166 vocab entries (575 -> 409) whose removal
causes no Vale flags across all 908 English pages: dictionary words
that never needed listing (agents, setup, endpoints, webhooks, yaml),
lowercase entries the speller already accepts, and filename entries
made redundant by inline vale toggles.

Kept every case-enforcing entry (API, JSON, GitHub, ...) so casing
policy is unchanged, plus entries that double as capitalization
exceptions for headings (mcp, md, auth, cursor, txt).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Update ai/mintlify-mcp.mdx

* Update api/agent/v2/create-agent-job.mdx

* chore: alphabetize Headings exceptions and accept.txt

Case-insensitive sort, ignoring the (?i) prefix; also drops a
duplicate Scala entry.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix: re-apply OxfordComma rewrite lost in branch merge

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* docs: resolve Vale suggestions batch 1 (acronyms, semicolons, passive voice)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* docs: resolve remaining Vale suggestions (passive voice batch 2)

Rewrite ~90 passive constructions to active voice across deploy,
guides, migration-services, and organize docs. Toggle the deliberate
passive examples in the style-and-tone guide ('by zombies' test).
Add axios/lodash vocab entries for a repositioned code example.

vale . is now fully clean: 0 errors, 0 warnings, 0 suggestions.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-02 17:17:56 -07:00

237 lines
7.5 KiB
Plaintext

---
title: "Tutorial: Build an in-app documentation assistant"
sidebarTitle: "Build an in-app assistant"
description: "Build and embed an in-app documentation assistant that answers user questions with cited information from your Mintlify documentation site."
keywords: ["assistant embed", "in-app chat", "widget", "chatbot"]
---
## What you'll build
A reusable widget that embeds the [assistant](/assistant/index) directly in your application. The widget provides:
- A floating button that opens a chat panel when clicked
- Real-time streaming responses based on information from your documentation
- Message rendering with Markdown support
Users can use the widget to get help with your product without leaving your application.
<Frame>
<img src="/images/assistant/assistant-embed-demo.gif" alt="Demo of the assistant widget being opened and the user typing in How do I get started? Then the assistant responds." />
</Frame>
## Prerequisites
- The Mintlify assistant enabled
- Your domain name, which appears at the end of your dashboard URL. For example, if your dashboard URL is `https://app.mintlify.com/org-name/domain-name`, your domain name is `domain-name`
- An [assistant API key](https://app.mintlify.com/settings/organization/api-keys)
- Node.js v18 or higher and npm installed
- Basic React knowledge
### Get your assistant API key
1. Navigate to the [API keys](https://app.mintlify.com/settings/organization/api-keys) page in your dashboard.
2. Click **Create Assistant API Key**.
3. Copy the assistant API key (starts with `mint_dsc_`) and save it securely.
<Note>
Your assistant API key controls access to your assistant quota. This tutorial keeps the key server-side using a backend proxy so it never reaches the client bundle.
</Note>
## Set up the example
Clone the [example repository](https://github.com/mintlify/assistant-embed-example) and customize it for your needs.
<Steps>
<Step title="Clone the repository">
```bash
git clone https://github.com/mintlify/assistant-embed-example.git
cd assistant-embed-example
```
</Step>
<Step title="Choose your development tool">
The repository includes Next.js and Vite examples. Choose the tool you prefer to use.
<CodeGroup>
```bash title="Next.js"
cd nextjs
npm install
```
```bash title="Vite"
cd vite
npm install
```
</CodeGroup>
</Step>
<Step title="Configure your project">
Open `src/config.js` and update with your Mintlify project details.
```js src/config.js
export const ASSISTANT_CONFIG = {
domain: 'your-domain',
docsURL: 'https://yourdocs.mintlify.site',
};
```
Replace:
- `your-domain` with your Mintlify project domain found at the end of your dashboard URL.
- `https://yourdocs.mintlify.site` with your actual documentation URL.
</Step>
<Step title="Set up your API key">
Store your assistant API key as a server-side environment variable. Avoid the `VITE_` prefix, which bundles the value into your client code:
```bash .env
MINTLIFY_TOKEN=mint_dsc_your_token_here
```
Replace `mint_dsc_your_token_here` with your assistant API key.
Then add a backend route (for example, `/api/assistant`) to proxy requests to the Mintlify API:
1. Accept the user's message from the widget.
2. Attach the `Authorization: Bearer $MINTLIFY_TOKEN` header and forward the request to `https://api.mintlify.com/discovery/v1/assistant/{domain}/message`.
3. Stream the upstream response back to the client unchanged, so token streaming and `X-Thread-Id` / `X-Thread-Key` headers reach the widget.
4. Point the widget's `api` option at your backend route instead of the Mintlify API directly.
</Step>
<Step title="Start the development server">
```bash
npm run dev
```
Open your application in a browser and click the **Ask** button to open the assistant widget.
</Step>
</Steps>
## Customization ideas
### Source citations
Extract and display sources from assistant responses:
```jsx
const extractSources = (parts) => {
return parts
?.filter(p => p.type === 'tool-invocation' && p.toolInvocation?.toolName === 'search')
.flatMap(p => p.toolInvocation?.result || [])
.map(source => ({
url: source.url || source.path,
title: source.metadata?.title || source.path,
})) || [];
};
// In your message rendering:
{messages.map((message) => {
const sources = message.role === 'assistant' ? extractSources(message.parts) : [];
return (
<div key={message.id}>
{/* message content */}
{sources.length > 0 && (
<div className="mt-2 text-xs">
<p className="font-semibold">Sources:</p>
{sources.map((s, i) => (
<a key={i} href={s.url} target="_blank" rel="noopener noreferrer" className="text-blue-600">
{s.title}
</a>
))}
</div>
)}
</div>
);
})}
```
### Track conversation threads
Store thread IDs and thread keys to maintain conversation history across sessions.
When a user creates a new conversation thread, the server returns two values in the response headers:
- `X-Thread-Id`: The thread identifier
- `X-Thread-Key`: A secret key for the thread (only returned once, when you create the thread)
You must capture and persist both values on the first response. On every subsequent message, include both `threadId` and `threadKey` in the request body. If you send a `threadId` without the corresponding `threadKey`, the server returns a `404` error.
<Warning>
You must store the `X-Thread-Key` header immediately. The server only returns it when you create a new thread. You cannot retrieve it later.
</Warning>
```jsx
import { useState, useEffect } from 'react';
export function AssistantWidget({ domain, docsURL }) {
const [threadId, setThreadId] = useState(null);
const [threadKey, setThreadKey] = useState(null);
useEffect(() => {
// Retrieve saved thread ID and key from localStorage
const savedId = localStorage.getItem('assistant-thread-id');
const savedKey = localStorage.getItem('assistant-thread-key');
if (savedId && savedKey) {
setThreadId(savedId);
setThreadKey(savedKey);
}
}, []);
const { messages, input, handleInputChange, handleSubmit, isLoading } = useChat({
api: '/api/assistant',
body: {
fp: 'anonymous',
retrievalPageSize: 5,
...(threadId && { threadId }),
...(threadKey && { threadKey }),
},
streamProtocol: 'data',
sendExtraMessageFields: true,
fetch: async (url, options) => {
const response = await fetch(url, options);
const newThreadId = response.headers.get('x-thread-id');
const newThreadKey = response.headers.get('x-thread-key');
if (newThreadId) {
setThreadId(newThreadId);
localStorage.setItem('assistant-thread-id', newThreadId);
}
if (newThreadKey) {
setThreadKey(newThreadKey);
localStorage.setItem('assistant-thread-key', newThreadKey);
}
return response;
},
});
// ... rest of component
}
```
### Add keyboard shortcuts
Allow users to open the widget and submit messages with keyboard shortcuts:
```jsx
useEffect(() => {
const handleKeyDown = (e) => {
// Cmd/Ctrl + Shift + I to toggle widget
if ((e.metaKey || e.ctrlKey) && e.shiftKey && e.key === 'I') {
e.preventDefault();
setIsOpen((prev) => !prev);
}
// Enter (when widget is focused) to submit
if (e.key === 'Enter' && !e.shiftKey && document.activeElement.id === 'assistant-input') {
e.preventDefault();
handleSubmit();
}
};
window.addEventListener('keydown', handleKeyDown);
return () => window.removeEventListener('keydown', handleKeyDown);
}, [handleSubmit]);
```