The last lesson sent one request to the embeddings API for every chunk it scored. With thousands of chunks that means thousands of requests, and all of them again for the next question. The chunks don't change between questions, so you embed them once, before any question arrives.
The API takes a list of texts and returns one vector per text, in the same order. So one request can carry all 27 chunks, and each chunk can keep its own vector. After that a question costs one request, for the question itself. Scoring it against the stored vectors is plain arithmetic.
To find the best chunks you sort them by score. sorted needs a small helper that says what to sort by, and it goes from the lowest to the highest unless you pass reverse=True. A slice then keeps the first few. Here it is on products:
def by_price(product):
return product["price"]
expensive_first = sorted(products, key=by_price, reverse=True)
top_two = expensive_first[:2]
Your program must print the three chunks closest to "Can I get my money back?". The check then counts your requests and tries three more questions:
0.825 returns.md Returns and refunds: Gift cards and items bought on sale are... 0.783 returns.md Returns and refunds: You can return any item within 14 days ... 0.651 returns.md Returns and refunds: To start a return, write to help@corner... Requests to the embeddings API: 2 Texts in each request: [27, 1] Do you ship to Canada? -> 3 matches, the best: 0.802 shipping.md My teapot cracked, is it covered? -> 3 matches, the best: 0.577 warranty.md How do I delete my account? -> 3 matches, the best: 0.788 privacy.md
Your task: embed all the chunks with one request and store each vector in its chunk under "vector". Then write top_matches(question): it embeds the question, gives every chunk a "score", sorts the chunks with the highest score first and returns the first three. For the question, print each one's score rounded to 3 decimals, its source, and the first 60 characters of its text followed by "...".
Assignment
Follow the Coding Tutorial to embed every chunk once and write top_matches, which returns the three chunks closest to a question.
Hint
The vectors come back in the order of the texts, so vectors[i] belongs to chunks[i]. sorted puts the lowest score first; reverse=True turns that around. The helper by_score goes above top_matches.
Free plan: 30 tutor messages. PRO is unlimited.
