-
Notifications
You must be signed in to change notification settings - Fork 0
/
service
executable file
·193 lines (140 loc) · 5.12 KB
/
service
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
#!/usr/bin/env python3
import _jsonnet as j
from aiohttp import web
import aiohttp
import asyncio
import logging
import os
import json
import yaml
from trustgraph.clients.embeddings_client import EmbeddingsClient
from trustgraph.clients.graph_rag_client import GraphRagClient
from trustgraph.clients.prompt_client import PromptClient
from trustgraph.clients.triples_query_client import TriplesQueryClient
from trustgraph.clients.llm_client import LlmClient
logger = logging.getLogger("service")
logger.setLevel(logging.INFO)
class Api:
def __init__(self, config=None):
if not config:
self.config = {}
self.config = config
pulsar_host = config.get("pulsar-host", "pulsar://localhost:6650")
self.port = int(self.config.get("port", "8081"))
self.app = web.Application(middlewares=[])
self.app.router.add_route('GET', '/ws', self.websocket_handler)
self.app.add_routes([web.get("/{tail:.*}", self.everything_else)])
self.embed = EmbeddingsClient(pulsar_host=pulsar_host)
self.llm = LlmClient(pulsar_host=pulsar_host)
print("Initialised")
async def websocket_handler(self, request):
print('Websocket connection starting')
ws = aiohttp.web.WebSocketResponse()
await ws.prepare(request)
print('Websocket connection ready')
handlers = {
"message": self.handle_message
}
async for msg in ws:
print(msg)
if msg.type == aiohttp.WSMsgType.TEXT:
try:
obj = json.loads(msg.data)
except:
await ws.send_json({
"type": "error",
"body": {
"message": f"JSON parse fail",
}
})
continue
try:
if "type" not in obj:
raise RuntimeError("Message has no type field")
if obj["type"] == "close":
await ws.close()
break
if "body" not in obj:
raise RuntimeError("Message has no body field")
if obj["type"] not in handlers:
raise RuntimeError("Don't understand that type")
handler = handlers.get(obj["type"])
resp = await handler(obj["body"])
# Code above must either set 'resp' or raise an exception
await ws.send_json(resp)
continue
except Exception as e:
await ws.send_json({
"type": "error",
"body": {
"message": str(e),
}
})
continue
print('Websocket connection closed')
return ws
async def handle_message(self, obj):
if "text" not in obj:
raise RuntimeError("Message has no message field")
q = obj["text"]
print(">", q)
resp = self.llm.request(q)
print("<", resp)
return {
"type": "message",
"body": {
"role": "ai",
"text": resp,
},
}
async def everything_else(self, request):
print(">", request.path)
if ".." in request.path:
return web.HTTPNotFound()
if request.path == "/":
with open("dist/index.html", "r") as f:
return web.Response(
text=f.read(), content_type="text/html"
)
if request.path == "/api/patterns":
return web.Response(
text=self.patterns, content_type="application/json"
)
if request.path.endswith(".css"):
with open("dist" + request.path, "r") as f:
data = f.read()
return web.Response(
text=data, content_type="text/css"
)
if request.path.endswith(".js"):
with open("dist" + request.path, "r") as f:
data = f.read()
return web.Response(
text=data, content_type="text/javascript"
)
if request.path.endswith(".html"):
with open("dist" + request.path, "r") as f:
data = f.read()
return web.Response(
text=data, content_type="text/html"
)
return web.HTTPNotFound()
async def generate(self, request):
print("Generate...")
config = await request.text()
print(config)
config = config.encode("utf-8")
gen = Generator(config)
with open("./templates/config-loader.jsonnet", "r") as f:
wrapper = f.read()
processed = gen.process(wrapper)
return web.Response(
text=yaml.dump(processed), content_type = "text/plain"
)
def run(self):
web.run_app(self.app, port=self.port)
config = {
"pulsar-host": "pulsar://localhost:6650"
}
a = Api(config=config)
a.run()