0
Phase 5

Build Memory from Scratch

~3 min read

Concept & How It Works

    Why Does It Exist?

    Framework abstractions hide failure modes. Building once teaches you exactly what gets stored, how retrieval works, and where latency hides.

    Real-World Analogy

    Building memory from scratch is like writing your own ORM once — painful, but you never misunderstand what the database is doing.
    Loading diagram...

    Visual Workflows

    What is Build Memory from Scratch?

    Loading diagram...

    Example

    Scenario

    A 100-line Python module that remembers user preferences across Streamlit sessions using Chroma and OpenAI embeddings.

    Solution

    In Agent Memory, apply Build Memory from Scratch to this scenario: A 100-line Python module that remembers user preferences across Streamlit sessions using Chroma and OpenAI embeddings. Identify the inputs, run the technique, validate the output, and note one thing you would monitor in production.

    Practice Task

    Do this before moving to the next module — reading alone is not enough.

    Open the Code Walkthrough below and run it locally. Change one parameter related to Build Memory from Scratch (e.g. model, temperature, top_k, or tool name), observe the difference in output, and write 2–3 sentences explaining what changed.

    Code Walkthrough

    Highlighted lines show where Build Memory from Scratch happens in the code.

    Build Memory from Scratch
    1def update_memory(user_id, conversation, llm, store):  # define a reusable function2    facts = llm.invoke(f"Extract new facts as bullet points:\n{conversation}").content3    for fact in facts.split("\n"):4        if fact.strip():5            store.add(texts=[fact], metadatas=[{"user_id": user_id}], ids=[str(uuid4())])6
    7def inject_memory(user_id, query, store):  # define a reusable function8    hits = store.similarity_search(query, k=5, filter={"user_id": user_id})9    return "\n".join(h.page_content for h in hits)  # return the result

    Commands to Remember

    Commands to Remember

    • pip install chromadb # vector store for long-term memory
    • pip install redis # fast session / working memory
    • pip install tiktoken # count tokens before injecting memory

    Common Mistakes

    • Treating Build Memory from Scratch as a black box without evaluation
    • Ignoring cost and latency in production
    • Skipping error handling for build memory from scratch

    Cheat Sheet

    Quick recap — the most important points from this module.

    Cheat Sheet

    quick ref
    • Build Memory from Scratch
    • Extract-Store-Retrieve
    • Chroma
    • User Scoping