Skip to content
claudneysessaPublic

About

A browser-only chat where a 0.5B LLM answers Star Wars questions from real SWAPI data instead of from memory: deterministic router, exact values rendered by the code, no build step.

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Repository files navigation

swapi-ia — the model looks it up, it doesn't remember

A language model running inside your browser tab that answers Star Wars questions from real data instead of from memory — the code looks the facts up, the model only writes the sentence around them.

🇧🇷 Leia em português

Live demo WebLLM Data: SWAPI No build step License: MIT

Live demo: https://claudneysessa.github.io/swapi-ia/

Scope. This is a study project, not a Star Wars encyclopedia. It answers what the SWAPI actually stores — attributes and direct links between records — and it refuses, out loud, everything else. The interface and the answers are in Brazilian Portuguese; this document is the English entry point.

Opening screen of swapi-ia: the side panel listing what can be asked and what the dataset does not know, and the card explaining that the code queries SWAPI while the model only writes the sentence, with a model selector and a single Start button

The opening screen states the contract before downloading anything: what the app does with the data, how much it is about to fetch, and — in the side panel — the exact list of questions it refuses. The panel is not decoration; it is the router's contract, written out.

Then the chat, with the model on your GPU

Animation of a question about Han Solo being typed and the model streaming its answer word by word inside the browser

Unedited output from Qwen2.5-0.5B running locally, picking up after the weights finished downloading. Look at what it gets right and what it does not: the film comes from the record, and "protagonista principal" and "soldado de guerra" do not — that is a 0.5B padding a sentence. Which is the whole reason the exact values are rendered by the code and never recited by the model: ask for the ficha and every number on screen comes straight from the JSON.

The inversion, in one paragraph

Qwen2.5-0.5B does not know Star Wars accurately. Ask a 500 MB model how tall Luke Skywalker is and it will answer with a plausible, wrong number, with complete confidence. Here it never answers from memory: the code queries SWAPI, builds the record card, and the model only writes the sentence around it. The model stops being the source of the fact and becomes the translator.

This is the deliberate counterpart to IA de Bolso: same model, same inference parameters, same dependency-free static base. There, the model is a closed box with no network. Here, it is given a tool.

The flow

question
   ↓
[router.js]  resource + field matched?  ──no──→  "the API doesn't have that; it has X"
   ↓ yes                                         (the model never runs)
[swapi.js]   in-memory lookup + joins + field pruning
   ↓
[card]       exact values, rendered by the code (on request)
   ↓
[app.js]     restrictive prompt → WebLLM/Qwen → connecting sentence

The rules run before the model. It never picks a resource, never plans a query, never recites a number. It runs once, at the end, only to write.


1. The data layer — swapi.js

What the API actually is

Surveyed from real payloads, not from the documentation:

Base https://swapi.info/api
Authentication none
Methods GET only
CORS Access-Control-Allow-Origin: * — called straight from the browser, no proxy
Resources 6 · 260 records in total
Search does not exist — ?search= is ignored and returns the whole list
Pagination does not exist — every list comes complete
Images none — 56 distinct keys across the 260 records, zero media fields

The open CORS policy is what makes the project possible without a server. The absence of search is what forces name matching to happen locally.

Strategy: download everything, once

With no search and no pagination, and with the largest list weighing 45 KB, fetching on demand would be worse in every dimension. The client fires six parallel GETs at startup and never touches the network again:

await Promise.all(RECURSOS.map(async (recurso) => {
  const dados = await (await fetch(`${BASE}/${recurso}`)).json();
  this.#porRecurso.set(recurso, dados);
  for (const item of dados) this.#porUrl.set(item.url, { recurso, item });
}));

Two indexes are built right after:

  • #porUrl — url → { resource, record }. This is what resolves the links.
  • #indiceNomes — normalized name → record, sorted from the longest name to the shortest. Without that ordering, "Luke" would match before "Luke Skywalker", and "Darth" would run over "Darth Vader".

Normalization strips accents and punctuation, so C-3PO and c3po land in the same place and Padmé matches even when typed without the accent.

Links are URLs, and the join is local

No relation field carries embedded data — every one of them carries a URL:

"homeworld": "https://swapi.info/api/planets/1",
"vehicles":  ["https://swapi.info/api/vehicles/14", ".../vehicles/30"]

With everything in memory, following those links costs no request: it is a Map lookup. The same is true in reverse — the 10 residents of Tatooine become 10 names with zero network.

The graph is bidirectional in almost every direction, which is why nearly every legitimate question fits in a single hop:

people    → homeworld (1:1) · films · vehicles · starships · species
planets   → residents · films
films     → characters · planets · starships · vehicles · species
species   → homeworld (1:1) · people · films
vehicles  → pilots · films
starships → pilots · films

Fields per resource

resource n scalar fields
people 82 name, height, mass, hair/skin/eye_color, birth_year, gender
planets 60 name, rotation/orbital_period, diameter, climate, gravity, terrain, surface_water, population
films 6 title, episode_id, opening_crawl, director, producer, release_date
species 37 name, classification, designation, average_height/lifespan, language, colors
vehicles 39 name, model, manufacturer, cost, length, speed, crew, passengers, cargo, consumables, class
starships 36 same as vehicles + hyperdrive_rating, MGLT

A single ESQUEMA object describes each resource once — which fields become card rows and which fields are links. It is the only source of "what exists", so the router reads from it instead of from a second list that could drift.

Normalization and translation, in the same pass

The dataset has real inconsistencies: blond and blonde, desert and deserts, mammal and mammals, and artic spelled without the "c". The pt-BR translation dictionaries collapse those duplicates for free.

Formatting is local too: 172 → 1,72 m, 10465 → 10.465 km, 19BBY → 19 ABY, 1977-05-25 → 25/05/1977. Some numbers arrive with a thousands separator ("1,358"), which Number() would turn into NaN.

Absence has two meanings

const VAZIO = new Set(["unknown", "n/a", "none", "", "unknown/unknown"]);

An empty array means "not applicable", not "unknown" — Luke has species: [] because being human is the absence of a species in this dataset. On the card the row is simply not drawn, and the field never reaches the model. What it does not see, it cannot invent.


2. The router — router.js

This is the heart of the project: it defines what the app knows and what it admits it does not. It never returns "maybe" — always an explicit decision.

Order of checks

1. Does the requested relation exist in the dataset? This comes first. "Who passed through Tatooine" does match the name Tatooine, and without this check the app would return the planet card as if it were the answer. There are 8 refusal patterns, each with its own explanation — a generic "I don't know" helps nobody:

pattern why
passed / was at / visited SWAPI stores a homeworld, not movement
killed / died / defeated there is no record of deaths or battles
father / sibling / family there is no kinship field
Jedi / Sith / ally / side there is no affiliation field
master / apprentice not SWAPI fields
personality / feels / likes it is a technical catalogue, not an encyclopedia
stronger / would win / duel nothing about combat or performance
plot / what happens only the film's record

2. Is a record mentioned? Full name first (the index is sorted longest to shortest), then an isolated token. "quem é o luke" does not contain "lukeskywalker", which is why there is a second pass. Ambiguous tokens go into a stoplist:

const TOKENS_AMBIGUOS = new Set(["solo", "boba", "base", "ray", "rey", "the", "dos", "das"]);

Without it, "qual o solo de Tatooine" ("what is Tatooine's soil") would match Han Solo.

If a token hits several records — "skywalker" finds Luke, Anakin and Shmi — it asks which one instead of choosing.

3. Continuation. If nobody was named but the question uses a pronoun (ele, dela, lá, esse), the previous record is reused. Without this the conversation dies inside the router: "e de onde ele vem?" ("and where does he come from?") contains no name at all.

4. Listing. A plural resource word with no name mentioned returns the list as chips.

Field pruning — the change that improved answers the most

FOCOS maps the question to the card's labels. Handing over the whole record forces the model to choose, and choosing is what a 0.5B does worst — it mixes rows and invents a link between them.

For the question "quem é o Luke, de onde ele vem e que veículo ele controla" ("who is Luke, where is he from and what vehicle does he drive"):

before — 332 characters, 12 rows     after — 128 characters, 4 rows
Luke Skywalker (Personagem)          Luke Skywalker (Personagem)
- Altura: 1,72 m                     - Planeta: Tatooine
- Massa: 77 kg                       - Veículos: Snowspeeder, Speeder Bike
- Nascimento: 19 ABY                 - Naves: X-wing, Imperial shuttle
- Gênero / Olhos / Cabelo / Pele
- Planeta / Veículos / Naves / Filmes

Two focuses matched in the same sentence — "where is he from" and "what does he drive" — so planet and vehicles came through together. If a focus finds nothing on the card, the summary falls back to everything: better to let the model choose than to answer with no data at all.


3. The model integration — app.js

Where the model comes in

WebLLM compiles the model for WebGPU and exposes an OpenAI-compatible API. It has no network access whatsoever — the JavaScript is what calls the API. The model receives text and returns text.

const stream = await engine.chat.completions.create({
  messages: [
    { role: "system", content: SYSTEM_PROMPT },
    ...historico.slice(-MEMORIA),
    { role: "user", content: `Dados:\n${contexto}\n\nPergunta: ${pergunta}` },
  ],
  stream: true,
  temperature: 0.2,
  max_tokens: 220,
});

Why not function calling

The "obvious" path would be to hand tools to the model and let it pick the query. Two reasons not to: in WebLLM this is marked WIP, and a 0.5B does not pick a tool reliably. With a deterministic router the model runs exactly once, and the step where it was the weak link simply disappears.

The prompt

You read SWAPI record cards and answer in Brazilian Portuguese.
Use only the data provided. Do not add anything that is not in it —
neither from memory nor by deduction.
Previous messages are there to understand the question, never as a source of fact.
If a value is not there, say you do not have that information.
Never repeat the question: start with the answer.
Answer in 1 to 3 sentences, directly, without listing URLs.

(The prompt ships in Portuguese, since the answers are in Portuguese — see SYSTEM_PROMPT in app.js.)

Temperature at 0.2, not 0.7. The value inherited from the sibling project was meant for creative conversation; here the task is rewriting a value that already exists, and creativity only produces drift and question repetition.

Conversation context, on two separate levels

level what it keeps why
Router the last record mentioned resolves ele/dela/lá
Model up to 3 exchanges, text only continuity without risk

That distinction is what makes it safe: what goes back to the model is the sentence already written, never the record card. The question is stored clean, without the Dados: block — so today's JSON does not reappear on the next turn. Put two field tables in a 0.5B's context and it starts assigning one record's height to the other.

The most expensive lesson in this project

I tried teaching the output format with a few-shot example — a fake exchange using data from the planet Hoth. The result, on a question about Luke:

"O Luke é o personagem principal do filme A New Hope, de 1982. Ele nasceu em Tatooine, um planeta no sistema de Hoth."

The model pulled Hoth out of the example and invented the year. A formatting example is not neutral context — for a small model, everything in the window is available fact. The example was removed, and field pruning solved the problem by attacking the cause: fewer rows in the context, fewer things to stitch together wrongly.

The card belongs to the code, not to the model

Values go from the JSON straight to the DOM. 1,72 m is 1,72 m, always. The model never needs to recite a value and therefore never gets a value wrong — all that is left for it is the connecting sentence.

The card appears on request ("mostra a ficha do Luke", "ficha do Vader"). Without a request the answer comes as text — the data is queried the same way. On refusals there is no card: its absence is the visual signal that the API does not have that, and it comes with a chip offering what does exist.


Interface

  • Fixed brand at the top; the display font is used only for "Star Wars"
  • Full-height side panel showing the router's contract in two tabs: how to ask, and where the dataset ends
  • Centered chat, 80% of the remaining area, capped at 840 px
  • Only the body scrolls — the question field, the brand and the footer stay put
  • Chips walk the graph: Tatooine on Luke's card opens Tatooine's card
  • The confirmation dialog is a styled <dialog>; window.confirm cannot be themed and breaks the screen's identity

The brand and footer heights are measured with a ResizeObserver, not hardcoded. A guessed value broke the moment the footer wrapped to two lines, cutting off the send button.

Models

A selector on the opening screen, with VRAM figures extracted from WebLLM 0.2.84's own bundle:

model VRAM
Gemma 3 1B 711 MB
Llama 3.2 1B 879 MB
Qwen2.5 0.5B (default) 945 MB
Qwen2.5 1.5B 1,630 MB
Gemma 2 2B 1,895 MB
Llama 3.2 3B 2,264 MB

Qwen3 and Qwen3.5 were left out on purpose: they have a reasoning mode and may emit a "thinking" block before the answer — noise inside a 3-sentence bubble.

The choice is stored in localStorage, and a cached model loads by itself on refresh. The cache is per origin: switching ports or using 127.0.0.1 re-downloads everything.

Running locally

A static server is required — Chrome blocks ES modules loaded over file://, so double-clicking index.html will not work.

git clone https://github.com/claudneysessa/swapi-ia.git
cd swapi-ia
npx serve .          # or: python -m http.server 8000

Open the address it prints, in desktop Chrome or Edge with WebGPU. The first start downloads the model weights once; later starts read them from the browser cache. An internet connection is required on first run for the weights, and on every run for the six SWAPI requests.

Requirements and limits

  • WebGPU is mandatory. Recent Chrome or Edge on desktop. The opening screen says so instead of failing silently.
  • First load is a real download. From 711 MB to 2.3 GB depending on the model chosen. The progress bar reports actual bytes.
  • The router is pattern-based. A question outside the expected vocabulary falls into "I did not find that record" even when the data exists.
  • The connecting sentence is still written by a 0.5B. The values are safe because the code renders them; the prose around them can still add filler, as the animation above shows. The guarantee is about the facts, not about literary restraint — and asking for the ficha is what puts the verified values on screen next to the sentence.
  • No images. SWAPI is plain text. External sources that offered a portrait by id are fragile — starwars-visualguide answers 403 today, and akabab has ids that do not match SWAPI's (only 16 of 87 line up).
  • No inferred relations. "Who passed through Tatooine" does not exist. Both possible routes fail: residents gives 10 names and loses Han Solo; crossing by films gives 79 of 82 people, because Tatooine appears in 5 of the 6 films. The app says it does not know.
  • No test suite or CI. With no build to break and no server-side logic to guard, a pipeline would be ceremony — the same choice made in the sibling project. Verification here is opening the page. Only pages.yml runs, and it only publishes.

Privacy

  • No camera, microphone, location or upload is used.
  • Inference runs on your GPU. No question and no answer leaves the device.
  • Three network destinations, all of them public and read-only: swapi.info for the six lists, esm.run for the pinned WebLLM library, and the MLC model repository for the weights.
  • Model weights and the chosen model id live in the browser's own storage (Cache Storage and localStorage) and are removed by the Remover do cache button.

Roadmap

Delivered:

  • Six SWAPI resources in memory, with reverse joins
  • Deterministic router with 8 explained refusal patterns
  • Field pruning driven by the question
  • Record card rendered by the code, with graph navigation via chips
  • Model selector with cache detection and choice persistence

Possible next steps, in order of cost:

  • Widen the router's vocabulary using questions that fell into "record not found" — the honest measure of coverage
  • Compare answers across the six offered models on the same question set
  • Move inference to a Web Worker so the interface stays responsive while generating
  • Offer answers in English, which mostly means a second label dictionary
  • Measure and display real tokens per second per device

Credits

  • SWAPI — the Star Wars data source, read directly from the browser.
  • WebLLM / MLC AI — the runtime that compiles and runs the model in the browser.
  • Qwen2.5-0.5B-Instruct — model by the Qwen team at Alibaba Cloud, quantised by MLC AI. Gemma and Llama in the selector belong to Google and Meta respectively.
  • SF Distant Galaxy by ShyFonts — the display font used only in the "Star Wars" brand. Freeware; the complete package and its original documentation are redistributed in fonts/ as its terms require.

Application code, router, interface and documentation by Claudney Sarti Sessa, during the Engenharia de Software com IA Aplicada postgraduate course. The models are not mine — the contribution here is engineering: making a small model reliable by taking the facts away from it.

Trademarks

Unofficial fan project, with no affiliation to or endorsement by Lucasfilm Ltd. or The Walt Disney Company. Star Wars and all related names, logos and insignias are trademarks of their respective owners.

License

MIT — covers the application code and this documentation. It does not cover the SWAPI data, the model weights, the WebLLM library or the fonts/ package, each of which keeps the terms of its own author.

About

A browser-only chat where a 0.5B LLM answers Star Wars questions from real SWAPI data instead of from memory: deterministic router, exact values rendered by the code, no build step.

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages