Token LabBuscar

← Todos los tutoriales
GUÍA PARA DESARROLLADORES / 01

Tokens y tokenizadores: del texto a la entrada del modelo

Entiende qué representa un token, observa una codificación real y comprueba la reconstrucción del texto.

Un token no es una palabra

El modelo recibe IDs de tokens. El tokenizador transforma el texto en enteros mediante un vocabulario y reglas de codificación. Una palabra frecuente puede ocupar un token; un nombre poco común, varios. Los espacios, los signos y los saltos de línea también cuentan.

BPE forma unidades de subpalabras mediante reglas de combinación aprendidas. Los fragmentos visibles sirven para depurar, no para analizar lingüísticamente una frase.

Study guide & lesson outlineLEARNING CONTRACT

Understand → implement → investigate

Goal: explain the mechanism in this lesson, reproduce one example and test a failure case. Reading alone does not mark mastery.

  • Understand: state assumptions, shapes/units and a counterexample.
  • Implement: reproduce a numerical example and inspect boundaries.
  • Investigate: compare one alternative under a matched budget.

Ejecuta un ejemplo reproducible

Elige cl100k_base e introduce exactamente Hello, world!, con coma y espacio. Obtendrás cuatro IDs: 9906, 11, 1917, 0. Selecciona cada bloque de color. Después elimina la coma o cambia las mayúsculas y observa el resultado.

Al pasar a o200k_base cambia el vocabulario, por lo que pueden cambiar los IDs y el recuento. Un ID solo tiene sentido junto con su codificación. Exporta ambos.

import { encode, decode } from
  'gpt-tokenizer/encoding/cl100k_base';

const text = 'Hello, world!';
const ids = encode(text);
// [9906, 11, 1917, 0]
console.log(ids.length); // 4
console.log(decode(ids) === text); // true
Probar en la herramienta →

Verifica antes de integrar

Decodifica toda la secuencia y compárala con el original. Un token puede dividir un carácter UTF-8 y mostrarse como � por separado, aunque la secuencia completa se reconstruya correctamente.

Este contador procesa texto, no una solicitud API completa. Roles, definiciones de herramientas y medios pueden añadir uso. Contrasta el resultado local con la respuesta de la API antes de aplicarlo a facturación o límites estrictos.

Referencias e implementación

MATHEMATICAL REVIEW · 2026-10-26

Assumptions, implementation & acceptance

Round-trip decode(encode(text)) equals the original text. Individual tokens may split UTF-8 sequences; do not require each token to decode independently.

Shared code, English mathematical explanation and key multilingual numeric passages reviewed. This is not a full translation proofread.

Unicode text → UTF-8 bytes → merge vocabulary → Token IDs → count → Decode full sequence → round trip
Mechanism map: follow the transformations from top to bottom.

Before running: predict a boundary case

Round-trip decode(encode(text)) equals the original text. Individual tokens may split UTF-8 sequences; do not require each token to decode independently.

Hint: isolate the assumption

Keep the baseline input fixed, change one parameter or boundary, and compare both the numerical result and the claimed units. A passing example verifies this fixture only.

Minimal executable example

Save the example and linked modules in one folder. Use Node.js 22 or newer, then run node tokens-and-tokenizers.mjs. npm install gpt-tokenizer@4.1.0

import { encode, decode } from
  'gpt-tokenizer/encoding/cl100k_base';

const text = 'Hello, world!';
const ids = encode(text);
// [9906, 11, 1917, 0]
console.log(ids.length); // 4
console.log(decode(ids) === text); // true

Test and transfer

Round-trip decode(encode(text)) equals the original text. Individual tokens may split UTF-8 sequences; do not require each token to decode independently.

Record input, code version, expected result and observed result in the notebook below. Then construct a counterexample that violates the assumption above and explain why the original conclusion no longer follows.

Download complete kit (.tar.gz) · Complete reference kit and regression checks

Predict, test and keep evidence

Before revealing an answer, predict one result. After the exercise, record the discrepancy and a transfer test. Saved locally across language editions.

Open notebook / export / clear →

The mathematical review scope is recorded per lesson. It does not establish empirical paper reproduction; report suspected errors in your notes. Review scope