Skip to content

server

StreamingResult

Bases: AsyncIterator[ThreadStreamEvent]

A single-owner stream. Accepted turns expose their thread and turn IDs.

Source code in chatkit/server.py
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
class StreamingResult(AsyncIterator[ThreadStreamEvent]):
    """A single-owner stream. Accepted turns expose their thread and turn IDs."""

    def __init__(
        self,
        stream: AsyncIterator[ThreadStreamEvent],
        *,
        thread_id: str | None = None,
        turn_id: str | None = None,
        on_close_before_start: Callable[[], Awaitable[object]] | None = None,
    ):
        self.thread_id = thread_id
        self.turn_id = turn_id
        self._stream = stream
        self._on_close_before_start = on_close_before_start
        self._started = False
        self._closed = False

    async def __anext__(self) -> ThreadStreamEvent:
        if self._closed:
            raise StopAsyncIteration
        self._started = True
        return await anext(self._stream)

    async def aclose(self) -> None:
        """Close the stream and run its cleanup."""
        try:
            if not self._closed:
                self._closed = True
                await _close_stream(self._stream)
        finally:
            if not self._started and self._on_close_before_start is not None:
                await self._on_close_before_start()
                self._on_close_before_start = None

aclose async

aclose() -> None

Close the stream and run its cleanup.

Source code in chatkit/server.py
147
148
149
150
151
152
153
154
155
156
async def aclose(self) -> None:
    """Close the stream and run its cleanup."""
    try:
        if not self._closed:
            self._closed = True
            await _close_stream(self._stream)
    finally:
        if not self._started and self._on_close_before_start is not None:
            await self._on_close_before_start()
            self._on_close_before_start = None

EmptyResult

Bases: BaseModel

An acknowledgement without response fields.

Source code in chatkit/server.py
159
160
class EmptyResult(BaseModel):
    """An acknowledgement without response fields."""

ChatKitServer

Bases: ABC

Source code in chatkit/server.py
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
class ChatKitServer[TContext = Any](ABC):
    def __init__(
        self,
        store: ThreadStore[TContext],
        attachment_store: AttachmentStore[TContext] | None = None,
        *,
        attachment_metadata_store: AttachmentMetadataStore[TContext] | None = None,
    ):
        """Configure thread persistence and optional attachment capabilities."""
        self.store = store
        self.attachment_store = attachment_store
        self.attachment_metadata_store = attachment_metadata_store

    def _require_client_tool_store(self) -> None:
        store_type = type(self.store)
        if (
            store_type.register_client_tool_call
            is ThreadStore.register_client_tool_call
            or store_type.load_client_tool_status is ThreadStore.load_client_tool_status
            or store_type.cancel_client_tool_call is ThreadStore.cancel_client_tool_call
        ):
            raise UnsupportedOperationError(
                "Client tool callbacks require a compatible thread store"
            )

    def _get_attachment_store(self) -> AttachmentStore[TContext]:
        """Return the configured AttachmentStore or raise if missing."""
        if self.attachment_store is None:
            raise UnsupportedOperationError(
                "AttachmentStore is not configured. Provide an AttachmentStore to ChatKitServer to handle file operations."
            )
        return self.attachment_store

    def _get_attachment_metadata_store(self) -> AttachmentMetadataStore[TContext]:
        if self.attachment_metadata_store is None:
            raise UnsupportedOperationError(
                "AttachmentMetadataStore is not configured. Pass "
                "attachment_metadata_store to ChatKitServer to use attachments."
            )
        return self.attachment_metadata_store

    @abstractmethod
    def respond(self, turn: Turn[TContext]) -> AsyncIterator[ResponderEvent]:
        """Stream events for a new message, a resumed turn, or a retry."""
        pass

    async def prepare_user_message(
        self, thread: ThreadMetadata, item: UserMessageItem, context: TContext
    ) -> UserMessageItem:
        """Validate or enrich a new user message before the server saves it.

        The thread snapshot and resolved attachments are available. For a new
        thread, the snapshot has an ID and has yet to be saved. Return the item
        with its original ID, thread ID, and creation time.

        Raise `InvalidOperationError` for a request error (HTTP 422 with the
        FastAPI adapter), or `CustomStreamError` for a user-facing error event.
        A rejected message produces no thread, attachment, or message writes.
        Retries and continuations use their stored inputs.
        """
        return item

    async def save_approval_checkpoint(
        self, thread: ThreadMetadata, turn_id: str, checkpoint: str, context: TContext
    ) -> None:
        """Save the paused run privately for an authorized reviewer to resume."""
        raise UnsupportedOperationError(
            "Override save_approval_checkpoint to handle runs that require approval."
        )

    async def on_turn_finished(  # noqa: B027
        self, turn: Turn[TContext], outcome: TurnOutcome
    ) -> None:
        """Observe a turn's terminal outcome after server persistence or cleanup.

        A waiting turn has a pending browser tool, form, or saved approval checkpoint.
        Completion describes server processing, not delivery to a browser. Exceptions
        raised by this hook are logged.
        """
        pass

    async def update_thread(
        self,
        thread_id: str,
        patch: ThreadPatch,
        context: TContext,
        *,
        turn_id: str,
    ) -> ThreadUpdatedEvent:
        """Apply a patch as the active responder and return its browser event."""
        updated = await self.store.patch_thread(
            thread_id, patch, context, turn_id=turn_id
        )
        return ThreadUpdatedEvent(thread=browser_thread(updated))

    async def add_feedback(  # noqa: B027
        self,
        thread_id: str,
        item_ids: list[str],
        feedback: FeedbackKind,
        context: TContext,
    ) -> None:
        """Persist user feedback for one or more thread items."""
        pass

    async def transcribe(  # noqa: B027
        self, audio_input: AudioInput, context: TContext
    ) -> TranscriptionResult:
        """Transcribe speech audio to text (dictation).

        Audio bytes are in `audio_input.data`. The raw MIME type is `audio_input.mime_type`; use
        `audio_input.media_type` for the base media type (one of: `audio/webm`, `audio/ogg`, `audio/mp4`).

        Args:
            audio_input: Audio bytes plus MIME type metadata for transcription.
            context: Arbitrary per-request context provided by the caller.

        Returns:
            A `TranscriptionResult` whose `text` is what should appear in the composer.
        """
        raise NotImplementedError(
            "transcribe() must be overridden to support the input.transcribe request."
        )

    def action(
        self,
        thread: ThreadMetadata,
        action: Action[str, Any],
        sender: WidgetItem | None,
        context: TContext,
        *,
        turn_id: str,
    ) -> AsyncIterator[ResponderEvent]:
        """Handle a streaming action. Use its turn ID for direct store writes."""
        raise NotImplementedError(
            "The action() method must be overridden to react to actions. "
            "See https://michaelgiraldo.github.io/chatkit-python/guides/build-interactive-responses-with-widgets/#handle-widget-actions"
        )

    async def sync_action(
        self,
        thread: ThreadMetadata,
        action: Action[str, Any],
        sender: WidgetItem | None,
        context: TContext,
    ) -> SyncCustomActionResponse:
        """Handle a widget or client-dispatched action and return a SyncCustomActionResponse."""
        raise NotImplementedError(
            "The sync_action() method must be overridden to react to sync actions. "
            "See https://michaelgiraldo.github.io/chatkit-python/guides/build-interactive-responses-with-widgets/#handle-widget-actions"
        )

    def get_stream_options(
        self, thread: ThreadMetadata, context: TContext
    ) -> StreamOptions:
        """
        Return stream-level runtime options. Allows the user to cancel the stream by default.
        Override this method to customize behavior.
        """
        return StreamOptions(allow_cancel=True)

    async def handle_stream_cancelled(
        self,
        thread: ThreadMetadata,
        pending_items: list[ThreadItem],
        context: TContext,
        *,
        turn_id: str,
    ):
        """Perform custom cleanup / stop inference when a stream is cancelled.
        Updates you make here will not be reflected in the UI until a reload.

        The default implementation persists any non-empty pending assistant messages
        to the thread but does not auto-save pending widget items or workflow items.

        Args:
            thread: The thread that was being processed.
            pending_items: Items that were not done streaming at cancellation time.
            context: Arbitrary per-request context provided by the caller.
            turn_id: The turn being cancelled. Use it to fence cleanup writes.
        """
        pending_assistant_message_items: list[AssistantMessageItem] = [
            item for item in pending_items if isinstance(item, AssistantMessageItem)
        ]
        for item in pending_assistant_message_items:
            is_empty = len(item.content) == 0 or all(
                (not content.text.strip()) for content in item.content
            )
            if not is_empty:
                await self.store.add_thread_item(
                    thread.id, item, context=context, turn_id=turn_id
                )

        # Add a hidden context item to the thread to indicate that the stream was cancelled.
        # Otherwise, depending on the timing of the cancellation, subsequent responses may
        # attempt to continue the cancelled response.
        await self.store.add_thread_item(
            thread.id,
            SDKHiddenContextItem(
                thread_id=thread.id,
                created_at=datetime.now(UTC),
                id=self.store.generate_item_id("sdk_hidden_context", thread, context),
                content="The user cancelled the stream. Stop responding to the prior request.",
            ),
            context=context,
            turn_id=turn_id,
        )

    async def process(
        self, request: ChatKitReq, context: TContext
    ) -> StreamingResult | ImmediateResult:
        """Process a validated request. Resolve streaming inputs before returning."""
        logger.info("Received request op: %s", request.type)
        if not is_streaming_req(request):
            return await self._process_non_streaming(request, context)
        try:
            return await self._prepare_streaming(request, context)
        except (CustomStreamError, StreamError) as error:
            event = _stream_error_event(error)

            async def rejection() -> AsyncIterator[ThreadStreamEvent]:
                yield event

            return StreamingResult(rejection())

    async def _process_non_streaming(
        self, request: NonStreamingReq, context: TContext
    ) -> ImmediateResult:
        match request:
            case ThreadsGetByIdReq():
                return await self._load_thread_with_first_page(
                    request.params.thread_id, context
                )
            case ThreadsListReq():
                params = request.params
                threads = await self.store.load_threads(
                    limit=params.limit or DEFAULT_PAGE_SIZE,
                    after=params.after,
                    order=params.order,
                    context=context,
                )
                return Page(
                    has_more=threads.has_more,
                    after=threads.after,
                    data=[browser_thread(thread) for thread in threads.data],
                )
            case ItemsFeedbackReq():
                await self.add_feedback(
                    request.params.thread_id,
                    request.params.item_ids,
                    request.params.kind,
                    context,
                )
                return EmptyResult()
            case AttachmentsCreateReq():
                attachment_store = self._get_attachment_store()
                metadata_store = self._get_attachment_metadata_store()
                attachment = await attachment_store.create_attachment(
                    request.params, context
                )
                await metadata_store.save_attachment(attachment, context=context)
                return attachment
            case AttachmentsDeleteReq():
                attachment_store = self._get_attachment_store()
                metadata_store = self._get_attachment_metadata_store()
                await attachment_store.delete_attachment(
                    request.params.attachment_id, context=context
                )
                await metadata_store.delete_attachment(
                    request.params.attachment_id, context=context
                )
                return EmptyResult()
            case InputTranscribeReq():
                if type(self).transcribe is ChatKitServer.transcribe:
                    raise UnsupportedOperationError("Transcription is unavailable.")
                try:
                    audio_bytes = base64.b64decode(
                        request.params.audio_base64, validate=True
                    )
                except ValueError as error:
                    raise InvalidOperationError(
                        "Audio must be Base64 encoded."
                    ) from error
                return await self.transcribe(
                    AudioInput(data=audio_bytes, mime_type=request.params.mime_type),
                    context=context,
                )
            case ItemsListReq():
                items_list_params = request.params
                items = await self.store.load_thread_items(
                    items_list_params.thread_id,
                    limit=items_list_params.limit or DEFAULT_PAGE_SIZE,
                    order=items_list_params.order,
                    after=items_list_params.after,
                    context=context,
                    include_hidden=False,
                )
                return require_visible_page(items)
            case ThreadsUpdateReq():
                updated = await self.store.patch_thread(
                    request.params.thread_id, {"title": request.params.title}, context
                )
                return browser_thread(updated)
            case ThreadsDeleteReq():
                await self.store.delete_thread(
                    request.params.thread_id, context=context
                )
                return EmptyResult()
            case ThreadsSyncCustomActionReq():
                return await self._process_sync_custom_action(request, context)
            case _:
                assert_never(request)

    async def _prepare_streaming(
        self, request: StreamingReq, context: TContext
    ) -> StreamingResult:
        turn_id = str(uuid4())
        match request:
            case ThreadsCreateReq():
                thread = ThreadMetadata(
                    id=self.store.generate_thread_id(context),
                    created_at=datetime.now(UTC),
                )
                user_message = await self._build_user_message_item(
                    request.params.input, thread, context
                )
                return await self._accept_user_message(
                    Turn(thread, UserMessageTurn(user_message), context, id=turn_id),
                    create_thread=True,
                )

            case ThreadsAddUserMessageReq():
                thread = await self.store.load_thread(
                    request.params.thread_id, context=context
                )
                user_message = await self._build_user_message_item(
                    request.params.input, thread, context
                )
                return await self._accept_user_message(
                    Turn(thread, UserMessageTurn(user_message), context, id=turn_id),
                )

            case ThreadsAddClientToolOutputReq():
                self._require_client_tool_store()
                thread = await self.store.load_thread(
                    request.params.thread_id, context=context
                )
                result = request.params.result
                status = await self.store.load_client_tool_status(
                    thread.id, result.item_id, context
                )
                if status != "pending":
                    raise ConflictError("The client tool call is no longer pending.")

                tool_call = await self.store.load_item(
                    thread.id, result.item_id, context=context
                )
                if (
                    not isinstance(tool_call, ClientToolCallItem)
                    or tool_call.id != result.item_id
                    or tool_call.thread_id != thread.id
                ):
                    raise InvalidOperationError(
                        "The requested item does not accept a client tool result."
                    )
                if tool_call.status != "pending":
                    raise ConflictError("The client tool call is no longer pending.")

                completed = tool_call.model_copy(
                    update={"output": result.output, "status": "completed"}
                )
                invocation = await self.store.claim_pending_item(
                    thread.id, tool_call, completed, context, next_turn_id=turn_id
                )
                if invocation is None:
                    raise ConflictError("The client tool has no executable invocation.")

                return self._respond_to_turn(
                    Turn(
                        thread,
                        ClientToolTurn(completed, invocation),
                        context,
                        id=turn_id,
                    )
                )

            case ThreadsAddStructuredInputReq():
                thread = await self.store.load_thread(
                    request.params.thread_id, context=context
                )
                item = await self.store.load_item(
                    request.params.thread_id,
                    request.params.item_id,
                    context=context,
                )
                if not isinstance(item, StructuredInputItem):
                    raise InvalidOperationError(
                        "The requested item does not accept structured input."
                    )

                updated_item = self._apply_structured_input_submission(
                    item,
                    request.params.input,
                )
                await self.store.claim_pending_item(
                    thread.id, item, updated_item, context, next_turn_id=turn_id
                )

                return self._respond_to_turn(
                    Turn(thread, StructuredInputTurn(updated_item), context, id=turn_id)
                )

            case ThreadsRetryAfterItemReq():
                thread_metadata = await self.store.load_thread(
                    request.params.thread_id, context=context
                )

                user_message_item = await self.store.truncate_after(
                    thread_metadata.id,
                    request.params.item_id,
                    context,
                    next_turn_id=turn_id,
                )
                return self._respond_to_turn(
                    Turn(
                        thread_metadata,
                        RetryTurn(user_message_item),
                        context,
                        id=turn_id,
                    )
                )

            case ThreadsCustomActionReq():
                if type(self).action is ChatKitServer.action:
                    raise UnsupportedOperationError(
                        "Streaming actions are unavailable."
                    )
                thread_metadata = await self.store.load_thread(
                    request.params.thread_id, context=context
                )

                item: ThreadItem | None = None
                if request.params.item_id:
                    item = await self.store.load_item(
                        request.params.thread_id,
                        request.params.item_id,
                        context=context,
                    )

                if item and not isinstance(item, WidgetItem):
                    raise InvalidOperationError(
                        "A custom action needs a widget sender."
                    )

                await self.store.begin_turn(thread_metadata.id, turn_id, context)
                return self._stream_turn(
                    thread_metadata,
                    turn_id,
                    context,
                    lambda: self.action(
                        thread_metadata,
                        request.params.action,
                        item,
                        context,
                        turn_id=turn_id,
                    ),
                )

            case _:
                assert_never(request)

    async def _process_sync_custom_action(
        self, request: ThreadsSyncCustomActionReq, context: TContext
    ) -> SyncCustomActionResponse:
        if type(self).sync_action is ChatKitServer.sync_action:
            raise UnsupportedOperationError("Synchronous actions are unavailable.")
        thread_metadata = await self.store.load_thread(
            request.params.thread_id, context=context
        )

        item: ThreadItem | None = None
        if request.params.item_id:
            item = await self.store.load_item(
                request.params.thread_id,
                request.params.item_id,
                context=context,
            )

        if item and not isinstance(item, WidgetItem):
            raise InvalidOperationError("A custom action needs a widget sender.")
        response = await self.sync_action(
            thread_metadata,
            request.params.action,
            item,
            context,
        )
        return browser_widget_response(response)

    def _apply_structured_input_submission(
        self,
        item: StructuredInputItem,
        submission: StructuredInputSubmission,
    ) -> StructuredInputItem:
        if item.status != "pending":
            raise ConflictError("The thread is not waiting for this form.")

        updated_item = item.model_copy(deep=True)
        questions_by_id = {question.id: question for question in updated_item.inputs}
        submitted_question_ids = set(submission.answers)
        unknown_question_ids = submitted_question_ids.difference(questions_by_id)
        if unknown_question_ids:
            unknown = ", ".join(sorted(unknown_question_ids))
            logger.warning(
                f"Structured input item {item.id} received unknown question id(s), ignoring: {unknown}"
            )

        for question in updated_item.inputs:
            answer = submission.answers.get(question.id)

            if (
                submission.status == "skipped"
                or answer is None
                or answer.skipped
                or not answer.values
            ):
                question.answer = StructuredInputAnswer(skipped=True)
                continue

            values = answer.values
            if isinstance(question, StructuredInputMultipleChoice):
                if not question.multiple:
                    values = values[:1]

            question.answer = StructuredInputAnswer(values=values)

        updated_item.status = submission.status
        return updated_item

    async def _accept_user_message(
        self,
        turn: Turn[TContext],
        *,
        create_thread: bool = False,
    ) -> StreamingResult:
        assert isinstance(turn.input, UserMessageTurn)
        item = turn.input.message
        for attachment in item.attachments:
            await self._get_attachment_metadata_store().save_attachment(
                attachment, context=turn.context
            )
        await self.store.begin_turn(
            turn.thread.id,
            turn.id,
            turn.context,
            message=item,
            create_thread=turn.thread if create_thread else None,
        )
        initial_events: list[ThreadStreamEvent] = []
        if create_thread:
            initial_events.append(
                ThreadCreatedEvent(thread=browser_thread(turn.thread))
            )
        initial_events.append(ThreadItemDoneEvent(item=item))
        return self._respond_to_turn(turn, initial_events=initial_events)

    def _respond_to_turn(
        self,
        turn: Turn[TContext],
        *,
        initial_events: list[ThreadStreamEvent] | None = None,
    ) -> StreamingResult:
        # The store applied the replacement when it accepted the form.
        form_update = (
            ThreadItemReplacedEvent(item=turn.input.item)
            if isinstance(turn.input, StructuredInputTurn)
            else None
        )
        return self._stream_turn(
            turn.thread,
            turn.id,
            turn.context,
            lambda: self.respond(turn),
            turn=turn,
            initial_events=initial_events,
            form_update=form_update,
        )

    def _stream_turn(
        self,
        thread: ThreadMetadata,
        turn_id: str,
        context: TContext,
        stream: Callable[[], AsyncIterator[ResponderEvent]],
        *,
        turn: Turn[TContext] | None = None,
        initial_events: list[ThreadStreamEvent] | None = None,
        form_update: ThreadItemReplacedEvent | None = None,
    ) -> StreamingResult:
        return StreamingResult(
            self._run_turn(
                thread,
                turn_id,
                context,
                stream,
                turn=turn,
                initial_events=initial_events,
                form_update=form_update,
            ),
            thread_id=thread.id,
            turn_id=turn_id,
            on_close_before_start=lambda: self._finish_turn(
                thread.id, turn_id, TurnOutcome.CANCELLED, context
            ),
        )

    async def _finish_turn(
        self, thread_id: str, turn_id: str, outcome: TurnOutcome, context: TContext
    ) -> TurnState | None:
        try:
            return await self.store.finish_turn(thread_id, turn_id, outcome, context)
        except NotFoundError:
            # Deleting a thread also removes its turn records.
            return None

    async def _run_turn(
        self,
        thread: ThreadMetadata,
        turn_id: str,
        context: TContext,
        stream: Callable[[], AsyncIterator[ResponderEvent]],
        *,
        turn: Turn[TContext] | None,
        initial_events: list[ThreadStreamEvent] | None,
        form_update: ThreadItemReplacedEvent | None,
    ) -> AsyncIterator[ThreadStreamEvent]:
        outcome = TurnOutcome.COMPLETED
        pending_inputs: set[str] = set()
        started = False
        try:
            await self.store.start_turn(thread.id, turn_id, context)
            started = True
            for event in initial_events or ():
                await self.store.require_current_turn(thread.id, turn_id, context)
                yield event
            async with _closing_stream(
                self._process_events(
                    thread, turn_id, context, stream, form_update=form_update
                )
            ) as events:
                async for event in events:
                    match event:
                        case ApprovalRequired():
                            if outcome is TurnOutcome.COMPLETED:
                                outcome = TurnOutcome.WAITING
                            continue
                        case ErrorEvent():
                            outcome = TurnOutcome.FAILED
                        case (
                            ThreadItemDoneEvent(item=item)
                            | ThreadItemReplacedEvent(item=item)
                        ):
                            if (
                                isinstance(
                                    item, (ClientToolCallItem, StructuredInputItem)
                                )
                                and item.status == "pending"
                            ):
                                pending_inputs.add(item.id)
                            else:
                                pending_inputs.discard(item.id)
                        case ThreadItemRemovedEvent(item_id=item_id):
                            pending_inputs.discard(item_id)
                    yield event
            if outcome is TurnOutcome.COMPLETED and pending_inputs:
                outcome = TurnOutcome.WAITING
        except TurnSupersededError, NotFoundError:
            outcome = TurnOutcome.SUPERSEDED
        except asyncio.CancelledError, GeneratorExit:
            outcome = TurnOutcome.CANCELLED
            raise
        except Exception:
            outcome = TurnOutcome.FAILED
            raise
        finally:
            state = await self._finish_turn(thread.id, turn_id, outcome, context)
            if started and turn is not None:
                if state is None or state is TurnState.SUPERSEDED:
                    outcome = TurnOutcome.SUPERSEDED
                elif state is TurnState.WAITING:
                    outcome = TurnOutcome.WAITING
                try:
                    await self.on_turn_finished(turn, outcome)
                except Exception:
                    logger.exception("Error in on_turn_finished")

    async def _process_events(
        self,
        thread: ThreadMetadata,
        turn_id: str,
        context: TContext,
        stream: Callable[[], AsyncIterator[ResponderEvent]],
        *,
        form_update: ThreadItemReplacedEvent | None = None,
    ) -> AsyncIterator[ThreadStreamEvent | ApprovalRequired]:
        # Send initial stream options
        await self.store.require_current_turn(thread.id, turn_id, context)
        yield StreamOptionsEvent(
            stream_options=self.get_stream_options(thread, context)
        )

        # Keep track of items that were streamed but not yet saved
        # so that we can persist them when the stream is cancelled.
        pending_items: dict[str, ThreadItem] = {}
        hidden_item_ids: set[str] = set()
        issued_tool_ids: set[str] = set()
        stream_failed = False
        loop = asyncio.get_running_loop()

        async def register_client_tool(request: ClientToolRequest) -> None:
            self._require_client_tool_store()
            invocation = ClientToolInvocation(
                item_id=request.item.id,
                thread_id=thread.id,
                turn_id=turn_id,
                call_id=request.call_id,
                model_continuation=request.model_continuation,
            )
            await self.store.register_client_tool_call(
                thread.id, request.item, invocation, context
            )
            issued_tool_ids.add(request.item.id)

        async def cancel_issued_tools() -> None:
            for item_id in issued_tool_ids.copy():
                await self.store.cancel_client_tool_call(
                    thread.id, item_id, context, turn_id=turn_id
                )
                issued_tool_ids.discard(item_id)

        try:
            if form_update is not None:
                await self.store.require_current_turn(thread.id, turn_id, context)
                yield form_update
            await self.store.require_current_turn(thread.id, turn_id, context)
            next_check = loop.time() + _TRANSIENT_OWNERSHIP_CHECK_INTERVAL
            async with _closing_stream(aiter(stream())) as events:
                while (event := await anext(events, None)) is not None:
                    match event:
                        case (
                            ThreadItemAddedEvent(item=ClientToolCallItem())
                            | ThreadItemDoneEvent(item=ClientToolCallItem())
                            | ThreadItemReplacedEvent(item=ClientToolCallItem())
                        ):
                            raise ValueError(
                                "Publish client tools with ClientToolRequest"
                            )
                        case ApprovalRequired(checkpoint=checkpoint):
                            if not stream_failed:
                                await self.store.require_current_turn(
                                    thread.id, turn_id, context
                                )
                                try:
                                    await self.save_approval_checkpoint(
                                        thread, turn_id, checkpoint, context
                                    )
                                except TurnSupersededError:
                                    raise
                                except Exception as exc:
                                    # Storage errors may contain private run state.
                                    logger.error(
                                        "Could not save approval checkpoint (%s)",
                                        type(exc).__name__,
                                    )
                                    raise StreamError(ErrorCode.STREAM_ERROR) from None
                                yield event
                            continue
                        case ClientToolRequest() as request:
                            if stream_failed:
                                continue
                            # A disconnect during a transaction must settle registration
                            # before cleanup decides which exact callback to cancel.
                            registration = asyncio.create_task(
                                register_client_tool(request)
                            )
                            try:
                                await asyncio.shield(registration)
                            except asyncio.CancelledError:
                                try:
                                    await registration
                                except TurnSupersededError:
                                    pass
                                except Exception:
                                    logger.exception("Error registering client tool")
                                raise
                            event = ThreadItemDoneEvent(item=request.item)
                        case ThreadItemDoneEvent():
                            await self.store.add_thread_item(
                                thread.id, event.item, context=context, turn_id=turn_id
                            )
                            pending_items.pop(event.item.id, None)
                        case ThreadItemRemovedEvent():
                            await self.store.delete_thread_item(
                                thread.id,
                                event.item_id,
                                context=context,
                                turn_id=turn_id,
                            )
                            pending_items.pop(event.item_id, None)
                            issued_tool_ids.discard(event.item_id)
                        case ThreadItemReplacedEvent():
                            await self.store.save_item(
                                thread.id, event.item, context=context, turn_id=turn_id
                            )
                            pending_items.pop(event.item.id, None)
                        case PersistWorkflow(item=item, replace=True):
                            await self.store.save_item(
                                thread.id, item, context=context, turn_id=turn_id
                            )
                            continue
                        case PersistWorkflow(item=item):
                            await self.store.add_thread_item(
                                thread.id, item, context=context, turn_id=turn_id
                            )
                            continue
                        case ThreadItemAddedEvent() | ThreadItemUpdatedEvent():
                            track_pending_item(pending_items, event)
                        case ErrorEvent():
                            stream_failed = True
                            await cancel_issued_tools()

                    if (
                        isinstance(
                            event,
                            (
                                ErrorEvent,
                                ThreadCreatedEvent,
                                ThreadUpdatedEvent,
                                ThreadItemDoneEvent,
                                ThreadItemRemovedEvent,
                                ThreadItemReplacedEvent,
                            ),
                        )
                        or loop.time() >= next_check
                    ):
                        await self.store.require_current_turn(
                            thread.id, turn_id, context
                        )
                        next_check = loop.time() + _TRANSIENT_OWNERSHIP_CHECK_INTERVAL
                    visible = browser_event(event, hidden_item_ids)
                    if visible is not None:
                        yield visible

        except asyncio.CancelledError, GeneratorExit:
            with suppress(TurnSupersededError):
                await self.store.require_current_turn(thread.id, turn_id, context)
                try:
                    await cancel_issued_tools()
                finally:
                    await self.handle_stream_cancelled(
                        thread, list(pending_items.values()), context, turn_id=turn_id
                    )
            raise
        except TurnSupersededError:
            raise
        except (CustomStreamError, StreamError) as error:
            await cancel_issued_tools()
            await self.store.require_current_turn(thread.id, turn_id, context)
            yield _stream_error_event(error)
        except Exception as e:
            await cancel_issued_tools()
            await self.store.require_current_turn(thread.id, turn_id, context)
            yield ErrorEvent(
                code=ErrorCode.STREAM_ERROR,
                allow_retry=True,
            )
            logger.exception(e)

    async def _build_user_message_item(
        self, input: UserMessageInput, thread: ThreadMetadata, context: TContext
    ) -> UserMessageItem:
        item = UserMessageItem(
            id=self.store.generate_item_id("message", thread, context),
            content=input.content,
            thread_id=thread.id,
            attachments=[
                (
                    await self._get_attachment_metadata_store().load_attachment(
                        attachment_id, context
                    )
                ).model_copy(update={"thread_id": thread.id})
                for attachment_id in input.attachments
            ],
            quoted_text=input.quoted_text,
            inference_options=input.inference_options,
            created_at=datetime.now(UTC),
        )
        identity = (item.id, item.thread_id, item.created_at)
        prepared = await self.prepare_user_message(thread, item, context)
        if (prepared.id, prepared.thread_id, prepared.created_at) != identity:
            raise ValueError("prepare_user_message must preserve message identity")
        return prepared

    async def _load_thread_with_first_page(
        self, thread_id: str, context: TContext
    ) -> Thread:
        thread_meta = await self.store.load_thread(thread_id, context=context)
        thread_items = await self.store.load_thread_items(
            thread_id,
            after=None,
            limit=DEFAULT_PAGE_SIZE,
            order="asc",
            context=context,
            include_hidden=False,
        )
        return browser_thread(thread_meta, stored_page=thread_items)

respond abstractmethod

respond(turn: Turn[TContext]) -> AsyncIterator[ResponderEvent]

Stream events for a new message, a resumed turn, or a retry.

Source code in chatkit/server.py
215
216
217
218
@abstractmethod
def respond(self, turn: Turn[TContext]) -> AsyncIterator[ResponderEvent]:
    """Stream events for a new message, a resumed turn, or a retry."""
    pass

prepare_user_message async

prepare_user_message(thread: ThreadMetadata, item: UserMessageItem, context: TContext) -> UserMessageItem

Validate or enrich a new user message before the server saves it.

The thread snapshot and resolved attachments are available. For a new thread, the snapshot has an ID and has yet to be saved. Return the item with its original ID, thread ID, and creation time.

Raise InvalidOperationError for a request error (HTTP 422 with the FastAPI adapter), or CustomStreamError for a user-facing error event. A rejected message produces no thread, attachment, or message writes. Retries and continuations use their stored inputs.

Source code in chatkit/server.py
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
async def prepare_user_message(
    self, thread: ThreadMetadata, item: UserMessageItem, context: TContext
) -> UserMessageItem:
    """Validate or enrich a new user message before the server saves it.

    The thread snapshot and resolved attachments are available. For a new
    thread, the snapshot has an ID and has yet to be saved. Return the item
    with its original ID, thread ID, and creation time.

    Raise `InvalidOperationError` for a request error (HTTP 422 with the
    FastAPI adapter), or `CustomStreamError` for a user-facing error event.
    A rejected message produces no thread, attachment, or message writes.
    Retries and continuations use their stored inputs.
    """
    return item

save_approval_checkpoint async

save_approval_checkpoint(thread: ThreadMetadata, turn_id: str, checkpoint: str, context: TContext) -> None

Save the paused run privately for an authorized reviewer to resume.

Source code in chatkit/server.py
236
237
238
239
240
241
242
async def save_approval_checkpoint(
    self, thread: ThreadMetadata, turn_id: str, checkpoint: str, context: TContext
) -> None:
    """Save the paused run privately for an authorized reviewer to resume."""
    raise UnsupportedOperationError(
        "Override save_approval_checkpoint to handle runs that require approval."
    )

on_turn_finished async

on_turn_finished(turn: Turn[TContext], outcome: TurnOutcome) -> None

Observe a turn's terminal outcome after server persistence or cleanup.

A waiting turn has a pending browser tool, form, or saved approval checkpoint. Completion describes server processing, not delivery to a browser. Exceptions raised by this hook are logged.

Source code in chatkit/server.py
244
245
246
247
248
249
250
251
252
253
async def on_turn_finished(  # noqa: B027
    self, turn: Turn[TContext], outcome: TurnOutcome
) -> None:
    """Observe a turn's terminal outcome after server persistence or cleanup.

    A waiting turn has a pending browser tool, form, or saved approval checkpoint.
    Completion describes server processing, not delivery to a browser. Exceptions
    raised by this hook are logged.
    """
    pass

update_thread async

update_thread(thread_id: str, patch: ThreadPatch, context: TContext, *, turn_id: str) -> ThreadUpdatedEvent

Apply a patch as the active responder and return its browser event.

Source code in chatkit/server.py
255
256
257
258
259
260
261
262
263
264
265
266
267
async def update_thread(
    self,
    thread_id: str,
    patch: ThreadPatch,
    context: TContext,
    *,
    turn_id: str,
) -> ThreadUpdatedEvent:
    """Apply a patch as the active responder and return its browser event."""
    updated = await self.store.patch_thread(
        thread_id, patch, context, turn_id=turn_id
    )
    return ThreadUpdatedEvent(thread=browser_thread(updated))

add_feedback async

add_feedback(thread_id: str, item_ids: list[str], feedback: FeedbackKind, context: TContext) -> None

Persist user feedback for one or more thread items.

Source code in chatkit/server.py
269
270
271
272
273
274
275
276
277
async def add_feedback(  # noqa: B027
    self,
    thread_id: str,
    item_ids: list[str],
    feedback: FeedbackKind,
    context: TContext,
) -> None:
    """Persist user feedback for one or more thread items."""
    pass

transcribe async

transcribe(audio_input: AudioInput, context: TContext) -> TranscriptionResult

Transcribe speech audio to text (dictation).

Audio bytes are in audio_input.data. The raw MIME type is audio_input.mime_type; use audio_input.media_type for the base media type (one of: audio/webm, audio/ogg, audio/mp4).

Parameters:

Name Type Description Default
audio_input AudioInput

Audio bytes plus MIME type metadata for transcription.

required
context TContext

Arbitrary per-request context provided by the caller.

required

Returns:

Type Description
TranscriptionResult

A TranscriptionResult whose text is what should appear in the composer.

Source code in chatkit/server.py
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
async def transcribe(  # noqa: B027
    self, audio_input: AudioInput, context: TContext
) -> TranscriptionResult:
    """Transcribe speech audio to text (dictation).

    Audio bytes are in `audio_input.data`. The raw MIME type is `audio_input.mime_type`; use
    `audio_input.media_type` for the base media type (one of: `audio/webm`, `audio/ogg`, `audio/mp4`).

    Args:
        audio_input: Audio bytes plus MIME type metadata for transcription.
        context: Arbitrary per-request context provided by the caller.

    Returns:
        A `TranscriptionResult` whose `text` is what should appear in the composer.
    """
    raise NotImplementedError(
        "transcribe() must be overridden to support the input.transcribe request."
    )

action

action(thread: ThreadMetadata, action: Action[str, Any], sender: WidgetItem | None, context: TContext, *, turn_id: str) -> AsyncIterator[ResponderEvent]

Handle a streaming action. Use its turn ID for direct store writes.

Source code in chatkit/server.py
298
299
300
301
302
303
304
305
306
307
308
309
310
311
def action(
    self,
    thread: ThreadMetadata,
    action: Action[str, Any],
    sender: WidgetItem | None,
    context: TContext,
    *,
    turn_id: str,
) -> AsyncIterator[ResponderEvent]:
    """Handle a streaming action. Use its turn ID for direct store writes."""
    raise NotImplementedError(
        "The action() method must be overridden to react to actions. "
        "See https://michaelgiraldo.github.io/chatkit-python/guides/build-interactive-responses-with-widgets/#handle-widget-actions"
    )

sync_action async

sync_action(thread: ThreadMetadata, action: Action[str, Any], sender: WidgetItem | None, context: TContext) -> SyncCustomActionResponse

Handle a widget or client-dispatched action and return a SyncCustomActionResponse.

Source code in chatkit/server.py
313
314
315
316
317
318
319
320
321
322
323
324
async def sync_action(
    self,
    thread: ThreadMetadata,
    action: Action[str, Any],
    sender: WidgetItem | None,
    context: TContext,
) -> SyncCustomActionResponse:
    """Handle a widget or client-dispatched action and return a SyncCustomActionResponse."""
    raise NotImplementedError(
        "The sync_action() method must be overridden to react to sync actions. "
        "See https://michaelgiraldo.github.io/chatkit-python/guides/build-interactive-responses-with-widgets/#handle-widget-actions"
    )

get_stream_options

get_stream_options(thread: ThreadMetadata, context: TContext) -> StreamOptions

Return stream-level runtime options. Allows the user to cancel the stream by default. Override this method to customize behavior.

Source code in chatkit/server.py
326
327
328
329
330
331
332
333
def get_stream_options(
    self, thread: ThreadMetadata, context: TContext
) -> StreamOptions:
    """
    Return stream-level runtime options. Allows the user to cancel the stream by default.
    Override this method to customize behavior.
    """
    return StreamOptions(allow_cancel=True)

handle_stream_cancelled async

handle_stream_cancelled(thread: ThreadMetadata, pending_items: list[ThreadItem], context: TContext, *, turn_id: str)

Perform custom cleanup / stop inference when a stream is cancelled. Updates you make here will not be reflected in the UI until a reload.

The default implementation persists any non-empty pending assistant messages to the thread but does not auto-save pending widget items or workflow items.

Parameters:

Name Type Description Default
thread ThreadMetadata

The thread that was being processed.

required
pending_items list[ThreadItem]

Items that were not done streaming at cancellation time.

required
context TContext

Arbitrary per-request context provided by the caller.

required
turn_id str

The turn being cancelled. Use it to fence cleanup writes.

required
Source code in chatkit/server.py
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
async def handle_stream_cancelled(
    self,
    thread: ThreadMetadata,
    pending_items: list[ThreadItem],
    context: TContext,
    *,
    turn_id: str,
):
    """Perform custom cleanup / stop inference when a stream is cancelled.
    Updates you make here will not be reflected in the UI until a reload.

    The default implementation persists any non-empty pending assistant messages
    to the thread but does not auto-save pending widget items or workflow items.

    Args:
        thread: The thread that was being processed.
        pending_items: Items that were not done streaming at cancellation time.
        context: Arbitrary per-request context provided by the caller.
        turn_id: The turn being cancelled. Use it to fence cleanup writes.
    """
    pending_assistant_message_items: list[AssistantMessageItem] = [
        item for item in pending_items if isinstance(item, AssistantMessageItem)
    ]
    for item in pending_assistant_message_items:
        is_empty = len(item.content) == 0 or all(
            (not content.text.strip()) for content in item.content
        )
        if not is_empty:
            await self.store.add_thread_item(
                thread.id, item, context=context, turn_id=turn_id
            )

    # Add a hidden context item to the thread to indicate that the stream was cancelled.
    # Otherwise, depending on the timing of the cancellation, subsequent responses may
    # attempt to continue the cancelled response.
    await self.store.add_thread_item(
        thread.id,
        SDKHiddenContextItem(
            thread_id=thread.id,
            created_at=datetime.now(UTC),
            id=self.store.generate_item_id("sdk_hidden_context", thread, context),
            content="The user cancelled the stream. Stop responding to the prior request.",
        ),
        context=context,
        turn_id=turn_id,
    )

process async

process(request: ChatKitReq, context: TContext) -> StreamingResult | ImmediateResult

Process a validated request. Resolve streaming inputs before returning.

Source code in chatkit/server.py
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
async def process(
    self, request: ChatKitReq, context: TContext
) -> StreamingResult | ImmediateResult:
    """Process a validated request. Resolve streaming inputs before returning."""
    logger.info("Received request op: %s", request.type)
    if not is_streaming_req(request):
        return await self._process_non_streaming(request, context)
    try:
        return await self._prepare_streaming(request, context)
    except (CustomStreamError, StreamError) as error:
        event = _stream_error_event(error)

        async def rejection() -> AsyncIterator[ThreadStreamEvent]:
            yield event

        return StreamingResult(rejection())