Skip to content

Conversation

@alekszievr
Copy link
Contributor

@alekszievr alekszievr commented Mar 7, 2025

Description

  • Compare retrieved context to golden context using deepeval's summarization metric
  • Display relevant fields to each metric on metrics dashboard

Example output:
image

DCO Affirmation

I affirm that all code in every commit of this pull request conforms to the terms of the Topoteretes Developer Certificate of Origin

Summary by CodeRabbit

  • New Features

    • Enhanced context handling in answer generation and corpus building to include extended details.
    • Introduced a new context coverage metric for deeper evaluation insights.
    • Upgraded the evaluation dashboard with dynamic presentation of metric details.
    • Added a new parameter to support loading golden context in corpus loading methods.
  • Bug Fixes

    • Improved clarity in how answers are structured and appended in the answer generation process.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Mar 7, 2025

Walkthrough

This pull request makes several updates across the evaluation framework. The answer generation now conditionally includes a golden_context key. Corpus loading and building methods in multiple modules have a new load_golden_context parameter, with corresponding logic adjustments. A new evaluation metric, context_coverage, is integrated into the evaluation process and dashboard, and its functionality is encapsulated in a new ContextCoverageMetric class. Additionally, tests have been updated to account for the new metric while maintaining existing behavior.

Changes

File(s) Change Summary
cognee/.../answer_generation_executor.py Refactored question_answering_non_parallel in AnswerGeneratorExecutor to build the answer dictionary first and conditionally add golden_context.
cognee/.../dummy_adapter.py, cognee/.../corpus_builder_executor.py, cognee/.../run_corpus_builder.py Added load_golden_context parameter (default False) to corpus loading/building methods; modified logic to conditionally include golden_context in question-answer pairs.
cognee/.../deep_eval_adapter.py, cognee/.../evaluation_executor.py Integrated new "context_coverage" metric; updated evaluate_answers to pass context from golden_context and appended the metric during evaluation.
cognee/.../context_coverage.py Introduced new ContextCoverageMetric class with synchronous (measure) and asynchronous (a_measure) evaluation methods, plus an is_successful check.
cognee/.../metrics_dashboard.py Added metrics_fields and default_metrics_fields variables; refactored HTML generation for dynamic metric details display.
cognee/.../deepeval_adapter_test.py Updated test patching to include a mocked entry for the context_coverage module using MagicMock().

Sequence Diagram(s)

sequenceDiagram
    participant RB as run_corpus_builder
    participant CBE as CorpusBuilderExecutor
    participant DA as DummyAdapter

    RB->>CBE: build_corpus(limit, chunk_size, chunker, load_golden_context)
    CBE->>DA: load_corpus(limit, seed, load_golden_context)
    DA-->>CBE: (corpus_list, qa_pair)
    CBE-->>RB: (corpus_list, qa_pair)
Loading
sequenceDiagram
    participant EE as EvaluationExecutor
    participant DEA as DeepEvalAdapter
    participant CCM as ContextCoverageMetric

    EE->>DEA: evaluate_answers(answers)
    DEA->>DEA: For each answer, extract golden_context if exists
    DEA->>LLM: Instantiate LLMTestCase(with context)
    DEA->>CCM: Invoke measure/a_measure(test_case)
    CCM-->>DEA: Return coverage score
    DEA-->>EE: Return evaluated results
Loading

Possibly related PRs

Suggested reviewers

  • hajdul88
  • lxobr
  • borisarzentar

Poem

I’m a rabbit in a maze of code,
Hopping through changes on a winding road.
With golden context tucked in tight,
And new metrics shining bright.
I nibble on bugs and dance with glee,
In a PR world where code runs free.
🥕 Happy hopping in our coding spree!

✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 48cba01 and 61a1167.

📒 Files selected for processing (1)
  • cognee/tests/unit/eval_framework/deepeval_adapter_test.py (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (30)
  • GitHub Check: run_dynamic_steps_example_test / test
  • GitHub Check: run_simple_example_test / test
  • GitHub Check: Test on macos-15
  • GitHub Check: run_multimedia_example_test / test
  • GitHub Check: run_notebook_test / test
  • GitHub Check: run_notebook_test / test
  • GitHub Check: Test on macos-15
  • GitHub Check: run_notebook_test / test
  • GitHub Check: run_networkx_metrics_test / test
  • GitHub Check: run_notebook_test / test
  • GitHub Check: Test on macos-15
  • GitHub Check: test
  • GitHub Check: Test on macos-13
  • GitHub Check: run_eval_framework_test / test
  • GitHub Check: test
  • GitHub Check: Test on macos-13
  • GitHub Check: Test on macos-13
  • GitHub Check: Test on ubuntu-22.04
  • GitHub Check: Test on ubuntu-22.04
  • GitHub Check: test
  • GitHub Check: test
  • GitHub Check: Test on ubuntu-22.04
  • GitHub Check: Test on ubuntu-22.04
  • GitHub Check: windows-latest
  • GitHub Check: test
  • GitHub Check: test
  • GitHub Check: test
  • GitHub Check: Build Cognee Backend Docker App Image
  • GitHub Check: run_simple_example_test
  • GitHub Check: docker-compose-test

@alekszievr alekszievr requested review from hajdul88 and lxobr March 7, 2025 13:15
@alekszievr alekszievr changed the title Feature: evaluate retrieved context against golden context [cog-1481] Feat: evaluate retrieved context against golden context [cog-1481] Mar 7, 2025
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (4)
cognee/eval_framework/evaluation/metrics/context_match.py (4)

9-50: Add docstrings to improve code documentation.

The class and its methods lack docstrings explaining their purpose, parameters, expected behavior, and return values. This makes it harder for other developers to understand and use this code correctly.

Consider adding docstrings to the class and methods:

class ContextMatchMetric(SummarizationMetric):
+    """
+    Metric to evaluate how well retrieved context matches the golden context.
+    
+    This metric extends SummarizationMetric from deepeval and compares the
+    retrieval context against the original context using coverage-based evaluation.
+    """
    def measure(
        self,
        test_case,
        _show_indicator: bool = True,
    ) -> float:
+        """
+        Measure how well the retrieved context matches the golden context.
+        
+        Args:
+            test_case: The test case containing context and retrieval_context
+            _show_indicator: Whether to show progress indicator
+            
+        Returns:
+            float: Score representing context match quality
+        """

1-6: Add a module docstring.

The file lacks a module-level docstring explaining its purpose and how it fits into the broader evaluation framework.

Consider adding a module docstring:

+"""
+Context matching metric for evaluating retrieval quality.
+
+This module provides a metric that compares retrieved contexts against golden contexts
+using summarization metrics from deepeval, helping evaluate retrieval performance.
+"""
from deepeval.metrics import SummarizationMetric

10-14: Add type hints for the test_case parameter.

The test_case parameter lacks a type hint, making it unclear what type of object it should be.

Consider adding appropriate type hints:

    def measure(
        self,
-        test_case,
+        test_case: LLMTestCase,
        _show_indicator: bool = True,
    ) -> float:

Similarly, update the parameter type in the a_measure method as well.


28-30: Consider adding logging for better observability.

When calculating scores and making pass/fail determinations, it would be helpful to have logging for debugging and monitoring purposes.

Consider adding logging:

+import logging
+
+logger = logging.getLogger(__name__)
+
 class ContextMatchMetric(SummarizationMetric):
     # ... existing code ...
     
                 self.coverage_verdicts = self._generate_coverage_verdicts(mapped_test_case)
                 self.score = self._calculate_score(ScoreType.COVERAGE)
+                logger.debug(f"Context match score: {self.score}, threshold: {self.threshold}")
                 self.success = self.score >= self.threshold
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 61a1167 and 9dfa123.

📒 Files selected for processing (1)
  • cognee/eval_framework/evaluation/metrics/context_match.py (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (29)
  • GitHub Check: run_notebook_test / test
  • GitHub Check: Test on macos-15
  • GitHub Check: run_networkx_metrics_test / test
  • GitHub Check: run_eval_framework_test / test
  • GitHub Check: Test on macos-15
  • GitHub Check: run_notebook_test / test
  • GitHub Check: run_simple_example_test / test
  • GitHub Check: Test on macos-13
  • GitHub Check: run_dynamic_steps_example_test / test
  • GitHub Check: Test on macos-15
  • GitHub Check: run_notebook_test / test
  • GitHub Check: run_multimedia_example_test / test
  • GitHub Check: Test on macos-13
  • GitHub Check: Test on ubuntu-22.04
  • GitHub Check: test
  • GitHub Check: test
  • GitHub Check: Test on ubuntu-22.04
  • GitHub Check: Test on ubuntu-22.04
  • GitHub Check: run_notebook_test / test
  • GitHub Check: test
  • GitHub Check: test
  • GitHub Check: test
  • GitHub Check: Test on ubuntu-22.04
  • GitHub Check: windows-latest
  • GitHub Check: test
  • GitHub Check: test
  • GitHub Check: docker-compose-test
  • GitHub Check: run_simple_example_test
  • GitHub Check: Build Cognee Backend Docker App Image
🔇 Additional comments (1)
cognee/eval_framework/evaluation/metrics/context_match.py (1)

16-17: Clarify the mapping of test case fields.

The code maps test_case.context[0] to input and test_case.retrieval_context[0] to actual_output, but it's not immediately clear why these specific mappings were chosen. This could confuse future developers.

Consider adding a comment to explain the mapping logic:

        mapped_test_case = LLMTestCase(
+            # Map golden context to input and retrieved context to actual_output
+            # for comparison via SummarizationMetric
            input=test_case.context[0],
            actual_output=test_case.retrieval_context[0],
        )

@gitguardian
Copy link

gitguardian bot commented Mar 10, 2025

⚠️ GitGuardian has uncovered 1 secret following the scan of your pull request.

Please consider investigating the findings and remediating the incidents. Failure to do so may lead to compromising the associated services or software components.

🔎 Detected hardcoded secret in your pull request
GitGuardian id GitGuardian status Secret Commit Filename
9573981 Triggered Generic Password bc18b4d helm/values.yaml View secret
🛠 Guidelines to remediate hardcoded secrets
  1. Understand the implications of revoking this secret by investigating where it is used in your code.
  2. Replace and store your secret safely. Learn here the best practices.
  3. Revoke and rotate this secret.
  4. If possible, rewrite git history. Rewriting git history is not a trivial act. You might completely break other contributing developers' workflow and you risk accidentally deleting legitimate data.

To avoid such incidents in the future consider


🦉 GitGuardian detects secrets in your source code to help developers and security teams secure the modern development process. You are seeing this because you or someone else with access to this repository has authorized GitGuardian to scan your pull request.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 3

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 9dfa123 and ec7a0cc.

📒 Files selected for processing (5)
  • cognee/eval_framework/evaluation/deep_eval_adapter.py (3 hunks)
  • cognee/eval_framework/evaluation/evaluation_executor.py (1 hunks)
  • cognee/eval_framework/evaluation/metrics/context_coverage.py (1 hunks)
  • cognee/eval_framework/metrics_dashboard.py (2 hunks)
  • cognee/tests/unit/eval_framework/deepeval_adapter_test.py (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • cognee/eval_framework/metrics_dashboard.py
  • cognee/eval_framework/evaluation/evaluation_executor.py
  • cognee/tests/unit/eval_framework/deepeval_adapter_test.py
⏰ Context from checks skipped due to timeout of 90000ms (22)
  • GitHub Check: run_dynamic_steps_example_test / test
  • GitHub Check: run_eval_framework_test / test
  • GitHub Check: run_notebook_test / test
  • GitHub Check: Test on macos-15
  • GitHub Check: run_notebook_test / test
  • GitHub Check: run_notebook_test / test
  • GitHub Check: run_notebook_test / test
  • GitHub Check: test
  • GitHub Check: Test on macos-15
  • GitHub Check: Test on macos-13
  • GitHub Check: Test on macos-15
  • GitHub Check: Test on ubuntu-22.04
  • GitHub Check: windows-latest
  • GitHub Check: test
  • GitHub Check: Test on ubuntu-22.04
  • GitHub Check: Test on macos-13
  • GitHub Check: Test on macos-13
  • GitHub Check: Test on ubuntu-22.04
  • GitHub Check: test
  • GitHub Check: Test on ubuntu-22.04
  • GitHub Check: run_simple_example_test
  • GitHub Check: docker-compose-test
🔇 Additional comments (4)
cognee/eval_framework/evaluation/deep_eval_adapter.py (2)

7-7: Nice addition of the ContextCoverageMetric import.

No immediate issues found with this import. The path appears correct and consistent with the newly introduced metric file.


19-19: Metric integration looks good.

Including "context_coverage": ContextCoverageMetric() in the g_eval_metrics dictionary follows the established pattern for other metrics (e.g., "correctness", "EM", etc.). This should integrate cleanly into the existing evaluation framework.

cognee/eval_framework/evaluation/metrics/context_coverage.py (2)

1-9: All imports appear valid.

No immediate issues or conflicts detected in these import statements. This setup for the metric definitions aligns well with the deepeval architecture.


55-56: Straightforward success check.

Returning self.success here is clear and consistent, assuming it’s always set by either measure or a_measure. No issues found.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (2)
cognee/eval_framework/evaluation/metrics/context_coverage.py (2)

9-13: Consider adding docstrings or type hints.

Adding docstrings and type hints for measure (and other methods below) can enhance clarity and maintainability by documenting the expected types and behavior.


27-32: Reduce duplicate logic in measure and a_measure.

The code for generating coverage verdicts, alignment verdicts, calculating the score, and deriving the success status is duplicated in both methods. Consider refactoring these steps into a shared helper function to streamline maintenance and ensure consistency.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between ec7a0cc and 576aca1.

📒 Files selected for processing (1)
  • cognee/eval_framework/evaluation/metrics/context_coverage.py (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (30)
  • GitHub Check: Test on macos-15
  • GitHub Check: run_networkx_metrics_test / test
  • GitHub Check: run_notebook_test / test
  • GitHub Check: run_multimedia_example_test / test
  • GitHub Check: Test on macos-13
  • GitHub Check: run_eval_framework_test / test
  • GitHub Check: run_dynamic_steps_example_test / test
  • GitHub Check: run_simple_example_test / test
  • GitHub Check: Test on macos-15
  • GitHub Check: run_notebook_test / test
  • GitHub Check: run_notebook_test / test
  • GitHub Check: Test on macos-15
  • GitHub Check: test
  • GitHub Check: windows-latest
  • GitHub Check: Test on ubuntu-22.04
  • GitHub Check: test
  • GitHub Check: test
  • GitHub Check: Test on macos-13
  • GitHub Check: Test on macos-13
  • GitHub Check: test
  • GitHub Check: Test on ubuntu-22.04
  • GitHub Check: test
  • GitHub Check: Test on ubuntu-22.04
  • GitHub Check: test
  • GitHub Check: run_notebook_test / test
  • GitHub Check: Test on ubuntu-22.04
  • GitHub Check: run_simple_example_test
  • GitHub Check: test
  • GitHub Check: Build Cognee Backend Docker App Image
  • GitHub Check: docker-compose-test
🔇 Additional comments (2)
cognee/eval_framework/evaluation/metrics/context_coverage.py (2)

15-16: Potential IndexError for empty contexts.

This issue was previously noted in a past review. If test_case.context or test_case.retrieval_context is None or empty, indexing [0] can raise an error. Consider validating inputs or returning early to avoid runtime exceptions.


34-50: Overall implementation aligns with PR objectives.

Your asynchronous method correctly captures the same logic flow for coverage verdict generation. Aside from the duplication concern noted above, everything looks good, and the solution meets the intent of comparing retrieved context.

@lxobr
Copy link
Collaborator

lxobr commented Mar 10, 2025

Nice work! Tested it and I the outputs seem meaningful and useful.
I have a basic understanding of the contextual_coverage and it seems to be the appropriate tool for the job, but nevertheless it would be great to open a separate issue and document what it is and how we are using it exactly.

@alekszievr alekszievr merged commit 7b5bd78 into dev Mar 10, 2025
36 of 38 checks passed
@alekszievr alekszievr deleted the feat/cog-1481-context-vs-golden-context branch March 10, 2025 14:27
@coderabbitai coderabbitai bot mentioned this pull request Mar 11, 2025
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.

4 participants