Skip to content

store

ConflictError

Bases: Exception

The stored state no longer permits the requested operation.

Source code in chatkit/store.py
53
54
class ConflictError(Exception):
    """The stored state no longer permits the requested operation."""

TurnSupersededError

Bases: ConflictError

Another turn owns the thread, or the thread no longer exists.

Source code in chatkit/store.py
57
58
class TurnSupersededError(ConflictError):
    """Another turn owns the thread, or the thread no longer exists."""

ThreadPatch

Bases: TypedDict

Explicit changes to thread display fields or individual metadata keys.

Source code in chatkit/store.py
65
66
67
68
69
70
71
72
class ThreadPatch(TypedDict, total=False):
    """Explicit changes to thread display fields or individual metadata keys."""

    title: str | None
    status: ThreadStatus
    allowed_image_domains: list[str] | None
    metadata_set: dict[str, Any]
    metadata_delete: tuple[str, ...]

AttachmentStore

Bases: ABC

Handle attachment uploads and delete the associated file data.

Source code in chatkit/store.py
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
class AttachmentStore[TContext = Any](ABC):
    """Handle attachment uploads and delete the associated file data."""

    @abstractmethod
    async def delete_attachment(self, attachment_id: str, context: TContext) -> None:
        """Delete an attachment by id."""
        pass

    async def create_attachment(
        self, input: AttachmentCreateParams, context: TContext
    ) -> Attachment:
        """Create an attachment record from upload metadata."""
        raise NotImplementedError(
            f"{type(self).__name__} must override create_attachment() to support two-phase file upload"
        )

    def generate_attachment_id(self, mime_type: str, context: TContext) -> str:
        """Return a new identifier for a file. Override this method to customize file ID generation."""

        return default_generate_id("attachment")

delete_attachment abstractmethod async

delete_attachment(attachment_id: str, context: TContext) -> None

Delete an attachment by id.

Source code in chatkit/store.py
141
142
143
144
@abstractmethod
async def delete_attachment(self, attachment_id: str, context: TContext) -> None:
    """Delete an attachment by id."""
    pass

create_attachment async

create_attachment(input: AttachmentCreateParams, context: TContext) -> Attachment

Create an attachment record from upload metadata.

Source code in chatkit/store.py
146
147
148
149
150
151
152
async def create_attachment(
    self, input: AttachmentCreateParams, context: TContext
) -> Attachment:
    """Create an attachment record from upload metadata."""
    raise NotImplementedError(
        f"{type(self).__name__} must override create_attachment() to support two-phase file upload"
    )

generate_attachment_id

generate_attachment_id(mime_type: str, context: TContext) -> str

Return a new identifier for a file. Override this method to customize file ID generation.

Source code in chatkit/store.py
154
155
156
157
def generate_attachment_id(self, mime_type: str, context: TContext) -> str:
    """Return a new identifier for a file. Override this method to customize file ID generation."""

    return default_generate_id("attachment")

ThreadStore

Bases: ABC

Persist threads and their items, with access scoped by the request context.

Source code in chatkit/store.py
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
class ThreadStore[TContext = Any](ABC):
    """Persist threads and their items, with access scoped by the request context."""

    def generate_thread_id(self, context: TContext) -> str:
        """Return a new identifier for a thread. Override this method to customize thread ID generation."""

        return default_generate_id("thread")

    def generate_item_id(
        self, item_type: StoreItemType, thread: ThreadMetadata, context: TContext
    ) -> str:
        """Return a new identifier for a thread item. Override this method to customize item ID generation."""

        return default_generate_id(item_type)

    @abstractmethod
    async def load_thread(self, thread_id: str, context: TContext) -> ThreadMetadata:
        """Load thread metadata or raise `NotFoundError` if it is unavailable."""
        pass

    @abstractmethod
    async def save_thread(self, thread: ThreadMetadata, context: TContext) -> None:
        """Save an initial thread snapshot. Use `patch_thread` for live edits."""
        pass

    @abstractmethod
    async def begin_turn(
        self,
        thread_id: str,
        turn_id: str,
        context: TContext,
        *,
        message: UserMessageItem | None = None,
        create_thread: ThreadMetadata | None = None,
    ) -> None:
        """Atomically accept a new current turn and cancel pending callbacks.

        Save the optional new thread and user message in the same transaction.
        Preserve the previous turn's disposition and reject reused turn IDs.
        """
        pass

    @abstractmethod
    async def start_turn(self, thread_id: str, turn_id: str, context: TContext) -> None:
        """Atomically move the current accepted turn to running, once."""
        pass

    @abstractmethod
    async def require_current_turn(
        self, thread_id: str, turn_id: str, context: TContext
    ) -> None:
        """Raise `ConflictError` when this turn no longer owns the thread."""
        pass

    @abstractmethod
    async def load_turn_state(
        self, thread_id: str, turn_id: str, context: TContext
    ) -> TurnState:
        """Read a scoped turn's state, including after ownership changes."""
        pass

    @abstractmethod
    async def finish_turn(
        self, thread_id: str, turn_id: str, outcome: TurnOutcome, context: TContext
    ) -> TurnState:
        """Finish the current running turn and return its recorded disposition.

        Cancellation before start records abandonment. Previously finalized and
        superseded turns keep their state even when their producers finish later.
        A current turn that stops without waiting cancels its pending callback.
        """
        pass

    @abstractmethod
    async def patch_thread(
        self,
        thread_id: str,
        patch: ThreadPatch,
        context: TContext,
        *,
        turn_id: str | None = None,
    ) -> ThreadMetadata:
        """Atomically apply a patch to the latest stored thread and return the result.

        Omitted display fields are left alone. Delete metadata keys before applying
        `metadata_set`. Raise `NotFoundError` for an unavailable thread.
        When `turn_id` is given, verify ownership within the write transaction.
        """
        pass

    @abstractmethod
    async def load_thread_items(
        self,
        thread_id: str,
        after: str | None,
        limit: int,
        order: str,
        context: TContext,
        *,
        include_hidden: bool = True,
    ) -> Page[ThreadItem]:
        """Load up to `limit` items in creation order, starting after `after`.

        Use a stable order for items with the same timestamp. Accept `"asc"`
        for oldest first and `"desc"` for newest first. If more items exist,
        set `has_more=True` and return a cursor in `Page.after` for the next page.
        When `include_hidden=False`, exclude `HIDDEN_ITEM_TYPES` and pending
        client tool items whose callback is no longer pending or was never
        registered before applying the cursor and limit. Derive pagination
        metadata from the visible rows.
        """
        pass

    @abstractmethod
    async def load_threads(
        self,
        limit: int,
        after: str | None,
        order: str,
        context: TContext,
    ) -> Page[ThreadMetadata]:
        """Load up to `limit` threads in creation order, starting after `after`.

        Use a stable order for threads with the same timestamp. Accept `"asc"`
        for oldest first and `"desc"` for newest first. If more threads exist,
        set `has_more=True` and return a cursor in `Page.after` for the next page.
        """
        pass

    @abstractmethod
    async def add_thread_item(
        self,
        thread_id: str,
        item: ThreadItem,
        context: TContext,
        *,
        turn_id: str | None = None,
    ) -> None:
        """Persist a newly created thread item.

        Use `register_client_tool_call` to persist client tool items. Reject
        reused callback IDs, including IDs whose items were removed, with
        `ConflictError`. A new user message atomically cancels a pending callback.
        Verify `turn_id` ownership within the insertion transaction.
        """
        pass

    @abstractmethod
    async def save_item(
        self,
        thread_id: str,
        item: ThreadItem,
        context: TContext,
        *,
        turn_id: str | None = None,
    ) -> None:
        """Upsert a thread item by id.

        For client tools, use `register_client_tool_call` for registration and
        `claim_pending_item` for completion. Reject direct writes to those
        items and their reserved IDs. A first insertion of a user message
        has the same cancellation semantics as `add_thread_item`.
        When `turn_id` is given, verify ownership within the write transaction.
        """
        pass

    async def register_client_tool_call(
        self,
        thread_id: str,
        item: ClientToolCallItem,
        invocation: ClientToolInvocation,
        context: TContext,
    ) -> None:
        """Atomically save a browser item and its matching private invocation.

        Require the invocation's turn to be current and running. The thread can
        have one pending callback. Reserved callback IDs remain reserved after
        completion, cancellation, and display item deletion.
        """
        raise UnsupportedOperationError(
            "Client tool callbacks require a compatible thread store"
        )

    async def load_client_tool_invocation(
        self, thread_id: str, item_id: str, context: TContext
    ) -> ClientToolInvocation:
        """Read a scoped private invocation and its continuation turn, if claimed.

        Raise `NotFoundError` for an unavailable or unregistered callback.
        """
        raise UnsupportedOperationError(
            "Client tool callbacks require a compatible thread store"
        )

    async def load_client_tool_status(
        self, thread_id: str, item_id: str, context: TContext
    ) -> ClientToolCallbackStatus:
        """Read a scoped callback's lifecycle, including after item deletion.

        Raise `NotFoundError` for an unavailable or unregistered callback.
        """
        raise UnsupportedOperationError(
            "Client tool callbacks require a compatible thread store"
        )

    async def cancel_client_tool_call(
        self,
        thread_id: str,
        item_id: str,
        context: TContext,
        *,
        turn_id: str | None = None,
    ) -> None:
        """Atomically cancel one pending callback. Closed or unknown IDs have no effect.

        When `turn_id` is given, verify ownership within the write transaction.
        """
        raise UnsupportedOperationError(
            "Client tool callbacks require a compatible thread store"
        )

    @abstractmethod
    async def claim_pending_item(
        self,
        thread_id: str,
        expected: PendingTurnItem,
        replacement: PendingTurnItem,
        context: TContext,
        *,
        next_turn_id: str | None = None,
    ) -> ClientToolInvocation | None:
        """Atomically replace a pending item if its stored value matches `expected`.

        The replacement must complete the same thread item. A client tool claim
        requires `next_turn_id` and a registered pending callback with a current
        owner. Save its result and the accepted continuation turn in the same
        transaction and return the private invocation linked to that turn.
        A structured input claim returns `None`. Record which turn issued a
        form. If a different turn is ACCEPTED or RUNNING, reject the claim
        with `ConflictError` in the same transaction, leaving the form pending.
        A form with no recorded owner can be claimed when the thread is idle.

        Raise `ConflictError` on stale or closed state and `NotFoundError` for
        an unavailable item or thread. Commit the claim before starting inference.
        """
        pass

    @abstractmethod
    async def truncate_after(
        self,
        thread_id: str,
        item_id: str,
        context: TContext,
        *,
        next_turn_id: str | None = None,
    ) -> UserMessageItem:
        """Atomically truncate the active history after a stored user message.

        Use the stable order of `load_thread_items` and return the retained
        user message. Later items must disappear from pagination and direct
        reads before returning. Atomically cancel any pending client tool
        callback and retain its status. A store can commit a visibility
        boundary and reclaim the inactive records separately.
        When `next_turn_id` is provided, accept that turn in the same transaction.

        Raise `NotFoundError` for an unavailable target and `ConflictError`
        when the target is not a user message.
        """
        pass

    @abstractmethod
    async def load_item(
        self, thread_id: str, item_id: str, context: TContext
    ) -> ThreadItem:
        """Load an item in the given thread or raise `NotFoundError`."""
        pass

    @abstractmethod
    async def delete_thread(self, thread_id: str, context: TContext) -> None:
        """Delete a thread and its associated item, callback, and turn records."""
        pass

    @abstractmethod
    async def delete_thread_item(
        self,
        thread_id: str,
        item_id: str,
        context: TContext,
        *,
        turn_id: str | None = None,
    ) -> None:
        """Delete an item and atomically cancel its pending callback.

        When `turn_id` is given, verify ownership within the write transaction.
        """
        pass

generate_thread_id

generate_thread_id(context: TContext) -> str

Return a new identifier for a thread. Override this method to customize thread ID generation.

Source code in chatkit/store.py
163
164
165
166
def generate_thread_id(self, context: TContext) -> str:
    """Return a new identifier for a thread. Override this method to customize thread ID generation."""

    return default_generate_id("thread")

generate_item_id

generate_item_id(item_type: StoreItemType, thread: ThreadMetadata, context: TContext) -> str

Return a new identifier for a thread item. Override this method to customize item ID generation.

Source code in chatkit/store.py
168
169
170
171
172
173
def generate_item_id(
    self, item_type: StoreItemType, thread: ThreadMetadata, context: TContext
) -> str:
    """Return a new identifier for a thread item. Override this method to customize item ID generation."""

    return default_generate_id(item_type)

load_thread abstractmethod async

load_thread(thread_id: str, context: TContext) -> ThreadMetadata

Load thread metadata or raise NotFoundError if it is unavailable.

Source code in chatkit/store.py
175
176
177
178
@abstractmethod
async def load_thread(self, thread_id: str, context: TContext) -> ThreadMetadata:
    """Load thread metadata or raise `NotFoundError` if it is unavailable."""
    pass

save_thread abstractmethod async

save_thread(thread: ThreadMetadata, context: TContext) -> None

Save an initial thread snapshot. Use patch_thread for live edits.

Source code in chatkit/store.py
180
181
182
183
@abstractmethod
async def save_thread(self, thread: ThreadMetadata, context: TContext) -> None:
    """Save an initial thread snapshot. Use `patch_thread` for live edits."""
    pass

begin_turn abstractmethod async

begin_turn(thread_id: str, turn_id: str, context: TContext, *, message: UserMessageItem | None = None, create_thread: ThreadMetadata | None = None) -> None

Atomically accept a new current turn and cancel pending callbacks.

Save the optional new thread and user message in the same transaction. Preserve the previous turn's disposition and reject reused turn IDs.

Source code in chatkit/store.py
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
@abstractmethod
async def begin_turn(
    self,
    thread_id: str,
    turn_id: str,
    context: TContext,
    *,
    message: UserMessageItem | None = None,
    create_thread: ThreadMetadata | None = None,
) -> None:
    """Atomically accept a new current turn and cancel pending callbacks.

    Save the optional new thread and user message in the same transaction.
    Preserve the previous turn's disposition and reject reused turn IDs.
    """
    pass

start_turn abstractmethod async

start_turn(thread_id: str, turn_id: str, context: TContext) -> None

Atomically move the current accepted turn to running, once.

Source code in chatkit/store.py
202
203
204
205
@abstractmethod
async def start_turn(self, thread_id: str, turn_id: str, context: TContext) -> None:
    """Atomically move the current accepted turn to running, once."""
    pass

require_current_turn abstractmethod async

require_current_turn(thread_id: str, turn_id: str, context: TContext) -> None

Raise ConflictError when this turn no longer owns the thread.

Source code in chatkit/store.py
207
208
209
210
211
212
@abstractmethod
async def require_current_turn(
    self, thread_id: str, turn_id: str, context: TContext
) -> None:
    """Raise `ConflictError` when this turn no longer owns the thread."""
    pass

load_turn_state abstractmethod async

load_turn_state(thread_id: str, turn_id: str, context: TContext) -> TurnState

Read a scoped turn's state, including after ownership changes.

Source code in chatkit/store.py
214
215
216
217
218
219
@abstractmethod
async def load_turn_state(
    self, thread_id: str, turn_id: str, context: TContext
) -> TurnState:
    """Read a scoped turn's state, including after ownership changes."""
    pass

finish_turn abstractmethod async

finish_turn(thread_id: str, turn_id: str, outcome: TurnOutcome, context: TContext) -> TurnState

Finish the current running turn and return its recorded disposition.

Cancellation before start records abandonment. Previously finalized and superseded turns keep their state even when their producers finish later. A current turn that stops without waiting cancels its pending callback.

Source code in chatkit/store.py
221
222
223
224
225
226
227
228
229
230
231
@abstractmethod
async def finish_turn(
    self, thread_id: str, turn_id: str, outcome: TurnOutcome, context: TContext
) -> TurnState:
    """Finish the current running turn and return its recorded disposition.

    Cancellation before start records abandonment. Previously finalized and
    superseded turns keep their state even when their producers finish later.
    A current turn that stops without waiting cancels its pending callback.
    """
    pass

patch_thread abstractmethod async

patch_thread(thread_id: str, patch: ThreadPatch, context: TContext, *, turn_id: str | None = None) -> ThreadMetadata

Atomically apply a patch to the latest stored thread and return the result.

Omitted display fields are left alone. Delete metadata keys before applying metadata_set. Raise NotFoundError for an unavailable thread. When turn_id is given, verify ownership within the write transaction.

Source code in chatkit/store.py
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
@abstractmethod
async def patch_thread(
    self,
    thread_id: str,
    patch: ThreadPatch,
    context: TContext,
    *,
    turn_id: str | None = None,
) -> ThreadMetadata:
    """Atomically apply a patch to the latest stored thread and return the result.

    Omitted display fields are left alone. Delete metadata keys before applying
    `metadata_set`. Raise `NotFoundError` for an unavailable thread.
    When `turn_id` is given, verify ownership within the write transaction.
    """
    pass

load_thread_items abstractmethod async

load_thread_items(thread_id: str, after: str | None, limit: int, order: str, context: TContext, *, include_hidden: bool = True) -> Page[ThreadItem]

Load up to limit items in creation order, starting after after.

Use a stable order for items with the same timestamp. Accept "asc" for oldest first and "desc" for newest first. If more items exist, set has_more=True and return a cursor in Page.after for the next page. When include_hidden=False, exclude HIDDEN_ITEM_TYPES and pending client tool items whose callback is no longer pending or was never registered before applying the cursor and limit. Derive pagination metadata from the visible rows.

Source code in chatkit/store.py
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
@abstractmethod
async def load_thread_items(
    self,
    thread_id: str,
    after: str | None,
    limit: int,
    order: str,
    context: TContext,
    *,
    include_hidden: bool = True,
) -> Page[ThreadItem]:
    """Load up to `limit` items in creation order, starting after `after`.

    Use a stable order for items with the same timestamp. Accept `"asc"`
    for oldest first and `"desc"` for newest first. If more items exist,
    set `has_more=True` and return a cursor in `Page.after` for the next page.
    When `include_hidden=False`, exclude `HIDDEN_ITEM_TYPES` and pending
    client tool items whose callback is no longer pending or was never
    registered before applying the cursor and limit. Derive pagination
    metadata from the visible rows.
    """
    pass

load_threads abstractmethod async

load_threads(limit: int, after: str | None, order: str, context: TContext) -> Page[ThreadMetadata]

Load up to limit threads in creation order, starting after after.

Use a stable order for threads with the same timestamp. Accept "asc" for oldest first and "desc" for newest first. If more threads exist, set has_more=True and return a cursor in Page.after for the next page.

Source code in chatkit/store.py
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
@abstractmethod
async def load_threads(
    self,
    limit: int,
    after: str | None,
    order: str,
    context: TContext,
) -> Page[ThreadMetadata]:
    """Load up to `limit` threads in creation order, starting after `after`.

    Use a stable order for threads with the same timestamp. Accept `"asc"`
    for oldest first and `"desc"` for newest first. If more threads exist,
    set `has_more=True` and return a cursor in `Page.after` for the next page.
    """
    pass

add_thread_item abstractmethod async

add_thread_item(thread_id: str, item: ThreadItem, context: TContext, *, turn_id: str | None = None) -> None

Persist a newly created thread item.

Use register_client_tool_call to persist client tool items. Reject reused callback IDs, including IDs whose items were removed, with ConflictError. A new user message atomically cancels a pending callback. Verify turn_id ownership within the insertion transaction.

Source code in chatkit/store.py
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
@abstractmethod
async def add_thread_item(
    self,
    thread_id: str,
    item: ThreadItem,
    context: TContext,
    *,
    turn_id: str | None = None,
) -> None:
    """Persist a newly created thread item.

    Use `register_client_tool_call` to persist client tool items. Reject
    reused callback IDs, including IDs whose items were removed, with
    `ConflictError`. A new user message atomically cancels a pending callback.
    Verify `turn_id` ownership within the insertion transaction.
    """
    pass

save_item abstractmethod async

save_item(thread_id: str, item: ThreadItem, context: TContext, *, turn_id: str | None = None) -> None

Upsert a thread item by id.

For client tools, use register_client_tool_call for registration and claim_pending_item for completion. Reject direct writes to those items and their reserved IDs. A first insertion of a user message has the same cancellation semantics as add_thread_item. When turn_id is given, verify ownership within the write transaction.

Source code in chatkit/store.py
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
@abstractmethod
async def save_item(
    self,
    thread_id: str,
    item: ThreadItem,
    context: TContext,
    *,
    turn_id: str | None = None,
) -> None:
    """Upsert a thread item by id.

    For client tools, use `register_client_tool_call` for registration and
    `claim_pending_item` for completion. Reject direct writes to those
    items and their reserved IDs. A first insertion of a user message
    has the same cancellation semantics as `add_thread_item`.
    When `turn_id` is given, verify ownership within the write transaction.
    """
    pass

register_client_tool_call async

register_client_tool_call(thread_id: str, item: ClientToolCallItem, invocation: ClientToolInvocation, context: TContext) -> None

Atomically save a browser item and its matching private invocation.

Require the invocation's turn to be current and running. The thread can have one pending callback. Reserved callback IDs remain reserved after completion, cancellation, and display item deletion.

Source code in chatkit/store.py
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
async def register_client_tool_call(
    self,
    thread_id: str,
    item: ClientToolCallItem,
    invocation: ClientToolInvocation,
    context: TContext,
) -> None:
    """Atomically save a browser item and its matching private invocation.

    Require the invocation's turn to be current and running. The thread can
    have one pending callback. Reserved callback IDs remain reserved after
    completion, cancellation, and display item deletion.
    """
    raise UnsupportedOperationError(
        "Client tool callbacks require a compatible thread store"
    )

load_client_tool_invocation async

load_client_tool_invocation(thread_id: str, item_id: str, context: TContext) -> ClientToolInvocation

Read a scoped private invocation and its continuation turn, if claimed.

Raise NotFoundError for an unavailable or unregistered callback.

Source code in chatkit/store.py
343
344
345
346
347
348
349
350
351
352
async def load_client_tool_invocation(
    self, thread_id: str, item_id: str, context: TContext
) -> ClientToolInvocation:
    """Read a scoped private invocation and its continuation turn, if claimed.

    Raise `NotFoundError` for an unavailable or unregistered callback.
    """
    raise UnsupportedOperationError(
        "Client tool callbacks require a compatible thread store"
    )

load_client_tool_status async

load_client_tool_status(thread_id: str, item_id: str, context: TContext) -> ClientToolCallbackStatus

Read a scoped callback's lifecycle, including after item deletion.

Raise NotFoundError for an unavailable or unregistered callback.

Source code in chatkit/store.py
354
355
356
357
358
359
360
361
362
363
async def load_client_tool_status(
    self, thread_id: str, item_id: str, context: TContext
) -> ClientToolCallbackStatus:
    """Read a scoped callback's lifecycle, including after item deletion.

    Raise `NotFoundError` for an unavailable or unregistered callback.
    """
    raise UnsupportedOperationError(
        "Client tool callbacks require a compatible thread store"
    )

cancel_client_tool_call async

cancel_client_tool_call(thread_id: str, item_id: str, context: TContext, *, turn_id: str | None = None) -> None

Atomically cancel one pending callback. Closed or unknown IDs have no effect.

When turn_id is given, verify ownership within the write transaction.

Source code in chatkit/store.py
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
async def cancel_client_tool_call(
    self,
    thread_id: str,
    item_id: str,
    context: TContext,
    *,
    turn_id: str | None = None,
) -> None:
    """Atomically cancel one pending callback. Closed or unknown IDs have no effect.

    When `turn_id` is given, verify ownership within the write transaction.
    """
    raise UnsupportedOperationError(
        "Client tool callbacks require a compatible thread store"
    )

claim_pending_item abstractmethod async

claim_pending_item(thread_id: str, expected: PendingTurnItem, replacement: PendingTurnItem, context: TContext, *, next_turn_id: str | None = None) -> ClientToolInvocation | None

Atomically replace a pending item if its stored value matches expected.

The replacement must complete the same thread item. A client tool claim requires next_turn_id and a registered pending callback with a current owner. Save its result and the accepted continuation turn in the same transaction and return the private invocation linked to that turn. A structured input claim returns None. Record which turn issued a form. If a different turn is ACCEPTED or RUNNING, reject the claim with ConflictError in the same transaction, leaving the form pending. A form with no recorded owner can be claimed when the thread is idle.

Raise ConflictError on stale or closed state and NotFoundError for an unavailable item or thread. Commit the claim before starting inference.

Source code in chatkit/store.py
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
@abstractmethod
async def claim_pending_item(
    self,
    thread_id: str,
    expected: PendingTurnItem,
    replacement: PendingTurnItem,
    context: TContext,
    *,
    next_turn_id: str | None = None,
) -> ClientToolInvocation | None:
    """Atomically replace a pending item if its stored value matches `expected`.

    The replacement must complete the same thread item. A client tool claim
    requires `next_turn_id` and a registered pending callback with a current
    owner. Save its result and the accepted continuation turn in the same
    transaction and return the private invocation linked to that turn.
    A structured input claim returns `None`. Record which turn issued a
    form. If a different turn is ACCEPTED or RUNNING, reject the claim
    with `ConflictError` in the same transaction, leaving the form pending.
    A form with no recorded owner can be claimed when the thread is idle.

    Raise `ConflictError` on stale or closed state and `NotFoundError` for
    an unavailable item or thread. Commit the claim before starting inference.
    """
    pass

truncate_after abstractmethod async

truncate_after(thread_id: str, item_id: str, context: TContext, *, next_turn_id: str | None = None) -> UserMessageItem

Atomically truncate the active history after a stored user message.

Use the stable order of load_thread_items and return the retained user message. Later items must disappear from pagination and direct reads before returning. Atomically cancel any pending client tool callback and retain its status. A store can commit a visibility boundary and reclaim the inactive records separately. When next_turn_id is provided, accept that turn in the same transaction.

Raise NotFoundError for an unavailable target and ConflictError when the target is not a user message.

Source code in chatkit/store.py
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
@abstractmethod
async def truncate_after(
    self,
    thread_id: str,
    item_id: str,
    context: TContext,
    *,
    next_turn_id: str | None = None,
) -> UserMessageItem:
    """Atomically truncate the active history after a stored user message.

    Use the stable order of `load_thread_items` and return the retained
    user message. Later items must disappear from pagination and direct
    reads before returning. Atomically cancel any pending client tool
    callback and retain its status. A store can commit a visibility
    boundary and reclaim the inactive records separately.
    When `next_turn_id` is provided, accept that turn in the same transaction.

    Raise `NotFoundError` for an unavailable target and `ConflictError`
    when the target is not a user message.
    """
    pass

load_item abstractmethod async

load_item(thread_id: str, item_id: str, context: TContext) -> ThreadItem

Load an item in the given thread or raise NotFoundError.

Source code in chatkit/store.py
430
431
432
433
434
435
@abstractmethod
async def load_item(
    self, thread_id: str, item_id: str, context: TContext
) -> ThreadItem:
    """Load an item in the given thread or raise `NotFoundError`."""
    pass

delete_thread abstractmethod async

delete_thread(thread_id: str, context: TContext) -> None

Delete a thread and its associated item, callback, and turn records.

Source code in chatkit/store.py
437
438
439
440
@abstractmethod
async def delete_thread(self, thread_id: str, context: TContext) -> None:
    """Delete a thread and its associated item, callback, and turn records."""
    pass

delete_thread_item abstractmethod async

delete_thread_item(thread_id: str, item_id: str, context: TContext, *, turn_id: str | None = None) -> None

Delete an item and atomically cancel its pending callback.

When turn_id is given, verify ownership within the write transaction.

Source code in chatkit/store.py
442
443
444
445
446
447
448
449
450
451
452
453
454
455
@abstractmethod
async def delete_thread_item(
    self,
    thread_id: str,
    item_id: str,
    context: TContext,
    *,
    turn_id: str | None = None,
) -> None:
    """Delete an item and atomically cancel its pending callback.

    When `turn_id` is given, verify ownership within the write transaction.
    """
    pass

AttachmentMetadataStore

Bases: ABC

Persist attachment records, with access scoped by the request context.

Source code in chatkit/store.py
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
class AttachmentMetadataStore[TContext = Any](ABC):
    """Persist attachment records, with access scoped by the request context."""

    @abstractmethod
    async def save_attachment(self, attachment: Attachment, context: TContext) -> None:
        """Upsert attachment metadata."""
        pass

    @abstractmethod
    async def load_attachment(
        self, attachment_id: str, context: TContext
    ) -> Attachment:
        """Load attachment metadata or raise `NotFoundError`."""
        pass

    @abstractmethod
    async def delete_attachment(self, attachment_id: str, context: TContext) -> None:
        """Delete attachment metadata by id."""
        pass

save_attachment abstractmethod async

save_attachment(attachment: Attachment, context: TContext) -> None

Upsert attachment metadata.

Source code in chatkit/store.py
461
462
463
464
@abstractmethod
async def save_attachment(self, attachment: Attachment, context: TContext) -> None:
    """Upsert attachment metadata."""
    pass

load_attachment abstractmethod async

load_attachment(attachment_id: str, context: TContext) -> Attachment

Load attachment metadata or raise NotFoundError.

Source code in chatkit/store.py
466
467
468
469
470
471
@abstractmethod
async def load_attachment(
    self, attachment_id: str, context: TContext
) -> Attachment:
    """Load attachment metadata or raise `NotFoundError`."""
    pass

delete_attachment abstractmethod async

delete_attachment(attachment_id: str, context: TContext) -> None

Delete attachment metadata by id.

Source code in chatkit/store.py
473
474
475
476
@abstractmethod
async def delete_attachment(self, attachment_id: str, context: TContext) -> None:
    """Delete attachment metadata by id."""
    pass

apply_thread_patch

apply_thread_patch(thread: ThreadMetadata, patch: ThreadPatch) -> ThreadMetadata

Build an updated snapshot from a store's current thread and a patch.

Source code in chatkit/store.py
75
76
77
78
79
80
81
82
83
84
85
86
87
88
def apply_thread_patch(thread: ThreadMetadata, patch: ThreadPatch) -> ThreadMetadata:
    """Build an updated snapshot from a store's current thread and a patch."""
    fields = {
        key: value
        for key, value in patch.items()
        if key in ("title", "status", "allowed_image_domains")
    }
    metadata = {
        key: value
        for key, value in thread.metadata.items()
        if key not in patch.get("metadata_delete", ())
    }
    metadata.update(patch.get("metadata_set", {}))
    return thread.model_copy(update={**fields, "metadata": metadata})

validate_pending_claim

validate_pending_claim(current: ThreadItem, expected: PendingTurnItem, replacement: PendingTurnItem) -> None

Validate a claim against the current state inside a store transaction.

Source code in chatkit/store.py
 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
def validate_pending_claim(
    current: ThreadItem,
    expected: PendingTurnItem,
    replacement: PendingTurnItem,
) -> None:
    """Validate a claim against the current state inside a store transaction."""
    if (
        replacement.id != expected.id
        or replacement.thread_id != expected.thread_id
        or replacement.created_at != expected.created_at
        or replacement.type != expected.type
        or replacement.status == "pending"
    ):
        raise ValueError("A pending claim must complete the same thread item")
    if current != expected or expected.status != "pending":
        raise ConflictError(
            "The thread item is no longer pending in the expected state"
        )
    if isinstance(expected, ClientToolCallItem) and (
        not isinstance(replacement, ClientToolCallItem)
        or replacement.status != "completed"
        or replacement.name != expected.name
        or replacement.arguments != expected.arguments
    ):
        raise ValueError("A client tool claim may only complete the item with output")

validate_client_tool_registration

validate_client_tool_registration(thread_id: str, item: ClientToolCallItem, invocation: ClientToolInvocation) -> None

Validate correspondence before saving a public item and private invocation.

Source code in chatkit/store.py
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
def validate_client_tool_registration(
    thread_id: str, item: ClientToolCallItem, invocation: ClientToolInvocation
) -> None:
    """Validate correspondence before saving a public item and private invocation."""
    if (
        item.thread_id != thread_id
        or invocation.thread_id != thread_id
        or invocation.item_id != item.id
    ):
        raise ValueError(
            "The client tool item and invocation must identify the same thread item"
        )
    if (
        item.status != "pending"
        or item.output is not None
        or invocation.continuation_turn_id is not None
    ):
        raise ValueError("A new client tool call must be pending")