LangChain / RAG / Vector DBs · Lección

Memoria y contexto conversacional en LangChain

Aprenda cómo la memoria de LangChain realiza un seguimiento del historial de la conversación para que las cadenas y los chatbots mantengan conversaciones coherentes de varios turnos.

Lección 4 de 413 pasos

Memoria y contexto conversacional en LangChain es una lección gratuita de LangChain / RAG / Vector DBs en CoddyKit. Esta es la lección 4 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de LangChain / RAG / Vector DBs, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de LangChain / RAG / Vector DBs incluye 4 lecciones en total.

Partes de esta lección aún no han sido traducidas y se muestran en inglés.

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
Gratis para empezar

Aprende LangChain / RAG / Vector DBs con un tutor de IA — gratis

Escribe y ejecuta código real en tu navegador, obtén ayuda instantánea de un tutor de IA disponible 24/7 y continúa donde lo dejaste en la web o en la aplicación.

Cursos
12
Lecciones
48

Preguntas frecuentes

¿La lección «Memoria y contexto conversacional en LangChain» es gratis?

Sí — el texto completo de «Memoria y contexto conversacional en LangChain» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de LangChain / RAG / Vector DBs, actualiza a CoddyKit PRO. El curso de LangChain / RAG / Vector DBs incluye 4 lecciones en total.

¿Qué aprenderé en «Memoria y contexto conversacional en LangChain»?

Aprenda cómo la memoria de LangChain realiza un seguimiento del historial de la conversación para que las cadenas y los chatbots mantengan conversaciones coherentes de varios turnos. Practicas LangChain / RAG / Vector DBs con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.

¿Necesito experiencia previa para empezar LangChain / RAG / Vector DBs?

No se requiere experiencia previa. LangChain / RAG / Vector DBs en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 4 de 4.

¿Cuánto tiempo toma la lección «Memoria y contexto conversacional en LangChain»?

La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.

¿Puedo escribir y ejecutar código en esta lección de LangChain / RAG / Vector DBs?

Sí. Cada lección de LangChain / RAG / Vector DBs incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.

Todas las lecciones de este curso

  1. Configuración de su entorno LangChain
  2. Prompts, LLM y cadenas básicas
  3. Analizadores de salida y callbacks
  4. Memoria y contexto conversacional en LangChain
← Volver a LangChain / RAG / Vector DBs