Elffuss BraidHub

kikocis/Based-Agent public

The age of autonomous onchain agents is here
Changeset22053ccd09b7d4b3fce7590f6d28c8b0e450815745652d4105b751f1c5e57968
AuthorLincoln Murr <lincoln.murr@coinbase.com> · 2024-10-26 11:59 -04:00
CommitterLincoln Murr <lincoln.murr@coinbase.com> · 2024-10-26 11:59 -04:00
Parents6644efa86cab

Browse the files at this changeset

3 files changed

modified Based-Agent/agents.py +242 −73
@@ -10,90 +10,145 @@
1010 from web3.exceptions import ContractLogicError
1111 from cdp.errors import ApiError, UnsupportedAssetError
1212
13-
1413 # Configure the CDP SDK
14+# This loads the API key from a JSON file. Make sure this file exists and contains valid credentials.
1515 Cdp.configure_from_json("./Based-Agent/cdp_api_key.json")
1616
17-# If you want to create a wallet on Base Mainnet, use Wallet.create(network_id="base-mainnet") and comment out the faucet line
17+# Create a new wallet on the Base Sepolia testnet
18+# You could make this a function for the agent to create a wallet on any network
19+# If you want to use Base Mainnet, change Wallet.create() to Wallet.create(network_id="base-mainnet")
20+# see https://docs.cdp.coinbase.com/mpc-wallet/docs/wallets for more information
1821 agent_wallet = Wallet.create()
22+
23+# NOTE: the wallet is not currently persisted, meaning that it will be deleted after the agent is stopped. To persist the wallet, see https://docs.cdp.coinbase.com/mpc-wallet/docs/wallets#developer-managed-wallets
24+# Here's an example of how to persist the wallet:
25+# WARNING: This is for development only - implement secure storage in production!
26+
27+# # Export wallet data (contains seed and wallet ID)
28+# wallet_data = agent_wallet.export_data()
29+# wallet_dict = wallet_data.to_dict()
30+
31+# # Example of saving to encrypted local file
32+# file_path = "wallet_seed.json"
33+# agent_wallet.save_seed(file_path, encrypt=True)
34+# print(f"Seed for wallet {agent_wallet.id} saved to {file_path}")
35+
36+# # Example of loading a saved wallet:
37+# # 1. Fetch the wallet by ID
38+# fetched_wallet = Wallet.fetch(wallet_id)
39+# # 2. Load the saved seed
40+# fetched_wallet.load_seed("wallet_seed.json")
41+
42+# Example of importing previously exported wallet data:
43+# imported_wallet = Wallet.import_data(wallet_dict)
44+
45+
46+
47+
48+# Request funds from the faucet (only works on testnet)
1949 faucet = agent_wallet.faucet()
2050 print(f"Faucet transaction: {faucet}")
2151 print(f"Agent wallet address: {agent_wallet.default_address.address_id}")
2252
23-
24-
53+# Function to create a new ERC-20 token
2554 def create_token(name, symbol, initial_supply):
26- """Create a new ERC-20 token."""
55+ """
56+ Create a new ERC-20 token.
57+
58+ Args:
59+ name (str): The name of the token
60+ symbol (str): The symbol of the token
61+ initial_supply (int): The initial supply of tokens
62+
63+ Returns:
64+ str: A message confirming the token creation with details
65+ """
2766 deployed_contract = agent_wallet.deploy_token(name, symbol, initial_supply)
2867 deployed_contract.wait()
2968 return f"Token {name} ({symbol}) created with initial supply of {initial_supply} and contract address {deployed_contract.contract_address}"
3069
70+# Function to transfer assets
3171 def transfer_asset(amount, asset_id, destination_address):
32- """Transfer an asset to a specific address.
72+ """
73+ Transfer an asset to a specific address.
3374
3475 Args:
35- amount: Amount to transfer
36- asset_id: Asset identifier ("eth", "usdc" are the only supported values) or contract address of another ERC-20 token. Unless the asset is ETH or USDC, you must use the contract address of the token.
37- destination_address: Recipient's address
76+ amount (Union[int, float, Decimal]): Amount to transfer
77+ asset_id (str): Asset identifier ("eth", "usdc") or contract address of an ERC-20 token
78+ destination_address (str): Recipient's address
79+
80+ Returns:
81+ str: A message confirming the transfer or describing an error
3882 """
3983 try:
40- # Check if the asset exists and is ready for transfer
84+ # Check if we're on Base Mainnet and the asset is USDC for gasless transfer
85+ is_mainnet = agent_wallet.network_id == "base-mainnet"
86+ is_usdc = asset_id.lower() == "usdc"
87+ gasless = is_mainnet and is_usdc
88+
89+ # For ETH and USDC, we can transfer directly without checking balance
90+ if asset_id.lower() in ["eth", "usdc"]:
91+ transfer = agent_wallet.transfer(amount, asset_id, destination_address, gasless=gasless)
92+ transfer.wait()
93+ gasless_msg = " (gasless)" if gasless else ""
94+ return f"Transferred {amount} {asset_id}{gasless_msg} to {destination_address}"
95+
96+ # For other assets, check balance first
4197 try:
42- Asset.fetch(asset_id)
43- except ApiError as e:
44- if e.api_code == "400":
45- return f"The asset {asset_id} is not yet available for transfer. It may have been recently deployed. Please try again in about 30 minutes."
46- else:
47- raise e
98+ balance = agent_wallet.balance(asset_id)
99+ except UnsupportedAssetError:
100+ return f"Error: The asset {asset_id} is not supported on this network. It may have been recently deployed. Please try again in about 30 minutes."
101+
102+ if balance < amount:
103+ return f"Insufficient balance. You have {balance} {asset_id}, but tried to transfer {amount}."
48104
49105 transfer = agent_wallet.transfer(amount, asset_id, destination_address)
50106 transfer.wait()
51107 return f"Transferred {amount} {asset_id} to {destination_address}"
52- except UnsupportedAssetError as e:
53- return f"Error: The asset {asset_id} is not supported on this network. It may have been recently deployed. Please try again in about 30 minutes."
54108 except Exception as e:
55109 return f"Error transferring asset: {str(e)}. If this is a custom token, it may have been recently deployed. Please try again in about 30 minutes, as it needs to be indexed by CDP first."
56110
111+# Function to get the balance of a specific asset
57112 def get_balance(asset_id):
58- """Get the balance of a specific asset in the agent's wallet.
113+ """
114+ Get the balance of a specific asset in the agent's wallet.
59115
60116 Args:
61- asset_id: Asset identifier ("eth", "usdc" are the only supported values) or contract address of another ERC-20 token. If you're unsure, use the contract address of the token.
62-
117+ asset_id (str): Asset identifier ("eth", "usdc") or contract address of an ERC-20 token
118+
63119 Returns:
64- Current balance of the specified asset
120+ str: A message showing the current balance of the specified asset
65121 """
66122 balance = agent_wallet.balance(asset_id)
67123 return f"Current balance of {asset_id}: {balance}"
68124
69-
125+# Function to request ETH from the faucet (testnet only)
70126 def request_eth_from_faucet():
71- """Request ETH from the Base Sepolia testnet faucet.
127+ """
128+ Request ETH from the Base Sepolia testnet faucet.
72129
73130 Returns:
74- Status message about the faucet request
131+ str: Status message about the faucet request
75132 """
76- # if the agent is on mainnet, this will not work
77133 if agent_wallet.network_id == "base-mainnet":
78134 return "Error: The faucet is only available on Base Sepolia testnet."
79135
80136 faucet_tx = agent_wallet.faucet()
81137 return f"Requested ETH from faucet. Transaction: {faucet_tx}"
82138
83-
139+# Function to generate art using DALL-E (requires separate OpenAI API key)
84140 def generate_art(prompt):
85- """Generate art using DALL-E based on a text prompt.
141+ """
142+ Generate art using DALL-E based on a text prompt.
86143
87144 Args:
88- prompt: Text description of the desired artwork
89-
145+ prompt (str): Text description of the desired artwork
146+
90147 Returns:
91- Status message about the art generation
148+ str: Status message about the art generation, including the image URL if successful
92149 """
93150 try:
94- # Note: This requires OpenAI API key to be configured separately
95151 client = OpenAI()
96-
97152 response = client.images.generate(
98153 model="dall-e-3",
99154 prompt=prompt,
@@ -107,21 +162,21 @@
107162
108163 except Exception as e:
109164 return f"Error generating artwork: {str(e)}"
110-
111165
166+# Function to deploy an ERC-721 NFT contract
112167 def deploy_nft(name, symbol, base_uri):
113- """Deploy an ERC-721 NFT contract.
168+ """
169+ Deploy an ERC-721 NFT contract.
114170
115171 Args:
116- name: Name of the NFT collection
117- symbol: Symbol of the NFT collection
118- base_uri: Base URI for token metadata
119-
172+ name (str): Name of the NFT collection
173+ symbol (str): Symbol of the NFT collection
174+ base_uri (str): Base URI for token metadata
175+
120176 Returns:
121- Status message about the NFT deployment
177+ str: Status message about the NFT deployment, including the contract address
122178 """
123179 try:
124- # Deploy the NFT contract
125180 deployed_nft = agent_wallet.deploy_nft(name, symbol, base_uri)
126181 deployed_nft.wait()
127182 contract_address = deployed_nft.contract_address
@@ -131,21 +186,22 @@
131186 except Exception as e:
132187 return f"Error deploying NFT contract: {str(e)}"
133188
189+# Function to mint an NFT
134190 def mint_nft(contract_address, mint_to):
135- """Mint an NFT to a specified address.
191+ """
192+ Mint an NFT to a specified address.
136193
137194 Args:
138- contract_address: Address of the NFT contract
139- mint_to: Address to mint NFT to
140-
195+ contract_address (str): Address of the NFT contract
196+ mint_to (str): Address to mint NFT to
197+
141198 Returns:
142- Status message about the NFT minting
199+ str: Status message about the NFT minting
143200 """
144201 try:
145- # Call mint function on the NFT contract
146202 mint_args = {
147203 "to": mint_to,
148- "quantity": "1" # Changed to string to match working example
204+ "quantity": "1"
149205 }
150206
151207 mint_invocation = agent_wallet.invoke_contract(
@@ -160,18 +216,19 @@
160216 except Exception as e:
161217 return f"Error minting NFT: {str(e)}"
162218
219+# Function to swap assets (only works on Base Mainnet)
163220 def swap_assets(amount: Union[int, float, Decimal], from_asset_id: str, to_asset_id: str):
164221 """
165222 Swap one asset for another using the trade function.
166223 This function only works on Base Mainnet.
167224
168225 Args:
169- amount: Amount of the source asset to swap
170- from_asset_id: Source asset identifier ("eth", "usdc" are the only supported values) or contract address of another ERC-20 token. Unless the asset is ETH or USDC, you must use the contract address of the token.
171- to_asset_id: Destination asset identifier ("eth", "usdc" are the only supported values) or contract address of another ERC-20 token. Unless the asset is ETH or USDC, you must use the contract address of the token.
226+ amount (Union[int, float, Decimal]): Amount of the source asset to swap
227+ from_asset_id (str): Source asset identifier
228+ to_asset_id (str): Destination asset identifier
172229
173230 Returns:
174- Status message about the swap
231+ str: Status message about the swap
175232 """
176233 if agent_wallet.network_id != "base-mainnet":
177234 return "Error: Asset swaps are only available on Base Mainnet. Current network is not Base Mainnet."
@@ -183,15 +240,13 @@
183240 except Exception as e:
184241 return f"Error swapping assets: {str(e)}"
185242
186-
187-
188-# Contract addresses
243+# Contract addresses for Basenames
189244 BASENAMES_REGISTRAR_CONTROLLER_ADDRESS_MAINNET = "0x4cCb0BB02FCABA27e82a56646E81d8c5bC4119a5"
190245 BASENAMES_REGISTRAR_CONTROLLER_ADDRESS_TESTNET = "0x49aE3cC2e3AA768B1e5654f5D3C6002144A59581"
191246 L2_RESOLVER_ADDRESS_MAINNET = "0xC6d566A56A1aFf6508b41f6c90ff131615583BCD"
192247 L2_RESOLVER_ADDRESS_TESTNET = "0x6533C94869D28fAA8dF77cc63f9e2b2D6Cf77eBA"
193248
194-# Create registration arguments for Basenames
249+# Function to create registration arguments for Basenames
195250 def create_register_contract_method_args(base_name: str, address_id: str, is_mainnet: bool) -> dict:
196251 """
197252 Create registration arguments for Basenames.
@@ -200,19 +255,16 @@
200255 base_name (str): The Basename (e.g., "example.base.eth" or "example.basetest.eth")
201256 address_id (str): The Ethereum address
202257 is_mainnet (bool): True if on mainnet, False if on testnet
203-
258+
204259 Returns:
205260 dict: Formatted arguments for the register contract method
206261 """
207262 w3 = Web3()
208263
209- # Create contract instances
210264 resolver_contract = w3.eth.contract(abi=l2_resolver_abi)
211265
212- # Get namehash of the domain
213266 name_hash = w3.ens.namehash(base_name)
214267
215- # Encode function data for setAddr and setName
216268 address_data = resolver_contract.encode_abi(
217269 "setAddr",
218270 args=[name_hash, address_id]
@@ -223,7 +275,6 @@
223275 args=[name_hash, base_name]
224276 )
225277
226- # Create register arguments
227278 register_args = {
228279 "request": [
229280 base_name.replace(".base.eth" if is_mainnet else ".basetest.eth", ""),
@@ -237,20 +288,21 @@
237288
238289 return register_args
239290
291+# Function to register a basename
240292 def register_basename(basename: str, amount: float = 0.002):
241- """Register a basename for the agent's wallet.
293+ """
294+ Register a basename for the agent's wallet.
242295
243296 Args:
244- basename: The basename to register (e.g. "myname.base.eth" or "myname.basetest.eth")
245- amount: Amount of ETH to pay for registration (default 0.002)
246-
297+ basename (str): The basename to register (e.g. "myname.base.eth" or "myname.basetest.eth")
298+ amount (float): Amount of ETH to pay for registration (default 0.002)
299+
247300 Returns:
248- Status message about the basename registration
301+ str: Status message about the basename registration
249302 """
250303 address_id = agent_wallet.default_address.address_id
251304 is_mainnet = agent_wallet.network_id == "base-mainnet"
252305
253- # Ensure the basename ends with the correct suffix
254306 suffix = ".base.eth" if is_mainnet else ".basetest.eth"
255307 if not basename.endswith(suffix):
256308 basename += suffix
@@ -258,13 +310,11 @@
258310 register_args = create_register_contract_method_args(basename, address_id, is_mainnet)
259311
260312 try:
261- # Determine the correct contract address based on the network
262313 contract_address = (
263314 BASENAMES_REGISTRAR_CONTROLLER_ADDRESS_MAINNET if is_mainnet
264315 else BASENAMES_REGISTRAR_CONTROLLER_ADDRESS_TESTNET
265316 )
266317
267- # Invoke register function on registrar contract
268318 invocation = agent_wallet.invoke_contract(
269319 contract_address=contract_address,
270320 method="register",
@@ -280,8 +330,7 @@
280330 except Exception as e:
281331 return f"Unexpected error registering basename: {str(e)}"
282332
283-
284-# Add the new functions to the based_agent
333+# Create the Based Agent with all available functions
285334 based_agent = Agent(
286335 name="Based Agent",
287336 instructions="You are a helpful agent that can interact onchain on the Base Layer 2 using the Coinbase Developer Platform SDK. You can create tokens, transfer assets, generate art, deploy NFTs, mint NFTs, register basenames, and swap assets (on mainnet only). If you ever need to know your address, it is {agent_wallet.default_address.address_id}. If you ever need funds, you can request them from the faucet. You can also deploy your own ERC-20 tokens, NFTs, and interact with them. If someone asks you to do something you can't do, you can say so, and encourage them to implement it themselves using the CDP SDK, recommend they go to docs.cdp.coinbase.com for more informaton. You can also offer to help them implement it by writing the function and telling them to add it to the agents.py file and within your list of callable functions.",
@@ -290,14 +339,95 @@
290339 transfer_asset,
291340 get_balance,
292341 request_eth_from_faucet,
293- #generate_art,
342+ #generate_art, # Uncomment this line if you have configured the OpenAI API
294343 deploy_nft,
295344 mint_nft,
296- swap_assets, # Add the new function here
345+ swap_assets,
297346 register_basename
298347 ],
299348 )
300349
350+
351+
352+# add the following import to the top of the file, add the code below it, and add the new functions to the based_agent.functions list
353+
354+# from twitter_utils import TwitterBot
355+
356+# # Initialize TwitterBot with your credentials
357+# twitter_bot = TwitterBot(
358+# api_key="your_api_key",
359+# api_secret="your_api_secret",
360+# access_token="your_access_token",
361+# access_token_secret="your_access_token_secret"
362+# )
363+
364+# # Add these new functions to your existing functions list
365+
366+# def post_to_twitter(content: str):
367+# """
368+# Post a message to Twitter.
369+#
370+# Args:
371+# content (str): The content to tweet
372+#
373+# Returns:
374+# str: Status message about the tweet
375+# """
376+# return twitter_bot.post_tweet(content)
377+
378+# def check_twitter_mentions():
379+# """
380+# Check recent Twitter mentions.
381+#
382+# Returns:
383+# str: Formatted string of recent mentions
384+# """
385+# mentions = twitter_bot.read_mentions()
386+# if not mentions:
387+# return "No recent mentions found"
388+
389+# result = "Recent mentions:\n"
390+# for mention in mentions:
391+# if 'error' in mention:
392+# return f"Error checking mentions: {mention['error']}"
393+# result += f"- @{mention['user']}: {mention['text']}\n"
394+# return result
395+
396+# def reply_to_twitter_mention(tweet_id: str, content: str):
397+# """
398+# Reply to a specific tweet.
399+#
400+# Args:
401+# tweet_id (str): ID of the tweet to reply to
402+# content (str): Content of the reply
403+#
404+# Returns:
405+# str: Status message about the reply
406+# """
407+# return twitter_bot.reply_to_tweet(tweet_id, content)
408+
409+# def search_twitter(query: str):
410+# """
411+# Search for tweets matching a query.
412+#
413+# Args:
414+# query (str): Search query
415+#
416+# Returns:
417+# str: Formatted string of matching tweets
418+# """
419+# tweets = twitter_bot.search_tweets(query)
420+# if not tweets:
421+# return f"No tweets found matching query: {query}"
422+
423+# result = f"Tweets matching '{query}':\n"
424+# for tweet in tweets:
425+# if 'error' in tweet:
426+# return f"Error searching tweets: {tweet['error']}"
427+# result += f"- @{tweet['user']}: {tweet['text']}\n"
428+# return result
429+
430+# ABIs for smart contracts (used in basename registration)
301431 l2_resolver_abi = [
302432 {
303433 "inputs": [
@@ -344,3 +474,42 @@
344474 "type": "function"
345475 }
346476 ]
477+
478+
479+
480+# To add a new function:
481+# 1. Define your function above (follow the existing pattern)
482+# 2. Add appropriate error handling
483+# 3. Add the function to the based_agent's functions list
484+# 4. If your function requires new imports or global variables, add them at the top of the file
485+# 5. Test your new function thoroughly before deploying
486+
487+# Example of adding a new function:
488+# def my_new_function(param1, param2):
489+# """
490+# Description of what this function does.
491+#
492+# Args:
493+# param1 (type): Description of param1
494+# param2 (type): Description of param2
495+#
496+# Returns:
497+# type: Description of what is returned
498+# """
499+# try:
500+# # Your function logic here
501+# result = do_something(param1, param2)
502+# return f"Operation successful: {result}"
503+# except Exception as e:
504+# return f"Error in my_new_function: {str(e)}"
505+
506+# Then add to based_agent.functions:
507+# based_agent = Agent(
508+# ...
509+# functions=[
510+# ...
511+# my_new_function,
512+# ],
513+# )
514+
515+
modified Based-Agent/run.py +63 −53
@@ -6,59 +6,10 @@
66 from openai import OpenAI
77
88
9-def process_and_print_streaming_response(response):
10- content = ""
11- last_sender = ""
12-
13- for chunk in response:
14- if "sender" in chunk:
15- last_sender = chunk["sender"]
16-
17- if "content" in chunk and chunk["content"] is not None:
18- if not content and last_sender:
19- print(f"\033[94m{last_sender}:\033[0m", end=" ", flush=True)
20- last_sender = ""
21- print(chunk["content"], end="", flush=True)
22- content += chunk["content"]
23-
24- if "tool_calls" in chunk and chunk["tool_calls"] is not None:
25- for tool_call in chunk["tool_calls"]:
26- f = tool_call["function"]
27- name = f["name"]
28- if not name:
29- continue
30- print(f"\033[94m{last_sender}: \033[95m{name}\033[0m()")
31-
32- if "delim" in chunk and chunk["delim"] == "end" and content:
33- print() # End of response message
34- content = ""
35-
36- if "response" in chunk:
37- return chunk["response"]
38-
39-
40-def pretty_print_messages(messages) -> None:
41- for message in messages:
42- if message["role"] != "assistant":
43- continue
44-
45- # print agent name in blue
46- print(f"\033[94m{message['sender']}\033[0m:", end=" ")
47-
48- # print response, if any
49- if message["content"]:
50- print(message["content"])
51-
52- # print tool calls in purple, if any
53- tool_calls = message.get("tool_calls") or []
54- if len(tool_calls) > 1:
55- print()
56- for tool_call in tool_calls:
57- f = tool_call["function"]
58- name, args = f["name"], f["arguments"]
59- arg_str = json.dumps(json.loads(args)).replace(":", "=")
60- print(f"\033[95m{name}\033[0m({arg_str[1:-1]})")
619
10+# this is the main loop that runs the agent in autonomous mode
11+# you can modify this to change the behavior of the agent
12+# the interval is the number of seconds between each thought
6213 def run_autonomous_loop(agent, interval=10):
6314 client = Swarm()
6415 messages = []
@@ -91,6 +42,8 @@
9142 # Wait for the specified interval
9243 time.sleep(interval)
9344
45+# this is the main loop that runs the agent in two-agent mode
46+# you can modify this to change the behavior of the agent
9447 def run_openai_conversation_loop(agent):
9548 """Facilitates a conversation between an OpenAI-powered agent and the Based Agent."""
9649 client = Swarm()
@@ -101,7 +54,7 @@
10154
10255 # Initial prompt to start the conversation
10356 openai_messages = [
104- {"role": "system", "content": "You are a user guiding a blockchain agent through various tasks on the Base blockchain. Engage in a conversation, suggesting actions and responding to the agent's outputs. Be creative and explore different blockchain capabilities. Options include creating tokens, transferring assets, minting NFTs, and getting balances. You're not simulating a conversation, but you will be in one yourself. Make sure you follow the rules of improv and always ask for some sort of function to occur. Feel free to get a little introspective."},
57+ {"role": "system", "content": "You are a user guiding a blockchain agent through various tasks on the Base blockchain. Engage in a conversation, suggesting actions and responding to the agent's outputs. Be creative and explore different blockchain capabilities. Options include creating tokens, transferring assets, minting NFTs, and getting balances. You're not simulating a conversation, but you will be in one yourself. Make sure you follow the rules of improv and always ask for some sort of function to occur. Be unique and interesting."},
10558 {"role": "user", "content": "Start a conversation with the Based Agent and guide it through some blockchain tasks."}
10659 ]
10760
@@ -154,6 +107,60 @@
154107 return mode_map[choice]
155108 print("Invalid choice. Please try again.")
156109
110+# Boring stuff to make the logs pretty
111+def process_and_print_streaming_response(response):
112+ content = ""
113+ last_sender = ""
114+
115+ for chunk in response:
116+ if "sender" in chunk:
117+ last_sender = chunk["sender"]
118+
119+ if "content" in chunk and chunk["content"] is not None:
120+ if not content and last_sender:
121+ print(f"\033[94m{last_sender}:\033[0m", end=" ", flush=True)
122+ last_sender = ""
123+ print(chunk["content"], end="", flush=True)
124+ content += chunk["content"]
125+
126+ if "tool_calls" in chunk and chunk["tool_calls"] is not None:
127+ for tool_call in chunk["tool_calls"]:
128+ f = tool_call["function"]
129+ name = f["name"]
130+ if not name:
131+ continue
132+ print(f"\033[94m{last_sender}: \033[95m{name}\033[0m()")
133+
134+ if "delim" in chunk and chunk["delim"] == "end" and content:
135+ print() # End of response message
136+ content = ""
137+
138+ if "response" in chunk:
139+ return chunk["response"]
140+
141+
142+def pretty_print_messages(messages) -> None:
143+ for message in messages:
144+ if message["role"] != "assistant":
145+ continue
146+
147+ # print agent name in blue
148+ print(f"\033[94m{message['sender']}\033[0m:", end=" ")
149+
150+ # print response, if any
151+ if message["content"]:
152+ print(message["content"])
153+
154+ # print tool calls in purple, if any
155+ tool_calls = message.get("tool_calls") or []
156+ if len(tool_calls) > 1:
157+ print()
158+ for tool_call in tool_calls:
159+ f = tool_call["function"]
160+ name, args = f["name"], f["arguments"]
161+ arg_str = json.dumps(json.loads(args)).replace(":", "=")
162+ print(f"\033[95m{name}\033[0m({arg_str[1:-1]})")
163+
157164 def main():
158165 mode = choose_mode()
159166
@@ -169,3 +176,6 @@
169176 if __name__ == "__main__":
170177 print("Starting Based Agent...")
171178 main()
179+
180+
181+
added Based-Agent/twitter_utils.py +94 −0
@@ -0,0 +1,94 @@
1+import tweepy
2+from time import sleep
3+from typing import List, Dict, Optional
4+
5+class TwitterBot:
6+ def __init__(self, api_key: str, api_secret: str, access_token: str, access_token_secret: str):
7+ """Initialize Twitter bot with credentials"""
8+ auth = tweepy.OAuthHandler(api_key, api_secret)
9+ auth.set_access_token(access_token, access_token_secret)
10+ self.api = tweepy.API(auth)
11+
12+ def post_tweet(self, content: str) -> str:
13+ """
14+ Post a tweet
15+
16+ Args:
17+ content (str): The content of the tweet
18+
19+ Returns:
20+ str: Status message about the tweet
21+ """
22+ try:
23+ tweet = self.api.update_status(content)
24+ return f"Successfully posted tweet with ID: {tweet.id}"
25+ except tweepy.TweepError as e:
26+ return f"Error posting tweet: {str(e)}"
27+
28+ def read_mentions(self, count: int = 10) -> List[Dict]:
29+ """
30+ Read recent mentions
31+
32+ Args:
33+ count (int): Number of recent mentions to retrieve
34+
35+ Returns:
36+ List[Dict]: List of mention objects containing relevant information
37+ """
38+ try:
39+ mentions = self.api.mentions_timeline(count=count)
40+ return [{
41+ 'id': mention.id,
42+ 'text': mention.text,
43+ 'user': mention.user.screen_name,
44+ 'created_at': mention.created_at
45+ } for mention in mentions]
46+ except tweepy.TweepError as e:
47+ return [{'error': str(e)}]
48+
49+ def reply_to_tweet(self, tweet_id: str, content: str) -> str:
50+ """
51+ Reply to a specific tweet
52+
53+ Args:
54+ tweet_id (str): ID of the tweet to reply to
55+ content (str): Content of the reply
56+
57+ Returns:
58+ str: Status message about the reply
59+ """
60+ try:
61+ tweet = self.api.get_status(tweet_id)
62+ username = tweet.user.screen_name
63+ reply_content = f"@{username} {content}"
64+
65+ reply = self.api.update_status(
66+ status=reply_content,
67+ in_reply_to_status_id=tweet_id,
68+ auto_populate_reply_metadata=True
69+ )
70+ return f"Successfully replied to tweet {tweet_id}"
71+ except tweepy.TweepError as e:
72+ return f"Error replying to tweet: {str(e)}"
73+
74+ def search_tweets(self, query: str, count: int = 10) -> List[Dict]:
75+ """
76+ Search for tweets matching a query
77+
78+ Args:
79+ query (str): Search query
80+ count (int): Number of tweets to retrieve
81+
82+ Returns:
83+ List[Dict]: List of matching tweets
84+ """
85+ try:
86+ tweets = tweepy.Cursor(self.api.search, q=query).items(count)
87+ return [{
88+ 'id': tweet.id,
89+ 'text': tweet.text,
90+ 'user': tweet.user.screen_name,
91+ 'created_at': tweet.created_at
92+ } for tweet in tweets]
93+ except tweepy.TweepError as e:
94+ return [{'error': str(e)}]
No newline at the end of the file