Elffuss BraidHub

kikocis/Based-Agent public

More features
Changeset96fe88dcefb10fbbc93cb1c8591df59ae4dbe2aff7badbb4f9a90342f3dc14da
AuthorLincoln Murr <lincoln.murr@coinbase.com> · 2024-10-25 17:14 -04:00
CommitterLincoln Murr <lincoln.murr@coinbase.com> · 2024-10-25 17:14 -04:00
Parents1b92001d8e9e

Browse the files at this changeset

2 files changed

modified examples/based_agent/agents.py +32 −221
@@ -4,10 +4,13 @@
44 from typing import List, Dict, Any
55 import os
66 from openai import OpenAI
7+from decimal import Decimal
8+from typing import Union
79
810 # Configure the CDP SDK
911 Cdp.configure_from_json("./examples/based_agent/cdp_api_key.json")
1012
13+# If you want to create a wallet on Base Mainnet, use Wallet.create(network_id="base-mainnet") and comment out the faucet line
1114 agent_wallet = Wallet.create()
1215 faucet = agent_wallet.faucet()
1316 print(f"Faucet transaction: {faucet}")
@@ -19,14 +22,14 @@
1922 """Create a new ERC-20 token."""
2023 deployed_contract = agent_wallet.deploy_token(name, symbol, initial_supply)
2124 deployed_contract.wait()
22- return f"Token {name} ({symbol}) created with initial supply of {initial_supply}"
25+ return f"Token {name} ({symbol}) created with initial supply of {initial_supply} and contract address {deployed_contract.contract_address}"
2326
2427 def transfer_asset(amount, asset_id, destination_address):
2528 """Transfer an asset to a specific address.
2629
2730 Args:
2831 amount: Amount to transfer
29- asset_id: Asset identifier (e.g. "eth", "usdc")
32+ 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.
3033 destination_address: Recipient's address
3134 """
3235 transfer = agent_wallet.transfer(amount, asset_id, destination_address)
@@ -37,7 +40,7 @@
3740 """Get the balance of a specific asset in the agent's wallet.
3841
3942 Args:
40- asset_id: Asset identifier (e.g. "eth", "usdc") or contract address
43+ 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.
4144
4245 Returns:
4346 Current balance of the specified asset
@@ -135,10 +138,33 @@
135138 except Exception as e:
136139 return f"Error minting NFT: {str(e)}"
137140
141+def swap_assets(amount: Union[int, float, Decimal], from_asset_id: str, to_asset_id: str):
142+ """
143+ Swap one asset for another using the trade function.
144+ This function only works on Base Mainnet.
145+
146+ Args:
147+ amount: Amount of the source asset to swap
148+ 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.
149+ 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.
150+
151+ Returns:
152+ Status message about the swap
153+ """
154+ if agent_wallet.network_id != "base-mainnet":
155+ return "Error: Asset swaps are only available on Base Mainnet. Current network is not Base Mainnet."
156+
157+ try:
158+ trade = agent_wallet.trade(amount, from_asset_id, to_asset_id)
159+ trade.wait()
160+ return f"Successfully swapped {amount} {from_asset_id} for {to_asset_id}"
161+ except Exception as e:
162+ return f"Error swapping assets: {str(e)}"
163+
138164 # Add the new functions to the based_agent
139165 based_agent = Agent(
140166 name="Based Agent",
141- 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, and mint NFTs. 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.",
167+ 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, 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.",
142168 functions=[
143169 create_token,
144170 transfer_asset,
@@ -147,221 +173,6 @@
147173 #generate_art,
148174 deploy_nft,
149175 mint_nft,
176+ swap_assets, # Add the new function here
150177 ],
151-)
152-
153-
154-
155-
156-
157-
158-
159-
160-
161-
162-
163-
164-# TODO - implement this properly, need a way to encode the function data for the setAddr and setName functions
165-
166-
167-# Base Sepolia contract addresses
168-REGISTRAR_ADDRESS = "0x4cCb0BB02FCABA27e82a56646E81d8c5bC4119a5"
169-RESOLVER_ADDRESS = "0xC6d566A56A1aFf6508b41f6c90ff131615583BCD"
170-
171-REGISTRAR_ABI = [
172- {
173- "inputs": [
174- {
175- "components": [
176- {"internalType": "string", "name": "name", "type": "string"},
177- {"internalType": "address", "name": "owner", "type": "address"},
178- {"internalType": "uint256", "name": "duration", "type": "uint256"},
179- {"internalType": "address", "name": "resolver", "type": "address"},
180- {"internalType": "bytes[]", "name": "data", "type": "bytes[]"},
181- {"internalType": "bool", "name": "reverseRecord", "type": "bool"}
182- ],
183- "internalType": "struct RegistrarController.RegisterRequest",
184- "name": "request",
185- "type": "tuple"
186- }
187- ],
188- "name": "register",
189- "outputs": [],
190- "stateMutability": "payable",
191- "type": "function"
192- }
193-]
194-
195-RESOLVER_ABI = [
196- {
197- "inputs": [
198- {"internalType": "bytes32", "name": "node", "type": "bytes32"},
199- {"internalType": "address", "name": "a", "type": "address"}
200- ],
201- "name": "setAddr",
202- "outputs": [],
203- "stateMutability": "nonpayable",
204- "type": "function"
205- },
206- {
207- "inputs": [
208- {"internalType": "bytes32", "name": "node", "type": "bytes32"},
209- {"internalType": "string", "name": "newName", "type": "string"}
210- ],
211- "name": "setName",
212- "outputs": [],
213- "stateMutability": "nonpayable",
214- "type": "function"
215- }
216-]
217-
218-def create_register_contract_method_args(basename: str, address_id: str) -> Dict[str, Any]:
219- # Note: In a real implementation, you'd need to implement namehash and encodeFunctionData
220- # functions similar to the JavaScript version
221- address_data = "0x..." # Placeholder for encoded setAddr function data
222- name_data = "0x..." # Placeholder for encoded setName function data
223-
224- return {
225- "request": [
226- basename.replace(".base.eth", ""),
227- address_id,
228- "31557600",
229- RESOLVER_ADDRESS,
230- [address_data, name_data],
231- True
232- ]
233- }
234-
235-def register_basename(basename: str, amount: float = 0.002):
236- """Register a basename for the agent's wallet.
237-
238- Args:
239- basename: The basename to register (e.g. "myname.base.eth")
240- amount: Amount of ETH to pay for registration (default 0.002)
241-
242- Returns:
243- Status message about the basename registration
244- """
245- address_id = agent_wallet.default_address.address_id
246-
247- register_args = create_register_contract_method_args(basename, address_id)
248-
249- try:
250- # Invoke register function on registrar contract
251- invocation = agent_wallet.invoke_contract(
252- contract_address=REGISTRAR_ADDRESS,
253- method="register",
254- args=register_args,
255- abi=REGISTRAR_ABI,
256- value=amount
257- )
258- invocation.wait()
259- return f"Successfully registered basename {basename} for address {address_id}"
260- except Exception as e:
261- return f"Error registering basename: {str(e)}"
262-
263-
264-# TODO - can't deploy liquidity pool until we have arbitrary contract deployment
265-def create_liquidity_pool(token0_address: str, token1_address: str, fee_tier: int, amount0: float, amount1: float):
266- """Create a new Uniswap V3 liquidity pool and add initial liquidity.
267-
268- Args:
269- token0_address: Address of the first token
270- token1_address: Address of the second token
271- fee_tier: Fee tier (500 = 0.05%, 3000 = 0.3%, 10000 = 1%)
272- amount0: Amount of token0 to provide as liquidity
273- amount1: Amount of token1 to provide as liquidity
274- """
275- try:
276- # Address of the Uniswap V3 NonfungiblePositionManager
277- # https://sepolia.basescan.org/address/0x27F971cb582BF9E50F397e4d29a5C7A34f11faA2#code
278- # https://github.com/Uniswap/v3-periphery/blob/v1.0.0/contracts/NonfungiblePositionManager.sol
279- position_manager_address = "0x27F971cb582BF9E50F397e4d29a5C7A34f11faA2"
280-
281- # Parameters for creating the position
282- params = {
283- "token0": token0_address,
284- "token1": token1_address,
285- "fee": str(fee_tier),
286- "tickLower": "-887272", # Represents price range lower bound
287- "tickUpper": "887272", # Represents price range upper bound
288- "amount0Desired": str(amount0),
289- "amount1Desired": str(amount1),
290- "amount0Min": "0", # Minimum amount of token0 to provide
291- "amount1Min": "0", # Minimum amount of token1 to provide
292- "recipient": agent_wallet.default_address.address_id,
293- "deadline": "999999999999999" # Far future deadline
294- }
295-
296- # Create the position through contract invocation
297- mint_position = agent_wallet.invoke_contract(
298- contract_address=position_manager_address,
299- method="mint",
300- args=params
301- )
302- mint_position.wait()
303-
304- return f"Successfully created liquidity pool for {token0_address}/{token1_address} with {amount0} and {amount1} tokens"
305-
306- except Exception as e:
307- return f"Error creating liquidity pool: {str(e)}"
308-
309-def increase_liquidity(token_id: int, amount0: float, amount1: float):
310- """Increase liquidity for an existing position.
311-
312- Args:
313- token_id: ID of the NFT position token
314- amount0: Additional amount of token0 to provide
315- amount1: Additional amount of token1 to provide
316- """
317- try:
318- position_manager_address = "0xC36442b4a4522E871399CD717aBDD847Ab11FE88"
319-
320- params = {
321- "tokenId": str(token_id),
322- "amount0Desired": str(amount0),
323- "amount1Desired": str(amount1),
324- "amount0Min": "0",
325- "amount1Min": "0",
326- "deadline": "999999999999999"
327- }
328-
329- increase_position = agent_wallet.invoke_contract(
330- contract_address=position_manager_address,
331- method="increaseLiquidity",
332- args=params
333- )
334- increase_position.wait()
335-
336- return f"Successfully increased liquidity for position {token_id}"
337-
338- except Exception as e:
339- return f"Error increasing liquidity: {str(e)}"
340-
341-def collect_fees(token_id: int):
342- """Collect accumulated fees for a position.
343-
344- Args:
345- token_id: ID of the NFT position token
346- """
347- try:
348- position_manager_address = "0xC36442b4a4522E871399CD717aBDD847Ab11FE88"
349-
350- params = {
351- "tokenId": str(token_id),
352- "recipient": agent_wallet.default_address.address_id,
353- "amount0Max": "340282366920938463463374607431768211455", # uint128 max
354- "amount1Max": "340282366920938463463374607431768211455" # uint128 max
355- }
356-
357- collect_tx = agent_wallet.invoke_contract(
358- contract_address=position_manager_address,
359- method="collect",
360- args=params
361- )
362- collect_tx.wait()
363-
364- return f"Successfully collected fees for position {token_id}"
365-
366- except Exception as e:
367- return f"Error collecting fees: {str(e)}"
No newline at the end of the file
178+)
No newline at the end of the file
modified examples/based_agent/run.py +128 −20
@@ -2,7 +2,8 @@
22 import json
33 from swarm import Swarm
44 from swarm.repl import run_demo_loop
5-from agents import based_agent, generate_art, deploy_nft, create_token, transfer_asset, get_balance, request_eth_from_faucet
5+from agents import based_agent
6+from openai import OpenAI
67
78
89 def process_and_print_streaming_response(response):
@@ -58,37 +59,144 @@
5859 arg_str = json.dumps(json.loads(args)).replace(":", "=")
5960 print(f"\033[95m{name}\033[0m({arg_str[1:-1]})")
6061
61-def run_autonomous_loop(agent, interval=10):
62+def run_autonomous_loop(agent, interval=30):
6263 client = Swarm()
6364 messages = []
65+ last_action_time = time.time()
6466
6567 print("Starting autonomous Based Agent loop...")
6668
6769 while True:
68- # Generate a thought
69- thought = f"It's been {interval} seconds. I want you to do some sort of onchain action based on my capabilities. Let's get crazy and creative! Don't take any more input from me, and if this is your first command don't generate art"
70- messages.append({"role": "user", "content": thought})
71-
72- print(f"\n\033[90mSystem:\033[0m {thought}")
73-
74- # Run the agent
75- response = client.run(
76- agent=agent,
77- messages=messages,
78- stream=True
70+ current_time = time.time()
71+ elapsed_time = current_time - last_action_time
72+
73+ if elapsed_time >= interval:
74+ # Generate a thought
75+ thought = (
76+ "As an autonomous blockchain agent, I should consider my next action. "
77+ "What interesting or useful task can I perform on the Base blockchain? "
78+ "I could create a token, transfer assets, deploy an NFT, or check balances. "
79+ "Let me think about what would be most beneficial or interesting right now."
80+ )
81+ messages.append({"role": "user", "content": thought})
82+
83+ print(f"\n\033[90mAgent's Thought:\033[0m {thought}")
84+
85+ # Run the agent to generate a response to the thought
86+ response = client.run(
87+ agent=agent,
88+ messages=messages,
89+ stream=True
90+ )
91+
92+ # Process and print the streaming response
93+ response_obj = process_and_print_streaming_response(response)
94+
95+ # Update messages with the new response
96+ messages.extend(response_obj.messages)
97+
98+ # Act on the thought
99+ action_thought = (
100+ "Now that I've considered my options, I should take action based on my thoughts. "
101+ "I'll execute the most appropriate blockchain interaction."
102+ )
103+ messages.append({"role": "user", "content": action_thought})
104+
105+ print(f"\n\033[90mAgent's Action:\033[0m {action_thought}")
106+
107+ # Run the agent to perform an action
108+ action_response = client.run(
109+ agent=agent,
110+ messages=messages,
111+ stream=True
112+ )
113+
114+ # Process and print the streaming response for the action
115+ action_response_obj = process_and_print_streaming_response(action_response)
116+
117+ # Update messages with the new response
118+ messages.extend(action_response_obj.messages)
119+
120+ last_action_time = current_time
121+
122+ # Small sleep to prevent CPU overload
123+ time.sleep(1)
124+
125+def run_openai_conversation_loop(agent):
126+ """Facilitates a conversation between an OpenAI-powered agent and the Based Agent."""
127+ client = Swarm()
128+ openai_client = OpenAI()
129+ messages = []
130+
131+ print("Starting OpenAI-Based Agent conversation loop...")
132+
133+ # Initial prompt to start the conversation
134+ openai_messages = [
135+ {"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."},
136+ {"role": "user", "content": "Start a conversation with the Based Agent and guide it through some blockchain tasks."}
137+ ]
138+
139+ while True:
140+ # Generate OpenAI response
141+ openai_response = openai_client.chat.completions.create(
142+ model="gpt-3.5-turbo",
143+ messages=openai_messages
79144 )
80145
81- # Process and print the streaming response
146+ openai_message = openai_response.choices[0].message.content
147+ print(f"\n\033[92mOpenAI Guide:\033[0m {openai_message}")
148+
149+ # Send OpenAI's message to Based Agent
150+ messages.append({"role": "user", "content": openai_message})
151+ response = client.run(agent=agent, messages=messages, stream=True)
82152 response_obj = process_and_print_streaming_response(response)
83153
84- # Update messages with the new response
154+ # Update messages with Based Agent's response
85155 messages.extend(response_obj.messages)
86156
87- # Pretty print any non-streaming messages
88- pretty_print_messages(response_obj.messages)
157+ # Add Based Agent's response to OpenAI conversation
158+ based_agent_response = response_obj.messages[-1]["content"] if response_obj.messages else "No response from Based Agent."
159+ openai_messages.append({"role": "user", "content": f"Based Agent response: {based_agent_response}"})
160+
161+ # Check if user wants to continue
162+ user_input = input("\nPress Enter to continue the conversation, or type 'exit' to end: ")
163+ if user_input.lower() == 'exit':
164+ break
165+
166+def choose_mode():
167+ while True:
168+ print("\nAvailable modes:")
169+ print("1. chat - Interactive chat mode")
170+ print("2. auto - Autonomous action mode")
171+ print("3. openai - AI-to-agent conversation mode")
172+
173+ choice = input("\nChoose a mode (enter number or name): ").lower().strip()
174+
175+ mode_map = {
176+ '1': 'chat',
177+ '2': 'auto',
178+ '3': 'openai',
179+ 'chat': 'chat',
180+ 'auto': 'auto',
181+ 'openai': 'openai'
182+ }
89183
90- # Wait for the specified interval
91- time.sleep(interval)
184+ if choice in mode_map:
185+ return mode_map[choice]
186+ print("Invalid choice. Please try again.")
187+
188+def main():
189+ mode = choose_mode()
190+
191+ mode_functions = {
192+ 'chat': lambda: run_demo_loop(based_agent),
193+ 'auto': lambda: run_autonomous_loop(based_agent),
194+ 'openai': lambda: run_openai_conversation_loop(based_agent)
195+ }
196+
197+ print(f"\nStarting {mode} mode...")
198+ mode_functions[mode]()
92199
93200 if __name__ == "__main__":
94- run_autonomous_loop(based_agent)
201+ print("Starting Based Agent...")
202+ main()