---
title: "AI Chat"
description: "为文档站启用内置 AI 助手：说明启用条件与依赖安装、模型与端点路由的配置方式、如何接入其他厂商，以及组件与组合式函数的 API，帮助你在几分钟内让读者直接向文档提问。"
canonical_url: "https://docs.mhaibaraai.cn/docs/ai/ai-chat"
---
# AI Chat

> 为文档站启用内置 AI 助手：说明启用条件与依赖安装、模型与端点路由的配置方式、如何接入其他厂商，以及组件与组合式函数的 API，帮助你在几分钟内让读者直接向文档提问。

AI Chat 是一个基于 [Vercel AI SDK](https://ai-sdk.dev) 的对话面板。它把站点内置的 [MCP Server](https://docs.mhaibaraai.cn/docs/ai/mcp) 工具直接交给模型调用，回答前先检索和阅读文档，并在消息中显示正在搜索或读取的页面。

::u-color-mode-image{alt="文档页右侧展开的 AI Chat 面板" class="rounded-md border border-default" dark="/screenshots/ai-chat-dark.png" light="/screenshots/ai-chat-light.png"}
::

## 启用

AI Chat 默认关闭，需要满足三个条件：

### 安装依赖

AI 相关依赖是 layer 的 optional peer，启用前需要安装到你的项目中：

```bash [pnpm]
pnpm add ai @ai-sdk/openai @ai-sdk/vue @comark/vue @shikijs/engine-javascript @shikijs/langs @shikijs/themes
```

```bash [npm]
npm install ai @ai-sdk/openai @ai-sdk/vue @comark/vue @shikijs/engine-javascript @shikijs/langs @shikijs/themes
```

```bash [yarn]
yarn add ai @ai-sdk/openai @ai-sdk/vue @comark/vue @shikijs/engine-javascript @shikijs/langs @shikijs/themes
```

```bash [bun]
bun add ai @ai-sdk/openai @ai-sdk/vue @comark/vue @shikijs/engine-javascript @shikijs/langs @shikijs/themes
```

启用后缺少任何一个依赖，构建会直接中止并打印需要安装的包。

### 设置环境变量

```bash [.env]
# 必需：存在即启用 AI Chat
AI_API_KEY=your-api-key

# 可选：OpenAI 兼容端点，留空则走 AI Gateway
AI_BASE_URL=https://dashscope.aliyuncs.com/compatible-mode/v1
```

`AI_API_KEY` 在**构建期**读取：`aiChat.enabled` 未设置时，构建环境中存在该变量就启用 AI Chat。部署平台需要在构建和运行两个阶段都能读到它。

### 配置模型

```ts [nuxt.config.ts]
export default defineNuxtConfig({
  extends: ['@movk/nuxt-docs'],
  aiChat: {
    model: 'alibaba/qwen3.8-27b',
    models: [
      'alibaba/qwen3.8-27b',
      'deepseek/deepseek-v4-pro-0813'
    ]
  }
})
```

这是本站正在使用的配置。`model` 是默认模型，`models` 是面板中可切换的模型列表。

> [!WARNING]
> 
> AI Chat 通过 MCP Server 获取文档工具，启用 AI Chat 时不能设置 
> 
> movkNuxtDocs.mcp: false
> 
> ，否则构建报错。

### 显式开关

`aiChat.enabled` 可以覆盖环境变量判定：

```ts [nuxt.config.ts]
export default defineNuxtConfig({
  aiChat: {
    // true：即使构建期没有 AI_API_KEY 也启用（运行期仍需提供，否则接口返回 503）
    // false：即使存在 AI_API_KEY 也关闭
    enabled: true
  }
})
```

关闭时，`AiChat`、`AiChatPanel` 等组件替换为空组件，`useAIChat()` 返回禁用态实现，AI 依赖不参与打包与类型检查。页面代码无需判断开关。

## 模块选项

`nuxt.config.ts` 中的 `aiChat`：

| 选项 | 类型 | 默认值 | 说明 |
| --- | --- | --- | --- |
| `enabled` | `boolean` | 由 `AI_API_KEY` 决定 | 是否启用 AI Chat |
| `model` | `string` | `''` | 默认模型 id |
| `models` | `string[]` | `[]` | 面板中可切换的模型，格式为 `provider/model` 或 `model` |
| `apiPath` | `string` | `'/api/ai-chat'` | 聊天接口路径 |
| `mcpPath` | `string` | `'/mcp'` | MCP Server 路径 |

## 模型路由

每次请求时，服务端按以下顺序解析模型 id：

1. **已注册的提供商**：模型 id 的前缀命中 `modelProviderRegistry` 中注册的提供商，交给它创建模型
2. **OpenAI 兼容直连**：设置了 `AI_BASE_URL`，以 chat completions 协议直连该端点
3. **AI Gateway**：以上都不满足时，通过 [Vercel AI Gateway](https://vercel.com/docs/ai-gateway) 调用

**AI Gateway** 只需要一个 `AI_API_KEY`，`models` 可以混用不同厂商的模型，模型 id 保持 `provider/model` 形式发送。

**OpenAI 兼容直连** 下，前缀只用于在模型下拉框中显示厂商图标，发请求前会被去掉：`deepseek/deepseek-v4-pro-0813` 实际发送 `deepseek-v4-pro-0813`。一组 `AI_API_KEY` + `AI_BASE_URL` 只对应一个上游，`models` 应填写该上游支持的模型。

| 厂商 | `AI_BASE_URL` |
| --- | --- |
| 阿里云百炼（国内） | `https://dashscope.aliyuncs.com/compatible-mode/v1` |
| 阿里云百炼（国际） | `https://dashscope-intl.aliyuncs.com/compatible-mode/v1` |
| DeepSeek | `https://api.deepseek.com/v1` |
| 智谱 GLM | `https://open.bigmodel.cn/api/paas/v4` |

### 接入其他提供商

layer 只内置 `@ai-sdk/openai`。需要同时接入多家厂商，或接入非 OpenAI 兼容协议的厂商时，在项目中安装对应的 [AI SDK 提供商](https://ai-sdk.dev/providers/ai-sdk-providers) 包，再按前缀注册：

```ts [server/plugins/model-providers.ts]
import { createAnthropic } from '@ai-sdk/anthropic'
import { modelProviderRegistry } from '#ai-chat/server/utils/modelProviders'

export default defineNitroPlugin(() => {
  const anthropic = createAnthropic({ apiKey: process.env.ANTHROPIC_API_KEY })

  // anthropic/claude-sonnet-5-5 会命中这里，factory 收到的 modelId 已去掉前缀
  modelProviderRegistry.register('anthropic', ({ modelId }) => anthropic(modelId))
})
```

注册的前缀优先级最高，其余模型仍按 `AI_BASE_URL` 或 AI Gateway 路由。

## 界面配置

浮动输入框、「用 AI 解释」按钮、快捷键、文案、图标与常见问题都在 `app.config.ts` 的 `aiChat` 下配置，完整字段见 [app.config 参考](https://docs.mhaibaraai.cn/docs/reference/app-config#aichat)。常用项：

```ts [app/app.config.ts]
export default defineAppConfig({
  aiChat: {
    floatingInput: true,
    explainWithAi: true,
    shortcuts: {
      focusInput: 'meta_i'
    },
    icons: {
      providers: {
        alibaba: 'i-hugeicons-qwen'
      }
    },
    faqQuestions: {
      'zh-CN': [
        { category: '安装与配置', items: ['如何从零创建文档站？', '如何启用多语言？'] }
      ],
      'en': [
        { category: 'Setup', items: ['How do I create a docs site?', 'How do I enable multiple languages?'] }
      ]
    }
  }
})
```

- `faqQuestions` 支持字符串数组、`{ category, items }` 分类数组，或按 locale 分组的对象；面板为空时显示这些问题
- `texts.*` 留空时使用当前语言的内置文案，只在需要改词时设置
- `icons.providers` 把模型前缀映射到图标，未映射的前缀回退为 `i-simple-icons-{provider}`

## 内置入口

启用后，layer 自动挂载以下入口，无需手动添加组件：

- **页头按钮**：`HeaderCTA` 中的 `AiChat`，点击切换面板
- **浮动输入框**：文档页底部的 `AiChatFloatingInput`，按 `⌘I` / `Ctrl+I` 聚焦，`Esc` 失焦，`Enter` 发送
- **用 AI 解释**：文档页右侧目录下方的按钮，以当前页面为上下文提问
- **对话面板**：`AiChatPanel`，打开后挤压正文而不是覆盖；对话记录与开关状态保存在 `localStorage`

::u-color-mode-image{alt="文档页底部的 AI 浮动输入框" class="rounded-md border border-default" dark="/screenshots/ai-chat-floating-input-dark.png" light="/screenshots/ai-chat-floating-input-light.png"}
::

每条用户消息会附带当前页面路径，模型据此优先读取当前页，回答「解释这一页」之类的问题。

## 自定义

### 系统提示词与接口

默认接口为 `layer/modules/ai-chat/runtime/server/api/ai-chat.ts`。在项目中创建与 `apiPath` 对应的文件（默认 `server/api/ai-chat.ts`），layer 会跳过默认接口的注册，由你的实现接管，可以在其中修改系统提示词、工具或步数限制。

[](https://github.com/mhaibaraai/movk-nuxt-docs/blob/main/layer/modules/ai-chat/runtime/server/api/ai-chat.ts)

### 工具调用的显示

内置工具在消息中显示为「搜索中 / 已搜索 文档页面」这类文案。为自己注册的 MCP 工具添加文案和图标时，在 `app/composables/` 中创建同名的 `useToolCall` 覆盖默认实现：

```ts [app/composables/useToolCall.ts]
export function useToolCall(state: string, toolName: string, input: Record<string, string | undefined>) {
  const done = state === 'output-available'

  return {
    toolMessage: {
      'search-api': `${done ? '已搜索' : '搜索中'} API ${input.query ?? ''}`
    } as Record<string, string>,
    toolIcon: {
      'search-api': 'i-lucide-book-open'
    } as Record<string, string>
  }
}
```

返回值只需包含自定义工具，内置工具的显示由 `AiChatPanel` 处理；未匹配的工具显示为「搜索中 {toolName}」，图标为 `i-lucide-search`。

| 内置工具 | 图标 |
| --- | --- |
| `search-documentation` | `i-lucide-book-search` |
| `get-documentation-page` | `i-lucide-book-open` |
| `search-composables` | `i-lucide-braces` |
| `search-icons` | `i-lucide-search` |
| `list-examples` | `i-lucide-codesandbox` |
| `get-example` | `i-lucide-codepen` |
| `get-component` | `i-lucide-box` |
| `get-component-metadata` | `i-lucide-file-code` |

## API

### 组件

以下组件均无 props，配置来自 `nuxt.config.ts` 的 `aiChat` 与 `app.config.ts` 的 `aiChat`。AI Chat 关闭时它们都替换为 `AiChatDisabled`（渲染一个空 `div`）。

| 组件 | 说明 |
| --- | --- |
| `AiChat` | 打开或关闭面板的按钮，提示文本取 `aiChat.texts.trigger` |
| `AiChatPanel` | 对话面板，含消息列表、流式输出、推理过程与工具调用展示 |
| `AiChatFloatingInput` | 文档页底部的浮动输入框，仅在 `docs` 布局下响应快捷键 |
| `AiChatModelSelect` | 模型下拉框，列出 `aiChat.models` |

在自定义页面中使用时，与 layer 的挂载方式保持一致：

```vue [app/pages/playground.vue]
<script setup lang="ts">
const { isEnabled } = useAIChat()
</script>

<template>
  <div>
    <AiChat />
    <template v-if="isEnabled">
      <AiChatPanel />
      <ClientOnly>
        <AiChatFloatingInput />
      </ClientOnly>
    </template>
  </div>
</template>
```

### `useAIChat()`{lang="ts-type"}

全局共享的对话状态。

**isEnabled** (`ComputedRef<boolean>`): AI Chat 是否启用。

**isOpen** (`Ref<boolean>`): 面板是否打开，同步到 localStorage。

**messages** (`Ref<UIMessage[]>`): 对话记录，同步到 localStorage。

**currentPage** (`ComputedRef<string>`): 当前路由路径，随用户消息发送。

**open** (`(text: string) => void`): 追加一条用户消息并打开面板。

**toggleChat** (`() => void`): 切换面板开关。

```ts
const { open } = useAIChat()

open('如何启用多语言？')
```

### `useModels()`{lang="ts-type"}

模型列表与当前选择。

**models** (`string[]`): aiChat.models 的值。

**model** (`Ref<string>`): 当前模型，保存在名为 model 的 Cookie 中，默认 aiChat.model。

**formatModelName** (`(modelId: string) => string`): 去掉前缀并格式化为显示名称，如 deepseek/deepseek-v4-pro-0813 显示为 Deepseek V4 Pro 0813。

**getModelIcon** (`(modelId: string) => string`): 按前缀返回 aiChat.icons.providers 中的图标。

### `useHighlighter()`{lang="ts-type"}

返回 `Promise<HighlighterCore>`，面板内代码块使用的 Shiki 实例，按需加载且只创建一次。内置语言为 `vue`、`javascript`、`typescript`、`css`、`html`、`json`、`yaml`、`markdown`、`bash`，主题为 `github-light` 与 `github-dark`，与正文代码块一致。

### `useToolCall(state, toolName, input)`{lang="ts-type"}

工具调用显示的扩展点，见 [工具调用的显示](#%E5%B7%A5%E5%85%B7%E8%B0%83%E7%94%A8%E7%9A%84%E6%98%BE%E7%A4%BA)。`state` 为 AI SDK 的工具调用状态（`'output-available'` 表示已完成），类型为 `string`，使 layer 核心代码不依赖可选的 `ai` 包。


## Sitemap

See the full [sitemap](https://docs.mhaibaraai.cn/sitemap.md) for all pages.
