WebLLM은 서버 없이 웹 브라우저 안에서 WebGPU 하드웨어 가속을 통해 대규모 언어 모델(LLM) 추론을 직접 실행할 수 있는 오픈소스 엔진입니다. OpenAI API와 완전 호환되어 스트리밍, JSON 모드 등을 로컬에서 사용할 수 있으며, Llama 3, Phi 3, Gemma, Mistral, Qwen2 등 다양한 모델을 지원합니다. 프라이버시 보호와 GPU 가속을 동시에 누릴 수 있어 브라우저 기반 AI 어시스턴트 개발에 중요한 프로젝트입니다.
번역된 본문
WebLLM: 브라우저 내 고성능 LLM 추론 엔진
문서 | 블로그 포스트 | 논문 | 예제
개요
WebLLM은 하드웨어 가속을 통해 언어 모델 추론을 웹 브라우저로 직접 가져오는 고성능 브라우저 내 LLM 추론 엔진입니다. 모든 것이 서버 지원 없이 브라우저 내부에서 실행되며 WebGPU로 가속됩니다. WebLLM은 OpenAI API와 완전히 호환됩니다. 즉, 오픈소스 모델을 로컬에서 실행하면서 스트리밍, JSON 모드, 함수 호출(개발 중) 등의 기능을 갖춘 동일한 OpenAI API를 사용할 수 있습니다. 이를 통해 GPU 가속의 이점을 누리면서 프라이버시를 보장하는 AI 어시스턴트를 모두를 위해 구축하는 많은 흥미로운 기회를 만들 수 있습니다. WebLLM을 기본 npm 패키지로 사용하고 아래 예제를 따라 자신만의 웹 애플리케이션을 그 위에 구축할 수 있습니다. 이 프로젝트는 다양한 하드웨어 환경에 걸쳐 LLM의 범용 배포를 가능하게 하는 MLC LLM의 동반 프로젝트입니다. WebLLM Chat을 통해 직접 사용해 보세요!
주요 기능
브라우저 내 추론: WebLLM은 WebGPU를 활용한 하드웨어 가속으로 고성능 브라우저 내 언어 모델 추론 엔진을 제공하며, 서버 측 처리 없이 웹 브라우저에서 직접 강력한 LLM 작업을 수행할 수 있습니다.
완전한 OpenAI API 호환: 스트리밍, JSON 모드, 로짓(logit) 수준 제어, 시드 설정 등의 기능을 갖춘 OpenAI API로 앱을 WebLLM과 원활하게 통합할 수 있습니다.
구조화된 JSON 생성: WebLLM은 최신 수준의 JSON 모드 구조화 생성을 지원하며, 최적의 성능을 위해 모델 라이브러리의 WebAssembly 부분에서 구현됩니다. HuggingFace의 WebLLM JSON Playground에서 커스텀 JSON 스키마로 JSON 출력을 생성해 볼 수 있습니다.
폭넓은 모델 지원: WebLLM은 Llama 3, Phi 3, Gemma, Mistral, Qwen(통의천문) 등 다양한 모델을 기본 지원하여 다양한 AI 작업에 활용할 수 있습니다. 지원되는 전체 모델 목록은 MLC Models에서 확인하세요.
커스텀 모델 통합: MLC 형식의 커스텀 모델을 쉽게 통합하고 배포하여 특정 요구와 시나리오에 맞게 WebLLM을 조정할 수 있어 모델 배포의 유연성이 향상됩니다.
플러그 앤 플레이 통합: NPM, Yarn 같은 패키지 매니저나 CDN을 통해 WebLLM을 프로젝트에 쉽게 통합할 수 있으며, UI 컴포넌트 연결을 위한 포괄적인 예제와 모듈형 설계를 제공합니다.
스트리밍 및 실시간 상호작용: 스트리밍 채팅 완성을 지원하여 챗봇 및 가상 어시스턴트 같은 대화형 애플리케이션의 실시간 출력 생성이 가능합니다.
웹 워커 및 서비스 워커 지원: 계산을 별도의 워커 스레드나 서비스 워커로 오프로드하여 UI 성능을 최적화하고 모델 라이프사이클을 효율적으로 관리합니다.
크롬 확장 프로그램 지원: WebLLM을 사용한 커스텀 크롬 확장 프로그램을 통해 웹 브라우저 기능을 확장할 수 있으며, 기본 및 고급 확장 프로그램 구축 예제가 제공됩니다.
내장 모델
사용 가능한 전체 모델 목록은 MLC Models에서 확인하세요. WebLLM은 이 중 일부 모델을 지원하며 해당 목록은 prebuiltAppConfig.model_list에서 접근할 수 있습니다. 현재 지원되는 주요 모델 계열은 다음과 같습니다:
더 많은 모델이 필요하다면 이슈를 열어 새 모델을 요청하거나, 커스텀 모델 문서를 참고하여 자신만의 모델을 컴파일하고 WebLLM에서 사용하는 방법을 확인하세요.
예제로 빠르게 시작하기
이 간단한 챗봇 예제를 통해 WebLLM을 사용해 애플리케이션에 대규모 언어 모델을 통합하고 채팅 완성을 생성하는 방법을 배워보세요. 더 크고 복잡한 프로젝트의 고급 예제는 WebLLM Chat을 확인하세요. 다양한 사용 사례에 대한 추가 예제는 examples 폴더에서 제공됩니다.
시작하기
WebLLM은 브라우저에서 챗봇에 접근할 수 있는 미니멀하고 모듈화된 인터페이스를 제공합니다. 이 패키지는 모듈 방식으로 설계되어
WebLLM High-Performance In-Browser LLM Inference Engine. Documentation | Blogpost | Paper | Examples Overview WebLLM is a high-performance in-browser LLM inference engine that brings language model inference directly onto web browsers with hardware acceleration. Everything runs inside the browser with no server support and is accelerated with WebGPU. WebLLM is fully compatible with OpenAI API . That is, you can use the same OpenAI API on any open source models locally, with functionalities including streaming, JSON-mode, function-calling (WIP), etc. We can bring a lot of fun opportunities to build AI assistants for everyone and enable privacy while enjoying GPU acceleration. You can use WebLLM as a base npm package and build your own web application on top of it by following the examples below. This project is a companion project of MLC LLM , which enables universal deployment of LLM across hardware environments. Check out WebLLM Chat to try it out! Key Features 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. Full OpenAI API Compatibility : Seamlessly integrate your app with WebLLM using OpenAI API with functionalities such as streaming, JSON-mode, logit-level control, seeding, and more. 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 on HuggingFace to try generating JSON output with custom JSON schema. Extensive Model Support : 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 . Custom Model Integration : Easily integrate and deploy custom models in MLC format, allowing you to adapt WebLLM to specific needs and scenarios, enhancing flexibility in model deployment. 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 and a modular design for connecting with UI components. Streaming & Real-Time Interactions : Supports streaming chat completions, allowing real-time output generation which enhances interactive applications like chatbots and virtual assistants. 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. 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. Built-in Models Check the complete list of available models on MLC Models . WebLLM supports a subset of these available models and the list can be accessed at prebuiltAppConfig.model_list . Here are the primary families of models currently supported: Llama : Llama 3, Llama 2, Hermes-2-Pro-Llama-3 Phi : Phi 3, Phi 2, Phi 1.5 Gemma : Gemma-2B Mistral : Mistral-7B-v0.3, Hermes-2-Pro-Mistral-7B, NeuralHermes-2.5-Mistral-7B, OpenHermes-2.5-Mistral-7B Qwen (通义千问) : Qwen2 0.5B, 1.5B, 7B If you need more models, request a new model via opening an issue or check Custom Models for how to compile and use your own models with WebLLM. Jumpstart with Examples Learn how to use WebLLM to integrate large language models into your application and generate chat completions through this simple Chatbot example: For an advanced example of a larger, more complicated project, check WebLLM Chat . More examples for different use cases are available in the examples folder. Get Started WebLLM offers a minimalist and modular interface to access the chatbot in the browser. The package is designed in a modular way to hook to any of the UI components. Installation Package Manager # npm npm install @mlc-ai/web-llm # yarn yarn add @mlc-ai/web-llm # or pnpm pnpm install @mlc-ai/web-llm Then import the module in your code. // Import everything import * as webllm from "@mlc-ai/web-llm" ; // Or only import what you need import { CreateMLCEngine } from "@mlc-ai/web-llm" ; CDN Delivery Thanks to jsdelivr.com , WebLLM can be imported directly through URL and work out-of-the-box on cloud development platforms like jsfiddle.net , Codepen.io , and Scribbler : import * as webllm from "https://esm.run/@mlc-ai/web-llm" ; It can also be dynamically imported as: const webllm = await import ( "https://esm.run/@mlc-ai/web-llm" ) ; Create MLCEngine Most 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. (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.) import { CreateMLCEngine } from "@mlc-ai/web-llm" ; // Callback function to update model loading progress const initProgressCallback = ( initProgress ) => { console . log ( initProgress ) ; } ; const selectedModel = "Llama-3.1-8B-Instruct-q4f32_1-MLC" ; const engine = await CreateMLCEngine ( selectedModel , { initProgressCallback : initProgressCallback } , // engineConfig ) ; Under 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. import { MLCEngine } from "@mlc-ai/web-llm" ; // This is a synchronous call that returns immediately const engine = new MLCEngine ( { initProgressCallback : initProgressCallback , } ) ; // This is an asynchronous call and can take a long time to finish await engine . reload ( selectedModel ) ; Cache Backend Policy WebLLM supports four cache backends through AppConfig.cacheBackend : "cache" : browser Cache API (default). "indexeddb" : browser IndexedDB . "opfs" : browser Origin Private File System (OPFS) . "cross-origin" : experimental Chrome Cross-Origin Storage API extension backend. Install the Cross-Origin Storage extension to use it. (If the extension isn't installed, WebLLM falls back to the default cache automatically.) Example: import { CreateMLCEngine , prebuiltAppConfig } from "@mlc-ai/web-llm" ; const appConfig = { ... prebuiltAppConfig , cacheBackend : "cross-origin" } ; const engine = await CreateMLCEngine ( "Llama-3.1-8B-Instruct-q4f32_1-MLC" , { appConfig , } ) ; Notes: If "opfs" is selected in an environment without OPFS support, cache operations fail with an OPFS availability error. When using "opfs" , appConfig.opfsAccessMode can be set to "auto" to use OPFS sync access handles where supported, or "sync" to require sync access handles. The default is "async" . The "cross-origin" backend requires installing and enabling a compatible browser extension. Cross-origin backend currently does not support programmatic tensor-cache deletion; clearing is extension-managed. Chat Completion After 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 and OpenAI API reference . (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 above.) const messages = [ { role : "system" , content : "You are a helpful AI assistant." } , { role : "user" , content : "Hello!" } , ] ; const reply = await engine . chat . completions . create ( { messages , } ) ; console . log ( reply . choices [ 0 ] . message ) ; console . log ( reply . usage ) ; Streaming WebLLM also supports streaming chat completion