Executando LLMs no Navegador: WebLLM, Transformers.js e ONNX Runtime Web em 2026
技术架构
LLMs Já Não Precisam de Servidores
GPT-4 requer APIs na nuvem? Esse é o pensamento de 2024. Em 2026, modelos de 7B parâmetros rodam sem problemas no navegador, e seus dados nunca saem do seu dispositivo.
Privacidade + Custo Zero + Offline = As três vantagens decisivas da IA no navegador
Linha do Tempo da Evolução da IA no Navegador
2023 Q4 WebLLM é lançado, Llama 2 a 2 tok/s no navegador
2024 Q2 Transformers.js lançado, ecossistema Hugging Face conectado
2024 Q4 Suporte completo ao WebGPU, 5x de aceleração na inferência
2025 Q2 ONNX Runtime Web suporta WebGPU, nível empresarial
2025 Q4 Avanço na quantização, modelos de 7B comprimidos para 3GB
2026 Q2 Gemma 3 4B atinge 25 tok/s no navegador — ponto de inflexão de qualidade
Três Frameworks de Relance
| Framework | Foco | Tecnologia Central | Melhor Para |
|---|---|---|---|
| WebLLM | Inferência LLM de alto desempenho | WebGPU + MLCEngine | Chat, autocompletar código |
| Transformers.js | Inferência ML full-stack | ONNX + WASM/WebGPU | NLP, visão, áudio |
| ONNX Runtime Web | Motor de inferência empresarial | ONNX + WebGPU/WASM | Implantação em produção |
WebLLM — O Rei do Desempenho dos LLMs no Navegador
Arquitetura
┌──────────────────────────────────────────────────┐
│ Camada de Aplicação │
│ Chat UI │ Autocompletar │ Resumo │ ... │
├──────────────────────────────────────────────────┤
│ Motor WebLLM │
│ ChatModule │ Pipeline │ Tokenizer │ Scheduler │
├──────────────────────────────────────────────────┤
│ MLCEngine (Otimização de Compilação) │
│ Model Compile │ Kernel Opt │ Quantization │
├──────────────────────────────────────────────────┤
│ Runtime WebGPU │
│ Compute Shader │ GPU Buffer │ Pipeline State │
└──────────────────────────────────────────────────┘
Início Rápido
import { CreateMLCEngine } from "@mlc-ai/web-llm";
const engine = await CreateMLCEngine("gemma-3-4b-it-q4f16_1-MLC", {
initProgressCallback: (progress) => {
console.log(`Loading: ${(progress.progress * 100).toFixed(1)}%`);
},
});
const reply = await engine.chat.completions.create({
messages: [
{ role: "system", content: "You are a helpful AI assistant." },
{ role: "user", content: "Write a quicksort in TypeScript" },
],
temperature: 0.7,
max_tokens: 1024,
stream: true,
});
for await (const chunk of reply) {
process.stdout.write(chunk.choices[0]?.delta?.content || "");
}
Modelos Suportados e Desempenho (Junho 2026)
| Modelo | Parâmetros | Tamanho Quantizado | Velocidade (tok/s) | Primeira Carga |
|---|---|---|---|---|
| Gemma 3 4B IT | 4B | 2.3GB | 25 | 8s |
| Phi-4 Mini | 3.8B | 2.1GB | 28 | 7s |
| Qwen2.5 3B | 3B | 1.8GB | 32 | 6s |
| SmolLM2 1.7B | 1.7B | 1.0GB | 45 | 4s |
| Qwen2.5 0.5B | 0.5B | 0.4GB | 85 | 2s |
Ambiente de teste: M3 MacBook Pro / Chrome 126 / WebGPU
Transformers.js — O Ecossistema Hugging Face no Navegador
Vantagem Central: O Ecossistema de Modelos Mais Rico
import { pipeline } from "@xenova/transformers";
const classifier = await pipeline("text-classification", "Xenova/distilbert-base-uncased-finetuned-sst-2-english");
const result = await classifier("This browser AI is amazing!");
// [{ label: "POSITIVE", score: 0.9998 }]
Pipelines Suportados
| Pipeline | Caso de Uso | Modelo de Exemplo |
|---|---|---|
| text-classification | Análise de sentimento | distilbert-sst2 |
| question-answering | Sistema de perguntas e respostas | distilbert-qa |
| summarization | Resumo | distilbart-cnn |
| translation | Tradução | opus-mt-en-zh |
| image-classification | Classificação de imagens | vit-base-patch16 |
| automatic-speech-recognition | Reconhecimento de fala | whisper-tiny |
ONNX Runtime Web — Motor de Inferência Empresarial
Uso Básico
import ort from "onnxruntime-web";
async function runInference(modelPath: string, input: Float32Array) {
const session = await ort.InferenceSession.create(modelPath, {
executionProviders: ["webgpu", "wasm"],
graphOptimizationLevel: "all",
});
const inputTensor = new ort.Tensor("float32", input, [1, input.length]);
const results = await session.run({ input: inputTensor });
return results.output.data;
}
Estratégia de Seleção de Provedor
function getBestProvider(): string {
if (navigator.gpu) return "webgpu";
if (document.createElement("canvas").getContext("webgl2")) return "webgl";
return "wasm";
}
Benchmarks de Desempenho: Comparação Completa
Inferência LLM (Gemma 3 4B, quantização de 4 bits)
| Métrica | WebLLM | Transformers.js | ONNX Runtime Web |
|---|---|---|---|
| Velocidade (tok/s) | 25 | 18 | 22 |
| Primeira Carga | 8s | 12s | 10s |
| Memória | 3.2GB | 3.8GB | 3.5GB |
| Streaming | ✅ | ✅ | ❌ |
| Compatibilidade OpenAI API | ✅ | ❌ | ❌ |
Estratégias de Implantação em Produção
Degradação Elegante
async function createEngineWithFallback() {
if (navigator.gpu) {
try { return await CreateMLCEngine("gemma-3-4b-it-q4f16_1-MLC"); }
catch (e) { console.warn("WebGPU failed, falling back to smaller model"); }
}
try { return await CreateMLCEngine("SmolLM2-1.7B-q4f16_1-MLC"); }
catch (e) { console.warn("Small model failed, falling back to API"); }
return new APIFallbackEngine({ endpoint: "/api/chat" });
}
Suporte Offline com Service Worker
const MODEL_CACHE = "ai-models-v1";
self.addEventListener("install", (event) => {
event.waitUntil(
caches.open(MODEL_CACHE).then((cache) =>
cache.addAll(["/models/smolm2-1.7b-q4.onnx", "/models/tokenizer.json"])
)
);
});
Matriz de Decisão
Sua necessidade?
├─ Chat / IA Conversacional → ✅ WebLLM
├─ IA Multimodal → ✅ Transformers.js
├─ Produção Empresarial → ✅ ONNX Runtime Web
├─ App Offline-First → ✅ WebLLM + Service Worker
└─ Protótipo Rápido → ✅ Transformers.js
Tendências H2 2026
| Tendência | Descrição |
|---|---|
| WebGPU Universal | Suporte no Safari 18+, sem mais problemas de compatibilidade |
| MoE no Navegador | Modelos esparsos do Mixtral rodando no navegador |
| Fine-tuning no Dispositivo | Pesos LoRA baixados, modelos personalizados sem servidor |
| API Web AI do W3C | Capacidades de IA nativas do navegador padronizadas |
Resumo
- A IA no navegador passou de "brinquedo" para "ferramenta" — modelo de 4B a 25 tok/s é utilizável
- Três frameworks, três forças — WebLLM rápido, Transformers.js completo, ONNX estável
- A privacidade é a característica decisiva — Os dados nunca saem do navegador, custo de servidor zero
- A estratégia de degradação é fundamental — WebGPU → modelo pequeno → API na nuvem, disponibilidade garantida
Se o seu produto de IA ainda envia cada requisição para a nuvem em 2026, você não está apenas desperdiçando custos de servidor — está perdendo a proteção de privacidade, o maior diferenciador.
Experimente estas ferramentas executadas localmente no navegador — nenhum cadastro necessário →
#WebLLM#Transformers.js#ONNX#WebGPU#浏览器AI#边缘推理#大模型#本地AI