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

Sending messages from general agent #581

Merged
merged 8 commits into from
Dec 6, 2024
Merged

Sending messages from general agent #581

merged 8 commits into from
Dec 6, 2024

Conversation

kongzii
Copy link
Contributor

@kongzii kongzii commented Dec 4, 2024

No description provided.

Copy link
Contributor

coderabbitai bot commented Dec 4, 2024

Important

Review skipped

Review was skipped due to path filters

⛔ Files ignored due to path filters (1)
  • poetry.lock is excluded by !**/*.lock, !**/*.lock

CodeRabbit blocks several paths by default. You can override this behavior by explicitly including those paths in the path filters. For example, including **/dist/** will override the default block on the dist directory, by removing the pattern from both the lists.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

The pull request introduces multiple changes across several files in the microchain_agent module. Key modifications include the addition of new classes for message handling, specifically BroadcastPublicMessageToHumans and SendPaidMessageToAnotherAgent, while removing the SendMessage class. A new MicrochainAgentKeys class is introduced to manage API keys and transaction limits. Additionally, updates are made to the SendTweet class for enhanced tweet handling, and new utility functions for message compression and decompression are added. Tests for the new compression functions are also included.

Changes

File Change Summary
prediction_market_agent/agents/microchain_agent/messages_functions.py - Added constant TRANSACTION_MESSAGE_FEE.
- Added classes BroadcastPublicMessageToHumans and SendPaidMessageToAnotherAgent.
- Removed class SendMessage.
- Updated method signatures for message handling classes.
prediction_market_agent/agents/microchain_agent/microchain_agent_keys.py - Added class MicrochainAgentKeys with attributes ENABLE_SOCIAL_MEDIA and SENDING_XDAI_CAP.
- Added method cap_sending_xdai.
prediction_market_agent/agents/microchain_agent/prompts.py - Updated from_system_prompt_choice method to remove setting include_sending_functions for a specific prompt.
prediction_market_agent/agents/microchain_agent/sending_functions.py - Updated SendXDAI class to use MicrochainAgentKeys instead of APIKeys.
prediction_market_agent/agents/microchain_agent/twitter_functions.py - Updated SendTweet class to include tweet length validation and conditional posting based on ENABLE_SOCIAL_MEDIA.
prediction_market_agent/agents/microchain_agent/utils.py - Added functions compress_message and decompress_message for handling message compression.
prediction_market_agent/agents/social_media_agent/social_media/twitter_handler.py - Updated TwitterHandler class to modify method signatures and add a new post_tweet method.
tests/agents/microchain/test_utils.py - Added test function test_message_compression for new compression functionalities.

Possibly related PRs

  • Various improvements and fixes for microchain agent #201: This PR involves changes to the microchain_agent module, including the removal of the SendMessage class, which is directly related to the changes in the main PR where SendMessage is replaced by new classes for sending messages.
  • Twitter posting fucntion for Microchain #567: This PR introduces a new class SendTweet in the twitter_functions.py file, which is relevant as it relates to the new messaging functionalities being developed in the main PR, particularly with the introduction of the SendXDAI class and the overall messaging framework.

Suggested reviewers

  • evangriffiths

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.

Base automatically changed from peter/daring-logic-prototype-twitter to main December 6, 2024 11:39
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

🧹 Outside diff range and nitpick comments (11)
prediction_market_agent/agents/microchain_agent/messages_functions.py (4)

27-27: Remove unnecessary f-string in return statement

The return statement does not contain any placeholders, so the f prefix is unnecessary.

Apply this diff to fix the issue:

-return f"Message broadcasted to humans."
+return "Message broadcasted to humans."
🧰 Tools
🪛 Ruff (0.8.0)

27-27: f-string without any placeholders

Remove extraneous f prefix

(F541)


26-26: Use logger instead of print statement

Using print statements is not recommended in production code. Consider using a logger to record messages, which allows better control over logging levels and output destinations.

Apply this diff to replace print with logger.info:

+from prediction_market_agent_tooling.loggers import logger

 def __call__(self, message: str) -> str:
     # TODO: Implement as needed in https://github.com/gnosis/prediction-market-agent/issues/570.
-    print(message)
+    logger.info(message)
     return "Message broadcasted to humans."

33-34: Use gender-neutral language and correct article in description

In the description property, consider correcting "send a message to an another agent, given his wallet address" to "send a message to another agent, given their wallet address" for grammatical correctness and inclusivity.

Apply this diff to fix the issue:

-return f"""Use {SendPaidMessageToAnotherAgent.__name__} to send a message to an another agent, given his wallet address. 
+return f"""Use {SendPaidMessageToAnotherAgent.__name__} to send a message to another agent, given their wallet address. 
 Fee for sending the message is {TRANSACTION_MESSAGE_FEE} xDai."""

54-56: Offer assistance to complete the implementation of ReceiveMessage

The ReceiveMessage class contains TODO comments indicating that the number of unseen messages should be added to the description, and the logic is incomplete in the __call__ method.

Would you like assistance in implementing the required functionality or opening a new GitHub issue to track this task?

tests/agents/microchain/test_utils.py (1)

7-10: Enhance test coverage for message compression

Currently, the test only verifies a simple message. Consider adding test cases for edge cases, such as:

  • Empty strings
  • Very long messages
  • Messages containing special characters or Unicode characters

This will ensure that the compression and decompression functions handle all scenarios correctly.

prediction_market_agent/agents/microchain_agent/microchain_agent_keys.py (2)

18-18: Fix typo in log message

There is a typo in the word "Caping"; it should be "Capping".

Apply this diff to fix the typo:

-logger.warning(f"Caping sending xDai value to {amount}.")
+logger.warning(f"Capping sending xDai value to {amount}.")

12-12: Consider using precise types for monetary values

The attribute SENDING_XDAI_CAP is defined as float | None. Using floats for currency amounts may lead to precision issues. Consider using a fixed-precision decimal type or the xDai type for accurate monetary calculations.

Apply this diff to update the type annotation:

-    SENDING_XDAI_CAP: float | None = OMEN_TINY_BET_AMOUNT
+    SENDING_XDAI_CAP: xDai | None = xDai(OMEN_TINY_BET_AMOUNT)
prediction_market_agent/agents/microchain_agent/sending_functions.py (1)

Line range hint 13-13: Fix class name reference in description

The description property uses SendXDAI.__class__, which returns <class 'type'> instead of the class name. To correctly reference the class name, use SendXDAI.__name__.

Apply this diff to fix the issue:

-return f"Use {SendXDAI.__class__} to send xDai (stable coin, where 1 xDai equal $1) to a specified blockchain address on Gnosis Chain."
+return f"Use {SendXDAI.__name__} to send xDai (stable coin, where 1 xDai equals $1) to a specified blockchain address on Gnosis Chain."
prediction_market_agent/agents/social_media_agent/social_media/twitter_handler.py (2)

60-65: Consider adding error handling for quote_tweet_id

The method correctly handles the optional reasoning_reply_tweet parameter, but there's no validation of the quote_tweet_id before using it in the nested call.

Consider adding validation:

 def post(self, text: str, reasoning_reply_tweet: str | None = None) -> None:
     quote_tweet_id = self.post_else_retry_with_summarization(text)
-    if reasoning_reply_tweet is not None:
+    if reasoning_reply_tweet is not None and quote_tweet_id is not None:
         self.post_else_retry_with_summarization(
             reasoning_reply_tweet, quote_tweet_id=quote_tweet_id
         )

Line range hint 85-96: Enhance error handling in post_tweet method

The method has good basic error handling but could be improved.

Consider these enhancements:

 def post_tweet(self, text: str, quote_tweet_id: str | None = None) -> str | None:
     """
     Posts the provided text on Twitter.
     """
+    if not text:
+        logger.warning("Attempted to post empty tweet")
+        return None
+
     posted_tweet = self.client.create_tweet(
         text=text, quote_tweet_id=quote_tweet_id
     )
     logger.info(f"Tweeted {text} - {posted_tweet}")
     try:
         return str(posted_tweet.data["id"])
-    except Exception as e:
-        logger.exception("Could not extract tweet ID. Exception: ", e)
+    except (KeyError, AttributeError) as e:
+        logger.exception(f"Could not extract tweet ID from response {posted_tweet}. Error: {e}")
         return None
prediction_market_agent/agents/microchain_agent/utils.py (1)

2-2: Consider documenting compression ratio expectations

While the compression is correctly implemented for gas optimization, it would be helpful to document expected compression ratios for typical messages to help with gas estimation.

Consider enhancing the docstring:

 def compress_message(message: str) -> bytes:
-    """Used to reduce size of the message before sending it to reduce gas costs."""
+    """Compresses a message to reduce gas costs for blockchain transmission.
+    
+    For typical English text messages, achieves ~60-70% size reduction using
+    BEST_COMPRESSION level. Empty or very short messages may result in larger output
+    due to compression overhead.
+    
+    Args:
+        message: The string message to compress
+    Returns:
+        Compressed message as bytes
+    """

Also applies to: 146-148

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 6f65c01 and d40864d.

⛔ Files ignored due to path filters (2)
  • poetry.lock is excluded by !**/*.lock, !**/*.lock
  • pyproject.toml is excluded by !**/*.toml
📒 Files selected for processing (8)
  • prediction_market_agent/agents/microchain_agent/messages_functions.py (2 hunks)
  • prediction_market_agent/agents/microchain_agent/microchain_agent_keys.py (1 hunks)
  • prediction_market_agent/agents/microchain_agent/prompts.py (0 hunks)
  • prediction_market_agent/agents/microchain_agent/sending_functions.py (2 hunks)
  • prediction_market_agent/agents/microchain_agent/twitter_functions.py (1 hunks)
  • prediction_market_agent/agents/microchain_agent/utils.py (2 hunks)
  • prediction_market_agent/agents/social_media_agent/social_media/twitter_handler.py (4 hunks)
  • tests/agents/microchain/test_utils.py (1 hunks)
💤 Files with no reviewable changes (1)
  • prediction_market_agent/agents/microchain_agent/prompts.py
🧰 Additional context used
🪛 Ruff (0.8.0)
prediction_market_agent/agents/microchain_agent/messages_functions.py

27-27: f-string without any placeholders

Remove extraneous f prefix

(F541)

🔇 Additional comments (2)
prediction_market_agent/agents/microchain_agent/twitter_functions.py (1)

22-31: LGTM

The updates to the SendTweet class enhance error handling for tweet length and conditionally post based on social media settings. The changes are correct and improve functionality.

prediction_market_agent/agents/social_media_agent/social_media/twitter_handler.py (1)

16-16: LGTM: Clean dependency update

The switch to SocialMediaAPIKeys and corresponding key usage is implemented correctly.

Also applies to: 39-39

Comment on lines +40 to +49
def __call__(self, address: str, message: str) -> str:
keys = MicrochainAgentKeys()
send_xdai_to(
web3=ContractOnGnosisChain.get_web3(),
from_private_key=keys.bet_from_private_key,
to_address=Web3.to_checksum_address(address),
value=xdai_to_wei(keys.cap_sending_xdai(TRANSACTION_MESSAGE_FEE)),
data_text=compress_message(message),
)
return "Message sent to the agent."
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add error handling for transaction failures

The __call__ method does not handle exceptions that may occur during the send_xdai_to function call. To enhance robustness, add error handling to manage potential errors such as transaction failures, invalid addresses, or insufficient funds.

Apply this diff to add error handling:

+from prediction_market_agent_tooling.loggers import logger

 def __call__(self, address: str, message: str) -> str:
     keys = MicrochainAgentKeys()
     try:
         send_xdai_to(
             web3=ContractOnGnosisChain.get_web3(),
             from_private_key=keys.bet_from_private_key,
             to_address=Web3.to_checksum_address(address),
             value=xdai_to_wei(keys.cap_sending_xdai(TRANSACTION_MESSAGE_FEE)),
             data_text=compress_message(message),
         )
         return "Message sent to the agent."
+    except Exception as e:
+        logger.error(f"Failed to send message: {e}")
+        return "Failed to send message due to an error."
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
def __call__(self, address: str, message: str) -> str:
keys = MicrochainAgentKeys()
send_xdai_to(
web3=ContractOnGnosisChain.get_web3(),
from_private_key=keys.bet_from_private_key,
to_address=Web3.to_checksum_address(address),
value=xdai_to_wei(keys.cap_sending_xdai(TRANSACTION_MESSAGE_FEE)),
data_text=compress_message(message),
)
return "Message sent to the agent."
def __call__(self, address: str, message: str) -> str:
keys = MicrochainAgentKeys()
try:
send_xdai_to(
web3=ContractOnGnosisChain.get_web3(),
from_private_key=keys.bet_from_private_key,
to_address=Web3.to_checksum_address(address),
value=xdai_to_wei(keys.cap_sending_xdai(TRANSACTION_MESSAGE_FEE)),
data_text=compress_message(message),
)
return "Message sent to the agent."
except Exception as e:
logger.error(f"Failed to send message: {e}")
return "Failed to send message due to an error."

Comment on lines +26 to +33
keys = MicrochainAgentKeys()
web3 = ContractOnGnosisChain.get_web3()
address_checksum = Web3.to_checksum_address(address)
send_xdai_to(
web3,
keys.bet_from_private_key,
address_checksum,
xdai_to_wei(xdai_type(amount)),
xdai_to_wei(keys.cap_sending_xdai(xdai_type(amount))),
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add error handling for transaction failures

The __call__ method lacks error handling for exceptions that may occur during the send_xdai_to function call. Incorporate error handling to manage issues such as invalid addresses, network errors, or insufficient funds gracefully.

Apply this diff to add error handling:

+from prediction_market_agent_tooling.loggers import logger

 def __call__(
     self,
     address: str,
     amount: float,
 ) -> str:
     keys = MicrochainAgentKeys()
     web3 = ContractOnGnosisChain.get_web3()
     address_checksum = Web3.to_checksum_address(address)
+    try:
         send_xdai_to(
             web3,
             keys.bet_from_private_key,
             address_checksum,
             xdai_to_wei(keys.cap_sending_xdai(xdai_type(amount))),
         )
-        return f"Sent {amount} xDAI to {address_checksum}."
+        return f"Sent {amount} xDai to {address_checksum}."
+    except Exception as e:
+        logger.error(f"Failed to send xDai: {e}")
+        return "Failed to send xDai due to an error."
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
keys = MicrochainAgentKeys()
web3 = ContractOnGnosisChain.get_web3()
address_checksum = Web3.to_checksum_address(address)
send_xdai_to(
web3,
keys.bet_from_private_key,
address_checksum,
xdai_to_wei(xdai_type(amount)),
xdai_to_wei(keys.cap_sending_xdai(xdai_type(amount))),
from prediction_market_agent_tooling.loggers import logger
keys = MicrochainAgentKeys()
web3 = ContractOnGnosisChain.get_web3()
address_checksum = Web3.to_checksum_address(address)
try:
send_xdai_to(
web3,
keys.bet_from_private_key,
address_checksum,
xdai_to_wei(keys.cap_sending_xdai(xdai_type(amount))),
)
return f"Sent {amount} xDai to {address_checksum}."
except Exception as e:
logger.error(f"Failed to send xDai: {e}")
return "Failed to send xDai due to an error."

Comment on lines +151 to +152
def decompress_message(message: bytes) -> str:
return zlib.decompress(message).decode()
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add error handling for malformed compressed data

The decompression function should handle potential errors from malformed input.

Add error handling:

 def decompress_message(message: bytes) -> str:
-    return zlib.decompress(message).decode()
+    """Decompresses a message previously compressed with compress_message.
+    
+    Args:
+        message: The compressed message bytes
+    Returns:
+        Original string message
+    Raises:
+        ValueError: If the message is corrupted or not valid compressed data
+    """
+    try:
+        return zlib.decompress(message).decode()
+    except (zlib.error, UnicodeDecodeError) as e:
+        raise ValueError(f"Failed to decompress message: {e}")
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
def decompress_message(message: bytes) -> str:
return zlib.decompress(message).decode()
def decompress_message(message: bytes) -> str:
"""Decompresses a message previously compressed with compress_message.
Args:
message: The compressed message bytes
Returns:
Original string message
Raises:
ValueError: If the message is corrupted or not valid compressed data
"""
try:
return zlib.decompress(message).decode()
except (zlib.error, UnicodeDecodeError) as e:
raise ValueError(f"Failed to decompress message: {e}")

Comment on lines +144 to +152


def compress_message(message: str) -> bytes:
"""Used to reduce size of the message before sending it to reduce gas costs."""
return zlib.compress(message.encode(), level=zlib.Z_BEST_COMPRESSION)


def decompress_message(message: bytes) -> str:
return zlib.decompress(message).decode()
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Codebase verification

Compression functions are properly integrated but message decompression is missing in handlers

  • The compress_message function is correctly used in SendPaidMessageToAnotherAgent to compress messages before sending them on-chain
  • However, decompress_message is not implemented in any message receiving logic
  • The ReceiveMessage function is currently a TODO stub and needs to implement message decompression
  • The compression utilities are properly tested in isolation
🔗 Analysis chain

Verify compression usage in message handlers

The compression utilities are well implemented, but we should verify their integration with message handlers.


Let's examine the actual usage of these compression functions in the message handlers.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for usage of compression functions in message handlers
echo "Searching for compression function usage..."
rg -l "compress_message|decompress_message" --type py

# Look for potential message size constants or limits
echo "Checking for message size limits..."
rg -i "message.*size|size.*limit|max.*size" --type py

Length of output: 609


Script:

#!/bin/bash
# Check the implementation in messages_functions.py
echo "Content of messages_functions.py:"
cat prediction_market_agent/agents/microchain_agent/messages_functions.py

# Check the test implementation
echo -e "\nContent of test_utils.py:"
cat tests/agents/microchain/test_utils.py

Length of output: 3109

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