ChatKit provides an embeddable chat UI for your agent. It supports file attachments, interactive widgets, and tool calls.
Run ChatKit on your own infrastructure with the custom server integration. Use the ChatKit Python SDK to connect it to a server-side agent, including one built with the Agents SDK.
Use the custom server integration to connect the ChatKit UI to your backend. Authenticate each user on your server and restrict access to their threads and files.
-
In your project directory, install the ChatKit React bindings:
npm install @openai/chatkit-react
-
Add the ChatKit JS script to your page. Drop this snippet into your pageâs <head> or wherever you load scripts, and the browser will fetch and run ChatKit for you.
1
2
3
4<script
src="https://cdn.platform.openai.com/deployments/chatkit/chatkit.js"
async
></script>
-
Import ChatKit and useChatKit from @openai/chatkit-react. In your React component, call useChatKit with api.url set to the endpoint your server exposes (for example, /chatkit). Set api.domainKey to a nonempty development value on localhost. For production, register your frontend domain and use the public domain key issued for it. Keep your OpenAI API key on the server.
-
Pass the hookâs control to the ChatKit component, give the component a visible height, and send a message. Check that your endpoint receives the request and the reply appears in the chat. See the React component in the customer support example.
To try a complete integration, follow the customer support quickstart. Install uv and set OPENAI_API_KEY in the terminal that runs the backend. From examples/customer-support, install the exampleâs dependencies with npm install, then run npm start. The React app proxies requests to the Python server at /support/chatkit. Ask the agent about your seat assignment to verify the connection.
See the custom theming, widgets, and actions docs to learn more about how ChatKit works. Or explore the following resources to test your chat, iterate on prompts, and add widgets and tools.
Learn to handle authentication, add theming and customization, and more.
Add server-side storage, access control, tools, and other backend
functionality.
Check out the ChatKit JS repo.
Play with an interactive demo of ChatKit.
Browse available widgets.
Play with an interactive demo to learn by doing.
See working examples of ChatKit and get inspired.
Use workflow evaluations to test your agent before deploying changes.
If you previously used Agent Builder, look for a workflow ID in your serverâs session request and a client secret exchange in your frontend. Replace that integration with a connection to your own ChatKit endpoint. Configure authentication and thread storage on the new server, then test a new conversation and reopen it as the same user.
Historical examples of an Agent Builder integration
Use these examples only to locate the hosted session dependency in existing code. The Java example used the Maven dependency com.openai:openai-java:4.117.0. The Go example used the module installed with go get github.com/openai/openai-go/v3@v3.111.0.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33export default async function getChatKitSessionToken(deviceId: string) {
const apiKey = process.env.OPENAI_API_KEY;
if (!apiKey) {
throw new Error("OPENAI_API_KEY is required");
}
const response = await fetch("https://api.openai.com/v1/chatkit/sessions", {
method: "POST",
headers: {
"Content-Type": "application/json",
"OpenAI-Beta": "chatkit_beta=v1",
Authorization: `Bearer ${apiKey}`,
},
body: JSON.stringify({
workflow: { id: "wf_68df4b13b3588190a09d19288d4610ec0df388c3983f58d1" },
user: deviceId,
}),
});
if (!response.ok) {
throw new Error(
`Failed to create a ChatKit session: ${response.status} ${await response.text()}`
);
}
const { client_secret } = await response.json();
if (!client_secret) {
throw new Error("ChatKit session response did not include client_secret");
}
return client_secret;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60# Replace the illustrative IDs and URLs below with your own resource values.
import hmac
import json
import os
from typing import Annotated
import requests
from fastapi import Depends, FastAPI, HTTPException
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
from pydantic import BaseModel
api_key = os.environ["OPENAI_API_KEY"]
workflow_id = "wf_123"
authenticated_users: dict[str, str] = json.loads(
os.environ["CHATKIT_AUTHENTICATED_USERS"]
)
bearer_auth = HTTPBearer(auto_error=False)
def get_authenticated_user_id(
credentials: Annotated[
HTTPAuthorizationCredentials | None,
Depends(bearer_auth),
],
) -> str:
if credentials is not None:
for token, user_id in authenticated_users.items():
if hmac.compare_digest(credentials.credentials, token):
return user_id
raise HTTPException(status_code=401, detail="Invalid authentication token")
class ChatKitSession(BaseModel):
client_secret: str
app = FastAPI()
@app.post("/api/chatkit/session")
def create_chatkit_session(
user_id: Annotated[str, Depends(get_authenticated_user_id)],
):
response = requests.post(
"https://api.openai.com/v1/chatkit/sessions",
headers={
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json",
"OpenAI-Beta": "chatkit_beta=v1",
},
json={
"workflow": {"id": workflow_id},
"user": user_id,
},
timeout=30,
)
response.raise_for_status()
session = ChatKitSession.model_validate(response.json())
return {"client_secret": session.client_secret}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15// Call after authenticating the request. Pass the user's stable ID from your
// server-side authentication context, never a client-supplied device ID.
func getChatKitSessionToken(ctx context.Context, client openai.Client, authenticatedUserID string) (string, error) {
// Replace this illustrative workflow ID with your published workflow.
session, err := client.Beta.ChatKit.Sessions.New(ctx, openai.BetaChatKitSessionNewParams{
User: authenticatedUserID,
Workflow: openai.ChatSessionWorkflowParam{
ID: "wf_68df4b13b3588190a09d19288d4610ec0df388c3983f58d1",
},
})
if err != nil {
return "", err
}
return session.ClientSecret, nil
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.beta.chatkit.sessions.*;
import com.openai.models.beta.chatkit.threads.ChatSessionWorkflowParam;
// Call after authenticating the request. Pass the user's stable ID from your
// server-side authentication context, never a client-supplied device ID.
static String getChatKitSessionToken(OpenAIClient client, String authenticatedUserId) {
// Replace this illustrative workflow ID with your published workflow.
return client
.beta()
.chatkit()
.sessions()
.create(
SessionCreateParams.builder()
.user(authenticatedUserId)
.workflow(
ChatSessionWorkflowParam.builder()
.id("wf_68df4b13b3588190a09d19288d4610ec0df388c3983f58d1")
.build())
.build())
.clientSecret();
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57# Replace the illustrative IDs and URLs below with your own resource values.
require "json"
require "net/http"
require "openssl"
require "webrick"
api_key = ENV.fetch("OPENAI_API_KEY")
workflow_id = "wf_123"
# Demo authentication mapping. Replace this with your application's session authentication.
authenticated_users = JSON.parse(ENV.fetch("CHATKIT_AUTHENTICATED_USERS"))
server = WEBrick::HTTPServer.new(
BindAddress: "127.0.0.1", Port: Integer(ENV.fetch("PORT", "8000")),
AccessLog: [], Logger: WEBrick::Log.new($stderr, WEBrick::BasicLog::WARN)
)
server.mount_proc("/api/chatkit/session") do |request, response|
response["Content-Type"] = "application/json"
response["Cache-Control"] = "no-store"
unless request.path == "/api/chatkit/session" && request.request_method == "POST"
response.status = 405
response.body = JSON.generate(error: "Use POST /api/chatkit/session")
next
end
token = request["Authorization"].to_s.delete_prefix("Bearer ")
user = authenticated_users.find do |credential, _id|
request["Authorization"].to_s.start_with?("Bearer ") &&
OpenSSL.secure_compare(credential, token)
end
unless user
response.status = 401
response.body = JSON.generate(error: "Invalid authentication token")
next
end
uri = URI("https://api.openai.com/v1/chatkit/sessions")
upstream = Net::HTTP::Post.new(uri)
upstream["Authorization"] = "Bearer #{api_key}"
upstream["Content-Type"] = "application/json"
upstream["OpenAI-Beta"] = "chatkit_beta=v1"
upstream.body = JSON.generate(workflow: { id: workflow_id }, user: user.fetch(1))
begin
result = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true, open_timeout: 10, read_timeout: 30) do |http|
http.request(upstream)
end
result.value
secret = JSON.parse(result.body).fetch("client_secret")
raise "Missing session secret" unless secret.is_a?(String) && !secret.empty?
response.body = JSON.generate(client_secret: secret)
rescue
response.status = 502
response.body = JSON.generate(error: "Unable to create a ChatKit session")
end
end
trap("INT") { server.shutdown }
trap("TERM") { server.shutdown }
puts("http://127.0.0.1:#{server.config[:Port]}/api/chatkit/session")
$stdout.flush
server.start
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28const chatkit = document.getElementById("my-chat");
if (
!chatkit ||
!("setOptions" in chatkit) ||
typeof chatkit.setOptions !== "function"
) {
throw new Error("ChatKit element not found.");
}
chatkit.setOptions({
api: {
async getClientSecret() {
const appAuthToken = await getAppAuthToken();
const res = await fetch("/api/chatkit/session", {
method: "POST",
headers: {
Authorization: `Bearer ${appAuthToken}`,
"Content-Type": "application/json",
},
});
if (!res.ok) {
throw new Error(`ChatKit session request failed: ${res.status}`);
}
const { client_secret } = await res.json();
return client_secret;
},
},
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26import { ChatKit, useChatKit } from '@openai/chatkit-react';
export function MyChat({ getAppAuthToken }) {
const { control } = useChatKit({
api: {
async getClientSecret(existing) {
if (existing) {
// implement session refresh
}
const appAuthToken = await getAppAuthToken();
const res = await fetch('/api/chatkit/session', {
method: 'POST',
headers: {
'Authorization': 'Bearer ' + appAuthToken,
'Content-Type': 'application/json',
},
});
const { client_secret } = await res.json();
return client_secret;
},
},
});
return <ChatKit control={control} className="h-[600px] w-[320px]" />;
}