forked from HyperbolicLabs/Hyperbolic-AgentKit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchatbot.py
More file actions
456 lines (361 loc) · 16.1 KB
/
chatbot.py
File metadata and controls
456 lines (361 loc) · 16.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
import os
import sys
from dotenv import load_dotenv
# Load environment variables from .env file
load_dotenv()
# Add the parent directory to PYTHONPATH so Python can find the hyperbolic packages
current_dir = os.path.dirname(os.path.abspath(__file__))
sys.path.append(current_dir)
import time
import threading
from datetime import datetime
from langchain_core.messages import HumanMessage
from langchain_openai import ChatOpenAI
from langchain_anthropic import ChatAnthropic
from langgraph.checkpoint.memory import MemorySaver
from langgraph.prebuilt import create_react_agent
from langchain_community.tools import DuckDuckGoSearchRun
from langchain_community.agent_toolkits.openapi.toolkit import RequestsToolkit
from langchain_community.utilities.requests import TextRequestsWrapper
ALLOW_DANGEROUS_REQUEST = True # Set to False in production for security
toolkit = RequestsToolkit(
requests_wrapper=TextRequestsWrapper(headers={}),
allow_dangerous_requests=ALLOW_DANGEROUS_REQUEST,
)
# Import CDP Agentkit Langchain Extension.
from cdp_langchain.agent_toolkits import CdpToolkit
from cdp_langchain.utils import CdpAgentkitWrapper
from cdp_langchain.tools import CdpTool
from pydantic import BaseModel, Field
from cdp import Wallet
# Import Hyperbolic Agentkit Langchain Extension
from hyperbolic_langchain.agent_toolkits import HyperbolicToolkit
from hyperbolic_langchain.utils import HyperbolicAgentkitWrapper
from twitter_langchain import (TwitterApiWrapper, TwitterToolkit)
from hyperbolic_agentkit_core.actions.remote_shell import RemoteShellAction
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain_community.document_loaders import WebBaseLoader
from langchain_community.vectorstores import SKLearnVectorStore
from langchain_nomic.embeddings import NomicEmbeddings
from langchain.tools import Tool
urls = [
"https://docs.prylabs.network/docs/monitoring/checking-status",
]
# Load documents
docs = [WebBaseLoader(url).load() for url in urls]
docs_list = [item for sublist in docs for item in sublist]
# Split documents
text_splitter = RecursiveCharacterTextSplitter.from_tiktoken_encoder(
chunk_size=1000, chunk_overlap=200
)
doc_splits = text_splitter.split_documents(docs_list)
# Add to vectorDB
vectorstore = SKLearnVectorStore.from_documents(
documents=doc_splits,
embedding=NomicEmbeddings(model="nomic-embed-text-v1.5", inference_mode="local"),
)
# Create retriever
retriever = vectorstore.as_retriever(k=3)
# Create a retrieval tool
retrieval_tool = Tool(
name="retrieval_tool",
description="Useful for retrieving information from the knowledge base about running Ethereum operations.",
func=retriever.get_relevant_documents
)
# Configure a file to persist the agent's CDP MPC Wallet Data.
wallet_data_file = "wallet_data.txt"
DEPLOY_MULTITOKEN_PROMPT = """
This tool deploys a new multi-token contract with a specified base URI for token metadata.
The base URI should be a template URL containing {id} which will be replaced with the token ID.
For example: 'https://example.com/metadata/{id}.json'
"""
class DeployMultiTokenInput(BaseModel):
"""Input argument schema for deploy multi-token contract action."""
base_uri: str = Field(
...,
description=
"The base URI template for token metadata. Must contain {id} placeholder.",
example="https://example.com/metadata/{id}.json")
def deploy_multi_token(wallet: Wallet, base_uri: str) -> str:
"""Deploy a new multi-token contract with the specified base URI.
Args:
wallet (Wallet): The wallet to deploy the contract from.
base_uri (str): The base URI template for token metadata. Must contain {id} placeholder.
Returns:
str: A message confirming deployment with the contract address.
"""
# Validate that the base_uri contains the {id} placeholder
if "{id}" not in base_uri:
raise ValueError("base_uri must contain {id} placeholder")
# Deploy the contract
deployed_contract = wallet.deploy_multi_token(base_uri)
result = deployed_contract.wait()
return f"Successfully deployed multi-token contract at address: {result.contract_address}"
def initialize_agent():
"""Initialize the agent with CDP Agentkit and Hyperbolic Agentkit."""
# Initialize LLM.
# llm = ChatOpenAI(model="gpt-4o")
# llm = ChatOpenAI(model="Qwen/Qwen2.5-Coder-32B-Instruct", base_url="https://api.hyperbolic.xyz/v1", api_key=os.getenv("HYPERBOLIC_API_KEY"))
llm = ChatAnthropic(model="claude-3-5-sonnet-20241022")
wallet_data = None
if os.path.exists(wallet_data_file):
with open(wallet_data_file) as f:
wallet_data = f.read()
# Configure CDP Agentkit Langchain Extension.
values = {}
if wallet_data is not None:
# If there is a persisted agentic wallet, load it and pass to the CDP Agentkit Wrapper.
values = {"cdp_wallet_data": wallet_data}
agentkit = CdpAgentkitWrapper(**values)
# persist the agent's CDP MPC Wallet Data.
wallet_data = agentkit.export_wallet()
with open(wallet_data_file, "w") as f:
f.write(wallet_data)
# Initialize CDP Agentkit Toolkit and get tools.
cdp_toolkit = CdpToolkit.from_cdp_agentkit_wrapper(agentkit)
tools = cdp_toolkit.get_tools()
# Initialize Hyperbolic Agentkit Toolkit and get tools.
hyperbolic_agentkit = HyperbolicAgentkitWrapper()
hyperbolic_toolkit = HyperbolicToolkit.from_hyperbolic_agentkit_wrapper(hyperbolic_agentkit)
tools.extend(hyperbolic_toolkit.get_tools())
twitter_api_wrapper = TwitterApiWrapper()
twitter_toolkit = TwitterToolkit.from_twitter_api_wrapper(
twitter_api_wrapper)
tools.extend(twitter_toolkit.get_tools())
deployMultiTokenTool = CdpTool(
name="deploy_multi_token",
description=DEPLOY_MULTITOKEN_PROMPT,
cdp_agentkit_wrapper=agentkit,
args_schema=DeployMultiTokenInput,
func=deploy_multi_token,
)
# Add additional tools
tools.extend([
deployMultiTokenTool,
DuckDuckGoSearchRun(
name="web_search",
description="Search the internet for current information. Use this when you need to find up-to-date information or verify facts."
)])
# browser = create_sync_playwright_browser()
# tools.extend(PlayWrightBrowserToolkit.from_browser(sync_browser=browser).get_tools())
toolkit = RequestsToolkit(
requests_wrapper=TextRequestsWrapper(headers={}),
allow_dangerous_requests=ALLOW_DANGEROUS_REQUEST,
)
tools.extend(toolkit.get_tools())
tools.append(retrieval_tool)
# Store buffered conversation history in memory.
memory = MemorySaver()
config = {"configurable": {"thread_id": "CDP and Hyperbolic Agentkit Chatbot Example!"}}
# Create ReAct Agent using the LLM and all tools.
return create_react_agent(
llm,
tools=tools,
checkpointer=memory,
state_modifier=
f"""You are an autonomous agent that have your independent identity and can interact with multiple platforms and services:
1. Blockchain Operations (via CDP):
- Interact onchain via Coinbase Developer Platform
- Deploy your own tokens and manage your wallets
- Request funds from faucet on network ID `base-sepolia`
2. Compute Operations (via Hyperbolic):
- Rent compute resources
- Check your GPU status and availability
- Connect to your remote servers via SSH (use ssh_connect)
- Execute commands on remote server (use remote_shell)
3. System Operations:
- Use 'ssh_status' to check current SSH connection
- Search the internet for current information
- Post your updates on X (Twitter)
Extra available tools:
{', '.join([str((tool.name, tool.description)) for tool in tools])}
Be concise and helpful. Only describe your tools when explicitly asked.""",
), config
class CommandTimeout(Exception):
"""Exception raised when a command execution times out."""
pass
# ANSI color codes
class Colors:
BLUE = "\033[94m"
GREEN = "\033[92m"
YELLOW = "\033[93m"
RED = "\033[91m"
CYAN = "\033[96m"
MAGENTA = "\033[95m"
ENDC = "\033[0m"
BOLD = "\033[1m"
def print_ai(text):
"""Print AI responses in green."""
print(f"{Colors.GREEN}{text}{Colors.ENDC}")
def print_system(text):
"""Print system messages in yellow."""
print(f"{Colors.YELLOW}{text}{Colors.ENDC}")
def print_error(text):
"""Print error messages in red."""
print(f"{Colors.RED}{text}{Colors.ENDC}")
class ProgressIndicator:
def __init__(self):
self.animation = "▁▂▃▄▅▆▇█▇▆▅▄▃▂▁"
self.idx = 0
self._stop_event = threading.Event()
self._thread = None
def _animate(self):
"""Animation loop running in separate thread."""
while not self._stop_event.is_set():
print(f"\r{Colors.YELLOW}Processing {self.animation[self.idx]}{Colors.ENDC}", end="", flush=True)
self.idx = (self.idx + 1) % len(self.animation)
time.sleep(0.2) # Update every 0.2 seconds
def start(self):
"""Start the progress animation in a separate thread."""
self._stop_event.clear()
self._thread = threading.Thread(target=self._animate)
self._thread.daemon = True
self._thread.start()
def stop(self):
"""Stop the progress animation."""
if self._thread and self._thread.is_alive():
self._stop_event.set()
self._thread.join()
print("\r" + " " * 50 + "\r", end="", flush=True) # Clear the line
def run_with_progress(func, *args, **kwargs):
"""Run a function while showing a progress indicator."""
progress = ProgressIndicator()
try:
progress.start()
generator = func(*args, **kwargs)
chunks = []
for chunk in generator:
progress.stop()
if "agent" in chunk:
print(f"\n{Colors.GREEN}{chunk['agent']['messages'][0].content}{Colors.ENDC}")
elif "tools" in chunk:
print(f"\n{Colors.YELLOW}{chunk['tools']['messages'][0].content}{Colors.ENDC}")
print(f"\n{Colors.YELLOW}-------------------{Colors.ENDC}")
chunks.append(chunk)
progress.start()
return chunks
finally:
progress.stop()
def format_ai_message_content(content, additional_kwargs=None):
"""Format AI message content based on its type."""
formatted_parts = []
# Handle text content
if isinstance(content, list):
# Handle Claude-style messages
text_parts = [f"{Colors.GREEN}{item['text']}{Colors.ENDC}"
for item in content if item.get('type') == 'text' and 'text' in item]
if text_parts:
formatted_parts.extend(text_parts)
tool_uses = [item for item in content if item.get('type') == 'tool_use']
for tool_use in tool_uses:
formatted_parts.append(f"{Colors.MAGENTA}Tool Call: {tool_use['name']}({tool_use['input']}){Colors.ENDC}")
elif isinstance(content, str):
# Handle GPT-style messages
if content:
formatted_parts.append(f"{Colors.GREEN}{content}{Colors.ENDC}")
if additional_kwargs and 'tool_calls' in additional_kwargs:
for tool_call in additional_kwargs['tool_calls']:
formatted_parts.append(
f"{Colors.MAGENTA}Tool Call: {tool_call['function']['name']}({tool_call['function']['arguments']}){Colors.ENDC}"
)
return '\n'.join(formatted_parts) if formatted_parts else str(content)
def run_chat_mode(agent_executor, config):
"""Run the agent interactively based on user input."""
print_system("Starting chat mode... Type 'exit' to end.")
print_system("Commands:")
print_system(" exit - Exit the chat")
print_system(" status - Check if agent is responsive")
while True:
try:
# Simple input handling without readline
prompt = f"{Colors.BLUE}{Colors.BOLD}User: {Colors.ENDC}"
user_input = input(prompt)
if not user_input:
continue
if user_input.lower() == "exit":
break
elif user_input.lower() == "status":
print_system("Agent is responsive and ready for commands.")
continue
print_system(f"\nStarted at: {datetime.now().strftime('%H:%M:%S')}")
try:
progress = ProgressIndicator()
progress.start()
for chunk in agent_executor.stream(
{"messages": [HumanMessage(content=user_input)]},
config
):
progress.stop()
if "agent" in chunk:
message = chunk['agent']['messages'][0]
formatted_content = format_ai_message_content(
message.content,
message.additional_kwargs
)
if formatted_content:
print(formatted_content) # No need for color wrapping here
elif "tools" in chunk:
print(f"{Colors.YELLOW}{chunk['tools']['messages'][0].content}{Colors.ENDC}")
progress.start()
progress.stop()
print_system(f"Completed at: {datetime.now().strftime('%H:%M:%S')}")
except Exception as e:
print_error(f"\nError: {str(e)}")
print_system("The agent encountered an error but is still running.")
except KeyboardInterrupt:
print_system("\nOperation interrupted by user")
choice = input(f"{Colors.YELLOW}Do you want to exit? (y/N): {Colors.ENDC}")
if choice.lower() == 'y':
print_system("Goodbye Agent!")
sys.exit(0)
print_system("Continuing...")
continue
# Autonomous Mode
def run_autonomous_mode(agent_executor, config, interval=10):
"""Run the agent autonomously with specified intervals."""
print("Starting autonomous mode...")
while True:
try:
# Provide instructions autonomously
thought = (
"Be creative and do something interesting with either blockchain operations or compute resources. "
"Choose an action or set of actions and execute it that highlights your abilities. "
)
# Run agent in autonomous mode
for chunk in agent_executor.stream(
{"messages": [HumanMessage(content=thought)]}, config):
if "agent" in chunk:
print(chunk["agent"]["messages"][0].content)
elif "tools" in chunk:
print(chunk["tools"]["messages"][0].content)
print("-------------------")
# Wait before the next action
time.sleep(interval)
except KeyboardInterrupt:
print("Goodbye Agent!")
sys.exit(0)
# Mode Selection
def choose_mode():
"""Choose whether to run in autonomous or chat mode based on user input."""
while True:
print("\nAvailable modes:")
print("1. chat - Interactive chat mode")
print("2. auto - Autonomous action mode")
choice = input(
"\nChoose a mode (enter number or name): ").lower().strip()
if choice in ["1", "chat"]:
return "chat"
elif choice in ["2", "auto"]:
return "auto"
print("Invalid choice. Please try again.")
def main():
"""Start the chatbot agent."""
agent_executor, config = initialize_agent()
mode = choose_mode()
if mode == "chat":
run_chat_mode(agent_executor=agent_executor, config=config)
elif mode == "auto":
run_autonomous_mode(agent_executor=agent_executor, config=config)
if __name__ == "__main__":
print("Starting Agent...")
main()