SDK
docket-sdk adds a chat to your site with streamed, markdown-formatted answers and their sources. Use the ready-made widget, the React component, or the headless client with your own UI.
Set this up with your AI agent
Set up the Docket SDK (docket-sdk) in this project.
Docket answers questions from my own documents, streams the answer, and checks it against them before showing it. It is hosted at https://YOUR_HOST. Docs: https://YOUR_HOST/docs?page=sdk
My publishable key: pk_live_PASTE_YOUR_KEY_HERE
If that still says PASTE, ask me for the key. Never invent one.
What to do
1. Look at the project first: the framework, the package manager, and where the app's root layout or entry file is. If something important is unclear, ask me one short question before you change anything.
2. Install the package with the project's package manager: npm install docket-sdk
3. Add the chat once, at the app root. Pick what fits the project:
- React or Next.js (in Next.js, put it in a client component with "use client"):
import { DocketChat } from "docket-sdk/react";
<DocketChat publishableKey="MY_PUBLISHABLE_KEY" apiBase="https://YOUR_HOST" theme="auto" />
- Any other JavaScript app:
import { createWidget } from "docket-sdk";
const chat = createWidget({ publishableKey: "MY_PUBLISHABLE_KEY", apiBase: "https://YOUR_HOST", theme: "auto", onError: (err) => console.warn(err.code, err.message) });
- Only if I ask for my own chat interface:
import { createClient } from "docket-sdk"; const docket = createClient({ apiKey: "MY_PUBLISHABLE_KEY", apiBase: "https://YOUR_HOST" });
for await (const event of docket.stream(question)) { ... } // "delta" events carry text, the "done" event carries the full reply and citations
apiBase is required when the SDK comes from npm.
4. If the project uses env files, keep the key in its public variable (for example NEXT_PUBLIC_DOCKET_KEY or VITE_DOCKET_KEY) instead of hard-coding it.
5. Check it works: start the dev server, open the page, ask a question my documents answer and one they do not (the second should get my fallback message), and confirm the console shows no Docket errors.
Rules
- Browser code uses a publishable key (pk_live_...). Never put a secret key (sk_live_...) in browser code. The SDK refuses it.
- Do not render the chat on the server.
- Set other options only if I ask: mode ("floating", or "inline" with a container), position, accentColor, botName, welcomeMessage, quickPrompts, open, persist, identityToken, onMessage.
- If a request fails, read the error code. UNAUTHORIZED: the key is wrong, or this site is not allowed, so add its address to the group's allowed domains in Studio. RATE_LIMITED: wait retryAfterSeconds. SECRET_KEY_IN_BROWSER: the wrong key type.
When you finish, list the files you changed. Do not change anything unrelated.Choose an integration
Each step down gives you more control and asks for a little more code.
| Integration | What you write | What you control |
|---|---|---|
| Script tag | One <script> tag | Theme, corner, color, open on load |
createWidget or <DocketChat /> | A few lines of JavaScript | All of the above, plus callbacks, history storage, signed-in users and inline layout |
createClient | Your own chat UI | Everything. Also runs on your server, in Node, Deno or edge runtimes |
What the SDK cannot change
The bot’s persona, rules, documents, fallback message and allowed sites are set in Studio and enforced on the server. The SDK only changes how the chat looks and behaves on your page. Each publishable key belongs to one bot: to show a different bot on another page, use that bot’s key.Script tag
Paste this before </body>. The widget mounts itself in a shadow root, so your page’s CSS and its CSS never affect each other.
<script src="https://YOUR_HOST/docket-sdk.js" data-key="pk_live_YOUR_PUBLIC_KEY" async></script>| Attribute | Values | Description |
|---|---|---|
data-key | pk_live_… | Required. Your publishable key. |
data-theme | light, dark, auto | auto follows the visitor’s system setting. |
data-position | bottom-right, bottom-left | Overrides the corner set in Studio. |
data-accent-color | Hex color | Overrides the color set in Studio. |
data-open | true | Open the chat as soon as the page loads. |
data-api-base | URL | Your Docket origin. Defaults to where the script was loaded from. |
The script adds window.Docket. For callbacks or signed-in users, leave out data-key and call Docket.init() with the same options as createWidget.
<script src="https://YOUR_HOST/docket-sdk.js"></script><script> Docket.init({ publishableKey: "pk_live_YOUR_PUBLIC_KEY", theme: "auto", onMessage: (m) => console.log(m.role, m.content), });</script><button onclick="Docket.open()">Ask our docs</button>Install from npm
npm install docket-sdkimport { createWidget } from "docket-sdk";
const chat = createWidget({ publishableKey: "pk_live_YOUR_PUBLIC_KEY", apiBase: "https://YOUR_HOST", theme: "auto", onError: (err) => console.warn(err.code, err.message),});
chat.open();await chat.send("How do refunds work?");Options
Branding options default to the values in Studio, so set them only to override.
| Option | Default | Description |
|---|---|---|
publishableKey | Required | Your pk_ key. It decides which bot answers. |
apiBase | Required on npm | Origin of your Docket app. |
mode | floating | floating shows a chat button and panel. inline fills container. |
container | – | Element to render into. Required for inline mode. |
theme | light | light, dark or auto. |
accentColor | From Studio | Hex color for the button, header and your visitor’s messages. |
position | From Studio | bottom-right or bottom-left. |
botName | From Studio | Name in the header. |
subtitle | “Answers cite verified documentation” | Line under the name. |
welcomeMessage | From Studio | First message in an empty chat. |
quickPrompts | From Studio | Suggested questions, shown until the visitor asks one. |
open | false | Open the panel on load. |
persist | local | local keeps history in localStorage. none keeps it in memory only. |
identityToken | – | A signed token, or a function that returns one. See Signed-in users. |
onRestore() | – | Return earlier messages from your own store. |
onSave(messages) | – | Called after each reply and on reset, with the whole conversation. |
onReady(config) | – | Called once the bot’s settings have loaded. |
onOpen() | – | The panel opened. |
onClose() | – | The panel closed. |
onMessage(message) | – | A message finished: the visitor’s, the bot’s, or a failed reply. |
onError(error) | – | A request failed. See Errors. |
Controller
createWidget and Docket.init return an object for your own buttons and flows.
| Member | Description |
|---|---|
open() | Open the panel (floating mode). |
close() | Close it. |
toggle() | Open if closed, close if open. |
send(text) | Ask a question as if the visitor typed it. Resolves when the reply has finished. |
reset() | Clear the conversation and its stored history, and start a new session. |
setIdentityToken(token) | Set or replace the signed-in user’s token, for example after login. |
destroy() | Remove the widget and its listeners from the page. |
isOpen | Whether the panel is open. |
messages | A copy of the conversation, without the welcome message. |
React
<DocketChat /> takes the same options as props. Callbacks are read on every call, so passing new functions on each render does not rebuild the widget. Pass widgetRef to get the controller.
"use client";import { useRef } from "react";import { DocketChat, type DocketWidget } from "docket-sdk/react";
export function Support() { const chat = useRef<DocketWidget | null>(null);
return ( <> <button onClick={() => chat.current?.open()}>Ask our docs</button> <DocketChat widgetRef={chat} publishableKey="pk_live_YOUR_PUBLIC_KEY" apiBase="https://YOUR_HOST" theme="auto" /> </> );}For a chat inside your layout, set mode="inline" and give it a height:
<DocketChat mode="inline" style={{ height: 560 }} publishableKey="pk_live_…" apiBase="https://YOUR_HOST" />Headless client
Build your own interface on createClient. stream() hands you the reply as it arrives; chat() waits for the whole reply.
import { createClient } from "docket-sdk";
const docket = createClient({ apiKey: "pk_live_YOUR_PUBLIC_KEY", apiBase: "https://YOUR_HOST" });
for await (const event of docket.stream("How do refunds work?", { history })) { if (event.type === "delta") appendText(event.text); if (event.type === "done") showSources(event.citations);}
const { reply, verified, citations } = await docket.chat("And for annual plans?", { history });On your server, use a secret key (sk_live_…). The SDK refuses a secret key in a browser, and the API refuses one on any request that comes from a web page. renderMarkdown(text) and StreamingMarkdown are exported too, if you want the widget’s safe markdown rendering in your own UI.
Streaming
Every reply is checked against your documents before any of it is sent. If the check fails, the visitor sees your fallback message, so they never watch an answer appear and then get taken back. The checked reply then arrives in small pieces and takes under a second to appear in full.
The widget formats markdown as it arrives. Each message gets one element, and only the paragraph or list that is still growing is redrawn, so the rest of the chat stays still and scrolling isn’t interrupted. A reply looks exactly the same whether it streamed in or was reloaded from history. Links open in a new tab, only http, https and mailto links are allowed, and HTML in a reply is shown as text.
Under the hood the SDK calls POST /api/v1/chat, which answers with server-sent events:
event: metadata: {"verified":true,"score":100,"blockedByGuardrail":false}
event: deltadata: {"text":"Pro plans can be "}
event: deltadata: {"text":"refunded within 30 days."}
event: donedata: {"reply":"Pro plans can be refunded within 30 days.","verified":true,"score":100, "citations":[{"file":"billing/refunds.md","startLine":12,"endLine":14,"verified":true}], "latencyMs":948}| Event | Data |
|---|---|
meta | Sent first: verified, score, blockedByGuardrail. |
delta | A piece of the reply. Joined together, the pieces equal done.reply. |
done | The full reply with citations, latencyMs and remainingBalanceUSD. |
error | Only if the stream fails partway: code and error. |
Request body: message (required), history (earlier turns as { role, content }), sessionId and identityToken. Send the key in the Authorization header, as for the REST API.
Conversations
Docket does not store conversations. The widget keeps them in the visitor’s browser:
- The last 50 messages are saved in localStorage and restored on the next visit.
- The last 20 are sent with each question so follow-ups make sense. The server uses only the most recent few.
- Each browser gets a session id, used for the per-session limits. The clear button and reset() start a new one.
- To keep history in your own database, implement
onRestoreandonSave, and setpersist: "none"if nothing should stay in the browser.
Signed-in users
If your visitors log in, your server can sign a short-lived token that says who they are. Docket then applies per-user limits across tabs and devices. It is optional: without a token, visitors are anonymous and the session and IP limits apply.
| Part | Value |
|---|---|
| Format | JWT signed with HS256 |
| Signing key | The lowercase hex SHA-256 of one of this bot’s secret keys, used as a UTF-8 string |
sub | Required. Your id for the user |
exp | Required. At most 24 hours after iat |
iat | Recommended. Issue time, in seconds |
import { createHash, createHmac } from "node:crypto";
// The signing key is the SHA-256 (lowercase hex) of one of this bot's secret keys.const signingKey = createHash("sha256") .update(process.env.DOCKET_SECRET_KEY!) .digest("hex");
const b64 = (o: object) => Buffer.from(JSON.stringify(o)).toString("base64url");
export function docketToken(userId: string) { const now = Math.floor(Date.now() / 1000); const head = b64({ alg: "HS256", typ: "JWT" }); const body = b64({ sub: userId, iat: now, exp: now + 3600 }); const sig = createHmac("sha256", signingKey).update(`${head}.${body}`).digest("base64url"); return `${head}.${body}.${sig}`;}Serve the token from an endpoint only your signed-in users can reach, and pass a function so the SDK fetches a fresh one when it needs it:
createWidget({ publishableKey: "pk_live_YOUR_PUBLIC_KEY", apiBase: "https://YOUR_HOST", identityToken: () => fetch("/api/docket-token").then((r) => r.text()),});Bad tokens are refused
An invalid or expired token gets401 with code INVALID_IDENTITY; it is not quietly ignored. Deleting the secret key in Studio invalidates every token signed with it.Limits
| Scope | Limit |
|---|---|
| Per session | 10 messages a minute, 100 a day |
| Per signed-in user | 200 messages a day |
| Per key, all visitors together | 120 a minute, 5,000 a day |
| Per visitor IP address | 30 a minute on one key, 60 a minute across keys |
| Message length | 2,000 characters |
Over a limit, the API answers 429 with a Retry-After header. The widget tells the visitor how long to wait and offers a retry button.
Errors
Failed requests reject with a DocketError that has code, status and, when rate limited, retryAfterSeconds.
| Code | Status | Meaning |
|---|---|---|
RATE_LIMITED | 429 | A limit was reached. Wait retryAfterSeconds, then retry. |
UNAUTHORIZED | 401 | The key is missing, invalid, deactivated, or not allowed on this site. |
INVALID_IDENTITY | 401 | The identity token is malformed, expired or wrongly signed. |
SECRET_KEY_IN_BROWSER | 401 | A secret key was used from a web page. Use a publishable key. |
MESSAGE_TOO_LONG | 400 | The message is over 2,000 characters. |
BAD_REQUEST | 400 | The message is empty, or sessionId or identityToken is malformed. |
STREAM_INTERRUPTED | – | The connection dropped before the reply finished. |
NETWORK | – | Docket could not be reached. |
For allowed sites and key types, see API keys.