ChatKit Python SDK

repository·main·Indexed 18 days ago

https://github.com/openai/chatkit-python

A backend SDK for building chat-based interfaces and managing conversational workflows. It provides the ChatKitServer class for handling user messages, streaming widget updates via ThreadStreamEvents, and managing thread state and persistence through a Store. The library includes modules for agents, widgets, and structured entities to enable rich UI responses and domain-specific data integration.

Tokens
33.6K
Snippets
71
Records
108
Agent score
60%

What's inside openai-chatkit-python

  1. Get started with the ChatKit Python SDK

    main

    The ChatKit Python SDK provides tools for building chat-based applications. To begin using the SDK, you should follow the Quick start guide, understand the core concept of Threads, and refer to the API reference for detailed method signatures.

    Key resources for developers:

    • Quick start: For initial setup and first calls.
    • Core concepts: To understand how Threads manage conversation state.
    • Guides: For specific tasks like responding to user messages or preparing an application for production.
    • API reference: For the complete technical specification of the chatkit package.
  2. Explore the Chatkit Python API Reference

    main

    The Chatkit Python API is organized into several functional modules to help you build chat-based applications, manage state, and integrate with agents:

    • chatkit.server: Use ChatKitServer and its helpers to receive incoming messages, stream responses, and wire up tools and widgets.
    • chatkit.store: Provides interfaces and utilities for persisting threads, items, and metadata.
    • chatkit.agents: Contains helpers and utilities for using ChatKit in conjunction with the Agents SDK.
    • chatkit.types: Access Pydantic models for core data structures like threads, items, and events.
    • chatkit.errors: Use these structured error types to ensure your integration emits consistent ErrorEvents to the client.
    • chatkit.widgets: Use models and helpers like WidgetTemplate, DynamicWidgetRoot, and BasicRoot to build rich UI responses.
  3. What is a thread and how does it work?

    main

    In ChatKit, a thread is the central unit representing a single conversation. It acts as an ordered timeline of thread items, which includes conversation history (user and assistant messages), structured content (widgets, workflows), internal signals, and metadata (titles, status flags).

    Threads are persisted by your store implementation. ChatKit manages the lifecycle of a thread by loading, paginating, and rendering these items as needed. A thread can be updated, continued, or made read-only based on your application logic.

  4. Implement a ChatKit Store

    main

    ChatKit servers require a Store implementation to manage the lifecycle of threads, items (messages), and attachments. To implement a custom store, inherit from Store[T] and implement the following core methods:

    • load_thread(thread_id, context): Retrieve thread metadata.
    • save_thread(thread, context): Persist thread metadata.
    • load_threads(limit, after, order, context): Paginate through threads.
    • load_thread_items(thread_id, after, limit, order, context): Paginate through items in a thread.
    • add_thread_item(thread_id, item, context): Add a new item to a thread.
    • save_item(thread_id, item, context): Update or create an item.
    • load_item(thread_id, item_id, context): Retrieve a specific item.
    • delete_thread(thread_id, context) / delete_thread_item(thread_id, item_id, context): Remove data.

    For production, use a database-backed store (e.g., Postgres or MySQL) instead of in-memory implementations.

  5. What are Tools in ChatKit

    main

    Tools allow an assistant to execute application logic during a conversation turn. This enables the model to search data, run workflows, or fetch user context, then incorporate the results back into the conversation.

    There are two primary types of tools:

    1. Server tools: Run on your backend. The assistant calls them through your inference pipeline, and results are streamed back into the conversation.
    2. Client tools: Run in the browser or host application. ChatKit surfaces the tool call as a streamed thread item, allows the client to handle the execution, and then resumes the conversation with the client's output.
  6. Configure an attachment upload strategy

    main

    Choose between two upload strategies by setting ChatKitOptions.api.uploadStrategy:

    1. Direct: The client sends bytes to a single uploadUrl provided by your backend. This is simpler and faster if your app server handles uploads directly.
    2. Two-phase: The client first requests metadata via the ChatKit API, receives an upload_url (e.g., a presigned cloud storage URL), and then uploads the bytes in a second step. This is preferred for offloading bandwidth to third-party blob storage or using cloud object storage.

    Note: Both strategies require an AttachmentStore to handle delete cleanup.

    // Example Direct configuration
    {
      type: "direct",
      uploadUrl: "/files",
    }
    
    // Example Two-phase configuration
    {
      type: "two_phase",
    }
  7. How Thread stream events work

    main

    ThreadStreamEvents are Server-Sent Event (SSE) payloads streamed by ChatKitServer during user interactions. These events serve two primary purposes:

    1. UI Synchronization: They keep the client interface in sync with server-side processing.
    2. Persistence: They drive the persistence of conversation state in your data store.

    Events are categorized into metadata updates, item events, errors, progress updates, client effects, and stream options.

  8. What are Widgets in ChatKit

    main
    Widgets are structured UI elements that an assistant can stream into a conversation. Instead of relying solely on plain text, widgets allow you to render interactive components such as forms, cards, lists, and charts. They are designed to collect structured input, present rich results, or provide multiple-choice options for users to interact with via actions.
  9. Use Entities as cited sources in assistant messages

    main

    You can use entities to provide citations or references within assistant responses. This allows the assistant to link its text to specific data objects.

    To implement this, you should use the EntitySource Pydantic model to define the source of the information. For detailed implementation steps on how to attach these to messages, refer to the guide on adding annotations in assistant messages.

  10. Use Client tools for local application context

    main

    Client tools are used when the model needs access to data or capabilities that only exist in the user's local environment (browser or host app) and cannot be safely or effectively accessed from the server.

    Use cases for Client tools:

    • Reading current selections in a canvas or document.
    • Inspecting local application state that should not leave the browser.
    • Interacting with host application APIs (e.g., an IDE or design tool).

    Lifecycle of a Client tool call:

    1. Server-side: You must instruct your inference pipeline to stop when the specific tool is called (e.g., by using StopAtTools around that tool).
    2. Streaming: ChatKit converts the tool call into a streamed thread item.
    3. Client-side: The onClientTool callback receives the item, executes the local logic, and returns a JSON result.
    4. Resumption: ChatKit sends the result back to the server, which initiates a new stream to continue the run using the tool output as model input.
  11. What are hidden context items?

    main

    Hidden context items are included in the model input but are not rendered in the chat UI. They allow the model to react to interface actions (like widget interactions or selection states) that aren't explicitly typed by the user.

    • HiddenContextItem: Integration-defined context where you control the schema and how it is converted for the model.
    • SDKHiddenContextItem: Internal hidden context used by the ChatKit Python SDK. Most applications do not need to modify this.
  12. What are thread items and how are they used?

    main

    Thread items are the individual records that constitute a thread's history. They serve two primary roles:

    1. Model Input: Your server's respond logic reads thread items to construct the context for the model. This ensures the model maintains conversational continuity.
    2. UI Rendering: On the client side, ChatKit.js renders these items incrementally as they stream in or when a past thread is loaded to reconstruct the conversation UI.

    Common item types include user messages, assistant messages, widgets, and hidden context items.