Estratégias de memória de entidades e resumos
Vá além dos buffers brutos acompanhando entidades nomeadas e resumos progressivos para que os agentes se lembrem dos fatos importantes em conversas longas sem estourar o orçamento de tokens.
Estratégias de memória de entidades e resumos é uma aula grátis de AI Agents with LangChain & Autonomous Workflows 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 AI Agents with LangChain & Autonomous Workflows, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de AI Agents with LangChain & Autonomous Workflows inclui 4 aulas no total.
Partes desta aula ainda não foram traduzidas e aparecem em inglês.
Why Buffers Are Not Enough
A plain buffer stores every message verbatim. In long chats this quickly exceeds the model context window and wastes tokens on irrelevant chatter.
Two smarter strategies fix this: summary memory compresses the past, and entity memory tracks specific facts about people and things.
What Is Summary Memory?
Summary memory uses an LLM to keep a running, condensed summary of the conversation. Instead of replaying 50 turns, the agent reads a few sentences capturing the gist.
- Keeps token usage roughly constant
- Preserves long-term context
- Loses fine-grained wording
ConversationSummaryMemory
LangChain's ConversationSummaryMemory calls the LLM after each turn to update the summary. You pass it the same model the agent uses.
from langchain.memory import ConversationSummaryMemory
from langchain_openai import ChatOpenAI
llm = ChatOpenAI(model='gpt-4o-mini')
memory = ConversationSummaryMemory(llm=llm)Saving and Reading the Summary
As turns happen you save context; reading the variables returns the compressed history rather than raw turns.
memory.save_context(
{'input': 'My name is Ana and I love hiking.'},
{'output': 'Nice to meet you, Ana!'}
)
print(memory.load_memory_variables({}))Summary Buffer: Best of Both
ConversationSummaryBufferMemory keeps recent turns verbatim AND summarizes older ones once a token limit is crossed. Recent context stays sharp while old context is compressed.
from langchain.memory import ConversationSummaryBufferMemory
memory = ConversationSummaryBufferMemory(
llm=llm,
max_token_limit=200
)What Is Entity Memory?
Entity memory extracts named things — people, projects, places — and stores a fact sheet for each. When an entity reappears, the agent recalls exactly what it knows.
This is ideal for personal assistants that must remember user preferences.
ConversationEntityMemory
The entity memory uses the LLM to detect entities and maintain a per-entity store.
from langchain.memory import ConversationEntityMemory
memory = ConversationEntityMemory(llm=llm)
memory.save_context(
{'input': 'Deepak is leading the Mars project.'},
{'output': 'Got it.'}
)Inspecting the Entity Store
Each entity accumulates facts. Asking about an entity loads only its relevant summary into the prompt.
vars = memory.load_memory_variables(
{'input': 'What is Deepak working on?'}
)
print(vars['entities'])Choosing a Strategy
Pick based on the use case:
- Buffer: short, exact conversations
- Summary: long chats where the gist matters
- Summary Buffer: long chats needing recent precision
- Entity: assistants tracking facts about specific subjects
Cost and Latency Trade-offs
Summary and entity memory make extra LLM calls on every turn to update their state. That adds cost and latency.
Use cheaper, faster models for the memory-update step than for the main agent reasoning when possible.
Combining Memories
For sophisticated agents you can combine memories with CombinedMemory, e.g. a summary for flow plus entity memory for facts. Just ensure their output keys do not collide.
from langchain.memory import CombinedMemory
memory = CombinedMemory(memories=[summary_mem, entity_mem])Quick Check
Test your understanding of advanced memory strategies.
Recap
You learned memory strategies beyond raw buffers:
- Summary memory compresses history with the LLM
- Summary buffer keeps recent turns exact and summarizes the rest
- Entity memory tracks facts about named subjects
- Each adds LLM calls — balance cost vs. recall
- Combine memories for richer agents
Choosing the right strategy keeps agents both knowledgeable and efficient.
Perguntas Frequentes
A aula “Estratégias de memória de entidades e resumos” é grátis?
Sim — o texto completo de “Estratégias de memória de entidades e resumos” é 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 AI Agents with LangChain & Autonomous Workflows, atualize para CoddyKit PRO. O curso de AI Agents with LangChain & Autonomous Workflows inclui 4 aulas no total.
O que vou aprender em “Estratégias de memória de entidades e resumos”?
Vá além dos buffers brutos acompanhando entidades nomeadas e resumos progressivos para que os agentes se lembrem dos fatos importantes em conversas longas sem estourar o orçamento de tokens. Você pratica AI Agents with LangChain & Autonomous Workflows 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 AI Agents with LangChain & Autonomous Workflows?
Nenhuma experiência prévia é necessária. AI Agents with LangChain & Autonomous Workflows 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 “Estratégias de memória de entidades e resumos”?
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 AI Agents with LangChain & Autonomous Workflows?
Sim. Cada aula de AI Agents with LangChain & Autonomous Workflows 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
- Conceitos de memória dos agentes
- Memória de buffer de conversação
- Soluções avançadas de memória
- Estratégias de memória de entidades e resumos