Recursos · 09

Calidad RAG: evaluar un asistente de conocimiento con evidencia

Mida el corpus, la recuperación, las citas, las respuestas, la abstención y la deriva por separado para saber qué es lo que realmente necesita arreglarse.

Actualizado · 9 min

Archivo ficticio sin personas: seis bandejas con documentos en blanco, carpeta burdeos y lámpara de latón Ilustración editorial generada con IA

Lo que esta guía ayuda a lograr

  • Saber si el fallo proviene del corpus, recuperación o modelo
  • Seguimiento de cada cita
  • Premia la abstención adecuada
  • Detectar deriva tras cambio

Comprobación rápida

  • ¿La fuente de referencia está autorizada y vigente?
  • ¿Aparece el pasaje correcto cerca de la parte superior?
  • ¿Se sustentan todas las afirmaciones decisivas?
  • ¿El asistente puede decir que no sabe?
  • ¿Se escalan casos sensibles?

Método paso a paso

  1. 1

    Definir tareas útiles

    Recoger preguntas reales, sus variantes y el resultado empresarial esperado. Agregue ambigüedad, conflicto de fuentes, documentos vencidos y solicitudes fuera de alcance.

    Entregable: taxonomía de casos y riesgos.

  2. 2

    Limpiar el corpus

    Asignar propietario, derechos, fecha de validez y estado a cada fuente. Elimina duplicados, fragmentos huérfanos y documentos de autoridad desconocida.

    Entregable: registro de corpus.

  3. 3

    Evaluar recuperación

    Mida si se encuentran y clasifican los pasajes necesarios antes de evaluar la redacción final. Inspeccionar consultas para las que no existe evidencia.

    Entregable: medidas de cobertura y relevancia.

  4. 4

    Evaluar respuestas y citas

    Verificar la fidelidad a los pasajes, la integridad, las limitaciones, la relación citación-reclamación y la capacidad de señalar contradicciones.

    Entregable: rúbrica de fidelidad y utilidad.

  5. 5

    Rechazo de pruebas y ataques

    Añade inyección indirecta, solicitudes de datos prohibidos, fuentes maliciosas, documentos de prioridad falsos y acciones irreversibles. Definir escalada humana.

    Entregable: resultados de seguridad y barandillas.

  6. 6

    Cambio de monitor

    Versión corpus, índice, configuraciones, modelo e instrucciones. Reproduzca el conjunto estable en cada cambio y analice comentarios reales sin retener datos innecesarios.

    Entregable: tablero de deriva y procedimiento de revisión.

Comprender, calcular y decidir

Respuestas IA: distinguir calidad, cobertura y abstención

Cuente por separado preguntas probadas, respuestas producidas y respuestas validadas. Esta rejilla pedagógica de CIE no es una puntuación NIST ni establece un umbral universal de aprobación.

Use aquí solo preguntas para las que se esperaba respuesta. Defina la validación antes de probar: respuesta correcta, pasaje citado que la respalda, acceso autorizado y fuente vigente. Evalúe aparte las abstenciones esperadas, las contradicciones y los errores graves.

Indicadores y pruebas

IndicadorInterpretaciónPrueba necesaria
Preguntas probadas Conjunto con respuesta esperada Preguntas, criterio y versiones fijadas
Respuestas producidas Preguntas que recibieron respuesta Texto y abstenciones conservados
Respuestas validadas Respuestas que cumplen el criterio Veredicto y pasaje justificativo

Ejemplo trabajado ficticio

Ejemplo ficticio: 100 preguntas, 80 respuestas y 72 validadas. Calidad entre respuestas: 90 %; cobertura: 80 %; éxito en el conjunto: 72 %. El 90 % aislado oculta 20 preguntas sin respuesta y 8 respuestas no validadas.

Desglose del ejemplo ficticio
  • 72 / 100 · Validadas
  • 8 / 100 · No validadas
  • 20 / 100 · Sin respuesta

100 = 72 + 8 + 20. El gráfico mantiene visibles las preguntas sin respuesta; no representa una medición del sitio.

Regla de cálculo

Calidad = validadas / producidas. Cobertura = producidas / probadas. Éxito = validadas / probadas. Un denominador cero no permite calcular la proporción.

Las referencias respaldan el método. Adapte los controles a su contexto; no constituyen certificación. Los títulos de referencia originales y los documentos fuente pueden estar en otro idioma.

Ejemplo trabajado ficticio

Situación ilustrativa

Un asistente interno atiende trámites, algunos de los cuales están vencidos. El conjunto de pruebas contiene preguntas rutinarias, ambiguas y sin respuesta; cada cita se compara con la versión del documento.

Decisión y pruebas esperadas

La publicación espera hasta que se excluyen las fuentes caducadas, se rechazan las respuestas no admitidas y se identifica al propietario del corpus.

Indicadores de gestión

IndicadorQué midePrimera acción
Cobertura de recuperaciónPreguntas para las que se encuentran pasajes necesariosArreglar corpus, fragmentación o consulta antes del modelo
FidelidadAfirmaciones genuinamente respaldadas por fuentes citadasBloquear o reescribir respuestas no admitidas
Abstención útilCasos sin pruebas correctamente rechazados o escaladosUmbrales de confianza de sintonización
RegresiónDiferencia de calidad entre versiones de un mismo setIdentificar el cambio responsable

Errores comunes

  • Medición únicamente de fluidez en escritura
  • Mezclando fallo de recuperación y alucinación
  • Usar un set de evaluación demasiado fácil
  • Cambiando varios componentes sin comparar

Preguntas frecuentes

¿Cuántas preguntas se necesitan?

Comience con un conjunto versionado y representativo que cubra riesgos importantes. La diversidad y la calidad importan más que el volumen artificial.

¿Es suficiente una métrica automatizada?

No. Acelera el triaje, pero los casos sensibles, ambiguos y de dominio necesitan criterios explícitos y revisión humana.

¿Se deben conservar todas las conversaciones?

No. Conservar únicamente los rastros necesarios con una finalidad, acceso y duración definida. Prefiere casos anónimos para mejorar.

RAG: permisos, citas y cachés

Las notas detalladas de esta edición están disponibles en inglés.

Evaluate an answer alongside its document rights

A relevant citation can support an accurate answer while revealing a forbidden document. RAG evaluation should separate faithfulness, freshness and authorisation of passages actually supplied to the model.

  • Annotate permitted documents for each test identity.
  • Remove a group and replay an existing conversation and citation.
  • Track incorrect answers, missing evidence and out-of-scope exposure separately.

Explore the RAG access matrix and replay cases →

References consulted on · OWASP · LLM08:2025 Vector and Embedding Weaknesses OWASP · API1:2023 Broken Object Level Authorization

IA: comprobar un resultado JSON

Las notas detalladas de esta edición están disponibles en inglés.

A retrieved reference does not prove the extracted value

A RAG system can find the right document and return schema-valid JSON that misstates a field. Separate retrieval, the output contract and passage reconciliation to locate what needs correction.

  • Keep an independent reference for decisive fields.
  • Test missing values, contradictions and unavailable documents.
  • Retain unexecuted checks as such instead of counting them as passes.

Compare the 14 outputs and their reasons →

Sources reviewed on · IETF · RFC 8259 · JSON Schema · Object reference · JSON Schema · Draft 2020-12 validation · Python 3.12 · json decoder · python-jsonschema · Schema validation · OWASP · LLM05:2025 Improper Output Handling

RAG: relevancia y clasificación

Las notas detalladas de esta edición están disponibles en inglés.

A RAG system can retrieve useful documents and still produce an incorrect answer. Retrieval evaluation therefore needs its own questions, relevance judgments and defined reading depth. This dossier explains four ranking measures without confusing them with answer faithfulness, access permissions or guaranteed business outcomes.

Documentary references: Stanford CS276’s evaluation material from the 2019 archive and NIST TREC’s reciprocal-rank definition. The CIE workshop uses binary judgments and one query at a time. RR@k here is truncated at k; MRR is a mean RR across multiple queries and is not computed by this workshop.

Stanford CS276 · Retrieval evaluation · 2019 course archive · PDF pp. 3, 5–6 · consulted 2026-10-23

Four measures, four different questions

Four measures, four different questions
MeasureWorkshop calculationUseful readingCondition or limitation
Precision@kRelevant results in the first k / kMeasures the useful proportion in the inspected window.Unavailable if any judgment is missing in the first k.
Recall@kRelevant results in the first k / RR is the number of relevant records in the entire small judged corpus.If R is unknown, publish a value only when it is defined and identical in every possible case.
RR@k1 / rank of the first relevant result within kEquals 0 when no relevant record appears in that fully judged window.An unjudged record before the first relevant result makes that rank uncertain.
nDCG@kDCG@k / IDCG@kCompares ranking gain with the ideal order at the same k.Unavailable if the value changes across possible cases or any case has a zero ideal.

Explicit convention: judgment rᵢ is 0 or 1; DCG@k = Σᵢ₌₁ᵏ rᵢ / log₂(i + 1). With binary relevance, gain 2ʳⁱ − 1 also equals rᵢ. IDCG@k puts min(R, k) relevant records first using the same discount. nDCG@k = DCG@k / IDCG@k when that ideal is defined and nonzero. Keep gain, discount, depth and conventions with any published score.

NIST TREC · Reciprocal rank definition · Repository snapshot 35cf096ba6d5ae08ca4803c056b31ed61a56a6d4 · consulted 2026-10-23

A fictional six-record corpus with declared judgments

Titles and judgments below are created for this exercise. They are neither real search results nor automatic title-based judgments. 1 means relevant, 0 nonrelevant and ? unjudged. Columns Q1–Q5 correspond to the needs displayed in the workshop.

  • Q1 · Prepare a restoration test
  • Q2 · Authorise a document read
  • Q3 · Check a quantum sensor
  • Q4 · Restoration test: C judgment missing
  • Q5 · Restoration: B unjudged, other records off-topic
A fictional six-record corpus with declared judgments
Fictional recordQ1Q2Q3Q4Q5
A · Restoration procedure10011
B · Recovery budget1001?
C · Restoration test log100?0
D · Account and permission guide01000
E · Archiving policy00000
F · Publication schedule00000

Taller de clasificación

Choose a need and enter an ordered list of A–F identifiers separated by commas. Change k to inspect only the first k results. The list may omit documents, but each identifier must be unique and k cannot exceed its length. Calculation stays local without collection, import, transmission, storage or export.

This reader queries no search engine, private corpus or AI model. It measures neither answer truth, correct citation nor permission security. Scores concern declared judgments in this small fictional universe. Do not present an exercise value as a benchmark of your system or a universal deployment threshold.

Unjudged and nonrelevant are different states

Unjudged and nonrelevant are different states
SituationCIE educational convention
Missing judgment within kPrecision may vary. Reciprocal rank remains known if the first relevant record is identified before any unjudged record.
Missing judgment elsewhereR becomes a range of possibilities. Do not assume recall and nDCG are always unknown: a value may remain constant, for example when the order is ideal in every case.
No relevant record in a fully judged corpusPrecision@k and RR@k are 0. The reader shows Recall@k and nDCG@k as unavailable for this zero-denominator case.
CIE publication ruleExplore every binary assignment of missing judgments, at most 64 for six records. Publish a measure only if it is defined and identical in every assignment. These are possibilities, with no probabilities assigned and no actual imputation.

Ten explained scenarios, available without JavaScript

K01 · Relevant records first
Relevant records first
NeedSupplied orderkExpected reading
Q1A,B,C,D,E,F3Precision@3 = 1, Recall@3 = 1, RR@3 = 1 and nDCG@3 = 1 in this fully judged corpus.
K02 · Relevant records after cutoff
Relevant records after cutoff
NeedSupplied orderkExpected reading
Q1D,E,F,A,B,C3All four measures are 0 at k = 3. Relevant records exist but are placed after the inspected window.
K03 · First relevant record at rank two
First relevant record at rank two
NeedSupplied orderkExpected reading
Q1D,A,E,B,F,C3Precision@3 and Recall@3 are 1/3; RR@3 is 1/2. nDCG considers position and the ideal order.
K04 · Relevant records omitted
Relevant records omitted
NeedSupplied orderkExpected reading
Q1A,D,E,F3R remains 3 in the corpus even though B and C are absent from the list. Recall must not use only returned results as its denominator.
K05 · Duplicate identifier
Duplicate identifier
NeedSupplied orderkExpected reading
Q1A,A,B3Input rejected: A must not be counted twice. Correct the ranking rather than inflating the relevant count.
K06 · Unjudged before the first relevant record
Unjudged before the first relevant record
NeedSupplied orderkExpected reading
Q4C,A,D,E,B,F3C is unjudged. Precision@3, Recall@3, RR@3 and nDCG@3 are unavailable under the declared conventions.
K07 · Unjudged after the window
Unjudged after the window
NeedSupplied orderkExpected reading
Q4A,B,D,E,F,C3Precision@3 is 2/3 and RR@3 is 1. Recall@3 and nDCG@3 remain unavailable because C’s corpus judgment is missing.
K08 · Need with no relevant record
Need with no relevant record
NeedSupplied orderkExpected reading
Q3A,B,C,D,E,F3Precision@3 and RR@3 are 0. Recall and nDCG remain unavailable; this is an explicit convention rather than division by zero.
K09 · Change reading depth
Change reading depth
NeedSupplied orderkExpected reading
Q2A,D,B,C,E,F1At k = 1 no relevant record is visible. At k = 2, D appears: precision 1/2, recall 1 and RR@2 = 1/2.
K10 · Unknown relevance, always ideal ordering
Unknown relevance, always ideal ordering
NeedSupplied orderkExpected reading
Q5A,B,C,D,E,F2B may be relevant or not. Either way, all relevant records are within the first two ranks and the order stays ideal: recall, RR and nDCG are 1. Precision remains unknown.

Prepare a reproducible evaluation

Prepare a reproducible evaluation
Suggested checkRecord to retain
NeedsRepresentative and unanswerable questions; specify the documentary need behind each wording.
CorpusDocument and index versions, accessible scope and deletion or revocation rules.
JudgmentsRelevance rule, assessors, disagreements and unjudged state; do not equate clicks with documentary truth.
ProtocolSame k, filters, data and conventions before and after a retrieval change.
RegressionPer-query and per-need-family results, gaining and losing cases, hypothesis and checks on new documents.
Final answerEvaluate faithfulness, citations, useful refusals and permissions separately; better retrieval scores do not validate this stage.

For a reviewable decision, keep the question, ranking, judgments, k and corpus limitations with the score. One average can conceal a regression on a critical need. Error tracking and answer review remain necessary even when the first records are relevant.

Sources, editions and credits

Original CIE explanations, six documents, five needs, judgments and scenarios. Conceptual references: Stanford CS276 and NIST TREC’s reciprocal-rank definition. No source chart, ranking example or code is reproduced. The CIE program and its unavailable-value conventions are not a complete trec_eval implementation.

Stanford CS276 · Retrieval evaluation · 2019 course archive · PDF pp. 3, 5–6 · consulted 2026-10-23

SHA-256 : be38261a8cdbc95551a502504d0a1c146ea453ffd9712243ea067ac8538c1826

NIST TREC · Reciprocal rank definition · Repository snapshot 35cf096ba6d5ae08ca4803c056b31ed61a56a6d4 · consulted 2026-10-23

SHA-256 : 64159909e6e1e4e9e4dd3c569b119fdc90696d0b03cd902e6a9358dcd6e84677

Referencias oficiales

Las referencias respaldan el método. Adapte los controles a su contexto; no constituyen certificación. Los títulos de referencia originales y los documentos fuente pueden estar en otro idioma.

Referencias consultadas el .