Guide · 使用教程
Transformers.js 教程|在浏览器做本地英文 FAQ 语义搜索
复制 HTML 和 JavaScript,通过浏览器 WebAssembly 给八条 FAQ 生成向量,检查七个问句、前三个候选和同源资源加载。
在浏览器里复现一份英文 FAQ 搜索
把八条英文 FAQ 算成向量,再为七个问句各找出最相近的三条。六个问句有标准答案,最后一个故意在 FAQ 里找不到答案。这个示例用普通静态文件和浏览器的 WebAssembly 推理,可以在本机检查每次排名以及实际的资源请求。 模型卡 · 本次评测
准备浏览器库和模型文件
安装步骤需要 Node.js、npm、curl 和 Python 3。Node.js 在这里用于安装浏览器依赖。网页里的模型由 WebAssembly 运行。在一个空目录里执行下面的命令可准备所需文件。模型权重大小约 23 MB,下载被打断后可重新运行下载命令。源码和权重都有各自的许可,重新分发前请核对。
mkdir faq-browser
cd faq-browser
npm init -y
npm install --save-exact --ignore-scripts \
@huggingface/[email protected] [email protected]
model_dir='.model-cache/Xenova/all-MiniLM-L6-v2'
mkdir -p "$model_dir/onnx"
base='https://huggingface.co/Xenova/all-MiniLM-L6-v2/resolve/main'
for f in config.json tokenizer.json tokenizer_config.json onnx/model_quantized.onnx
do
curl --http1.1 -fL --retry 2 -C - -o "$model_dir/$f" "$base/$f" || break
done
权重文件 model_quantized.onnx 本次核对为 22,972,370 字节。等下载结束再打开页面。官方模型仓库的文件记录可用于校验权重的 SHA-256。 模型文件目录
保存页面和检索模块
把第一段保存为 faq.html。导入映射把 runtime 指向 npm 安装目录。模型、JavaScript 和 WASM 都从本机 HTTP 服务读取。
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Local FAQ search test</title>
<script type="importmap">
{
"imports": {
"onnxruntime-common": "/node_modules/onnxruntime-common/dist/esm/index.js",
"onnxruntime-web/webgpu": "/node_modules/onnxruntime-web/dist/ort.webgpu.min.mjs"
}
}
</script>
</head>
<body>
<h1>Local FAQ test</h1>
<pre>Loading model</pre>
<script type="module">
try {
await import('./faq-web.mjs')
} catch (error) {
document.querySelector('pre').textContent = 'Error: ' + error.message
}
</script>
</body>
</html>
第二段保存为同目录下的 faq-web.mjs。代码把句子向量归一化,因此点积等于余弦相似度。文档 ID 用来把候选映射回 FAQ 原文。
import { env, pipeline } from './node_modules/@huggingface/transformers/dist/transformers.web.js';
env.allowLocalModels = true;
env.allowRemoteModels = false;
env.localModelPath = '/.model-cache/';
env.backends.onnx.wasm.numThreads = 1;
env.backends.onnx.wasm.wasmPaths = '/node_modules/onnxruntime-web/dist/';
const model = 'Xenova/all-MiniLM-L6-v2';
const docs = [
{ id: 'password', text: 'Reset a forgotten password. Request a reset link by email.' },
{ id: 'invoice', text: 'Download a PDF invoice or receipt from Billing History.' },
{ id: 'refund', text: 'Request a refund for an eligible purchase within 14 days.' },
{ id: 'cancel', text: 'Cancel your subscription to stop automatic renewal.' },
{ id: 'timezone', text: 'Set your time zone in Profile Settings to correct meeting times.' },
{ id: 'seat', text: 'Invite a teammate or add a seat to your workspace.' },
{ id: 'export', text: 'Export your workspace data as a CSV spreadsheet.' },
{ id: 'email', text: 'Change the email address used for account notifications.' },
];
const queries = [
{ text: "I can't remember my sign-in credentials", expected: 'password' },
{ text: 'Where do I get proof of payment?', expected: 'invoice' },
{ text: 'Can I get my money back?', expected: 'refund' },
{ text: 'I want to stop being billed next month', expected: 'cancel' },
{ text: 'My appointments show the wrong local hour', expected: 'timezone' },
{ text: 'How do I bring another person into our team?', expected: 'seat' },
{ text: 'Can I pay with a gift card?', expected: null },
];
const totalStart = performance.now();
const embed = await pipeline('feature-extraction', model, { device: 'wasm', dtype: 'q8' });
const loaded = performance.now();
const options = { pooling: 'mean', normalize: true };
const index = await embed(docs.map(item => item.text), options);
const queryVectors = await embed(queries.map(item => item.text), options);
const vectors = index.tolist();
const dot = (a, b) => a.reduce((sum, value, i) => sum + value * b[i], 0);
const output = queryVectors.tolist().map((vector, i) => {
const ranked = docs.map(({ id }, j) => ({ id, score: dot(vector, vectors[j]) }));
ranked.sort((a, b) => b.score - a.score);
return {
...queries[i],
top: ranked.slice(0, 3).map(({ id, score }) => ({ id, score: Number(score.toFixed(4)) })),
};
});
const supported = output.filter(item => item.expected);
const hitAt = n => supported.filter(item => item.top.slice(0, n).some(x => x.id === item.expected)).length;
document.querySelector('pre').textContent = JSON.stringify({
browser: navigator.userAgent,
platform: navigator.platform,
model,
dtype: 'q8',
dimensions: index.dims,
remoteModelsAllowed: env.allowRemoteModels,
loadMs: Math.round(loaded - totalStart),
embedAndRankMs: Math.round(performance.now() - loaded),
hit1: hitAt(1),
hit3: hitAt(3),
supported: supported.length,
output,
}, null, 2);
从当前目录启动 HTTP 服务。使用浏览器打开 http://127.0.0.1:8765/faq.html。
python3 -m http.server 8765 --bind 127.0.0.1
核对结果和浏览器请求
本次在 Intel Mac 的 Chromium 浏览器 用 q8 权重得到 [8, 384] 的文档向量矩阵。首位命中 6/6,前三位命中 6/6。礼品卡提问的首条候选是 refund,得分 0.2679。浏览器始终会给输入一个排序,所以实际界面要为没有可靠答案的情况保留其他求助入口。
模型文件提前下载,浏览器第一次从本机加载约 2.19 秒,刷新后初始化约 0.43 秒,本批编码和排序约 154 毫秒。两次的前三名排序与得分一致,检查到的资源请求只访问本机。耗时包含本机加载,线上首次下载和移动端性能需要另外测量。
打开浏览器开发者工具的 Network 面板,刷新页面。这个示例应当只请求本机地址。若读取不到模型文件,先按浏览器中的请求路径核对 .model-cache 及模型目录大小写。WASM 初始化失败时,检查 ONNX Runtime 的 JavaScript 模块和 .wasm 资源是否来自同一版本。 Transformers.js 浏览器应用教程 · ONNX Runtime Web
迁移到真实帮助中心
把示例文本替换成真实帮助条目的标题和核心内容,并把记录的 ID 对应到可以点开的 URL。正式版可在构建时先生成文档向量,浏览器只计算新问句的向量。重新发布模型或调整文本切片后,用同一版本重建文档索引。中文 FAQ 选支持中文的模型,并制作自己的近义问句与反例。编号、工单号等字段增加精确匹配。
注意首次下载与后续查询耗时的区别。面向真实访客时,在目标手机和网络上分别测两次,检查第一次打开时的静态包大小及浏览器是否能正常运行。这个例子验证的是本机同源加载和搜索;如果需要网页完全断网,也要独立设计页面和静态资源的预缓存。 工具档案 · 部署路线对比
常见问题
- 浏览器为什么要从本机 HTTP 地址打开?
- 示例通过 HTTP 加载 ES 模块、WASM 和模型文件。本机服务可让这些资源保持同源,便于在浏览器里核对请求路径。
- 搜索输入需要发给模型托管站点吗?
- 示例让库只加载同源模型文件,在浏览器运行推理。开发者工具的网络记录可用于核对静态资源与额外请求。