Стратегии памяти сущностей и сводок
Выйдите за пределы простых буферов: отслеживайте именованные сущности и обновляемые сводки, чтобы агенты помнили важные факты в длинных беседах без чрезмерного расхода токенов.
«Стратегии памяти сущностей и сводок» — бесплатный урок AI Agents with LangChain & Autonomous Workflows на CoddyKit. Это урок 4 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения AI Agents with LangChain & Autonomous Workflows, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс AI Agents with LangChain & Autonomous Workflows содержит 4 уроков всего.
Части этого урока еще не переведены и отображаются на английском.
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.
Изучай AI Agents with LangChain & Autonomous Workflows с ИИ-репетитором — бесплатно
Пиши и запускай код прямо в браузере, получай мгновенную помощь от ИИ-репетитора 24/7 и продолжи учиться на сайте или в приложении.
- Курсы
- 12
- Уроки
- 50
Часто задаваемые вопросы
Урок «Стратегии памяти сущностей и сводок» бесплатный?
Да — полный текст урока «Стратегии памяти сущностей и сводок» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс AI Agents with LangChain & Autonomous Workflows, подпишись на CoddyKit PRO. Курс AI Agents with LangChain & Autonomous Workflows содержит 4 уроков всего.
Чему я научусь в уроке «Стратегии памяти сущностей и сводок»?
Выйдите за пределы простых буферов: отслеживайте именованные сущности и обновляемые сводки, чтобы агенты помнили важные факты в длинных беседах без чрезмерного расхода токенов. Ты практикуешь AI Agents with LangChain & Autonomous Workflows с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать AI Agents with LangChain & Autonomous Workflows?
Предыдущий опыт не требуется. AI Agents with LangChain & Autonomous Workflows на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 4 из 4.
Сколько времени занимает урок «Стратегии памяти сущностей и сводок»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке AI Agents with LangChain & Autonomous Workflows?
Да. Каждый урок AI Agents with LangChain & Autonomous Workflows включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.
Все уроки этого курса
- Понятие памяти агентов
- Буферная память диалога
- Продвинутые решения для памяти
- Стратегии памяти сущностей и сводок