A Tiny Vector Store

Store each text with its vector, then return the top k matches for a question. This is what a vector database does.

AI · intermediate · 8 min · 45 steps · free

What you'll learn

vector_store.py

import math

def embed(text):
    words = text.lower().split()
    return [words.count(w) for w in ['refund', 'ship', 'open', 'receipt']]

class VectorStore:
    def __init__(self):
        self.items = []

    def add(self, text):
        self.items.append((text, embed(text)))

    def search(self, query, k):
        q = embed(query)
        scored = []
        for text, vec in self.items:
            scored.append((math.sumprod(q, vec), text))
        scored.sort(reverse=True)
        return [text for score, text in scored[:k]]

store = VectorStore()
store.add('refund within 30 days')
store.add('we ship worldwide')
store.add('refund needs a receipt')
print(store.search('can i get a refund with no receipt', 2))

Step by step

  1. This brings in Python's built-in math module, so the program can use the functions it provides.
  2. Python defines the function embed(). Its body does not run yet: it runs each time the function is called.
  3. Python starts building the class VectorStore. Its methods are stored, but none of them run yet.
  4. Python reads the class body: everything indented under class VectorStore belongs to it.
  5. The method __init__ is stored in VectorStore. It runs only when it is called on an object.
  6. The method add is stored in VectorStore. It runs only when it is called on an object.
  7. The method search is stored in VectorStore. It runs only when it is called on an object.
  8. The class VectorStore is now defined, ready to make objects from.
  9. Python calls __init__(), with self = {}. It gets its own names.
  10. The store starts empty.
  11. __init__() has finished, so its names are gone. The value it returned, {items: a list}, is stored in store.
  12. Python calls add(), with self = {items: a list} and text = 'refund within 30 days'. It gets its own names.
  13. Python calls embed(), with text = 'refund within 30 days'. It gets its own names.
  14. words is created and points to a new list: ['refund', 'within', '30', 'days'].
  15. The function returns [words.count(w) for w in ['refund', 'ship', 'open', 'receipt']].
  16. ("refund within 30 days", [1, 0, 0, 0]) is stored: the text and its vector, side by side.
  17. add() has finished, so its names are gone.
  18. Python calls add(), with self = {items: a list} and text = 'we ship worldwide'. It gets its own names.
  19. Python calls embed(), with text = 'we ship worldwide'. It gets its own names.
  20. words is created and points to a new list: ['we', 'ship', 'worldwide'].
  21. The function returns [words.count(w) for w in ['refund', 'ship', 'open', 'receipt']].
  22. embed() has finished, so its names are gone. a tuple is added to the end of the list object.
  23. add() has finished, so its names are gone.
  24. Python calls add(), with self = {items: a list} and text = 'refund needs a receipt'. It gets its own names.
  25. Python calls embed(), with text = 'refund needs a receipt'. It gets its own names.
  26. words is created and points to a new list: ['refund', 'needs', 'a', 'receipt'].
  27. The function returns [words.count(w) for w in ['refund', 'ship', 'open', 'receipt']].
  28. embed() has finished, so its names are gone. a tuple is added to the end of the list object.
  29. add() has finished, so its names are gone.
  30. Python calls search(), with self = {items: a list}, query = 'can i get a refund with no receipt' and k = 2. It gets its own names.
  31. Python calls embed(), with text = 'can i get a refund with no receipt'. It gets its own names.
  32. words is created and points to a new list: ['can', 'i', 'get', 'a', 'refund', 'with', 'no', 'receipt'].
  33. The function returns [words.count(w) for w in ['refund', 'ship', 'open', 'receipt']].
  34. The question becomes [1, 0, 0, 1]: it mentions refund and receipt.
  35. scored is created and points to a new list: [].
  36. text is created with the value 'refund within 30 days'. vec is created and points to a new list: [1, 0, 0, 0].
  37. Score = dot product of the two vectors: how many vocabulary words they share.
  38. text changes from 'refund within 30 days' to 'we ship worldwide'. vec now points to a different list: [0, 1, 0, 0].
  39. a tuple is added to the end of the list that scored points to.
  40. text changes from 'we ship worldwide' to 'refund needs a receipt'. vec now points to a different list: [1, 0, 0, 1].
  41. a tuple is added to the end of the list that scored points to.
  42. Python moves to the next item of the loop: for text, vec in self.items.
  43. Sort the scores, biggest first.
  44. The function returns [text for score, text in scored[:k]].
  45. The top 2 go into the prompt.

Common mistakes

Best practices

Key takeaways

Check yourself

What does k control?

Answer: How many chunks come back

Scoring every item costs?

Answer: O(n)

·

More in Retrieval