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

Using latest PMAT with db_cache #536

Merged
merged 7 commits into from
Nov 6, 2024
Merged

Using latest PMAT with db_cache #536

merged 7 commits into from
Nov 6, 2024

Conversation

kongzii
Copy link
Contributor

@kongzii kongzii commented Oct 30, 2024

No description provided.

Copy link
Contributor

coderabbitai bot commented Oct 30, 2024

Walkthrough

This pull request introduces several modifications across multiple files, primarily focusing on the removal of the tavily_storage parameter from various function calls and class methods. This change affects the PredictProbabilityForQuestion class, several subclasses of DeployableTraderAgentER, and methods within the ThinkThoroughlyWithPredictionProphetResearch class. Additionally, updates to the prophet_research function and changes in caching strategies within the markdown.py file are included. Overall, the changes streamline the codebase by simplifying interfaces and enhancing clarity.

Changes

File Change Summary
prediction_market_agent/agents/microchain_agent/market_functions.py Removed tavily_storage parameter from prophet_research call in PredictProbabilityForQuestion class.
prediction_market_agent/agents/prophet_agent/deploy.py Removed tavily_storage parameter from PredictionProphetAgent and OlasAgent instantiations in multiple subclasses. Updated bet_on_n_markets_per_run values for various subclasses.
prediction_market_agent/agents/think_thoroughly_agent/think_thoroughly_agent.py Removed tavily_storage parameter from generate_prediction_for_one_outcome and generate_final_decision methods in ThinkThoroughlyWithPredictionProphetResearch class.
prediction_market_agent/tools/prediction_prophet/research.py Removed tavily_storage parameter from prophet_research function signature and its invocation.
prediction_market_agent/tools/web_scrape/markdown.py Replaced @persistent_inmemory_cache with @db_cache(max_age=timedelta(days=1)) in web_scrape function.
scripts/benchmark_ofv_resolver.py Updated import path for persistent_inmemory_cache and applied it to ofv_answer_binary_question_cached function.
scripts/llm_randomness.py Updated import path for persistent_inmemory_cache.

Possibly related PRs

  • Tavily storage #381: The changes in this PR involve the removal of the tavily_storage parameter from the market_functions.py file, which is directly related to the changes in the main PR that also removed this parameter from the PredictProbabilityForQuestion class.
  • Migrate prophet #366: This PR modifies the DeployableTraderAgentER class by removing the tavily_storage parameter from the instantiation of various agents, which aligns with the main PR's focus on simplifying the function interface by removing the same parameter.
  • Set minimum scraping requirement for prediction prophet research #383: Similar to the main PR, this PR also removes the use_summaries parameter from the prophet_research function call in market_functions.py, indicating a consistent approach to refining function parameters across different components.
  • Evan/prophet research comment #513: This PR updates the min_scraped_sites parameter in the prophet_research function, which is relevant as it reflects ongoing adjustments to the research parameters that may impact the prediction logic discussed in the main PR.
  • Cheaper think thoroughly prophet agent #539: This PR discusses modifications to the ThinkThoroughly agent, particularly in how it utilizes models for predictions, which may relate to the overall changes in prediction logic and parameters in the main PR.

Suggested reviewers

  • evangriffiths

📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 02b2d73 and 9b5a79d.

⛔ Files ignored due to path filters (2)
  • poetry.lock is excluded by !**/*.lock, !**/*.lock
  • pyproject.toml is excluded by !**/*.toml
📒 Files selected for processing (1)
  • prediction_market_agent/agents/prophet_agent/deploy.py (0 hunks)
💤 Files with no reviewable changes (1)
  • prediction_market_agent/agents/prophet_agent/deploy.py

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 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.

@kongzii kongzii force-pushed the peter/latest-pmat-cache branch from c445cac to 5742f8f Compare October 31, 2024 14:45
@kongzii kongzii force-pushed the peter/latest-pmat-cache branch from 5742f8f to c04227b Compare October 31, 2024 14:51
@kongzii kongzii marked this pull request as ready for review October 31, 2024 14:51
@kongzii kongzii changed the title Using latest PMAT, cleanup Using latest PMAT with db_cache Oct 31, 2024
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

🧹 Outside diff range and nitpick comments (6)
prediction_market_agent/tools/web_scrape/markdown.py (2)

Line range hint 13-21: LGTM: Clean separation of concerns

Good architectural decision to move caching to the higher-level web_scrape function while maintaining retry logic here. This separation allows for more flexible caching strategies while ensuring robust HTTP requests.


Line range hint 36-44: Consider optimizing DOM manipulations

The current implementation uses multiple separate list comprehensions for element removal. This could be optimized by:

  1. Combining selectors into a single query
  2. Using a more efficient selector method
-[x.extract() for x in soup.findAll("script")]
-[x.extract() for x in soup.findAll("style")]
-[x.extract() for x in soup.findAll("noscript")]
-[x.extract() for x in soup.findAll("link")]
-[x.extract() for x in soup.findAll("head")]
-[x.extract() for x in soup.findAll("image")]
-[x.extract() for x in soup.findAll("img")]
+for element in soup.find_all(['script', 'style', 'noscript', 'link', 'head', 'image', 'img']):
+    element.extract()
scripts/benchmark_ofv_resolver.py (3)

Line range hint 15-18: Add docstring to explain caching behavior.

The cached wrapper function would benefit from documentation explaining:

  • The caching strategy
  • Cache invalidation behavior
  • When None results are cached

Add a docstring like this:

 @persistent_inmemory_cache
 def ofv_answer_binary_question_cached(question: str) -> bool | None:
+    """Cached wrapper for ofv_answer_binary_question.
+    
+    Results are persistently cached in memory based on the question string.
+    None results are also cached to avoid repeated API calls for invalid questions.
+    
+    Args:
+        question: The question to be answered
+    
+    Returns:
+        bool: True for YES, False for NO
+        None: When resolution is not possible
+    """
     result = ofv_answer_binary_question(question, APIKeys())
     return result.factuality if result is not None else None

Line range hint 15-18: Optimize APIKeys instantiation.

Currently, APIKeys() is instantiated for each question, even though the result is cached. Consider moving the instantiation outside the function to improve performance.

+_API_KEYS = APIKeys()
+
 @persistent_inmemory_cache
 def ofv_answer_binary_question_cached(question: str) -> bool | None:
-    result = ofv_answer_binary_question(question, APIKeys())
+    result = ofv_answer_binary_question(question, _API_KEYS)
     return result.factuality if result is not None else None

Line range hint 33-34: Add error handling for file operations.

The script should gracefully handle file-related errors when reading the input TSV and writing the output files.

-    df = pd.read_csv(data_path, sep="\t")
+    try:
+        df = pd.read_csv(data_path, sep="\t")
+    except FileNotFoundError:
+        print(f"Error: Input file '{data_path}' not found")
+        raise typer.Exit(1)
+    except pd.errors.EmptyDataError:
+        print(f"Error: Input file '{data_path}' is empty")
+        raise typer.Exit(1)
+    except Exception as e:
+        print(f"Error reading input file: {e}")
+        raise typer.Exit(1)
scripts/llm_randomness.py (1)

Line range hint 33-35: Consider making the number parsing more robust.

The current implementation assumes the LLM will always return properly formatted comma-separated numbers. Consider adding error handling for malformed responses.

Here's a more robust implementation:

-    completion = [
-        int(x) for x in str(llm.invoke(messages, max_tokens=512).content).split(",")
-    ]
+    def parse_numbers(content: str) -> list[int]:
+        try:
+            # Strip whitespace and filter out empty strings
+            numbers = [x.strip() for x in content.split(",") if x.strip()]
+            return [int(x) for x in numbers]
+        except ValueError as e:
+            raise ValueError(f"Failed to parse LLM response: {content}") from e
+
+    content = str(llm.invoke(messages, max_tokens=512).content)
+    completion = parse_numbers(content)
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 4b3d1c0 and c04227b.

⛔ Files ignored due to path filters (2)
  • poetry.lock is excluded by !**/*.lock, !**/*.lock
  • pyproject.toml is excluded by !**/*.toml
📒 Files selected for processing (7)
  • prediction_market_agent/agents/microchain_agent/market_functions.py (0 hunks)
  • prediction_market_agent/agents/prophet_agent/deploy.py (0 hunks)
  • prediction_market_agent/agents/think_thoroughly_agent/think_thoroughly_agent.py (0 hunks)
  • prediction_market_agent/tools/prediction_prophet/research.py (0 hunks)
  • prediction_market_agent/tools/web_scrape/markdown.py (2 hunks)
  • scripts/benchmark_ofv_resolver.py (1 hunks)
  • scripts/llm_randomness.py (1 hunks)
💤 Files with no reviewable changes (4)
  • prediction_market_agent/agents/microchain_agent/market_functions.py
  • prediction_market_agent/agents/prophet_agent/deploy.py
  • prediction_market_agent/agents/think_thoroughly_agent/think_thoroughly_agent.py
  • prediction_market_agent/tools/prediction_prophet/research.py
🔇 Additional comments (4)
prediction_market_agent/tools/web_scrape/markdown.py (2)

1-1: LGTM: Import changes align with new caching strategy

The new imports support the transition from in-memory caching to database-backed caching with TTL support.

Also applies to: 8-8


25-26: 🛠️ Refactor suggestion

Consider enhancing cache error handling and performance

While the switch to DB-based caching with TTL is good, consider these improvements:

  1. Add error handling for cache operations
  2. Consider implementing cache warmup for frequently accessed URLs
  3. Add compression for cached content to reduce DB storage

Let's verify the cache implementation:

scripts/benchmark_ofv_resolver.py (1)

3-5: Verify consistent usage of the new import path across the codebase.

The import path has been updated to be more specific. Let's ensure this change is consistent across all files.

scripts/llm_randomness.py (1)

7-9: LGTM! Import path update looks good.

The import path change reflects a better module organization by moving cache-related functionality to a dedicated caches module.

@kongzii kongzii merged commit 612db6b into main Nov 6, 2024
9 checks passed
@kongzii kongzii deleted the peter/latest-pmat-cache branch November 6, 2024 11:41
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