-
Notifications
You must be signed in to change notification settings - Fork 4
[BLCKCHN-439] AI Agent Explorer – Transaction Description Generation #116
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
Open
leejw51crypto
wants to merge
2
commits into
main
Choose a base branch
from
feature/439
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -2,18 +2,18 @@ | |
""" | ||
Telegram Bot Example | ||
|
||
This example demonstrates how to use the existing Telegram bot functionality | ||
This example demonstrates how to use the Telegram bot functionality | ||
with the crypto_com_agent_client library. The bot will: | ||
|
||
1. Load the TELEGRAM_BOT_TOKEN from .env file | ||
2. Ask user to choose LLM provider (OpenAI or Grok3) | ||
3. Initialize the agent with selected provider and Telegram plugin | ||
3. Initialize the agent with selected provider | ||
4. Start the Telegram bot to handle user messages | ||
|
||
Prerequisites: | ||
1. Create a .env file with TELEGRAM_BOT_TOKEN | ||
2. Set up your Telegram bot via @BotFather | ||
3. Install dependencies: python-telegram-bot is already in pyproject.toml | ||
3. Install dependencies: python-telegram-bot==22.3 | ||
4. Set DASHBOARD_API_KEY in .env for blockchain operations | ||
5. For OpenAI: Set OPENAI_API_KEY in .env | ||
6. For Grok3: Set GROK_API_KEY in .env | ||
|
@@ -32,18 +32,39 @@ | |
DEBUG_LOGGING=true python bot.py | ||
""" | ||
|
||
import logging | ||
import os | ||
import sys | ||
from datetime import datetime | ||
|
||
import pytz | ||
from crypto_com_agent_client import Agent, tool, SQLitePlugin | ||
from crypto_com_agent_client import Agent, SQLitePlugin, tool | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. we have recently migrated https://pypi.org/project/cryptocom-agent-plugin-telegram/ There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. ok |
||
from crypto_com_agent_client.lib.enums.provider_enum import Provider | ||
# Add agent-plugins-py to path for TelegramPlugin | ||
# sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'agent-plugins-py', 'telegram')) | ||
from crypto_com_agent_plugin_telegram import TelegramPlugin | ||
from dotenv import load_dotenv | ||
|
||
from cronos_tx_analyzer import CronosTransactionAnalyzer | ||
|
||
# Load environment variables from .env file | ||
load_dotenv() | ||
|
||
# Custom storage for persistence (optional) | ||
custom_storage = SQLitePlugin(db_path="telegram_agent_state.db") | ||
# Set up logging | ||
logging.basicConfig( | ||
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO | ||
) | ||
logger = logging.getLogger(__name__) | ||
|
||
|
||
# Initialize the Cronos transaction analyzer with dashboard API key | ||
# This will automatically determine the correct chain and RPC endpoint | ||
tx_analyzer = CronosTransactionAnalyzer( | ||
dashboard_api_key=os.getenv("DASHBOARD_API_KEY") | ||
) | ||
|
||
# Global agent instance | ||
agent = None | ||
|
||
|
||
# Example custom tool that the bot can use | ||
|
@@ -62,14 +83,83 @@ def get_time() -> str: | |
local_time = datetime.now() | ||
|
||
message = ( | ||
f"🕒 Current time:\n\n" | ||
f"Current time:\n\n" | ||
f"UTC: {utc_time.strftime('%Y-%m-%d %H:%M:%S %Z')}\n" | ||
f"Local: {local_time.strftime('%Y-%m-%d %H:%M:%S')}" | ||
) | ||
|
||
return message | ||
|
||
|
||
@tool | ||
def get_transaction_info(tx_hash: str) -> str: | ||
""" | ||
Get detailed information about a Cronos EVM transaction. | ||
|
||
Args: | ||
tx_hash: The transaction hash (0x followed by 64 hex characters) | ||
|
||
Returns: | ||
A detailed description of the transaction including type, participants, amounts, and status. | ||
""" | ||
try: | ||
print(f"[get_transaction_info] Retrieving transaction info for: {tx_hash}") | ||
# Validate transaction hash format | ||
if not tx_hash.startswith("0x") or len(tx_hash) != 66: | ||
return f"Invalid transaction hash format. Expected 0x followed by 64 hex characters, got: {tx_hash}" | ||
|
||
# Check connection | ||
if not tx_analyzer.is_connected(): | ||
return ( | ||
"Unable to connect to Cronos EVM RPC. Please check network connection." | ||
) | ||
|
||
# Get transaction data | ||
tx_data = tx_analyzer.get_transaction(tx_hash) | ||
if not tx_data: | ||
return f"Transaction not found: {tx_hash}. Please verify the hash is correct and on Cronos mainnet." | ||
|
||
# Analyze the transaction | ||
analysis = tx_analyzer.analyze_transaction_flow(tx_data) | ||
|
||
# Build response in formatted display style | ||
result = [] | ||
|
||
result.append(f"Analyzing: {tx_hash}") | ||
result.append("------------------------------------------------------------") | ||
|
||
# DESCRIPTION | ||
result.append("Description:") | ||
description = tx_analyzer.generate_transaction_description(tx_hash) | ||
result.append(description) | ||
|
||
# TECHNICAL DETAILS | ||
result.append("\nTechnical Details:") | ||
result.append(f"Type: {analysis['type']}") | ||
result.append(f"From: {analysis['from']}") | ||
result.append(f"To: {analysis['to']}") | ||
result.append(f"Status: {analysis['status']}") | ||
result.append(f"Gas Used: {analysis['gas_used']:,}") | ||
if analysis["value_cro"] > 0: | ||
result.append(f"CRO Value: {analysis['value_cro']}") | ||
|
||
# SWAP DETAILS (if applicable) | ||
if analysis["type"] == "token_swap": | ||
from_token = analysis.get("from_token") or analysis.get("input_token") | ||
to_token = analysis.get("to_token") or analysis.get("output_token") | ||
from_amount = analysis.get("from_amount") or analysis.get("input_amount") | ||
to_amount = analysis.get("to_amount") or analysis.get("output_amount") | ||
|
||
if from_token and to_token and from_amount and to_amount: | ||
result.append("Swap Details:") | ||
result.append(f" {from_amount} {from_token} → {to_amount} {to_token}") | ||
|
||
return "\n".join(result) | ||
|
||
except Exception as e: | ||
return f"Error analyzing transaction: {str(e)}" | ||
|
||
|
||
def get_llm_choice(): | ||
""" | ||
Ask user to choose which LLM provider to use. | ||
|
@@ -78,7 +168,7 @@ def get_llm_choice(): | |
str: 'openai' or 'grok3' | ||
""" | ||
print("\nChoose your LLM provider:") | ||
print("1. OpenAI (gpt-4o-mini)") | ||
print("1. OpenAI (gpt-5-nano)") | ||
print("2. Grok3") | ||
|
||
while True: | ||
|
@@ -115,8 +205,7 @@ def get_llm_config(provider_choice): | |
return None | ||
|
||
return { | ||
"provider": "OpenAI", | ||
"model": "gpt-4o-mini", | ||
"provider": Provider.OpenAI, | ||
"provider-api-key": api_key, | ||
"debug-logging": debug_logging, | ||
} | ||
|
@@ -136,10 +225,17 @@ def get_llm_config(provider_choice): | |
} | ||
|
||
|
||
# Note: The handler functions (start, help_command, handle_message) are now managed | ||
# by the TelegramPlugin and don't need to be defined here anymore. | ||
# The plugin handles all Telegram-specific interactions internally. | ||
|
||
|
||
def main(): | ||
""" | ||
Main function to initialize and start the Telegram bot. | ||
""" | ||
global agent | ||
|
||
# Check if TELEGRAM_BOT_TOKEN is set | ||
telegram_token = os.getenv("TELEGRAM_BOT_TOKEN") | ||
if not telegram_token: | ||
|
@@ -160,9 +256,12 @@ def main(): | |
if not llm_config: | ||
return | ||
|
||
print(f"\nInitializing Telegram Agent with {provider_choice.upper()}...") | ||
print(f"\nInitializing Agent with {provider_choice.upper()}...") | ||
|
||
# Create TelegramPlugin instance | ||
telegram_plugin = TelegramPlugin(bot_token=telegram_token) | ||
|
||
# Initialize the agent with selected configuration | ||
# Initialize the agent with TelegramPlugin as a plugin instance | ||
agent = Agent.init( | ||
llm_config=llm_config, | ||
blockchain_config={ | ||
|
@@ -177,27 +276,29 @@ def main(): | |
"verbosity": "medium", | ||
}, | ||
"instructions": ( | ||
"You are a helpful Crypto.com AI assistant. " | ||
"You can help users with cryptocurrency information, " | ||
"blockchain queries, and general crypto-related questions. " | ||
"You are a blockchain transaction analyst and Crypto.com AI assistant. " | ||
"When asked about a transaction, use the get_transaction_info tool to retrieve detailed information. " | ||
"The tool returns pre-formatted responses with '**Summary:**' and '**Description:**' sections. " | ||
"Present the tool's response EXACTLY as returned, without reformatting or summarizing. " | ||
"Do not modify, truncate, or rephrase the formatted response from get_transaction_info. " | ||
"You can also help users with cryptocurrency information, blockchain queries, and general crypto-related questions. " | ||
"Be friendly and informative in your responses." | ||
), | ||
"tools": [get_time], | ||
"storage": custom_storage, | ||
"telegram": {"bot_token": telegram_token}, | ||
"tools": [get_time, get_transaction_info], | ||
# Disabled to avoid SQLite issues | ||
}, | ||
plugin_instances=[telegram_plugin], # Pass TelegramPlugin as a plugin instance | ||
) | ||
|
||
print("Agent initialized successfully!") | ||
print(f"Using {provider_choice.upper()} provider") | ||
print(f"Bot Token: ***...") | ||
print("Starting Telegram bot...") | ||
print("Your bot is now ready to receive messages!") | ||
print("Press Ctrl+C to stop the bot") | ||
|
||
# Run the bot through the plugin | ||
try: | ||
# Start the Telegram bot | ||
agent.start_telegram() | ||
telegram_plugin.run() | ||
except KeyboardInterrupt: | ||
print("\nBot stopped by user") | ||
except Exception as e: | ||
|
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
not needed intirely, its in the package