# aix-chat 中文文档

规范地址：https://npmcn.com/package/aix-chat/

版本：1\.0\.10
npm 元数据更新时间：2026-11-03T01:23:50.886Z
中文译文更新时间：2026-11-03T02:27:17.076Z
软件包许可：MIT

本文由上游 README 机器翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/aix-chat
原文对照：https://npmcn.com/package/aix-chat/?lang=original
项目主页：https://github.com/iMyth/aix-chat#readme
源码仓库：https://github.com/iMyth/aix-chat

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：213 kB，56 个文件
- 模块格式：ES Module
- TypeScript 类型：包内自带
- 运行依赖：2 个
- peer 依赖：ai ^7\.0\.0，vue ^3\.5\.0，@ai-sdk/vue ^4\.0\.0
- 首次发布：2026-07-17T05:59:01.629Z
- 最新版本发布：2026-11-03T01:23:50.696Z
- 已发布版本数：11（近 12 个月 11 个）

## 中文简介

Vue 3 AI聊天UI -流媒体，自定义工具卡，语音和图像输入，光/暗主题。船与克劳德代码技能。

## 安装

```sh
npm install aix-chat
```

也可以使用：`pnpm add aix-chat`、`yarn add aix-chat`、`bun add aix-chat`

## README

# aix-chat

开箱即用的 Vue 3 AI 聊天组件。支持流式响应、自定义卡片、语音输入、图片上传、明暗主题。

[English](https://npmcn.com/package/aix-chat/README.md)

## 安装

```bash
npm install aix-chat
```

就这样 — `aix-chat` 内置了 `vue-i18n`，不需要额外配置。

## 最简用法

```vue
<script setup>
import { ChatApp } from 'aix-chat'
import 'aix-chat/style.css'
</script>

<template>
  <ChatApp agent-id="my-agent" api-base="http://localhost:3000" />
</template>
```

三行代码，一个完整的聊天界面就跑起来了。

## 完整示例

```vue
<script setup>
import { ChatApp } from 'aix-chat'
import 'aix-chat/style.css'
import { tools } from './tools'

const headers = {
  Authorization: `Bearer ${yourToken}`
}
</script>

<template>
  <ChatApp
    agent-id="order-assistant"
    api-base="http://localhost:3000"
    :headers="headers"
    assistant-name="订单助手"
    assistant-avatar="/ai-avatar.png"
    user-name="张三"
    :tools="tools"
    system-prompt="你是一个专业的订单助手。"
    :welcome="{
      text: '你好！有什么可以帮你的？',
      quickReplies: [
        { label: '下订单', value: '我想下一个新订单' },
        { label: '查订单', value: '帮我查最近的订单' }
      ]
    }"
    :enable-voice="true"
    stt-endpoint="/api/stt/open"
    :enable-image-upload="true"
    :enable-reasoning="true"
    input-placeholder="请输入您的问题..."
  />
</template>
```

## Props

#### 必填

| Prop | 类型 | 说明 |
| --- | --- | --- |
| `agent-id` | `string` | Agent 标识符 |

#### API 配置

| Prop | 类型 | 默认值 | 说明 |
| --- | --- | --- | --- |
| `api-base` | `string` | `''` | API 基础地址 |
| `api-endpoint` | `string` | `'/api/agent/chat'` | API 端点路径 |
| `headers` | `Record<string, string> | () => Record<string, string>` | `{}` | 请求头（支持函数，每次请求时调用） |

#### 外观

| Prop | 类型 | 默认值 | 说明 |
| --- | --- | --- | --- |
| `assistant-name` | `string` | `''` | 助手名称 |
| `assistant-avatar` | `string` | `''` | 助手头像 URL |
| `user-name` | `string` | `''` | 用户名称 |
| `user-avatar` | `string` | `''` | 用户头像 URL |
| `theme` | `'light' | 'dark' | 'auto'` | `'auto'` | 主题 |
| `show-header` | `boolean` | `true` | 显示头部 |
| `input-placeholder` | `string` | `''` | 输入框占位符 |

#### 功能开关

| Prop | 类型 | 默认值 | 说明 |
| --- | --- | --- | --- |
| `enable-voice` | `boolean` | `true` | 语音输入 |
| `stt-endpoint` | `string` | `'/api/stt/open'` | 语音识别接口地址，支持相对路径或完整 URL，独立于 `api-base`。 |
| `enable-image-upload` | `boolean` | `true` | 图片上传 |
| `enable-reset` | `boolean` | `true` | 重置对话按钮 |
| `enable-reasoning` | `boolean` | `true` | 思考过程展示 |
| `max-image-size` | `number` | `5242880` | 最大图片大小（字节） |

#### 内容与工具

| Prop | 类型 | 说明 |
| --- | --- | --- |
| `system-prompt` | `string` | 系统提示词 |
| `welcome` | `{ text: string, quickReplies?: Array<{ label: string, value: string }> }` | 欢迎消息 |
| `tools` | `ToolConfig[] | defineTools()` | 工具定义（见下方） |

语音接口接收 `POST` JSON `{ base64, sender }`（`base64` 为音频 Data URI），返回 `{ text: "识别结果" }`。跨域接口需支持 CORS。该地址在组件初始化时读取。

## 自定义工具 & 卡片

用 `defineTools()` 定义工具 — AI 调用工具时，自动渲染你指定的 Vue 卡片组件。

```ts
import { defineTools } from 'aix-chat'
import OptionCard from './OptionCard.vue'

export const tools = defineTools([
  {
    name: 'showOptions',
    description: '展示选项让用户选择',
    parameters: {
      type: 'object',
      properties: {
        title: { type: 'string' },
        options: { type: 'array', items: { type: 'object' } }
      },
      required: ['title', 'options']
    },
    component: OptionCard,
    mapProps: (result) => ({ title: result.title, options: result.options }),
    execute: async (args) => ({ pending: true, ...args }),
    onEvent: (eventName, data) => console.log(eventName, data)
  }
])
```

然后在 `ChatApp` 上传入 `:tools="tools"` 即可。AI 决定调用工具时，`OptionCard` 组件会自动渲染在聊天气泡中。

## 其他用法

### `mountChat()` — 一行挂载（无需 Vue SFC）

```ts
import { mountChat } from 'aix-chat'
import 'aix-chat/style.css'

const { unmount } = mountChat('#app', {
  agentId: 'my-agent',
  apiBase: 'http://localhost:3000'
})
```

适合快速验证、非 Vue 项目、或嵌入式场景。

### `createChat()` — 完全自定义 UI

如果你想自己画界面，只要聊天逻辑：

```ts
import { createChat } from 'aix-chat'

const { chat, sendMessage, chatBusy, pendingToolCall, resolve } = createChat({
  agentId: 'my-agent',
  apiBase: 'http://localhost:3000',
  tools: tools.schemas,
  onToolCall: async (name, args) => { /* 自己处理工具调用 */ }
})

await sendMessage({ text: '你好' })
```

## 样式定制

```scss
// 导入卡片样式 mixin
@use 'aix-chat/styles/chat-card';
```

通过 `./styles/*` 可以引用更多源样式文件：

```ts
import 'aix-chat/style.css'
```

## Claude Code Skills

安装后，Claude Code Skills 会自动链接到你项目的 `.claude/skills` 目录。

**不会写代码？没关系。** 在 Claude Code 里直接问：

-   "帮我添加一个 AI 聊天卡片"
-   "怎么创建一个聊天工具？"
-   "对接后端 Agent API"

Claude 会自动加载 `ai-chat-integration` skill，一步步指导你完成。

如果自动链接失败，手动操作：

```bash
npx aix-chat-skills --project .
```

## 后端对接

组件对接一个 SSE 流式端点（默认：`POST /api/agent/chat`）。你的后端接收消息 + 工具定义，调用 LLM，流式返回响应。

### 请求格式

```json
{
  "agentId": "my-agent",
  "messages": [{ "role": "user", "content": "你好" }],
  "tools": [
    { "name": "showOptions", "description": "...", "parameters": { ... } }
  ],
  "systemPrompt": "你是助手..."
}
```

### 响应格式

SSE 流，使用 [AI SDK UI Message Stream](https://sdk.vercel.ai/docs/reference/ai-sdk-ui/stream-protocol#ui-message-stream) 协议。用 `ai` 包的 `streamText()` + `toUIMessageStream()` 生成。

### 最小后端实现（Vercel AI SDK）

```ts
// POST /api/agent/chat
import { streamText, convertToModelMessages, toUIMessageStream, createUIMessageStreamResponse } from 'ai'
import { createOpenAI } from '@ai-sdk/openai'

const openai = createOpenAI({ apiKey: process.env.OPENAI_API_KEY })

export async function POST(req: Request) {
  const { messages, tools = [], systemPrompt } = await req.json()

  // 将工具定义转为 AI SDK 格式
  const aiTools = Object.fromEntries(
    tools.map((t: any) => [t.name, { description: t.description, parameters: t.parameters }])
  )

  const result = streamText({
    model: openai('gpt-4o-mini'),
    instructions: systemPrompt,
    messages: await convertToModelMessages(messages),
    tools: aiTools,
  })

  return createUIMessageStreamResponse({
    stream: toUIMessageStream({ stream: result.stream, sendReasoning: true }),
  })
}
```

支持 AI SDK 的任何 AI 提供商 — OpenAI、Anthropic、Google、DashScope（通义千问）、Ollama 等，只需换 provider。

完整的数据库持久化实现请看 Claude Code Skills 里的 `references/backend-api-guide.md`。

## 技术栈

-   Vue 3 + TypeScript
-   AI SDK v7 (`ai` + `@ai-sdk/vue`)
-   Pinia 状态管理

## License

MIT

### Skills 安装恢复

安装脚本自动创建 `.claude/skills` 并链接 Skill。若禁用了生命周期脚本或链接缺失，运行 `npx aix-chat-skills --project .`；查看安装诊断可用 `npm install --foreground-scripts`。已有的非链接目录会保留，需自行移走后重试。设置 `SKIP_AIX_SKILLS=1` 可跳过安装。其他 AI 客户端可直接读取 `node_modules/aix-chat/.claude/skills/ai-chat-integration/SKILL.md`。

`mapProps(result, args)` 的首参数是 execute 返回值；没有 execute 时才是 args。卡片 type 自动填入工具名。有 execute 时只有 `pending: true` 才等待交互。历史卡片事件带有 `mode`、`toolName`、`toolCallId`，不会完成另一张待处理卡片。

### 停止当前回复

ChatApp 在请求中显示“停止回复”，调用 SDK stop 终止 HTTP 请求并保留会话；之后可以继续发送消息。组件卸载和重置也会停止请求。使用 createChat 时可调用 `await stopChat()`；ChatApp 的组件 ref 暴露 `stop()`。后端须监听连接断开并将 AbortSignal 传给模型与工具。已提交的独立后台任务需由业务任务 API 另行取消，已完成的写入不会回滚。

## 常见问题

### aix-chat 是什么？

Vue 3 AI聊天UI -流媒体，自定义工具卡，语音和图像输入，光/暗主题。船与克劳德代码技能。

### 如何安装 aix-chat？

在项目目录运行 npm install aix-chat，或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖：ai（^7\.0\.0）、vue（^3\.5\.0）、@ai-sdk/vue（^4\.0\.0）。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖，Yarn 需要手动安装。它还提供命令行工具 aix-chat-skills，可以用 npx aix-chat-skills 直接运行。

### aix-chat 支持 TypeScript 吗？

支持。包内自带 TypeScript 类型声明（package\.json 声明了 types 入口），安装后即可获得类型提示，无需再安装 @types 包。

### aix-chat 支持 ESM 还是 CommonJS？

以 ES Module 形式发布，推荐使用 import 引入。在 CommonJS 项目中，Node\.js 20\.19\+ / 22\.12\+ 可以直接 require\(\) 不含顶层 await 的 ES Module，更早的版本需要改用动态 import\(\)。

### aix-chat 可以商用吗？

aix-chat 使用 MIT 许可。宽松许可：允许商业使用、修改和再分发，通常只需在分发时保留原版权与许可声明。以上为概括，不构成法律意见，请以许可原文为准。

### aix-chat 还在维护吗？

最新版本 1\.0\.10 发布于 2026/11/03（今天）；至今共发布 11 个版本，其中过去 12 个月发布了 11 个；首次发布于 2026/07/17。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

