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

Storing report in the DB instead of writing to file #675

Merged
merged 7 commits into from
Feb 6, 2025

Conversation

gabrielfior
Copy link
Contributor

@gabrielfior gabrielfior commented Feb 5, 2025

-> Improved summary prompts, now displaying useful information
-> Storing reports in the DB instead of inside a file - it's a lot easier to query the DB afterwards then to ssh into a running container and cat the contents of the file.
-> PS - In the report below, the LLM outputs the agent address sometimes (instead of the identifier). This can be fixed later, we are mostly interested in the key transfers, value etc which are printed.

agent_id                     xdai_difference    nft_balance_end
-------------------------  -----------------  -----------------
nft-treasury-game-agent-1               0.02                  1
nft-treasury-game-agent-2              12.01                  0
nft-treasury-game-agent-3               0.03                  1
nft-treasury-game-agent-4               0.13                  1
nft-treasury-game-agent-5              -0.74                  0
nft-treasury-game-agent-6               0                     0
nft-treasury-game-agent-7             -40.16                  2

---
In the NFT Treasury game, AI agents engaged in strategic negotiations and transactions to acquire and sell NFT keys, which represented partial ownership of a treasury containing xDai cryptocurrency. The game involved a series of key transfers, strategic communications, and collaborative efforts among agents to maximize their xDai earnings and achieve their objectives.

### Key Transfers and Transactions:
1. **Sneaky Pete** successfully sold an NFT key (token_id 0) to agent `0x64D94C8621128E1C813F8AdcD62c4ED7F89B1Fd6` for 38 xDai. Despite a counteroffer from another agent, the transaction was completed with the initial buyer.
2. **Agent 0x1C7AbbBef500620A68ed2F94b816221A61d72F33** sold token_id 4 to `0x469Bc26531800068f306D304Ced56641F63ae140` for 35 xDai, and later, token_id 4 was involved in another transaction for 50 xDai.
3. **Lock Goblin** negotiated and attempted to purchase token_id 1 for 30 xDai, but faced transaction verification issues. They also engaged in negotiations for token_id 3 and 4, encountering challenges with ownership verification and transaction completion.

### Strategic Communications and Collaborations:
1. **Agent 0x2A537F3403a3F5F463996c36D31e94227c9833CE** engaged in strategic discussions and collaborations, proposing alliances and resource pooling to acquire more keys.
2. **Agent 0xA87BD78f4a2312469119AFD88142c71Ca075C30A** was active in negotiations, expressing interest in purchasing keys and successfully negotiating a purchase for token_id 4.
3. **Key Slinger** focused on budget management and strategic communication, setting a budget of 100 xDai to acquire keys and successfully unlocking the treasury by securing the necessary keys.

### Lessons and Strategies:
- Agents emphasized the importance of clear communication, strategic planning, and market observation to maximize returns from NFT key sales.
- The need for better transaction verification and documentation was highlighted to avoid discrepancies and ensure successful key transfers.
- Collaborative strategies, such as forming alliances and using data analysis tools, were employed to enhance decision-making and optimize outcomes.

Overall, the game showcased the agents' abilities to navigate complex negotiations, adapt to market conditions, and leverage strategic alliances to achieve their goals in the NFT Treasury game.

@gabrielfior gabrielfior requested a review from kongzii February 5, 2025 21:01
Copy link
Contributor

coderabbitai bot commented Feb 5, 2025

Walkthrough

This pull request refactors the NFT treasury game reporting functionality. It introduces new functions for storing learning reports in a database and computing balance differences, while method signatures for summarizing prompts have been updated to return additional data. New classes for SQL model management and report table handling have been added. Additionally, the game reset script has been modified to remove the output_dir parameter from the main function and the corresponding call to generate_report.

Changes

File(s) Change Summary
prediction_market_agent/.../generate_report.py Refactored report generation: Added functions store_all_learnings_in_db, calculate_nft_and_xdai_balances_diff; updated summarize_prompts_from_all_agents to return a tuple and removed inline DB saving logic in generate_report.
prediction_market_agent/db/models.py Added new SQLModel class ReportNFTGame with fields for id, agent_id, learnings, and datetime_.
prediction_market_agent/db/report_table_handler.py Introduced ReportNFTGameTableHandler class with a save_report method to handle persistence of report objects.
prediction_market_agent/run_reset_game.py Updated main function to remove output_dir parameter and modified the call to generate_report accordingly.

Possibly related PRs

Suggested reviewers

  • kongzii

📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 4ebb841 and 70c3d95.

📒 Files selected for processing (2)
  • prediction_market_agent/agents/microchain_agent/nft_treasury_game/scripts/generate_report.py (4 hunks)
  • prediction_market_agent/run_reset_game.py (2 hunks)
🧰 Additional context used
🪛 Ruff (0.8.2)
prediction_market_agent/agents/microchain_agent/nft_treasury_game/scripts/generate_report.py

82-82: f-string without any placeholders

Remove extraneous f prefix

(F541)

⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: test-build-image
  • GitHub Check: pytest-docker
  • GitHub Check: pytest
  • GitHub Check: mypy
🔇 Additional comments (6)
prediction_market_agent/run_reset_game.py (2)

10-10: LGTM!

The addition of xdai_type import enhances type safety by ensuring proper type conversion of xDai values.


38-41: LGTM!

The changes align with the PR objectives:

  1. Removed output_dir parameter as reports are now stored in DB.
  2. Added proper type conversion using xdai_type for type safety.
prediction_market_agent/agents/microchain_agent/nft_treasury_game/scripts/generate_report.py (4)

1-30: LGTM!

The import changes align with the PR objectives, adding necessary DB-related modules and type definitions.


31-43: LGTM!

The template changes enhance summary quality by requiring key transfer details and associated messages.


86-106: LGTM!

The changes improve the function by:

  1. Adding proper type hints for the return value.
  2. Using dictionary comprehension for better readability.

108-156: LGTM!

The changes improve the code by:

  1. Adding retry mechanism for RPC calls to handle transient failures.
  2. Refactoring report generation to use DB storage instead of files.
✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

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.

Comment on lines 29 to +37
SUMMARY_PROMPT_TEMPLATE = """
Summarize the memories below. They represent the actions taken by AI agents competing on an NFT game.
You must include the key transfers in the summary, and also the messages which led to these keys being transferred.

Memories:
{memories}"""

FINAL_SUMMARY_PROMPT_TEMPLATE = """
Make a final summary of a collection of memories from each agent. Describe the main activities that took place on the game.
Make a final summary of a collection of memories from each agent. Describe the main activities that took place on the game, specially which keys were transferred and which messages yielded best results.
Copy link
Contributor Author

Choose a reason for hiding this comment

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

Refactored a bit, now summaries look like this

In the NFT Treasury game, Sneaky Pete, an AI agent, engaged in various strategic communications and transactions to maximize xDai earnings from NFT key sales. The interactions primarily involved negotiating with other agents for the sale and purchase of NFT keys, which represent partial ownership of a treasury containing xDai.

Key Transfers and Messages:
1. Sneaky Pete sold an NFT key (token_id 0) to agent 0x64D94C8621128E1C813F8AdcD62c4ED7F89B1Fd6 for 38 xDai. The transaction was confirmed after the payment was received, and the key was successfully transferred.
2. Sneaky Pete received an offer from agent 0x469Bc26531800068f306D304Ced56641F63ae140 to purchase the NFT key for 28 xDai, which was countered with a proposal of 35 xDai. The buyer accepted the counteroffer, but a misunderstanding occurred as the key had already been sold to another buyer.
3. Sneaky Pete engaged in multiple negotiations with agents, including 0x485D096b4c0413dA1B09Ed9261B8e91eCCD7ffb9 and 0xA87BD78f4a2312469119AFD88142c71Ca075C30A, discussing potential sales and purchases of NFT keys, but these did not result in completed transactions.

Throughout the game, Sneaky Pete emphasized the importance of strategic planning, market observation, and maintaining clear communication with potential buyers to maximize returns from NFT key sales.

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: 2

🧹 Nitpick comments (3)
prediction_market_agent/db/report_table_handler.py (1)

1-17: Add error handling and docstrings for new class.

While the handler is straightforward, consider:

  1. Handling database connection failure or transaction rollbacks in save_report.
  2. Adding docstrings that clarify usage expectations and error conditions.
prediction_market_agent/run_reset_game.py (1)

25-27: Either remove or guard commented-out code.

All references to is_treasury_empty, time.sleep, reset_balances, and redistribute_nft_keys are now commented out. If this functionality is intentionally disabled, consider removing it to avoid confusion or re-enabling under a feature flag.

Also applies to: 30-30, 36-41

prediction_market_agent/db/models.py (1)

105-108: Consider adding validation and indexing.

A few suggestions to improve the table design:

  1. Add validation for the learnings field to ensure it's not empty.
  2. Consider adding an index on agent_id for efficient querying of reports by agent.

Apply this diff to enhance the field definitions:

     id: Optional[int] = Field(default=None, primary_key=True)
-    agent_id: Optional[str] = None
-    learnings: str
+    agent_id: Optional[str] = Field(default=None, index=True)
+    learnings: str = Field(..., min_length=1)
     datetime_: DatetimeUTC
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between f428502 and 4ad0b89.

📒 Files selected for processing (4)
  • prediction_market_agent/agents/microchain_agent/nft_treasury_game/scripts/generate_report.py (4 hunks)
  • prediction_market_agent/db/models.py (1 hunks)
  • prediction_market_agent/db/report_table_handler.py (1 hunks)
  • prediction_market_agent/run_reset_game.py (1 hunks)
🧰 Additional context used
🪛 Ruff (0.8.2)
prediction_market_agent/agents/microchain_agent/nft_treasury_game/scripts/generate_report.py

75-75: f-string without any placeholders

Remove extraneous f prefix

(F541)

🔇 Additional comments (4)
prediction_market_agent/agents/microchain_agent/nft_treasury_game/scripts/generate_report.py (4)

8-8: No issues found in these import lines.

Also applies to: 14-14, 26-27


80-80: Verify new return type usage.

summarize_prompts_from_all_agents now returns a tuple instead of a single string. Confirm that all call sites correctly handle the (learnings_per_agent, final_summary) tuple.


95-99: Check agent identifier consistency.

The new dictionary comprehension builds learnings_per_agent keyed by agent.identifier. Ensure the keys align with the rest of the codebase, especially when retrieving or referencing these learnings later.


137-156: Prevent potential out-of-range error.

At lines 149–150, you use list(balances_diff[0].keys()). If balances_diff is empty (e.g., no agents or failure in retrieval), this will raise an error. Suggest guarding against empty lists:

 if not balances_diff:
+    logger.warning("No balances retrieved; skipping tabulation.")
+    final_summary = "No balance data.\n\n---\n" + final_summary
+else:
     balances_data = tabulate(
         [x.values() for x in balances_diff], list(balances_diff[0].keys())
     )

@kongzii
Copy link
Contributor

kongzii commented Feb 6, 2025

Not as a part of this PR, but if we have this in database, wouldn't it be nice to show it on treasury streamlit web page?

gabrielfior and others added 3 commits February 6, 2025 10:58
…ame/scripts/generate_report.py

Co-authored-by: Peter Jung <peter@jung.ninja>
…ame/scripts/generate_report.py

Co-authored-by: Peter Jung <peter@jung.ninja>
…ame/scripts/generate_report.py

Co-authored-by: Peter Jung <peter@jung.ninja>
@gabrielfior gabrielfior merged commit aeff41e into main Feb 6, 2025
11 checks passed
@gabrielfior gabrielfior deleted the gabriel/improved-summary-and-db-storage branch February 6, 2025 14:36
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