Most RAG tutorials end exactly where production begins. You split your documents into 512-token chunks, push them through a single embedding model, and call a vector database with simple top-k retrieval. In a demo, this looks convincing. Ask the bot about your company leave policy and it returns a coherent paragraph. Everyone nods. Unfortunately, demos lie.

Production exposes every shortcut. Fixed chunks slice through legal contracts in the middle of indemnification clauses. API documentation turns into overlapping noise that drowns the signal you actually need. Latency creeps up until users abandon the query before the answer arrives. We hit this wall and had to rebuild. Our retrieval layer evolved from “semantic search and hope” into a measured, instrumented pipeline. The result was 95% recall and a 40% cut in latency. Here is what actually worked.

Match the Chunking Strategy to the Document

The 512-token default persists because it is easy, not because it is correct. Different documents carry meaning differently, and your chunking strategy should reflect that.

For legal contracts, use recursive chunking that respects structural boundaries. Legal language is nested. A clause depends on the section above it, and a fixed cut mid-sentence destroys the logic of an obligation. Recursive chunking attempts splits on natural separators first—paragraphs, then sentences—before imposing a token limit. This keeps indemnification or liability clauses intact.

For API documentation, use function-aware chunking. Developers do not search for random paragraphs; they search for endpoints, parameters, and error signatures. A chunk should contain the full function signature, its description, and the return schema as one logical unit. If you split that block in half, the retrieval system returns half the context and the generation model hallucinates the rest.

For support tickets, rely on semantic chunking that follows conversation turns. Support threads are linear and repetitive. A customer repeats the problem, an agent asks for logs, the customer attaches them. Each turn is its own semantic unit. Chunking by turns preserves who said what and when, which matters when the user asks, “What did the agent suggest on Tuesday?”

For internal wikis, try agentic chunking. Hand an LLM a section and ask it to decide where one topic ends and another begins. This costs more at ingest time, but wikis are messy. Pages contain unrelated updates from different teams, and a human-defined boundary rarely helps. Letting a model draw boundaries based on topic shifts cuts noise dramatically.

Running multiple strategies in one pipeline requires tagging documents by type at ingest. That small bit of schema discipline pays off immediately.

Combine Search Methods, Don’t Choose One

Vector search understands intent, but it routinely fails on exact matches. Ask for error code ERR_CONNECTION_REFUSED or a specific SKU, and dense embeddings often return conceptually similar but factually wrong results. BM25, the classic keyword sparse retrieval method, handles exact strings beautifully but misses semantic nuance. You need both.

Use hybrid retrieval. Run vector search and BM25 in parallel. Then combine them with Reciprocal Rank Fusion (RRF). RRF rewards documents that both methods agree are relevant, while still surfacing strong candidates from either approach. The math is simple and the result is stable: no single retrieval method dominates the final ranking.

After fusion, add a cross-encoder reranker. The first stage — vector plus sparse retrieval — is fast and broad. The cross-encoder then scores each query-document pair with full attention, meaning it actually reads the candidate against the original question. Yes, this adds latency. In our case, roughly fifty to one hundred milliseconds. But the gain in precision is sharp enough that the trade is obvious. You cannot afford to skip this if you care about recall.

Fix the Query Before You Fix the Index

Users do not write queries for your search engine. They write them for humans. “It doesn’t work” is a common support query. A vague feature description is a common internal wiki search. If you search the index with that raw input, you get garbage back.

Transform the query before it hits the retriever.

Utiliza la expansión de consultas (query expansion) para generar múltiples versiones de la pregunta del usuario. Si alguien escribe “server down”, tu sistema también debería buscar “service unavailable”, “502 error” y “connection timeout”. Cubrir estas variantes de intención aumentó nuestro recall del 78% al 96%. Es un solo paso y no cuesta casi nada en comparación con la ganancia obtenida.

Utiliza la descomposición de consultas (query decomposition) para preguntas complejas. Cuando un usuario pregunta algo como “¿Cómo migro de la API de facturación heredada a la nueva y qué cambios que rompen la compatibilidad afectan a las cuentas empresariales?”, divídela en subpreguntas. Una subpregunta se enfoca en los pasos de migración. Otra se enfoca en los cambios que rompen la compatibilidad específicos para empresas. Cada una llega a una parte diferente del índice. El modelo de lenguaje posterior sintetiza la respuesta final a partir de fragmentos (chunks) bien recuperados, en lugar de intentar adivinar a través de una ventana de contexto ruidosa.

Deja de adivinar los hiperparámetros

Una vez que tienes múltiples estrategias de fragmentación (chunking), recuperación híbrida y transformación de consultas, te enfrentas a un problema combinatorio. El tamaño del fragmento, el solapamiento, los pesos de fusión, la profundidad del reranker y el recuento de expansión interactúan entre sí. Ajustar uno de forma aislada rompe otro. La búsqueda de cuadrícula (grid search) en este espacio es ineficiente y lenta.

Utiliza la optimización bayesiana en su lugar. Trata esto como una tarea de ajuste (tuning) de aprendizaje automático. Define tu objetivo claramente: maximizar el recall manteniendo la latencia por debajo de un límite. Construye un golden dataset —un conjunto de cientos de preguntas representativas donde sepas con precisión qué fragmentos deben recuperarse—. Luego, deja que la búsqueda bayesiana explore el espacio de configuración de manera eficiente. Esta construye un modelo probabilístico de lo que funciona y luego prueba las regiones más prometedoras.

Cada configuración candidata debe pasar por el golden dataset antes de llegar a staging. Si un nuevo tamaño de fragmento reduce el recall o un reranker más pesado te hace exceder el presupuesto de latencia, la optimización lo detecta automáticamente. Esto elimina la subjetividad de la ecuación. Dejas de debatir si 256 o 512 tokens es “mejor” y empiezas a leer los resultados.

El resultado

Los cambios en el pipeline se acumularon exactamente como esperábamos.

  • Recall@10 subió del 78% al 95%.
  • Latencia P95 bajó de 850 ms a 320 ms.
  • Tasa de alucinación cayó del 12% al 3%.
  • Coste por consulta bajó un 38%, debido en gran medida a que una mejor recuperación nos permitió utilizar un modelo de generación más pequeño y menos tokens de prompt.

La reducción de la latencia sorprendió a algunos miembros del equipo. Añadir rerankers y expansión de consultas parece que debería ralentizar las cosas. Pero como la calidad de la recuperación mejoró, el modelo de generación necesitó menos prompting, menos especulación y menos reintentos. Una buena recuperación hace que todo lo que viene después sea más barato.

Trata la recuperación como infraestructura

La recuperación no es un notebook que ejecutas una vez y olvidas. Es infraestructura y debe gestionarse como código. Versiona tus estrategias de fragmentación. Cuando el equipo legal publique una nueva plantilla de contrato, prueba tu divisor recursivo (recursive splitter) antes de que llegue a producción. Mantén tu golden dataset como documentos vivos, no como un CSV estático del trimestre pasado. Automatiza tus evaluaciones en CI para que cualquier pull request que modifique un modelo de embedding o un peso de fusión reciba un comentario con las cifras de recall y latencia antes de que un humano lo revise.

Tus usuarios nunca preguntarán qué modelo de embedding utilizas. No les importará tu heurística de fragmentación ni tu arquitectura de reranker. Les importa si la respuesta es correcta, si llega rápido y si pueden confiar en ella. Construye un pipeline que se gane esa confianza, mídela con honestidad y deja de tratar la recuperación como algo secundario.

Fuente: Optimizing RAG At Scale
Únete a la discusión: GyaanSetu AI Community