-
Notifications
You must be signed in to change notification settings - Fork 1
/
chat_instance.py
194 lines (171 loc) · 6.27 KB
/
chat_instance.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
"""Define a chat instance"""
from __future__ import annotations
from collections import defaultdict
import traceback
import weakref
from typing import TYPE_CHECKING
from ..loader import LOADERS
from .message import KernelProcess, MessageContext
if TYPE_CHECKING:
from .kernelcomm import KernelComm
from .message import IChatMessage
def apply_partial(original: dict, update: dict):
"""Apply nested changes to original dict"""
for key, value in update.items():
if isinstance(value, dict):
apply_partial(original[key], value)
else:
original[key] = value
class ChatInstance:
"""Chat Instance handler"""
def __init__(self, comm: KernelComm, chat_name: str, mode="newton"):
self.mode = mode
self.comm_ref = weakref.ref(comm)
self.bot_loader = LOADERS[mode](comm)
self.memory = defaultdict(lambda: None)
self.chat_name = chat_name
self.history = []
self.message_map = {}
self.config = {
"process_in_kernel": True,
"enable_autocomplete": True,
"enable_auto_loading": False,
"loading": False,
"process_base_chat_message": True,
"show_replied": False,
"show_index": False,
"show_time": True,
"show_build_messages": True,
"show_kernel_messages": True,
"show_metadata": False,
"direct_send_to_user": False,
}
self.checkpoints = {}
@property
def bot(self):
"""Returns current bot"""
return self.bot_loader.current()
def start_bot(self, data: dict):
"""Starts bot and sets history map"""
self.bot.start(self, data)
for message in self.history:
self.message_map[message['id']] = message
return self
def sync_chat(self, operation):
"""Sends message with history and general config"""
self.send({
"operation": operation,
"history": self.history,
"config": self.config,
})
def refresh(self):
"""Refreshes instance"""
self.bot.refresh(self)
self.sync_chat("refresh")
def receive(self, data: dict):
"""Processes received requests"""
try:
operation = data["operation"]
if operation == "message":
self.receive_message(data.get("message"))
elif operation == "refresh":
self.refresh()
elif operation == "autocomplete-query":
self.receive_autocomplete_query(
data.get('requestId'),
data.get('query')
)
elif operation == "config":
key = data["key"]
value = data["value"]
if data["_mode"] == "update" or key not in self.config:
self.config[key] = value
self.send({
"operation": "update-config",
"config": {key: self.config[key]},
})
elif operation == "sync-message":
partial_message = data["message"]
message = self.message_map[partial_message["id"]]
apply_partial(message, partial_message)
self.send({
"operation": "update-message",
"message": message,
})
except Exception: # pylint: disable=broad-except
print(traceback.format_exc())
self.send({
"operation": "error",
"command": operation,
"message": traceback.format_exc(),
})
def receive_message(self, message: IChatMessage):
"""Receives message from user"""
self.history.append(message)
self.message_map[message['id']] = message
self.send({
"operation": "reply",
"message": message
})
process_message = (
message.get('kernelProcess') == KernelProcess.PROCESS
and self.config["process_in_kernel"]
or message.get('kernelProcess') == KernelProcess.FORCE
)
if process_message:
context = MessageContext(self.comm_ref(), self, message)
self.bot.process_message(context)
replicate_other_instances = (
self.chat_name == "base"
and (
process_message
or message.get('kernelProcess') == KernelProcess.PROCESS
)
)
if replicate_other_instances:
for chat_name, instance in self.comm_ref().chat_instances.items():
if chat_name != "base" and instance.config["process_base_chat_message"]:
instance.receive_message(message)
def receive_autocomplete_query(self, request_id, query):
"""Receives query from user"""
if self.config["enable_autocomplete"]:
self.bot.process_autocomplete(self, request_id, query)
else:
self.send({
"operation": "autocomplete-response",
"responseId": request_id,
"items": [],
})
def send(self, data):
"""Receives send results"""
data["instance"] = self.chat_name
self.comm_ref().comm.send(data)
def reply_message(self, message: IChatMessage):
"""Replies IChatMessage to user"""
self.history.append(message)
self.message_map[message['id']] = message
self.send({
"operation": "reply",
"message": message
})
def save(self):
"""Saves instance data"""
return {
"name": self.chat_name,
"mode": self.mode,
"bot": self.bot.save(),
"history": self.history,
"config": self.config
}
def load(self, data):
"""Loads instance data"""
self.chat_name = data.get("name", self.chat_name)
self.mode = data.get("mode", self.mode)
if "bot" in data:
self.bot.load(data["bot"])
if "history" in data:
self.history = data["history"]
self.message_map = {}
for message in self.history:
self.message_map[message['id']] = message
self.config = {**self.config, **data.get("config", {})}