forked from frdel/agent-zero
-
Notifications
You must be signed in to change notification settings - Fork 0
/
run_ui.py
374 lines (294 loc) · 9.67 KB
/
run_ui.py
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
import json
from functools import wraps
import os
from pathlib import Path
import threading
import uuid
from flask import Flask, request, jsonify, Response
from flask_basicauth import BasicAuth
from agent import AgentContext
from initialize import initialize
from python.helpers import files
from python.helpers.files import get_abs_path
from python.helpers.print_style import PrintStyle
from python.helpers.dotenv import load_dotenv
from python.helpers import persist_chat
# initialize the internal Flask server
app = Flask("app", static_folder=get_abs_path("./webui"), static_url_path="/")
app.config["JSON_SORT_KEYS"] = False # Disable key sorting in jsonify
lock = threading.Lock()
# Set up basic authentication, name and password from .env variables
app.config["BASIC_AUTH_USERNAME"] = (
os.environ.get("BASIC_AUTH_USERNAME") or "admin"
) # default name
app.config["BASIC_AUTH_PASSWORD"] = (
os.environ.get("BASIC_AUTH_PASSWORD") or "admin"
) # default pass
basic_auth = BasicAuth(app)
# get context to run agent zero in
def get_context(ctxid: str):
with lock:
if not ctxid:
first = AgentContext.first()
if first:
return first
return AgentContext(config=initialize())
got = AgentContext.get(ctxid)
if got:
return got
return AgentContext(config=initialize(), id=ctxid)
# Now you can use @requires_auth function decorator to require login on certain pages
def requires_auth(f):
@wraps(f)
async def decorated(*args, **kwargs):
auth = request.authorization
if not auth or not (
auth.username == app.config["BASIC_AUTH_USERNAME"]
and auth.password == app.config["BASIC_AUTH_PASSWORD"]
):
return Response(
"Could not verify your access level for that URL.\n"
"You have to login with proper credentials",
401,
{"WWW-Authenticate": 'Basic realm="Login Required"'},
)
return await f(*args, **kwargs)
return decorated
# handle default address, show demo html page from ./test_form.html
@app.route("/", methods=["GET"])
async def test_form():
return Path(get_abs_path("./webui/index.html")).read_text()
# simple health check, just return OK to see the server is running
@app.route("/ok", methods=["GET", "POST"])
async def health_check():
return "OK"
# # secret page, requires authentication
# @app.route('/secret', methods=['GET'])
# @requires_auth
# async def secret_page():
# return Path("./secret_page.html").read_text()
# send message to agent (async UI)
@app.route("/msg", methods=["POST"])
async def handle_message_async():
return await handle_message(False)
# send message to agent (synchronous API)
@app.route("/msg_sync", methods=["POST"])
async def handle_msg_sync():
return await handle_message(True)
async def handle_message(sync: bool):
try:
# data sent to the server
input = request.get_json()
text = input.get("text", "")
ctxid = input.get("context", "")
blev = input.get("broadcast", 1)
# context instance - get or create
context = get_context(ctxid)
# print to console and log
PrintStyle(
background_color="#6C3483", font_color="white", bold=True, padding=True
).print(f"User message:")
PrintStyle(font_color="white", padding=False).print(f"> {text}")
context.log.log(type="user", heading="User message", content=text)
if sync:
context.communicate(text)
result = await context.process.result() # type: ignore
response = {
"ok": True,
"message": result,
"context": context.id,
}
else:
context.communicate(text)
response = {
"ok": True,
"message": "Message received.",
"context": context.id,
}
except Exception as e:
response = {
"ok": False,
"message": str(e),
}
PrintStyle.error(str(e))
# respond with json
return jsonify(response)
# pausing/unpausing the agent
@app.route("/pause", methods=["POST"])
async def pause():
try:
# data sent to the server
input = request.get_json()
paused = input.get("paused", False)
ctxid = input.get("context", "")
# context instance - get or create
context = get_context(ctxid)
context.paused = paused
response = {
"ok": True,
"message": "Agent paused." if paused else "Agent unpaused.",
"pause": paused,
}
except Exception as e:
response = {
"ok": False,
"message": str(e),
}
PrintStyle.error(str(e))
# respond with json
return jsonify(response)
# load chats from json
@app.route("/loadChats", methods=["POST"])
async def load_chats():
try:
# data sent to the server
input = request.get_json()
chats = input.get("chats", [])
if not chats:
raise Exception("No chats provided")
ctxids = persist_chat.load_json_chats(chats)
response = {
"ok": True,
"message": "Chats loaded.",
"ctxids": ctxids,
}
except Exception as e:
response = {
"ok": False,
"message": str(e),
}
PrintStyle.error(str(e))
# respond with json
return jsonify(response)
# load chats from json
@app.route("/exportChat", methods=["POST"])
async def export_chat():
try:
# data sent to the server
input = request.get_json()
ctxid = input.get("ctxid", "")
if not ctxid:
raise Exception("No context id provided")
context = get_context(ctxid)
content = persist_chat.export_json_chat(context)
response = {
"ok": True,
"message": "Chats loaded.",
"ctxid": context.id,
"content": content,
}
except Exception as e:
response = {
"ok": False,
"message": str(e),
}
PrintStyle.error(str(e))
# respond with json
return jsonify(response)
# restarting with new agent0
@app.route("/reset", methods=["POST"])
async def reset():
try:
# data sent to the server
input = request.get_json()
ctxid = input.get("context", "")
# context instance - get or create
context = get_context(ctxid)
context.reset()
persist_chat.save_tmp_chat(context)
response = {
"ok": True,
"message": "Agent restarted.",
}
except Exception as e:
response = {
"ok": False,
"message": str(e),
}
PrintStyle.error(str(e))
# respond with json
return jsonify(response)
# killing context
@app.route("/remove", methods=["POST"])
async def remove():
try:
# data sent to the server
input = request.get_json()
ctxid = input.get("context", "")
# context instance - get or create
AgentContext.remove(ctxid)
persist_chat.remove_chat(ctxid)
response = {
"ok": True,
"message": "Context removed.",
}
except Exception as e:
response = {
"ok": False,
"message": str(e),
}
PrintStyle.error(str(e))
# respond with json
return jsonify(response)
# Web UI polling
@app.route("/poll", methods=["POST"])
async def poll():
try:
# data sent to the server
input = request.get_json()
ctxid = input.get("context", None)
from_no = input.get("log_from", 0)
# context instance - get or create
context = get_context(ctxid)
logs = context.log.output(start=from_no)
# loop AgentContext._contexts
ctxs = []
for ctx in AgentContext._contexts.values():
ctxs.append(
{
"id": ctx.id,
"no": ctx.no,
"log_guid": ctx.log.guid,
"log_version": len(ctx.log.updates),
"log_length": len(ctx.log.logs),
"paused": ctx.paused,
}
)
# data from this server
response = {
"ok": True,
"context": context.id,
"contexts": ctxs,
"logs": logs,
"log_guid": context.log.guid,
"log_version": len(context.log.updates),
"log_progress": context.log.progress,
"paused": context.paused,
}
except Exception as e:
response = {
"ok": False,
"message": str(e),
}
PrintStyle.error(str(e))
# serialize json with json.dumps to preserve OrderedDict order
response_json = json.dumps(response)
return Response(response=response_json, status=200, mimetype="application/json")
# return jsonify(response)
def run():
print("Initializing framework...")
# load env vars
load_dotenv()
# initialize contexts from persisted chats
persist_chat.load_tmp_chats()
# Suppress only request logs but keep the startup messages
from werkzeug.serving import WSGIRequestHandler
class NoRequestLoggingWSGIRequestHandler(WSGIRequestHandler):
def log_request(self, code="-", size="-"):
pass # Override to suppress request logging
# run the server on port from .env
port = int(os.environ.get("WEB_UI_PORT", 0)) or None
app.run(request_handler=NoRequestLoggingWSGIRequestHandler, port=port)
# run the internal server
if __name__ == "__main__":
run()