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


|
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 |
What a Token Is |

|
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ñolEso 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 SpanishThat 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" |
The Model Doesn't "Reason" |

|
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 contextoPor 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 WindowFor 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
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
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. |

prompt-engineering
inteligencia-artificial
machine-learning
llm
educacion
ai-learning
tecnologia
stem
aprendizaje
0
0
0.000
Congratulations @richard-mvm! You have completed the following achievement on the Hive blockchain And have been rewarded with New badge(s)
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
STOPCheck out our last posts:
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.