chainlit 2.0rc1__py3-none-any.whl → 2.0.2__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.
- chainlit/__init__.py +47 -57
- chainlit/action.py +8 -8
- chainlit/auth/__init__.py +1 -1
- chainlit/auth/cookie.py +7 -9
- chainlit/auth/jwt.py +5 -3
- chainlit/callbacks.py +1 -1
- chainlit/config.py +8 -59
- chainlit/copilot/dist/index.js +8319 -1019
- chainlit/data/__init__.py +71 -2
- chainlit/data/chainlit_data_layer.py +608 -0
- chainlit/data/literalai.py +1 -1
- chainlit/data/sql_alchemy.py +26 -2
- chainlit/data/storage_clients/azure_blob.py +89 -0
- chainlit/data/storage_clients/base.py +10 -0
- chainlit/data/storage_clients/gcs.py +88 -0
- chainlit/data/storage_clients/s3.py +42 -4
- chainlit/element.py +7 -4
- chainlit/emitter.py +9 -14
- chainlit/frontend/dist/assets/{DailyMotion-C-_sjrtO.js → DailyMotion-DFvM941y.js} +1 -1
- chainlit/frontend/dist/assets/Dataframe-CA6SlUSB.js +22 -0
- chainlit/frontend/dist/assets/{Facebook-bB34P03l.js → Facebook-BM4MwXR1.js} +1 -1
- chainlit/frontend/dist/assets/{FilePlayer-BWgqGrXv.js → FilePlayer-CfjB8iXr.js} +1 -1
- chainlit/frontend/dist/assets/{Kaltura-OY4P9Ofd.js → Kaltura-Bg-U6Xkz.js} +1 -1
- chainlit/frontend/dist/assets/{Mixcloud-9CtT8w5Y.js → Mixcloud-xJrfoMTv.js} +1 -1
- chainlit/frontend/dist/assets/{Mux-BH9A0qEi.js → Mux-CKnKDBmk.js} +1 -1
- chainlit/frontend/dist/assets/{Preview-Og00EJ05.js → Preview-DwHPdmIg.js} +1 -1
- chainlit/frontend/dist/assets/{SoundCloud-D7resGfn.js → SoundCloud-Crd5dwXV.js} +1 -1
- chainlit/frontend/dist/assets/{Streamable-6f_6bYz1.js → Streamable-Dq0c8lyx.js} +1 -1
- chainlit/frontend/dist/assets/{Twitch-BZJl3peM.js → Twitch-DIDvP936.js} +1 -1
- chainlit/frontend/dist/assets/{Vidyard-B7tv4b8_.js → Vidyard-B1dz9WN4.js} +1 -1
- chainlit/frontend/dist/assets/{Vimeo-F-eA4zQI.js → Vimeo-22Su6q2w.js} +1 -1
- chainlit/frontend/dist/assets/Wistia-C7adXRjN.js +1 -0
- chainlit/frontend/dist/assets/{YouTube-aFdJGjI1.js → YouTube-Dt4UMtQI.js} +1 -1
- chainlit/frontend/dist/assets/index-DbdLVHtZ.js +8665 -0
- chainlit/frontend/dist/assets/index-g8LTJwwr.css +1 -0
- chainlit/frontend/dist/assets/{react-plotly-DoUJXMgz.js → react-plotly-DvpXYYRJ.js} +1 -1
- chainlit/frontend/dist/index.html +2 -2
- chainlit/message.py +1 -3
- chainlit/server.py +297 -78
- chainlit/session.py +9 -0
- chainlit/socket.py +5 -53
- chainlit/step.py +0 -1
- chainlit/translations/en-US.json +1 -1
- chainlit/types.py +17 -3
- chainlit/user_session.py +1 -0
- {chainlit-2.0rc1.dist-info → chainlit-2.0.2.dist-info}/METADATA +4 -35
- {chainlit-2.0rc1.dist-info → chainlit-2.0.2.dist-info}/RECORD +49 -45
- chainlit/frontend/dist/assets/Wistia-Dhxhn3IB.js +0 -1
- chainlit/frontend/dist/assets/index-Ba33_hdJ.js +0 -1091
- chainlit/frontend/dist/assets/index-CwmincdQ.css +0 -1
- {chainlit-2.0rc1.dist-info → chainlit-2.0.2.dist-info}/WHEEL +0 -0
- {chainlit-2.0rc1.dist-info → chainlit-2.0.2.dist-info}/entry_points.txt +0 -0
chainlit/data/__init__.py
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import os
|
|
2
|
+
import warnings
|
|
2
3
|
from typing import Optional
|
|
3
4
|
|
|
4
5
|
from .base import BaseDataLayer
|
|
@@ -16,7 +17,6 @@ def get_data_layer():
|
|
|
16
17
|
if not _data_layer_initialized:
|
|
17
18
|
if _data_layer:
|
|
18
19
|
# Data layer manually set, warn user that this is deprecated.
|
|
19
|
-
import warnings
|
|
20
20
|
|
|
21
21
|
warnings.warn(
|
|
22
22
|
"Setting data layer manually is deprecated. Use @data_layer instead.",
|
|
@@ -29,8 +29,77 @@ def get_data_layer():
|
|
|
29
29
|
if config.code.data_layer:
|
|
30
30
|
# When @data_layer is configured, call it to get data layer.
|
|
31
31
|
_data_layer = config.code.data_layer()
|
|
32
|
+
elif database_url := os.environ.get("DATABASE_URL"):
|
|
33
|
+
# Default to Chainlit data layer if DATABASE_URL specified.
|
|
34
|
+
from .chainlit_data_layer import ChainlitDataLayer
|
|
35
|
+
|
|
36
|
+
if os.environ.get("LITERAL_API_KEY"):
|
|
37
|
+
warnings.warn(
|
|
38
|
+
"Both LITERAL_API_KEY and DATABASE_URL specified. Ignoring Literal AI data layer and relying on data layer pointing to DATABASE_URL."
|
|
39
|
+
)
|
|
40
|
+
bucket_name = os.environ.get("BUCKET_NAME")
|
|
41
|
+
|
|
42
|
+
# AWS S3
|
|
43
|
+
aws_region = os.getenv("APP_AWS_REGION")
|
|
44
|
+
aws_access_key = os.getenv("APP_AWS_ACCESS_KEY")
|
|
45
|
+
aws_secret_key = os.getenv("APP_AWS_SECRET_KEY")
|
|
46
|
+
dev_aws_endpoint = os.getenv("DEV_AWS_ENDPOINT")
|
|
47
|
+
is_using_s3 = bool(aws_access_key and aws_secret_key and aws_region)
|
|
48
|
+
|
|
49
|
+
# Google Cloud Storage
|
|
50
|
+
gcs_project_id = os.getenv("APP_GCS_PROJECT_ID")
|
|
51
|
+
gcs_client_email = os.getenv("APP_GCS_CLIENT_EMAIL")
|
|
52
|
+
gcs_private_key = os.getenv("APP_GCS_PRIVATE_KEY")
|
|
53
|
+
is_using_gcs = bool(
|
|
54
|
+
gcs_project_id and gcs_client_email and gcs_private_key
|
|
55
|
+
)
|
|
56
|
+
|
|
57
|
+
# Azure Storage
|
|
58
|
+
azure_storage_account = os.getenv("APP_AZURE_STORAGE_ACCOUNT")
|
|
59
|
+
azure_storage_key = os.getenv("APP_AZURE_STORAGE_ACCESS_KEY")
|
|
60
|
+
is_using_azure = bool(azure_storage_account and azure_storage_key)
|
|
61
|
+
|
|
62
|
+
storage_client = None
|
|
63
|
+
|
|
64
|
+
if sum([is_using_s3, is_using_gcs, is_using_azure]) > 1:
|
|
65
|
+
warnings.warn(
|
|
66
|
+
"Multiple storage configurations detected. Please use only one."
|
|
67
|
+
)
|
|
68
|
+
elif is_using_s3:
|
|
69
|
+
from chainlit.data.storage_clients.s3 import S3StorageClient
|
|
70
|
+
|
|
71
|
+
storage_client = S3StorageClient(
|
|
72
|
+
bucket=bucket_name,
|
|
73
|
+
region_name=aws_region,
|
|
74
|
+
aws_access_key_id=aws_access_key,
|
|
75
|
+
aws_secret_access_key=aws_secret_key,
|
|
76
|
+
endpoint_url=dev_aws_endpoint,
|
|
77
|
+
)
|
|
78
|
+
elif is_using_gcs:
|
|
79
|
+
from chainlit.data.storage_clients.gcs import GCSStorageClient
|
|
80
|
+
|
|
81
|
+
storage_client = GCSStorageClient(
|
|
82
|
+
project_id=gcs_project_id,
|
|
83
|
+
client_email=gcs_client_email,
|
|
84
|
+
private_key=gcs_private_key,
|
|
85
|
+
bucket_name=bucket_name,
|
|
86
|
+
)
|
|
87
|
+
elif is_using_azure:
|
|
88
|
+
from chainlit.data.storage_clients.azure_blob import (
|
|
89
|
+
AzureBlobStorageClient,
|
|
90
|
+
)
|
|
91
|
+
|
|
92
|
+
storage_client = AzureBlobStorageClient(
|
|
93
|
+
container_name=bucket_name,
|
|
94
|
+
storage_account=azure_storage_account,
|
|
95
|
+
storage_key=azure_storage_key,
|
|
96
|
+
)
|
|
97
|
+
|
|
98
|
+
_data_layer = ChainlitDataLayer(
|
|
99
|
+
database_url=database_url, storage_client=storage_client
|
|
100
|
+
)
|
|
32
101
|
elif api_key := os.environ.get("LITERAL_API_KEY"):
|
|
33
|
-
# When LITERAL_API_KEY is defined, use
|
|
102
|
+
# When LITERAL_API_KEY is defined, use Literal AI data layer
|
|
34
103
|
from .literalai import LiteralDataLayer
|
|
35
104
|
|
|
36
105
|
# support legacy LITERAL_SERVER variable as fallback
|
|
@@ -0,0 +1,608 @@
|
|
|
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.name}"
|
|
179
|
+
else:
|
|
180
|
+
path = f"files/{element.name}"
|
|
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": 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
|
+
data = {
|
|
534
|
+
"id": thread_id,
|
|
535
|
+
"name": (
|
|
536
|
+
name
|
|
537
|
+
if name is not None
|
|
538
|
+
else (metadata.get("name") if metadata and "name" in metadata else None)
|
|
539
|
+
),
|
|
540
|
+
"userId": user_id,
|
|
541
|
+
"tags": tags,
|
|
542
|
+
"metadata": json.dumps(metadata or {}),
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
# Remove None values
|
|
546
|
+
data = {k: v for k, v in data.items() if v is not None}
|
|
547
|
+
|
|
548
|
+
# Build the query dynamically based on available fields
|
|
549
|
+
columns = [f'"{k}"' for k in data.keys()]
|
|
550
|
+
placeholders = [f"${i + 1}" for i in range(len(data))]
|
|
551
|
+
values = list(data.values())
|
|
552
|
+
|
|
553
|
+
update_sets = [f'"{k}" = EXCLUDED."{k}"' for k in data.keys() if k != "id"]
|
|
554
|
+
|
|
555
|
+
query = f"""
|
|
556
|
+
INSERT INTO "Thread" ({", ".join(columns)})
|
|
557
|
+
VALUES ({", ".join(placeholders)})
|
|
558
|
+
ON CONFLICT (id) DO UPDATE
|
|
559
|
+
SET {", ".join(update_sets)};
|
|
560
|
+
"""
|
|
561
|
+
|
|
562
|
+
await self.execute_query(query, {str(i + 1): v for i, v in enumerate(values)})
|
|
563
|
+
|
|
564
|
+
def _convert_step_row_to_dict(self, row: Dict) -> StepDict:
|
|
565
|
+
return StepDict(
|
|
566
|
+
id=str(row["id"]),
|
|
567
|
+
threadId=str(row["threadId"]) if row.get("threadId") else "",
|
|
568
|
+
parentId=str(row["parentId"]) if row.get("parentId") else None,
|
|
569
|
+
name=str(row.get("name")),
|
|
570
|
+
type=row["type"],
|
|
571
|
+
input=row.get("input", {}),
|
|
572
|
+
output=row.get("output", {}),
|
|
573
|
+
metadata=json.loads(row.get("metadata", "{}")),
|
|
574
|
+
createdAt=row["createdAt"].isoformat() if row.get("createdAt") else None,
|
|
575
|
+
start=row["startTime"].isoformat() if row.get("startTime") else None,
|
|
576
|
+
showInput=row.get("showInput"),
|
|
577
|
+
isError=row.get("isError"),
|
|
578
|
+
end=row["endTime"].isoformat() if row.get("endTime") else None,
|
|
579
|
+
)
|
|
580
|
+
|
|
581
|
+
def _convert_element_row_to_dict(self, row: Dict) -> ElementDict:
|
|
582
|
+
metadata = json.loads(row.get("metadata", "{}"))
|
|
583
|
+
return ElementDict(
|
|
584
|
+
id=str(row["id"]),
|
|
585
|
+
threadId=str(row["threadId"]) if row.get("threadId") else None,
|
|
586
|
+
type=metadata.get("type", "file"),
|
|
587
|
+
url=row["url"],
|
|
588
|
+
name=row["name"],
|
|
589
|
+
mime=row["mime"],
|
|
590
|
+
objectKey=row["objectKey"],
|
|
591
|
+
forId=str(row["stepId"]),
|
|
592
|
+
chainlitKey=row.get("chainlitKey"),
|
|
593
|
+
display=row["display"],
|
|
594
|
+
size=row["size"],
|
|
595
|
+
language=row["language"],
|
|
596
|
+
page=row["page"],
|
|
597
|
+
autoPlay=row.get("autoPlay"),
|
|
598
|
+
playerConfig=row.get("playerConfig"),
|
|
599
|
+
props=json.loads(row.get("props") or "{}"),
|
|
600
|
+
)
|
|
601
|
+
|
|
602
|
+
async def build_debug_url(self) -> str:
|
|
603
|
+
return ""
|
|
604
|
+
|
|
605
|
+
async def cleanup(self):
|
|
606
|
+
"""Cleanup database connections"""
|
|
607
|
+
if self.pool:
|
|
608
|
+
await self.pool.close()
|