Skip to content

feat(docs): Improve knowledgebase adherence#1059

Merged
AkhileshNegi merged 2 commits into
feat/three-metric-evalsfrom
enhancement/adherence-to-knowledgebase
Jul 21, 2026
Merged

feat(docs): Improve knowledgebase adherence#1059
AkhileshNegi merged 2 commits into
feat/three-metric-evalsfrom
enhancement/adherence-to-knowledgebase

Conversation

@AkhileshNegi

@AkhileshNegi AkhileshNegi commented Jul 21, 2026

Copy link
Copy Markdown
Collaborator

Issue

Closes #1045

Summary

A new LLM-judged evaluation metric — "Adherence to Knowledge Base" — that measures whether an AI answer is actually grounded in the knowledge-base chunks that were retrieved to produce it. In short: hallucination detection.

Checklist

Before submitting a pull request, please ensure that you mark these task.

  • Ran fastapi run --reload app/main.py or docker compose up in the repository root and test.
  • If you've fixed a bug or added code that is tested and has test cases.

Summary by CodeRabbit

  • New Features

    • Added Knowledge Base groundedness scoring to evaluations.
    • Evaluations now capture retrieved file-search passages, scores, and filenames.
    • Knowledge Base results include top matching sources in reasoning comments.
    • Rows without retrieved content display an “N/A” result and are excluded from averages.
    • File-search retrieval is automatically enabled when configured.
  • Documentation

    • Updated evaluation documentation with Knowledge Base scoring behavior and applicability details.

@AkhileshNegi AkhileshNegi self-assigned this Jul 21, 2026
@github-actions github-actions Bot changed the title Enhancement/adherence to knowledgebase feat(docs): Improve knowledgebase alignment Jul 21, 2026
@coderabbitai

coderabbitai Bot commented Jul 21, 2026

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

This PR adds a knowledge-base groundedness metric to v2 evaluations. File-search results, including filenames, flow into per-row judging and trace comments. Metric applicability, N/A handling, top-match formatting, persistence, tests, and evaluation documentation are updated.

Changes

Knowledge-base groundedness evaluation

Layer / File(s) Summary
Knowledge-base judge contract
backend/app/crud/evaluations/judge.py, backend/app/crud/evaluations/score.py
Registers the groundedness metric and retrieved-chunk input, composes prompts per applicable metric, and updates judge_row to accept structured inputs.
Retrieved chunk capture
backend/app/models/response.py, backend/app/services/response/response.py, backend/app/crud/evaluations/fast.py
Preserves file-search filenames and requests, serializes, and stores retrieved chunks from Responses results.
Fast judge and trace integration
backend/app/crud/evaluations/fast.py
Passes chunks to judging, handles optional per-item persistence, formats top matches, and emits knowledge-base scores or N/A trace entries.
Behavior validation and documentation
backend/app/tests/crud/evaluations/*, backend/app/tests/services/response/response/test_generate_response.py, docs/wiki/modules/evaluations.md
Tests retrieval capture, applicability, scoring, formatting, and request wiring while documenting the updated v2 evaluation behavior.

Estimated code review effort: 4 (Complex) | ~60 minutes

Sequence Diagram(s)

sequenceDiagram
  participant ResponsesAPI
  participant FastEvaluation
  participant JudgeRow
  participant TraceStorage
  ResponsesAPI->>FastEvaluation: return file_search_call.results
  FastEvaluation->>JudgeRow: pass generated_answer and retrieved_chunks
  JudgeRow->>FastEvaluation: return applicable metric scores and reasoning
  FastEvaluation->>TraceStorage: persist scores and formatted top matches
Loading

Possibly related PRs

Suggested labels: enhancement

Suggested reviewers: ayush8923

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 22.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed The PR adds a knowledge-base groundedness metric, uses retrieved chunks in judging, and aligns with the goals in #1045.
Out of Scope Changes check ✅ Passed The changes stay focused on the new knowledge-base metric, related plumbing, tests, and docs, with no clear unrelated additions.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title matches the main change: adding a new knowledge-base adherence metric, though the docs prefix understates the code-heavy scope.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch enhancement/adherence-to-knowledgebase

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@AkhileshNegi AkhileshNegi changed the title feat(docs): Improve knowledgebase alignment feat(docs): Improve knowledgebase adherence Jul 21, 2026
@AkhileshNegi
AkhileshNegi marked this pull request as ready for review July 21, 2026 16:54
@AkhileshNegi
AkhileshNegi merged commit 902575b into feat/three-metric-evals Jul 21, 2026
1 of 2 checks passed
@AkhileshNegi
AkhileshNegi deleted the enhancement/adherence-to-knowledgebase branch July 21, 2026 16:59

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
backend/app/crud/evaluations/fast.py (1)

1058-1071: 🎯 Functional Correctness | 🟠 Major | 🏗️ Heavy lift

Don't block KB judging on missing ground_truth (backend/app/crud/evaluations/fast.py:944-1071).
judgeable filters out rows that lack ground_truth, and the earlier UNSCOREABLE_EMPTY_GROUND_TRUTH branch marks them unscoreable before _judge_rows runs. That prevents knowledge_base from scoring rows that have a generated answer and retrieved chunks, even though its required_inputs don’t include ground_truth. Let per-metric applicability inside judge_row decide; only the ground-truth metric should require the reference answer.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@backend/app/crud/evaluations/fast.py` around lines 1058 - 1071, The
evaluation flow currently excludes judgeable rows without ground_truth before
_judge_rows runs. Update the filtering and earlier
UNSCOREABLE_EMPTY_GROUND_TRUTH handling in the surrounding evaluation logic so
rows with generated_output and retrieved knowledge-base chunks proceed to
_judge_rows; leave applicability decisions to judge_row, where only
ground-truth-dependent metrics require the reference answer.
🧹 Nitpick comments (3)
backend/app/tests/crud/evaluations/test_fast_judge.py (2)

817-819: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Remove the duplicated assertion.

Line 819 repeats the assert "include" not in base_params check from Line 817. Harmless, but it reads like a copy-paste leftover.

♻️ Drop the redundant line
         assert "include" not in base_params
         assert "tool_choice" not in base_params
-        assert "include" not in base_params
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@backend/app/tests/crud/evaluations/test_fast_judge.py` around lines 817 -
819, Remove the duplicated `assert "include" not in base_params` assertion in
the test’s base-parameter assertions, keeping the single existing check and the
`tool_choice` assertion unchanged.

482-488: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add missing return type annotations.

_openai_response has no return annotation, and the test methods in TestResponsesChunkCapture, TestKnowledgeBaseScoring, and TestFileSearchIncludeParam lack -> None (unlike TestFormatTopKbMatches in the same file). As per coding guidelines: "Use type hints on every function parameter and return value."

♻️ Annotate the helper return type
-def _openai_response():
+def _openai_response() -> SimpleNamespace:
     return SimpleNamespace(
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@backend/app/tests/crud/evaluations/test_fast_judge.py` around lines 482 -
488, Add return type annotations to the _openai_response helper and every
unannotated test method in TestResponsesChunkCapture, TestKnowledgeBaseScoring,
and TestFileSearchIncludeParam, using -> None for test methods and the
appropriate response type for _openai_response.

Source: Coding guidelines

backend/app/crud/evaluations/fast.py (1)

1160-1171: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Extract the KB "N/A" reason strings into named constants.

"Knowledge base not queried." and "Knowledge base score unavailable for this row." are inline literals, while this same file already extracts sibling reason strings (UNSCOREABLE_EMPTY_OUTPUT, UNSCOREABLE_EMPTY_GROUND_TRUTH, JUDGE_FAILED_REASON) into named constants. As per coding guidelines: "Do not use magic values in code; extract repeated literals into constants, Enum members, or settings."

♻️ Proposed fix
+KB_NOT_QUERIED_REASON = "Knowledge base not queried."
+KB_SCORE_UNAVAILABLE_REASON = "Knowledge base score unavailable for this row."
+
 ...
                     if not sorted_chunks:
-                        reason = "Knowledge base not queried."
+                        reason = KB_NOT_QUERIED_REASON
                     else:
-                        reason = "Knowledge base score unavailable for this row."
+                        reason = KB_SCORE_UNAVAILABLE_REASON
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@backend/app/crud/evaluations/fast.py` around lines 1160 - 1171, Extract the
two KB reason strings used in the is_kb branch into named module-level
constants, following the existing UNSCOREABLE_EMPTY_OUTPUT,
UNSCOREABLE_EMPTY_GROUND_TRUTH, and JUDGE_FAILED_REASON pattern. Update the
empty sorted_chunks and missing-score branches to reference those constants
without changing their behavior.

Source: Coding guidelines

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Outside diff comments:
In `@backend/app/crud/evaluations/fast.py`:
- Around line 1058-1071: The evaluation flow currently excludes judgeable rows
without ground_truth before _judge_rows runs. Update the filtering and earlier
UNSCOREABLE_EMPTY_GROUND_TRUTH handling in the surrounding evaluation logic so
rows with generated_output and retrieved knowledge-base chunks proceed to
_judge_rows; leave applicability decisions to judge_row, where only
ground-truth-dependent metrics require the reference answer.

---

Nitpick comments:
In `@backend/app/crud/evaluations/fast.py`:
- Around line 1160-1171: Extract the two KB reason strings used in the is_kb
branch into named module-level constants, following the existing
UNSCOREABLE_EMPTY_OUTPUT, UNSCOREABLE_EMPTY_GROUND_TRUTH, and
JUDGE_FAILED_REASON pattern. Update the empty sorted_chunks and missing-score
branches to reference those constants without changing their behavior.

In `@backend/app/tests/crud/evaluations/test_fast_judge.py`:
- Around line 817-819: Remove the duplicated `assert "include" not in
base_params` assertion in the test’s base-parameter assertions, keeping the
single existing check and the `tool_choice` assertion unchanged.
- Around line 482-488: Add return type annotations to the _openai_response
helper and every unannotated test method in TestResponsesChunkCapture,
TestKnowledgeBaseScoring, and TestFileSearchIncludeParam, using -> None for test
methods and the appropriate response type for _openai_response.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 5288d079-38ff-43c4-9549-dc26d56f6d65

📥 Commits

Reviewing files that changed from the base of the PR and between b6328ed and e440002.

📒 Files selected for processing (9)
  • backend/app/crud/evaluations/fast.py
  • backend/app/crud/evaluations/judge.py
  • backend/app/crud/evaluations/score.py
  • backend/app/models/response.py
  • backend/app/services/response/response.py
  • backend/app/tests/crud/evaluations/test_fast_judge.py
  • backend/app/tests/crud/evaluations/test_judge.py
  • backend/app/tests/services/response/response/test_generate_response.py
  • docs/wiki/modules/evaluations.md

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant