[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"similar-mlc-ai--web-llm":3,"tool-mlc-ai--web-llm":61},[4,18,26,36,44,52],{"id":5,"name":6,"github_repo":7,"description_zh":8,"stars":9,"difficulty_score":10,"last_commit_at":11,"category_tags":12,"status":17},4358,"openclaw","openclaw\u002Fopenclaw","OpenClaw 是一款专为个人打造的本地化 AI 助手，旨在让你在自己的设备上拥有完全可控的智能伙伴。它打破了传统 AI 助手局限于特定网页或应用的束缚，能够直接接入你日常使用的各类通讯渠道，包括微信、WhatsApp、Telegram、Discord、iMessage 等数十种平台。无论你在哪个聊天软件中发送消息，OpenClaw 都能即时响应，甚至支持在 macOS、iOS 和 Android 设备上进行语音交互，并提供实时的画布渲染功能供你操控。\n\n这款工具主要解决了用户对数据隐私、响应速度以及“始终在线”体验的需求。通过将 AI 部署在本地，用户无需依赖云端服务即可享受快速、私密的智能辅助，真正实现了“你的数据，你做主”。其独特的技术亮点在于强大的网关架构，将控制平面与核心助手分离，确保跨平台通信的流畅性与扩展性。\n\nOpenClaw 非常适合希望构建个性化工作流的技术爱好者、开发者，以及注重隐私保护且不愿被单一生态绑定的普通用户。只要具备基础的终端操作能力（支持 macOS、Linux 及 Windows WSL2），即可通过简单的命令行引导完成部署。如果你渴望拥有一个懂你",349277,3,"2026-04-06T06:32:30",[13,14,15,16],"Agent","开发框架","图像","数据工具","ready",{"id":19,"name":20,"github_repo":21,"description_zh":22,"stars":23,"difficulty_score":10,"last_commit_at":24,"category_tags":25,"status":17},3808,"stable-diffusion-webui","AUTOMATIC1111\u002Fstable-diffusion-webui","stable-diffusion-webui 是一个基于 Gradio 构建的网页版操作界面，旨在让用户能够轻松地在本地运行和使用强大的 Stable Diffusion 图像生成模型。它解决了原始模型依赖命令行、操作门槛高且功能分散的痛点，将复杂的 AI 绘图流程整合进一个直观易用的图形化平台。\n\n无论是希望快速上手的普通创作者、需要精细控制画面细节的设计师，还是想要深入探索模型潜力的开发者与研究人员，都能从中获益。其核心亮点在于极高的功能丰富度：不仅支持文生图、图生图、局部重绘（Inpainting）和外绘（Outpainting）等基础模式，还独创了注意力机制调整、提示词矩阵、负向提示词以及“高清修复”等高级功能。此外，它内置了 GFPGAN 和 CodeFormer 等人脸修复工具，支持多种神经网络放大算法，并允许用户通过插件系统无限扩展能力。即使是显存有限的设备，stable-diffusion-webui 也提供了相应的优化选项，让高质量的 AI 艺术创作变得触手可及。",162132,"2026-04-05T11:01:52",[14,15,13],{"id":27,"name":28,"github_repo":29,"description_zh":30,"stars":31,"difficulty_score":32,"last_commit_at":33,"category_tags":34,"status":17},1381,"everything-claude-code","affaan-m\u002Feverything-claude-code","everything-claude-code 是一套专为 AI 编程助手（如 Claude Code、Codex、Cursor 等）打造的高性能优化系统。它不仅仅是一组配置文件，而是一个经过长期实战打磨的完整框架，旨在解决 AI 代理在实际开发中面临的效率低下、记忆丢失、安全隐患及缺乏持续学习能力等核心痛点。\n\n通过引入技能模块化、直觉增强、记忆持久化机制以及内置的安全扫描功能，everything-claude-code 能显著提升 AI 在复杂任务中的表现，帮助开发者构建更稳定、更智能的生产级 AI 代理。其独特的“研究优先”开发理念和针对 Token 消耗的优化策略，使得模型响应更快、成本更低，同时有效防御潜在的攻击向量。\n\n这套工具特别适合软件开发者、AI 研究人员以及希望深度定制 AI 工作流的技术团队使用。无论您是在构建大型代码库，还是需要 AI 协助进行安全审计与自动化测试，everything-claude-code 都能提供强大的底层支持。作为一个曾荣获 Anthropic 黑客大奖的开源项目，它融合了多语言支持与丰富的实战钩子（hooks），让 AI 真正成长为懂上",141543,2,"2026-04-06T11:32:54",[14,13,35],"语言模型",{"id":37,"name":38,"github_repo":39,"description_zh":40,"stars":41,"difficulty_score":32,"last_commit_at":42,"category_tags":43,"status":17},2271,"ComfyUI","Comfy-Org\u002FComfyUI","ComfyUI 是一款功能强大且高度模块化的视觉 AI 引擎，专为设计和执行复杂的 Stable Diffusion 图像生成流程而打造。它摒弃了传统的代码编写模式，采用直观的节点式流程图界面，让用户通过连接不同的功能模块即可构建个性化的生成管线。\n\n这一设计巧妙解决了高级 AI 绘图工作流配置复杂、灵活性不足的痛点。用户无需具备编程背景，也能自由组合模型、调整参数并实时预览效果，轻松实现从基础文生图到多步骤高清修复等各类复杂任务。ComfyUI 拥有极佳的兼容性，不仅支持 Windows、macOS 和 Linux 全平台，还广泛适配 NVIDIA、AMD、Intel 及苹果 Silicon 等多种硬件架构，并率先支持 SDXL、Flux、SD3 等前沿模型。\n\n无论是希望深入探索算法潜力的研究人员和开发者，还是追求极致创作自由度的设计师与资深 AI 绘画爱好者，ComfyUI 都能提供强大的支持。其独特的模块化架构允许社区不断扩展新功能，使其成为当前最灵活、生态最丰富的开源扩散模型工具之一，帮助用户将创意高效转化为现实。",107888,"2026-04-06T11:32:50",[14,15,13],{"id":45,"name":46,"github_repo":47,"description_zh":48,"stars":49,"difficulty_score":10,"last_commit_at":50,"category_tags":51,"status":17},4487,"LLMs-from-scratch","rasbt\u002FLLMs-from-scratch","LLMs-from-scratch 是一个基于 PyTorch 的开源教育项目，旨在引导用户从零开始一步步构建一个类似 ChatGPT 的大型语言模型（LLM）。它不仅是同名技术著作的官方代码库，更提供了一套完整的实践方案，涵盖模型开发、预训练及微调的全过程。\n\n该项目主要解决了大模型领域“黑盒化”的学习痛点。许多开发者虽能调用现成模型，却难以深入理解其内部架构与训练机制。通过亲手编写每一行核心代码，用户能够透彻掌握 Transformer 架构、注意力机制等关键原理，从而真正理解大模型是如何“思考”的。此外，项目还包含了加载大型预训练权重进行微调的代码，帮助用户将理论知识延伸至实际应用。\n\nLLMs-from-scratch 特别适合希望深入底层原理的 AI 开发者、研究人员以及计算机专业的学生。对于不满足于仅使用 API，而是渴望探究模型构建细节的技术人员而言，这是极佳的学习资源。其独特的技术亮点在于“循序渐进”的教学设计：将复杂的系统工程拆解为清晰的步骤，配合详细的图表与示例，让构建一个虽小但功能完备的大模型变得触手可及。无论你是想夯实理论基础，还是为未来研发更大规模的模型做准备",90106,"2026-04-06T11:19:32",[35,15,13,14],{"id":53,"name":54,"github_repo":55,"description_zh":56,"stars":57,"difficulty_score":10,"last_commit_at":58,"category_tags":59,"status":17},4292,"Deep-Live-Cam","hacksider\u002FDeep-Live-Cam","Deep-Live-Cam 是一款专注于实时换脸与视频生成的开源工具，用户仅需一张静态照片，即可通过“一键操作”实现摄像头画面的即时变脸或制作深度伪造视频。它有效解决了传统换脸技术流程繁琐、对硬件配置要求极高以及难以实时预览的痛点，让高质量的数字内容创作变得触手可及。\n\n这款工具不仅适合开发者和技术研究人员探索算法边界，更因其极简的操作逻辑（仅需三步：选脸、选摄像头、启动），广泛适用于普通用户、内容创作者、设计师及直播主播。无论是为了动画角色定制、服装展示模特替换，还是制作趣味短视频和直播互动，Deep-Live-Cam 都能提供流畅的支持。\n\n其核心技术亮点在于强大的实时处理能力，支持口型遮罩（Mouth Mask）以保留使用者原始的嘴部动作，确保表情自然精准；同时具备“人脸映射”功能，可同时对画面中的多个主体应用不同面孔。此外，项目内置了严格的内容安全过滤机制，自动拦截涉及裸露、暴力等不当素材，并倡导用户在获得授权及明确标注的前提下合规使用，体现了技术发展与伦理责任的平衡。",88924,"2026-04-06T03:28:53",[14,15,13,60],"视频",{"id":62,"github_repo":63,"name":64,"description_en":65,"description_zh":66,"ai_summary_zh":67,"readme_en":68,"readme_zh":69,"quickstart_zh":70,"use_case_zh":71,"hero_image_url":72,"owner_login":73,"owner_name":73,"owner_avatar_url":74,"owner_bio":75,"owner_company":75,"owner_location":75,"owner_email":75,"owner_twitter":75,"owner_website":75,"owner_url":76,"languages":77,"stars":97,"forks":98,"last_commit_at":99,"license":100,"difficulty_score":32,"env_os":101,"env_gpu":102,"env_ram":103,"env_deps":104,"category_tags":111,"github_topics":112,"view_count":32,"oss_zip_url":75,"oss_zip_packed_at":75,"status":17,"created_at":120,"updated_at":121,"faqs":122,"releases":153},4438,"mlc-ai\u002Fweb-llm","web-llm","High-performance In-browser LLM Inference Engine ","WebLLM 是一款高性能的浏览器端大语言模型推理引擎，它让强大的 AI 模型能够直接在网页浏览器中运行，无需依赖后端服务器。通过将计算任务完全移至本地并利用 WebGPU 进行硬件加速，WebLLM 有效解决了传统云端部署带来的数据隐私泄露风险、网络延迟以及高昂的服务器成本问题，同时确保了用户数据的绝对私密性。\n\n这款工具特别适合前端开发者、全栈工程师以及希望构建隐私优先型 AI 应用的研究人员。借助 WebLLM，开发者可以轻松在网页中集成智能助手、聊天机器人或数据分析工具，而普通用户也能通过支持该技术的网站体验流畅的本地化 AI 服务。\n\nWebLLM 的技术亮点在于其全面兼容 OpenAI API 标准，这意味着开发者可以使用熟悉的接口调用 Llama 3、Qwen（通义千问）、Phi 3 等多种开源模型，并直接享受流式输出、结构化 JSON 生成等高级功能。此外，它支持通过 NPM 或 CDN 快速集成，并提供 Web Worker 多线程支持以优化界面响应速度。作为 MLC LLM 生态的重要一环，WebLLM 真正实现了“一次编写，处处运行”，让高质量的 AI 推理能力触","WebLLM 是一款高性能的浏览器端大语言模型推理引擎，它让强大的 AI 模型能够直接在网页浏览器中运行，无需依赖后端服务器。通过将计算任务完全移至本地并利用 WebGPU 进行硬件加速，WebLLM 有效解决了传统云端部署带来的数据隐私泄露风险、网络延迟以及高昂的服务器成本问题，同时确保了用户数据的绝对私密性。\n\n这款工具特别适合前端开发者、全栈工程师以及希望构建隐私优先型 AI 应用的研究人员。借助 WebLLM，开发者可以轻松在网页中集成智能助手、聊天机器人或数据分析工具，而普通用户也能通过支持该技术的网站体验流畅的本地化 AI 服务。\n\nWebLLM 的技术亮点在于其全面兼容 OpenAI API 标准，这意味着开发者可以使用熟悉的接口调用 Llama 3、Qwen（通义千问）、Phi 3 等多种开源模型，并直接享受流式输出、结构化 JSON 生成等高级功能。此外，它支持通过 NPM 或 CDN 快速集成，并提供 Web Worker 多线程支持以优化界面响应速度。作为 MLC LLM 生态的重要一环，WebLLM 真正实现了“一次编写，处处运行”，让高质量的 AI 推理能力触手可及。","\u003Cdiv align=\"center\" id=\"top\">\n\n# WebLLM\n\n[![NPM Package](https:\u002F\u002Fimg.shields.io\u002Fbadge\u002FNPM_Package-Published-cc3534)](https:\u002F\u002Fwww.npmjs.com\u002Fpackage\u002F@mlc-ai\u002Fweb-llm)\n[![\"WebLLM Chat Deployed\"](https:\u002F\u002Fimg.shields.io\u002Fbadge\u002FWebLLM_Chat-Deployed-%2332a852)](https:\u002F\u002Fchat.webllm.ai\u002F)\n[![Join Discord](https:\u002F\u002Fimg.shields.io\u002Fbadge\u002FJoin-Discord-7289DA?logo=discord&logoColor=white)](https:\u002F\u002Fdiscord.gg\u002F9Xpy2HGBuD)\n[![Related Repository: WebLLM Chat](https:\u002F\u002Fimg.shields.io\u002Fbadge\u002FRelated_Repo-WebLLM_Chat-fafbfc?logo=github)](https:\u002F\u002Fgithub.com\u002Fmlc-ai\u002Fweb-llm-chat\u002F)\n[![Related Repository: MLC LLM](https:\u002F\u002Fimg.shields.io\u002Fbadge\u002FRelated_Repo-MLC_LLM-fafbfc?logo=github)](https:\u002F\u002Fgithub.com\u002Fmlc-ai\u002Fmlc-llm\u002F)\n\n**High-Performance In-Browser LLM Inference Engine.**\n\n[Documentation](https:\u002F\u002Fwebllm.mlc.ai\u002Fdocs\u002F) | [Blogpost](https:\u002F\u002Fblog.mlc.ai\u002F2024\u002F06\u002F13\u002Fwebllm-a-high-performance-in-browser-llm-inference-engine) | [Paper](https:\u002F\u002Farxiv.org\u002Fabs\u002F2412.15803) | [Examples](examples)\n\n\u003C\u002Fdiv>\n\n## Overview\n\nWebLLM is a high-performance in-browser LLM inference engine that brings language model inference directly onto web browsers with hardware acceleration.\nEverything runs inside the browser with no server support and is accelerated with WebGPU.\n\nWebLLM is **fully compatible with [OpenAI API](https:\u002F\u002Fplatform.openai.com\u002Fdocs\u002Fapi-reference\u002Fchat).**\nThat is, you can use the same OpenAI API on **any open source models** locally, with functionalities\nincluding streaming, JSON-mode, function-calling (WIP), etc.\n\nWe can bring a lot of fun opportunities to build AI assistants for everyone and enable privacy while enjoying GPU acceleration.\n\nYou can use WebLLM as a base [npm package](https:\u002F\u002Fwww.npmjs.com\u002Fpackage\u002F@mlc-ai\u002Fweb-llm) and build your own web application on top of it by following the examples below. This project is a companion project of [MLC LLM](https:\u002F\u002Fgithub.com\u002Fmlc-ai\u002Fmlc-llm), which enables universal deployment of LLM across hardware environments.\n\n\u003Cdiv align=\"center\">\n\n**[Check out WebLLM Chat to try it out!](https:\u002F\u002Fchat.webllm.ai\u002F)**\n\n\u003C\u002Fdiv>\n\n## Key Features\n\n- **In-Browser Inference**: WebLLM is a high-performance, in-browser language model inference engine that leverages WebGPU for hardware acceleration, enabling powerful LLM operations directly within web browsers without server-side processing.\n\n- [**Full OpenAI API Compatibility**](#full-openai-compatibility): Seamlessly integrate your app with WebLLM using OpenAI API with functionalities such as streaming, JSON-mode, logit-level control, seeding, and more.\n\n- **Structured JSON Generation**: WebLLM supports state-of-the-art JSON mode structured generation, implemented in the WebAssembly portion of the model library for optimal performance. Check [WebLLM JSON Playground](https:\u002F\u002Fhuggingface.co\u002Fspaces\u002Fmlc-ai\u002FWebLLM-JSON-Playground) on HuggingFace to try generating JSON output with custom JSON schema.\n\n- [**Extensive Model Support**](#built-in-models): WebLLM natively supports a range of models including Llama 3, Phi 3, Gemma, Mistral, Qwen(通义千问), and many others, making it versatile for various AI tasks. For the complete supported model list, check [MLC Models](https:\u002F\u002Fmlc.ai\u002Fmodels).\n\n- [**Custom Model Integration**](#custom-models): Easily integrate and deploy custom models in MLC format, allowing you to adapt WebLLM to specific needs and scenarios, enhancing flexibility in model deployment.\n\n- **Plug-and-Play Integration**: Easily integrate WebLLM into your projects using package managers like NPM and Yarn, or directly via CDN, complete with comprehensive [examples](.\u002Fexamples\u002F) and a modular design for connecting with UI components.\n\n- **Streaming & Real-Time Interactions**: Supports streaming chat completions, allowing real-time output generation which enhances interactive applications like chatbots and virtual assistants.\n\n- **Web Worker & Service Worker Support**: Optimize UI performance and manage the lifecycle of models efficiently by offloading computations to separate worker threads or service workers.\n\n- **Chrome Extension Support**: Extend the functionality of web browsers through custom Chrome extensions using WebLLM, with examples available for building both basic and advanced extensions.\n\n## Built-in Models\n\nCheck the complete list of available models on [MLC Models](https:\u002F\u002Fmlc.ai\u002Fmodels). WebLLM supports a subset of these available models and the list can be accessed at [`prebuiltAppConfig.model_list`](https:\u002F\u002Fgithub.com\u002Fmlc-ai\u002Fweb-llm\u002Fblob\u002Fmain\u002Fsrc\u002Fconfig.ts#L293).\n\nHere are the primary families of models currently supported:\n\n- **Llama**: Llama 3, Llama 2, Hermes-2-Pro-Llama-3\n- **Phi**: Phi 3, Phi 2, Phi 1.5\n- **Gemma**: Gemma-2B\n- **Mistral**: Mistral-7B-v0.3, Hermes-2-Pro-Mistral-7B, NeuralHermes-2.5-Mistral-7B, OpenHermes-2.5-Mistral-7B\n- **Qwen (通义千问)**: Qwen2 0.5B, 1.5B, 7B\n\nIf you need more models, [request a new model via opening an issue](https:\u002F\u002Fgithub.com\u002Fmlc-ai\u002Fweb-llm\u002Fissues\u002Fnew\u002Fchoose) or check [Custom Models](#custom-models) for how to compile and use your own models with WebLLM.\n\n## Jumpstart with Examples\n\nLearn how to use WebLLM to integrate large language models into your application and generate chat completions through this simple Chatbot example:\n\n[![Example Chatbot on JSFiddle](https:\u002F\u002Fimg.shields.io\u002Fbadge\u002FExample-JSFiddle-blue?logo=jsfiddle&logoColor=white)](https:\u002F\u002Fjsfiddle.net\u002Fneetnestor\u002F4nmgvsa2\u002F)\n[![Example Chatbot on Codepen](https:\u002F\u002Fimg.shields.io\u002Fbadge\u002FExample-Codepen-gainsboro?logo=codepen)](https:\u002F\u002Fcodepen.io\u002Fneetnestor\u002Fpen\u002FvYwgZaG)\n\nFor an advanced example of a larger, more complicated project, check [WebLLM Chat](https:\u002F\u002Fgithub.com\u002Fmlc-ai\u002Fweb-llm-chat\u002Fblob\u002Fmain\u002Fapp\u002Fclient\u002Fwebllm.ts).\n\nMore examples for different use cases are available in the [examples](.\u002Fexamples\u002F) folder.\n\n## Get Started\n\nWebLLM offers a minimalist and modular interface to access the chatbot in the browser.\nThe package is designed in a modular way to hook to any of the UI components.\n\n### Installation\n\n#### Package Manager\n\n```sh\n# npm\nnpm install @mlc-ai\u002Fweb-llm\n# yarn\nyarn add @mlc-ai\u002Fweb-llm\n# or pnpm\npnpm install @mlc-ai\u002Fweb-llm\n```\n\nThen import the module in your code.\n\n```typescript\n\u002F\u002F Import everything\nimport * as webllm from \"@mlc-ai\u002Fweb-llm\";\n\u002F\u002F Or only import what you need\nimport { CreateMLCEngine } from \"@mlc-ai\u002Fweb-llm\";\n```\n\n#### CDN Delivery\n\nThanks to [jsdelivr.com](https:\u002F\u002Fwww.jsdelivr.com\u002Fpackage\u002Fnpm\u002F@mlc-ai\u002Fweb-llm), WebLLM can be imported directly through URL and work out-of-the-box on cloud development platforms like [jsfiddle.net](https:\u002F\u002Fjsfiddle.net\u002F), [Codepen.io](https:\u002F\u002Fcodepen.io\u002F), and [Scribbler](https:\u002F\u002Fscribbler.live):\n\n```javascript\nimport * as webllm from \"https:\u002F\u002Fesm.run\u002F@mlc-ai\u002Fweb-llm\";\n```\n\nIt can also be dynamically imported as:\n\n```javascript\nconst webllm = await import(\"https:\u002F\u002Fesm.run\u002F@mlc-ai\u002Fweb-llm\");\n```\n\n### Create MLCEngine\n\nMost operations in WebLLM are invoked through the `MLCEngine` interface. You can create an `MLCEngine` instance and loading the model by calling the `CreateMLCEngine()` factory function.\n\n(Note that loading models requires downloading and it can take a significant amount of time for the very first run without caching previously. You should properly handle this asynchronous call.)\n\n```typescript\nimport { CreateMLCEngine } from \"@mlc-ai\u002Fweb-llm\";\n\n\u002F\u002F Callback function to update model loading progress\nconst initProgressCallback = (initProgress) => {\n  console.log(initProgress);\n};\nconst selectedModel = \"Llama-3.1-8B-Instruct-q4f32_1-MLC\";\n\nconst engine = await CreateMLCEngine(\n  selectedModel,\n  { initProgressCallback: initProgressCallback }, \u002F\u002F engineConfig\n);\n```\n\nUnder the hood, this factory function does the following steps for first creating an engine instance (synchronous) and then loading the model (asynchronous). You can also do them separately in your application.\n\n```typescript\nimport { MLCEngine } from \"@mlc-ai\u002Fweb-llm\";\n\n\u002F\u002F This is a synchronous call that returns immediately\nconst engine = new MLCEngine({\n  initProgressCallback: initProgressCallback,\n});\n\n\u002F\u002F This is an asynchronous call and can take a long time to finish\nawait engine.reload(selectedModel);\n```\n\n### Cache Backend Policy\n\nWebLLM supports three cache backends through `AppConfig.cacheBackend`:\n\n- `\"cache\"`: browser [Cache API](https:\u002F\u002Fdeveloper.mozilla.org\u002Fen-US\u002Fdocs\u002FWeb\u002FAPI\u002FCache) (default).\n- `\"indexeddb\"`: browser [IndexedDB](https:\u002F\u002Fdeveloper.mozilla.org\u002Fen-US\u002Fdocs\u002FWeb\u002FAPI\u002FIndexedDB_API).\n- `\"cross-origin\"`: experimental Chrome [Cross-Origin Storage API](https:\u002F\u002Fgithub.com\u002FWICG\u002Fcross-origin-storage) extension backend. Install the [Cross-Origin Storage extension](https:\u002F\u002Fchromewebstore.google.com\u002Fdetail\u002Fcross-origin-storage\u002Fdenpnpcgjgikjpoglpjefakmdcbmlgih) to use it. (If the extension isn't installed, WebLLM falls back to the default cache automatically.)\n\nExample:\n\n```typescript\nimport { CreateMLCEngine, prebuiltAppConfig } from \"@mlc-ai\u002Fweb-llm\";\n\nconst appConfig = { ...prebuiltAppConfig, cacheBackend: \"cross-origin\" };\nconst engine = await CreateMLCEngine(\"Llama-3.1-8B-Instruct-q4f32_1-MLC\", {\n  appConfig,\n});\n```\n\nNotes:\n- The `\"cross-origin\"` backend requires installing and enabling a compatible browser extension.\n- Cross-origin backend currently does not support programmatic tensor-cache deletion; clearing is extension-managed.\n\n### Chat Completion\n\nAfter successfully initializing the engine, you can now invoke chat completions using OpenAI style chat APIs through the `engine.chat.completions` interface. For the full list of parameters and their descriptions, check [section below](#full-openai-compatibility) and [OpenAI API reference](https:\u002F\u002Fplatform.openai.com\u002Fdocs\u002Fapi-reference\u002Fchat\u002Fcreate).\n\n(Note: The `model` parameter is not supported and will be ignored here. Instead, call `CreateMLCEngine(model)` or `engine.reload(model)` instead as shown in the [Create MLCEngine](#create-mlcengine) above.)\n\n```typescript\nconst messages = [\n  { role: \"system\", content: \"You are a helpful AI assistant.\" },\n  { role: \"user\", content: \"Hello!\" },\n];\n\nconst reply = await engine.chat.completions.create({\n  messages,\n});\nconsole.log(reply.choices[0].message);\nconsole.log(reply.usage);\n```\n\n### Streaming\n\nWebLLM also supports streaming chat completion generating. To use it, simply pass `stream: true` to the `engine.chat.completions.create` call.\n\n```typescript\nconst messages = [\n  { role: \"system\", content: \"You are a helpful AI assistant.\" },\n  { role: \"user\", content: \"Hello!\" },\n];\n\n\u002F\u002F Chunks is an AsyncGenerator object\nconst chunks = await engine.chat.completions.create({\n  messages,\n  temperature: 1,\n  stream: true, \u002F\u002F \u003C-- Enable streaming\n  stream_options: { include_usage: true },\n});\n\nlet reply = \"\";\nfor await (const chunk of chunks) {\n  reply += chunk.choices[0]?.delta.content || \"\";\n  console.log(reply);\n  if (chunk.usage) {\n    console.log(chunk.usage); \u002F\u002F only last chunk has usage\n  }\n}\n\nconst fullReply = await engine.getMessage();\nconsole.log(fullReply);\n```\n\n## Advanced Usage\n\n### Using Workers\n\nYou can put the heavy computation in a worker script to optimize your application performance. To do so, you need to:\n\n1. Create a handler in the worker thread that communicates with the frontend while handling the requests.\n2. Create a Worker Engine in your main application, which under the hood sends messages to the handler in the worker thread.\n\nFor detailed implementations of different kinds of Workers, check the following sections.\n\n#### Dedicated Web Worker\n\nWebLLM comes with API support for WebWorker so you can hook\nthe generation process into a separate worker thread so that\nthe computing in the worker thread won't disrupt the UI.\n\nWe create a handler in the worker thread that communicates with the frontend while handling the requests.\n\n```typescript\n\u002F\u002F worker.ts\nimport { WebWorkerMLCEngineHandler } from \"@mlc-ai\u002Fweb-llm\";\n\n\u002F\u002F A handler that resides in the worker thread\nconst handler = new WebWorkerMLCEngineHandler();\nself.onmessage = (msg: MessageEvent) => {\n  handler.onmessage(msg);\n};\n```\n\nIn the main logic, we create a `WebWorkerMLCEngine` that\nimplements the same `MLCEngineInterface`. The rest of the logic remains the same.\n\n```typescript\n\u002F\u002F main.ts\nimport { CreateWebWorkerMLCEngine } from \"@mlc-ai\u002Fweb-llm\";\n\nasync function main() {\n  \u002F\u002F Use a WebWorkerMLCEngine instead of MLCEngine here\n  const engine = await CreateWebWorkerMLCEngine(\n    new Worker(new URL(\".\u002Fworker.ts\", import.meta.url), {\n      type: \"module\",\n    }),\n    selectedModel,\n    { initProgressCallback }, \u002F\u002F engineConfig\n  );\n\n  \u002F\u002F everything else remains the same\n}\n```\n\n### Use Service Worker\n\nWebLLM comes with API support for ServiceWorker so you can hook the generation process\ninto a service worker to avoid reloading the model in every page visit and optimize\nyour application's offline experience.\n\n(Note, Service Worker's life cycle is managed by the browser and can be killed any time without notifying the webapp. `ServiceWorkerMLCEngine` will try to keep the service worker thread alive by periodically sending heartbeat events, but your application should also include proper error handling. Check `keepAliveMs` and `missedHeatbeat` in [`ServiceWorkerMLCEngine`](https:\u002F\u002Fgithub.com\u002Fmlc-ai\u002Fweb-llm\u002Fblob\u002Fmain\u002Fsrc\u002Fservice_worker.ts#L234) for more details.)\n\nWe create a handler in the worker thread that communicates with the frontend while handling the requests.\n\n```typescript\n\u002F\u002F sw.ts\nimport { ServiceWorkerMLCEngineHandler } from \"@mlc-ai\u002Fweb-llm\";\n\nlet handler: ServiceWorkerMLCEngineHandler;\n\nself.addEventListener(\"activate\", function (event) {\n  handler = new ServiceWorkerMLCEngineHandler();\n  console.log(\"Service Worker is ready\");\n});\n```\n\nThen in the main logic, we register the service worker and create the engine using\n`CreateServiceWorkerMLCEngine` function. The rest of the logic remains the same.\n\n```typescript\n\u002F\u002F main.ts\nimport {\n  MLCEngineInterface,\n  CreateServiceWorkerMLCEngine,\n} from \"@mlc-ai\u002Fweb-llm\";\n\nif (\"serviceWorker\" in navigator) {\n  navigator.serviceWorker.register(\n    new URL(\"sw.ts\", import.meta.url), \u002F\u002F worker script\n    { type: \"module\" },\n  );\n}\n\nconst engine: MLCEngineInterface = await CreateServiceWorkerMLCEngine(\n  selectedModel,\n  { initProgressCallback }, \u002F\u002F engineConfig\n);\n```\n\nYou can find a complete example on how to run WebLLM in service worker in [examples\u002Fservice-worker](examples\u002Fservice-worker\u002F).\n\n### Chrome Extension\n\nYou can also find examples of building Chrome extension with WebLLM in [examples\u002Fchrome-extension](examples\u002Fchrome-extension\u002F) and [examples\u002Fchrome-extension-webgpu-service-worker](examples\u002Fchrome-extension-webgpu-service-worker\u002F). The latter one leverages service worker, so the extension is persistent in the background. Additionally, you can explore another full project of a Chrome extension, WebLLM Assistant, which leverages WebLLM [here](https:\u002F\u002Fgithub.com\u002Fmlc-ai\u002Fweb-llm-assistant).\n\n## Full OpenAI Compatibility\n\nWebLLM is designed to be fully compatible with [OpenAI API](https:\u002F\u002Fplatform.openai.com\u002Fdocs\u002Fapi-reference\u002Fchat). Thus, besides building a simple chatbot, you can also have the following functionalities with WebLLM:\n\n- [streaming](examples\u002Fstreaming): return output as chunks in real-time in the form of an AsyncGenerator\n- [json-mode](examples\u002Fjson-mode): efficiently ensure output is in JSON format, see [OpenAI Reference](https:\u002F\u002Fplatform.openai.com\u002Fdocs\u002Fguides\u002Ftext-generation\u002Fchat-completions-api) for more.\n- [seed-to-reproduce](examples\u002Fseed-to-reproduce): use seeding to ensure a reproducible output with fields `seed`.\n- [function-calling](examples\u002Ffunction-calling) (WIP): function calling with fields `tools` and `tool_choice` (with preliminary support); or manual function calling without `tools` or `tool_choice` (keeps the most flexibility).\n\n## Integrity Verification\n\nWebLLM supports optional integrity verification for model artifacts using\n[SRI (Subresource Integrity)](https:\u002F\u002Fdeveloper.mozilla.org\u002Fen-US\u002Fdocs\u002FWeb\u002FSecurity\u002FSubresource_Integrity) hashes.\nWhen the `integrity` field is set on a `ModelRecord`, WebLLM will verify the downloaded config,\nWASM, and tokenizer files against the provided hashes before loading.\n\n```typescript\nimport { CreateMLCEngine } from \"@mlc-ai\u002Fweb-llm\";\n\nconst appConfig = {\n  model_list: [\n    {\n      model: \"https:\u002F\u002Fhuggingface.co\u002Fmlc-ai\u002FLlama-3.2-1B-Instruct-q4f16_1-MLC\",\n      model_id: \"Llama-3.2-1B-Instruct-q4f16_1-MLC\",\n      model_lib:\n        \"https:\u002F\u002Fraw.githubusercontent.com\u002Fuser\u002Fmodel-libs\u002Fmain\u002Fmodel.wasm\",\n      integrity: {\n        config: \"sha256-\u003Cbase64-hash-of-mlc-chat-config.json>\",\n        model_lib: \"sha256-\u003Cbase64-hash-of-wasm-file>\",\n        tokenizer: {\n          \"tokenizer.json\": \"sha256-\u003Cbase64-hash-of-tokenizer.json>\",\n        },\n        onFailure: \"error\", \u002F\u002F \"error\" (default) throws IntegrityError, \"warn\" logs and continues\n      },\n    },\n  ],\n};\n\nconst engine = await CreateMLCEngine(\"Llama-3.2-1B-Instruct-q4f16_1-MLC\", {\n  appConfig,\n});\n```\n\nYou can generate SRI hashes for model files with:\n\n```bash\n# SHA-256\nopenssl dgst -sha256 -binary \u003Cfile> | openssl base64 -A | sed 's\u002F^\u002Fsha256-\u002F'\n# SHA-384\nopenssl dgst -sha384 -binary \u003Cfile> | openssl base64 -A | sed 's\u002F^\u002Fsha384-\u002F'\n# SHA-512\nopenssl dgst -sha512 -binary \u003Cfile> | openssl base64 -A | sed 's\u002F^\u002Fsha512-\u002F'\n```\n\n> The `openssl` commands require a Unix-like shell (macOS\u002FLinux). On Windows, run `openssl` via [Git Bash](https:\u002F\u002Fgitforwindows.org\u002F) or [WSL](https:\u002F\u002Flearn.microsoft.com\u002Fen-us\u002Fwindows\u002Fwsl\u002F).\n\nIf a hash does not match, an `IntegrityError` is thrown (or a warning is logged when `onFailure: \"warn\"`).\nAll fields in `integrity` are optional — only specified artifacts will be verified.\nWhen the `integrity` field is omitted entirely, WebLLM behaves exactly as before (no verification).\n\nSee the [integrity-verification example](examples\u002Fintegrity-verification\u002F) for a complete working demo.\n\n## Custom Models\n\nWebLLM works as a companion project of [MLC LLM](https:\u002F\u002Fgithub.com\u002Fmlc-ai\u002Fmlc-llm) and it supports custom models in MLC format.\nIt reuses the model artifact and builds the flow of MLC LLM. To compile and use your own models with WebLLM, please check out\n[MLC LLM document](https:\u002F\u002Fllm.mlc.ai\u002Fdocs\u002Fdeploy\u002Fwebllm.html)\non how to compile and deploy new model weights and libraries to WebLLM.\n\nHere, we go over the high-level idea. There are two elements of the WebLLM package that enable new models and weight variants.\n\n- `model`: Contains a URL to model artifacts, such as weights and meta-data.\n- `model_lib`: A URL to the web assembly library (i.e. wasm file) that contains the executables to accelerate the model computations.\n\nBoth are customizable in the WebLLM.\n\n```typescript\nimport { CreateMLCEngine } from \"@mlc-ai\u002Fweb-llm\";\n\nasync main() {\n  const appConfig = {\n    \"model_list\": [\n      {\n        \"model\": \"\u002Furl\u002Fto\u002Fmy\u002Fllama\",\n        \"model_id\": \"MyLlama-3b-v1-q4f32_0\",\n        \"model_lib\": \"\u002Furl\u002Fto\u002Fmyllama3b.wasm\",\n      }\n    ],\n  };\n  \u002F\u002F override default\n  const chatOpts = {\n    \"repetition_penalty\": 1.01\n  };\n\n  \u002F\u002F load a prebuilt model\n  \u002F\u002F with a chat option override and app config\n  \u002F\u002F under the hood, it will load the model from myLlamaUrl\n  \u002F\u002F and cache it in the browser cache\n  \u002F\u002F The chat will also load the model library from \"\u002Furl\u002Fto\u002Fmyllama3b.wasm\",\n  \u002F\u002F assuming that it is compatible to the model in myLlamaUrl.\n  const engine = await CreateMLCEngine(\n    \"MyLlama-3b-v1-q4f32_0\",\n    { appConfig }, \u002F\u002F engineConfig\n    chatOpts,\n  );\n}\n```\n\nIn many cases, we only want to supply the model weight variant, but\nnot necessarily a new model (e.g. `NeuralHermes-Mistral` can reuse `Mistral`'s\nmodel library). For examples of how a model library can be shared by different model variants,\nsee `webllm.prebuiltAppConfig`.\n\n## Build WebLLM Package From Source\n\nNOTE: you don't need to build from source unless you would like to modify the WebLLM package.\nTo use the npm, simply follow [Get Started](#get-started) or any of the [examples](examples) instead.\n\nTo build from source, simply run:\n\n```bash\nnpm install\nnpm run build\n```\n\nThen, to test the effects of your code change in an example, inside `examples\u002Fget-started\u002Fpackage.json`, change from `\"@mlc-ai\u002Fweb-llm\": \"^0.2.82\"` to `\"@mlc-ai\u002Fweb-llm\": ..\u002F..`.\n\nThen run:\n\n```bash\ncd examples\u002Fget-started\nnpm install\nnpm start\n```\n\nNote that sometimes you would need to switch between `file:..\u002F..` and `..\u002F..` to trigger npm to recognize new changes. In the worst case, you can run:\n\n```bash\ncd examples\u002Fget-started\nrm -rf node_modules dist package-lock.json .parcel-cache\nnpm install\nnpm start\n```\n\n### In case you need to build TVMjs from source\n\nWebLLM's runtime largely depends on TVMjs: https:\u002F\u002Fgithub.com\u002Fapache\u002Ftvm\u002Ftree\u002Fmain\u002Fweb\n\nWhile it is also available as an npm package: https:\u002F\u002Fwww.npmjs.com\u002Fpackage\u002F@mlc-ai\u002Fweb-runtime, you can build it from source if needed by following the steps below.\n\n1. Install [emscripten](https:\u002F\u002Femscripten.org). It is an LLVM-based compiler that compiles C\u002FC++ source code to WebAssembly.\n   - Follow the [installation instruction](https:\u002F\u002Femscripten.org\u002Fdocs\u002Fgetting_started\u002Fdownloads.html#installation-instructions-using-the-emsdk-recommended) to install the latest emsdk.\n   - Source `emsdk_env.sh` by `source path\u002Fto\u002Femsdk_env.sh`, so that `emcc` is reachable from PATH and the command `emcc` works.\n\n   We can verify the successful installation by trying out `emcc` terminal.\n\n   Note: We recently found that using the latest `emcc` version may run into issues during runtime. Use `.\u002Femsdk install 3.1.56` instead of `.\u002Femsdk install latest` for now as a workaround. The error may look like\n\n   ```\n   Init error, LinkError: WebAssembly.instantiate(): Import #6 module=\"wasi_snapshot_preview1\"\n   function=\"proc_exit\": function import requires a callable\n   ```\n\n2. In `.\u002Fpackage.json`, change from `\"@mlc-ai\u002Fweb-runtime\": \"0.18.0-dev2\",` to `\"@mlc-ai\u002Fweb-runtime\": \"file:.\u002Ftvm_home\u002Fweb\",`.\n\n3. Setup necessary environment\n\n   Prepare all the necessary dependencies for web build:\n\n   ```shell\n   .\u002Fscripts\u002Fprep_deps.sh\n   ```\n\n   In this step, if `$TVM_SOURCE_DIR` is not defined in the environment, we will execute the following line to build `tvmjs` dependency:\n\n   ```shell\n   git clone https:\u002F\u002Fgithub.com\u002Fmlc-ai\u002Frelax 3rdparty\u002Ftvm-unity --recursive\n   ```\n\n   This clones the current HEAD of `mlc-ai\u002Frelax`. However, it may not always be the correct branch or commit to clone. To build a specific npm version from source, refer to the version bump PR, which states which branch (i.e. `mlc-ai\u002Frelax` or `apache\u002Ftvm`) and which commit the current WebLLM version depends on. For instance, version 0.2.52, according to its version bump PR https:\u002F\u002Fgithub.com\u002Fmlc-ai\u002Fweb-llm\u002Fpull\u002F521, is built by checking out the following commit https:\u002F\u002Fgithub.com\u002Fapache\u002Ftvm\u002Fcommit\u002Fe6476847753c80e054719ac47bc2091c888418b6 in `apache\u002Ftvm`, rather than the HEAD of `mlc-ai\u002Frelax`.\n\n   Besides, `--recursive` is necessary and important. Otherwise, you may encounter errors like `fatal error: 'dlpack\u002Fdlpack.h' file not found`.\n\n4. Build WebLLM Package\n\n   ```shell\n   npm run build\n   ```\n\n5. Validate some of the sub-packages\n\n   You can then go to the subfolders in [examples](examples) to validate some of the sub-packages.\n   We use Parcelv2 for bundling. Although Parcel is not very good at tracking parent directory\n   changes sometimes. When you make a change in the WebLLM package, try to edit the `package.json`\n   of the subfolder and save it, which will trigger Parcel to rebuild.\n\n## Links\n\n- [Demo App: WebLLM Chat](https:\u002F\u002Fchat.webllm.ai\u002F)\n- If you want to run LLM on native runtime, check out [MLC-LLM](https:\u002F\u002Fgithub.com\u002Fmlc-ai\u002Fmlc-llm)\n- You might also be interested in [Web Stable Diffusion](https:\u002F\u002Fgithub.com\u002Fmlc-ai\u002Fweb-stable-diffusion\u002F).\n\n## Acknowledgement\n\nThis project is initiated by members from CMU Catalyst, UW SAMPL, SJTU, OctoML, and the MLC community. We would love to continue developing and supporting the open-source ML community.\n\nThis project is only possible thanks to the shoulders open-source ecosystems that we stand on. We want to thank the Apache TVM community and developers of the TVM Unity effort. The open-source ML community members made these models publicly available. PyTorch and Hugging Face communities make these models accessible. We would like to thank the teams behind Vicuna, SentencePiece, LLaMA, and Alpaca. We also would like to thank the WebAssembly, Emscripten, and WebGPU communities. Finally, thanks to Dawn and WebGPU developers.\n\n## Citation\n\nIf you find this project to be useful, please cite:\n\n```\n@misc{ruan2024webllmhighperformanceinbrowserllm,\n      title={WebLLM: A High-Performance In-Browser LLM Inference Engine},\n      author={Charlie F. Ruan and Yucheng Qin and Xun Zhou and Ruihang Lai and Hongyi Jin and Yixin Dong and Bohan Hou and Meng-Shiun Yu and Yiyan Zhai and Sudeep Agarwal and Hangrui Cao and Siyuan Feng and Tianqi Chen},\n      year={2024},\n      eprint={2412.15803},\n      archivePrefix={arXiv},\n      primaryClass={cs.LG},\n      url={https:\u002F\u002Farxiv.org\u002Fabs\u002F2412.15803},\n}\n```\n\n## Contributors\n\n\u003Ca href=\"https:\u002F\u002Fgithub.com\u002Fmlc-ai\u002Fweb-llm\u002Fgraphs\u002Fcontributors\">\n  \u003Cimg alt=\"contributors\" src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fmlc-ai_web-llm_readme_6d03a6b4861b.png\"\u002F>\n\u003C\u002Fa>\n\n\u003Cp align=\"right\">\n  \u003Ca href=\"#top\">⬆ Back to Top ⬆\u003C\u002Fa>\n\u003C\u002Fp>\n","\u003Cdiv align=\"center\" id=\"top\">\n\n# WebLLM\n\n[![NPM Package](https:\u002F\u002Fimg.shields.io\u002Fbadge\u002FNPM_Package-Published-cc3534)](https:\u002F\u002Fwww.npmjs.com\u002Fpackage\u002F@mlc-ai\u002Fweb-llm)\n[![\"WebLLM Chat Deployed\"](https:\u002F\u002Fimg.shields.io\u002Fbadge\u002FWebLLM_Chat-Deployed-%2332a852)](https:\u002F\u002Fchat.webllm.ai\u002F)\n[![Join Discord](https:\u002F\u002Fimg.shields.io\u002Fbadge\u002FJoin-Discord-7289DA?logo=discord&logoColor=white)](https:\u002F\u002Fdiscord.gg\u002F9Xpy2HGBuD)\n[![Related Repository: WebLLM Chat](https:\u002F\u002Fimg.shields.io\u002Fbadge\u002FRelated_Repo-WebLLM_Chat-fafbfc?logo=github)](https:\u002F\u002Fgithub.com\u002Fmlc-ai\u002Fweb-llm-chat\u002F)\n[![Related Repository: MLC LLM](https:\u002F\u002Fimg.shields.io\u002Fbadge\u002FRelated_Repo-MLC_LLM-fafbfc?logo=github)](https:\u002F\u002Fgithub.com\u002Fmlc-ai\u002Fmlc-llm\u002F)\n\n**高性能的浏览器内LLM推理引擎。**\n\n[文档](https:\u002F\u002Fwebllm.mlc.ai\u002Fdocs\u002F) | [博客文章](https:\u002F\u002Fblog.mlc.ai\u002F2024\u002F06\u002F13\u002Fwebllm-a-high-performance-in-browser-llm-inference-engine) | [论文](https:\u002F\u002Farxiv.org\u002Fabs\u002F2412.15803) | [示例](examples)\n\n\u003C\u002Fdiv>\n\n## 概述\n\nWebLLM 是一款高性能的浏览器内LLM推理引擎，它通过硬件加速将语言模型推理直接带到网页浏览器中。\n所有计算都在浏览器内部完成，无需服务器支持，并且借助WebGPU进行加速。\n\nWebLLM **完全兼容[OpenAI API](https:\u002F\u002Fplatform.openai.com\u002Fdocs\u002Fapi-reference\u002Fchat)**。\n也就是说，你可以在本地使用相同的OpenAI API调用**任何开源模型**，并享受流式响应、JSON模式、函数调用（开发中）等功能。\n\n这为我们带来了许多有趣的机会，可以为每个人构建AI助手，在保护隐私的同时享受GPU加速带来的性能提升。\n\n你可以将WebLLM作为一个基础的[NPM包](https:\u002F\u002Fwww.npmjs.com\u002Fpackage\u002F@mlc-ai\u002Fweb-llm)，并参考下面的示例来构建自己的Web应用。该项目是[MLC LLM](https:\u002F\u002Fgithub.com\u002Fmlc-ai\u002Fmlc-llm)的配套项目，后者实现了LLM在各种硬件环境中的通用部署。\n\n\u003Cdiv align=\"center\">\n\n**[立即体验WebLLM Chat！](https:\u002F\u002Fchat.webllm.ai\u002F)**\n\n\u003C\u002Fdiv>\n\n## 核心特性\n\n- **浏览器内推理**：WebLLM是一款高性能的浏览器内语言模型推理引擎，利用WebGPU进行硬件加速，能够在不依赖服务器的情况下直接在浏览器中运行强大的LLM任务。\n  \n- [**完全兼容OpenAI API**](#full-openai-compatibility)：通过OpenAI API无缝集成你的应用与WebLLM，支持流式响应、JSON模式、对logit级别的控制、种子设置等功能。\n\n- **结构化JSON生成**：WebLLM支持最先进的JSON模式结构化生成功能，该功能在模型库的WebAssembly部分实现，以确保最佳性能。你可以在HuggingFace上访问[WebLLM JSON Playground](https:\u002F\u002Fhuggingface.co\u002Fspaces\u002Fmlc-ai\u002FWebLLM-JSON-Playground)，尝试使用自定义JSON模式生成JSON输出。\n\n- [**广泛的模型支持**](#built-in-models)：WebLLM原生支持一系列模型，包括Llama 3、Phi 3、Gemma、Mistral、Qwen（通义千问）等，使其适用于多种AI任务。完整的支持模型列表请参阅[MLC Models](https:\u002F\u002Fmlc.ai\u002Fmodels)。\n\n- [**自定义模型集成**](#custom-models)：轻松集成和部署MLC格式的自定义模型，使你能够根据特定需求和场景调整WebLLM，从而提高模型部署的灵活性。\n\n- **即插即用的集成方式**：可以通过NPM、Yarn等包管理器，或直接通过CDN轻松将WebLLM集成到你的项目中，并配有全面的[示例](.\u002Fexamples\u002F)和模块化的设计，方便与UI组件对接。\n\n- **流式传输与实时交互**：支持流式聊天补全，允许实时生成输出，从而增强聊天机器人和虚拟助手等交互式应用的体验。\n\n- **Web Worker与Service Worker支持**：通过将计算任务卸载到独立的工作线程或服务工作者中，优化UI性能并高效管理模型的生命周期。\n\n- **Chrome扩展支持**：利用WebLLM通过自定义Chrome扩展来扩展浏览器的功能，我们提供了构建基础和高级扩展的示例。\n\n## 内置模型\n\n完整的可用模型列表请参见[MLC Models](https:\u002F\u002Fmlc.ai\u002Fmodels)。WebLLM支持其中的一部分模型，具体列表可在[`prebuiltAppConfig.model_list`](https:\u002F\u002Fgithub.com\u002Fmlc-ai\u002Fweb-llm\u002Fblob\u002Fmain\u002Fsrc\u002Fconfig.ts#L293)中找到。\n\n目前主要支持的模型系列如下：\n\n- **Llama**：Llama 3、Llama 2、Hermes-2-Pro-Llama-3\n- **Phi**：Phi 3、Phi 2、Phi 1.5\n- **Gemma**：Gemma-2B\n- **Mistral**：Mistral-7B-v0.3、Hermes-2-Pro-Mistral-7B、NeuralHermes-2.5-Mistral-7B、OpenHermes-2.5-Mistral-7B\n- **Qwen（通义千问）**：Qwen2 0.5B、1.5B、7B\n\n如果你需要更多模型，可以通过[提交issue请求新模型](https:\u002F\u002Fgithub.com\u002Fmlc-ai\u002Fweb-llm\u002Fissues\u002Fnew\u002Fchoose)，或者查看[自定义模型](#custom-models)部分，了解如何编译并使用自己的模型与WebLLM结合。\n\n## 从示例开始\n\n通过这个简单的聊天机器人示例，学习如何使用WebLLM将大型语言模型集成到你的应用中，并生成聊天回复：\n\n[![JSFiddle上的示例聊天机器人](https:\u002F\u002Fimg.shields.io\u002Fbadge\u002FExample-JSFiddle-blue?logo=jsfiddle&logoColor=white)](https:\u002F\u002Fjsfiddle.net\u002Fneetnestor\u002F4nmgvsa2\u002F)\n[![Codepen上的示例聊天机器人](https:\u002F\u002Fimg.shields.io\u002Fbadge\u002FExample-Codepen-gainsboro?logo=codepen)](https:\u002F\u002Fcodepen.io\u002Fneetnestor\u002Fpen\u002FvYwgZaG)\n\n如果你想了解一个更复杂、规模更大的项目示例，请查看[WebLLM Chat](https:\u002F\u002Fgithub.com\u002Fmlc-ai\u002Fweb-llm-chat\u002Fblob\u002Fmain\u002Fapp\u002Fclient\u002Fwebllm.ts)。\n\n更多不同用例的示例可在[examples](.\u002Fexamples\u002F)文件夹中找到。\n\n## 开始使用\n\nWebLLM提供了一个极简且模块化的接口，用于在浏览器中访问聊天机器人。\n该软件包采用模块化设计，可与任何UI组件无缝对接。\n\n### 安装\n\n#### 包管理器\n\n```sh\n# npm\nnpm install @mlc-ai\u002Fweb-llm\n# yarn\nyarn add @mlc-ai\u002Fweb-llm\n# 或 pnpm\npnpm install @mlc-ai\u002Fweb-llm\n```\n\n然后在你的代码中导入模块。\n\n```typescript\n\u002F\u002F 导入全部内容\nimport * as webllm from \"@mlc-ai\u002Fweb-llm\";\n\u002F\u002F 或仅导入你需要的部分\nimport { CreateMLCEngine } from \"@mlc-ai\u002Fweb-llm\";\n```\n\n#### CDN交付\n\n借助[jsdelivr.com](https:\u002F\u002Fwww.jsdelivr.com\u002Fpackage\u002Fnpm\u002F@mlc-ai\u002Fweb-llm)，WebLLM可以直接通过URL引入，并在云开发平台如[jsfiddle.net](https:\u002F\u002Fjsfiddle.net\u002F)、[Codepen.io](https:\u002F\u002Fcodepen.io\u002F)和[Scribbler](https:\u002F\u002Fscribbler.live)上开箱即用：\n\n```javascript\nimport * as webllm from \"https:\u002F\u002Fesm.run\u002F@mlc-ai\u002Fweb-llm\";\n```\n\n也可以动态导入：\n\n```javascript\nconst webllm = await import(\"https:\u002F\u002Fesm.run\u002F@mlc-ai\u002Fweb-llm\");\n```\n\n### 创建 MLCEngine\n\nWebLLM 中的大多数操作都是通过 `MLCEngine` 接口调用的。你可以通过调用 `CreateMLCEngine()` 工厂函数来创建一个 `MLCEngine` 实例并加载模型。\n\n（注意：加载模型需要下载，首次运行且未使用缓存时可能需要较长时间。你应该妥善处理这个异步调用。）\n\n```typescript\nimport { CreateMLCEngine } from \"@mlc-ai\u002Fweb-llm\";\n\n\u002F\u002F 用于更新模型加载进度的回调函数\nconst initProgressCallback = (initProgress) => {\n  console.log(initProgress);\n};\nconst selectedModel = \"Llama-3.1-8B-Instruct-q4f32_1-MLC\";\n\nconst engine = await CreateMLCEngine(\n  selectedModel,\n  { initProgressCallback: initProgressCallback }, \u002F\u002F engineConfig\n);\n```\n\n在底层，这个工厂函数会先同步地创建一个引擎实例，然后再异步地加载模型。你也可以在应用中分别执行这些步骤。\n\n```typescript\nimport { MLCEngine } from \"@mlc-ai\u002Fweb-llm\";\n\n\u002F\u002F 这是一个立即返回的同步调用\nconst engine = new MLCEngine({\n  initProgressCallback: initProgressCallback,\n});\n\n\u002F\u002F 这是一个异步调用，可能需要较长时间才能完成\nawait engine.reload(selectedModel);\n```\n\n### 缓存后端策略\n\nWebLLM 通过 `AppConfig.cacheBackend` 支持三种缓存后端：\n\n- `\"cache\"`：浏览器 [Cache API](https:\u002F\u002Fdeveloper.mozilla.org\u002Fen-US\u002Fdocs\u002FWeb\u002FAPI\u002FCache)（默认）。\n- `\"indexeddb\"`：浏览器 [IndexedDB](https:\u002F\u002Fdeveloper.mozilla.org\u002Fen-US\u002Fdocs\u002FWeb\u002FAPI\u002FIndexedDB_API)。\n- `\"cross-origin\"`：实验性的 Chrome [跨域存储 API](https:\u002F\u002Fgithub.com\u002FWICG\u002Fcross-origin-storage) 扩展后端。你需要安装 [跨域存储扩展](https:\u002F\u002Fchromewebstore.google.com\u002Fdetail\u002Fcross-origin-storage\u002Fdenpnpcgjgikjpoglpjefakmdcbmlgih) 才能使用它。（如果未安装该扩展，WebLLM 会自动回退到默认缓存。）\n\n示例：\n\n```typescript\nimport { CreateMLCEngine, prebuiltAppConfig } from \"@mlc-ai\u002Fweb-llm\";\n\nconst appConfig = { ...prebuiltAppConfig, cacheBackend: \"cross-origin\" };\nconst engine = await CreateMLCEngine(\"Llama-3.1-8B-Instruct-q4f32_1-MLC\", {\n  appConfig,\n});\n```\n\n注意事项：\n- `\"cross-origin\"` 后端需要安装并启用兼容的浏览器扩展。\n- 跨域后端目前不支持以编程方式删除张量缓存；清除操作由扩展管理。\n\n### 对话完成\n\n成功初始化引擎后，你现在可以使用 OpenAI 风格的聊天 API，通过 `engine.chat.completions` 接口调用对话完成。有关完整参数列表及其说明，请参阅[下方章节](#full-openai-compatibility)以及 [OpenAI API 参考文档](https:\u002F\u002Fplatform.openai.com\u002Fdocs\u002Fapi-reference\u002Fchat\u002Fcreate)。\n\n（注意：此处不支持 `model` 参数，该参数将被忽略。请改用上面 [创建 MLCEngine](#create-mlcengine) 中所示的 `CreateMLCEngine(model)` 或 `engine.reload(model)`。）\n\n```typescript\nconst messages = [\n  { role: \"system\", content: \"你是一位乐于助人的 AI 助手。\" },\n  { role: \"user\", content: \"你好！\" },\n];\n\nconst reply = await engine.chat.completions.create({\n  messages,\n});\nconsole.log(reply.choices[0].message);\nconsole.log(reply.usage);\n```\n\n### 流式传输\n\nWebLLM 还支持流式生成对话完成结果。要使用此功能，只需在调用 `engine.chat.completions.create` 时传递 `stream: true` 即可。\n\n```typescript\nconst messages = [\n  { role: \"system\", content: \"你是一位乐于助人的 AI 助手。\" },\n  { role: \"user\", content: \"你好！\" },\n];\n\n\u002F\u002F chunks 是一个异步生成器对象\nconst chunks = await engine.chat.completions.create({\n  messages,\n  temperature: 1,\n  stream: true, \u002F\u002F \u003C-- 启用流式传输\n  stream_options: { include_usage: true },\n});\n\nlet reply = \"\";\nfor await (const chunk of chunks) {\n  reply += chunk.choices[0]?.delta.content || \"\";\n  console.log(reply);\n  if (chunk.usage) {\n    console.log(chunk.usage); \u002F\u002F 只有最后一个块包含 usage 信息\n  }\n}\n\nconst fullReply = await engine.getMessage();\nconsole.log(fullReply);\n```\n\n## 高级用法\n\n### 使用 Worker\n\n你可以将繁重的计算任务放到 worker 脚本中，以优化应用性能。为此，你需要：\n\n1. 在 worker 线程中创建一个与前端通信并处理请求的处理器。\n2. 在主应用中创建一个 Worker Engine，它会在后台向 worker 线程中的处理器发送消息。\n\n有关不同类型 Worker 的详细实现，请参阅以下章节。\n\n#### 专用 Web Worker\n\nWebLLM 提供对 WebWorker 的 API 支持，因此你可以将生成过程挂载到一个独立的 worker 线程中，这样 worker 线程中的计算就不会阻塞 UI。\n\n我们在 worker 线程中创建了一个与前端通信并处理请求的处理器。\n\n```typescript\n\u002F\u002F worker.ts\nimport { WebWorkerMLCEngineHandler } from \"@mlc-ai\u002Fweb-llm\";\n\n\u002F\u002F 居住在 worker 线程中的处理器\nconst handler = new WebWorkerMLCEngineHandler();\nself.onmessage = (msg: MessageEvent) => {\n  handler.onmessage(msg);\n};\n```\n\n在主逻辑中，我们创建了一个 `WebWorkerMLCEngine`，它实现了相同的 `MLCEngineInterface`。其余逻辑保持不变。\n\n```typescript\n\u002F\u002F main.ts\nimport { CreateWebWorkerMLCEngine } from \"@mlc-ai\u002Fweb-llm\";\n\nasync function main() {\n  \u002F\u002F 此处使用 WebWorkerMLCEngine 而不是 MLCEngine\n  const engine = await CreateWebWorkerMLCEngine(\n    new Worker(new URL(\".\u002Fworker.ts\", import.meta.url), {\n      type: \"module\",\n    }),\n    selectedModel,\n    { initProgressCallback }, \u002F\u002F engineConfig\n  );\n\n  \u002F\u002F 其余部分保持不变\n}\n```\n\n### 使用 Service Worker\n\nWebLLM 提供了对 ServiceWorker 的 API 支持，因此你可以将生成过程挂载到 Service Worker 中，以避免每次访问页面时都重新加载模型，并优化应用的离线体验。\n\n（注意，Service Worker 的生命周期由浏览器管理，可能会在任何时候被终止而不会通知 Web 应用。`ServiceWorkerMLCEngine` 会通过定期发送心跳事件来尝试保持 Service Worker 线程的存活，但你的应用也应包含适当的错误处理逻辑。更多详情请参阅 [`ServiceWorkerMLCEngine`](https:\u002F\u002Fgithub.com\u002Fmlc-ai\u002Fweb-llm\u002Fblob\u002Fmain\u002Fsrc\u002Fservice_worker.ts#L234) 中的 `keepAliveMs` 和 `missedHeatbeat`。）\n\n我们在 Worker 线程中创建了一个处理器，用于与前端通信并处理请求。\n\n```typescript\n\u002F\u002F sw.ts\nimport { ServiceWorkerMLCEngineHandler } from \"@mlc-ai\u002Fweb-llm\";\n\nlet handler: ServiceWorkerMLCEngineHandler;\n\nself.addEventListener(\"activate\", function (event) {\n  handler = new ServiceWorkerMLCEngineHandler();\n  console.log(\"Service Worker is ready\");\n});\n```\n\n然后在主逻辑中，我们注册 Service Worker 并使用 `CreateServiceWorkerMLCEngine` 函数创建引擎。其余逻辑保持不变。\n\n```typescript\n\u002F\u002F main.ts\nimport {\n  MLCEngineInterface,\n  CreateServiceWorkerMLCEngine,\n} from \"@mlc-ai\u002Fweb-llm\";\n\nif (\"serviceWorker\" in navigator) {\n  navigator.serviceWorker.register(\n    new URL(\"sw.ts\", import.meta.url), \u002F\u002F Worker 脚本\n    { type: \"module\" },\n  );\n}\n\nconst engine: MLCEngineInterface = await CreateServiceWorkerMLCEngine(\n  selectedModel,\n  { initProgressCallback }, \u002F\u002F 引擎配置\n);\n```\n\n你可以在 [examples\u002Fservice-worker](examples\u002Fservice-worker\u002F) 中找到如何在 Service Worker 中运行 WebLLM 的完整示例。\n\n### Chrome 扩展\n\n你还可以在 [examples\u002Fchrome-extension](examples\u002Fchrome-extension\u002F) 和 [examples\u002Fchrome-extension-webgpu-service-worker](examples\u002Fchrome-extension-webgpu-service-worker\u002F) 中找到使用 WebLLM 构建 Chrome 扩展的示例。后者利用了 Service Worker，因此扩展可以在后台持续运行。此外，你还可以探索另一个完整的 Chrome 扩展项目——WebLLM Assistant，它正是基于 WebLLM 构建的，请参见 [这里](https:\u002F\u002Fgithub.com\u002Fmlc-ai\u002Fweb-llm-assistant)。\n\n## 完全兼容 OpenAI\n\nWebLLM 被设计为与 [OpenAI API](https:\u002F\u002Fplatform.openai.com\u002Fdocs\u002Fapi-reference\u002Fchat) 完全兼容。因此，除了构建一个简单的聊天机器人之外，你还可以使用 WebLLM 实现以下功能：\n\n- [流式输出](examples\u002Fstreaming)：以 AsyncGenerator 的形式实时返回分块输出。\n- [JSON 模式](examples\u002Fjson-mode)：高效地确保输出为 JSON 格式，更多信息请参阅 [OpenAI 文档](https:\u002F\u002Fplatform.openai.com\u002Fdocs\u002Fguides\u002Ftext-generation\u002Fchat-completions-api)。\n- [可复现性种子](examples\u002Fseed-to-reproduce)：通过设置 `seed` 字段来确保输出的可复现性。\n- [函数调用](examples\u002Ffunction-calling)（开发中）：使用 `tools` 和 `tool_choice` 字段进行函数调用（已提供初步支持）；或者不使用 `tools` 或 `tool_choice` 进行手动函数调用（保留最大灵活性）。\n\n## 完整性验证\n\nWebLLM 支持使用 [SRI（子资源完整性）](https:\u002F\u002Fdeveloper.mozilla.org\u002Fen-US\u002Fdocs\u002FWeb\u002FSecurity\u002FSubresource_Integrity) 哈希对模型文件进行可选的完整性验证。当 `ModelRecord` 中设置了 `integrity` 字段时，WebLLM 会在加载之前，根据提供的哈希值验证下载的配置文件、WASM 文件和分词器文件。\n\n```typescript\nimport { CreateMLCEngine } from \"@mlc-ai\u002Fweb-llm\";\n\nconst appConfig = {\n  model_list: [\n    {\n      model: \"https:\u002F\u002Fhuggingface.co\u002Fmlc-ai\u002FLlama-3.2-1B-Instruct-q4f16_1-MLC\",\n      model_id: \"Llama-3.2-1B-Instruct-q4f16_1-MLC\",\n      model_lib:\n        \"https:\u002F\u002Fraw.githubusercontent.com\u002Fuser\u002Fmodel-libs\u002Fmain\u002Fmodel.wasm\",\n      integrity: {\n        config: \"sha256-\u003Cbase64-hash-of-mlc-chat-config.json>\",\n        model_lib: \"sha256-\u003Cbase64-hash-of-wasm-file>\",\n        tokenizer: {\n          \"tokenizer.json\": \"sha256-\u003Cbase64-hash-of-tokenizer.json>\",\n        },\n        onFailure: \"error\", \u002F\u002F \"error\"（默认）会抛出 IntegrityError，\"warn\" 则会记录警告并继续执行\n      },\n    },\n  ],\n};\n\nconst engine = await CreateMLCEngine(\"Llama-3.2-1B-Instruct-q4f16_1-MLC\", {\n  appConfig,\n});\n```\n\n你可以使用以下命令为模型文件生成 SRI 哈希值：\n\n```bash\n# SHA-256\nopenssl dgst -sha256 -binary \u003Cfile> | openssl base64 -A | sed 's\u002F^\u002Fsha256-\u002F'\n# SHA-384\nopenssl dgst -sha384 -binary \u003Cfile> | openssl base64 -A | sed 's\u002F^\u002Fsha384-\u002F'\n# SHA-512\nopenssl dgst -sha512 -binary \u003Cfile> | openssl base64 -A | sed 's\u002F^\u002Fsha512-\u002F'\n```\n\n> `openssl` 命令需要类 Unix 环境（macOS\u002FLinux）。在 Windows 上，可以通过 [Git Bash](https:\u002F\u002Fgitforwindows.org\u002F) 或 [WSL](https:\u002F\u002Flearn.microsoft.com\u002Fen-us\u002Fwindows\u002Fwsl\u002F) 来运行 `openssl`。\n\n如果哈希值不匹配，将会抛出 `IntegrityError`（或在 `onFailure: \"warn\"` 时记录警告）。`integrity` 中的所有字段都是可选的——只有指定的文件才会被验证。如果完全省略 `integrity` 字段，WebLLM 将按原有方式运行（不进行任何验证）。\n\n完整的演示示例请参阅 [integrity-verification 示例](examples\u002Fintegrity-verification\u002F)。\n\n## 自定义模型\n\nWebLLM 是 [MLC LLM](https:\u002F\u002Fgithub.com\u002Fmlc-ai\u002Fmlc-llm) 的配套项目，支持 MLC 格式的自定义模型。它复用 MLC LLM 的模型工件，并沿用了其工作流程。要使用 WebLLM 编译和运行您自己的模型，请参阅 [MLC LLM 文档](https:\u002F\u002Fllm.mlc.ai\u002Fdocs\u002Fdeploy\u002Fwebllm.html)，了解如何将新的模型权重和库部署到 WebLLM 中。\n\n以下我们简要介绍其高层次的设计思路。WebLLM 包中有两个关键元素，用于支持新模型及其权重变体：\n\n- `model`：包含指向模型工件（如权重和元数据）的 URL。\n- `model_lib`：指向 WebAssembly 库（即 `.wasm` 文件）的 URL，该库包含用于加速模型计算的可执行代码。\n\n这两个元素均可在 WebLLM 中进行自定义配置。\n\n```typescript\nimport { CreateMLCEngine } from \"@mlc-ai\u002Fweb-llm\";\n\nasync function main() {\n  const appConfig = {\n    \"model_list\": [\n      {\n        \"model\": \"\u002Furl\u002Fto\u002Fmy\u002Fllama\",\n        \"model_id\": \"MyLlama-3b-v1-q4f32_0\",\n        \"model_lib\": \"\u002Furl\u002Fto\u002Fmyllama3b.wasm\",\n      }\n    ],\n  };\n  \u002F\u002F 覆盖默认设置\n  const chatOpts = {\n    \"repetition_penalty\": 1.01\n  };\n\n  \u002F\u002F 加载预构建模型，并应用聊天选项覆盖及应用配置\n  \u002F\u002F 在后台，它会从 myLlamaUrl 加载模型并缓存在浏览器缓存中\n  \u002F\u002F 同时，聊天界面也会从 \"\u002Furl\u002Fto\u002Fmyllama3b.wasm\" 加载模型库，\n  \u002F\u002F 假设该库与 myLlamaUrl 中的模型兼容。\n  const engine = await CreateMLCEngine(\n    \"MyLlama-3b-v1-q4f32_0\",\n    { appConfig }, \u002F\u002F 引擎配置\n    chatOpts,\n  );\n}\n```\n\n在许多情况下，我们只需提供不同的模型权重变体，而不一定需要引入全新的模型（例如，“NeuralHermes-Mistral”可以复用“Mistral”的模型库）。有关不同模型变体如何共享同一模型库的示例，请参阅 `webllm.prebuiltAppConfig`。\n\n## 从源码构建 WebLLM 包\n\n注意：除非您希望修改 WebLLM 包，否则无需从源码构建。若要使用 npm 包，只需按照[快速入门](#get-started)或任何[示例](examples)中的说明操作即可。\n\n若要从源码构建，只需执行以下命令：\n\n```bash\nnpm install\nnpm run build\n```\n\n然后，要在示例中测试您的代码更改效果，在 `examples\u002Fget-started\u002Fpackage.json` 中将 `\"@mlc-ai\u002Fweb-llm\": \"^0.2.82\"` 更改为 `\"@mlc-ai\u002Fweb-llm\": ..\u002F..\"`。\n\n接着运行：\n\n```bash\ncd examples\u002Fget-started\nnpm install\nnpm start\n```\n\n请注意，有时需要在 `file:..\u002F..` 和 `..\u002F..` 之间切换，以使 npm 识别到新更改。最坏的情况下，您可以执行以下操作：\n\n```bash\ncd examples\u002Fget-started\nrm -rf node_modules dist package-lock.json .parcel-cache\nnpm install\nnpm start\n```\n\n### 如需从源码构建 TVMjs\n\nWebLLM 的运行时环境很大程度上依赖于 TVMjs：https:\u002F\u002Fgithub.com\u002Fapache\u002Ftvm\u002Ftree\u002Fmain\u002Fweb。虽然它也可以作为 npm 包使用：https:\u002F\u002Fwww.npmjs.com\u002Fpackage\u002F@mlc-ai\u002Fweb-runtime，但如有需要，您仍可按照以下步骤从源码构建。\n\n1. 安装 [emscripten](https:\u002F\u002Femscripten.org)。它是一个基于 LLVM 的编译器，可将 C\u002FC++ 源代码编译为 WebAssembly。\n   - 按照[安装说明](https:\u002F\u002Femscripten.org\u002Fdocs\u002Fgetting_started\u002Fdownloads.html#installation-instructions-using-the-emsdk-recommended)安装最新版本的 emsdk。\n   - 执行 `source path\u002Fto\u002Femsdk_env.sh` 来加载 `emsdk_env.sh`，以便 `emcc` 可通过 PATH 访问，并确保 `emcc` 命令正常运行。\n\n   我们可以通过尝试运行 `emcc` 终端命令来验证安装是否成功。\n\n   注意：我们最近发现，使用最新版本的 `emcc` 可能在运行时遇到问题。目前，作为临时解决方案，建议使用 `.\u002Femsdk install 3.1.56` 而不是 `.\u002Femsdk install latest`。错误信息可能如下所示：\n\n   ```\n   初始化错误，LinkError：WebAssembly.instantiate(): 导入 #6 模块=\"wasi_snapshot_preview1\"\n   函数=\"proc_exit\"：函数导入需要一个可调用对象\n   ```\n\n2. 在 `.\u002Fpackage.json` 中，将 `\"@mlc-ai\u002Fweb-runtime\": \"0.18.0-dev2\",` 更改为 `\"@mlc-ai\u002Fweb-runtime\": \"file:.\u002Ftvm_home\u002Fweb\",`。\n\n3. 设置必要的环境\n\n   准备所有用于 Web 构建的依赖项：\n\n   ```shell\n   .\u002Fscripts\u002Fprep_deps.sh\n   ```\n\n   在此步骤中，如果环境中未定义 `$TVM_SOURCE_DIR`，我们将执行以下命令来构建 `tvmjs` 依赖项：\n\n   ```shell\n   git clone https:\u002F\u002Fgithub.com\u002Fmlc-ai\u002Frelax 3rdparty\u002Ftvm-unity --recursive\n   ```\n\n   这将克隆 `mlc-ai\u002Frelax` 的当前 HEAD 版本。然而，这并不总是正确的分支或提交。要从源码构建特定的 npm 版本，请参考版本更新的 PR，其中会说明当前 WebLLM 版本依赖于哪个分支（即 `mlc-ai\u002Frelax` 或 `apache\u002Ftvm`）以及具体哪个提交。例如，根据其版本更新 PR https:\u002F\u002Fgithub.com\u002Fmlc-ai\u002Fweb-llm\u002Fpull\u002F521，版本 0.2.52 是基于 `apache\u002Ftvm` 中的提交 https:\u002F\u002Fgithub.com\u002Fapache\u002Ftvm\u002Fcommit\u002Fe6476847753c80e054719ac47bc2091c888418b6 构建的，而非 `mlc-ai\u002Frelax` 的 HEAD。\n\n   此外，`--recursive` 参数是必要且重要的。否则，您可能会遇到类似 `fatal error: 'dlpack\u002Fdlpack.h' file not found` 的错误。\n\n4. 构建 WebLLM 包\n\n   ```shell\n   npm run build\n   ```\n\n5. 验证部分子包\n\n   您可以进入 [examples](examples) 中的子文件夹，验证其中的部分子包。我们使用 Parcelv2 进行打包。尽管 Parcel 有时难以追踪父目录的变化，但当您对 WebLLM 包进行更改时，可以尝试编辑子文件夹的 `package.json` 并保存，这样会触发 Parcel 重新构建。\n\n## 链接\n\n- [演示应用：WebLLM 聊天](https:\u002F\u002Fchat.webllm.ai\u002F)\n- 如果您希望在原生运行时环境中运行 LLM，请查看 [MLC-LLM](https:\u002F\u002Fgithub.com\u002Fmlc-ai\u002Fmlc-llm)。\n- 您可能还会对 [Web 稳定扩散](https:\u002F\u002Fgithub.com\u002Fmlc-ai\u002Fweb-stable-diffusion\u002F)感兴趣。\n\n## 致谢\n\n本项目由 CMU Catalyst、UW SAMPL、上海交通大学、OctoML 以及 MLC 社区的成员共同发起。我们期待继续开发并支持开源机器学习社区。\n\n本项目得以实现，离不开我们所依托的开源生态系统。我们衷心感谢 Apache TVM 社区以及 TVM Unity 团队的开发者们。正是开源机器学习社区的成员们公开了这些模型，而 PyTorch 和 Hugging Face 社区则让这些模型更加易于获取。我们特别感谢 Vicuna、SentencePiece、LLaMA 和 Alpaca 团队的支持。此外，我们也感谢 WebAssembly、Emscripten 和 WebGPU 社区，以及 Dawn 和 WebGPU 的开发者们。\n\n## 引用\n\n如果您觉得本项目有用，请引用以下文献：\n\n```\n@misc{ruan2024webllmhighperformanceinbrowserllm,\n      title={WebLLM：一款高性能的浏览器内LLM推理引擎},\n      author={Charlie F. Ruan、Qin Yucheng、Zhou Xun、Lai Ruihang、Jin Hongyi、Dong Yixin、Hou Bohan、Yu Meng-Shiun、Zhai Yiyan、Agarwal Sudeep、Cao Hangrui、Feng Siyuan、Chen Tianqi},\n      year={2024},\n      eprint={2412.15803},\n      archivePrefix={arXiv},\n      primaryClass={cs.LG},\n      url={https:\u002F\u002Farxiv.org\u002Fabs\u002F2412.15803},\n}\n```\n\n## 贡献者\n\n\u003Ca href=\"https:\u002F\u002Fgithub.com\u002Fmlc-ai\u002Fweb-llm\u002Fgraphs\u002Fcontributors\">\n  \u003Cimg alt=\"contributors\" src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fmlc-ai_web-llm_readme_6d03a6b4861b.png\"\u002F>\n\u003C\u002Fa>\n\n\u003Cp align=\"right\">\n  \u003Ca href=\"#top\">⬆ 返回顶部 ⬆\u003C\u002Fa>\n\u003C\u002Fp>","# WebLLM 快速上手指南\n\nWebLLM 是一个高性能的浏览器端大语言模型（LLM）推理引擎。它利用 WebGPU 进行硬件加速，无需服务器支持即可在浏览器中直接运行开源大模型，并完全兼容 OpenAI API 格式。\n\n## 环境准备\n\n在使用 WebLLM 之前，请确保满足以下软硬件要求：\n\n*   **浏览器要求**：必须使用支持 **WebGPU** 的现代浏览器。\n    *   推荐：Chrome 113+、Edge 113+ 或其他基于 Chromium 且开启 WebGPU 支持的浏览器。\n    *   检查方法：访问 `chrome:\u002F\u002Fgpu` 查看 WebGPU 状态是否为 \"Enabled\"。\n*   **网络环境**：首次运行时需要下载模型权重文件（通常几百 MB 到几 GB），请确保网络连接稳定。\n*   **前置依赖**：无需安装 Python 或后端服务，仅需标准的 Web 开发环境（Node.js 用于构建项目，或直接使用 CDN）。\n\n## 安装步骤\n\n你可以通过包管理器安装，也可以直接通过 CDN 在网页中使用。\n\n### 方式一：使用包管理器（推荐用于项目开发）\n\n在项目目录中执行以下命令之一：\n\n```bash\n# npm\nnpm install @mlc-ai\u002Fweb-llm\n\n# yarn\nyarn add @mlc-ai\u002Fweb-llm\n\n# pnpm\npnpm install @mlc-ai\u002Fweb-llm\n```\n\n安装完成后，在代码中导入模块：\n\n```typescript\n\u002F\u002F 导入全部功能\nimport * as webllm from \"@mlc-ai\u002Fweb-llm\";\n\n\u002F\u002F 或仅导入所需功能\nimport { CreateMLCEngine } from \"@mlc-ai\u002Fweb-llm\";\n```\n\n### 方式二：使用 CDN（推荐用于快速测试或原型开发）\n\n无需安装，直接在 HTML 或 JS 文件中通过 URL 导入，适用于 JSFiddle、Codepen 等在线编辑器：\n\n```javascript\nimport * as webllm from \"https:\u002F\u002Fesm.run\u002F@mlc-ai\u002Fweb-llm\";\n```\n\n或者动态导入：\n\n```javascript\nconst webllm = await import(\"https:\u002F\u002Fesm.run\u002F@mlc-ai\u002Fweb-llm\");\n```\n\n## 基本使用\n\n以下是创建一个聊天机器人并生成回复的最简示例。\n\n### 1. 初始化引擎 (Create MLCEngine)\n\n首先加载模型。注意：首次加载模型需要下载文件，耗时较长，建议添加进度回调。\n\n```typescript\nimport { CreateMLCEngine } from \"@mlc-ai\u002Fweb-llm\";\n\n\u002F\u002F 定义进度回调函数\nconst initProgressCallback = (initProgress) => {\n  console.log(\"加载进度:\", initProgress);\n};\n\n\u002F\u002F 选择模型 (此处以 Llama-3.1-8B 为例，也可选用 Qwen, Phi 等)\nconst selectedModel = \"Llama-3.1-8B-Instruct-q4f32_1-MLC\";\n\n\u002F\u002F 创建引擎实例\nconst engine = await CreateMLCEngine(\n  selectedModel,\n  { initProgressCallback: initProgressCallback }\n);\n```\n\n> **提示**：内置支持的模型家族包括 Llama 3, Phi 3, Gemma, Mistral, Qwen (通义千问) 等。完整列表可查阅 [MLC Models](https:\u002F\u002Fmlc.ai\u002Fmodels)。\n\n### 2. 发送对话请求 (Chat Completion)\n\n引擎初始化完成后，即可使用类似 OpenAI 的 API 格式进行对话。\n\n```typescript\nconst messages = [\n  { role: \"system\", content: \"你是一个乐于助人的 AI 助手。\" },\n  { role: \"user\", content: \"你好！请介绍一下你自己。\" },\n];\n\n\u002F\u002F 获取完整回复\nconst reply = await engine.chat.completions.create({\n  messages,\n});\n\nconsole.log(\"AI 回复:\", reply.choices[0].message.content);\nconsole.log(\"资源使用情况:\", reply.usage);\n```\n\n### 3. 流式输出 (Streaming)\n\n为了实现打字机效果，可以启用流式模式：\n\n```typescript\nconst messages = [\n  { role: \"user\", content: \"写一首关于春天的短诗。\" },\n];\n\n\u002F\u002F 启用 stream: true\nconst chunks = await engine.chat.completions.create({\n  messages,\n  temperature: 1,\n  stream: true, \n  stream_options: { include_usage: true },\n});\n\nlet fullReply = \"\";\nfor await (const chunk of chunks) {\n  const content = chunk.choices[0]?.delta.content || \"\";\n  fullReply += content;\n  \u002F\u002F 在此处将 content 渲染到 UI 上实现流式显示\n  console.log(content); \n  \n  if (chunk.usage) {\n    console.log(\"最终统计:\", chunk.usage);\n  }\n}\n```\n\n### 进阶提示：缓存策略\n\n为了加速二次加载，WebLLM 默认使用浏览器的 Cache API。如果需要跨域存储或更持久的缓存，可在配置中指定 `cacheBackend`：\n\n```typescript\nimport { CreateMLCEngine, prebuiltAppConfig } from \"@mlc-ai\u002Fweb-llm\";\n\nconst appConfig = { \n  ...prebuiltAppConfig, \n  cacheBackend: \"indexeddb\" \u002F\u002F 可选：\"cache\"(默认), \"indexeddb\", \"cross-origin\"\n};\n\nconst engine = await CreateMLCEngine(\"Llama-3.1-8B-Instruct-q4f32_1-MLC\", {\n  appConfig,\n});\n```","一家初创教育科技公司希望在网页端为用户提供个性化的 AI 作文辅导助手，要求响应迅速且严格保护学生隐私。\n\n### 没有 web-llm 时\n- **高昂的服务器成本**：每增加一名用户就需要扩容后端 GPU 集群来支撑推理，导致运营预算迅速枯竭。\n- **隐私合规风险**：学生的作文内容必须上传至云端处理，存在数据泄露隐患，难以满足严格的未成年人数据保护法规。\n- **网络延迟影响体验**：在网络波动环境下，请求往返云端造成明显的回答卡顿，破坏了写作时的流畅心流。\n- **部署维护复杂**：需要专门团队维护后端推理服务、负载均衡及模型版本更新，分散了核心产品开发精力。\n\n### 使用 web-llm 后\n- **零服务器推理成本**：利用 WebGPU 直接调用用户本地显卡进行计算，完全消除了后端推理带来的巨额算力开支。\n- **原生隐私安全**：所有数据处理均在浏览器本地完成，敏感作文内容从未离开用户设备，从架构上杜绝了泄露风险。\n- **极速实时交互**：省去了网络传输环节，结合硬件加速实现了低延迟的流式输出，让修改建议如本地软件般丝滑。\n- **轻量化集成部署**：通过 NPM 包即可将 Llama 3 或 Qwen 等模型嵌入现有网页，无需搭建复杂的后端基础设施。\n\nweb-llm 通过将高性能大模型推理能力下沉至浏览器端，让开发者能以零服务器成本构建出既保护隐私又具备原生应用体验的 AI 产品。","https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fmlc-ai_web-llm_5ec0d829.png","mlc-ai","https:\u002F\u002Foss.gittoolsai.com\u002Favatars\u002Fmlc-ai_a1be60ad.jpg",null,"https:\u002F\u002Fgithub.com\u002Fmlc-ai",[78,82,86,90,93],{"name":79,"color":80,"percentage":81},"TypeScript","#3178c6",97.1,{"name":83,"color":84,"percentage":85},"SCSS","#c6538c",0.9,{"name":87,"color":88,"percentage":89},"HTML","#e34c26",0.8,{"name":91,"color":92,"percentage":89},"Shell","#89e051",{"name":94,"color":95,"percentage":96},"JavaScript","#f1e05a",0.5,17694,1231,"2026-04-06T09:21:39","Apache-2.0","未说明 (基于浏览器的跨平台工具，支持任何现代浏览器运行的操作系统)","必需：支持 WebGPU 的显卡 (无需特定型号或 CUDA，依赖浏览器对 WebGPU 的支持)","未说明 (取决于所选模型大小，通常在浏览器中运行需足够内存加载模型权重)",{"notes":105,"python":106,"dependencies":107},"这是一个纯前端运行的工具，无需服务器后端。核心依赖是浏览器必须支持 WebGPU (如新版 Chrome, Edge)。首次运行需下载模型文件，支持通过 Cache API 或 IndexedDB 缓存。可通过 npm、yarn 安装或直接使用 CDN 引入。","不需要 (纯 JavaScript\u002FTypeScript 项目)",[108,109,110],"@mlc-ai\u002Fweb-llm","WebGPU API","WebAssembly",[14,35],[113,114,115,116,117,118,119],"deep-learning","llm","tvm","webgpu","webml","chatgpt","language-model","2026-03-27T02:49:30.150509","2026-04-06T22:01:56.653375",[123,128,133,138,143,148],{"id":124,"question_zh":125,"answer_zh":126,"source_url":127},20175,"如何在本地部署 WebLLM？遇到安全警告或 WebGPU 初始化失败怎么办？","本地部署时，如果直接访问本地文件路径（如 `\u002Fdist\u002Fvicuna-7b\u002F...`）遇到浏览器安全警告，建议启用 CORS 头来提供服务。可以使用 `dserve` 工具（https:\u002F\u002Fgithub.com\u002Floretoparisi\u002Fdserve）来启动本地服务器。此外，确保模型权重已正确转换为分片格式（shards），如果是使用 delta 权重，需参考 FastChat 文档进行转换和处理。","https:\u002F\u002Fgithub.com\u002Fmlc-ai\u002Fweb-llm\u002Fissues\u002F19",{"id":129,"question_zh":130,"answer_zh":131,"source_url":132},20176,"在 Android 设备上运行 Chat Demo 时遇到 maxStorageBufferBindingSize 限制错误如何解决？","部分 Android 设备（如 Pixel 7）的 `maxStorageBufferBindingSize` 限制较低（仅 128MB），而某些模型需要更高限制。目前可以通过更新到 webllm npm 0.2.36 及以上版本来捕获 `createBuffer()` 中的 OOM（内存溢出）错误。维护者已重新部署了演示站点以包含此修复。未来计划通过检测 GPU 厂商和架构字段来自动适配移动端 GPU。","https:\u002F\u002Fgithub.com\u002Fmlc-ai\u002Fweb-llm\u002Fissues\u002F209",{"id":134,"question_zh":135,"answer_zh":136,"source_url":137},20177,"遇到 'cannot read properties of undefined' 或 adapterInfo 未定义的错误如何处理？","该错误通常由缓存文件或构建中间文件过旧引起。建议清理所有相关缓存和构建目录，执行以下命令后重新安装和构建：\n`rm -r lib\u002F node_modules\u002F dist\u002F .parcel-cache`\n`npm install`\n`npm run build`\n如果是 Next.js 项目，尝试删除 `.next\u002F` 目录。确保使用的 `index.js` 是 npm 包中最新的源代码。","https:\u002F\u002Fgithub.com\u002Fmlc-ai\u002Fweb-llm\u002Fissues\u002F572",{"id":139,"question_zh":140,"answer_zh":141,"source_url":142},20178,"如何使用 Mistral-7B 模型？遇到 'Cannot find global function vm.builtin.param_module_from_cache_by_name' 错误怎么办？","该错误通常是因为模型库版本不匹配。有两种解决方案：\n1. 使用向后兼容的非 SLM 模型库并重新编译：`Mistral-7B-Instruct-v0.1-q4f16_1-sw4k_cs1k-webgpu.wasm`。\n2. 使用 SLM 模型库（`Mistral-7B-Instruct-v0.2...MLC-webgpu.wasm`），并按照官方文档（https:\u002F\u002Fllm.mlc.ai\u002Fdocs\u002Fdeploy\u002Fjavascript.html#bring-your-own-model-variant）重新编译 OpenOrca 权重。\n请确保更新文档推荐配置以保证未来构建正常工作。","https:\u002F\u002Fgithub.com\u002Fmlc-ai\u002Fweb-llm\u002Fissues\u002F202",{"id":144,"question_zh":145,"answer_zh":146,"source_url":147},20179,"运行 Phi-3.5 等视觉模型时报错 'ValueError: Cannot find parameter in cache...' 如何解决？","此错误表明缓存中缺少特定的视觉模型参数（如 `vision_embed_tokens...q_weight`）。这通常是模型文件或缓存不一致导致的。建议在运行前彻底清除浏览器缓存，可以使用以下代码清空包含 'webllm' 的缓存：\n`(await window.caches.keys()).forEach(async k => k.includes(\"webllm\") && await window.caches.delete(k))`\n如果问题依旧，可能是特定模型版本（如 q4f16_1）的问题，尝试切换到其他精度版本（如 `Phi-3.5-vision-instruct-q4f32_1-MLC`）或等待官方修复合并。","https:\u002F\u002Fgithub.com\u002Fmlc-ai\u002Fweb-llm\u002Fissues\u002F727",{"id":149,"question_zh":150,"answer_zh":151,"source_url":152},20180,"为什么 Llama-2-7b 模型输出乱码（Gibberish）？","虽然提供的数据中该 Issue 内容被截断，但此类问题通常与模型量化格式（如 q4f32_1 vs q4f16_1）与当前运行时环境或 WebGPU 驱动不兼容有关。一般建议尝试切换模型的量化版本（例如从 q4f32 切换到 q4f16），或者更新浏览器至最新版本以确保 WebGPU 功能正常。若问题持续，请检查控制台是否有具体的 Shader 编译错误或内存不足提示。","https:\u002F\u002Fgithub.com\u002Fmlc-ai\u002Fweb-llm\u002Fissues\u002F356",[154,159,164],{"id":155,"version":156,"summary_zh":157,"released_at":158},118212,"v0.2.82","* 修复失败的测试用例\n* 添加 CONTRIBUTING.md 文件\n* 为测试、构建和安全添加持续集成\n\n**完整变更日志**: https:\u002F\u002Fgithub.com\u002Fmlc-ai\u002Fweb-llm\u002Fcompare\u002Fv0.2.81...v0.2.82","2026-03-13T04:06:40",{"id":160,"version":161,"summary_zh":162,"released_at":163},118213,"v0.2.81","* 引擎与 API 重构：将 ChatModule 重构为 Engine\u002FMLCEngine，整合构造函数和重载行为，支持多模型加载、更完善的 Worker 生命周期管理及并发处理\n* OpenAI API：镜像 chat\u002Fcompletions API，支持有状态选项、函数调用和嵌入向量生成\n* 对话模板：统一对话模板 schema，并支持自定义模板\n* 扩展预构建模型支持：新增对更多模型的支持（Llama 2\u002F3\u002F3.1\u002F3.2、Mistral 系列、Gemma 2、Qwen2\u002F2.5\u002F3、Phi 系列，含视觉模型）\n* 运行时与缓存：WebGPU 性能与可靠性提升（增加 GPU 端内核，优化 OOM 和 deviceLost 处理）、Wasm\u002F预构建版本号更新，支持 IndexedDB 缓存\n* XGrammar 集成：基于 JSON Schema 和文法约束的生成，以及 XGrammar 结构化标签\n* TVM-FFI 集成：重构以兼容较新的 TVM 提交记录及 TVM FFI\n* 示例：ServiceWorkerEngine + 更新的 Chrome 扩展演示，新增 RAG\u002F文档聊天示例，通过结构化标签实现工具调用\n* CI：使用 GitHub Actions 进行代码 linting，并引入 pre-commit 钩子\n\n**完整变更日志**：https:\u002F\u002Fgithub.com\u002Fmlc-ai\u002Fweb-llm\u002Fcompare\u002Fv0.2.0...v0.2.81","2026-02-18T21:43:44",{"id":165,"version":166,"summary_zh":167,"released_at":168},118214,"v0.2.0","- 重大源代码重构\n- npm 包\n- Web Worker 支持","2023-05-26T12:52:57"]