0Pricing
LangChain / RAG / Vector DBs · Урок

Память и контекст диалога в LangChain

Узнайте, как память LangChain отслеживает историю диалога, позволяя цепочкам и чат-ботам поддерживать связные многошаговые беседы.

«Память и контекст диалога в LangChain» — бесплатный урок LangChain / RAG / Vector DBs на CoddyKit. Это урок 4 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения LangChain / RAG / Vector DBs, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс LangChain / RAG / Vector DBs содержит 4 уроков всего.

Части этого урока еще не переведены и отображаются на английском.

LLMs Are Stateless

A language model has no memory between calls. Each request is independent — it only knows what you put in the current prompt. To build a chatbot that remembers, you must feed prior turns back in yourself.

What LangChain Memory Does

LangChain memory automates this: it stores the conversation and injects relevant history into the prompt on each new turn. Your chain stays simple while the model appears to remember.

Conversation Buffer Memory

The simplest memory keeps the full transcript and prepends it to every prompt. Great for short chats, but it grows with every turn.

from langchain.memory import ConversationBufferMemory
memory = ConversationBufferMemory()
memory.save_context({'input': 'Hi, I am Sam'}, {'output': 'Hello Sam!'})
print(memory.load_memory_variables({}))

The Context Window Limit

Every model has a finite context window (a token budget). A growing buffer eventually overflows it, causing errors or truncation. Managing history size is the central challenge of memory.

turns = 50
tokens_per_turn = 200
total = turns * tokens_per_turn
print('history tokens:', total)

Window Memory

ConversationBufferWindowMemory keeps only the last k turns. It bounds token usage at the cost of forgetting older context — a simple, effective trade-off for many chatbots.

from langchain.memory import ConversationBufferWindowMemory
memory = ConversationBufferWindowMemory(k=3)
# only the most recent 3 exchanges are kept

Summary Memory

ConversationSummaryMemory uses the LLM to compress old turns into a running summary. You keep the gist of a long conversation in far fewer tokens, sacrificing exact wording for breadth.

Summary Buffer: Best of Both

ConversationSummaryBufferMemory keeps recent turns verbatim and summarizes everything older. Recent context stays precise while distant context is condensed — a popular default for production chatbots.

Wiring Memory into a Chain

You attach memory to a conversational chain. On each call, the chain loads history, builds the prompt, calls the model, and saves the new turn back to memory automatically.

from langchain.chains import ConversationChain
chain = ConversationChain(llm=llm, memory=memory)
chain.predict(input='What is my name?')

Memory Variables and Prompts

Memory exposes its content as a variable (often history or chat_history) that your prompt template references. The placeholder is where the stored conversation gets injected.

template = 'Conversation so far:\n{history}\nHuman: {input}\nAI:'

Persisting Memory

In-process memory vanishes when the app restarts. For real users, back memory with a store — Redis, a database, or a chat-message-history backend keyed by session id — so conversations survive across requests and servers.

Choosing a Memory Type

Match memory to need: buffer for short chats, window when you only care about recent turns, summary for long sessions on a budget, and summary-buffer for the common case. Always persist memory for multi-user apps.

Quick Check

Test your understanding of LangChain memory.

Recap

You learned how LangChain gives chatbots memory:

  • LLMs are stateless; memory re-injects history each turn
  • Buffer, window, summary, and summary-buffer trade detail against tokens
  • Memory exposes a history variable that the prompt template uses
  • Persist memory per session for multi-user, multi-server apps

Часто задаваемые вопросы

Урок «Память и контекст диалога в LangChain» бесплатный?

Да — полный текст урока «Память и контекст диалога в LangChain» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс LangChain / RAG / Vector DBs, подпишись на CoddyKit PRO. Курс LangChain / RAG / Vector DBs содержит 4 уроков всего.

Чему я научусь в уроке «Память и контекст диалога в LangChain»?

Узнайте, как память LangChain отслеживает историю диалога, позволяя цепочкам и чат-ботам поддерживать связные многошаговые беседы. Ты практикуешь LangChain / RAG / Vector DBs с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.

Нужен ли мне опыт, чтобы начать LangChain / RAG / Vector DBs?

Предыдущий опыт не требуется. LangChain / RAG / Vector DBs на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 4 из 4.

Сколько времени занимает урок «Память и контекст диалога в LangChain»?

Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.

Можно ли писать и запускать код в этом уроке LangChain / RAG / Vector DBs?

Да. Каждый урок LangChain / RAG / Vector DBs включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.

Все уроки этого курса

  1. Настройка среды LangChain
  2. Промпты, LLM и базовые цепочки
  3. Парсеры вывода и обратные вызовы
  4. Память и контекст диалога в LangChain
← Назад к LangChain / RAG / Vector DBs