LangChain / RAG / Vector DBs · Aula

Memória e Estado em RAG Agêntico

Dê ao seu agente de RAG memória de curto e longo prazo para que ele mantenha conversas e recupere fatos entre as interações.

Aula 4 de 413 etapas

Memória e Estado em RAG Agêntico é uma aula grátis de LangChain / RAG / Vector DBs 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 LangChain / RAG / Vector DBs, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de LangChain / RAG / Vector DBs inclui 4 aulas no total.

Partes desta aula ainda não foram traduzidas e aparecem em inglês.

Why Agents Need Memory

A stateless agent forgets everything after each call. Memory lets an agent track the conversation, remember user preferences, and avoid repeating retrievals.

Short-Term vs. Long-Term

Short-term memory holds the current conversation in the context window. Long-term memory persists facts across sessions, often in a vector store or database.

Conversation Buffer

The simplest memory keeps the full message history and replays it each turn so the model has full context.

history = []

def chat(user_msg):
    history.append({"role": "user", "content": user_msg})
    reply = llm.invoke(history)
    history.append({"role": "assistant", "content": reply})
    return reply

The Context Window Limit

Replaying the entire history eventually overflows the model context. You must summarize or trim older turns to stay within the token budget.

Summary Memory

Periodically compress old turns into a running summary, keeping recent turns verbatim. This preserves gist while freeing tokens.

if len(history) > 20:
    summary = llm.invoke("Summarize: " + str(history[:-6]))
    history[:] = [{"role": "system", "content": summary}] + history[-6:]

Long-Term Memory via Vectors

Store durable facts as embeddings. On each turn, retrieve relevant memories by similarity and inject them, just like RAG over a knowledge base.

memory_store.add_texts(["User prefers metric units"])
relevant = memory_store.similarity_search(user_msg, k=3)

Choosing What to Remember

Do not store everything. Extract durable, reusable facts (preferences, decisions, entities) and skip ephemeral chatter to keep long-term memory clean.

State Beyond Chat

Agents also track non-conversational state: which tools ran, intermediate results, and a scratchpad of reasoning steps used to plan the next action.

Thread and Session Keys

In multi-user systems, scope memory by a thread_id or user_id so conversations never leak between people.

def get_history(thread_id):
    return store.get(thread_id, [])

def save(thread_id, messages):
    store[thread_id] = messages

Persistence

For memory to survive restarts, back it with a database or checkpointer rather than an in-process dictionary. LangGraph offers checkpointers for exactly this.

Putting It Together

Combine a trimmed conversation buffer for recency, summary memory for the middle, and vector long-term memory for durable facts, all keyed by session.

Quick Check

Test your understanding of agent memory.

Recap

You added memory to agents:

  • Short-term buffer for the current chat
  • Summary memory to fit the context window
  • Long-term vector memory for durable facts
  • Scope by session and persist for durability
Grátis para começar

Aprenda LangChain / RAG / Vector DBs com um tutor de IA — grátis

Escreva e execute código real no seu navegador, obtenha ajuda instantânea de um tutor de IA 24/7 e continue de onde parou na web ou no app.

Cursos
12
Aulas
48

Perguntas Frequentes

A aula “Memória e Estado em RAG Agêntico” é grátis?

Sim — o texto completo de “Memória e Estado em RAG Agêntico” é 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 LangChain / RAG / Vector DBs, atualize para CoddyKit PRO. O curso de LangChain / RAG / Vector DBs inclui 4 aulas no total.

O que vou aprender em “Memória e Estado em RAG Agêntico”?

Dê ao seu agente de RAG memória de curto e longo prazo para que ele mantenha conversas e recupere fatos entre as interações. Você pratica LangChain / RAG / Vector DBs 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 LangChain / RAG / Vector DBs?

Nenhuma experiência prévia é necessária. LangChain / RAG / Vector DBs 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 “Memória e Estado em RAG Agêntico”?

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 LangChain / RAG / Vector DBs?

Sim. Cada aula de LangChain / RAG / Vector DBs 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

  1. Agentes e conceitos de ferramentas do LangChain
  2. Desenvolvimento de fluxos RAG multiagente
  3. Integração de APIs externas como ferramentas
  4. Memória e Estado em RAG Agêntico
← Voltar para LangChain / RAG / Vector DBs