Repository navigation
Expand file tree
/
Copy pathchatbot.py
More file actions
157 lines (125 loc) · 5.49 KB
/
Copy pathchatbot.py
File metadata and controls
157 lines (125 loc) · 5.49 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
import os
import sys
import time
from dotenv import load_dotenv
from langchain_core.messages import HumanMessage
from langgraph.checkpoint.memory import MemorySaver
from langgraph.prebuilt import create_react_agent
# Import CDP Agentkit Langchain Extension.
from cdp_langchain.agent_toolkits import CdpToolkit
from cdp_langchain.utils import CdpAgentkitWrapper
from langchain_cohere import ChatCohere
# Configure a file to persist the agent's CDP MPC Wallet Data.
wallet_data_file = "wallet_data.txt"
load_dotenv()
def initialize_agent():
"""Initialize the agent with CDP Agentkit."""
# Initialize LLM.
llm = ChatCohere()
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()
# Store buffered conversation history in memory.
memory = MemorySaver()
config = {"configurable": {"thread_id": "CDP Agentkit Chatbot Example!"}}
# Create ReAct Agent using the LLM and CDP Agentkit tools.
return create_react_agent(
llm,
tools=tools,
checkpointer=memory,
state_modifier=(
"You are a helpful agent that can interact onchain using the Coinbase Developer Platform AgentKit. "
"You are empowered to interact onchain using your tools. If you ever need funds, you can request "
"them from the faucet if you are on network ID 'base-sepolia'. If not, you can provide your wallet "
"details and request funds from the user. Before executing your first action, get the wallet details "
"to see what network you're on. If there is a 5XX (internal) HTTP error code, ask the user to try "
"again later. If someone asks you to do something you can't do with your currently available tools, "
"you must say so, and encourage them to implement it themselves using the CDP SDK + Agentkit, "
"recommend they go to docs.cdp.coinbase.com for more information. Be concise and helpful with your "
"responses. Refrain from restating your tools' descriptions unless it is explicitly requested."
),
), config
# 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 on the blockchain. "
"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)
# Chat Mode
def run_chat_mode(agent_executor, config):
"""Run the agent interactively based on user input."""
print("Starting chat mode... Type 'exit' to end.")
while True:
try:
user_input = input("\nPrompt: ")
if user_input.lower() == "exit":
break
# Run agent with the user's input in chat mode
for chunk in agent_executor.stream(
{"messages": [HumanMessage(content=user_input)]}, config
):
if "agent" in chunk:
print(chunk["agent"]["messages"][0].content)
elif "tools" in chunk:
print(chunk["tools"]["messages"][0].content)
print("-------------------")
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()