forked from openai/chatkit-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_store.py
More file actions
448 lines (391 loc) · 16.1 KB
/
Copy pathtest_store.py
File metadata and controls
448 lines (391 loc) · 16.1 KB
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
import sqlite3
from abc import ABC, abstractmethod
from datetime import datetime, timedelta
import pytest
from helpers.mock_store import SQLiteStore
from pydantic import AnyUrl
from chatkit.store import NotFoundError, Store
from chatkit.types import (
AssistantMessageContent,
AssistantMessageItem,
FileAttachment,
ImageAttachment,
InferenceOptions,
ThreadItem,
ThreadMetadata,
UserMessageItem,
UserMessageTextContent,
WidgetItem,
)
from chatkit.widgets import Card, Col, Text
from tests._types import RequestContext
def make_thread(thread_id="test_thread", created_at=None):
if created_at is None:
created_at = datetime.now()
return ThreadMetadata(
id=thread_id,
title="Test Thread",
created_at=created_at,
metadata={"test": "test"},
)
def make_thread_items() -> list[ThreadItem]:
now = datetime.now()
user_msg = UserMessageItem(
id="msg_100000",
content=[UserMessageTextContent(text="Hello!")],
attachments=[],
inference_options=InferenceOptions(),
thread_id="test_thread",
created_at=now,
)
assistant_msg = AssistantMessageItem(
id="msg_000001",
content=[AssistantMessageContent(text="Hi there!")],
thread_id="test_thread",
created_at=now + timedelta(seconds=1),
)
widget = WidgetItem(
id="widget_1",
type="widget",
thread_id="test_thread",
created_at=now + timedelta(seconds=2),
widget=Card(
children=[
Col(
padding={"x": 4, "y": 3},
border={"bottom": 1},
children=[
Text(
value="Title",
weight="medium",
size="sm",
color="secondary",
),
Text(
value="test",
),
],
),
]
),
)
return [user_msg, assistant_msg, widget]
DEFAULT_CONTEXT = RequestContext(user_id="test_user")
ALTERNATIVE_CONTEXT = RequestContext(user_id="alternative_user")
class TestStore(ABC):
store: Store
@abstractmethod
def setup_method(self, method):
pass
@abstractmethod
def teardown_method(self, method):
pass
@pytest.mark.asyncio
async def test_save_and_load_thread_metadata(self):
thread = make_thread()
await self.store.save_thread(thread, DEFAULT_CONTEXT)
loaded_meta = await self.store.load_thread(thread.id, DEFAULT_CONTEXT)
assert loaded_meta.id == thread.id
assert loaded_meta.title == thread.title
assert loaded_meta.metadata == thread.metadata
@pytest.mark.asyncio
async def test_save_and_load_thread_metadata_null_title(self):
thread = ThreadMetadata(
id="test_thread",
title=None,
created_at=datetime.now(),
metadata={"test": "test"},
)
await self.store.save_thread(thread, DEFAULT_CONTEXT)
loaded_meta = await self.store.load_thread(thread.id, DEFAULT_CONTEXT)
assert loaded_meta.id == thread.id
assert loaded_meta.title is None
assert loaded_meta.metadata == thread.metadata
@pytest.mark.asyncio
async def test_update_thread_metadata(self):
thread = make_thread()
await self.store.save_thread(thread, DEFAULT_CONTEXT)
thread.title = "Updated Title"
await self.store.save_thread(thread, DEFAULT_CONTEXT)
loaded_meta = await self.store.load_thread(thread.id, DEFAULT_CONTEXT)
assert loaded_meta.title == "Updated Title"
@pytest.mark.asyncio
async def test_save_and_load_thread_items(self):
thread = make_thread()
items = make_thread_items()
await self.store.save_thread(thread, DEFAULT_CONTEXT)
for item in items:
await self.store.add_thread_item(thread.id, item, DEFAULT_CONTEXT)
loaded_items = (
await self.store.load_thread_items(
thread.id, None, 10, "asc", DEFAULT_CONTEXT
)
).data
assert loaded_items == items
@pytest.mark.asyncio
async def test_overwrite_thread_metadata(self):
thread = make_thread()
await self.store.save_thread(thread, DEFAULT_CONTEXT)
thread.title = "Updated Title"
await self.store.save_thread(thread, DEFAULT_CONTEXT)
loaded_meta = await self.store.load_thread(thread.id, DEFAULT_CONTEXT)
assert loaded_meta.title == "Updated Title"
@pytest.mark.asyncio
async def test_save_and_load_file(self):
file = FileAttachment(
id="file_1",
type="file",
mime_type="text/plain",
name="test.txt",
)
await self.store.save_attachment(file, DEFAULT_CONTEXT)
loaded = await self.store.load_attachment(file.id, DEFAULT_CONTEXT)
assert loaded == file
@pytest.mark.asyncio
async def test_save_and_load_image(self):
image = ImageAttachment(
id="image_1",
type="image",
mime_type="image/png",
name="test.png",
preview_url=AnyUrl("https://example.com/test.png"),
)
await self.store.save_attachment(image, DEFAULT_CONTEXT)
loaded = await self.store.load_attachment(image.id, DEFAULT_CONTEXT)
assert loaded == image
@pytest.mark.asyncio
async def test_load_threads(self):
now = datetime.now()
thread1 = make_thread(thread_id="thread1", created_at=now)
thread2 = make_thread(
thread_id="thread2", created_at=now + timedelta(seconds=1)
)
thread3 = make_thread(
thread_id="thread3", created_at=now + timedelta(seconds=2)
)
await self.store.save_thread(thread1, DEFAULT_CONTEXT)
await self.store.save_thread(thread2, DEFAULT_CONTEXT)
await self.store.save_thread(thread3, DEFAULT_CONTEXT)
page1 = await self.store.load_threads(
limit=2, after=None, order="asc", context=DEFAULT_CONTEXT
)
assert [t.id for t in page1.data] == ["thread1", "thread2"]
assert page1.has_more is True
assert page1.after == "thread2"
page2 = await self.store.load_threads(
limit=2, after=page1.data[-1].id, order="asc", context=DEFAULT_CONTEXT
)
assert [t.id for t in page2.data] == ["thread3"]
assert page2.has_more is False
assert not page2.after
@pytest.mark.asyncio
async def test_thread_items_ordering(self):
thread = make_thread()
now = datetime.now()
items = [
UserMessageItem(
id="msg1",
content=[UserMessageTextContent(text="A")],
attachments=[],
inference_options=InferenceOptions(),
thread_id=thread.id,
created_at=now,
),
UserMessageItem(
id="msg2",
content=[UserMessageTextContent(text="B")],
attachments=[],
inference_options=InferenceOptions(),
thread_id=thread.id,
created_at=now + timedelta(seconds=1),
),
UserMessageItem(
id="msg3",
content=[UserMessageTextContent(text="C")],
attachments=[],
inference_options=InferenceOptions(),
thread_id=thread.id,
created_at=now + timedelta(seconds=2),
),
]
await self.store.save_thread(thread, DEFAULT_CONTEXT)
for item in items:
await self.store.add_thread_item(thread.id, item, DEFAULT_CONTEXT)
asc = await self.store.load_thread_items(
thread.id, after=None, limit=3, order="asc", context=DEFAULT_CONTEXT
)
desc = await self.store.load_thread_items(
thread.id, after=None, limit=3, order="desc", context=DEFAULT_CONTEXT
)
assert [i.id for i in asc.data] == ["msg1", "msg2", "msg3"]
assert [i.id for i in desc.data] == ["msg3", "msg2", "msg1"]
@pytest.mark.asyncio
async def test_thread_items_offset(self):
thread = make_thread()
now = datetime.now()
items = [
UserMessageItem(
id=f"msg{i}",
content=[UserMessageTextContent(text=str(i))],
attachments=[],
inference_options=InferenceOptions(),
thread_id=thread.id,
created_at=now + timedelta(seconds=i),
)
for i in range(5)
]
await self.store.save_thread(thread, DEFAULT_CONTEXT)
for item in items:
await self.store.add_thread_item(thread.id, item, DEFAULT_CONTEXT)
after = await self.store.load_thread_items(
thread.id, after="msg1", limit=3, order="asc", context=DEFAULT_CONTEXT
)
assert [i.id for i in after.data] == ["msg2", "msg3", "msg4"]
assert after.has_more is False
assert not after.after
after_limit = await self.store.load_thread_items(
thread.id, after=None, limit=2, order="asc", context=DEFAULT_CONTEXT
)
assert [i.id for i in after_limit.data] == ["msg0", "msg1"]
assert after_limit.has_more is True
assert after_limit.after == "msg1"
@pytest.mark.asyncio
async def test_save_and_load_item(self):
thread = make_thread()
now = datetime.now()
assistant_msg = AssistantMessageItem(
id="msg_000001",
content=[],
thread_id=thread.id,
created_at=now,
)
widget = WidgetItem(
id="widget_1",
type="widget",
thread_id=thread.id,
created_at=now + timedelta(seconds=1),
widget=Card(children=[Text(value="Test")]),
)
await self.store.save_thread(thread, DEFAULT_CONTEXT)
await self.store.add_thread_item(thread.id, assistant_msg, DEFAULT_CONTEXT)
await self.store.add_thread_item(thread.id, widget, DEFAULT_CONTEXT)
assistant_msg.content = [
AssistantMessageContent(text="This is an assistant message.")
]
await self.store.save_item(thread.id, assistant_msg, DEFAULT_CONTEXT)
loaded_assistant = await self.store.load_item(
thread.id, assistant_msg.id, DEFAULT_CONTEXT
)
assert isinstance(loaded_assistant, AssistantMessageItem)
assert loaded_assistant.id == assistant_msg.id
assert loaded_assistant.content[0] == AssistantMessageContent(
text="This is an assistant message."
)
await self.store.save_item(thread.id, widget, DEFAULT_CONTEXT)
loaded_widget = await self.store.load_item(
thread.id, widget.id, DEFAULT_CONTEXT
)
assert isinstance(loaded_widget, WidgetItem)
assert loaded_widget.id == widget.id
@pytest.mark.asyncio
async def test_load_nonexistent_item(self):
thread = make_thread()
await self.store.save_thread(thread, DEFAULT_CONTEXT)
with pytest.raises(NotFoundError):
await self.store.load_item(thread.id, "does_not_exist", DEFAULT_CONTEXT)
@pytest.mark.asyncio
async def test_thread_isolation_by_user(self):
# Create a thread for DEFAULT_CONTEXT
thread = make_thread(thread_id="user1_thread")
await self.store.save_thread(thread, DEFAULT_CONTEXT)
# Should be accessible by the same user
loaded_default = await self.store.load_thread(thread.id, DEFAULT_CONTEXT)
assert loaded_default.title == thread.title
# Should not be accessible by another user
with pytest.raises(NotFoundError):
await self.store.load_thread(thread.id, ALTERNATIVE_CONTEXT)
@pytest.mark.asyncio
async def test_thread_items_isolation_by_user(self):
thread = make_thread(thread_id="shared_thread")
await self.store.save_thread(thread, DEFAULT_CONTEXT)
# Add items for DEFAULT_CONTEXT
items_default = make_thread_items()
for item in items_default:
await self.store.add_thread_item(thread.id, item, DEFAULT_CONTEXT)
# Should be accessible by the same user
loaded_items_default = (
await self.store.load_thread_items(
thread.id, None, 10, "asc", DEFAULT_CONTEXT
)
).data
assert loaded_items_default == items_default
# Should not be accessible by another user (should return empty list)
loaded_items_alternative = (
await self.store.load_thread_items(
thread.id, None, 10, "asc", ALTERNATIVE_CONTEXT
)
).data
assert loaded_items_alternative == []
# Try to load a specific item with another user's context (should raise ValueError)
with pytest.raises(NotFoundError):
await self.store.load_item(
thread.id, items_default[0].id, ALTERNATIVE_CONTEXT
)
class TestSqliteStore(TestStore):
def setup_method(self, method):
db_path = f"file:{method.__name__}?mode=memory&cache=shared"
# Keep the shared in-memory database from being deleted when the last connection is closed
self.db = sqlite3.connect(db_path, uri=True)
self.store = SQLiteStore(db_path)
def teardown_method(self, method):
self.db.close()
@pytest.mark.asyncio
async def test_default_id_generators_use_default_prefixes(self):
ctx = DEFAULT_CONTEXT
thread_id = self.store.generate_thread_id(ctx)
assert thread_id.startswith("thr_")
thread = make_thread(thread_id=thread_id)
assert self.store.generate_item_id("message", thread, ctx).startswith("msg_")
assert self.store.generate_item_id("tool_call", thread, ctx).startswith("tc_")
assert self.store.generate_item_id("task", thread, ctx).startswith("tsk_")
assert self.store.generate_item_id("workflow", thread, ctx).startswith("wf_")
class TestSqliteStoreCustomIds(TestStore):
def setup_method(self, method):
db_path = f"file:{method.__name__}_custom?mode=memory&cache=shared"
# Keep the shared in-memory database from being deleted when the last connection is closed
self.db = sqlite3.connect(db_path, uri=True)
class CustomSQLiteStore(SQLiteStore):
def __init__(self, path: str):
super().__init__(path)
self.counter = 0
def generate_thread_id(self, context) -> str:
self.counter += 1
return f"thr_custom_{self.counter}"
def generate_item_id(
self, item_type: str, thread: ThreadMetadata, context
) -> str:
self.counter += 1
return f"{item_type}_custom_{self.counter}_{thread.id}"
self.store = CustomSQLiteStore(db_path)
def teardown_method(self, method):
self.db.close()
@pytest.mark.asyncio
async def test_overridden_id_generators_are_used(self):
ctx = DEFAULT_CONTEXT
thread_id = self.store.generate_thread_id(ctx)
assert thread_id == "thr_custom_1"
thread = make_thread(thread_id=thread_id)
msg_id = self.store.generate_item_id("message", thread, ctx)
tool_call_id = self.store.generate_item_id("tool_call", thread, ctx)
task_id = self.store.generate_item_id("task", thread, ctx)
assert msg_id == "message_custom_2_thr_custom_1"
assert tool_call_id == "tool_call_custom_3_thr_custom_1"
assert task_id == "task_custom_4_thr_custom_1"
thread2 = make_thread(thread_id=self.store.generate_thread_id(ctx))
assert thread2.id == "thr_custom_5"
msg_id2 = self.store.generate_item_id("message", thread2, ctx)
tool_call_id2 = self.store.generate_item_id("tool_call", thread2, ctx)
task_id2 = self.store.generate_item_id("task", thread2, ctx)
assert msg_id2 == "message_custom_6_thr_custom_5"
assert tool_call_id2 == "tool_call_custom_7_thr_custom_5"
assert task_id2 == "task_custom_8_thr_custom_5"