Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat: Save and load contexts and answers for eval #462

Merged
merged 8 commits into from
Jan 22, 2025

Conversation

alekszievr
Copy link
Contributor

@alekszievr alekszievr commented Jan 20, 2025

Description

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

Release Notes

  • New Features

    • Enhanced evaluation process with context and answer caching.
    • Added support for preloading contexts and answers from JSON files.
    • Expanded evaluation metrics for more comprehensive assessment, including Directness, Diversity, and Empowerment.
  • Improvements

    • Introduced random sampling for dataset instances.
    • Optimized context retrieval and storage mechanism.
    • Updated default search types to include insights.
  • Changes

    • Updated function signatures in evaluation scripts.
    • Modified parameter handling in evaluation functions.

Copy link
Contributor

coderabbitai bot commented Jan 20, 2025

Warning

Rate limit exceeded

@alekszievr has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 22 minutes and 57 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 5b6fe00 and b2f7f73.

📒 Files selected for processing (1)
  • evals/eval_on_hotpot.py (4 hunks)

Walkthrough

This pull request enhances the evaluation process for QA datasets by introducing context and answer caching mechanisms. The modifications primarily affect eval_on_hotpot.py and promptfoo_metrics.py, allowing preloading of contexts and answers from JSON files. The changes enable more efficient evaluation by storing and reusing previously retrieved contexts and answers. The qa_eval_parameters.json file has been updated to include additional evaluation metrics, expanding the assessment criteria for the dataset.

Changes

File Change Summary
evals/eval_on_hotpot.py - Updated method signatures for answer_qa_instance, deepeval_on_instances, eval_on_QA_dataset, and incremental_eval_on_QA_dataset
- Added support for preloading and caching contexts and answers from JSON files
- Modified instance sampling to use random.sample
evals/promptfoo_metrics.py - Updated measure method signature in PromptfooMetric class
- Added context caching mechanism
- Added exception handling for invalid metric names
evals/qa_eval_parameters.json - Expanded metric_names to include: "Directness", "Diversity", "Empowerment", and "promptfoo.directness"
evals/run_qa_eval.py - Added out_path parameter to incremental_eval_on_QA_dataset and eval_on_QA_dataset function calls
evals/qa_context_provider_utils.py - Refined logic in _insight_to_string function for description assignment

Possibly related PRs

Suggested labels

run-checks

Suggested reviewers

  • lxobr

Poem

🐰 Hop, hop, through the data's maze,
Caching contexts with rabbity ways,
Metrics dancing, JSON in sight,
Evaluation's now swift and bright!
CodeRabbit's magic, eval's delight! 🌟


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 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. (Beta)
  • @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: 4

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between bbb8e89 and 1c16a17.

📒 Files selected for processing (4)
  • evals/eval_on_hotpot.py (4 hunks)
  • evals/promptfoo_metrics.py (3 hunks)
  • evals/qa_eval_parameters.json (1 hunks)
  • evals/run_qa_eval.py (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: docker-compose-test
🔇 Additional comments (3)
evals/run_qa_eval.py (1)

25-25: LGTM! The out_path parameter is correctly propagated.

The addition of the out_path parameter to both evaluation functions enables proper saving of contexts and answers, aligning with the PR's objective.

Also applies to: 30-30

evals/eval_on_hotpot.py (2)

13-19: LGTM! Good practice setting random seed for reproducibility.

The addition of necessary imports and setting a random seed ensures reproducible results across runs.


113-133: LGTM! Good improvements in sampling and file handling.

  • Using random.sample is better than slicing for getting a random subset
  • File paths are properly constructed using Path

evals/eval_on_hotpot.py Show resolved Hide resolved
evals/eval_on_hotpot.py Show resolved Hide resolved
evals/qa_eval_parameters.json Show resolved Hide resolved
evals/promptfoo_metrics.py Show resolved Hide resolved
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

♻️ Duplicate comments (2)
evals/eval_on_hotpot.py (2)

21-35: ⚠️ Potential issue

Fix race conditions and optimize file operations.

The implementation has two issues:

  1. File operations are not thread-safe, which could lead to race conditions.
  2. The file is written even when using preloaded context, which is inefficient.

Previous review already suggested using filelock. Additionally, optimize the file operations:

+from filelock import FileLock
+
 async def answer_qa_instance(instance, context_provider, contexts_filename):
+    lock = FileLock(f"{contexts_filename}.lock")
     preloaded_contexts = {}
+    with lock:
         if os.path.exists(contexts_filename):
             with open(contexts_filename, "r") as file:
                 preloaded_contexts = json.load(file)

     if instance["_id"] in preloaded_contexts:
         context = preloaded_contexts[instance["_id"]]
     else:
         context = await context_provider(instance)
         preloaded_contexts[instance["_id"]] = context
+        with lock:
             with open(contexts_filename, "w") as file:
                 json.dump(preloaded_contexts, file)
-    with open(contexts_filename, "w") as file:
-        json.dump(preloaded_contexts, file)

69-89: ⚠️ Potential issue

Fix race conditions in answer caching.

The implementation has similar thread-safety issues as answer_qa_instance.

Previous review already suggested using filelock. Apply similar optimizations:

+from filelock import FileLock
+
 async def deepeval_on_instances(
     instances, context_provider, eval_metrics, answers_filename, contexts_filename
 ):
+    lock = FileLock(f"{answers_filename}.lock")
     preloaded_answers = {}
+    with lock:
         if os.path.exists(answers_filename):
             with open(answers_filename, "r") as file:
                 preloaded_answers = json.load(file)

     answers = []
     for instance in tqdm(instances, desc="Getting answers"):
         if instance["_id"] in preloaded_answers:
             answer = preloaded_answers[instance["_id"]]
         else:
             answer = await answer_qa_instance(instance, context_provider, contexts_filename)
             preloaded_answers[instance["_id"]] = answer
+            with lock:
+                with open(answers_filename, "w") as file:
+                    json.dump(preloaded_answers, file)
         answers.append(answer)

-    with open(answers_filename, "w") as file:
-        json.dump(preloaded_answers, file)
🧹 Nitpick comments (1)
evals/qa_context_provider_utils.py (1)

42-48: Refactor description logic to improve readability and reduce duplication.

The nested conditional expressions make the code less readable and the logic is duplicated between node1 and node2 descriptions.

Consider extracting the logic into a helper function:

+def _get_node_description(node: dict) -> str:
+    return node.get("description") or node.get("text") or "N/A"
+
 def _insight_to_string(triplet: tuple) -> str:
     # ... previous code ...
-    node1_description = (
-        node1["description"]
-        if "description" in node1
-        else node1["text"]
-        if "text" in node1
-        else "N/A"
-    )
+    node1_description = _get_node_description(node1)
     node1_string = f"name: {node1_name}, description: {node1_description}"
     node2_name = node2["name"] if "name" in node2 else "N/A"
-    node2_description = (
-        node2["description"]
-        if "description" in node2
-        else node2["text"]
-        if "text" in node2
-        else "N/A"
-    )
+    node2_description = _get_node_description(node2)

Also applies to: 51-57

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 1c16a17 and 9fec8fd.

📒 Files selected for processing (2)
  • evals/eval_on_hotpot.py (4 hunks)
  • evals/qa_context_provider_utils.py (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (19)
  • GitHub Check: run_simple_example_test / test
  • GitHub Check: run_dynamic_steps_example_test / test
  • GitHub Check: run_multimedia_example_test / test
  • GitHub Check: run_notebook_test / test
  • GitHub Check: run_notebook_test / test
  • GitHub Check: run_notebook_test / test
  • GitHub Check: test
  • GitHub Check: test
  • GitHub Check: test
  • GitHub Check: run_notebook_test / test
  • GitHub Check: test
  • GitHub Check: test
  • GitHub Check: windows-latest
  • GitHub Check: test
  • GitHub Check: test
  • GitHub Check: test
  • GitHub Check: test
  • GitHub Check: profiler
  • GitHub Check: docker-compose-test
🔇 Additional comments (1)
evals/eval_on_hotpot.py (1)

142-142: LGTM!

The changes correctly propagate the out_path parameter to eval_on_QA_dataset.

Also applies to: 149-149

evals/eval_on_hotpot.py Show resolved Hide resolved
@alekszievr alekszievr self-assigned this Jan 22, 2025
@lxobr lxobr self-requested a review January 22, 2025 15:16
@alekszievr alekszievr merged commit 4e3a666 into dev Jan 22, 2025
27 checks passed
@alekszievr alekszievr deleted the feat/save_and_load_answers branch January 22, 2025 15:17
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants