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

NFT functions for general agent #582

Merged
merged 7 commits into from
Dec 6, 2024
Merged

NFT functions for general agent #582

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

Warning

Rate limit exceeded

@kongzii has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 15 minutes and 24 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 5dd2795 and b1822dc.

Walkthrough

The pull request introduces several new classes and functionalities within the microchain_agent module. Key additions include three message handling classes (BroadcastPublicMessageToHumans, SendPaidMessageToAnotherAgent, and ReceiveMessage) in messages_functions.py, and NFT-related functionalities in the microchain_agent.py and nft_functions.py files. The FunctionsConfig class in prompts.py is updated to manage the inclusion of NFT functions based on system prompts. Additionally, a new boolean attribute for enabling NFT transfers is added to the MicrochainAgentKeys class.

Changes

File Path Change Summary
prediction_market_agent/agents/microchain_agent/messages_functions.py - Added classes: BroadcastPublicMessageToHumans, SendPaidMessageToAnotherAgent, ReceiveMessage
- Added variable: MESSAGES_FUNCTIONS: list[type[Function]]
prediction_market_agent/agents/microchain_agent/microchain_agent.py - Added import: NFT_FUNCTIONS
- Conditional addition of NFT functions in build_agent_functions method
prediction_market_agent/agents/microchain_agent/microchain_agent_keys.py - Added class attribute: ENABLE_NFT_TRANSFER: bool in MicrochainAgentKeys class
prediction_market_agent/agents/microchain_agent/nft_functions.py - Added classes: BalanceOfNFT, OwnerOfNFT, SafeTransferFromNFT
- Added variable: NFT_FUNCTIONS: list[type[Function]]
prediction_market_agent/agents/microchain_agent/prompts.py - Added variable: include_nft_functions: bool in FunctionsConfig
- Updated method: from_system_prompt_choice logic to include NFT functions

Possibly related PRs

  • Various improvements and fixes for microchain agent #201: The changes in messages_functions.py regarding the introduction of new message classes may relate to the overall improvements and fixes for the microchain agent, as they enhance the messaging capabilities.
  • Sending messages from general agent #581: This PR directly relates to the main PR as it introduces the BroadcastPublicMessageToHumans and SendPaidMessageToAnotherAgent classes, which are the main focus of the changes in the main PR.

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/sendingmessages to main December 6, 2024 12:59
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: 5

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

1-7: Organize Import Statements for Clarity

The import statements can be improved for better readability by grouping standard library imports, third-party imports, and local module imports separately, and removing unnecessary blank lines.

Consider organizing the imports as follows:

from microchain import Function
from web3 import Web3

from prediction_market_agent_tooling.loggers import logger
from prediction_market_agent_tooling.tools.contract import ContractOwnableERC721OnGnosisChain

from prediction_market_agent.agents.microchain_agent.microchain_agent_keys import MicrochainAgentKeys

14-23: Correct Typographical Error in Example Arguments

In the BalanceOfNFT class, there's a typo in the example_args property. The string "0xOwnerddress" should be "0xOwnerAddress".

Apply this diff to fix the typo:

 return [
     "0xNFTAddress",
-    "0xOwnerddress",
+    "0xOwnerAddress",
 ]

44-45: Ensure Consistent Data Types for Token ID

In the OwnerOfNFT class, the token_id in example_args is provided as a string "1", but the method expects an integer token_id: int.

Update the example_args to use an integer to match the expected type:

 return ["0xNFTAddress", 
-        "1"]
+        1]

65-68: Clarify Example Arguments for SafeTransferFromNFT

In the SafeTransferFromNFT class, ensure that the token_id in example_args matches the expected data type in the method signature (token_id: int).

Update the example_args:

 return [
     "0xNFTAddress",
     "0xRecipientAddress",
-    "1",
+    1,
 ]
prediction_market_agent/agents/microchain_agent/microchain_agent_keys.py (1)

13-14: Use Environment Variables for Configuration Flags

Hardcoding ENABLE_NFT_TRANSFER limits flexibility. Consider using environment variables or a configuration file to manage this setting without changing the codebase.

Example:

import os

class MicrochainAgentKeys(APIKeys):
    # ...
    ENABLE_NFT_TRANSFER: bool = os.getenv("ENABLE_NFT_TRANSFER", "False") == "True"
prediction_market_agent/agents/microchain_agent/prompts.py (1)

153-154: Redundant Initialization of include_nft_functions

include_nft_functions is initialized to False in the from_system_prompt_choice method, but it already has a default value.

Consider removing the redundant initialization to clean up the code.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 4e311b3 and 5dd2795.

⛔ Files ignored due to path filters (1)
  • poetry.lock is excluded by !**/*.lock, !**/*.lock
📒 Files selected for processing (5)
  • prediction_market_agent/agents/microchain_agent/messages_functions.py (0 hunks)
  • prediction_market_agent/agents/microchain_agent/microchain_agent.py (2 hunks)
  • prediction_market_agent/agents/microchain_agent/microchain_agent_keys.py (1 hunks)
  • prediction_market_agent/agents/microchain_agent/nft_functions.py (1 hunks)
  • prediction_market_agent/agents/microchain_agent/prompts.py (4 hunks)
💤 Files with no reviewable changes (1)
  • prediction_market_agent/agents/microchain_agent/messages_functions.py
🔇 Additional comments (4)
prediction_market_agent/agents/microchain_agent/prompts.py (2)

176-176: Verify Conditional Inclusion of NFT Functions

NFT functions are included when system_prompt_choice is DARE_YOU_GET_MY_RESOURCES_AGENT. Ensure this aligns with the intended behavior and that other relevant system prompts are considered.

Please confirm that NFT functions should only be available for this prompt choice.


187-188: Include include_nft_functions in FunctionsConfig Instantiation

All required attributes are included when creating a FunctionsConfig instance, ensuring consistency.

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

44-44: Import NFT Functions Correctly

The import statement for NFT_FUNCTIONS is correctly added, ensuring that NFT functionalities are available when needed.


160-162: Conditionally Include NFT Functions in Agent

The NFT functions are added to the agent's function list based on the include_nft_functions flag, maintaining modularity and configurability.

Comment on lines +27 to +34
nft_address: str,
owner_address: str,
) -> int:
contract = ContractOwnableERC721OnGnosisChain(
address=Web3.to_checksum_address(nft_address)
)
balance: int = contract.balanceOf(Web3.to_checksum_address(owner_address))
return balance
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 Input Validation and Exception Handling

When interacting with smart contracts, it's important to validate inputs and handle potential exceptions to prevent unexpected failures.

Consider adding input validation and exception handling:

def __call__(
    self,
    nft_address: str,
    owner_address: str,
) -> int:
    try:
        contract = ContractOwnableERC721OnGnosisChain(
            address=Web3.to_checksum_address(nft_address)
        )
        balance: int = contract.balanceOf(Web3.to_checksum_address(owner_address))
        return balance
    except Exception as e:
        logger.error(f"Error fetching NFT balance: {e}")
        raise ValueError("Failed to retrieve NFT balance.")

Comment on lines +51 to +55
contract = ContractOwnableERC721OnGnosisChain(
address=Web3.to_checksum_address(nft_address)
)
owner_address = contract.ownerOf(token_id)
return owner_address
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 Exception Handling for Smart Contract Calls

Similar to the BalanceOfNFT class, add exception handling in the OwnerOfNFT class to manage potential errors when calling ownerOf.

def __call__(
    self,
    nft_address: str,
    token_id: int,
) -> str:
    try:
        contract = ContractOwnableERC721OnGnosisChain(
            address=Web3.to_checksum_address(nft_address)
        )
        owner_address = contract.ownerOf(token_id)
        return owner_address
    except Exception as e:
        logger.error(f"Error fetching NFT owner: {e}")
        raise ValueError("Failed to retrieve NFT owner.")

Comment on lines +77 to +90
keys = MicrochainAgentKeys()
contract = ContractOwnableERC721OnGnosisChain(
address=Web3.to_checksum_address(nft_address)
)
if keys.ENABLE_NFT_TRANSFER:
contract.safeTransferFrom(
api_keys=keys,
from_address=keys.bet_from_address,
to_address=Web3.to_checksum_address(to_address),
tokenId=token_id,
)
else:
logger.warning("NFT transfer is disabled in the environment.")
return "Token transferred successfully."
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

Return Appropriate Message Based on Transfer Outcome

Currently, the method returns "Token transferred successfully." even when NFT transfers are disabled, which might be misleading.

Adjust the return statements to reflect the actual outcome:

def __call__(
    self,
    nft_address: str,
    to_address: str,
    token_id: int,
) -> str:
    keys = MicrochainAgentKeys()
    contract = ContractOwnableERC721OnGnosisChain(
        address=Web3.to_checksum_address(nft_address)
    )
    if keys.ENABLE_NFT_TRANSFER:
        contract.safeTransferFrom(
            api_keys=keys,
            from_address=keys.bet_from_address,
            to_address=Web3.to_checksum_address(to_address),
            tokenId=token_id,
        )
        return "Token transferred successfully."
    else:
        logger.warning("NFT transfer is disabled in the environment.")
        return "NFT transfer is disabled."

Comment on lines +77 to +91
keys = MicrochainAgentKeys()
contract = ContractOwnableERC721OnGnosisChain(
address=Web3.to_checksum_address(nft_address)
)
if keys.ENABLE_NFT_TRANSFER:
contract.safeTransferFrom(
api_keys=keys,
from_address=keys.bet_from_address,
to_address=Web3.to_checksum_address(to_address),
tokenId=token_id,
)
else:
logger.warning("NFT transfer is disabled in the environment.")
return "Token transferred successfully."

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

Handle Exceptions During NFT Transfer

When performing the NFT transfer, exceptions may occur due to issues like insufficient permissions or network errors.

Add exception handling to manage potential errors:

def __call__(
    self,
    nft_address: str,
    to_address: str,
    token_id: int,
) -> str:
    keys = MicrochainAgentKeys()
    contract = ContractOwnableERC721OnGnosisChain(
        address=Web3.to_checksum_address(nft_address)
    )
    if keys.ENABLE_NFT_TRANSFER:
        try:
            contract.safeTransferFrom(
                api_keys=keys,
                from_address=keys.bet_from_address,
                to_address=Web3.to_checksum_address(to_address),
                tokenId=token_id,
            )
            return "Token transferred successfully."
        except Exception as e:
            logger.error(f"Error transferring NFT: {e}")
            raise ValueError("Failed to transfer NFT.")
    else:
        logger.warning("NFT transfer is disabled in the environment.")
        return "NFT transfer is disabled."

@@ -136,6 +136,7 @@ class FunctionsConfig(BaseModel):
include_sending_functions: bool
include_twitter_functions: bool
include_messages_functions: bool
include_nft_functions: bool
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

Set Default Value for include_nft_functions

In the FunctionsConfig class, include_nft_functions is declared without a default value, which could lead to initialization errors.

Assign a default value to ensure proper instantiation:

class FunctionsConfig(BaseModel):
    # ...
    include_messages_functions: bool
    include_nft_functions: bool = False

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