
Running language models in JupyterLite with Python
College of Computing, Data Science, and Society, UC Berkeley
github.com/ericvd-ucb · Universidad Europea de Madrid
The aim is not a better chatbot. It is a model students can take apart.

Requires a browser with WebGPU support, such as a recent Chrome or Edge.

huggingface.co/spaces/mlc-ai/webllm-llama-3.2-chat, built by the MLC team with WebLLM
From a research lab to a student’s laptop

Qwen3-0.6B from Alibaba’s Qwen team: huggingface.co/Qwen/Qwen3-0.6B
Qwen3-0.6B-q4f16_1-MLC
| Part | Meaning |
|---|---|
Qwen3 |
Model family and version (Alibaba’s Qwen 3) |
0.6B |
0.6 billion parameters (the learned weights) |
q4f16_1 |
4-bit weights, 16-bit floating-point arithmetic |
MLC |
Compiled for the MLC and WebLLM runtime |
“Instruct” or “-it” in a name marks a chat-tuned model; a base model only continues text. The files live at huggingface.co/mlc-ai/Qwen3-0.6B-q4f16_1-MLC.
| Model | Parameters | Rough 4-bit size* | Good for |
|---|---|---|---|
| SmolLM2-360M-Instruct | 0.36 B | about 0.2 GB | Fast demos; seeing failure modes |
| Qwen3-0.6B | 0.6 B | about 0.3 GB | Default starter; visible reasoning |
| Llama-3.2-1B-Instruct | 1.2 B | about 0.6 GB | Solid general chat |
| Qwen3-1.7B | 1.7 B | about 0.9 GB | Better answers, still laptop-friendly |
| Phi-3.5-mini-instruct | 3.8 B | about 1.9 GB | Strongest here; needs a capable GPU |
*Estimate: parameters × 0.5 bytes. Actual downloads are somewhat larger. Start with the smallest model whose failures are still instructive.
For an open data class, the model card raises the same questions as any data source: provenance, license, and fitness for purpose.
One request format across cloud, laptop, and browser
In WebLLM the model is chosen when the engine loads, so the model argument is not used.
import js
from pyodide.ffi import to_js
if getattr(js.navigator, "gpu", None):
print("WebGPU is available. You can run models.")
webllm = await js.eval("import('https://esm.run/@mlc-ai/web-llm')")
engine = await webllm.CreateMLCEngine("Qwen3-0.6B-q4f16_1-MLC")
def js_obj(d):
"""Turn a Python dict into a JavaScript object."""
return to_js(d, dict_converter=js.Object.fromEntries)
async def chat(messages, **settings):
"""Send a conversation and return the reply."""
request = js_obj({"messages": messages, **settings})
return await engine.chat.completions.create(request)Simplified from webllm_starter.ipynb, which adds a download progress bar and the browser model cache. All of the code is visible in the notebook.
The model is stateless. Memory is the notebook resending the history on every turn.
"stop" means the model ended; "length" means max_tokens cut it offBefore, during, and after the call: parsing input and output

Most of the work, and most of the errors, sit outside the model.
import pandas as pd
df = pd.read_csv("[dataset].csv") # open data with a free-text column
SYSTEM = "You extract fields from city service requests. Reply with JSON only."
def build_messages(text):
prompt = f"""Request: {text}
Return JSON with keys "category" and "urgency" (low, medium, or high)."""
return [
{"role": "system", "content": SYSTEM},
{"role": "user", "content": prompt},
]
messages = build_messages(df["texto"].iloc[0])temperature=0 for extractionStreaming: see tokens as they arrive
import json, re
def clean(text):
# drop a Qwen3 reasoning block, then any code fences
text = re.sub(r"<think>.*?</think>", "", text, flags=re.S)
text = re.sub(r"^```(json)?|```$", "", text.strip(), flags=re.M)
return text.strip()
def parse(reply):
choice = reply.choices[0]
if choice.finish_reason != "stop":
return None # cut off: do not trust it
try:
return json.loads(clean(choice.message.content))
except json.JSONDecodeError:
return None # count it as a failureALLOWED = {"low", "medium", "high"}
def valid(fields):
return (
isinstance(fields, dict)
and isinstance(fields.get("category"), str)
and fields.get("urgency") in ALLOWED
)
parsed = [parse(r) if r else None for r in replies]
parsed = [p if valid(p) else None for p in parsed]
sample = df.head(20).copy()
sample["category"] = [p["category"] if p else None for p in parsed]
sample["urgency"] = [p["urgency"] if p else None for p in parsed]Text in, a table out: the result is ordinary data, ready for pandas.
Backends spell this differently: the OpenAI API uses {"type": "json_schema", ...}.
| texto | category | urgency |
|---|---|---|
| Farola apagada en la calle desde hace una semana | street lighting | medium |
| Contenedor desbordado frente al colegio | waste collection | high |
| Banco del parque con pintura descascarillada | park furniture | low |
Illustrative records. In class, use a free-text column from an open data portal such as datos.madrid.es or datos.gob.es.
The harness turns a demo into an experiment.
What happens inside a single call

The list of messages becomes one string with special tokens (Qwen’s ChatML format):
<|im_start|>system
You are a concise tutor.<|im_end|>
<|im_start|>user
What is a token?<|im_end|>
<|im_start|>assistant
Each model family has its own template, which is why the model card matters.
temperaturetop_pstop string, or max_tokensPrefill reads the whole prompt in one pass. Decode produces one token per step, which is the tokens-per-second figure students measured earlier.
Next token after “The capital of France is”
| Token | T = 0.5 | T = 1 | T = 2 |
|---|---|---|---|
| Paris | 97.2% | 77.1% | 48.7% |
| Lyon | 1.8% | 10.4% | 17.9% |
| the | 0.7% | 6.3% | 14.0% |
| France | 0.2% | 3.8% | 10.9% |
| a | 0.1% | 2.3% | 8.5% |
Illustrative logits. At temperature 0 the engine always takes the top token.
| Argument | Values | What it does |
|---|---|---|
temperature |
0 to 2 | Randomness of each pick; 0 is greedy |
top_p |
0 to 1 | Sample only from the most likely tokens, up to total probability p |
max_tokens |
integer | Hard cap on reply length |
stop |
strings | Text that ends generation early |
seed |
integer | Repeatable sampling for the same model and settings |
stream |
true or false | Receive tokens as they are generated |
response_format |
JSON schema | Constrain the reply to valid JSON |
frequency_penalty, presence_penalty |
−2 to 2 | Discourage repetition |
logprobs |
true or false | Return token probabilities for inspection |
| Notebook | Section of this talk |
|---|---|
| Starter sampler | Why small models |
| Finding and picking models | Where models come from |
| The chat format: roles, settings, JSON reply | The OpenAI chat interface |
| Memory: a chat that remembers | The OpenAI chat interface |
| The harness: parsing input and output (new) | The harness |
| Tokens: numbers all the way down | Behind the scenes |
| SAT test taker | Evaluation |
github.com/ericvd-ucb/small-models-lite
A JupyterLite site where small language models run in the student’s browser through WebLLM, with no server, API key or installation.
Requires Chrome or Edge with WebGPU.
Questions and discussion

github.com/ericvd-ucb