Embedding-based LLM-systems
All tool-calling LLMs we discussed until here (see Chatbots and Tool Calling) are using tools that allow them to use their generated inputs in some way. In most of the tasks we want to utilize LLMs for, we do not only want to generate text but to also inform the generation based on some kind of existing knowledge base. Examples for these kinds of use cases include:
- Answering questions about a specific topic (e.g., a company or product)
- Summarizing a document
- Generating a report based on data
Though most modern LLMs are increasingly capable in answering basic knowledge-questions, the more complex a topic or the more relevant the factual basis of an answer is, the more important it is to base generated answers on actual data.
Semantic embeddings and vector stores
To empower an LLM to look up information during its thought-process, one has to build a tool that allows an LLM to use natural language to retrieve information necessary for a task. The fundamental principle to do this are so-called semantic embeddings. These are pretty close to the concept we introduced when talking about the foundations of LLMs (see Language Model Basics) and can be understood as a way to map textual data into a vector space. The main idea is that semantically similar texts should have similar embeddings, i.e., they are close in the vector space. Close in this context is meant as having a reasonably small distance between them. The go-to standard to measure this distance is the cosine similarity, which has proven useful enough to be the standard for a range of semantic retrieval implementations (e.g., it is used in OpenAI tutorials and in Azure AI Foundry embedding-applications). The cosine similarity is defined as:
\[ \text{cosine\_similarity}(u, v) = \frac{u \cdot v}{\|u\| \|v\|} = \frac{\sum_{i=1}^{n} u_i v_i}{\sqrt{\sum_{i=1}^{n} u_i^2} \sqrt{\sum_{i=1}^{n} v_i^2}} \] The rationale here is that sequences with semantically similar contents should point to similar directions in the high dimensional vector space. See Figure 6.1 for an illustration of this and other common similarity concepts seen in semantic retrieval.
As always, there is not the one solution to all problems though and the applicability of cosine similarity might not be optimal for your use case (Goyal & Sharma, 2022; Steck et al., 2024).
Though one could use any kind of (L)LM to calculate embeddings for this case1, it is advisable to use models specifically trained for this purpose. Reimers & Gurevych (2019) proposed Sentence-BERT which is a simple but effective approach to calculate semantic embeddings. SBERT and similar approaches are based on a (L)LM that was trained to predict missing words as we discussed before, resulting in a general representation of natural language. In the case of the original paper, they used (among others) the BERT model (Devlin et al., 2019) mentioned before.
1 And there are approaches to use LLMs to solve this task, e.g., Jiang et al. (2023)
2 The original BERT-paper did this by adding a pooling layer before the task-header that extracted and weighed the context-dependent embedding of the first token. The SBERT paper tried different pooling-strategies and used a mean over each embedding dimension of the sequence.
The authors then use this to embed a pair of sentences into one embedding-vector each2, for which some measure of semantic similarity is known. An example for a dataset containing such sentences is the Stanford Natural Language Inference (SNLI) corpus (Bowman et al., 2015) which labels 570k pairs of sentences as either entailment, contradiction or neutral. Reimers & Gurevych (2019) then concatenated both sentence embeddings and their absolute element-wise difference into a single vector which is fed to a multiclass classifier, indicating in which category the sentences relationship falls. At inference, this classification head was removed and replaced by the cosine similarity as discussed above. The resulting network is highly effective in calculating semantic similarities between sentences.
A look at the sbert-website shows that the module has somewhat grown and now does supply a series of learning paradigms that can be used to efficiently tune a model for your specific use case3. As the library has grown, so has the sheer amount of pretrained embedding-models in some way based on this architecture that are hosted on huggingface. The MTEB-Leaderboard is a good start to search for a model for your application. One utilization of this model-family is their very efficient ability to semantically search for documents. If a model is very good at finding similar sentences, it can also be very good to find documents that are very similar to a question.
3 And this does not have to be expensive. Tunstall et al. (2022) have shown a highly efficient contrastive learning paradigm that reduces the amount of necessary labels to a ridiculously small number.
Look at the example illustrated in Figure 6.2. The question “why is the sky blue” is embedded with the same model as our 5 documents stating some facts.
We can then calculate the cosine-similarity between these embeddings and return the document, that has the highest similarity to our question.
Note📝 Task
Install the sentence-transformers package (uv add sentence-transformers datasets scikit-learn) and download the climate_fever-dataset.
Choose one model from the MTEB-Leaderboard that you deem adequately sized and appropriate for the task
Test the different metrics shown in Figure 6.1 for the first twenty claims of the dataset and a question you formulate.
Use the similarity-implementations from sklearn.metrics.pairwise.
This approach of using a model to embed documents and questions into a vector space is the basis for the so-called Retrieval augmented generation.
Retrieval augmented generation
Retrieval augmented generation (RAG) is a framework that does pretty much what it says on the tin. You use a retrieval model to find documents that are similar to your question and then either return these documents or feed them into a generative model, which then generates an answer based on these documents. This process can additionally be wrapped as a tool (see Chatbots and Tool Calling), so that your LLM can now also use external knowledge sources to answer questions.
Retrieval does not have to be semantics-based in this context: all kinds of data sources and databases can be made accessible for an LLM. We will focus on a purely embedding based approach here though.
Although the small example in the last task was working, it is not really scalable. It was fine for a limited set of examples, if you want to realistically make a whole knowledge base searchable, you need to use an appropriate database system.
Vector databases
A vector database is a database that stores vectors and allows for efficient similarity searches.
Efficient here means that the database does not compare a query with every stored vector. Instead, it builds an index for approximate nearest neighbour search. Qdrant, for example, uses a graph-based index (HNSW, Hierarchical Navigable Small World) in which each vector is linked to a few similar vectors, so a search only has to follow a short path through the graph. The result is not guaranteed to be the exact top-k, but it is very close and orders of magnitude faster on large collections.
As can be seen in the db-engines ranking there has been a surge of interest in this area recently, with many new players entering the market. From the plethora of vector databases, these three are examples that deserve an honorary mention:
Chroma - an in-memory database for small applications that is especially easy to get to run.
Elasticsearch - a well established database that is the go to system for open source search engines and has recently (and kind of naturally) also branched out into vector databases.
Qdrant - the product of a Berlin-based startup that focuses on stability and scalability. It can also run in memory, but does natively support hard drive storage.
The best way to use qdrant is to use docker to run it and the python sdk to interact with it. The sdk also allows to just run the client in memory (QdrantClient(":memory:")).
Note📝 Task
Install the qdrant-client python-sdk (uv add qdrant-client).
Create a collection for the claims and one for the evidence in the climate_fever-dataset. Add the first 200 entries to each of these collections. Use sentence_transformers to do this, here is a tutorial by qdrant that leads you through the process.
Test the similarity search on a question you formulate.
RAG
The last step to make this into a RAG pipeline is to use a generative model to answer the question based on the retrieved documents.
This means that we collect the relevant documents like we did before, still based on a natural language question, but instead of returning the hits we got from the index, we feed them into an LLM and ask it to generate an answer based on these documents. This is where the name retrieval augmented generation comes from: we use the retrieval step to augment the generative model with additional information. The diagram in Figure 6.3 illustrates this process.
The retrieved documents simply become part of the prompt. A minimal template could look like this, with an ID per snippet so that the model can reference its sources:
# hits: the result of your Qdrant search, question: the user's question
snippets = "\n".join(f"[{i}] {hit.payload['text']}" for i, hit in enumerate(hits, start=1))
prompt = f"""Answer the question using only the numbered snippets below.
Cite the snippets you use as [1], [2], ... If they do not contain the answer, say so.
Snippets:
{snippets}
Question: {question}"""
Note📝 Task
Implement a RAG pipeline for the climate_fever dataset using qdrant as vector database and an LLM of your choice for the summarization.
Try to find a prompt that results in the LLM
- using the information given
- not inventing new information
- referencing the source of the information it uses
Upload your results until here (embedder, database and summarization) to moodle. All following tasks are optional.
Most agent frameworks provide integrations for a variety of vector databases.
Others, like Google’s Agent Development Kit (ADK), skip the wrappers: the retrieval stays plain qdrant code, and the agent just gets it as a tool. See Tip 6.1 for an example RAG-system implemented with ADK.
Document chunking
The examples we looked at until now were all working with short text-snippets that comfortably fit into the context window of an LLM. If you think about usual use cases for RAG-systems, this is not the most common case though. Usually, you will have a base of documents that can span several thousand tokens and you want to be able to answer questions about these documents. Furthermore, you do not only want to know which document might be relevant, but ideally also which part of the document matches your question best.
There is also a technical reason: embedding models have a maximum input length, often 256 to 512 tokens for SBERT-style models, and silently truncate everything beyond it. A whole document embedded as one vector would therefore often only represent its beginning.
This is where the process of document chunking or document splitting comes into play. The most common, so-called naive chunking methods ignore the content of the document: they either cut at structural boundaries such as sentences, paragraphs or pages, or into windows of a fixed size, measured in tokens or sentences. The resulting chunks are individually embedded and stored in the vector database. To prevent loss of relevant context at the cut points, it is additionally common to add some overlap between the chunks. This mitigates the lost context problem, but creates redundancies in the data.
An alternative is semantic chunking, which places the cuts based on the meaning of the text. The LlamaIndex documentation describes a popular variant: the splitter compares the embeddings of neighboring sentences and starts a new chunk where their similarity drops, with the threshold set as a percentile of all neighbor distances.
Qu et al. (2025) compared this breakpoint approach and a second semantic chunker against fixed-size chunking. The breakpoint-based chunker walks through the document and starts a new chunk wherever the cosine distance between two neighboring sentences exceeds a threshold, which is usually set relative to all distances in the document, for example as a percentile. The clustering-based chunker clusters all sentences at once instead. Its distance mixes the semantic distance of two sentences with their distance in the document, weighted by a parameter λ, so a chunk can also collect sentences that are far apart. The result of the comparison is sobering: across document retrieval, evidence retrieval and answer generation, neither semantic chunker consistently beat the fixed-size baseline, which makes the additional compute hard to justify.
A third option keeps the naive boundaries but changes how the chunks are embedded. In late chunking (Günther et al., 2024; Late Chunking in Long-Context Embedding Models, 2024), the whole document is first run once through a long-context embedding model, and the resulting token embeddings are only then averaged per chunk. Each chunk embedding thereby carries information about the context of the whole document, without any change to the chunk boundaries.
The interactive illustration below applies all three strategies to the introduction of their paper. The colours mark the four paragraphs of the introduction, so a chunk with a single colour stays within one paragraph.
Interactive illustration: fixed-size vs. semantic chunking
Fixed-size baseline
Cuts every n sentences, blind to their content. Overlap repeats sentences in neighbouring chunks to keep some context.
Breakpoint-based semantic
Cuts wherever two neighbouring sentences are further apart than the threshold (red bars), set either as a percentile of all distances or as an absolute cosine distance. Only ever compares two sentences at a time.
Clustering-based semantic
Links all sentence pairs closer than the threshold (white dots) and makes each connected group a chunk, even across the document. λ mixes position (1) and meaning (0).
Purity is the share of the most frequent paragraph per chunk, averaged over all chunks. Note that purity rewards small chunks (a single sentence is always pure), so compare settings with a similar number of sentences per chunk. The sentence embeddings were computed once with a small embedding model, everything else runs in your browser.
Playing with the sliders shows that the semantic chunkers can produce cleaner chunks than the fixed-size baseline. Whether this matters for retrieval is a different question. Figure 6.4 shows the document-retrieval results of Qu et al. (2025) as the gain of each semantic chunker over fixed-size chunking. The large gains appear only on the stitched datasets, which the authors built by concatenating short documents on unrelated topics, a situation in which topic shifts are easy to detect. Even there, only the breakpoint chunker gains substantially, and only on two of six datasets. On the datasets with real, coherent documents, fixed-size chunking is as good or better.
Note📝 Task
Implement a document chunking strategy for a book of your choice from the project_gutenberg dataset.
You can use any approach you like, but you should explain your choice and why it is appropriate for this dataset.
Query Expansion/Transformation
Until now, we have based our retrieval on the assumption, that the question the user formulates is a good representation of their information need. This is not always the case though. Often, users do not know what they are looking for or they use synonyms or paraphrases that are not present in the documents. If the question is not formulated well, or if it is too specific, the system might not be able to find relevant documents. To improve the quality of the questions, we can use query expansion. This means that we take the original question and expand it with additional information to cover paraphrases and synonyms and to increase the chances of finding relevant documents. This can be done in multiple ways, one common approach is to use a generative model to generate multiple queries based on the original question. Another approach is to use a keyword extraction algorithm to extract keywords from the question and then use these keywords to expand the query.
The most basic way to implement a query-expansion is to build a tool that instructs an LLM to give multiple alternate formulations of the original query. Though this will probably work, there are more refined methods.
Two more sophisticated approaches to transform queries are:
Hypothetical Document Embeddings (HyDE) (Gao et al., 2023): An LLM is instructed to generate a hypothetical document that answers the query. This document is then used to query the index
Multi-Step Query Transformations: After a first execution of a (complex) query against an index, the answer is used to iteratively formulate follow-up questions that are then executed against the index.
Note📝 Task
Implement query expansion for the climate_fever dataset. Use the openai client from Prompting to let an LLM either generate alternative formulations of the query or a hypothetical answer document (HyDE), and use its output to query your index.
Experiment with different prompts and temperatures.
Hybrid Search
Up to here, we have focused exclusively on semantic search using vector embeddings. However, purely semantic approaches can sometimes miss documents that contain exact keyword matches or specific terminology that users explicitly mention in their queries. This is where hybrid search becomes valuable by combining multiple retrieval strategies.
Hybrid search integrates semantic search with traditional keyword-based methods (like BM254 or full-text search) to leverage the strengths of both approaches. Semantic search excels at understanding context and finding conceptually related documents, while keyword search ensures exact matches are not missed.
4 BM25 scores a document by how often the query terms occur in it, weighted by how rare these terms are in the whole collection.
Qdrant supports hybrid search through its multi-stage query capabilities. The basic approach involves:
- Parallel retrieval: Execute both a dense vector search (semantic) and a sparse vector search (keyword-based) simultaneously
- Score fusion: Combine the results using a fusion strategy such as Reciprocal Rank Fusion (RRF) or weighted scoring
- Re-ranking: Optionally apply a re-ranking strategy to refine the final result ordering (e.g., using Maximal Marginal Relevance or a higher-resolution embedding-model like ColBERT Santhanam et al., 2022)
Qdrant’s implementation allows you to configure how these different search strategies are combined (e.g., Reciprocal Rank Fusion or Distribution-Based Score Fusion). For example, you might give more weight to semantic similarity for conceptual queries, while prioritizing keyword matches for queries containing specific technical terms or proper nouns.
Note📝 Task
Extend your climate_fever RAG system to use hybrid search combining semantic and keyword-based retrieval in Qdrant (you can find a tutorial on how to implement this here).
Compare the retrieval results of pure semantic search versus hybrid search on at least 5 different test queries. Pay attention to cases where one approach significantly outperforms the other.
Document your findings: When does hybrid search provide better results? When is pure semantic search sufficient?
RAG Evaluation
Building a RAG system is one thing, knowing whether it works well is another. Since a RAG system consists of a retriever and a generator, it can fail in two places: the retriever can miss the relevant documents, or the generator can ignore, misread or embellish what it was given. A useful evaluation therefore looks at both components separately before judging the final answers.
Evaluating the retriever
The retriever can be evaluated like any search engine, as long as we know which documents would have been relevant for a query. For each query, precision and recall compare two sets: the documents the retriever returned and the documents that are relevant (Figure 6.5). Precision is the share of retrieved documents that are relevant, \(\text{precision} = |\text{relevant} \cap \text{retrieved}| \,/\, |\text{retrieved}|\), recall the share of relevant documents that were retrieved, \(\text{recall} = |\text{relevant} \cap \text{retrieved}| \,/\, |\text{relevant}|\). Both are usually reported for a fixed number \(k\) of retrieved documents (precision@k and recall@k), and they pull in opposite directions: retrieving more chunks can never decrease recall, but usually decreases precision. Since the generator reads the retrieved chunks in order, the rank of the first relevant hit matters as well. The mean reciprocal rank (MRR) averages \(1/\text{rank}\) of the first relevant document over all queries, so an MRR of 1 means that the first hit was always relevant.
These metrics need no LLM and are cheap, exact and reproducible, but they need relevance labels. climate_fever comes with such labels: every claim is accompanied by five evidence sentences from Wikipedia that annotators judged against it, which gives us a ready-made set of relevant documents per claim.
Note📝 Task
Evaluate the retriever of your climate_fever RAG system. Use the claims as queries and treat the evidence sentences annotated for a claim as its relevant documents. You can additionally exclude evidence sentences whose evidence_label marks them as not containing enough information (see the dataset card for the label names). Make sure that your evidence collection contains the evidence of all claims you use as queries.
Compute precision@k, recall@k and MRR over at least 50 claims for k = 1, 3, 5 and 10, and compare two configurations, for example two embedding models or your semantic and your hybrid search.
Evaluating with an LLM as a judge
Relevance labels like those of climate_fever rarely exist for your own documents. An alternative is to let a second LLM judge the outputs of the system, an idea we will discuss in more depth in the section on LLMs as judges (LLM as a judge). DeepEval implements such judge-based metrics for both components of a RAG system. For the retriever, contextual relevancy lets the judge extract the statements in the retrieved chunks and reports the share of statements that are relevant to the query. Contextual precision checks whether the relevant chunks are ranked above the irrelevant ones, and contextual recall checks which statements of an expected answer can be attributed to the retrieved chunks. For the generator, faithfulness reports the share of claims in the answer that do not contradict the retrieved chunks, and answer relevancy the share of statements in the answer that address the query. Contextual relevancy, faithfulness and answer relevancy need no reference answer and can be computed for any query, whereas contextual precision and recall need an expected output to compare against (Figure 6.6). The judge does not have to be a commercial model, since the metrics accept custom model classes. RAGAS is a widely used alternative that implements comparable metrics.
flowchart LR
Q[Query] --> R[Retriever]
R --> C[Retrieved chunks]
C --> L[LLM]
L --> A[Answer]
E[Expected output]
C -.->|"Contextual Relevancy: relevant to the query?"| Q
C -.->|"Contextual Precision: relevant chunks ranked first?"| E
C -.->|"Contextual Recall: expected statements retrieved?"| E
A -.->|"Faithfulness: consistent with the chunks?"| C
A -.->|"Answer Relevancy: addresses the query?"| Q
Claim-level diagnosis with RAGChecker
RAGChecker (Ru et al., 2024) goes one step further and evaluates on the level of individual claims. An LLM first splits the ground-truth answer and the response into claims, and a second LLM call checks which of these claims are entailed by the ground truth, the response or the retrieved chunks. This needs a ground-truth answer per query, but no further annotation. The resulting metrics can be read off a Venn diagram of three sets of claims (Figure 6.7). Overall precision is the share of response claims that are correct, overall recall the share of ground-truth claims that the response contains. For the retriever, claim recall is the share of ground-truth claims found in the retrieved chunks, and context precision the share of retrieved chunks that contain at least one of them. For the generator, hallucination counts incorrect response claims that no chunk supports, noise sensitivity incorrect claims that the generator took over from the chunks, self-knowledge correct claims that stem from the model rather than from the chunks, and context utilization the share of retrieved ground-truth claims that made it into the response. The context circle thereby tells us why something went wrong: missing information that was retrieved but not used points to the generator, missing information that was never retrieved points to the retriever.
Choosing an approach
The three approaches differ less in whether they use an LLM than in what they need as input. Classic retrieval metrics need relevance labels per query, but no LLM. RAGChecker needs a ground-truth answer per query and uses LLM calls to extract and check claims, which in turn yields a fine-grained diagnosis of both components. DeepEval’s referenceless metrics need neither and can therefore be applied to any domain, at the price of depending entirely on the judge. Everything that relies on an LLM judge shares two concerns: the judge can be wrong itself, so its verdicts should be spot-checked against human judgment, and judging many queries with a large model is slow and costly. A pragmatic strategy is to build a small labeled test set for your own documents early, to evaluate the retriever with classic metrics on it, and to add judge-based metrics for the generator.
Summary
Taken together, a RAG system is a pipeline of decisions that can each be evaluated and tuned separately: how documents are chunked, which model embeds them, how the vector database indexes them, whether queries are expanded, whether keyword and semantic search are combined and re-ranked, how the retrieved chunks are put into the prompt, and finally how the result is evaluated. The tasks of this chapter walk through these steps in the same order, so your climate_fever system can serve as a test bed for each of them.
Further Readings
This blogpost by DeepSet gives a good overview of the concept of RAG
This blogpost by qdrant about (their) vector store and its inner workings
Qdrant’s Hybrid Search Documentation provides detailed information on combining multiple search strategies
DeepEval’s RAG Evaluation Guide offers practical approaches to measuring RAG system performance
References
Bowman, S. R., Angeli, G., Potts, C., & Manning, C. D. (2015). A large annotated corpus for learning natural language inference. In L. Màrquez, C. Callison-Burch, & J. Su (Eds.), Proceedings of the 2015 Conference on Empirical Methods in Natural Language Processing (pp. 632–642). Association for Computational Linguistics. https://doi.org/10.18653/v1/D15-1075
Devlin, J., Chang, M.-W., Lee, K., & Toutanova, K. (2019). BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding (arXiv:1810.04805). arXiv. https://doi.org/10.48550/arXiv.1810.04805
Gao, L., Ma, X., Lin, J., & Callan, J. (2023). Precise Zero-Shot Dense Retrieval without Relevance Labels. In A. Rogers, J. Boyd-Graber, & N. Okazaki (Eds.), Proceedings of the 61st Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers) (pp. 1762–1777). Association for Computational Linguistics. https://doi.org/10.18653/v1/2023.acl-long.99
Goyal, K., & Sharma, M. (2022). Comparative Analysis of Different Vectorizing Techniques for Document Similarity using Cosine Similarity. 2022 Second International Conference on Advanced Technologies in Intelligent Control, Environment, Computing & Communication Engineering (ICATIECE), 1–5. https://doi.org/10.1109/ICATIECE56365.2022.10046766
Günther, M., Mohr, I., Williams, D. J., Wang, B., & Xiao, H. (2024). Late Chunking: Contextual Chunk Embeddings Using Long-Context Embedding Models (arXiv:2409.04701). arXiv. https://doi.org/10.48550/arXiv.2409.04701
Jiang, T., Huang, S., Luan, Z., Wang, D., & Zhuang, F. (2023). Scaling Sentence Embeddings with Large Language Models (arXiv:2307.16645). arXiv. https://doi.org/10.48550/arXiv.2307.16645
Late Chunking in Long-Context Embedding Models. (2024). https://jina.ai/news/late-chunking-in-long-context-embedding-models.
Qu, R., Tu, R., & Bao, F. S. (2025). Is Semantic Chunking Worth the Computational Cost? In L. Chiruzzo, A. Ritter, & L. Wang (Eds.), Findings of the Association for Computational Linguistics: NAACL 2025 (pp. 2155–2177). Association for Computational Linguistics. https://doi.org/10.18653/v1/2025.findings-naacl.114
Reimers, N., & Gurevych, I. (2019). Sentence-BERT: Sentence Embeddings using Siamese BERT-Networks (arXiv:1908.10084). arXiv. https://doi.org/10.48550/arXiv.1908.10084
Ru, D., Qiu, L., Hu, X., Zhang, T., Shi, P., Chang, S., Jiayang, C., Wang, C., Sun, S., Li, H., Zhang, Z., Wang, B., Jiang, J., He, T., Wang, Z., Liu, P., Zhang, Y., & Zhang, Z. (2024). RAGChecker: A Fine-grained Framework for Diagnosing Retrieval-Augmented Generation (arXiv:2408.08067). arXiv. https://doi.org/10.48550/arXiv.2408.08067
Santhanam, K., Khattab, O., Saad-Falcon, J., Potts, C., & Zaharia, M. (2022). ColBERTv2: Effective and Efficient Retrieval via Lightweight Late Interaction (arXiv:2112.01488). arXiv. https://doi.org/10.48550/arXiv.2112.01488
Steck, H., Ekanadham, C., & Kallus, N. (2024). Is Cosine-Similarity of Embeddings Really About Similarity? Companion Proceedings of the ACM Web Conference 2024, 887–890. https://doi.org/10.1145/3589335.3651526
Tunstall, L., Reimers, N., Jo, U. E. S., Bates, L., Korat, D., Wasserblat, M., & Pereg, O. (2022). Efficient Few-Shot Learning Without Prompts (arXiv:2209.11055). arXiv. https://arxiv.org/abs/2209.11055
