| 1 | import time |
| 2 | import json |
| 3 | from swarm import Swarm |
| 4 | from swarm.repl import run_demo_loop |
| 5 | from agents import based_agent |
| 6 | from openai import OpenAI |
| 7 | |
| 8 | |
| 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]})") |
| 61 | |
| 62 | def run_autonomous_loop(agent, interval=30): |
| 63 | client = Swarm() |
| 64 | messages = [] |
| 65 | last_action_time = time.time() |
| 66 | |
| 67 | print("Starting autonomous Based Agent loop...") |
| 68 | |
| 69 | while 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 |
| 144 | ) |
| 145 | |
| 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) |
| 152 | response_obj = process_and_print_streaming_response(response) |
| 153 | |
| 154 | # Update messages with Based Agent's response |
| 155 | messages.extend(response_obj.messages) |
| 156 | |
| 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 | } |
| 183 | |
| 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]() |
| 199 | |
| 200 | if __name__ == "__main__": |
| 201 | print("Starting Based Agent...") |
| 202 | main() |