0Pricing
LLM Apps in Production (RAG + Vector DB + Caching) · Aula

Engenharia de prompts e janelas de contexto

Entenda a janela de contexto que limita cada chamada ao LLM e aprenda a criar prompts que acomodem juntos o contexto recuperado, as instruções e as perguntas para obter respostas confiáveis em produção.

Engenharia de prompts e janelas de contexto é uma aula grátis de LLM Apps in Production (RAG + Vector DB + Caching) no CoddyKit. Esta é a aula 4 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de LLM Apps in Production (RAG + Vector DB + Caching), e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de LLM Apps in Production (RAG + Vector DB + Caching) inclui 4 aulas no total.

Partes desta aula ainda não foram traduzidas e aparecem em 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_output

Few-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.

Perguntas Frequentes

A aula “Engenharia de prompts e janelas de contexto” é grátis?

Sim — o texto completo de “Engenharia de prompts e janelas de contexto” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de LLM Apps in Production (RAG + Vector DB + Caching), atualize para CoddyKit PRO. O curso de LLM Apps in Production (RAG + Vector DB + Caching) inclui 4 aulas no total.

O que vou aprender em “Engenharia de prompts e janelas de contexto”?

Entenda a janela de contexto que limita cada chamada ao LLM e aprenda a criar prompts que acomodem juntos o contexto recuperado, as instruções e as perguntas para obter respostas confiáveis em produç… Você pratica LLM Apps in Production (RAG + Vector DB + Caching) com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.

Preciso ter experiência prévia para começar LLM Apps in Production (RAG + Vector DB + Caching)?

Nenhuma experiência prévia é necessária. LLM Apps in Production (RAG + Vector DB + Caching) no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 4 de 4.

Quanto tempo leva a aula “Engenharia de prompts e janelas de contexto”?

A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.

Posso escrever e executar código nesta aula de LLM Apps in Production (RAG + Vector DB + Caching)?

Sim. Cada aula de LLM Apps in Production (RAG + Vector DB + Caching) inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.

Todas as aulas deste curso

  1. Entendendo Aplicações de LLM em Produção
  2. Fundamentos da Geração Aumentada por Recuperação
  3. Visão Geral da Arquitetura Básica de um Sistema RAG
  4. Engenharia de prompts e janelas de contexto
← Voltar para LLM Apps in Production (RAG + Vector DB + Caching)