-
Notifications
You must be signed in to change notification settings - Fork 725
/
message.py
551 lines (448 loc) · 17.3 KB
/
message.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
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
import asyncio
import json
import time
import uuid
from abc import ABC
from typing import Dict, List, Optional, Union, cast
from chainlit.action import Action
from chainlit.config import config
from chainlit.context import context
from chainlit.data import get_data_layer
from chainlit.element import ElementBased
from chainlit.logger import logger
from chainlit.step import StepDict
from chainlit.telemetry import trace_event
from chainlit.types import (
AskActionResponse,
AskActionSpec,
AskFileResponse,
AskFileSpec,
AskSpec,
FileDict,
)
from literalai import BaseGeneration
from literalai.helper import utc_now
from literalai.step import MessageStepType
class MessageBase(ABC):
id: str
thread_id: str
author: str
content: str = ""
type: MessageStepType = "assistant_message"
disable_feedback = False
streaming = False
created_at: Union[str, None] = None
fail_on_persist_error: bool = False
persisted = False
is_error = False
language: Optional[str] = None
wait_for_answer = False
indent: Optional[int] = None
generation: Optional[BaseGeneration] = None
def __post_init__(self) -> None:
trace_event(f"init {self.__class__.__name__}")
self.thread_id = context.session.thread_id
if not getattr(self, "id", None):
self.id = str(uuid.uuid4())
@classmethod
def from_dict(self, _dict: StepDict):
type = _dict.get("type", "assistant_message")
message = Message(
id=_dict["id"],
created_at=_dict["createdAt"],
content=_dict["output"],
author=_dict.get("name", config.ui.name),
type=type, # type: ignore
disable_feedback=_dict.get("disableFeedback", False),
language=_dict.get("language"),
)
return message
def to_dict(self) -> StepDict:
_dict: StepDict = {
"id": self.id,
"threadId": self.thread_id,
"createdAt": self.created_at,
"start": self.created_at,
"end": self.created_at,
"output": self.content,
"name": self.author,
"type": self.type,
"createdAt": self.created_at,
"language": self.language,
"streaming": self.streaming,
"disableFeedback": self.disable_feedback,
"isError": self.is_error,
"waitForAnswer": self.wait_for_answer,
"indent": self.indent,
"generation": self.generation.to_dict() if self.generation else None,
}
return _dict
async def update(
self,
):
"""
Update a message already sent to the UI.
"""
trace_event("update_message")
if self.streaming:
self.streaming = False
step_dict = self.to_dict()
data_layer = get_data_layer()
if data_layer:
try:
asyncio.create_task(data_layer.update_step(step_dict))
except Exception as e:
if self.fail_on_persist_error:
raise e
logger.error(f"Failed to persist message update: {str(e)}")
await context.emitter.update_step(step_dict)
return True
async def remove(self):
"""
Remove a message already sent to the UI.
"""
trace_event("remove_message")
step_dict = self.to_dict()
data_layer = get_data_layer()
if data_layer:
try:
asyncio.create_task(data_layer.delete_step(step_dict["id"]))
except Exception as e:
if self.fail_on_persist_error:
raise e
logger.error(f"Failed to persist message deletion: {str(e)}")
await context.emitter.delete_step(step_dict)
return True
async def _create(self):
step_dict = self.to_dict()
data_layer = get_data_layer()
if data_layer and not self.persisted:
try:
asyncio.create_task(data_layer.create_step(step_dict))
self.persisted = True
except Exception as e:
if self.fail_on_persist_error:
raise e
logger.error(f"Failed to persist message creation: {str(e)}")
return step_dict
async def send(self):
if not self.created_at:
self.created_at = utc_now()
if self.content is None:
self.content = ""
if config.code.author_rename:
self.author = await config.code.author_rename(self.author)
if self.streaming:
self.streaming = False
step_dict = await self._create()
await context.emitter.send_step(step_dict)
return self.id
async def stream_token(self, token: str, is_sequence=False):
"""
Sends a token to the UI. This is useful for streaming messages.
Once all tokens have been streamed, call .send() to end the stream and persist the message if persistence is enabled.
"""
if not self.streaming:
self.streaming = True
step_dict = self.to_dict()
await context.emitter.stream_start(step_dict)
if is_sequence:
self.content = token
else:
self.content += token
assert self.id
await context.emitter.send_token(
id=self.id, token=token, is_sequence=is_sequence
)
class Message(MessageBase):
"""
Send a message to the UI
Args:
content (Union[str, Dict]): The content of the message.
author (str, optional): The author of the message, this will be used in the UI. Defaults to the chatbot name (see config).
language (str, optional): Language of the code is the content is code. See https://react-code-blocks-rajinwonderland.vercel.app/?path=/story/codeblock--supported-languages for a list of supported languages.
actions (List[Action], optional): A list of actions to send with the message.
elements (List[ElementBased], optional): A list of elements to send with the message.
disable_feedback (bool, optional): Hide the feedback buttons for this specific message
"""
def __init__(
self,
content: Union[str, Dict],
author: str = config.ui.name,
language: Optional[str] = None,
actions: Optional[List[Action]] = None,
elements: Optional[List[ElementBased]] = None,
disable_feedback: bool = False,
type: MessageStepType = "assistant_message",
generation: Optional[BaseGeneration] = None,
id: Optional[str] = None,
created_at: Union[str, None] = None,
):
time.sleep(0.001)
self.language = language
self.generation = generation
if isinstance(content, dict):
try:
self.content = json.dumps(content, indent=4, ensure_ascii=False)
self.language = "json"
except TypeError:
self.content = str(content)
self.language = "text"
elif isinstance(content, str):
self.content = content
else:
self.content = str(content)
self.language = "text"
if id:
self.id = str(id)
if created_at:
self.created_at = created_at
self.author = author
self.type = type
self.actions = actions if actions is not None else []
self.elements = elements if elements is not None else []
self.disable_feedback = disable_feedback
super().__post_init__()
async def send(self) -> str:
"""
Send the message to the UI and persist it in the cloud if a project ID is configured.
Return the ID of the message.
"""
trace_event("send_message")
await super().send()
context.session.root_message = self
# Create tasks for all actions and elements
tasks = [action.send(for_id=self.id) for action in self.actions]
tasks.extend(element.send(for_id=self.id) for element in self.elements)
# Run all tasks concurrently
await asyncio.gather(*tasks)
return self.id
async def update(self):
"""
Send the message to the UI and persist it in the cloud if a project ID is configured.
Return the ID of the message.
"""
trace_event("send_message")
await super().update()
# Update tasks for all actions and elements
tasks = [
action.send(for_id=self.id)
for action in self.actions
if action.forId is None
]
tasks.extend(element.send(for_id=self.id) for element in self.elements)
# Run all tasks concurrently
await asyncio.gather(*tasks)
return True
async def remove_actions(self):
for action in self.actions:
await action.remove()
class ErrorMessage(MessageBase):
"""
Send an error message to the UI
If a project ID is configured, the message will be persisted in the cloud.
Args:
content (str): Text displayed above the upload button.
author (str, optional): The author of the message, this will be used in the UI. Defaults to the chatbot name (see config).
parent_id (str, optional): If provided, the message will be nested inside the parent in the UI.
indent (int, optional): If positive, the message will be nested in the UI.
"""
def __init__(
self,
content: str,
author: str = config.ui.name,
fail_on_persist_error: bool = False,
):
self.content = content
self.author = author
self.type = "system_message"
self.is_error = True
self.fail_on_persist_error = fail_on_persist_error
super().__post_init__()
async def send(self):
"""
Send the error message to the UI and persist it in the cloud if a project ID is configured.
Return the ID of the message.
"""
trace_event("send_error_message")
return await super().send()
class AskMessageBase(MessageBase):
async def remove(self):
removed = await super().remove()
if removed:
await context.emitter.clear("clear_ask")
class AskUserMessage(AskMessageBase):
"""
Ask for the user input before continuing.
If the user does not answer in time (see timeout), a TimeoutError will be raised or None will be returned depending on raise_on_timeout.
If a project ID is configured, the message will be uploaded to the cloud storage.
Args:
content (str): The content of the prompt.
author (str, optional): The author of the message, this will be used in the UI. Defaults to the chatbot name (see config).
disable_feedback (bool, optional): Hide the feedback buttons for this specific message
timeout (int, optional): The number of seconds to wait for an answer before raising a TimeoutError.
raise_on_timeout (bool, optional): Whether to raise a socketio TimeoutError if the user does not answer in time.
"""
def __init__(
self,
content: str,
author: str = config.ui.name,
type: MessageStepType = "assistant_message",
disable_feedback: bool = False,
timeout: int = 60,
raise_on_timeout: bool = False,
):
self.content = content
self.author = author
self.timeout = timeout
self.type = type
self.disable_feedback = disable_feedback
self.raise_on_timeout = raise_on_timeout
super().__post_init__()
async def send(self) -> Union[StepDict, None]:
"""
Sends the question to ask to the UI and waits for the reply.
"""
trace_event("send_ask_user")
if not self.created_at:
self.created_at = utc_now()
if config.code.author_rename:
self.author = await config.code.author_rename(self.author)
if self.streaming:
self.streaming = False
self.wait_for_answer = True
step_dict = await self._create()
spec = AskSpec(type="text", timeout=self.timeout)
res = cast(
Union[None, StepDict],
await context.emitter.send_ask_user(step_dict, spec, self.raise_on_timeout),
)
self.wait_for_answer = False
return res
class AskFileMessage(AskMessageBase):
"""
Ask the user to upload a file before continuing.
If the user does not answer in time (see timeout), a TimeoutError will be raised or None will be returned depending on raise_on_timeout.
If a project ID is configured, the file will be uploaded to the cloud storage.
Args:
content (str): Text displayed above the upload button.
accept (Union[List[str], Dict[str, List[str]]]): List of mime type to accept like ["text/csv", "application/pdf"] or a dict like {"text/plain": [".txt", ".py"]}.
max_size_mb (int, optional): Maximum size per file in MB. Maximum value is 100.
max_files (int, optional): Maximum number of files to upload. Maximum value is 10.
author (str, optional): The author of the message, this will be used in the UI. Defaults to the chatbot name (see config).
disable_feedback (bool, optional): Hide the feedback buttons for this specific message
timeout (int, optional): The number of seconds to wait for an answer before raising a TimeoutError.
raise_on_timeout (bool, optional): Whether to raise a socketio TimeoutError if the user does not answer in time.
"""
def __init__(
self,
content: str,
accept: Union[List[str], Dict[str, List[str]]],
max_size_mb=2,
max_files=1,
author=config.ui.name,
type: MessageStepType = "assistant_message",
disable_feedback: bool = False,
timeout=90,
raise_on_timeout=False,
):
self.content = content
self.max_size_mb = max_size_mb
self.max_files = max_files
self.accept = accept
self.type = type
self.author = author
self.timeout = timeout
self.raise_on_timeout = raise_on_timeout
self.disable_feedback = disable_feedback
super().__post_init__()
async def send(self) -> Union[List[AskFileResponse], None]:
"""
Sends the message to request a file from the user to the UI and waits for the reply.
"""
trace_event("send_ask_file")
if not self.created_at:
self.created_at = utc_now()
if self.streaming:
self.streaming = False
if config.code.author_rename:
self.author = await config.code.author_rename(self.author)
self.wait_for_answer = True
step_dict = await self._create()
spec = AskFileSpec(
type="file",
accept=self.accept,
max_size_mb=self.max_size_mb,
max_files=self.max_files,
timeout=self.timeout,
)
res = cast(
Union[None, List[FileDict]],
await context.emitter.send_ask_user(step_dict, spec, self.raise_on_timeout),
)
self.wait_for_answer = False
if res:
return [
AskFileResponse(
id=r["id"],
name=r["name"],
path=str(r["path"]),
size=r["size"],
type=r["type"],
)
for r in res
]
else:
return None
class AskActionMessage(AskMessageBase):
"""
Ask the user to select an action before continuing.
If the user does not answer in time (see timeout), a TimeoutError will be raised or None will be returned depending on raise_on_timeout.
"""
def __init__(
self,
content: str,
actions: List[Action],
author=config.ui.name,
disable_feedback=False,
timeout=90,
raise_on_timeout=False,
):
self.content = content
self.actions = actions
self.author = author
self.disable_feedback = disable_feedback
self.timeout = timeout
self.raise_on_timeout = raise_on_timeout
super().__post_init__()
async def send(self) -> Union[AskActionResponse, None]:
"""
Sends the question to ask to the UI and waits for the reply
"""
trace_event("send_ask_action")
if not self.created_at:
self.created_at = utc_now()
if self.streaming:
self.streaming = False
if config.code.author_rename:
self.author = await config.code.author_rename(self.author)
self.wait_for_answer = True
step_dict = await self._create()
action_keys = []
for action in self.actions:
action_keys.append(action.id)
await action.send(for_id=str(step_dict["id"]))
spec = AskActionSpec(type="action", timeout=self.timeout, keys=action_keys)
res = cast(
Union[AskActionResponse, None],
await context.emitter.send_ask_user(step_dict, spec, self.raise_on_timeout),
)
for action in self.actions:
await action.remove()
if res is None:
self.content = "Timed out: no action was taken"
else:
self.content = f'**Selected action:** {res["label"]}'
self.wait_for_answer = False
await self.update()
return res