chainlit 1.0.401__py3-none-any.whl → 2.0.4__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of chainlit might be problematic. Click here for more details.

Files changed (113) hide show
  1. chainlit/__init__.py +98 -279
  2. chainlit/_utils.py +8 -0
  3. chainlit/action.py +12 -10
  4. chainlit/{auth.py → auth/__init__.py} +28 -36
  5. chainlit/auth/cookie.py +123 -0
  6. chainlit/auth/jwt.py +39 -0
  7. chainlit/cache.py +4 -6
  8. chainlit/callbacks.py +362 -0
  9. chainlit/chat_context.py +64 -0
  10. chainlit/chat_settings.py +3 -1
  11. chainlit/cli/__init__.py +77 -8
  12. chainlit/config.py +191 -102
  13. chainlit/context.py +42 -13
  14. chainlit/copilot/dist/index.js +8750 -903
  15. chainlit/data/__init__.py +101 -416
  16. chainlit/data/acl.py +6 -2
  17. chainlit/data/base.py +107 -0
  18. chainlit/data/chainlit_data_layer.py +614 -0
  19. chainlit/data/dynamodb.py +590 -0
  20. chainlit/data/literalai.py +500 -0
  21. chainlit/data/sql_alchemy.py +721 -0
  22. chainlit/data/storage_clients/__init__.py +0 -0
  23. chainlit/data/storage_clients/azure.py +81 -0
  24. chainlit/data/storage_clients/azure_blob.py +89 -0
  25. chainlit/data/storage_clients/base.py +26 -0
  26. chainlit/data/storage_clients/gcs.py +88 -0
  27. chainlit/data/storage_clients/s3.py +75 -0
  28. chainlit/data/utils.py +29 -0
  29. chainlit/discord/__init__.py +6 -0
  30. chainlit/discord/app.py +354 -0
  31. chainlit/element.py +91 -33
  32. chainlit/emitter.py +81 -29
  33. chainlit/frontend/dist/assets/DailyMotion-Ce9dQoqZ.js +1 -0
  34. chainlit/frontend/dist/assets/Dataframe-C1XonMcV.js +22 -0
  35. chainlit/frontend/dist/assets/Facebook-DVVt6lrr.js +1 -0
  36. chainlit/frontend/dist/assets/FilePlayer-c7stW4vz.js +1 -0
  37. chainlit/frontend/dist/assets/Kaltura-BmMmgorA.js +1 -0
  38. chainlit/frontend/dist/assets/Mixcloud-Cw8hDmiO.js +1 -0
  39. chainlit/frontend/dist/assets/Mux-DiRZfeUf.js +1 -0
  40. chainlit/frontend/dist/assets/Preview-6Jt2mRHx.js +1 -0
  41. chainlit/frontend/dist/assets/SoundCloud-DKwcT58_.js +1 -0
  42. chainlit/frontend/dist/assets/Streamable-BVdxrEeX.js +1 -0
  43. chainlit/frontend/dist/assets/Twitch-DFqZR7Gu.js +1 -0
  44. chainlit/frontend/dist/assets/Vidyard-0BQAAtVk.js +1 -0
  45. chainlit/frontend/dist/assets/Vimeo-CRFSH0Vu.js +1 -0
  46. chainlit/frontend/dist/assets/Wistia-CKrmdQaG.js +1 -0
  47. chainlit/frontend/dist/assets/YouTube-CQpL-rvU.js +1 -0
  48. chainlit/frontend/dist/assets/index-DQmLRKyv.css +1 -0
  49. chainlit/frontend/dist/assets/index-QdmxtIMQ.js +8665 -0
  50. chainlit/frontend/dist/assets/react-plotly-B9hvVpUG.js +3484 -0
  51. chainlit/frontend/dist/index.html +2 -4
  52. chainlit/haystack/callbacks.py +4 -7
  53. chainlit/input_widget.py +8 -4
  54. chainlit/langchain/callbacks.py +103 -68
  55. chainlit/langflow/__init__.py +1 -0
  56. chainlit/llama_index/callbacks.py +65 -40
  57. chainlit/markdown.py +22 -6
  58. chainlit/message.py +54 -56
  59. chainlit/mistralai/__init__.py +50 -0
  60. chainlit/oauth_providers.py +266 -8
  61. chainlit/openai/__init__.py +10 -18
  62. chainlit/secret.py +1 -1
  63. chainlit/server.py +789 -228
  64. chainlit/session.py +108 -90
  65. chainlit/slack/__init__.py +6 -0
  66. chainlit/slack/app.py +397 -0
  67. chainlit/socket.py +199 -116
  68. chainlit/step.py +141 -89
  69. chainlit/sync.py +2 -1
  70. chainlit/teams/__init__.py +6 -0
  71. chainlit/teams/app.py +338 -0
  72. chainlit/translations/bn.json +244 -0
  73. chainlit/translations/en-US.json +122 -8
  74. chainlit/translations/gu.json +244 -0
  75. chainlit/translations/he-IL.json +244 -0
  76. chainlit/translations/hi.json +244 -0
  77. chainlit/translations/ja.json +242 -0
  78. chainlit/translations/kn.json +244 -0
  79. chainlit/translations/ml.json +244 -0
  80. chainlit/translations/mr.json +244 -0
  81. chainlit/translations/nl-NL.json +242 -0
  82. chainlit/translations/ta.json +244 -0
  83. chainlit/translations/te.json +244 -0
  84. chainlit/translations/zh-CN.json +243 -0
  85. chainlit/translations.py +60 -0
  86. chainlit/types.py +133 -28
  87. chainlit/user.py +14 -3
  88. chainlit/user_session.py +6 -3
  89. chainlit/utils.py +52 -5
  90. chainlit/version.py +3 -2
  91. {chainlit-1.0.401.dist-info → chainlit-2.0.4.dist-info}/METADATA +48 -50
  92. chainlit-2.0.4.dist-info/RECORD +107 -0
  93. chainlit/cli/utils.py +0 -24
  94. chainlit/frontend/dist/assets/index-9711593e.js +0 -723
  95. chainlit/frontend/dist/assets/index-d088547c.css +0 -1
  96. chainlit/frontend/dist/assets/react-plotly-d8762cc2.js +0 -3602
  97. chainlit/playground/__init__.py +0 -2
  98. chainlit/playground/config.py +0 -40
  99. chainlit/playground/provider.py +0 -108
  100. chainlit/playground/providers/__init__.py +0 -13
  101. chainlit/playground/providers/anthropic.py +0 -118
  102. chainlit/playground/providers/huggingface.py +0 -75
  103. chainlit/playground/providers/langchain.py +0 -89
  104. chainlit/playground/providers/openai.py +0 -408
  105. chainlit/playground/providers/vertexai.py +0 -171
  106. chainlit/translations/pt-BR.json +0 -155
  107. chainlit-1.0.401.dist-info/RECORD +0 -66
  108. /chainlit/copilot/dist/assets/{logo_dark-2a3cf740.svg → logo_dark-IkGJ_IwC.svg} +0 -0
  109. /chainlit/copilot/dist/assets/{logo_light-b078e7bc.svg → logo_light-Bb_IPh6r.svg} +0 -0
  110. /chainlit/frontend/dist/assets/{logo_dark-2a3cf740.svg → logo_dark-IkGJ_IwC.svg} +0 -0
  111. /chainlit/frontend/dist/assets/{logo_light-b078e7bc.svg → logo_light-Bb_IPh6r.svg} +0 -0
  112. {chainlit-1.0.401.dist-info → chainlit-2.0.4.dist-info}/WHEEL +0 -0
  113. {chainlit-1.0.401.dist-info → chainlit-2.0.4.dist-info}/entry_points.txt +0 -0
@@ -0,0 +1,614 @@
1
+ import json
2
+ import uuid
3
+ from datetime import datetime
4
+ from typing import TYPE_CHECKING, Any, Dict, List, Optional, Union
5
+
6
+ import aiofiles
7
+ import asyncpg # type: ignore
8
+
9
+ from chainlit.data.base import BaseDataLayer
10
+ from chainlit.data.storage_clients.base import BaseStorageClient
11
+ from chainlit.data.utils import queue_until_user_message
12
+ from chainlit.element import ElementDict
13
+ from chainlit.logger import logger
14
+ from chainlit.step import StepDict
15
+ from chainlit.types import (
16
+ Feedback,
17
+ PageInfo,
18
+ PaginatedResponse,
19
+ Pagination,
20
+ ThreadDict,
21
+ ThreadFilter,
22
+ )
23
+ from chainlit.user import PersistedUser, User
24
+
25
+ if TYPE_CHECKING:
26
+ from chainlit.element import Element, ElementDict
27
+ from chainlit.step import StepDict
28
+
29
+ ISO_FORMAT = "%Y-%m-%dT%H:%M:%S.%fZ"
30
+
31
+
32
+ class ChainlitDataLayer(BaseDataLayer):
33
+ def __init__(
34
+ self,
35
+ database_url: str,
36
+ storage_client: Optional[BaseStorageClient] = None,
37
+ show_logger: bool = False,
38
+ ):
39
+ self.database_url = database_url
40
+ self.pool: Optional[asyncpg.Pool] = None
41
+ self.storage_client = storage_client
42
+ self.show_logger = show_logger
43
+
44
+ async def connect(self):
45
+ if not self.pool:
46
+ self.pool = await asyncpg.create_pool(self.database_url)
47
+
48
+ async def get_current_timestamp(self) -> datetime:
49
+ return datetime.now()
50
+
51
+ async def execute_query(
52
+ self, query: str, params: Union[Dict, None] = None
53
+ ) -> List[Dict[str, Any]]:
54
+ if not self.pool:
55
+ await self.connect()
56
+
57
+ async with self.pool.acquire() as connection: # type: ignore
58
+ try:
59
+ if params:
60
+ records = await connection.fetch(query, *params.values())
61
+ else:
62
+ records = await connection.fetch(query)
63
+ return [dict(record) for record in records]
64
+ except Exception as e:
65
+ logger.error(f"Database error: {e!s}")
66
+ raise
67
+
68
+ async def get_user(self, identifier: str) -> Optional[PersistedUser]:
69
+ query = """
70
+ SELECT * FROM "User"
71
+ WHERE identifier = $1
72
+ """
73
+ result = await self.execute_query(query, {"identifier": identifier})
74
+ if not result or len(result) == 0:
75
+ return None
76
+ row = result[0]
77
+
78
+ return PersistedUser(
79
+ id=str(row.get("id")),
80
+ identifier=str(row.get("identifier")),
81
+ createdAt=row.get("createdAt").isoformat(), # type: ignore
82
+ metadata=json.loads(row.get("metadata", "{}")),
83
+ )
84
+
85
+ async def create_user(self, user: User) -> Optional[PersistedUser]:
86
+ query = """
87
+ INSERT INTO "User" (id, identifier, metadata, "createdAt", "updatedAt")
88
+ VALUES ($1, $2, $3, $4, $5)
89
+ ON CONFLICT (identifier) DO UPDATE
90
+ SET metadata = $3
91
+ RETURNING *
92
+ """
93
+ now = await self.get_current_timestamp()
94
+ params = {
95
+ "id": str(uuid.uuid4()),
96
+ "identifier": user.identifier,
97
+ "metadata": json.dumps(user.metadata),
98
+ "created_at": now,
99
+ "updated_at": now,
100
+ }
101
+ result = await self.execute_query(query, params)
102
+ row = result[0]
103
+
104
+ return PersistedUser(
105
+ id=str(row.get("id")),
106
+ identifier=str(row.get("identifier")),
107
+ createdAt=row.get("createdAt").isoformat(), # type: ignore
108
+ metadata=json.loads(row.get("metadata", "{}")),
109
+ )
110
+
111
+ async def delete_feedback(self, feedback_id: str) -> bool:
112
+ query = """
113
+ DELETE FROM "Feedback" WHERE id = $1
114
+ """
115
+ await self.execute_query(query, {"feedback_id": feedback_id})
116
+ return True
117
+
118
+ async def upsert_feedback(self, feedback: Feedback) -> str:
119
+ query = """
120
+ INSERT INTO "Feedback" (id, "stepId", name, value, comment)
121
+ VALUES ($1, $2, $3, $4, $5)
122
+ ON CONFLICT (id) DO UPDATE
123
+ SET value = $4, comment = $5
124
+ RETURNING id
125
+ """
126
+ feedback_id = feedback.id or str(uuid.uuid4())
127
+ params = {
128
+ "id": feedback_id,
129
+ "step_id": feedback.forId,
130
+ "name": "user_feedback",
131
+ "value": float(feedback.value),
132
+ "comment": feedback.comment,
133
+ }
134
+ results = await self.execute_query(query, params)
135
+ return str(results[0]["id"])
136
+
137
+ @queue_until_user_message()
138
+ async def create_element(self, element: "Element"):
139
+ if not self.storage_client:
140
+ logger.warn(
141
+ "Data Layer: create_element error. No cloud storage configured!"
142
+ )
143
+ return
144
+
145
+ if not element.for_id:
146
+ return
147
+
148
+ if element.thread_id:
149
+ query = 'SELECT id FROM "Thread" WHERE id = $1'
150
+ results = await self.execute_query(query, {"thread_id": element.thread_id})
151
+ if not results:
152
+ await self.update_thread(thread_id=element.thread_id)
153
+
154
+ if element.for_id:
155
+ query = 'SELECT id FROM "Step" WHERE id = $1'
156
+ results = await self.execute_query(query, {"step_id": element.for_id})
157
+ if not results:
158
+ await self.create_step(
159
+ {
160
+ "id": element.for_id,
161
+ "metadata": {},
162
+ "type": "run",
163
+ "start_time": await self.get_current_timestamp(),
164
+ "end_time": await self.get_current_timestamp(),
165
+ }
166
+ )
167
+ content: Optional[Union[bytes, str]] = None
168
+
169
+ if element.path:
170
+ async with aiofiles.open(element.path, "rb") as f:
171
+ content = await f.read()
172
+ elif element.content:
173
+ content = element.content
174
+ elif not element.url:
175
+ raise ValueError("Element url, path or content must be provided")
176
+
177
+ if element.thread_id:
178
+ path = f"threads/{element.thread_id}/files/{element.id}"
179
+ else:
180
+ path = f"files/{element.id}"
181
+
182
+ if content is not None:
183
+ await self.storage_client.upload_file(
184
+ object_key=path,
185
+ data=content,
186
+ mime=element.mime or "application/octet-stream",
187
+ overwrite=True,
188
+ )
189
+
190
+ query = """
191
+ INSERT INTO "Element" (
192
+ id, "threadId", "stepId", metadata, mime, name, "objectKey", url,
193
+ "chainlitKey", display, size, language, page, props
194
+ ) VALUES (
195
+ $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14
196
+ )
197
+ """
198
+ params = {
199
+ "id": element.id,
200
+ "thread_id": element.thread_id,
201
+ "step_id": element.for_id,
202
+ "metadata": json.dumps(
203
+ {
204
+ "size": element.size,
205
+ "language": element.language,
206
+ "display": element.display,
207
+ "type": element.type,
208
+ "page": getattr(element, "page", None),
209
+ }
210
+ ),
211
+ "mime": element.mime,
212
+ "name": element.name,
213
+ "object_key": path,
214
+ "url": element.url,
215
+ "chainlit_key": element.chainlit_key,
216
+ "display": element.display,
217
+ "size": element.size,
218
+ "language": element.language,
219
+ "page": getattr(element, "page", None),
220
+ "props": json.dumps(getattr(element, "props", {})),
221
+ }
222
+ await self.execute_query(query, params)
223
+
224
+ async def get_element(
225
+ self, thread_id: str, element_id: str
226
+ ) -> Optional[ElementDict]:
227
+ query = """
228
+ SELECT * FROM "Element"
229
+ WHERE id = $1 AND "threadId" = $2
230
+ """
231
+ results = await self.execute_query(
232
+ query, {"element_id": element_id, "thread_id": thread_id}
233
+ )
234
+
235
+ if not results:
236
+ return None
237
+
238
+ row = results[0]
239
+ metadata = json.loads(row.get("metadata", "{}"))
240
+
241
+ return ElementDict(
242
+ id=str(row["id"]),
243
+ threadId=str(row["threadId"]),
244
+ type=metadata.get("type", "file"),
245
+ url=str(row["url"]),
246
+ name=str(row["name"]),
247
+ mime=str(row["mime"]),
248
+ objectKey=str(row["objectKey"]),
249
+ forId=str(row["stepId"]),
250
+ chainlitKey=row.get("chainlitKey"),
251
+ display=row["display"],
252
+ size=row["size"],
253
+ language=row["language"],
254
+ page=row["page"],
255
+ autoPlay=row.get("autoPlay"),
256
+ playerConfig=row.get("playerConfig"),
257
+ props=json.loads(row.get("props", "{}")),
258
+ )
259
+
260
+ @queue_until_user_message()
261
+ async def delete_element(self, element_id: str, thread_id: Optional[str] = None):
262
+ query = """
263
+ SELECT * FROM "Element"
264
+ WHERE id = $1
265
+ """
266
+ elements = await self.execute_query(query, {"id": element_id})
267
+
268
+ if self.storage_client is not None and len(elements) > 0:
269
+ if elements[0]["objectKey"]:
270
+ await self.storage_client.delete_file(
271
+ object_key=elements[0]["objectKey"]
272
+ )
273
+ query = """
274
+ DELETE FROM "Element"
275
+ WHERE id = $1
276
+ """
277
+ params = {"id": element_id}
278
+
279
+ if thread_id:
280
+ query += ' AND "threadId" = $2'
281
+ params["thread_id"] = thread_id
282
+
283
+ await self.execute_query(query, params)
284
+
285
+ @queue_until_user_message()
286
+ async def create_step(self, step_dict: StepDict):
287
+ if step_dict.get("threadId"):
288
+ thread_query = 'SELECT id FROM "Thread" WHERE id = $1'
289
+ thread_results = await self.execute_query(
290
+ thread_query, {"thread_id": step_dict["threadId"]}
291
+ )
292
+ if not thread_results:
293
+ await self.update_thread(thread_id=step_dict["threadId"])
294
+
295
+ if step_dict.get("parentId"):
296
+ parent_query = 'SELECT id FROM "Step" WHERE id = $1'
297
+ parent_results = await self.execute_query(
298
+ parent_query, {"parent_id": step_dict["parentId"]}
299
+ )
300
+ if not parent_results:
301
+ await self.create_step(
302
+ {
303
+ "id": step_dict["parentId"],
304
+ "metadata": {},
305
+ "type": "run",
306
+ "createdAt": step_dict.get("createdAt"),
307
+ }
308
+ )
309
+
310
+ query = """
311
+ INSERT INTO "Step" (
312
+ id, "threadId", "parentId", input, metadata, name, output,
313
+ type, "startTime", "endTime", "showInput", "isError"
314
+ ) VALUES (
315
+ $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12
316
+ )
317
+ ON CONFLICT (id) DO UPDATE SET
318
+ "parentId" = COALESCE(EXCLUDED."parentId", "Step"."parentId"),
319
+ input = COALESCE(EXCLUDED.input, "Step".input),
320
+ metadata = CASE
321
+ WHEN EXCLUDED.metadata <> '{}' THEN EXCLUDED.metadata
322
+ ELSE "Step".metadata
323
+ END,
324
+ name = COALESCE(EXCLUDED.name, "Step".name),
325
+ output = COALESCE(EXCLUDED.output, "Step".output),
326
+ type = CASE
327
+ WHEN EXCLUDED.type = 'run' THEN "Step".type
328
+ ELSE EXCLUDED.type
329
+ END,
330
+ "threadId" = COALESCE(EXCLUDED."threadId", "Step"."threadId"),
331
+ "endTime" = COALESCE(EXCLUDED."endTime", "Step"."endTime"),
332
+ "startTime" = LEAST(EXCLUDED."startTime", "Step"."startTime"),
333
+ "showInput" = COALESCE(EXCLUDED."showInput", "Step"."showInput"),
334
+ "isError" = COALESCE(EXCLUDED."isError", "Step"."isError")
335
+ """
336
+
337
+ timestamp = await self.get_current_timestamp()
338
+ created_at = step_dict.get("createdAt")
339
+ if created_at:
340
+ timestamp = datetime.strptime(created_at, ISO_FORMAT)
341
+
342
+ params = {
343
+ "id": step_dict["id"],
344
+ "thread_id": step_dict.get("threadId"),
345
+ "parent_id": step_dict.get("parentId"),
346
+ "input": step_dict.get("input"),
347
+ "metadata": json.dumps(step_dict.get("metadata", {})),
348
+ "name": step_dict.get("name"),
349
+ "output": step_dict.get("output"),
350
+ "type": step_dict["type"],
351
+ "start_time": timestamp,
352
+ "end_time": timestamp,
353
+ "show_input": str(step_dict.get("showInput", "json")),
354
+ "is_error": step_dict.get("isError", False),
355
+ }
356
+ await self.execute_query(query, params)
357
+
358
+ @queue_until_user_message()
359
+ async def update_step(self, step_dict: StepDict):
360
+ await self.create_step(step_dict)
361
+
362
+ @queue_until_user_message()
363
+ async def delete_step(self, step_id: str):
364
+ # Delete associated elements and feedbacks first
365
+ await self.execute_query(
366
+ 'DELETE FROM "Element" WHERE "stepId" = $1', {"step_id": step_id}
367
+ )
368
+ await self.execute_query(
369
+ 'DELETE FROM "Feedback" WHERE "stepId" = $1', {"step_id": step_id}
370
+ )
371
+ # Delete the step
372
+ await self.execute_query(
373
+ 'DELETE FROM "Step" WHERE id = $1', {"step_id": step_id}
374
+ )
375
+
376
+ async def get_thread_author(self, thread_id: str) -> str:
377
+ query = """
378
+ SELECT u.identifier
379
+ FROM "Thread" t
380
+ JOIN "User" u ON t."userId" = u.id
381
+ WHERE t.id = $1
382
+ """
383
+ results = await self.execute_query(query, {"thread_id": thread_id})
384
+ if not results:
385
+ raise ValueError(f"Thread {thread_id} not found")
386
+ return results[0]["identifier"]
387
+
388
+ async def delete_thread(self, thread_id: str):
389
+ elements_query = """
390
+ SELECT * FROM "Element"
391
+ WHERE "threadId" = $1
392
+ """
393
+ elements_results = await self.execute_query(
394
+ elements_query, {"thread_id": thread_id}
395
+ )
396
+
397
+ if self.storage_client is not None:
398
+ for elem in elements_results:
399
+ if elem["objectKey"]:
400
+ await self.storage_client.delete_file(object_key=elem["objectKey"])
401
+
402
+ await self.execute_query(
403
+ 'DELETE FROM "Thread" WHERE id = $1', {"thread_id": thread_id}
404
+ )
405
+
406
+ async def list_threads(
407
+ self, pagination: Pagination, filters: ThreadFilter
408
+ ) -> PaginatedResponse[ThreadDict]:
409
+ query = """
410
+ SELECT
411
+ t.*,
412
+ u.identifier as user_identifier,
413
+ (SELECT COUNT(*) FROM "Thread" WHERE "userId" = t."userId") as total
414
+ FROM "Thread" t
415
+ LEFT JOIN "User" u ON t."userId" = u.id
416
+ WHERE t."deletedAt" IS NULL
417
+ """
418
+ params: Dict[str, Any] = {}
419
+ param_count = 1
420
+
421
+ if filters.search:
422
+ query += f" AND t.name ILIKE ${param_count}"
423
+ params["name"] = f"%{filters.search}%"
424
+ param_count += 1
425
+
426
+ if filters.userId:
427
+ query += f' AND t."userId" = ${param_count}'
428
+ params["user_id"] = filters.userId
429
+ param_count += 1
430
+
431
+ if pagination.cursor:
432
+ query += f' AND t."createdAt" < (SELECT "createdAt" FROM "Thread" WHERE id = ${param_count})'
433
+ params["cursor"] = pagination.cursor
434
+ param_count += 1
435
+
436
+ query += f' ORDER BY t."createdAt" DESC LIMIT ${param_count}'
437
+ params["limit"] = pagination.first + 1
438
+
439
+ results = await self.execute_query(query, params)
440
+ threads = results
441
+
442
+ has_next_page = len(threads) > pagination.first
443
+ if has_next_page:
444
+ threads = threads[:-1]
445
+
446
+ thread_dicts = []
447
+ for thread in threads:
448
+ thread_dict = ThreadDict(
449
+ id=str(thread["id"]),
450
+ createdAt=thread["createdAt"].isoformat(),
451
+ name=thread["name"],
452
+ userId=str(thread["userId"]) if thread["userId"] else None,
453
+ userIdentifier=thread["user_identifier"],
454
+ metadata=json.loads(thread["metadata"]),
455
+ steps=[],
456
+ elements=[],
457
+ tags=[],
458
+ )
459
+ thread_dicts.append(thread_dict)
460
+
461
+ return PaginatedResponse(
462
+ pageInfo=PageInfo(
463
+ hasNextPage=has_next_page,
464
+ startCursor=thread_dicts[0]["id"] if thread_dicts else None,
465
+ endCursor=thread_dicts[-1]["id"] if thread_dicts else None,
466
+ ),
467
+ data=thread_dicts,
468
+ )
469
+
470
+ async def get_thread(self, thread_id: str) -> Optional[ThreadDict]:
471
+ query = """
472
+ SELECT t.*, u.identifier as user_identifier
473
+ FROM "Thread" t
474
+ LEFT JOIN "User" u ON t."userId" = u.id
475
+ WHERE t.id = $1 AND t."deletedAt" IS NULL
476
+ """
477
+ results = await self.execute_query(query, {"thread_id": thread_id})
478
+
479
+ if not results:
480
+ return None
481
+
482
+ thread = results[0]
483
+
484
+ # Get steps
485
+ steps_query = """
486
+ SELECT * FROM "Step"
487
+ WHERE "threadId" = $1
488
+ ORDER BY "startTime"
489
+ """
490
+ steps_results = await self.execute_query(steps_query, {"thread_id": thread_id})
491
+
492
+ # Get elements
493
+ elements_query = """
494
+ SELECT * FROM "Element"
495
+ WHERE "threadId" = $1
496
+ """
497
+ elements_results = await self.execute_query(
498
+ elements_query, {"thread_id": thread_id}
499
+ )
500
+
501
+ if self.storage_client is not None:
502
+ for elem in elements_results:
503
+ if not elem["url"] and elem["objectKey"]:
504
+ elem["url"] = await self.storage_client.get_read_url(
505
+ object_key=elem["objectKey"],
506
+ )
507
+
508
+ return ThreadDict(
509
+ id=str(thread["id"]),
510
+ createdAt=thread["createdAt"].isoformat(),
511
+ name=thread["name"],
512
+ userId=str(thread["userId"]) if thread["userId"] else None,
513
+ userIdentifier=thread["user_identifier"],
514
+ metadata=json.loads(thread["metadata"]),
515
+ steps=[self._convert_step_row_to_dict(step) for step in steps_results],
516
+ elements=[
517
+ self._convert_element_row_to_dict(elem) for elem in elements_results
518
+ ],
519
+ tags=[],
520
+ )
521
+
522
+ async def update_thread(
523
+ self,
524
+ thread_id: str,
525
+ name: Optional[str] = None,
526
+ user_id: Optional[str] = None,
527
+ metadata: Optional[Dict] = None,
528
+ tags: Optional[List[str]] = None,
529
+ ):
530
+ if self.show_logger:
531
+ logger.info(f"asyncpg: update_thread, thread_id={thread_id}")
532
+
533
+ thread_name = truncate(
534
+ name
535
+ if name is not None
536
+ else (metadata.get("name") if metadata and "name" in metadata else None)
537
+ )
538
+
539
+ data = {
540
+ "id": thread_id,
541
+ "name": thread_name,
542
+ "userId": user_id,
543
+ "tags": tags,
544
+ "metadata": json.dumps(metadata or {}),
545
+ }
546
+
547
+ # Remove None values
548
+ data = {k: v for k, v in data.items() if v is not None}
549
+
550
+ # Build the query dynamically based on available fields
551
+ columns = [f'"{k}"' for k in data.keys()]
552
+ placeholders = [f"${i + 1}" for i in range(len(data))]
553
+ values = list(data.values())
554
+
555
+ update_sets = [f'"{k}" = EXCLUDED."{k}"' for k in data.keys() if k != "id"]
556
+
557
+ query = f"""
558
+ INSERT INTO "Thread" ({", ".join(columns)})
559
+ VALUES ({", ".join(placeholders)})
560
+ ON CONFLICT (id) DO UPDATE
561
+ SET {", ".join(update_sets)};
562
+ """
563
+
564
+ await self.execute_query(query, {str(i + 1): v for i, v in enumerate(values)})
565
+
566
+ def _convert_step_row_to_dict(self, row: Dict) -> StepDict:
567
+ return StepDict(
568
+ id=str(row["id"]),
569
+ threadId=str(row["threadId"]) if row.get("threadId") else "",
570
+ parentId=str(row["parentId"]) if row.get("parentId") else None,
571
+ name=str(row.get("name")),
572
+ type=row["type"],
573
+ input=row.get("input", {}),
574
+ output=row.get("output", {}),
575
+ metadata=json.loads(row.get("metadata", "{}")),
576
+ createdAt=row["createdAt"].isoformat() if row.get("createdAt") else None,
577
+ start=row["startTime"].isoformat() if row.get("startTime") else None,
578
+ showInput=row.get("showInput"),
579
+ isError=row.get("isError"),
580
+ end=row["endTime"].isoformat() if row.get("endTime") else None,
581
+ )
582
+
583
+ def _convert_element_row_to_dict(self, row: Dict) -> ElementDict:
584
+ metadata = json.loads(row.get("metadata", "{}"))
585
+ return ElementDict(
586
+ id=str(row["id"]),
587
+ threadId=str(row["threadId"]) if row.get("threadId") else None,
588
+ type=metadata.get("type", "file"),
589
+ url=row["url"],
590
+ name=row["name"],
591
+ mime=row["mime"],
592
+ objectKey=row["objectKey"],
593
+ forId=str(row["stepId"]),
594
+ chainlitKey=row.get("chainlitKey"),
595
+ display=row["display"],
596
+ size=row["size"],
597
+ language=row["language"],
598
+ page=row["page"],
599
+ autoPlay=row.get("autoPlay"),
600
+ playerConfig=row.get("playerConfig"),
601
+ props=json.loads(row.get("props") or "{}"),
602
+ )
603
+
604
+ async def build_debug_url(self) -> str:
605
+ return ""
606
+
607
+ async def cleanup(self):
608
+ """Cleanup database connections"""
609
+ if self.pool:
610
+ await self.pool.close()
611
+
612
+
613
+ def truncate(text: Optional[str], max_length: int = 255) -> Optional[str]:
614
+ return None if text is None else text[:max_length]