Curso de Ingeniería de Prompts (#3) Tokens, contexto y predicción 🇪🇸 ထ 🇺🇸 Prompt Engineering Course (#3): Tokens, Context, and Prediction

Si en el artículo anterior entendiste que un LLM no piensa como nosotros, sino que aprendió a completar patrones a partir de ejemplos de texto, este otro te enseñará qué son los tokens, su relación con la ventana de contexto, y por qué el modelo siempre está predeciendo cuál es el siguiente trozo de texto más probable.

Esta es la razón por la que un prompt bien escrito funciona y uno mal escrito no, la razón por la que el modelo olvida en conversaciones largas, y la razón por la que a veces falla en tareas que un niño de cinco años resuelve sin problemas.
If in the previous article you understood that an LLM doesn't think the way we do, but rather learned to complete patterns from examples of text, this one will teach you what tokens are, how they relate to the context window, and why the model is always predicting which next chunk of text is most likely.

This is the reason a well-written prompt works and a poorly written one doesn't, the reason the model forgets in long conversations, and the reason it sometimes fails at tasks a five-year-old can solve without trouble.

Qué es un token

Un modelo de lenguaje no procesa palabras, sino tokens, que son fragmentos de texto que pueden ser una palabra completa, un pedazo de palabra, o un solo carácter, dependiendo de cómo el tokenizador divide el texto.

What a Token Is

A language model doesn't process words, but tokens, which are chunks of text that can be a whole word, a piece of a word, or a single character, depending on how the tokenizer splits the text.

Por ejemplo, la frase "La IA es maravillosa, ¿no?" un tokenizador la puede dividir en piezas como: "La", "IA", "es", "maravillosa", ",", "¿", "no", "?" — cada símbolo es su propio token, y un tokenizador podría dividir esa frase separando cada palabra y cada signo de puntuación como unidades independientes. Con palabras más largas o menos comunes, el modelo no siempre va a tener un token dedicado. Y en esos casos, la palabra se parte en subpalabras: por ejemplo, de forma simplificada, "maravillosa" podría convertirse en "mara" + "villosa", resultando en dos tokens en vez de uno. Esa técnica se llama tokenización por subpalabras y es la que usan casi todos los modelos ahora, porque así pueden manejar palabras que nunca vieron en su entrenamiento sin tener que memorizar cada una.

Después de la tokenización, cada token se convierte en un vector numérico mediante un proceso llamado embedding. Eso es lo que el modelo "ve" realmente: números. No letras, ni palabras, ni significado en el sentido en que nosotros entendemos. Son números organizados en un espacio matemático donde palabras con usos parecidos terminan más cerca entre sí.
For example, a tokenizer might split the sentence "AI is wonderful, isn't it?" into pieces like: "AI", "is", "wonderful", ",", "isn", "'t", "it", "?" — each symbol becomes its own token, and a tokenizer could break that sentence apart by separating every word and every punctuation mark into independent units. With longer or less common words, the model doesn't always have a dedicated token. In those cases, the word gets split into subwords: for example, in simplified terms, "wonderful" might become "won" + "derful", resulting in two tokens instead of one. This technique is called subword tokenization, and it's what nearly every model uses today, because it lets them handle words they never saw during training without having to memorize each one.

After tokenization, each token gets converted into a numerical vector through a process called embedding. That's what the model actually "sees": numbers. Not letters, not words, not meaning in the sense we understand it. They're numbers arranged in a mathematical space where words with similar uses end up closer together.

Por qué te afecta si escribes en español

Como hispanohablantes nos toca que los tokenizadores de la mayoría de los LLM comerciales fueron optimizados sobre corpus dominados por el inglés. Y la consecuencia es que un texto en español ocupa entre un 20% y un 30% más tokens que el mismo contenido en inglés, porque el tokenizador BPE está optimizado para inglés.

Eso significa que el mismo prompt te cuesta más caro en tokens si lo escribes en español que si lo escribes en inglés, y que consume más rápido tu ventana de contexto. No es algo que deberías ignorar si trabajas con documentos largos o conversaciones extensas. Pero la buena noticia es que eso se ha ido reduciendo con cada generación de modelos. Un proyecto que hace un par de años pagaba un 50% más por procesar español, hoy paga entre un 25% y un 30% más, y la tendencia es seguir reduciéndose.

Así que si en algún momento comparas por qué una misma tarea en inglés parece rendir más que en español, no es que el modelo entienda mejor el inglés (aunque a veces sí pasa), es que le cuesta menos tokens decir lo mismo.

Why It Matters If You Write in Spanish

Spanish speakers, are stuck with the fact that the tokenizers of most commercial LLMs were optimized on corpora dominated by English. The consequence is that a text in Spanish takes up between 20% and 30% more tokens than the same content in English, because the BPE tokenizer is optimized for English.

That means the same prompt costs you more in tokens if you write it in Spanish than if you write it in English, and it eats through your context window faster. That's not something you should ignore if you work with long documents or extended conversations. But the good news is that this gap has been shrinking with every model generation. A project that a couple of years ago paid 50% more to process Spanish today pays between 25% and 30% more, and the trend keeps pointing downward.

So if you ever find yourself comparing why the same task in English seems to go further than in Spanish, it's not that the model understands English better (though sometimes it does) — it's that it costs fewer tokens to say the same thing.

El modelo no "razona"

Cuando le das al modelo el texto "El gato se subió a la", el modelo no piensa en gatos, sino que calcula, sobre todo el vocabulario que conoce (decenas de miles de tokens posibles), una probabilidad para cada uno de ser el siguiente. Así que "silla" podría tener 24% de probabilidad, "mesa" 18%, "ventana" 15%, "azotea" 6%, y así con miles de opciones más, y la mayoría con probabilidades de casi cero. El modelo elige uno, lo suma al texto (aunque no siempre el más probable, y ahí entra un parámetro llamado temperatura, que verás en otro artículo), y repite el proceso para elegir el siguiente token, el siguiente, y el siguiente.

The Model Doesn't "Reason"

When you give the model the text "The cat climbed onto the", the model isn't thinking about cats. Instead, it calculates, across its entire known vocabulary (tens of thousands of possible tokens), a probability for each one being the next. So "chair" might get a 24% probability, "table" 18%, "windowsill" 15%, "roof" 6%, and so on across thousands more options, most of them with probabilities near zero. The model picks one, adds it to the text (though not always the most probable one — that's where a parameter called temperature comes in, which you'll see in another article), and repeats the process to pick the next token, and the next, and the next.

A eso se le llama generación autorregresiva, y es todo lo que un LLM hace. No hay un paso separado donde el modelo planifica la respuesta completa y luego la escribe. Cada token se genera mirando lo que vino antes.

Esa forma de funcionar explica lo que viste en el artículo pasado. Pídele a un modelo que cuente cuántas veces aparece la letra "r" en la palabra "strawberry", y podría responder "dos" cuando la respuesta correcta es tres. Un modelo capaz de escribir un ensayo sobre un tema complejo puede fallar una pregunta que resolvería un niño de cinco años. Dirá dos cuando son tres, y si insistes, a veces se disculpa y sigue equivocándose. Y no es que el modelo sea tonto en ese momento, sino que "strawberry" probablemente no se tokenizó como ocho letras individuales, sino como dos o tres fragmentos ("straw" + "berry", por ejemplo). Entonces el modelo nunca pudo acceder a las letras sueltas para poder contarlas, sino que trabajó con las que ya venían pre-ensambladas. Eso pasa cuando pides que cuente algo a un nivel de detalle (la letra) que está por debajo de la unidad con la que realmente opera (el token). Cuando entiendas esto, vas a dejar de sorprenderte por algunos errores del modelo, y vas a poder diseñar prompts que lo rodeen. De eso verás más en el artículo 21, dedicado a reducir alucinaciones.
This is called autoregressive generation, and it's all an LLM does. There's no separate step where the model plans out the full response and then writes it. Every token gets generated by looking at what came before.

This way of working explains what you saw in the previous article. Ask a model to count how many times the letter "r" appears in the word "strawberry," and it might answer "two" when the correct answer is three. A model capable of writing an essay on a complex topic can fail a question a five-year-old would solve without trouble. It'll say two when the answer is three, and if you push back, it sometimes apologizes and keeps getting it wrong. It's not that the model is being dumb in that moment — it's that "strawberry" probably wasn't tokenized as eight individual letters, but as two or three chunks ("straw" + "berry", for example). So the model never had access to the loose letters to count them; it worked with pieces that came pre-assembled. That happens whenever you ask it to count something at a level of detail (the letter) that sits below the unit it actually operates on (the token). Once you understand this, you'll stop being surprised by certain model errors, and you'll be able to design prompts that work around them. You'll see more of that in article 21, dedicated to reducing hallucinations.

La ventana de contexto

Todo lo que el modelo puede "ver" en un momento dado —tu prompt, historial de la conversación, o cualquier documento que le hayas dado, y también lo que él mismo ya generó en esa respuesta— tiene que caber dentro de un límite fijo de tokens. Y eso es la ventana de contexto.

Por ejemplo, Claude Sonnet 5 admite hasta 1 millón de tokens de contexto en los planes pagos al chatear, mientras que otros modelos de la misma familia se manejan en 500.000 tokens.

O sea, que un texto en español de 200.000 tokens equivale a unas 260 páginas. Con una ventana de 1 millón de tokens, podrías en teoría meter varios libros completos en una sola conversación.

Ahora, "en teoría"... tener una ventana de contexto así de enorme no significa que el modelo use ese espacio de manera uniforme. Hay un fenómeno llamado "lost in the middle" (perdido en el medio): en muchos casos, a partir de cierto volumen de tokens, la capacidad del modelo para recuperar un dato específico enterrado en el medio del texto empieza a degradarse, incluso si técnicamente ese dato sigue "dentro" de la ventana de contexto. Es decir, que quepa no es lo mismo que el modelo lo recuerde tan bien como a algo que le diste al principio o al final de la conversación.

Eso importa a la hora de escribir tus prompts de aquí en adelante: si le das al modelo un documento largo y luego le haces una pregunta muy específica sobre un dato que está enterrado en medio de ese documento, no asumas que la respuesta va a ser precisa solo porque "cupo" en la ventana de contexto. La posición de la información dentro del prompt importa, y vamos a ver mejor esto cuando hablemos de estructura y delimitadores más adelante en el curso.

The Context Window

Everything the model can "see" at any given moment — your prompt, the conversation history, any document you've given it, and also whatever it has already generated in that response — has to fit within a fixed token limit. That's the context window.

For example, Claude Sonnet 5 supports up to 1 million tokens of context on paid plans when chatting, while other models in the same family top out at 500,000 tokens.

In other words, a Spanish-language text of 200,000 tokens is roughly equivalent to about 260 pages. With a 1-million-token window, you could in theory fit several complete books into a single conversation.

Now, "in theory"... having a context window that huge doesn't mean the model uses that space uniformly. There's a phenomenon called "lost in the middle": in many cases, past a certain volume of tokens, the model's ability to retrieve a specific piece of data buried in the middle of the text starts to degrade, even if that data is technically still "inside" the context window. In other words, fitting isn't the same as the model remembering it as well as something you gave it at the beginning or end of the conversation.

That matters for how you write your prompts going forward: if you give the model a long document and then ask a very specific question about a fact buried in the middle of it, don't assume the answer will be accurate just because it "fit" inside the context window. The position of information within the prompt matters, and we'll dig into this further when we cover structure and delimiters later in the course.

Por qué te sirve para escribir mejores prompts

  1. El modelo trabaja con tokens, no con palabras ni letras. Si le pides algo que requiere manipular texto a un nivel más fino que el token (como contar letras, invertir una palabra carácter por carácter), es probable que falle debido a cómo está construido.
  2. Escribir en español te cuesta más tokens que escribir en inglés para transmitir la misma idea. Así que si trabajas con documentos largos o prompts complejos, ten eso en cuenta al planificar cuánto contexto te queda.
  3. El modelo genera su respuesta token por token, sin un plan. Y eso explica por qué pedirle que "piense antes de responder" (algo que verás en los artículos sobre Chain of Thought) cambia tanto la calidad de sus respuestas, porque le estás dando permiso para ir construyendo el razonamiento en el propio texto que genera, en vez de tener que acertar todo de una vez.

Con esto ya tienes un vocabulario técnico mínimo para entender por qué las técnicas de prompting que vamos a ver de aquí en adelante funcionan. Nos vemos.

Why This Helps You Write Better Prompts

  1. The model works with tokens, not with words or letters. If you ask it to do something that requires manipulating text at a level finer than the token (like counting letters or reversing a word character by character), it's likely to fail because of how it's built.
  2. Writing in Spanish costs you more tokens than writing in English to convey the same idea. So if you work with long documents or complex prompts, keep that in mind when planning how much context you have left.
  3. The model generates its response token by token, with no plan. And that explains why asking it to "think before responding" (something you'll see in the articles on Chain of Thought) changes the quality of its answers so much — because you're giving it permission to build its reasoning within the very text it generates, instead of having to get everything right in one shot.

With this, you now have the minimum technical vocabulary to understand why the prompting techniques we'll cover from here on actually work. See you next time.

Todas las imágenes son de mi propiedad / generadas por IA, a menos que se indique lo contrario.
Texto original en español, traducido al inglés con asistencia de Claude.
All images are my own / AI-generated, unless otherwise noted.
Original text in Spanish, translated to English with Claude's assistance.



0
0
0.000
2 comments
avatar

Congratulations @richard-mvm! You have completed the following achievement on the Hive blockchain And have been rewarded with New badge(s)

You distributed more than 300 upvotes.
Your next target is to reach 400 upvotes.

You can view your badges on your board and compare yourself to others in the Ranking
If you no longer want to receive notifications, reply to this comment with the word STOP

Check out our last posts:

Hive Power Up Month Challenge - July 2026 Winners List
Be ready for the August edition of the Hive Power Up Month!
Hive Power Up Day - August 1st 2026
0
0
0.000
avatar

Thanks for your contribution to the STEMsocial community. Feel free to join us on discord to get to know the rest of us!

Please consider delegating to the @stemsocial account (85% of the curation rewards are returned).

Consider setting @stemsocial as a beneficiary of this post's rewards if you would like to support the community and contribute to its mission of promoting science and education on Hive. 
 

0
0
0.000