AI Hints
Home›RAG Tutorial›Vector Stores
RAG · Lesson 32 of 120

LangChain's Vector Store

In memory.

⏱ 2 min read▶ Video at 31:56🎓 Free
Watch this lesson in the RAG courseWatch on YouTube ↗Full RAG course

LangChain has many vector stores, and they all share one interface. The in memory vector store is the simplest. It's perfect for learning, and for small projects.

LangChain's Vector Store
From the video: LangChain's Vector Store
  • Many vector stores
  • One interface
  • In memory is simplest

In-memory vector store

LangChain needs an embeddings object, so we use Gemini's. From documents embeds every chunk and stores it. Similarity search with score returns the best chunks for a question, with their scores. Run it. The top match is the fix for an overheating motor, from the error codes page.

lc_store.pypython
from langchain_core.documents import Document
from langchain_core.vectorstores import InMemoryVectorStore
from langchain_google_genai import GoogleGenerativeAIEmbeddings
from rag_kit import load_docs, make_chunks

chunks = [Document(c["text"], metadata={"source": c["source"]}) for c in make_chunks(load_docs())]
store = InMemoryVectorStore.from_documents(chunks, GoogleGenerativeAIEmbeddings(model="gemini-embedding-001"))

for doc, score in store.similarity_search_with_score("What should I do if the motor gets too hot?", k=2):
    print(round(score, 2), doc.metadata["source"], "|", doc.page_content[:60])
Output
0.69 ebike_errors.md | E05: the motor is overheating. Stop riding for 15 minutes, t
0.63 ebike_errors.md | E09: the brake sensor is stuck on. Squeeze both brake levers
Also uses rag_kit.py
import warnings; warnings.filterwarnings("ignore")
from pathlib import Path
import numpy as np
from sentence_transformers import SentenceTransformer
import faiss  # after torch, so the two libraries load safely together
from langchain_text_splitters import RecursiveCharacterTextSplitter

def load_docs(folder="data/rag/northwind"):
    return [{"source": p.name, "text": p.read_text()} for p in sorted(Path(folder).glob("*.md"))]

def make_chunks(docs, size=300, overlap=50):
    splitter = RecursiveCharacterTextSplitter(chunk_size=size, chunk_overlap=overlap)
    return [{"source": d["source"], "text": t.replace("\n", " ")}
            for d in docs for t in splitter.split_text(d["text"])]

embedder = SentenceTransformer("all-MiniLM-L6-v2", device="cpu")

def embed(texts):
    return embedder.encode(texts, normalize_embeddings=True)

class Index:
    def __init__(self, chunks):
        self.chunks = chunks
        self.vectors = embed([c["text"] for c in chunks])

    def search(self, query, k=3):
        scores = self.vectors @ embed([query])[0]
        top = np.argsort(-scores)[:k]
        return [(round(float(scores[i]), 2), self.chunks[i]) for i in top]

The shared interface

Swap in memory for another store, and the rest of your code stays the same. Add documents adds more chunks. Similarity search finds them. And as retriever turns any store into a retriever, which plugs into LangChain chains.

keyvalue
from_documentsbuild
add_documentsadd more
similarity_searchfind
as_retrieverplug into chains

Summary

LangChain's in memory vector store embeds and searches chunks in a few lines, with the same interface as every other store. Next, FAISS.

Key takeaways
  • InMemoryVectorStore
  • similarity_search_with_score
  • as_retriever
Next up: FAISS — fast search