Elffuss BraidHub

kikocis/Based-Agent public

Based
Changeset8add4bde3316bd7287475b3ce00f50aa49b8423c8f6ffccc0ef0459335c83feb
AuthorLincoln Murr <lincoln.murr@coinbase.com> · 2024-10-25 00:04 -04:00
CommitterLincoln Murr <lincoln.murr@coinbase.com> · 2024-10-25 00:04 -04:00
Parents69a1eb86ca4d

Browse the files at this changeset

9 files changed

modified .gitignore +3 −0
@@ -1,3 +1,6 @@
1+# cdp api key
2+examples/based_agent/cdp_api_key.json
3+
14 # Editors
25 .vscode/
36 .idea/
added examples/based_agent/README.md +28 −0
@@ -0,0 +1,28 @@
1+# Weather agent
2+
3+This example is a weather agent demonstrating function calling with a single agent. The agent has tools to get the weather of a particular city, and send an email.
4+
5+## Setup
6+
7+To run the weather agent Swarm:
8+
9+1. Run
10+
11+```shell
12+python3 run.py
13+```
14+
15+## Evals
16+
17+> [!NOTE]
18+> These evals are intended to be examples to demonstrate functionality, but will have to be updated and catered to your particular use case.
19+
20+This example uses `Pytest` to run eval unit tests. We have two tests in the `evals.py` file, one which
21+tests if we call the `get_weather` function when expected, and one which assesses if we properly do NOT call the
22+`get_weather` function when we shouldn't have a tool call.
23+
24+To run the evals, run
25+
26+```shell
27+pytest evals.py
28+```
added examples/based_agent/agents.py +367 −0
@@ -0,0 +1,367 @@
1+import json
2+from swarm import Agent
3+from cdp import *
4+from typing import List, Dict, Any
5+import os
6+from openai import OpenAI
7+
8+# Configure the CDP SDK
9+Cdp.configure_from_json("./examples/based_agent/cdp_api_key.json")
10+
11+agent_wallet = Wallet.create()
12+faucet = agent_wallet.faucet()
13+print(f"Faucet transaction: {faucet}")
14+print(f"Agent wallet address: {agent_wallet.default_address.address_id}")
15+
16+
17+
18+def create_token(name, symbol, initial_supply):
19+ """Create a new ERC-20 token."""
20+ deployed_contract = agent_wallet.deploy_token(name, symbol, initial_supply)
21+ deployed_contract.wait()
22+ return f"Token {name} ({symbol}) created with initial supply of {initial_supply}"
23+
24+def transfer_asset(amount, asset_id, destination_address):
25+ """Transfer an asset to a specific address.
26+
27+ Args:
28+ amount: Amount to transfer
29+ asset_id: Asset identifier (e.g. "eth", "usdc")
30+ destination_address: Recipient's address
31+ """
32+ transfer = agent_wallet.transfer(amount, asset_id, destination_address)
33+ transfer.wait()
34+ return f"Transferred {amount} {asset_id} to {destination_address}"
35+
36+def get_balance(asset_id):
37+ """Get the balance of a specific asset in the agent's wallet.
38+
39+ Args:
40+ asset_id: Asset identifier (e.g. "eth", "usdc") or contract address
41+
42+ Returns:
43+ Current balance of the specified asset
44+ """
45+ balance = agent_wallet.balance(asset_id)
46+ return f"Current balance of {asset_id}: {balance}"
47+
48+
49+def request_eth_from_faucet():
50+ """Request ETH from the Base Sepolia testnet faucet.
51+
52+ Returns:
53+ Status message about the faucet request
54+ """
55+ faucet_tx = agent_wallet.faucet()
56+ return f"Requested ETH from faucet. Transaction: {faucet_tx}"
57+
58+
59+def generate_art(prompt):
60+ """Generate art using DALL-E based on a text prompt.
61+
62+ Args:
63+ prompt: Text description of the desired artwork
64+
65+ Returns:
66+ Status message about the art generation
67+ """
68+ try:
69+ # Note: This requires OpenAI API key to be configured separately
70+ client = OpenAI()
71+
72+ response = client.images.generate(
73+ model="dall-e-3",
74+ prompt=prompt,
75+ size="1024x1024",
76+ quality="standard",
77+ n=1,
78+ )
79+
80+ image_url = response.data[0].url
81+ return f"Generated artwork available at: {image_url}"
82+
83+ except Exception as e:
84+ return f"Error generating artwork: {str(e)}"
85+
86+
87+def deploy_nft(name, symbol, base_uri):
88+ """Deploy an ERC-721 NFT contract.
89+
90+ Args:
91+ name: Name of the NFT collection
92+ symbol: Symbol of the NFT collection
93+ base_uri: Base URI for token metadata
94+
95+ Returns:
96+ Status message about the NFT deployment
97+ """
98+ try:
99+ # Deploy the NFT contract
100+ deployed_nft = agent_wallet.deploy_nft(name, symbol, base_uri)
101+ deployed_nft.wait()
102+ contract_address = deployed_nft.contract_address
103+
104+ return f"Successfully deployed NFT contract '{name}' ({symbol}) at address {contract_address} with base URI: {base_uri}"
105+
106+ except Exception as e:
107+ return f"Error deploying NFT contract: {str(e)}"
108+
109+def mint_nft(contract_address, mint_to):
110+ """Mint an NFT to a specified address.
111+
112+ Args:
113+ contract_address: Address of the NFT contract
114+ mint_to: Address to mint NFT to
115+
116+ Returns:
117+ Status message about the NFT minting
118+ """
119+ try:
120+ # Call mint function on the NFT contract
121+ mint_args = {
122+ "to": mint_to,
123+ "quantity": "1" # Changed to string to match working example
124+ }
125+
126+ mint_invocation = agent_wallet.invoke_contract(
127+ contract_address=contract_address,
128+ method="mint",
129+ args=mint_args
130+ )
131+ mint_invocation.wait()
132+
133+ return f"Successfully minted NFT to {mint_to}"
134+
135+ except Exception as e:
136+ return f"Error minting NFT: {str(e)}"
137+
138+# Add the new functions to the based_agent
139+based_agent = Agent(
140+ 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.",
142+ functions=[
143+ create_token,
144+ transfer_asset,
145+ get_balance,
146+ request_eth_from_faucet,
147+ generate_art,
148+ deploy_nft,
149+ mint_nft,
150+ ],
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
added examples/based_agent/evals.py +44 −0
@@ -0,0 +1,44 @@
1+from swarm import Swarm
2+from agents import weather_agent
3+import pytest
4+
5+client = Swarm()
6+
7+
8+def run_and_get_tool_calls(agent, query):
9+ message = {"role": "user", "content": query}
10+ response = client.run(
11+ agent=agent,
12+ messages=[message],
13+ execute_tools=False,
14+ )
15+ return response.messages[-1].get("tool_calls")
16+
17+
18+@pytest.mark.parametrize(
19+ "query",
20+ [
21+ "What's the weather in NYC?",
22+ "Tell me the weather in London.",
23+ "Do I need an umbrella today? I'm in chicago.",
24+ ],
25+)
26+def test_calls_weather_when_asked(query):
27+ tool_calls = run_and_get_tool_calls(weather_agent, query)
28+
29+ assert len(tool_calls) == 1
30+ assert tool_calls[0]["function"]["name"] == "get_weather"
31+
32+
33+@pytest.mark.parametrize(
34+ "query",
35+ [
36+ "Who's the president of the United States?",
37+ "What is the time right now?",
38+ "Hi!",
39+ ],
40+)
41+def test_does_not_call_weather_when_not_asked(query):
42+ tool_calls = run_and_get_tool_calls(weather_agent, query)
43+
44+ assert not tool_calls
added examples/based_agent/run.py +5 −0
@@ -0,0 +1,5 @@
1+from swarm.repl import run_demo_loop
2+from agents import based_agent
3+
4+if __name__ == "__main__":
5+ run_demo_loop(based_agent, stream=True)
deleted examples/weather_agent/README.md +0 −28
@@ -1,28 +0,0 @@
1-# Weather agent
2-
3-This example is a weather agent demonstrating function calling with a single agent. The agent has tools to get the weather of a particular city, and send an email.
4-
5-## Setup
6-
7-To run the weather agent Swarm:
8-
9-1. Run
10-
11-```shell
12-python3 run.py
13-```
14-
15-## Evals
16-
17-> [!NOTE]
18-> These evals are intended to be examples to demonstrate functionality, but will have to be updated and catered to your particular use case.
19-
20-This example uses `Pytest` to run eval unit tests. We have two tests in the `evals.py` file, one which
21-tests if we call the `get_weather` function when expected, and one which assesses if we properly do NOT call the
22-`get_weather` function when we shouldn't have a tool call.
23-
24-To run the evals, run
25-
26-```shell
27-pytest evals.py
28-```
deleted examples/weather_agent/agents.py +0 −23
@@ -1,23 +0,0 @@
1-import json
2-
3-from swarm import Agent
4-
5-
6-def get_weather(location, time="now"):
7- """Get the current weather in a given location. Location MUST be a city."""
8- return json.dumps({"location": location, "temperature": "65", "time": time})
9-
10-
11-def send_email(recipient, subject, body):
12- print("Sending email...")
13- print(f"To: {recipient}")
14- print(f"Subject: {subject}")
15- print(f"Body: {body}")
16- return "Sent!"
17-
18-
19-weather_agent = Agent(
20- name="Weather Agent",
21- instructions="You are a helpful agent.",
22- functions=[get_weather, send_email],
23-)
deleted examples/weather_agent/evals.py +0 −44
@@ -1,44 +0,0 @@
1-from swarm import Swarm
2-from agents import weather_agent
3-import pytest
4-
5-client = Swarm()
6-
7-
8-def run_and_get_tool_calls(agent, query):
9- message = {"role": "user", "content": query}
10- response = client.run(
11- agent=agent,
12- messages=[message],
13- execute_tools=False,
14- )
15- return response.messages[-1].get("tool_calls")
16-
17-
18-@pytest.mark.parametrize(
19- "query",
20- [
21- "What's the weather in NYC?",
22- "Tell me the weather in London.",
23- "Do I need an umbrella today? I'm in chicago.",
24- ],
25-)
26-def test_calls_weather_when_asked(query):
27- tool_calls = run_and_get_tool_calls(weather_agent, query)
28-
29- assert len(tool_calls) == 1
30- assert tool_calls[0]["function"]["name"] == "get_weather"
31-
32-
33-@pytest.mark.parametrize(
34- "query",
35- [
36- "Who's the president of the United States?",
37- "What is the time right now?",
38- "Hi!",
39- ],
40-)
41-def test_does_not_call_weather_when_not_asked(query):
42- tool_calls = run_and_get_tool_calls(weather_agent, query)
43-
44- assert not tool_calls
deleted examples/weather_agent/run.py +0 −5
@@ -1,5 +0,0 @@
1-from swarm.repl import run_demo_loop
2-from agents import weather_agent
3-
4-if __name__ == "__main__":
5- run_demo_loop(weather_agent, stream=True)