FromZero2AI
CoursesPlaygroundBlog
Support on Ko-fi
AI Agent Frameworks • Module A: LangChain & LangGraphLesson 3: Agent Memory & State Management
PreviousNext

Lesson 3: Agent Memory & State Management

Differentiate in-context, external, and episodic memory. Implement a vector memory store that lets agents recall past interactions. Understand when each memory type is appropriate.

Built with AI for beginners. Free forever.

Support on Ko-fi•About•Blog•Privacy Policy•Terms of Service

An agent without memory starts every conversation from scratch. Memory architectures determine what the agent “knows” across turns, across sessions, and across users — and the choice profoundly affects both capability and cost.

Memory Type Explorer

Select a memory type to see its scope, storage mechanism, and implementation.

In-Context Memory

Scope:Current conversation only
Storage:LLM context window (messages array)

Use when: Short conversations, simple Q&A agents, prototyping. Zero infrastructure required — every message is passed in the messages array. Cost scales with conversation length.

# In-context memory: just pass all messages every call
from anthropic import Anthropic

client = Anthropic()
conversation_history = []

def chat(user_message: str) -> str:
    conversation_history.append({
        "role": "user",
        "content": user_message,
    })

    response = client.messages.create(
        model="claude-sonnet-4-6",
        max_tokens=1024,
        system="You are a helpful assistant.",
        messages=conversation_history,  # Full history every call
    )

    assistant_message = response.content[0].text
    conversation_history.append({
        "role": "assistant",
        "content": assistant_message,
    })
    return assistant_message

# Turn 1
print(chat("My name is Alice"))
# Turn 2 — remembers because full history is in context
print(chat("What is my name?"))  # → "Your name is Alice."

Summarization Memory: Managing Context Cost

def summarize_history_node(state: AgentState) -> dict:
    """Summarize old messages to keep context window manageable."""
    messages = state["messages"]
    KEEP_RECENT = 10   # Keep last 10 messages verbatim

    if len(messages) <= KEEP_RECENT:
        return {}  # No action needed

    old_messages = messages[:-KEEP_RECENT]
    recent_messages = messages[-KEEP_RECENT:]

    summary_response = model.invoke([
        HumanMessage(content=f"Summarize this conversation history in 3-5 bullet points: {old_messages}"),
    ])
    summary = summary_response.content

    # Replace old messages with summary
    return {
        "messages": [SystemMessage(content=f"[Conversation summary: {summary}]")] + recent_messages,
    }

Next, we scale from single agents to multi-agent systems using CrewAI — where specialized agents collaborate, delegate tasks, and share information.