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:

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.

Illustration of "semantic embeddings" of different word. The words "good", "nice", "orange", "bad" and "blue" are all mapped to a vector space.
(a) Illustration of “semantic embeddings” of different word.
Illustration of similarities between these words. 4 common similarity concepts seen in semantic retrieval: cosine, euclidean, dot product and manhattan.
(b) Illustration of 4 common similarity concepts seen in semantic retrieval: cosine, euclidean, dot product and manhattan. dot product and cosine are taking the direction of the vector into account, while the cosine ignores the length of the vectors and the dot product does not. Manhattan and euclidean are both measuring the distance between two points in a vector space, but they do it differently. Euclidean is the straight line between two points, while manhattan is the sum of the absolute differences between the coordinates of the two points. Distances are shown as similarities via 1/(1 + distance), and each panel is rescaled to 0 to 1.
Fig 6.1: Illustration of common similarity metrics in semantic search.

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.

Fig 6.2: Illustration of the usage of embedding-based distances in retrieval.

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:

  1. Chroma - an in-memory database for small applications that is especially easy to get to run.

  2. 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.

  3. 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.

Fig 6.3: Illustration of a RAG-system.

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

  1. using the information given
  2. not inventing new information
  3. 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.

ADK has no ready-made integration for local vector stores like Qdrant. This is less of a drawback than it sounds: the retrieval part stays exactly the plain Qdrant and sentence-transformers code from above, and ADK only enters the picture when an LLM is supposed to use it.

The first step is again the setup of a vector database and an embedding model. Note that an in-memory Qdrant client (location=":memory:") loses all data when the Python kernel restarts, which is fine for this example:

from qdrant_client import QdrantClient
from qdrant_client.models import Distance, VectorParams, PointStruct
from sentence_transformers import SentenceTransformer

embedder = SentenceTransformer("sentence-transformers/all-MiniLM-L12-v2")
client = QdrantClient(location=":memory:")
client.create_collection(
    collection_name="paper",
    vectors_config=VectorParams(size=embedder.get_embedding_dimension(),
                                distance=Distance.COSINE),
)
Loading weights:   0%|          | 0/199 [00:00<?, ?it/s]

True

As an example, we will add the paper “Attention Is All You Need”. Here is a short excerpt from our plain-text version of the paper:

         Attention Is All You Need
arXiv:1706.03762v7 [cs.CL] 2 Aug 2023




                                             Ashish Vaswani∗                Noam Shazeer∗               Niki Parmar∗             Jakob Uszkoreit∗
                                              Google Brain                   Google Brain             Google Research            Google Research
                                          avaswani@google.com             noam@google.com            nikip@google.com            usz@google.com

One embedding for the whole paper would average over every topic in it, and the embedding model truncates long inputs anyway. We therefore chunk the text (more about that later). For now, a naive chunking into windows of 100 words with an overlap of 20 words will do. The last line shows how many chunks this gives us:

def chunk(text: str, size: int = 100, overlap: int = 20) -> list[str]:
    words = text.split()
    return [" ".join(words[i:i + size]) for i in range(0, len(words), size - overlap)]

chunks = chunk(text)

client.upsert(
    collection_name="paper",
    points=[
        PointStruct(id=i, vector=vector.tolist(), payload={"text": c})
        for i, (c, vector) in enumerate(zip(chunks, embedder.encode(chunks)))
    ],
)
len(chunks)
78

The retrieval itself is a plain Python function. In ADK, any function with type hints and a docstring can be handed to an agent as a tool; the docstring becomes the tool description the model sees. Each returned snippet is prefixed with its cosine similarity to the question, higher means more similar:

def find_references(question: str) -> str:
    """Query a database containing the paper "Attention Is All You Need" in parts.
    This paper introduced the transformer architecture and its self-attention mechanism.
    Returns a collection of scored text snippets that are relevant to your question."""
    hits = client.query_points(
        collection_name="paper",
        query=embedder.encode(question).tolist(),
        limit=5,
    ).points
    return "\n".join(f"{round(h.score, 2)} - {h.payload['text']}" for h in hits)

print(find_references("What do the terms Key, Value and Query stand for in self-attention?")[:800])
0.55 - 3.2 Attention An attention function can be described as mapping a query and a set of key-value pairs to an output, where the query, keys, values, and output are all vectors. The output is computed as a weighted sum 3 Scaled Dot-Product Attention Multi-Head Attention Figure 2: (left) Scaled Dot-Product Attention. (right) Multi-Head Attention consists of several attention layers running in parallel. of the values, where the weight assigned to each value is computed by a compatibility function of the query with the corresponding key. 3.2.1 Scaled Dot-Product Attention We call our particular attention "Scaled Dot-Product Attention" (Figure 2). The
0.51 - query with the corresponding key. 3.2.1 Scaled Dot-Product Attention We call our particular attention "Scaled Dot-Product Attention" (

To use the tool, we need an agent: an LLM that can decide to call tools and read their results before it answers. We use Google’s Agent Development Kit (ADK) here, which we will look at in more detail in the session on agents. It is installed with uv add google-adk litellm, and the model used below has to be available in Ollama (ollama pull qwen3:4b). ADK talks to local models through a LiteLlm wrapper, whose model string starts with a provider prefix (ollama_chat/ for Ollama). The helper below keeps that string in one place, so swapping models is a one-word change:

import os
from google.adk.models.lite_llm import LiteLlm

os.environ["OLLAMA_API_BASE"] = "http://localhost:11434"

def model(name: str) -> LiteLlm:
    return LiteLlm(model=f"ollama_chat/{name}")

To run an agent, ADK needs a runner, which takes care of the session (the conversation state) for us. InMemoryRunner.run_debug is the shortest way to send a question and collect everything that happened as a list of events. As the name says, it is meant for experiments like this one, not for production code. With quiet=True it does not print the events itself, since our helper below prints what we want to see. run_debug is asynchronous: it waits for the model’s response over the network, and await lets Python pause at this point until the response has arrived. In a Jupyter notebook, await can be used directly in a cell; in a plain Python script, you would wrap the call as asyncio.run(ask(...)).

Since we are going to compare several agents, we wrap all of this into a small function. It creates a new runner, and thereby a fresh session, for every call, so the agent remembers nothing between questions and each test is independent. It prints every tool call, so we can see whether the agent actually used the database, and it skips the model’s reasoning (“thinking”) parts if the model returns them as separate parts, so only the answer is returned:

from google.adk import Agent
from google.adk.runners import InMemoryRunner

async def ask(agent, question: str) -> str:
    events = await InMemoryRunner(agent=agent).run_debug(question, quiet=True)
    for event in events:
        for call in event.get_function_calls():  # a model may request several calls at once
            print(f"[tool call] {call.name}({call.args})")
    final = [e for e in events if e.is_final_response() and e.content][-1]
    return "".join(p.text for p in final.content.parts if p.text and not p.thought)

To compare different ways of building the system, we ask all of them the same question:

q = "What is the meaning of Query, Key and Value in the context of self-attention?"

Now we can build the agent and give it our tool:

agent = Agent(
    name="paper_assistant",
    model=model("qwen3:4b"),
    instruction="You answer questions about scientific papers.",
    tools=[find_references],
)

print(await ask(agent, q))
The **Query (Q)**, **Key (K)**, and **Value (V)** are three transformed vectors derived from the input tokens in the self-attention mechanism:

1. **Query**: Represents the "question" or "focus" of the current token. It determines what information the token is seeking from other tokens.
2. **Key**: Acts as a "tag" or "identifier" for the tokens. It helps measure the relevance of other tokens to the current token.
3. **Value**: Contains the actual information or content of the tokens. It is used to compute the weighted sum of relevant information based on the attention scores.

In self-attention, the attention score between two tokens is computed as the dot product of the Query and Key vectors, followed by a softmax normalization. This score determines how much weight the Value of one token should contribute to the output of another. This mechanism allows the model to dynamically focus on relevant parts of the input sequence. 

This concept is central to the transformer architecture introduced in the paper *Attention Is All You Need*.

LLM answers vary from run to run, so your output will differ from ours. In our run, no [tool call] line appears: the agent did not consult the database at all and answered from its training data. Even in runs where it does call the tool, look closely at the answer: does it quote the retrieved passages, or does it read like general knowledge about attention? If nothing in the answer points back to the snippets printed above, we cannot tell which parts come from the paper and which from the model’s training data. Nothing in the instruction told the model to use the tool, or that the retrieved text should be the basis of its answer.

One way to steer the agent is to be more explicit in the system prompt. In ADK, the system prompt is simply the instruction of the agent:

strict_agent = Agent(
    name="strict_paper_assistant",
    model=model("qwen3:4b"),
    instruction="""You are designed to help answer questions based on a collection of paper excerpts.
You have access to tools that allow you to query the paper content.
Do not answer without using a tool if a tool can be used to answer a question.
Always back up your claims with a text passage you retrieved and quote it.
If the tools do not return relevant passages, say so instead of guessing.""",
    tools=[find_references],
)

print(await ask(strict_agent, q))
[tool call] find_references({'question': 'What is the meaning of Query, Key and Value in the context of self-attention?'})


The **Query**, **Key**, and **Value** are fundamental components of the self-attention mechanism in transformers. Here's their role based on the paper:

1. **Query (Q)**: Represents the current position's "question" or "focus" in the sequence. It is used to determine how much attention (weight) to assign to other elements in the sequence.  
2. **Key (K)**: Represents the "features" or "information" of other positions in the sequence. It is used to compute compatibility scores with the Query.  
3. **Value (V)**: Represents the actual information (e.g., word embeddings) that is weighted and summed based on the attention scores.  

The attention mechanism computes weights by comparing the Query to the Keys (e.g., via dot-product), then uses these weights to compute a weighted sum of the Values. This allows each position to "attend" to others, capturing dependencies within the sequence.  

**Key passage**:  
> "The output is computed as a weighted sum of the values, where the weight assigned to each value is computed by a compatibility function of the query with the corresponding key."  
> "We compute the dot products of the query with all keys, divide each by dk, and apply a softmax function to obtain the weights on the values."  

This process enables self-attention to dynamically prioritize relevant parts of the sequence for each position.

Compare the two answers: in our run, the stricter agent called the tool and quoted the paper. In general, the stricter instruction should lead to quotes that you can find in the retrieved snippets, and to less content that the snippets do not support.

Whether an agent uses its tools reliably depends heavily on the model. Very small models (around 1 billion parameters) frequently skip the tool and answer from their own, possibly hallucinated, knowledge, or produce malformed tool calls. Try swapping in a smaller model such as qwen3:0.6b or llama3.2:1b in the model(...) calls above and compare. Since a bigger model is not always an option, another approach is to take the decision about retrieval away from the model entirely. Instead of letting the model decide whether to retrieve, Python always retrieves and hands the snippets to the model, whose only job is to answer from them. This is the idea of an LLM pipeline with deterministic routing, which we will meet again in the session on LLM pipelines (?Multi-Agent Orchestration): the control flow is fixed in code, and the LLM fills in one well-defined step.

ADK expresses such a fixed control flow as a Workflow. A workflow is a graph of steps, called nodes, and its edges define which node runs after which. Graphs allow branches and loops, which we will use in the session on LLM pipelines; our pipeline is just a straight line.

Each node can be a plain Python function or an agent. Whatever a node returns is handed to the next node: a function receives it through a parameter that must be named node_input (other parameter names are looked up in the workflow’s state instead), and an agent receives it as its user message. A node sees nothing else, which is why retrieve below repeats the question in its output: otherwise the summarizer would get the snippets, but not the question. The tuple ("START", retrieve, summarizer) describes a chain: "START" is the entry point that receives the user’s message, which then flows through retrieve into summarizer.

from google.adk import Workflow

def retrieve(node_input: str) -> str:
    return f"Question: {node_input}\n\nSnippets:\n{find_references(node_input)}"

summarizer = Agent(
    name="summarizer",
    model=model("qwen3:4b"),
    instruction="""Answer the question using only the provided text snippets.
Quote the snippets you use. If they do not contain the answer, say so.""",
)

rag = Workflow(name="rag", edges=[("START", retrieve, summarizer)])

print(await ask(rag, q))
The meaning of Query, Key, and Value in the context of self-attention is as follows:  
- **Query**: Represents the current position's need for information.  
- **Key**: Used to compute the compatibility (or similarity) between the current position and others, determining how much each value should contribute.  
- **Value**: Holds the actual information that is weighted based on the compatibility between the query and keys.  

The attention mechanism computes weights by matching the query with keys, then uses these weights to compute a weighted sum of the values (quoted from snippet 0.55 and 0.52). In self-attention, all positions in a sequence act as both query, key, and value, enabling the model to relate different positions within the same sequence (snippet 0.53).

InMemoryRunner accepts a workflow just like an agent, so our ask helper works unchanged. Note that no [tool call] line appears: retrieval is now a step of the graph, not a decision of the model. This makes the pipeline work with models that are too small for reliable tool calling, but it comes at a cost. The workflow always retrieves, even for questions that need no retrieval, and it retrieves exactly once with the raw question, so it cannot rephrase the query or search again when the results are poor, as a tool-calling agent can. And “answer using only the snippets” is still just a request: a small summarizer can drift away from the snippets all the same.

who decides to retrieve? model size needed traceability
agent with tool the model large enough for reliable tool calls tool calls visible, use of the snippets unclear
agent with strict instruction the model large enough for reliable tool calls quotes can be checked against the snippets
retrieve-then-summarize workflow the code, always once small models suffice fixed path, quotes can be checked

To see how the three variants handle missing information, ask all of them a question the paper does not answer, for example about GPT-4, and compare whether they admit that the snippets do not contain the answer.

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.

Fig 6.4: Document retrieval (F1@5) of the two semantic chunkers relative to fixed-size chunking, redrawn from Table 1 of Qu et al. (2025) (CC BY 4.0). Datasets marked with * are stitched: artificially concatenated short documents on different topics.
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:

  1. 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

  2. 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.

In the workflow at the end of Tip 6.1, HyDE is just one more agent in front of the retrieval step: the agent writes the hypothetical document, and the retrieval function searches with it instead of with the question. Since the summarizer should still answer the original question, a first function node stores it in ctx.state, the workflow’s shared memory. The code reuses model, ask, find_references and summarizer from Tip 6.1:

from google.adk import Agent, Workflow

def store_question(node_input: str, ctx):
    ctx.state["question"] = node_input
    return node_input

hyde_writer = Agent(
    name="hyde_writer",
    model=model("qwen3:4b"),
    instruction="Write a short passage, as it could appear in a scientific paper, "
                "that answers the question. Output only the passage.",
)

def retrieve(node_input: str, ctx) -> str:
    # node_input is the hypothetical passage: search with it, but answer the original question
    return f"Question: {ctx.state['question']}\n\nSnippets:\n{find_references(node_input)}"

hyde_rag = Workflow(
    name="hyde_rag",
    edges=[("START", store_question, hyde_writer, retrieve, summarizer)],
)

print(await ask(hyde_rag, "What is the meaning of Query, Key and Value in the context of self-attention?"))

We will look at ctx.state and more complex workflow graphs in Multi-Agent Orchestration.

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.

Fig 6.5: Precision and recall of a retriever as a Venn diagram of relevant and retrieved documents, and DeepEval’s judge-based counterparts (see below).

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
Fig 6.6: What DeepEval’s RAG metrics compare. Solid arrows are the RAG pipeline, dotted arrows are the comparisons an LLM judge makes. Only the two metrics pointing to the expected output need a reference answer.

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.

Fig 6.7: The claims of ground-truth answer, model response and retrieved context, what each region means and the RAGChecker metric it feeds into.

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

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