# OpenAI ChatKit Tutorial: Self-Hosted Agent Chat in React

> Build an embedded agent chat with @openai/chatkit-react and the ChatKit Python server: the respond loop, the Store contract, widgets, attachments, auth and domain keys.

URL: https://www.matthewswong.com/en/blog/openai-chatkit-self-hosted-chat-ui/

- Author: Matthews Wong (https://www.matthewswong.com/en/about/)
- Published: 2026-10-01
- Updated: 2026-10-01
- Category: AI

> **Key takeaway:** OpenAI ChatKit is an embeddable React chat UI that, when self-hosted, talks to your own Python ChatKitServer endpoint, which runs an Agents SDK agent and streams replies, widgets and progress events. You still own authentication, the thread Store and attachment storage, and the UI itself loads from OpenAI's CDN behind a registered domain key.

The chat widget on this site is 826 lines of React in Chatbot.tsx and another 416 in its API route. A good share of that is plumbing nobody sees: reading the response body with getReader and a TextDecoder, cancelling the request with an AbortController when the panel closes, and keeping the last 20 messages in localStorage because there is no server-side thread store. So when OpenAI positioned ChatKit as the way to build agent chat without reinventing the chat UI, the question I cared about was which of those lines it would actually delete, and which new ones it would add.

This OpenAI ChatKit tutorial builds the self-hosted version end to end: @openai/chatkit-react on the front end, the open-source ChatKit Python server on the back end, and an Agents SDK agent behind it, using an ERP order-status desk as the example. It is the path OpenAI now recommends, because Agent Builder, which backed the hosted ChatKit option, is scheduled to shut down on 30 November 2026. Every API name below comes from OpenAI's ChatKit guides, the chatkit-python repository and its production guide, or the official advanced samples.

## OpenAI ChatKit tutorial: what self-hosted really means

ChatKit has two integration paths. The hosted one creates a session against an Agent Builder workflow and hands the browser a client secret; OpenAI's guide now limits it to teams who already have such a workflow, during the transition window. The other, which the docs call the advanced or custom server integration, is what this post builds. Self-hosted is slightly misleading as a name, because it describes the back end only. There are three pieces, and you run two of them:

- The UI: chatkit.js, loaded from cdn.platform.openai.com and rendered in an iframe, driven from React by the ChatKit component and the useChatKit hook. You configure it; you do not host it.
- The protocol endpoint: one POST route on your server, usually /chatkit, that hands the raw request body to a ChatKitServer instance and returns either JSON or a text/event-stream response.
- The persistence layer: a Store for threads and items and, if you enable uploads, an AttachmentStore for files. Both are abstract classes you implement against your own database and object storage.

The upside of that split is that your agent, your data and your model calls stay on your infrastructure, and the guide lists custom authentication, data residency and on-premises deployment as the reasons to choose it. The cost is that everything a hosted product would have done for you, namely login, tenancy, retention and file storage, is now code you write. The rest of this post is that code, in the order I would write it.

## The Python server: respond() and stream_agent_response

Install the server with pip install openai-chatkit, which pulls in the openai-agents package as a dependency. ChatKitServer is generic over a context type of your choosing, and the one method you must override is respond, an async generator that receives the thread metadata and the new user message and yields thread stream events. The chatkit.agents module provides the bridge: simple_to_agent_input converts stored thread items into Agents SDK input, and stream_agent_response turns a streamed run into ChatKit events, including tool progress and any widgets your tools emit.

Two details in that block matter more than they look. The model name comes from configuration because nothing in ChatKit ties you to one; the guide says the server can connect to any agentic service, and respond is just a generator, so it could call another provider entirely. And the tool reads the authenticated user from ctx.context.request_context, which is the same object your HTTP layer passed in. That is how a tool scopes an ERP query to the caller's tenant without the model ever being told the tenant id.

> OpenAI's two official snippets disagree on how to load history. The custom-integration guide loads the newest 20 items in descending order and reverses them; the chatkit-python quickstart loads 20 items in ascending order with no cursor. The second returns the oldest 20 items, so once a thread grows past 20 the user's new message silently drops out of the model's input. Use descending order and reverse, as above.

## The endpoint: authentication is your job

ChatKit routes every request type, such as creating a thread, posting a message, listing threads or running a widget action, through a single endpoint. ChatKitServer.process takes the raw body and a context object, and that context is the only channel through which identity reaches your store and tools. The production guide is explicit that the Python SDK expects your app to handle authentication, so the pattern is: authenticate with whatever your framework already uses, build a typed context with the user id, tenant and locale, and pass it in.

Locale comes for free: the ChatKit client sends a single locale in the Accept-Language header on every request, defaulting to the browser's language unless you override the locale option. For a bilingual audience like mine, that header is what decides whether tool output and error messages come back in English or Indonesian, and the production guide shows the gettext pattern for it. The other thing the guide asks for is that system instructions stay static and never include user-supplied values such as a thread title, because those are a prompt injection path.

## The Store contract: tenant scoping lives in twelve methods

chatkit.store.Store is an abstract class with twelve methods: load, save, list and delete for threads; add, save, load, list and delete for thread items; and save, load and delete for attachments. Every one of them receives the context object, which is the point. The quickstart's in-memory store is fine for a demo and wrong for anything shared, because its load_threads returns every thread in the dictionary regardless of who asked. The guide's advice for production is a durable database with the models stored as JSON blobs, so that a library upgrade which adds fields does not need a schema migration.

I would treat the Store as the real security boundary of the whole feature. The endpoint decides who you are; the Store decides what you can see. If load_thread does not check ownership, any user who learns or guesses a thread id can read another user's conversation, including whatever an ERP tool returned into it. Retention belongs here too: the production guide suggests implementing it in the Store, for example deleting threads older than a set number of days, because threads hold user text, attachments and tool output.

## The React front end: useChatKit with your own API

Install the bindings with npm install @openai/chatkit-react and load chatkit.js from OpenAI's CDN. For a custom server, the api option takes a url instead of the hosted getClientSecret callback, plus a domainKey, an optional fetch override and the upload strategy. The fetch override is the clean way to attach your own bearer token, because ChatKit calls it for every request it makes. Theme, start-screen prompts and composer settings all live in the same options object.

The theme options cover colour scheme, accent colour and level, a grayscale tint, corner radius from pill to sharp, density from compact to spacious, and typography. That was enough for me to match this site's dark palette with one accent colour. Attachment limits are worth setting explicitly: the published types default to 100 MB per file and 10 files per message, which is generous for a chat that forwards files to a model.

> Trust the TypeScript types over the prose examples. The theming guide shows attachments configured with an uploadStrategy inside composer and no enabled flag, but the @openai/chatkit type definitions put uploadStrategy under api and make composer.attachments.enabled the switch, defaulting to false. In a Next.js App Router project, the component also needs the use client directive, since useChatKit is a hook.

## Widgets and actions: rich replies without a protocol of your own

Widgets are where ChatKit earns its place over a hand-rolled UI. You design a card, list or form visually at widgets.chatkit.studio, preview it with sample data, export a .widget file and commit it beside the server code. On the server, WidgetTemplate.from_file loads it and build fills its placeholders; a tool can then call ctx.context.stream_widget, and stream_agent_response forwards the widget to the client. Buttons and form controls carry an action with a type and a payload, which arrives at the action method on your ChatKitServer without the user typing a message.

In an ERP setting I keep one rule for actions: a button may create a draft or a request, never a posted document. The cancellation button above files a request that a person approves, which keeps the chat surface out of the approval chain. Actions can also be routed to the browser by setting the handler to client, which suits pure UI work such as opening a record in another panel. If a widget text field should stream as it is generated, give that Text or Markdown node an id; the widgets guide notes that only those nodes stream their text, and other changes re-render.

## Attachments and domain keys before you ship

Attachments need an AttachmentStore passed to the ChatKitServer constructor. With the two_phase strategy, the client asks your server to create an attachment, your create_attachment returns an upload descriptor with a URL, and the browser uploads to it, which can be a signed URL on your object storage. The direct strategy posts the file to an uploadUrl you supply instead. The hosted strategy is for the Agent Builder path only. Getting the bytes to the model is a separate step: the official customer-support sample subclasses ThreadItemConverter and overrides attachment_to_message_content to turn a stored image into an input_image part.

Domain keys are the last step and the one that breaks deploys. You register each production hostname in the domain allowlist under your OpenAI organisation's security settings and copy the generated key into the domainKey option. On load, the ChatKit iframe calls api.openai.com to verify it, and if the key is missing or invalid ChatKit refuses to render. The official samples run locally on a placeholder key, so a staging hostname that was never registered is the first place this fails.

> Self-hosting the back end does not remove OpenAI from the browser. The UI is fetched from OpenAI's CDN, the iframe verifies the domain key against api.openai.com, and the production guide states that the iframe sends its own telemetry to OpenAI-controlled endpoints, Datadog and chatgpt.com, which it says contains no PII or message content. If your compliance review requires that a page make no third-party requests, ChatKit does not fit, however the server is hosted.

## ChatKit or a hand-rolled streaming chat UI

Comparing against the chatbot I already run makes the trade concrete. It streams from a Groq-backed route and keeps everything in the browser; ChatKit would replace the client half and move history to the server, at the price of a Python service and a CDN dependency.

| Concern | ChatKit, self-hosted | Hand-rolled, like this site's chatbot |
| --- | --- | --- |
| Streaming | StreamingResult over text/event-stream; the client parses events, including tool progress | A getReader and TextDecoder loop, plus abort handling, that you write and debug |
| Thread history | Server-side Store with a built-in thread list; you implement twelve methods | Whatever you build; mine keeps the last 20 messages in localStorage |
| Attachments | AttachmentStore with two_phase or direct uploads and previews | Upload route, storage, previews and model conversion all built by hand |
| Rich replies | Widgets designed in ChatKit Studio, with server or client actions | Your own components and your own message protocol to carry them |
| Where the UI runs | Iframe from OpenAI's CDN, domain key checked on load, OpenAI telemetry | Your bundle, your CSP, no third-party request |
| Server stack | Official server SDK is Python; respond can call any model or agent | Any language and any provider; this site uses a Next.js route and Groq |

My rule of thumb from that table: ChatKit pays off once you need two of server-side threads, attachments and widgets, because each is real, easy-to-get-wrong work when done by hand. For a single-purpose assistant that streams text, such as the one on this site, a hand-rolled UI on the Next.js stack you already run stays simpler, and keeps the page free of third-party requests. The deciding question is less about the chat UI than about whether a Python service is acceptable in your deployment.

ChatKit moves the hard part of agent chat from the browser to the server rather than removing it. The UI, streaming and widget rendering are done for you; authentication, the tenant-scoped Store, attachment storage, retention and domain keys are not. Build those five deliberately, load history newest-first, and keep every action a draft, and the self-hosted path gives you an agent chat whose data stays yours.

## Sources and further reading

- OpenAI — ChatKit guide (integration paths and Agent Builder transition)
- OpenAI — Advanced integrations with ChatKit (custom server)
- GitHub — openai/chatkit-python, the ChatKit Python SDK
- ChatKit Python docs — Prepare your app for production
- GitHub — openai/openai-chatkit-advanced-samples

## Source links

- https://developers.openai.com/api/docs/guides/chatkit
- https://developers.openai.com/api/docs/guides/custom-chatkit
- https://github.com/openai/chatkit-python
- https://openai.github.io/chatkit-python/guides/prepare-your-app-for-production/
- https://github.com/openai/openai-chatkit-advanced-samples

## FAQ

### What is OpenAI ChatKit?

ChatKit is OpenAI's embeddable chat interface for agent experiences. It ships widgets, tool-invocation display, file attachments and chain-of-thought visualisations, so you configure a chat UI instead of building one. In React you render it with the ChatKit component and the useChatKit hook from @openai/chatkit-react.

### How do I self-host ChatKit with my own agent?

Install the Python server with pip install openai-chatkit, subclass ChatKitServer and override respond to run your Agents SDK agent through stream_agent_response. Expose one POST endpoint that passes the request body to server.process, and point the useChatKit api.url option at it. You also implement a Store for threads and items.

### Is ChatKit still available after Agent Builder shuts down?

Yes. OpenAI states that Agent Builder is scheduled to shut down on 30 November 2026 but ChatKit remains available. The hosted path that backed ChatKit with an Agent Builder workflow is for existing users during the transition, and new work should use the advanced integration with your own server-side agent.

### Does self-hosted ChatKit still send data to OpenAI from the browser?

The UI is loaded from OpenAI's CDN and the iframe verifies your domain key against api.openai.com on load. The ChatKit production guide also says the iframe sends its own telemetry to OpenAI-controlled endpoints, which it states contains no PII or message content. Your threads, files and agent run on your own server.

### How do file attachments work in a custom ChatKit server?

Attachments are disabled by default, so set composer.attachments.enabled to true and choose an uploadStrategy of two_phase or direct under the api option. On the server, pass an AttachmentStore to ChatKitServer; with two_phase its create_attachment returns an upload URL the browser uploads to. Converting a stored file into model input is done in a ThreadItemConverter.

---

- HTML version: https://www.matthewswong.com/en/blog/openai-chatkit-self-hosted-chat-ui/
- Bahasa Indonesia: https://www.matthewswong.com/id/blog/openai-chatkit-self-hosted-chat-ui/
- Site index for agents: https://www.matthewswong.com/llms.txt
- Sitemap: https://www.matthewswong.com/sitemap.xml
- API description (OpenAPI): https://www.matthewswong.com/openapi.json
