When a user submits a query, it undergoes the same embedding process as the knowledge base documents, transforming it into a query vector. This query vector is then sent to the vector store, which performs a similarity search to identify the top N most relevant document chunks. The similarity metric typically used is cosine similarity. The retrieved chunks are the 'context' that will augment the LLM's understanding. This step is critical; if irrelevant chunks are retrieved, the LLM's response quality will suffer. Implementations often involve filtering and re-ranking techniques to optimize relevance.
from sentence_transformers import SentenceTransformer, util
model = SentenceTransformer('all-MiniLM-L6-v2')
corpus = [
'The quick brown fox jumps over the lazy dog.',
'Artificial intelligence is transforming industries.',
'Vectors are mathematical representations of magnitude and direction.',
'RAG enhances LLMs with external knowledge.'
]
corpus_embeddings = model.encode(corpus, convert_to_tensor=True)
query = 'How does RAG improve LLMs?'
query_embedding = model.encode(query, convert_to_tensor=True)
cosine_scores = util.cos_sim(query_embedding, corpus_embeddings)[0]
top_results = []
for score, idx in zip(cosine_scores, range(len(corpus))):
top_results.append({'text': corpus[idx], 'score': score.item()})
top_results.sort(key=lambda x: x['score'], reverse=True)
print(f"Query: {query}")
print("Top retrieved chunks:")
for result in top_results[:2]:
print(f"- {result['text']} (Score: {result['score']:.4f})")