-
-
Notifications
You must be signed in to change notification settings - Fork 16
/
GateKeeper.py
executable file
·203 lines (187 loc) · 7.51 KB
/
GateKeeper.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
from openai import OpenAI
import os
import json
import re
import html
import time
import wolframalpha
from duckduckgo_search import DDGS
import nmap
from datetime import datetime
import subprocess
import Shared_vars
from comfyui import imagegen
from inference import infer
from scrape import scrape_site
path = os.path.realpath(__file__).strip("GateKeeper.py")
client = OpenAI(
base_url=f"http://{Shared_vars.config.host}:{Shared_vars.config.port}/v1",
api_key=Shared_vars.config.api_key,
)
func = ""
client = wolframalpha.Client(Shared_vars.config.enabled_features["wolframalpha"]['app_id'])
with open(path + "functions.json") as user_file:
fcontent = json.loads(user_file.read())
for x in fcontent:
params = (
json.dumps(x["params"])
.strip("{}")
.replace('",', "\n ")
.replace('"', "")
)
template = f"""\n{x['name']}:
description: {x['description']}
params:
{params}"""
func += template
def GateKeep(input, ip):
content = ""
print("Begin streamed GateKeeper output.")
examplefnc = '<startfunc>{\n"function": "internetsearch",\n"params": {\n"keywords": "mixtral"\n}\n}<endfunc>'
fewshot = f"""{Shared_vars.config.llm_parameters['beginsep']} Input:\nDescribe the model mixtral.{Shared_vars.config.llm_parameters['endsep']}{examplefnc}"""
try:
ctxstr = ""
for x in Shared_vars.vismem[f"{ip}"][-2:]:
ctxstr += re.sub( r'!\[.*?\]\(.*?\)|<img.*?>', '', "USER: " + x["user"] + "\n" + "PolyMind: " + x["assistant"])
content = "<startfunc>\n{"
content += infer(
"Input: " + input,
mem=[],
modelname="Output:\n<startfunc>\n{",
system=f"You are an AI assistant named GateKeeper, The current date is {datetime.now()}, please select the single most suitable function and parameters from the list of available functions below, based on the user's input and pay attention to the context, which will then be passed over to polymind. Provide your response in JSON format surrounded by '<startfunc>' and '<endfunc>' without any notes, comments or follow-ups. Only JSON.\n{func}\nContext: {ctxstr}\n",
temperature=0.1,
top_p=0.1,
min_p=0.05,
top_k=40,
stopstrings=[
"Input: ",
"[INST]",
"[/INST]",
"```",
"</s>",
"user:",
"polymind:",
"Polymind:",
"<</SYS>>",
"[System Message]",
"endfunc",
"<endfunc>",
"}<",
"</startfunc>",
],
)[0]
except TypeError:
content = "<startfunc>\n{"
content += infer(
"Input: " + input,
mem=[],
modelname="Output:\n<startfunc>\n{",
system=f"You are an AI assistant named GateKeeper, The current date is {datetime.now()}, please select the single most suitable function and parameters from the list of available functions below, based on the user's input and pay attention to the context, which will then be passed over to polymind. Provide your response in JSON format surrounded by '<startfunc>' and '<endfunc>' without any notes, comments or follow-ups. Only JSON.\n{func}",
temperature=0.1,
top_p=0.1,
min_p=0.05,
top_k=40,
stopstrings=[
"Input: ",
"[INST]",
"[/INST]",
"```",
"</s>",
"user:",
"polymind:",
"Polymind:",
"<</SYS>>",
"[System Message]",
"endfunc",
"<endfunc>",
"}<",
"</startfunc>",
],
)[0]
try:
if "<startfunc>" in content:
content = content.split("<startfunc>")[1]
content = (
re.sub(r"\\_", "_", html.unescape(content))
.replace("\\_", "_")
.replace("}<", "}")
.replace("<startfunc>", "")
.replace("<", "")
.replace("/", "")
)
print(content)
return Util(json.loads(content.replace("Output:", "")), ip)
except Exception:
return "null"
def Util(rsp, ip):
result = ""
rsp["function"] = (
re.sub(r"\\_", "_", html.unescape(rsp["function"]))
.replace("\\_", "_")
.replace("{<", "{")
.replace("<startfunc>", "")
)
params = rsp["params"] if "params" in rsp else rsp
if rsp["function"] == "acknowledge":
return "null"
elif rsp["function"] == "clearmemory":
Shared_vars.mem[f"{ip}"] = []
Shared_vars.vismem[f"{ip}"] = []
return "skipment{<" + params["message"]
elif rsp["function"] == "wolframalpha":
try:
res = client.query(params["query"])
results = ''
checkimage = False
for pod in res.pods:
for sub in pod.subpods:
if "plot" in sub.img["@alt"].lower() and not "plot |" in sub.img["@alt"].lower():
results += f'<img src="{sub.img["@src"]}" alt="{sub.img["@alt"]}"/>' + '\n'
checkimage = True
elif sub.plaintext:
results += sub.plaintext + '\n'
if results == "":
result = "No results from Wolfram Alpha."
else:
result = "Wolfram Alpha result: " + results
if checkimage:
result += '\nREMINDER: include the graph images in your explanation if theres any when explaining the results in a short and concise manner.'
return result
except Exception as e:
return "Wolfram Alpha Error: " + str(e)
elif rsp["function"] == "generateimage":
return imagegen(params["prompt"])
elif rsp["function"] == "runpythoncode":
if ip != Shared_vars.config.adminip:
return "null"
time.sleep(5)
output = subprocess.run(
["python3", "-c", params["code"]],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
print(output)
stdout, stderr = output.stdout.decode(), output.stderr.decode()
return f"Code to be ran: \n```{rsp['params']['code']}```\n<Code interpreter output>:\nstdout: {stdout}\nstderr: {stderr}\n<\Code interpreter output>"
elif rsp["function"] == "internetsearch":
with DDGS() as ddgs:
for r in ddgs.text(
params["keywords"], safesearch="Off", max_results=4
):
title = r["title"]
link = r["href"]
result += f' *Title*: {title} *Link*: {link} *Body*: {r["body"]}\n*Scraped_text*: {scrape_site(link, 700)}'
return "<Search results>:\n" + result
elif rsp["function"] == "portscan":
if ip != Shared_vars.config.adminip:
return "null"
nm = nmap.PortScanner()
try:
nm.scan(params["ip"])
if nm[params["ip"]].state() == "up":
for x in nm[params["ip"]]["tcp"].keys():
result += f"{nm[rsp['params']['ip']]['tcp'][x]['name']}: State {nm[rsp['params']['ip']]['tcp'][x]['state']} ({x})\n"
return f"<Portscan output for IP {rsp['params']['ip']}>: " + result
except:
return f"<Portscan output for IP {rsp['params']['ip']}>: Host down."
return "null"