Elffuss BraidHub

kikocis/Based-Agent public

Cleaned up + upgraded
Changeset653c48ff15c3252ec2dc989e22439011e549a522c03b01ce7a2cbeaec1b8b4f2
AuthorLincoln Murr <lincoln.murr@coinbase.com> · 2024-10-25 17:30 -04:00
CommitterLincoln Murr <lincoln.murr@coinbase.com> · 2024-10-25 17:30 -04:00
Parents0c78bfc92685

Browse the files at this changeset

2 files changed

modified Based-Agent/agents.py +4 −10
@@ -1,20 +1,14 @@
1-from cdp import Cdp, Wallet # Changed from cdp_sdk to cdp
21 import json
32 from swarm import Agent
3+from cdp import *
44 from typing import List, Dict, Any
55 import os
66 from openai import OpenAI
77 from decimal import Decimal
88 from typing import Union
99
10-# Get configuration from environment variables
11-API_KEY_NAME = os.environ.get("CDP_API_KEY_NAME")
12-PRIVATE_KEY = os.environ.get("CDP_PRIVATE_KEY", "").replace('\\n', '\n')
13-
14-# Configure CDP with environment variables
15-Cdp.configure(API_KEY_NAME, PRIVATE_KEY)
16-agent_wallet = Wallet.create()
17-print(f"Agent wallet address: {agent_wallet.default_address.address_id}")
10+# Configure the CDP SDK
11+Cdp.configure_from_json("./examples/based_agent/cdp_api_key.json")
1812
1913 # If you want to create a wallet on Base Mainnet, use Wallet.create(network_id="base-mainnet") and comment out the faucet line
2014 agent_wallet = Wallet.create()
@@ -181,4 +175,4 @@
181175 mint_nft,
182176 swap_assets, # Add the new function here
183177 ],
184-)
No newline at the end of the file
178+)
modified Based-Agent/run.py +94 −16
@@ -2,8 +2,9 @@
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
6-import os
5+from agents import based_agent
6+from openai import OpenAI
7+
78
89 def process_and_print_streaming_response(response):
910 content = ""
@@ -35,6 +36,7 @@
3536 if "response" in chunk:
3637 return chunk["response"]
3738
39+
3840 def pretty_print_messages(messages) -> None:
3941 for message in messages:
4042 if message["role"] != "assistant":
@@ -60,34 +62,110 @@
6062 def run_autonomous_loop(agent, interval=10):
6163 client = Swarm()
6264 messages = []
63-
65+
6466 print("Starting autonomous Based Agent loop...")
65-
67+
6668 while True:
6769 # Generate a thought
68- 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+ thought = (
71+ "Be creative and do something interesting on the Base blockchain. "
72+ "Don't take any more input from me. Choose an action and execute it now."
73+ )
6974 messages.append({"role": "user", "content": thought})
70-
71- print(f"\n\033[90mSystem:\033[0m {thought}")
72-
73- # Run the agent
75+
76+ print(f"\n\033[90mAgent's Thought:\033[0m {thought}")
77+
78+ # Run the agent to generate a response and take action
7479 response = client.run(
7580 agent=agent,
7681 messages=messages,
7782 stream=True
7883 )
79-
84+
8085 # Process and print the streaming response
8186 response_obj = process_and_print_streaming_response(response)
82-
87+
8388 # Update messages with the new response
8489 messages.extend(response_obj.messages)
85-
86- # Pretty print any non-streaming messages
87- pretty_print_messages(response_obj.messages)
88-
90+
8991 # Wait for the specified interval
9092 time.sleep(interval)
9193
94+def run_openai_conversation_loop(agent):
95+ """Facilitates a conversation between an OpenAI-powered agent and the Based Agent."""
96+ client = Swarm()
97+ openai_client = OpenAI()
98+ messages = []
99+
100+ print("Starting OpenAI-Based Agent conversation loop...")
101+
102+ # Initial prompt to start the conversation
103+ 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."},
105+ {"role": "user", "content": "Start a conversation with the Based Agent and guide it through some blockchain tasks."}
106+ ]
107+
108+ while True:
109+ # Generate OpenAI response
110+ openai_response = openai_client.chat.completions.create(
111+ model="gpt-3.5-turbo",
112+ messages=openai_messages
113+ )
114+
115+ openai_message = openai_response.choices[0].message.content
116+ print(f"\n\033[92mOpenAI Guide:\033[0m {openai_message}")
117+
118+ # Send OpenAI's message to Based Agent
119+ messages.append({"role": "user", "content": openai_message})
120+ response = client.run(agent=agent, messages=messages, stream=True)
121+ response_obj = process_and_print_streaming_response(response)
122+
123+ # Update messages with Based Agent's response
124+ messages.extend(response_obj.messages)
125+
126+ # Add Based Agent's response to OpenAI conversation
127+ based_agent_response = response_obj.messages[-1]["content"] if response_obj.messages else "No response from Based Agent."
128+ openai_messages.append({"role": "user", "content": f"Based Agent response: {based_agent_response}"})
129+
130+ # Check if user wants to continue
131+ user_input = input("\nPress Enter to continue the conversation, or type 'exit' to end: ")
132+ if user_input.lower() == 'exit':
133+ break
134+
135+def choose_mode():
136+ while True:
137+ print("\nAvailable modes:")
138+ print("1. chat - Interactive chat mode")
139+ print("2. auto - Autonomous action mode")
140+ print("3. openai - AI-to-agent conversation mode")
141+
142+ choice = input("\nChoose a mode (enter number or name): ").lower().strip()
143+
144+ mode_map = {
145+ '1': 'chat',
146+ '2': 'auto',
147+ '3': 'openai',
148+ 'chat': 'chat',
149+ 'auto': 'auto',
150+ 'openai': 'openai'
151+ }
152+
153+ if choice in mode_map:
154+ return mode_map[choice]
155+ print("Invalid choice. Please try again.")
156+
157+def main():
158+ mode = choose_mode()
159+
160+ mode_functions = {
161+ 'chat': lambda: run_demo_loop(based_agent),
162+ 'auto': lambda: run_autonomous_loop(based_agent),
163+ 'openai': lambda: run_openai_conversation_loop(based_agent)
164+ }
165+
166+ print(f"\nStarting {mode} mode...")
167+ mode_functions[mode]()
168+
92169 if __name__ == "__main__":
93- run_autonomous_loop(based_agent)
No newline at the end of the file
170+ print("Starting Based Agent...")
171+ main()
No newline at the end of the file