Тестирование и оценка приложения RAG
Повышайте уверенность в своём первом приложении RAG: создайте набор тестов и измерьте качество извлечения и ответов с помощью практических метрик до выпуска приложения.
«Тестирование и оценка приложения RAG» — бесплатный урок LLM Apps in Production (RAG + Vector DB + Caching) на CoddyKit. Это урок 4 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения LLM Apps in Production (RAG + Vector DB + Caching), и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс LLM Apps in Production (RAG + Vector DB + Caching) содержит 4 уроков всего.
Части этого урока еще не переведены и отображаются на английском.
Why Evaluate RAG
A RAG app can look fine on a few queries and fail badly on others. Without measurement you cannot tell if a change helped or hurt.
Evaluation gives you a repeatable score to guide improvements.
Two Things to Measure
RAG quality has two parts:
- Retrieval: did we fetch the right documents?
- Generation: did the answer use them correctly?
A bad answer can come from either, so measure both.
Building a Test Set
Create a small set of questions with known correct answers and the documents that contain them. Even 20 to 50 examples are enough to start.
testset = [
{'q': 'What is the refund window?',
'answer': '30 days',
'source': 'policy.md'}
]Retrieval Metric: Hit Rate
Hit rate (or recall@k) checks whether the correct source appears in the top-k retrieved chunks. High hit rate means retrieval is doing its job.
def hit(retrieved, expected_source):
return any(d.metadata['source'] == expected_source
for d in retrieved)Faithfulness
Faithfulness asks: is the answer supported by the retrieved context, or did the model make things up? An LLM judge can score this automatically.
Answer Relevance
Answer relevance measures whether the response actually addresses the question, regardless of sources. A faithful answer can still be off-topic.
LLM as a Judge
You can use a strong model to grade outputs against the expected answer, returning a pass or score with a reason.
judge_prompt = (
'Question: {q}\nExpected: {gold}\n'
'Got: {pred}\nIs it correct? Answer yes or no.'
)Running the Evaluation
Loop over the test set, run your pipeline, and aggregate scores into a single report you can compare across versions.
scores = []
for case in testset:
pred = rag.invoke(case['q'])
scores.append(grade(case, pred))
print(sum(scores) / len(scores))Comparing Configurations
Change one variable — chunk size, k, prompt, model — rerun the same test set, and compare scores. This turns guesswork into evidence-based tuning.
Watching for Regressions
Keep the test suite in CI. When a change drops a metric, you catch the regression before users do. Treat evaluation like unit tests for AI quality.
Improving From Results
Use failures to guide fixes:
- Low hit rate? Adjust chunking or retrieval
- Low faithfulness? Strengthen grounding instructions
- Low relevance? Improve the prompt
Quick Check
Test your evaluation knowledge.
Recap
You learned to evaluate your RAG app:
- Measure both retrieval and generation
- Build a small test set with known answers
- Use hit rate, faithfulness, and answer relevance
- Let an LLM judge grade outputs
- Compare configs and guard against regressions in CI
Evaluation turns RAG improvement into a measurable, repeatable process.
Часто задаваемые вопросы
Урок «Тестирование и оценка приложения RAG» бесплатный?
Да — полный текст урока «Тестирование и оценка приложения RAG» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс LLM Apps in Production (RAG + Vector DB + Caching), подпишись на CoddyKit PRO. Курс LLM Apps in Production (RAG + Vector DB + Caching) содержит 4 уроков всего.
Чему я научусь в уроке «Тестирование и оценка приложения RAG»?
Повышайте уверенность в своём первом приложении RAG: создайте набор тестов и измерьте качество извлечения и ответов с помощью практических метрик до выпуска приложения. Ты практикуешь LLM Apps in Production (RAG + Vector DB + Caching) с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать LLM Apps in Production (RAG + Vector DB + Caching)?
Предыдущий опыт не требуется. LLM Apps in Production (RAG + Vector DB + Caching) на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 4 из 4.
Сколько времени занимает урок «Тестирование и оценка приложения RAG»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке LLM Apps in Production (RAG + Vector DB + Caching)?
Да. Каждый урок LLM Apps in Production (RAG + Vector DB + Caching) включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.
Все уроки этого курса
- Выбор поставщика LLM
- Основы загрузки данных и разбиения текста
- Создание простого конвейера RAG
- Тестирование и оценка приложения RAG