The transition of generative AI products from proof of concept to production has proven to be a major challenge for software engineers around the world. We believe many of these difficulties stem from the assumption that these products are merely extensions of traditional transactional or analytical systems. In our work with this technology, we've found that they introduce a whole new set of problems, including hallucinations, unbounded data access, and nondeterminism.
A handful of standard patterns can help us avoid these problems. Below are some practical notes from experience on these patterns:
- Direct Prompting
- Embeddings
- Evals
- Hybrid Retriever
- Query Rewriting
- Reranker
- Retrieval Augmented Generation (RAG)
Direct Prompting

CleanShot 2025-02-14 at 09.34.05@2x.png
The most basic way to use an LLM is to connect an off-the-shelf LLM directly to users so they can enter a prompt and receive a response immediately, with no intermediate steps. This is the kind of experience an LLM provider might offer directly.
When to use
Although it works well in many situations, it still has some notable drawbacks.
The first problem is that the LLM is limited by its training data and doesn't know what has happened since training. That also means the LLM doesn't know specific information outside its training set. In fact, even within its training set, it still doesn't understand the context it's operating in. You should consider using the parts of a knowledge base that are relevant to that context.
Beyond knowledge-base limitations, there are concerns about how the LLM will behave, especially when faced with malicious prompts. Can it be tricked into leaking confidential information, or into giving incorrect answers?
LLMs have a habit of sounding confident when their knowledge is weak and casually making up plausible but meaningless answers. That can be amusing, but if the LLM is acting as a spokesbot, it becomes a serious flaw.
Summary
Direct prompting is a powerful tool, but it usually can't be used on its own. We've found that for our users to apply LLMs in practice, additional measures are needed to address the limitations and problems that direct prompting itself introduces.
The first step we need to take is to figure out just how good the LLM's results are. In our regular software development work, we've learned to value testing and to make sure our systems reliably do what we intend.
As we extended our practices to working with Gen AI, we found it essential to establish a systematic way to evaluate the effectiveness of model responses.
Evals
Definition
Evaluate the responses of an LLM in the context of a specific task.
In traditional systems, we mostly do this through testing. We provide carefully selected sample inputs and verify that the system responds the way we expect.
With LLM-based systems, we run into a system that no longer behaves deterministically. Such a system will give different outputs for the same input when a request is repeated. That doesn't mean we can't check its behavior to make sure it matches our intent, but it does mean we have to think about it differently.
Gen-AI checks behavior through evaluations, often shortened to evals. Although you can evaluate a model on a single output, it's more common to evaluate its behavior across a variety of scenarios. This approach makes sure all expected cases are handled and that model output meets the expected standard.
Scoring and Judging
A scorer is a component or function that assigns a numerical score to generated output, reflecting evaluation metrics such as relevance, coherence, factuality, or semantic similarity between the model output and the expected answer.

CleanShot 2025-02-14 at 09.54.25@2x.png
Different evaluation techniques exist depending on who calculates the score, which raises a question: who ultimately acts as the judge?
- Self evaluation: Self-evaluation lets LLMs evaluate and improve their own answers. Although some LLMs are better at this than others, the approach carries a key risk. If the model's internal self-evaluation process is flawed, it can produce output that looks more confident or polished than it really is, leading to reinforcement of errors or bias in later evaluations. Although self-evaluation is one technique, we strongly recommend exploring other strategies.
- LLM as a judge: The LLM's output is scored by another model, which can be a more powerful LLM or a specialized Small Language Model (SLM). Although this approach still uses an LLM for evaluation, using a different LLM helps address some of the problems with self-evaluation. Since the two models are unlikely to make the same mistakes or share the same biases, this technique has become a popular choice for automated evaluation processes.
- Human evaluation: Vibe checking is a technique for assessing whether an LLM response matches the desired tone, style, and intent. It's an informal way to evaluate whether the model understands and responds in a way that fits the situation. In this technique, a human manually writes prompts and evaluates the responses. Although it's hard to scale, it's the most effective way to check for elements that automated methods often miss. In our experience, combining LLM evaluation with human evaluation is more effective for understanding how an LLM performs in critical areas of a general AI product. This combination strengthens the evaluation process by drawing on both automated judgment and human insight, giving a more comprehensive view of LLM performance.
Running the Evals
As with tests, we run evals as part of the build pipeline for Gen-AI systems. Unlike tests, they aren't simple pass/fail results. Instead, we have to set thresholds, along with checks to make sure performance doesn't degrade. In many ways, we treat evals similarly to performance tests.
A live generative AI system's performance may change in production. So we need to run periodic evaluations against the deployed production system, again looking for any drop in our scores.
Evals can target the entire system as well as any component that includes an LLM. Guardrails and Query Rewriting contain logically distinct LLMs that can be evaluated separately or as part of the full request flow.
Evals and Benchmarking
Benchmarking is the practice of establishing a baseline set of well-defined tasks for comparing LLM outputs. In benchmarking, the goal is to minimize variability as much as possible. This is done by using standardized datasets, well-defined tasks, and established metrics to continuously track model performance over time.
So when a new version of a model is released, you can compare metrics and make an informed decision about whether to upgrade or stay on the current version.
Unlike general benchmarks, evals measure LLM output on our specific tasks. There's no industry-accepted evaluation dataset, so we have to create one that best fits our use case.
The hard part of using evals is that our understanding of which mechanisms work best for scoring and judging is still early. Still, we believe evals are essential for putting LLM-based systems into use with confidence—and for letting users maintain a healthy skepticism about them.
Embedding
Definition
Transform large data blocks into numeric vectors so that embeddings near each other represent related concepts.
Embeddings in LLMs
An LLM is a specialized neural network called a Transformer. Although its internal structure is complex, it can be conceptually divided into an input layer, multiple hidden layers, and an output layer.

CleanShot 2025-02-14 at 10.02.59@2x.png
An important part of the input layer is the embedding of the LLM's vocabulary. These are known as the LLM's internal, parametric, or static embeddings.
An LLM performs the following logical steps to generate a response.
- At the input layer, the tokenizer converts the input prompt text and images into embeddings.
- These embeddings are then passed through the LLM's internal hidden layers, also called attention layers, which extract relevant features from the input. Suppose our model is trained on nutrition data; different attention layers analyze the input from the perspectives of health and nutrition.
- Finally, the output of the last hidden state (that is, the last attention layer) is used to make a prediction.
When to use it
Embeddings capture the meaning of data so that items such as text or images can be compared for semantic similarity. Unlike surface-level matching of keywords or patterns, embeddings encode deeper relationships and contextual meaning.
So generating embeddings involves running specialized AI models that are usually smaller and more efficient than large language models. Once created, embeddings can be used to perform similarity comparisons efficiently, often relying on simple vector operations such as cosine similarity.
However, embeddings aren't well suited to structured or relational data, where exact matching or traditional database queries are more appropriate. Tasks such as finding exact matches, performing numerical comparisons, or querying relationships are better handled by SQL and traditional databases than by embeddings and vector stores.
Evals give us a way to assess a system's overall capabilities, while embeddings give us a way to index large amounts of unstructured data. LLMs are trained on corpora of this data—or, as the community says, pretrained. For general cases, that's fine, but if we want the model to use more specific or newer information, we need the LLM to know about data outside its pretraining set.
One way to adapt a model to a specific task or domain is to do additional training, known as fine-tuning. The problem is that it's very expensive, so it's usually not the best approach. For most cases, we've found the best path is RAG.
Retrieval Augmented Generation (RAG)
Definition
Retrieve relevant document fragments and include these when prompting the LLM.
A common metaphor is that an LLM is a junior researcher. Such a person is articulate and generally knowledgeable but doesn't know the details of the subject—and is overconfident, preferring to invent a plausible answer rather than admit ignorance. In RAG, we ask this researcher a question and give them a file containing the most relevant documents, telling them to read those documents before giving an answer.
We've found RAGs to be an effective way to use LLMs with specialized knowledge. But they lead to a classic information retrieval (IR) problem—how do we find the right documents to give to our eager researcher?
A common approach is to build a document index using embeddings and then use that index to search for documents.
This part is building the index. We do it by splitting documents into chunks, creating embeddings for those chunks, and saving the chunks and their embeddings in a vector database.
CleanShot 2025-02-14 at 10.13.36@2x.png
We then handle user requests by creating an embedding for the query using an embedding model. We use that embedding to run an ANN similarity search over the vector store to retrieve matching fragments. Next, we combine the results with the original query using a RAG prompt template and send the full input to the LLM.

CleanShot 2025-02-14 at 10.14.04@2x.png
When to use
By giving the LLM relevant information in its query, RAG overcomes the limitation that an LLM can only respond based on its training data. It combines the strengths of information retrieval and generative models.
RAG is especially useful for rapidly changing data such as news articles, stock prices, or medical research. It can quickly retrieve the latest information and incorporate it into the LLM's response, providing more accurate and contextually relevant answers.
RAG improves the truthfulness of LLM responses by accessing and incorporating relevant information from a knowledge base, minimizing the risk of hallucinations or fabricated content. It's easy for the LLM to cite the provided documents as part of its context, allowing users to verify its analysis.
The context of the retrieved documents can mitigate bias in the training data. In addition, RAG can take advantage of in-context learning (ICL) by embedding task-specific examples or patterns in the retrieved content, enabling the model to adapt dynamically to new tasks or queries.
RAG in Practice
Our description is what we consider basic RAG, roughly the same as what's described in the original paper. We've used RAG on multiple projects and found it an effective way to interact with large, messy datasets using LLMs. However, we've also found that the basic idea needs a lot of refinement to solve serious problems.
Example
One example we'll focus on is work building a query system for a multinational life sciences company. The company's researchers often need to investigate details from past studies of various compounds and species. These studies span two decades of research and produced 17,000 reports, each thousands of pages long and containing both text and tabular data. We built a chatbot that let researchers query this treasure trove of loosely structured data.
Before this project, answering complex questions usually meant manually sifting through large numbers of PDF documents, which could take days to weeks. Now researchers can use multi-hop queries in our chatbot to find what they need in just a few minutes. We also added visualizations where necessary to make it easier to explore the datasets used in the reports.
This is an example of RAG applied successfully, but to move it from proof of concept to a viable production application, we needed to overcome several serious limitations.
Limitation
| Limitation | Explanation | Mitigating Pattern |
|---|---|---|
| Inefficient retrieval | When you first start using a retrieval system, it's sobering to realize that relying only on document chunk embeddings in a vector store doesn't lead to efficient retrieval. A common assumption is that chunk embeddings alone will work, but in practice, while they're useful, they're not very effective on their own. When we create a single embedding vector for a document chunk, we compress multiple paragraphs into one dense vector. Although dense embeddings do a good job of finding similar passages, they inevitably lose some semantic detail. No amount of fine-tuning can fully close that gap. | Hybrid Retriever |
| Minimalistic user query | Not every user can clearly express their intent in a well-structured natural language query. Often queries are short and vague, lacking the specificity needed to retrieve the most relevant documents. Without clear keywords or context, the retriever may pull in a broad range of information, including irrelevant content, which leads to less accurate and overly generic results. | Query Rewriting |
| Context bloat | The Lost in the Middle paper shows that LLMs currently struggle to use information effectively in long input contexts. Performance is usually strongest when relevant details are at the beginning or end of the context. However, when the model has to retrieve key information from the middle of a long input, performance drops sharply. This limitation persists even in models specifically designed for large contexts. | Reranker |
| Gullibility | We described LLMs earlier as a junior researcher: articulate, knowledgeable, but not deeply informed about specific details. There's one more adjective we should use: gullible. Our AI researcher is easy to persuade into saying things that are better left unsaid, leaking secrets, or making things up to appear more knowledgeable than it really is. | Guardrails |
Hybrid Retriever
Definition
Combine searches using embeddings with other search techniques.

CleanShot 2025-02-14 at 10.21.18@2x.png
Although vector operations on text embeddings are a powerful and sophisticated technique, there's a lot to be said for simple keyword search.
Techniques such as TF/IDF and BM25 are well-established methods for efficiently matching exact terms. We can use them to search large document collections faster and with less computation, finding candidates that vector search alone wouldn't surface. Combining these candidates with vector search results gives us a better candidate set.
The downside is that this can leave the LLM with too large a document set, but we can address that with a reranker.
When we use a hybrid retriever, we need to supplement the indexing process to prepare our data for vector search. We tried different chunk sizes and eventually settled on 1,000 characters with 100 characters of overlap.
This lets us focus the LLM's attention on the most relevant context fragments. Although model context lengths are increasing, current research suggests that accuracy decreases as prompts get larger.
When to use
Embeddings are a powerful way to find unstructured data chunks. They're a natural fit for LLMs because they play an essential role in LLMs themselves. But data often has characteristics that allow alternative search methods, which can be used as a supplement.
Indeed, sometimes we don't need to use vector search in the retriever at all.
As one example, we used AI to help understand legacy code. We used a Neo4J graph database to store an abstract syntax tree representation of the codebase and annotated the tree's nodes with data from documentation and other sources. In our experiments, we found that representing a module's dependencies, function calls, and caller relationships as a graph was more direct and effective than using embeddings.
Still, embeddings played a role here: during ingestion, we used them together with an LLM to place document fragments on graph nodes.
The key point here is that embeddings stored in a vector database are just one form of knowledge base that a retriever can operate on. Although chunking unstructured text is useful, we've found it beneficial to extract structure wherever possible and use that structure to support and improve the retriever. Every problem has a different best way to organize data for efficient retrieval, and we've found that using multiple approaches to gather valuable document fragments for downstream processing works best.
Query Rewriting
Definition
Use an LLM to create several alternative formulations of a query and search with all the alternatives.

CleanShot 2025-02-14 at 10.26.01@2x.png
Anyone who has used a search engine knows that trying different combinations of search terms is often the best way to find what we want. This is even more obvious with LLMs, where rephrasing a question often leads to very different answers.
We can take advantage of this by having an LLM rewrite the query several times and sending each query to vector search. We can then combine the results and put them into the LLM prompt (often with help from a reranker).
Example
In our life sciences example, a user might start with a prompt exploring thousands of research results.
Were any of the following clinical findings observed in the study XYZ-1234? Piloerection, ataxia, eyes partially closed, and loose feces?
The rewriter sends it to an LLM and asks for alternatives.
The optimal number of alternatives varies by dataset: usually, 3–5 variants work for diverse datasets, while simple datasets may need up to 3 rewrites. When tuning query rewriting, use evals to track progress.
When to use
Query rewriting is essential for complex searches involving multiple subtopics or specialized keywords, especially in domain-specific vector stores.
Creating several alternative queries can improve the documents we're able to find, but it requires extra LLM calls to generate those alternatives and extra retriever calls to use them. Those extra calls add resource cost and latency. Teams should try to determine whether the retrieval improvement is worth the cost.
In our life sciences collaboration example, we found that using GPT 4o to create five variants was worth it.
Reranker
Definition
Rank a set of retrieved document fragments according to their usefulness and send the best of them to the LLM.

CleanShot 2025-02-14 at 10.28.58@2x.png
A Retriever's job is to find relevant documents quickly, but fast search responses lead to lower-quality results. We can try more sophisticated searches, but running a complex search over the entire dataset usually takes too long. In this case, we can quickly generate a large number of documents of varying quality and then rank them by how relevant and useful their information is as context for the LLM prompt.
Rerankers can use deep neural network models—usually cross-encoders such as bge-reranker-large—to accurately rank retrieved documents by relevance to the input query. This reranking process is too slow and expensive to run over the entire contents of a vector store, but it's worthwhile when you're only considering candidates returned by a faster but coarser search. We can then choose the best of those candidates to put in the prompt, which keeps the prompt from getting bloated and prevents the LLM from being confused by low-quality documents.
When to use
Reranking improves the accuracy and relevance of answers in RAG systems. Reranking is valuable when there are too many candidate answers or when low-quality answers would degrade the LLM's response quality.
Reranking does involve an additional interaction with another AI model, which adds processing cost and latency to the response, making it less suitable for high-traffic applications. Ultimately, whether to rerank should be based on the specific requirements of the RAG system, balancing the need for high-quality responses against performance and cost constraints.