Barefoot AI HubTHE BAREFOOT FREELANCER
Start learning
⬢ AI Agents · Lesson 3 of 7

08Memory, Knowledge & RAG

Give AI your business knowledge. Learn embeddings, vector search and Retrieval-Augmented Generation — then build a working mini RAG system with a local model.

⏱ 28 min📶 Intermediate🧪 3-question check

What you'll learn

  • Explain short-term vs. long-term memory in AI systems
  • Understand embeddings and semantic search
  • Walk through the RAG pipeline: chunk, embed, retrieve, generate
  • Build a small, working RAG script with Ollama
  • Know when to use RAG vs. long context vs. fine-tuning

Three ways to give AI your knowledge

ApproachHow it worksBest whenWatch out
Paste into contextInclude the documents in the promptSmall knowledge (a few documents)Cost and limits grow with every request
RAGSearch your knowledge base, insert only the relevant piecesLarge or changing knowledge (FAQs, policies, manuals, past projects)Retrieval quality makes or breaks it
Fine-tuningFurther train the model on your examplesTeaching a consistent style or format at scalePoor at teaching facts; costly; hard to update

Memory in AI systems

  • Short-term memory = the context window: the current conversation and task.
  • Long-term memory = anything saved outside the model and re-inserted when relevant: user preferences, notes, summaries of past sessions, documents in a knowledge base.
  • Procedural memory = saved “how-to” instructions (skills) the agent can reload — e.g. Hermes Agent writes skill files from experience (Lesson 12).

Embeddings: meaning as numbers

An embedding model turns text into a list of numbers (a vector) that captures its meaning. Texts with similar meanings get similar vectors — even with no words in common.

"What time do you open?"[0.12, -0.44, 0.91, …]
"Store hours on Sunday"[0.10, -0.40, 0.88, …]very similar
"Refund for a cold latte"[-0.63, 0.25, 0.07, …]different

Comparing vectors (usually with cosine similarity) lets you find the most relevant passages for any question. That's semantic search, and it's the “retrieval” in RAG. Vector databases (pgvector, Chroma, Qdrant, and others) store and search millions of these efficiently.

The RAG pipeline

INGESTLoad documentsPDFs, docs, FAQs
CHUNKSplit into chunks~200–800 words
EMBEDEmbed each chunkstore vectors
QUERYEmbed the questionfind top matches
GENERATELLM answersfrom retrieved chunks, with sources
Steps 1–3 happen once (and when documents change). Steps 4–5 run for every question.

Build it: a working mini RAG with Ollama

This script answers questions about a small business knowledge base using only local models. No cloud, no vector database — just the idea, clearly.

  1. Pull an embedding model and a chat model

    terminalbash
    ollama pull nomic-embed-text
    ollama pull qwen3:8b
    pip install ollama
  2. Save the script

    mini_rag.pypython
    import ollama, math
    
    # 1) Your knowledge base — in real life, load and chunk your files
    docs = [
        "Barefoot Café is open Monday to Saturday 7am-9pm and Sunday 8am-6pm.",
        "We deliver within 5 km of Iloilo Business Park. Delivery fee is 49 pesos.",
        "Refunds: if an order is wrong or unsatisfactory, we replace it or refund within 24 hours.",
        "Our co-working corner upstairs has fiber Wi-Fi and power outlets at every seat.",
        "Sea-Salt Cold Brew costs 160 pesos and uses sea salt from Guimaras.",
    ]
    
    EMBED = "nomic-embed-text"
    CHAT = "qwen3:8b"
    
    def embed(texts):
        return ollama.embed(model=EMBED, input=texts)["embeddings"]
    
    def cosine(a, b):
        dot = sum(x * y for x, y in zip(a, b))
        return dot / (math.sqrt(sum(x * x for x in a)) * math.sqrt(sum(y * y for y in b)))
    
    # 2) Index once
    doc_vectors = embed(docs)
    
    def ask(question, k=2):
        # 3) Retrieve the k most similar chunks
        q_vec = embed([question])[0]
        ranked = sorted(zip(docs, doc_vectors), key=lambda d: cosine(q_vec, d[1]), reverse=True)
        context = "\n".join(f"[{i+1}] {text}" for i, (text, _) in enumerate(ranked[:k]))
    
        # 4) Generate a grounded answer
        prompt = f"""Answer the customer using ONLY the sources below.
    Cite sources like [1]. If the answer isn't in the sources, say you don't know.
    
    <sources>
    {context}
    </sources>
    
    Question: {question}"""
        reply = ollama.chat(model=CHAT, messages=[{"role": "user", "content": prompt}])
        return reply["message"]["content"]
    
    while True:
        q = input("\nAsk the café (or 'quit'): ")
        if q.lower() == "quit":
            break
        print(ask(q))
  3. Run it and test

    terminalbash
    python mini_rag.py

    Try: “Are you open Sunday evening?”, “How much is delivery?”, and something not in the docs like “Do you sell cakes?” — a good RAG system should say it doesn't know.

Making RAG good in production

LeverWhat to do
ChunkingSplit on natural boundaries (headings, paragraphs). Keep chunks self-contained; add the document title to each chunk.
MetadataStore source, date, product and department so you can filter (e.g. only current policies).
Hybrid searchCombine semantic search with keyword search — keywords catch exact codes, SKUs and names.
Re-rankingRetrieve 20 candidates, then use a re-ranker model to choose the best 3–5.
CitationsAlways show sources so users (and you) can verify answers.
FreshnessRe-index when documents change; remove outdated versions.
EvaluationKeep a list of real questions with known answers and check retrieval + answers after each change.

Key takeaways

  • Short-term memory is the context window; long-term memory is saved data re-inserted when relevant.
  • Embeddings turn meaning into vectors; similar meaning → similar vectors → semantic search.
  • RAG = chunk → embed → retrieve → generate with sources. It's the default way to add business knowledge.
  • Retrieval quality, citations and evaluation decide whether RAG is trustworthy.

Knowledge check

0 / 3

Q1What does an embedding represent?

Q2Your 500-page policy manual changes monthly. Best approach?

Q3What should a good RAG bot do when the answer isn't in the sources?

Finished this lesson?Your progress is saved in this browser.