Beyond Prompts: Context Engineering for Intelligent Systems
Parna Mehta20:552026
Um agente de IA sem contexto pode reservar seu hotel em Paris, Kentucky
Peça a um agente baseado em engenharia de prompt que reserve um hotel em Paris para uma conferência e ele pode escolher a primeira Paris que encontrar: a do Kentucky. Para quem coloca IA agêntica em produção, a confiabilidade depende menos do modelo e mais do que chega até ele. Parna Mehta, engenheira de AIOps da AWS responsável pela precisão de sistemas agênticos e de RAG, pergunta o que um modelo precisa saber e o que descartar quando o espaço acaba.
Conheça os componentes, princípios e prioridades de poda por trás de agentes de IA confiáveis
Parna Mehta, AI Ops Engineer na AWS, defende que a IA agêntica em nível de produção depende menos de prompts engenhosos e mais da engenharia de todo o contexto que o modelo recebe: instruções de sistema, histórico da conversa, conhecimento recuperado, saídas de ferramentas, perfil do usuário e estado do fluxo de trabalho. Com exemplos de atendimento ao cliente e reserva de hotel, ela explica quatro princípios de um contexto eficaz e como priorizar e podar uma janela de contexto finita e cara.
“E se algo estiver dando errado, não culpe o modelo. Vá olhar o seu contexto.”
“Mas, como engenheira de contexto, a pergunta será: que informação devo apresentar ao meu LLM, ou o que o modelo deve saber?”
What you will learn
Diferenciar engenharia de contexto de engenharia de prompt, trocando a pergunta "o que dizer ao modelo" por "o que o modelo deve saber".
Identificar as seis fontes de contexto de que um agente precisa: instruções de sistema, histórico da conversa, fatos recuperados, saídas de ferramentas, perfil do usuário e estado do fluxo de trabalho.
Aplicar quatro princípios (exatidão, precisão, coesão e concisão) para decidir o que entra na janela de contexto.
Priorizar, resumir, comprimir e podar o contexto para controlar custo de tokens, latência e qualidade das respostas em produção.
Colocar as informações importantes no início e no fim do contexto para contornar o problema de "perda no meio" (lost in the middle).
Details
Level
Intermediate
Format
Talk
Technical depth
Practitioner
For
Early career, Mid-career, Senior individual contributor
Length
20:55
Published
June 2026
Questions this talk answers
O que é engenharia de contexto e como ela difere da engenharia de prompt?
É a prática sistemática de projetar, estruturar e otimizar todo o sistema de informações apresentado a um LLM. Quem faz engenharia de prompt pergunta o que dizer ao modelo; quem faz engenharia de contexto pergunta o que o modelo deve saber.
O que compõe o contexto de um agente de IA?
Instruções de sistema, histórico da conversa, fatos recuperados por RAG e bases de conhecimento, interações com ferramentas e suas saídas, o perfil do usuário e o estado atual do fluxo de trabalho. Juntos, eles formam a janela de contexto de instruções, conhecimento e ferramentas.
Por que não simplesmente encher uma grande janela de contexto com tudo?
Tokens são finitos e caros, mais tokens aumentam custo e latência, e sobrecarregar o modelo pode piorar a qualidade das respostas. Só a informação certa deve entrar.
O que deve ser descartado primeiro quando a janela de contexto fica cheia?
Os componentes de menor prioridade, como exemplos few-shot e partes do histórico da conversa. As instruções de sistema nunca devem ser removidas.
O que fazer quando um agente produz resultados ruins?
Não culpe o modelo; examine o contexto. Trate o contexto como um sistema, com o mesmo rigor que você aplicaria a um pipeline de dados.
Perdido no palco: por que LLMs precisam de contexto (78 s)
O problema de Paris, Kentucky (88 s)
Não culpe o modelo, verifique o contexto (80 s)
Parna Mehta: All right, folks, thank you so much for joining in on time and taking our time to join my session. A very warm welcome to my session on Context Engineering for Intelligent Systems. My name is Parna. I work for AWS and I'm an AIOps engineer. So my day to day life is spent in cloud and AI/ML. And I'm glad that I'm able to do this on the cloud.
I've shared my insights with you and I'm loving the atmosphere here and love all the motivation and inspiration I'm getting from the other sessions as well. So thank you so much for joining in. We start. So just imagine that you've gone for a play to attend a play of your friend and you are backstage and suddenly you realize that the main character is unwell and they just hand over a script to you and just tell you you've got 10 minutes and you've got to perform.
These are your lines and they push you after 10 minutes. So imagine you are standing on the stage. You have your lines, but you have no clue. You don't have any clue about the context. What are the props? There is a seat over there. You don't know. Are you supposed to sit there? Are you supposed to use it? There are other actors and actresses on the stage. You don't know how you are going to interact with them. You don't know your audience. And finally, you don't know your play. You're lost without context. So imagine this is exactly the the way a LLM would feel if you would just give it a few lines of query and ask it to perform and give it its best performance. Do you think it will perform that well? Of course it won't,
right? So the systematic practice of designing, structuring and optimizing your entire information system before you present it to your LLM is actually the funda of context engineering. In plain prompt engineering, you just have a user input which you pass to the LLM and the LLM through its learned knowledge and its previous trainings, it's going to give you the best answer possible. But that's not good enough in this age. In this age of agentic AI, you need an entire information system to pass information dynamically at the right time of the right quantity and of the right relevance to the LML to get the best response. So what does this have in it? It has the user input, it has memory of past interaction, it will be your rag retrieved documents, it could
have the state of the workflows. Suppose your agent is doing a multi-step workflow, it's a complex workflow, it has to remember which step it is on, right? Plus, it has to have awareness of all its tools. All this assembled together is presented to your LLM and this is known as context engineering. So previously, as a context engineer, sorry, as a prompt engineer, you would focus on what should I say to the LLM or what should my instruction be? But as a context engineer, it will be what information should I present to my LLM or what should the model know? Now, it is an entirely art and science of dynamically curating all this information from different sources, external, internal files, the user input from memory. All of these together is dynamically given at the right time to the LLM
at runtime. Now, which are the components of your context engineering? So the first and foremost component would be your system instructions. Now, what are system instructions? So this is the guiding principle of your agent, right? What is its goal? What is its persona? What is it supposed to do? How is it supposed to behave? The entire guideline is given in your system instructions. This is the most important.
Then comes your conversation history. So if it's a multi-turn interaction, you are constantly talking to your agent and giving it queries or instructions or fine tuning your instructions further. That information also forms part of your context. Then, of course, you have facts. You have your enterprise data. So you're going to retrieve them through your RAG systems and knowledge bases. That is going to be your other source of context. Of course, the brain without hands is of no use. So they're going to be actions or tool interactions. So every time a tool is called, whatever responses the tool is given, that is also your context. Then the person who's actually interacting with your agent, the user, their profile, they could be a customer, they could be an administrator, they could be a developer, they could be anyone. So information
about that user will also alter the way the agent will behave. And finally, what state it is in. So if it is taking a multi-step process, it is following a standard operating procedure, which step it is on, that also the agent needs to remember. All of this become a part of your context. Now, when you package all of them together, this little box is known as your context window. Now your context window will be made up on the high level of instructions, like your system instructions, past memories, maybe you've given it few examples of how you want the output to be, your tool descriptions, all that policies, guidelines, all that form your instructions. Then comes the knowledge, knowledge is from your RAG sources, or it could even be your steering docs, okay, which will steer the behavior of your agent.
It could be best practices. All of this will form your knowledge. And then you have the tools. Tools are not only the actions that the LLM can take, but also the output of those tool actions that it has taken. It has to remember that. All this together in a little box is known as the context window. Now, in a traditional customer service interaction, you can see over here, I hope you can. There is a customer who comes in and says, I'm having trouble with my subscription renewal. It has been renewed twice. Now, a traditional way of a bot or a chat agent would be, I'm sorry to hear that. Can I get your account number or your email address?
That's the way they're going to identify who's coming. So you'll obviously give your email address. So you can see Sarah has given their email address. Again, the bot is going to ask you, can you verify your billing address for security? You must have heard this before. So it'll ask you the second level of identification. Sarah provides that. See, it's still it's not really got to the point. Then it's going to ask you, OK, tell me about your subscription.
When did you notice this double charge? And it still doesn't know that the user is on a pro plan or on a basic plan doesn't have any clue. It's not using its context information. And this can go on. And after a while, maybe the agent will say, oh, looks like I need to transfer you to another agent.
This is wasted time, right? You could spend anywhere between 10 minutes to 40 minutes to an hour just doing back and forth and realizing you just have been transferred. But how is it different in a context engineered support? Now, over here, say Sarah has come in, in the background, the agent would have already preloaded information about Sarah, that they are on a pro plan.
They have started their subscription, say, n months ago, and maybe it has already detected there was a double charge that was charged to Sarah's account. So it has already collected all that information in the back end. So it doesn't need to ask what is your email address or what is your billing address. It doesn't need to know that. So it can directly say, hey, Sarah, it welcomes you in a personalized way.
I can see that you already have a duplicate charge of twenty nine dollars and you are on a pro plan. And in the background, it probably already has a playbook or a standard operating procedure, what to do in case of a duplicate charge. So it has that playbook already in its context. So it knows what to do next.
So it says over here, in case there's a duplicate charge and it's below fifty dollars, offer them a refund. OK, we want to wow our customers. So you can see immediately the agent has already asked for initiating a refund. Right. So you can see how fast the interaction has flowed just in a couple of seconds or minutes, I would say.
And you see that the customer also gets wowed by it. Right. That was fast, you know. So when will I get it? Probably in the next month. Will it happen now or in the next month? But it already has that answer because it knows that a refund will be initiated. It will come back in about two, three days. It has all that information.
So it can give it to this. So this is the difference between a prompt engineer and a context engineer. I'll give you another example. Also, say Sarah comes in again and she's saying that she's having trouble with her recent order and she's given her recent order number in the background. So in the background, you'll see that the agent has already collected her user profile information that she's been a premium customer.
She's spent X amount of dollars in her past interactions. What is her current order? All the information is already there, where it is at this stage for tracking purpose, because the agent is preempting that probably Sarah is going to ask about tracking or some problem related to the last order. So it has all that information. Plus, it has previous memories of historic memories of the previous interactions as well.
It knows that there was a damage package in the last delivery that happened. So it has information about that, too. Now, all this together, plus its overarching goal as an agent, it knows at every stage I need to wow the customer. OK, so for every interaction, I need to raise the customer sentiments high, get a high customer rating.
I should try and do that in whatever way possible, having all this context. Now, when you go through the interaction, you see it already knows that it's speaking to Sarah knows all the information about the package. So it can instantly tell Sarah that, hey, it's going to be shipped in three days. And this is your tracking number and estimation time is tomorrow, day after, whatever.
And because it already had context that Sarah was a premium customer, it knows that premium customers usually like expedited delivery. So it will jump on that and it will say that, hey, do you want me to expedite it at no cost to you? Because she is a privileged customer at all. So this is everything without Sarah having to say anything and it is already offered to the customer.
Obviously, you know that Sarah will be really happy and she says that's great. And then she talks about her previous order. Remember that the agent already knows about it, right? It has context. And she asks, I had a problem with my previous order. There was a packaging issue and the agent already knows about it and it knows it has to wow the customer.
So it says that, yes, I do remember. I know the order number as well because it has the interaction history and I know it had damaged packaging. So I have ensured that you get reinforced packaging this time. And I'm going to wow you by giving you an additional 15% discount because it knows from previous interaction that this customer likes getting discounts and refunds.
And it's got a high rating because of that. All this put together, you can see what a splendid interaction this has become all because of context engineering. So that was one example just to showcase about context engineering. Now, going into what forms, what are the principles of effective context engineering? Now, this agent will effectively work only if it is given accurate information.
So if it's not given the right information, probably the background query would have given past interaction of some other customer. Then it would have landed up giving wrong information, right, to Sara. So having the correct information is very important. Also, for example, when you're talking to an AI agent and giving it information about files, if you've given it a wrong file path, then you've given it a file name which has another file with the same name.
So it will keep searching for it. So giving it the right file path, right location, right query from the database to get the customer data, for example, is very important. Preciseness. Now, preciseness is ensuring that you exactly let the agent know what you need. So for example, if this is a coding agent, if you just give it a piece of code and ask it to improve it or make it better, that's not precise.
So it might just go ahead and make some changes to the variable naming or it might just, you know, reorder and add some good comments. But probably what you meant was refactor my code, modularize my code, or if you would have been very specific, you could have said add a validation for null values. So it exactly knows what to do.
So preciseness is very important. Cohesiveness. Now, the information that is coming from different sources, the signal to noise ratio should be large. So there should not be unnecessary information which is flooding your context. For example, you want the agent to help you understand or refactor a particular function, then providing it with the entire code based on the repository information is unnecessary.
You're just wasting tokens or you're just wasting that finite context window that you have. Here, the amount of noise is more, but when you focus on an area, the agent will perform better. Conciseness is giving just the right amount of information, not too much, not too little. So, for example, if you are going to ask your agent to debug a problem in your code and you're going to give it logs, would you give it logs for that time period that you saw the problem or would you give it logs for the entire month?
It's better to give it only for that time period, right? So just the right amount of information, not too much. So these are some guiding principles. Let me take you to another problem. This is a fun one. It's called as the Paris, Kentucky problem. Yeah. Did you know that there is a Paris in Kentucky? When I was doing my research, I found out that there is a Paris there, too.
Now, think of a typical prompt engineered agent. And you said, book me a hotel in Paris for the Women in Tech Global Conference. Nothing else. No context. Nothing. Now, this agent will pick the first Paris that comes in its search and it might pick the one in Kentucky. But actually, the Paris conference possibly is in France. It did not bother to look that up.
And it went and booked you into one of the hotels, which probably you don't approve of. So you've not given it much information. So it's just gone and did what it felt like. Okay. So this is a complete failure. Now, think of a context engineered agent. It will first go and search up all the conferences, women in tech conferences, which are happening around the world, which are upcoming.
And it will search and give that there is one happening in Paris, France. So you got verified output. That is one. Then it knows that you cannot just go and book a hotel or an airline, which falls outside your company policy. So you will have corporate limits. So the agent needs to purchase based on that limit. So it will gather and retrieve that information from your rag sources.
Plus, it knows your user preferences. It has interacted with you before. It knows your preferred chain of hotels as well. So what you get is a correct, compliant and a very personalized response. So this is the power of context engineering. Now, there are different components. As you can see, there is a system prompt, user message, tool descriptions, agent responses, retrieve data and tool outputs.
Out of all of these, your static components are your system prompt and your tool descriptions. The remaining will keep growing in size. But remember, in production, your context window is finite and you have to prioritize amongst each component. Now, which component will you remove if you have to drop it from a context? The one with the least priority.
You will never remove your system instructions, right? We'll come to that. But just to give you an idea that what is exactly context window. Say you have a small window and you ask the agent, how many buildings can you see? It can see three buildings. But if you have large French windows, it can actually see multiple buildings.
It has more information. So you might be tempted to flood it with a lot of information. Now, remember, your context window is made up of tokens. Tokens are expensive. There is a finite limit to these tokens. As we have more advanced models, obviously, they have a bigger context window. But the question is, don't put everything into the context window.
Put only the right information. Okay. Because tokens have a cost to it. More number of tokens, meaning more cost. More tokens, meaning latency will also increase. You don't want your user waiting forever. Sometimes you see agents, it goes into this thinking loop. And your quality might deteriorate because you're overwhelming it. So of course, when you're going into production, all these factors are really important.
There are agents which are smart, which can actually tell you which components fill out which part of your context. So you get an idea of how much your context is remaining. You can take some active steps to actually go and summarize it yourself and compress it or prune it or get rid of some past interaction. Or the agent might summarize it when it hits that limit.
Now, which all things need to be dropped is very important. I've shown you there's a priority. This is also priority. So if at the lowest end is your few short examples, you'd rather get rid of that and some part of your conversation than have a non-compliant output, which you saw in the Paris, Kentucky problem. Apart from that, there are other pitfalls also.
Remember, your LLMs have this lost in the middle problem. It tends to lose focus on context in the middle and always focuses on the end. So you can use some strategies such that your important tokens are always towards the beginning and end. Of course, you can make sure that your token, your context window is not overwhelmed. It is not confused with large number of outputs from conflicting instructions or outputs from tools such that it fails.
Finally, I would leave you with this relevance is more important than the volume. Context is a system. It's not just a single prompt. It is a whole system treated with the same rigor that you would do for a data pipeline. And if something is going wrong, do not blame the model. Go and look at your context. Finally, I would say the context window is the new idea.
Go and explore and build something great. Thank you so much. And I think the future of AI engineers is by being great context architects. Thank you so much for being and attending my session. This is my QR code to my LinkedIn. Please feel free to connect with me and I'd love to know how you found this session.
Thank you so much.
Transcribed automatically; names checked against the speaker record. Select a time to jump there.
Article based on this talk
Por que agentes de IA confiáveis dependem de contexto, não de prompts engenhosos
Parna Mehta, da AWS, explica o que um agente precisa saber, como avaliar um bom contexto e o que cortar quando a janela fica cheia.
Em resumo
Parna Mehta, AI Ops Engineer na AWS, defende que agentes de IA em produção têm sucesso ou fracassam pela informação que recebem, e não por frases engenhosas. Engenharia de contexto, na visão dela, é a prática de projetar todo o sistema de informações em torno de um modelo: instruções, memória, conhecimento recuperado, saídas de ferramentas, perfil do usuário e estado do fluxo de trabalho, entregues no momento certo e na quantidade certa. O conselho final dela é simples: quando um agente erra, olhe o contexto antes de culpar o modelo.
Principais pontos
O que é engenharia de contexto e por que ela importa
Tipos de contexto
Técnicas de engenharia de contexto
Boas práticas e armadilhas comuns a evitar
Um ator com um roteiro e nenhum contexto
Mehta abre com uma cena: você está nos bastidores da peça de uma amiga, o ator principal fica doente e, dez minutos depois, você é empurrado para o palco só com as suas falas. Você não conhece os adereços, os outros atores, a plateia nem mesmo a peça. "E, por fim, você não conhece a sua peça. Você está perdido sem contexto." (0:59)
É assim, diz ela, que um grande modelo de linguagem se sente quando recebe apenas algumas linhas de consulta. A engenharia de prompt passa a entrada do usuário ao modelo e depende do que ele aprendeu no treinamento. Na era da IA agêntica, argumenta ela, isso já não basta: o modelo precisa de todo um sistema de informações que forneça dados relevantes de forma dinâmica, em tempo de execução. A mudança de mentalidade se resume a uma pergunta: "Mas, como engenheira de contexto, a pergunta será: que informação devo apresentar ao meu LLM, ou o que o modelo deve saber?" (2:37)
O que entra na janela de contexto
Mehta lista os componentes que um agente utiliza. As instruções de sistema vêm primeiro e são as mais importantes: o objetivo do agente, sua persona e o comportamento esperado. Depois vêm o histórico de interações com vários turnos, fatos e dados corporativos recuperados por sistemas de RAG e bases de conhecimento, chamadas de ferramentas e suas respostas, o perfil do usuário (um cliente, um administrador ou um desenvolvedor) e o estado de qualquer fluxo de trabalho com várias etapas ou procedimento operacional padrão. Sobre ferramentas, ela é direta: "Claro, um cérebro sem mãos não serve para nada." (4:04)
Reunidos, esses elementos formam a janela de contexto, que ela agrupa em três blocos. Instruções abrangem o prompt de sistema, memórias anteriores, exemplos few-shot, descrições de ferramentas, políticas e diretrizes. Conhecimento abrange fontes de RAG, documentos de orientação e boas práticas. Ferramentas abrangem tanto as ações disponíveis para o modelo quanto as saídas das ações que ele já executou.
Duas conversas com clientes, com e sem contexto
Para tornar a diferença concreta, Mehta percorre um chat de suporte. Uma cliente chamada Sarah relata uma assinatura renovada duas vezes. O bot tradicional pede o e-mail dela, depois o endereço de cobrança, depois quando ela percebeu a cobrança, tudo sem saber qual é o plano dela, e pode acabar transferindo-a para outro atendente. "Isso é tempo desperdiçado, certo?" (7:32)
Na versão com engenharia de contexto, o agente já carregou o plano pro de Sarah, o histórico da assinatura e a cobrança duplicada de US$ 29, junto com um playbook que manda reembolsar cobranças duplicadas abaixo de US$ 50. Ele a cumprimenta pelo nome, inicia o reembolso e informa quando o dinheiro vai chegar. Um segundo exemplo acrescenta rastreamento de pedidos, interações anteriores e um objetivo geral de encantar o cliente: o agente oferece entrega expressa gratuita a uma cliente premium, lembra de um pacote que chegou danificado antes, promete embalagem reforçada e acrescenta um desconto. "Juntando tudo isso, dá para ver que interação esplêndida isso se tornou, tudo graças à engenharia de contexto." (12:16)
Quatro princípios e o problema de Paris, Kentucky
Em seguida, Mehta apresenta quatro princípios de um contexto eficaz. Exatidão: entradas erradas, como o histórico de outro cliente ou um caminho de arquivo ambíguo, levam a respostas erradas. Precisão: pedir a um agente de programação que melhore o código abre espaço para mudanças cosméticas, enquanto pedir que adicione uma validação para valores nulos diz exatamente o que fazer. Coesão: mantenha alta a relação sinal-ruído, então não entregue um repositório inteiro para refatorar uma única função. "Você está só desperdiçando tokens, ou desperdiçando aquela janela de contexto finita que você tem." (14:32) Concisão: ao depurar, compartilhe logs do período em que o problema apareceu, não do mês inteiro.
Ela chama o exemplo seguinte de divertido: o problema de Paris, Kentucky. Ao receber o pedido de reservar um hotel em Paris para a Women in Tech Global Conference sem mais contexto, um agente baseado em engenharia de prompt pode escolher a primeira Paris que encontrar, possivelmente a do Kentucky, e um hotel que você não aprovaria. Um agente com engenharia de contexto primeiro verifica onde a conferência vai acontecer, recupera os limites da política de viagens corporativas nas fontes de RAG e aplica suas preferências de hotel já conhecidas. "Então o que você obtém é uma resposta correta, em conformidade e muito personalizada." (16:42)
Gerenciando uma janela finita e cara
Modelos mais avançados oferecem janelas de contexto maiores, e Mehta reconhece a tentação de enchê-las. O alerta dela é que tokens são finitos e caros. "Mais tokens significa mais custo. Mais tokens significa que a latência também vai aumentar." (18:13) Sobrecarregar o modelo também pode reduzir a qualidade, e os agentes podem ficar presos em loops de raciocínio.
Prompts de sistema e descrições de ferramentas permanecem estáticos, enquanto mensagens do usuário, respostas do agente, dados recuperados e saídas de ferramentas continuam crescendo. Por isso, as equipes precisam priorizar, resumir, comprimir e podar, seja ativamente, seja deixando o agente resumir quando atinge o limite. Quando algo precisa sair, descarte os itens de menor prioridade, como exemplos few-shot e partes da conversa, e nunca as instruções de sistema. Ela também aponta o problema de "perda no meio" (lost in the middle), em que os modelos perdem o foco no conteúdo do meio do contexto, e recomenda manter os tokens importantes perto do início e do fim.
Os princípios com que ela encerra: relevância importa mais que volume, e o contexto é um sistema que deve ser tratado com o mesmo rigor de um pipeline de dados. "E se algo estiver dando errado, não culpe o modelo. Vá olhar o seu contexto." (20:00)
Assista à palestra
Beyond Prompts: Context Engineering for Intelligent Systems, por Parna Mehta, 21 minutos: https://www.womentech.net/video/beyond-prompts-context-engineering-intelligent-systems
Sobre a palestrante
Parna Mehta é AI Ops Engineer na AWS e profissional de nuvem e IA/ML com 8 certificações AWS e mais de 12 anos de experiência no setor, responsável por garantir a qualidade, a confiabilidade e a precisão de sistemas de IA agêntica e de GenAI baseados em RAG. O recomeço da carreira dela após uma pausa de 13 anos foi reconhecido com os prêmios AWS SheDares, AWS Empower.eve e HerRising, e ela retribui como mentora e como co-organizadora principal da comunidade BeSA Cloud.
Perguntas que esta palestra responde
O que é engenharia de contexto e como ela difere da engenharia de prompt?
O que compõe o contexto de um agente de IA?
Por que não simplesmente encher uma grande janela de contexto com tudo?
O que deve ser descartado primeiro quando a janela de contexto fica cheia?
O que fazer quando um agente produz resultados ruins?
Rascunho gerado com IA a partir da transcrição da palestra. Revisão editorial pendente.