资讯动态

Transformers.js 文本生成实战指南:从基础生成、Token 流式输出到多轮聊天对话

发布时间:2026/9/15 15:50:11 来源:尧图企业网站定制
Transformers.js 文本生成实战指南从基础生成、Token 流式输出到多轮聊天对话【免费下载链接】skillsGive your agents the power of the Hugging Face ecosystem项目地址: https://gitcode.com/GitHub_Trending/skills7/skills本指南以transformers-js技能Skill中的 TEXT_GENERATION.md 为骨架系统讲解如何用 Transformers.js 在 JavaScript 中运行文本生成模型包括基于pipeline的基本生成、TextStreamer流式输出Node.js / 浏览器 / React 三种形态、system/user/assistant 结构化聊天格式以及temperature、top_k、top_p等生成参数的调优方法与模型选择策略。读完本文你将能够在浏览器或 Node.js 环境中从零搭建一个可流式输出、可多轮对话、可复用与安全释放资源的文本生成应用无需任何 Python 后端。本文所有示例均可在当前仓库 skills/transformers-js 目录下对应文档中找到原始出处配套的 SKILL.md 提供了 Pipeline API、模型选择、量化与设备选择等基础概念PIPELINE_OPTIONS.md 与 CONFIGURATION.md 提供了加载选项与运行环境的完整参考。一、环境准备安装 Transformers.jsTransformers.js 是面向 JavaScript/TypeScript 的机器学习运行时可在浏览器与服务端运行时Node.js 18、Bun、Deno中直接运行来自 Hugging Face Hub 的预训练模型支持 WebGPU/WASM 双后端。安装方式有两种见 SKILL.md 的 Installation 章节NPM 安装Node.js / Bundler 环境npm install huggingface/transformers浏览器 CDN无需构建工具script typemodule import { pipeline } from https://cdn.jsdelivr.net/npm/huggingface/transformers4; /script在浏览器中引用时建议像原文档那样锁定主版本4以确保 API 行为一致。运行前提Node.js 18 或兼容的 Bun/Deno 运行时、支持 ES Modules 的现代浏览器WebGPU 加速需要运行时与硬件支持WASM 是通用兜底后端从 Hub 下载模型需要网络连接可通过本地模型离线运行。二、基本生成一行代码创建文本生成器Transformers.js 的核心入口是pipeline()函数它把分词、模型推理与后处理封装成一步调用参见 SKILL.md 的 Pipeline API 一节。文本生成任务的任务 ID 为text-generation另见text2text-generation完整任务 ID 列表在 SKILL.md 的 Quick Reference 中列出。原文档 TEXT_GENERATION.md 给出的最小可运行示例如下import { pipeline } from huggingface/transformers; const generator await pipeline( text-generation, onnx-community/Qwen2.5-0.5B-Instruct, { dtype: q4 } ); const result await generator(Once upon a time, { max_new_tokens: 100, temperature: 0.7, }); console.log(result[0].generated_text); // Clean up when done await generator.dispose();要点拆解pipeline(text-generation, modelId, options)第一个参数指定任务类型第二个参数是模型标识此处为onnx-community/Qwen2.5-0.5B-Instruct一个 0.5B 参数的指令微调模型第三个参数{ dtype: q4 }用于量化加载将权重压缩为 4 位整数表示显著缩小下载体积并提升 CPU/浏览器推理速度。生成参数max_new_tokens: 100限制最多新生成 100 个 tokentemperature: 0.7控制采样随机性。两者都是生成阶段最常用的参数后面「生成参数完全指南」一节会逐一展开。返回结构调用结果是一个数组支持批处理result[0].generated_text包含完整的生成文本提示词 新生成内容除非配合TextStreamer流式输出时以skip_prompt: true跳过。资源释放await generator.dispose()是必须的收尾动作。模型会占用从数百 MB 到数 GB 不等的内存并持有 CPU/GPU 资源SKILL.md 的 Memory Management 一节对此有专门强调在浏览器中尤其关系到内存上限与页面稳定性在长驻服务中关系到服务器稳定性。应至少在应用关闭、组件卸载、加载新模型或完成批量处理之后调用。三、流式输出逐 Token 渲染让交互像聊天一样自然非流式生成要等全部 token 完成才一次性返回大模型场景下等待可达数秒甚至更久。流式输出通过TextStreamer在每个 token 生成后立即回调让界面逐字渲染显著改善用户体验。TextStreamer的构造与使用在三种运行环境中保持一致skip_prompt跳过回显提示词、skip_special_tokens跳过s、|endoftext|等特殊 token与callback_function每生成一个 token 调用一次是三个核心选项。Node.js输出到标准输出import { pipeline, TextStreamer } from huggingface/transformers; const generator await pipeline( text-generation, onnx-community/Qwen2.5-0.5B-Instruct, { dtype: q4 } ); const streamer new TextStreamer(generator.tokenizer, { skip_prompt: true, skip_special_tokens: true, callback_function: (token) { process.stdout.write(token); }, }); await generator(Tell me a story, { max_new_tokens: 200, temperature: 0.7, streamer, });这里的关键是generator.tokenizerPipeline 在加载模型时会一并装载对应的 tokenizerTextStreamer需要它来完成 token 到文本的解码。将streamer作为生成参数传入后generator()返回前每个新 token 已经通过回调被写入了标准输出用户能在终端实时看到文字生成过程。浏览器直接操作 DOM浏览器环境下只需把callback_function中追加 token 的目标从process.stdout换成 DOM 节点。以下 HTML 是原文档中的完整示例!DOCTYPE html html body textarea idprompt placeholderEnter prompt.../textarea button onclickgenerate()Generate/button div idoutput/div script typemodule import { pipeline, TextStreamer } from https://cdn.jsdelivr.net/npm/huggingface/transformers4; const generator await pipeline( text-generation, onnx-community/Qwen2.5-0.5B-Instruct, { dtype: q4 } ); window.generate async function() { const prompt document.getElementById(prompt).value; const outputDiv document.getElementById(output); outputDiv.textContent ; const streamer new TextStreamer(generator.tokenizer, { skip_prompt: true, skip_special_tokens: true, callback_function: (token) { outputDiv.textContent token; }, }); await generator(prompt, { max_new_tokens: 200, temperature: 0.7, streamer, }); }; /script /body /html注意两个浏览器特有细节其一import语句前省略了typemodule之外的其他依赖——Transformers.js 的浏览器构建会自行管理 WASM 二进制与模型下载其二为了获得更好的加载体验可以为pipeline()传入progress_callback展示模型下载进度详见 PIPELINE_OPTIONS.md 的 Progress Callback 一节以及 EXAMPLES.md 中带进度条的浏览器完整实现。React懒加载模型 卸载时自动清理在 React 中推荐用useRef缓存 Pipeline 实例只在首次生成时加载避免每次渲染重建模型并在组件卸载时通过useEffect清理函数释放资源。原文档给出了可直接落地的完整组件import { useState, useRef, useEffect } from react; import { pipeline, TextStreamer } from huggingface/transformers; function StreamingGenerator() { const generatorRef useRef(null); const [output, setOutput] useState(); const [loading, setLoading] useState(false); const handleGenerate async (prompt) { if (!prompt) return; setLoading(true); setOutput(); // Load model on first generate if (!generatorRef.current) { generatorRef.current await pipeline( text-generation, onnx-community/Qwen2.5-0.5B-Instruct, { dtype: q4 } ); } const streamer new TextStreamer(generatorRef.current.tokenizer, { skip_prompt: true, skip_special_tokens: true, callback_function: (token) { setOutput((prev) prev token); }, }); await generatorRef.current(prompt, { max_new_tokens: 200, temperature: 0.7, streamer, }); setLoading(false); }; // Cleanup on unmount useEffect(() { return () { if (generatorRef.current) { generatorRef.current.dispose(); } }; }, []); return ( div button onClick{() handleGenerate(Tell me a story)} disabled{loading} {loading ? Generating... : Generate} /button div{output}/div /div ); }该模式把「模型加载」「流式回调写状态」「卸载释放」三件事分离useRef保证模型单例复用回调中setOutput((prev) prev token)利用函数式更新逐 token 累积文本空依赖的useEffect返回清理函数在组件卸载时执行dispose()避免内存泄漏。与 EXAMPLES.md 中EmbeddingGenerator系列的清理模式beforeunload事件、React 卸载清理、Express 服务 SIGTERM 优雅关闭相互印证。四、聊天格式用 system / user / assistant 组织多轮对话指令微调Instruct模型通常期望输入按照聊天模板组织成结构化消息而不是一段裸文本。Transformers.js 接受符合 ChatML 习惯的消息数组role可取system系统指令、user用户输入、assistant模型历史回复。聊天格式与基本生成、流式输出完全兼容——流式只需在生成参数中追加streamer。单轮对话import { pipeline } from huggingface/transformers; const generator await pipeline( text-generation, onnx-community/Qwen2.5-0.5B-Instruct, { dtype: q4 } ); const messages [ { role: system, content: You are a helpful assistant. }, { role: user, content: How do I create an async function? } ]; const result await generator(messages, { max_new_tokens: 256, temperature: 0.7, }); console.log(result[0].generated_text);多轮对话多轮对话只需把历史消息按时间顺序完整放入数组——每轮新的用户提问都要携带之前的全部轮次模型才能拥有上下文记忆。原文档的示例const conversation [ { role: system, content: You are a helpful assistant. }, { role: user, content: What is JavaScript? }, { role: assistant, content: JavaScript is a programming language... }, { role: user, content: Can you show an example? } ]; const result await generator(conversation, { max_new_tokens: 200, temperature: 0.7, }); // To add streaming, just pass a streamer: // streamer: new TextStreamer(generator.tokenizer, {...})实操建议assistant角色的历史内容必须使用模型自己生成的文本否则容易产生错误的对话状态。上下文窗口历史越长占用的输入 token 越多。当模型输入接近上下文上限时应考虑裁剪早期轮次或截断历史避免生成被截断或性能下降。与流式组合await generator(conversation, { ..., streamer })即可聊天与流式互不排斥。五、生成参数完全指南生成参数在generator(prompt, params)的第二个参数中传递。原文档将常用参数按用途分为四组下面完整保留并补充解释。5.1 常用参数一览await generator(prompt, { // Token limits max_new_tokens: 512, // Maximum tokens to generate min_new_tokens: 0, // Minimum tokens to generate // Sampling temperature: 0.7, // Randomness (0.0-2.0) top_k: 50, // Consider top K tokens top_p: 0.95, // Nucleus sampling do_sample: true, // Use random sampling (false always pick most likely token) // Repetition control repetition_penalty: 1.0, // Penalty for repeating (1.0 no penalty) no_repeat_ngram_size: 0, // Prevent repeating n-grams // Streaming streamer: streamer, // TextStreamer instance });各参数含义与影响参数含义取值建议max_new_tokens最多新生成的 token 数防止失控生成按应用场景设置如 100–512min_new_tokens至少生成多少个 token 才允许结束默认0摘要等场景可设下限temperature采样温度控制随机性0.0–2.0见 5.2top_k只在概率最高的 K 个 token 中采样常见50top_p核采样累积概率达到 p 的最小 token 集合内采样常见0.9–0.95do_sampletrue使用随机采样false退化为贪心解码每步取概率最高 token需要确定性输出时设falserepetition_penalty对已出现 token 的惩罚系数1.0表示无惩罚抑制重复可设1.1–1.3no_repeat_ngram_size禁止生成与历史 n-gram 重复的序列0表示不限制设3可显著减少短语级重复streamerTextStreamer实例启用逐 token 回调见第三节5.2 Temperature从确定性到创造性的滑杆原文档给出三档经验区间低0.1–0.5输出更聚焦、更确定适合事实性回答、代码生成、抽取任务中0.6–0.9创造性与连贯性平衡通用对话、写作的默认区间高1.0–2.0更富创意也更随机适合头脑风暴、故事创作但可能牺牲连贯性。// Focused output await generator(prompt, { temperature: 0.3, max_new_tokens: 100 }); // Creative output await generator(prompt, { temperature: 1.2, max_new_tokens: 100 });5.3 采样方法贪心、Top-k 与 Top-p三种典型解码策略及其代码形态均摘自原文档// Greedy (deterministic) await generator(prompt, { do_sample: false, max_new_tokens: 100 }); // Top-k sampling await generator(prompt, { top_k: 50, temperature: 0.7, max_new_tokens: 100 }); // Top-p (nucleus) sampling await generator(prompt, { top_p: 0.95, temperature: 0.7, max_new_tokens: 100 });贪心do_sample: false每一步固定选取概率最高的 token输出可复现、稳定但易陷入重复与单调Top-ktop_k: 50先截断到概率最高的 50 个候选再采样可避免采样到极低概率的荒谬 tokenTop-ptop_p: 0.95动态选取累积概率达到 95% 的最小候选集候选集大小随概率分布自适应是当前最主流的采样方式之一。5.4 通过config覆盖默认生成参数除每次调用传参外还可以在pipeline()的第三个参数中用config覆盖模型自带的默认生成配置从而对整条 Pipeline 生效参见 PIPELINE_OPTIONS.md 的 Custom Configuration 一节const pipe await pipeline(text-generation, model-id, { config: { max_length: 512, temperature: 0.8, // ... other config options } });该方式适用于覆盖模型仓库generation_config.json中的默认生成参数、针对特定任务做全局微调、以及在不动模型文件的前提下对比不同配置。六、模型选择为浏览器与服务器挑选合适的生成模型文本生成模型可从 Hugging Face Hub 的模型检索页按任务与库双重过滤pipeline_tagtext-generation与librarytransformers.js按 trending/downloads/likes/modified 排序原文档直接给出了这一检索入口SKILL.md 的 Finding Models 一节还提供了更多任务的过滤方式。本文不展开外部链接实际操作时在 Hub 搜索框组合这两个过滤条件即可。确认模型兼容性的关键是模型仓库中存在onnx/文件夹含 ONNX 格式权重这是 Transformers.js 能直接运行的前提。6.1 按参数规模与运行环境选择原文档给出按模型规模的选型建议规模特征推荐 dtype小型模型 1B 参数快速、浏览器友好dtype: q4中型模型1–3B 参数质量与速度均衡dtype: q4或fp16大型模型 3B 参数质量高、速度慢最适合 Node.jsdtype: fp16dtype是加载时指定的权重精度详见 PIPELINE_OPTIONS.md 的 Data Type 一节与 SKILL.md 的 Quantization Options 一节可选值包括fp32全精度最大最准、fp16半精度体积与精度均衡、q88 位量化体积小、速度快、q44 位量化体积最小、速度最快。其取舍关系可概括为精度fp32 fp16 q8 q4速度与体积则相反。浏览器/边缘设备优先q4/q8服务器端Node.js可用fp16换取更高生成质量WebGPU 环境下可尝试device: webgpu配合dtype: fp16获取 GPU 加速SKILL.md 的 WebGPU Usage 一节建议 GPU 不可用时回退 WASM/CPU。6.2 模型卡检查清单选型时原文档明确列出应核对模型卡中的参数数量与模型体积决定下载大小、内存占用与推理速度支持语言多语言 vs 仅英文基准分数Benchmark作为质量横向对比的参考许可证限制确认是否允许商用与部署场景合规。补充一点来自 MODEL_ARCHITECTURES.md 的架构参考文本生成相关支持包括 GPT-2、GPT-Neo、GPT-NeoX、CodeGen、CodeLlama、LLaMA、Mistral、Cohere、T5、BART、Gemma 等架构同时支持dtype按组件分别指定如 encoder 用fp16、decoder 用q8详见 PIPELINE_OPTIONS.md 的 Per-Component 配置。文中示例使用的onnx-community/Qwen2.5-0.5B-Instruct是 Hub 上按librarytransformers.js过滤后可直接获取的 ONNX 指令模型SKILL.md 中另以onnx-community/gemma-3-270m-it-ONNX作为推荐示例两者选其一即可。6.3 版本固定与模型仓库结构revision生产环境建议固定模型版本git 分支、tag 或 commit hash例如{ revision: v1.0.0 }不同 revision 会独立缓存PIPELINE_OPTIONS.md 的 Model Revision 一节。subfolder与model_file_name模型仓库结构非标准时可指定subfolder: onnx默认或自定义model_file_name如 encoder-decoder 模型拆分的decoder_model_merged详见同文档。七、进阶配置加载进度、本地模型与错误处理7.1 展示模型下载进度文本生成模型体积从几 MB 到数 GB 不等且由多个文件组成。通过progress_callback可跟踪端到端与逐文件进度推荐优先使用progress_total状态展示整体进度PIPELINE_OPTIONS.md 的 Progress Callback 一节给出了浏览器 UI 的完整实现const fileProgress {}; const pipe await pipeline(text-generation, model-id, { progress_callback: (info) { // Recommended: end-to-end loading progress if (info.status progress_total) { console.log(Total: ${info.progress.toFixed(1)}%); return; } // Optional: per-file progress if (info.status progress) { fileProgress[info.file] info.progress; console.log(${info.file}: ${info.progress.toFixed(1)}%); } if (info.status done) { console.log(✓ ${info.file} complete); } } });ProgressInfo的主要字段statusinitiate/download/progress/progress_total/done/ready、name模型 id 或路径、file正在处理的文件、progress0–100 百分比、loaded/total已下载/总字节数。CLI 进度条、React 进度条等更多形态见 EXAMPLES.md。7.2 离线部署与缓存策略生产环境可以完全切断运行时下载用env配置本地模型路径并禁用远程加载CONFIGURATION.md 的 Production (Local Models) 模式import { env, pipeline } from huggingface/transformers; env.allowRemoteModels false; env.allowLocalModels true; env.localModelPath /app/models/; env.useFSCache false; // Models already local浏览器默认useBrowserCache trueCache APINode.js 默认useFSCache true目录默认./.cache模型会自动缓存、重复加载免下载自定义缓存目录、自定义env.fetch注入鉴权头等高级用法参见 CONFIGURATION.md 与 CACHE.md。注意env配置必须在加载任何模型之前完成否则可能不生效。7.3 错误处理网络中断、模型不兼容等场景应显式捕获SKILL.md 的 Error Handling 一节提供了分支处理思路try { const pipe await pipeline(text-generation, model-id); const result await pipe(text to generate); } catch (error) { if (error.message.includes(fetch)) { console.error(Model download failed. Check internet connection.); } else if (error.message.includes(ONNX)) { console.error(Model execution failed. Check model compatibility.); } else { console.error(Unknown error:, error); } }八、最佳实践清单综合原文档与仓库其余参考文档SKILL.md 的 Best Practices、Performance Tips、Memory Management 各节文本生成应用的落地要点如下按环境选择模型精度浏览器用量化模型q4服务器用更大的模型fp16兼顾体积、速度与质量始终启用流式输出TextStreamer让用户看到生成过程交互体感更流畅设置 Token 上限通过max_new_tokens防止失控生成与显存/内存暴涨按用途调温度创意类0.8–1.2事实类0.3–0.7需要确定性输出时do_sample: false及时释放内存完成生成后调用dispose()React 组件在卸载时清理服务端在 SIGTERM/SIGINT 时优雅释放复用 Pipeline 实例模型加载一次、多次推理不要为每次请求重复创建 PipelineReact 中用useRef服务端在启动时初始化参考 EXAMPLES.md 的 Express API 示例多轮对话携带历史按 system/user/assistant 顺序维护消息数组控制上下文长度避免超出窗口生产固定版本用revision固定模型版本用local_files_only: true或env.allowRemoteModels false避免运行时下载波动展示加载进度大模型下载用progress_callback反馈进度配合加载态提示显式错误边界Pipeline 创建与生成调用都包裹 try-catch针对网络与 ONNX 兼容性给出可读提示。九、相关文档导航Pipeline Options —— 配置 pipeline 加载progress_callback、device、dtype、revision、session_options等Configuration Reference ——env全局环境配置远程/本地模型、缓存、WASM、日志Code Examples —— 浏览器、Node.js、React、Express API 的完整运行示例Model Architectures —— 支持的全部模型架构与按任务选型建议Caching Reference —— 浏览器 Cache API、Node.js 文件系统缓存与自定义缓存Main Skill Guide —— Transformers.js 入门总览Pipeline API、量化、设备选择、任务 ID 表【免费下载链接】skillsGive your agents the power of the Hugging Face ecosystem项目地址: https://gitcode.com/GitHub_Trending/skills7/skills创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

读完文章,也想定制专属网站?

尧图设计师 24 小时内与您沟通定制方案

免费获取报价