-
Notifications
You must be signed in to change notification settings - Fork 725
/
__init__.py
470 lines (404 loc) · 15 KB
/
__init__.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
import functools
import json
import os
from collections import deque
from typing import TYPE_CHECKING, Dict, List, Literal, Optional, Union, cast
import aiofiles
from chainlit.config import config
from chainlit.context import context
from chainlit.logger import logger
from chainlit.session import WebsocketSession
from chainlit.types import Feedback, Pagination, ThreadDict, ThreadFilter
from chainlit.user import PersistedUser, User, UserDict
from literalai import Attachment, PageInfo, PaginatedResponse
from literalai import Score as LiteralScore
from literalai import Step as LiteralStep
from literalai.filter import threads_filters as LiteralThreadsFilters
from literalai.step import StepDict as LiteralStepDict
if TYPE_CHECKING:
from chainlit.element import Element, ElementDict
from chainlit.step import FeedbackDict, StepDict
def queue_until_user_message():
def decorator(method):
@functools.wraps(method)
async def wrapper(self, *args, **kwargs):
if (
isinstance(context.session, WebsocketSession)
and not context.session.has_first_interaction
):
# Queue the method invocation waiting for the first user message
queues = context.session.thread_queues
method_name = method.__name__
if method_name not in queues:
queues[method_name] = deque()
queues[method_name].append((method, self, args, kwargs))
else:
# Otherwise, Execute the method immediately
return await method(self, *args, **kwargs)
return wrapper
return decorator
class BaseDataLayer:
"""Base class for data persistence."""
async def get_user(self, identifier: str) -> Optional["PersistedUser"]:
return None
async def create_user(self, user: "User") -> Optional["PersistedUser"]:
pass
async def delete_feedback(
self,
feedback_id: str,
) -> bool:
return True
async def upsert_feedback(
self,
feedback: Feedback,
) -> str:
return ""
@queue_until_user_message()
async def create_element(self, element: "Element"):
pass
async def get_element(
self, thread_id: str, element_id: str
) -> Optional["ElementDict"]:
pass
@queue_until_user_message()
async def delete_element(self, element_id: str):
pass
@queue_until_user_message()
async def create_step(self, step_dict: "StepDict"):
pass
@queue_until_user_message()
async def update_step(self, step_dict: "StepDict"):
pass
@queue_until_user_message()
async def delete_step(self, step_id: str):
pass
async def get_thread_author(self, thread_id: str) -> str:
return ""
async def delete_thread(self, thread_id: str):
pass
async def list_threads(
self, pagination: "Pagination", filters: "ThreadFilter"
) -> "PaginatedResponse[ThreadDict]":
return PaginatedResponse(
data=[],
pageInfo=PageInfo(hasNextPage=False, startCursor=None, endCursor=None),
)
async def get_thread(self, thread_id: str) -> "Optional[ThreadDict]":
return None
async def update_thread(
self,
thread_id: str,
name: Optional[str] = None,
user_id: Optional[str] = None,
metadata: Optional[Dict] = None,
tags: Optional[List[str]] = None,
):
pass
async def delete_user_session(self, id: str) -> bool:
return True
_data_layer: Optional[BaseDataLayer] = None
class ChainlitDataLayer(BaseDataLayer):
def __init__(self, api_key: str, server: Optional[str]):
from literalai import LiteralClient
self.client = LiteralClient(api_key=api_key, url=server)
logger.info("Chainlit data layer initialized")
def attachment_to_element_dict(self, attachment: Attachment) -> "ElementDict":
metadata = attachment.metadata or {}
return {
"chainlitKey": None,
"display": metadata.get("display", "side"),
"language": metadata.get("language"),
"page": metadata.get("page"),
"size": metadata.get("size"),
"type": metadata.get("type", "file"),
"forId": attachment.step_id,
"id": attachment.id or "",
"mime": attachment.mime,
"name": attachment.name or "",
"objectKey": attachment.object_key,
"url": attachment.url,
"threadId": attachment.thread_id,
}
def score_to_feedback_dict(
self, score: Optional[LiteralScore]
) -> "Optional[FeedbackDict]":
if not score:
return None
return {
"id": score.id or "",
"forId": score.step_id or "",
"value": cast(Literal[0, 1], score.value),
"comment": score.comment,
}
def step_to_step_dict(self, step: LiteralStep) -> "StepDict":
metadata = step.metadata or {}
input = (step.input or {}).get("content") or (
json.dumps(step.input) if step.input and step.input != {} else ""
)
output = (step.output or {}).get("content") or (
json.dumps(step.output) if step.output and step.output != {} else ""
)
user_feedback = (
next(
(
s
for s in step.scores
if s.type == "HUMAN" and s.name == "user-feedback"
),
None,
)
if step.scores
else None
)
return {
"createdAt": step.created_at,
"id": step.id or "",
"threadId": step.thread_id or "",
"parentId": step.parent_id,
"feedback": self.score_to_feedback_dict(user_feedback),
"start": step.start_time,
"end": step.end_time,
"type": step.type or "undefined",
"name": step.name or "",
"generation": step.generation.to_dict() if step.generation else None,
"input": input,
"output": output,
"showInput": metadata.get("showInput", False),
"disableFeedback": metadata.get("disableFeedback", False),
"indent": metadata.get("indent"),
"language": metadata.get("language"),
"isError": metadata.get("isError", False),
"waitForAnswer": metadata.get("waitForAnswer", False),
}
async def get_user(self, identifier: str) -> Optional[PersistedUser]:
user = await self.client.api.get_user(identifier=identifier)
if not user:
return None
return PersistedUser(
id=user.id or "",
identifier=user.identifier or "",
metadata=user.metadata,
createdAt=user.created_at or "",
)
async def create_user(self, user: User) -> Optional[PersistedUser]:
_user = await self.client.api.get_user(identifier=user.identifier)
if not _user:
_user = await self.client.api.create_user(
identifier=user.identifier, metadata=user.metadata
)
elif _user.id:
await self.client.api.update_user(id=_user.id, metadata=user.metadata)
return PersistedUser(
id=_user.id or "",
identifier=_user.identifier or "",
metadata=_user.metadata,
createdAt=_user.created_at or "",
)
async def delete_feedback(
self,
feedback_id: str,
):
if feedback_id:
await self.client.api.delete_score(
id=feedback_id,
)
return True
return False
async def upsert_feedback(
self,
feedback: Feedback,
):
if feedback.id:
await self.client.api.update_score(
id=feedback.id,
update_params={
"comment": feedback.comment,
"value": feedback.value,
},
)
return feedback.id
else:
created = await self.client.api.create_score(
step_id=feedback.forId,
value=feedback.value,
comment=feedback.comment,
name="user-feedback",
type="HUMAN",
)
return created.id or ""
@queue_until_user_message()
async def create_element(self, element: "Element"):
metadata = {
"size": element.size,
"language": element.language,
"display": element.display,
"type": element.type,
"page": getattr(element, "page", None),
}
if not element.for_id:
return
object_key = None
if not element.url:
if element.path:
async with aiofiles.open(element.path, "rb") as f:
content = await f.read() # type: Union[bytes, str]
elif element.content:
content = element.content
else:
raise ValueError("Either path or content must be provided")
uploaded = await self.client.api.upload_file(
content=content, mime=element.mime, thread_id=element.thread_id
)
object_key = uploaded["object_key"]
await self.client.api.send_steps(
[
{
"id": element.for_id,
"threadId": element.thread_id,
"attachments": [
{
"id": element.id,
"name": element.name,
"metadata": metadata,
"mime": element.mime,
"url": element.url,
"objectKey": object_key,
}
],
}
]
)
async def get_element(
self, thread_id: str, element_id: str
) -> Optional["ElementDict"]:
attachment = await self.client.api.get_attachment(id=element_id)
if not attachment:
return None
return self.attachment_to_element_dict(attachment)
@queue_until_user_message()
async def delete_element(self, element_id: str):
await self.client.api.delete_attachment(id=element_id)
@queue_until_user_message()
async def create_step(self, step_dict: "StepDict"):
metadata = {
"disableFeedback": step_dict.get("disableFeedback"),
"isError": step_dict.get("isError"),
"waitForAnswer": step_dict.get("waitForAnswer"),
"language": step_dict.get("language"),
"showInput": step_dict.get("showInput"),
}
step: LiteralStepDict = {
"createdAt": step_dict.get("createdAt"),
"startTime": step_dict.get("start"),
"endTime": step_dict.get("end"),
"generation": step_dict.get("generation"),
"id": step_dict.get("id"),
"parentId": step_dict.get("parentId"),
"name": step_dict.get("name"),
"threadId": step_dict.get("threadId"),
"type": step_dict.get("type"),
"metadata": metadata,
}
if step_dict.get("input"):
step["input"] = {"content": step_dict.get("input")}
if step_dict.get("output"):
step["output"] = {"content": step_dict.get("output")}
await self.client.api.send_steps([step])
@queue_until_user_message()
async def update_step(self, step_dict: "StepDict"):
await self.create_step(step_dict)
@queue_until_user_message()
async def delete_step(self, step_id: str):
await self.client.api.delete_step(id=step_id)
async def get_thread_author(self, thread_id: str) -> str:
thread = await self.get_thread(thread_id)
if not thread:
return ""
user_identifier = thread.get("userIdentifier")
if not user_identifier:
return ""
return user_identifier
async def delete_thread(self, thread_id: str):
await self.client.api.delete_thread(id=thread_id)
async def list_threads(
self, pagination: "Pagination", filters: "ThreadFilter"
) -> "PaginatedResponse[ThreadDict]":
if not filters.userId:
raise ValueError("userId is required")
literal_filters: LiteralThreadsFilters = [
{
"field": "participantId",
"operator": "eq",
"value": filters.userId,
}
]
if filters.search:
literal_filters.append(
{
"field": "stepOutput",
"operator": "ilike",
"value": filters.search,
"path": "content",
}
)
if filters.feedback is not None:
literal_filters.append(
{
"field": "scoreValue",
"operator": "eq",
"value": filters.feedback,
"path": "user-feedback",
}
)
return await self.client.api.list_threads(
first=pagination.first,
after=pagination.cursor,
filters=literal_filters,
order_by={"column": "createdAt", "direction": "DESC"},
)
async def get_thread(self, thread_id: str) -> "Optional[ThreadDict]":
thread = await self.client.api.get_thread(id=thread_id)
if not thread:
return None
elements = [] # List[ElementDict]
steps = [] # List[StepDict]
if thread.steps:
for step in thread.steps:
if config.ui.hide_cot and step.parent_id:
continue
for attachment in step.attachments:
elements.append(self.attachment_to_element_dict(attachment))
if not config.features.prompt_playground and step.generation:
step.generation = None
steps.append(self.step_to_step_dict(step))
return {
"createdAt": thread.created_at or "",
"id": thread.id,
"name": thread.name or None,
"steps": steps,
"elements": elements,
"metadata": thread.metadata,
"userId": thread.participant_id,
"userIdentifier": thread.participant_identifier,
"tags": thread.tags,
}
async def update_thread(
self,
thread_id: str,
name: Optional[str] = None,
user_id: Optional[str] = None,
metadata: Optional[Dict] = None,
tags: Optional[List[str]] = None,
):
await self.client.api.upsert_thread(
thread_id=thread_id,
name=name,
participant_id=user_id,
metadata=metadata,
tags=tags,
)
if api_key := os.environ.get("LITERAL_API_KEY"):
server = os.environ.get("LITERAL_SERVER")
_data_layer = ChainlitDataLayer(api_key=api_key, server=server)
def get_data_layer():
return _data_layer