Prompt engineering y ventanas de contexto
Comprenda la ventana de contexto que limita cada llamada al LLM y aprenda a crear prompts que integren el contexto recuperado, las instrucciones y las preguntas para obtener respuestas fiables en producción.
Prompt engineering y ventanas de contexto es una lección gratuita de LLM Apps in Production (RAG + Vector DB + Caching) en CoddyKit. Esta es la lección 4 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de LLM Apps in Production (RAG + Vector DB + Caching), y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de LLM Apps in Production (RAG + Vector DB + Caching) incluye 4 lecciones en total.
Partes de esta lección aún no han sido traducidas y se muestran en inglés.
The Context Window
Every LLM has a fixed context window — the max tokens it reads and writes per call. System prompt, retrieved docs, history, and your question all have to fit.
What Lives in the Window
A production RAG prompt packs in system instructions, retrieved context, prior history, and the current question. Exceed the window and something gets cut.
Anatomy of a Prompt
A clear prompt structure helps the model tell instructions apart from data. Here's a clean layout separating context from the question.
prompt = (
'You are a support assistant. '
'Answer ONLY from the context.\n\n'
'Context:\n{context}\n\n'
'Question: {question}'
)Grounding Instructions
To cut hallucination, add grounding instructions: tell the model to answer only from the provided context and to admit when it doesn't know.
rule = 'If the answer is not in the context, say you do not know.'Using a Prompt Template
A prompt template makes prompts reusable and safe to fill with variables. LangChain's ChatPromptTemplate does exactly this.
from langchain_core.prompts import ChatPromptTemplate
template = ChatPromptTemplate.from_messages([
('system', 'Answer only from context: {context}'),
('human', '{question}')
])Counting Tokens
Before sending, count tokens so you don't overflow the window. Rough rule for English: about 4 characters per token.
import tiktoken
enc = tiktoken.get_encoding('cl100k_base')
print(len(enc.encode(filled_prompt)))When Context Is Too Big
When context is too big, shrink it: fewer chunks, smaller chunk sizes, or summarize. Never silently truncate the middle — you might drop the answer.
The Lost-in-the-Middle Effect
Watch the lost-in-the-middle effect: models attend best to the start and end of context, worst to the middle. Put your most relevant chunks first or last.
Reserving Output Space
Input and output share the window. Fill it all with input and there's no room to generate — so reserve output space for the expected answer length.
max_output = 800
budget_for_input = WINDOW - max_outputFew-Shot Examples
A few few-shot examples can steer format and tone, but they eat tokens. Weigh their value against the space they consume.
Iterating on Prompts
Prompt engineering is empirical: change one thing at a time, test on real questions, and measure. Small wording tweaks can shift answer quality a lot.
Quick Check
Test your understanding of context windows.
Recap
Recap: the context window holds system, context, history, question, and output. Structure prompts, ground them, count tokens, beat lost-in-the-middle, and reserve output room.
Preguntas frecuentes
¿La lección «Prompt engineering y ventanas de contexto» es gratis?
Sí — el texto completo de «Prompt engineering y ventanas de contexto» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de LLM Apps in Production (RAG + Vector DB + Caching), actualiza a CoddyKit PRO. El curso de LLM Apps in Production (RAG + Vector DB + Caching) incluye 4 lecciones en total.
¿Qué aprenderé en «Prompt engineering y ventanas de contexto»?
Comprenda la ventana de contexto que limita cada llamada al LLM y aprenda a crear prompts que integren el contexto recuperado, las instrucciones y las preguntas para obtener respuestas fiables en pro… Practicas LLM Apps in Production (RAG + Vector DB + Caching) con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.
¿Necesito experiencia previa para empezar LLM Apps in Production (RAG + Vector DB + Caching)?
No se requiere experiencia previa. LLM Apps in Production (RAG + Vector DB + Caching) en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 4 de 4.
¿Cuánto tiempo toma la lección «Prompt engineering y ventanas de contexto»?
La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.
¿Puedo escribir y ejecutar código en esta lección de LLM Apps in Production (RAG + Vector DB + Caching)?
Sí. Cada lección de LLM Apps in Production (RAG + Vector DB + Caching) incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.
Todas las lecciones de este curso
- Comprender las aplicaciones de LLM en producción
- Fundamentos de Retrieval Augmented Generation
- Descripción general de la arquitectura básica de un sistema RAG
- Prompt engineering y ventanas de contexto