-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path172.py
More file actions
257 lines (194 loc) · 6.1 KB
/
Copy path172.py
File metadata and controls
257 lines (194 loc) · 6.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
"""
The command line interface for the agent server
"""
import os
import pathlib
import click
import psutil
from backend import app
from backend.util.process import AppProcess
def get_pid_path() -> pathlib.Path:
home_dir = pathlib.Path.home()
new_dir = home_dir / ".config" / "agpt"
file_path = new_dir / "running.tmp"
return file_path
def get_pid() -> int | None:
file_path = get_pid_path()
if not file_path.exists():
return None
os.makedirs(file_path.parent, exist_ok=True)
with open(file_path, "r", encoding="utf-8") as file:
pid = file.read()
try:
return int(pid)
except ValueError:
return None
def write_pid(pid: int):
file_path = get_pid_path()
os.makedirs(file_path.parent, exist_ok=True)
with open(file_path, "w", encoding="utf-8") as file:
file.write(str(pid))
class MainApp(AppProcess):
def run(self):
app.main(silent=True)
@click.group()
def main():
"""AutoGPT Server CLI Tool"""
pass
@main.command()
def start():
"""
Starts the server in the background and saves the PID
"""
# Define the path for the new directory and file
pid = get_pid()
if pid and psutil.pid_exists(pid):
print("Server is already running")
exit(1)
elif pid:
print("PID does not exist deleting file")
os.remove(get_pid_path())
print("Starting server")
pid = MainApp().start(background=True, silent=True)
print(f"Server running in process: {pid}")
write_pid(pid)
print("done")
os._exit(status=0)
@main.command()
def stop():
"""
Stops the server
"""
pid = get_pid()
if not pid:
print("Server is not running")
return
os.remove(get_pid_path())
process = psutil.Process(int(pid))
for child in process.children(recursive=True):
child.terminate()
process.terminate()
print("Server Stopped")
@main.command()
def gen_encrypt_key():
"""
Generate a new encryption key
"""
from cryptography.fernet import Fernet
print(Fernet.generate_key().decode())
@click.group()
def test():
"""
Group for test commands
"""
pass
@test.command()
@click.argument("server_address")
def reddit(server_address: str):
"""
Create an event graph
"""
import requests
from backend.usecases.reddit_marketing import create_test_graph
test_graph = create_test_graph()
url = f"{server_address}/graphs"
headers = {"Content-Type": "application/json"}
data = test_graph.model_dump_json()
response = requests.post(url, headers=headers, data=data)
graph_id = response.json()["id"]
print(f"Graph created with ID: {graph_id}")
@test.command()
@click.argument("server_address")
def populate_db(server_address: str):
"""
Create an event graph
"""
import requests
from backend.usecases.sample import create_test_graph
test_graph = create_test_graph()
url = f"{server_address}/graphs"
headers = {"Content-Type": "application/json"}
data = test_graph.model_dump_json()
response = requests.post(url, headers=headers, data=data)
graph_id = response.json()["id"]
if response.status_code == 200:
execute_url = f"{server_address}/graphs/{response.json()['id']}/execute"
text = "Hello, World!"
input_data = {"input": text}
response = requests.post(execute_url, headers=headers, json=input_data)
schedule_url = f"{server_address}/graphs/{graph_id}/schedules"
data = {
"graph_id": graph_id,
"cron": "*/5 * * * *",
"input_data": {"input": "Hello, World!"},
}
response = requests.post(schedule_url, headers=headers, json=data)
print("Database populated with: \n- graph\n- execution\n- schedule")
@test.command()
@click.argument("server_address")
def graph(server_address: str):
"""
Create an event graph
"""
import requests
from backend.usecases.sample import create_test_graph
url = f"{server_address}/graphs"
headers = {"Content-Type": "application/json"}
data = create_test_graph().model_dump_json()
response = requests.post(url, headers=headers, data=data)
if response.status_code == 200:
print(response.json()["id"])
execute_url = f"{server_address}/graphs/{response.json()['id']}/execute"
text = "Hello, World!"
input_data = {"input": text}
response = requests.post(execute_url, headers=headers, json=input_data)
else:
print("Failed to send graph")
print(f"Response: {response.text}")
@test.command()
@click.argument("graph_id")
@click.argument("content")
def execute(graph_id: str, content: dict):
"""
Create an event graph
"""
import requests
headers = {"Content-Type": "application/json"}
execute_url = f"http://0.0.0.0:8000/graphs/{graph_id}/execute"
requests.post(execute_url, headers=headers, json=content)
@test.command()
def event():
"""
Send an event to the running server
"""
print("Event sent")
@test.command()
@click.argument("server_address")
@click.argument("graph_id")
def websocket(server_address: str, graph_id: str):
"""
Tests the websocket connection.
"""
import asyncio
import websockets.asyncio.client
from backend.server.ws_api import ExecutionSubscription, Methods, WsMessage
async def send_message(server_address: str):
uri = f"ws://{server_address}"
async with websockets.asyncio.client.connect(uri) as websocket:
try:
msg = WsMessage(
method=Methods.SUBSCRIBE,
data=ExecutionSubscription(graph_id=graph_id).model_dump(),
).model_dump_json()
await websocket.send(msg)
print(f"Sending: {msg}")
while True:
response = await websocket.recv()
print(f"Response from server: {response}")
except InterruptedError:
exit(0)
asyncio.run(send_message(server_address))
print("Testing WS")
main.add_command(test)
if __name__ == "__main__":
main()