@embeddable.com/ai-chat

中文文档
0.3.4发布于 2026/10/21MITTypeScriptESM + CJS近 30 天下载 2810

A framework-agnostic Web Component that renders a streaming AI chat widget and connects to an Embeddable orchestrator backend over a STOMP WebSocket.

原始使用文档
文档目录16 节
  1. Quick start
  2. 1. Configure your LLM
  3. 2. Mint a security token
  4. 3. Load the ai-chat
  5. 4. Add the ai-chat to your page
  6. Security tokens
  7. Matching tokens with an on-page dashboard
  8. Disallowing custom canvas mutation
  9. Ai-chat props
  10. Labels
  11. Slots
  12. Theming
  13. Framework integration
  14. React / Vue / Angular (ESM import)
  15. Local development
  16. Architecture

@embeddable.com/ai-chat

A framework-agnostic Web Component that renders a streaming AI chat widget and connects to an Embeddable orchestrator backend over a STOMP WebSocket.

Built with Stencil — works in plain HTML, React, Vue, Angular, or any other framework.


Quick start

1. Configure your LLM

Before the ai-chat can respond, your workspace needs an LLM configured on the orchestrator backend. Send a POST to /api/v1/llm-config, authenticated with your Embeddable API key (Authorization: Bearer <api-key>). This is a one-time, per-workspace setup — the config is stored encrypted and reused for every chat session.

curl -X POST https://api.[us|eu].embeddable.com/api/v1/llm-config \
  -H "Authorization: Bearer YOUR_EMBEDDABLE_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "provider": "anthropic",
    "model": "claude-sonnet-4-5",
    "apiKey": "sk-ant-...",
    "temperature": 0.7,
    "maxTokens": 2048,
    "systemPrompt": "You are a helpful analytics assistant."
  }'

LLM config fields

FieldTypeRequiredDescription
providerstringYesLLM provider ID. Must be one supported by the backend: anthropic, openai, google, openrouter, mistralai, bedrock, or ollama. An unsupported value returns 400.
modelstringYesModel ID for the chosen provider (e.g. claude-sonnet-4-5, claude-haiku-4-5). Must be a model the provider supports; an unsupported value returns 400 with the accepted set.
apiKeystringYesProvider API key used to authenticate LLM calls. Stored encrypted and never returned in full — GET/POST responses mask it.
temperaturenumberNoSampling temperature. Higher values produce more varied output. Provider default is used when omitted.
maxTokensintegerNoMaximum number of tokens to generate per response. Provider default is used when omitted.
systemPromptstringNoSystem prompt prepended to every conversation to steer tone and behavior.

Retrieve the current config (with the API key masked) with GET /api/v1/llm-config. If none is set, it returns 404.

2. Mint a security token

Each user needs a security token, minted server-side with your Embeddable API key and passed to the embeddable-tokens prop. See Security tokens for the request and its options (including making the canvas read-only).

3. Load the ai-chat

Add this script to load the component latest version from unpkg (no build step required):

<script type="module" src="https://unpkg.com/@embeddable.com/[email protected]/dist/ai-chat/ai-chat.esm.js"></script>

4. Add the ai-chat to your page

Choose between modal (floating panel) or inline (fills its container):

  1. Modal mode - the chat opens in a floating panel when the trigger is clicked
<em-ai-chat mode="modal" placement="bottom-right" orchestrator-url="wss://api.[us|eu].embeddable.com/ws" embeddable-tokens='["your-security-token"]'>
  <button slot="trigger">Open chat</button>
</em-ai-chat>
  1. Inline mode - the chat fills its container
<div style="width: 420px; height: 600px;">
  <em-ai-chat mode="inline" orchestrator-url="wss://api.[us|eu].embeddable.com/ws" embeddable-tokens='["your-security-token"]'></em-ai-chat>
</div>

See demo.html for a full working example.


Security tokens

Every request the ai-chat makes is authenticated with a security token. Mint one per user with POST /api/v1/security-token (authenticated with your Embeddable API key), then pass it to the embeddable-tokens prop as a JSON-encoded array — the first token is used as the Bearer credential.

curl -X POST https://api.[us|eu].embeddable.com/api/v1/security-token \
  -H "Authorization: Bearer YOUR_EMBEDDABLE_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "embeddableId": "your-embeddable-id",
    "user": "user-123",
    "securityContext": {},
    "expiryInSeconds": 3600
  }'

Matching tokens with an on-page dashboard

If the page also renders one or more Embeddable dashboards (<em-beddable token="...">), it's recommended to pass those same token(s) to embeddable-tokens on <em-ai-chat>. The ai-chat only looks at <em-beddable> elements whose token matches one it was given — that match is what lets it read the dashboard currently on screen (its loaded widgets, queries, and data) and read the custom canvas's current layout (e.g. how many columns it has available), so it can size and position additions like a newly generated chart sensibly.

The widget still works with a different or standalone token — it can still add a chart to the canvas — but without a match it won't have visibility into the on-page dashboard's data or its layout, so it can't resize or position what it adds effectively.

This requirement to match tokens is temporary — a future release will remove the need for the ai-chat token to match the dashboard's, so these capabilities work regardless.

Disallowing custom canvas mutation

The AI can mutate the dashboard's custom canvas (for example, adding a chart it just generated). To make the canvas read-only for a token, add "customCanvasReadOnly": true to the request above. When set, the orchestrator denies canvas writes for that token and the ai-chat's tools are marked read-only — the assistant can still answer questions and preview charts, but cannot add to or otherwise modify the canvas. The flag defaults to false (mutations allowed) when omitted. Because it lives on the token, different users can be granted different levels of access with the same embedded widget.


Ai-chat props

AttributeTypeDefaultDescription
orchestrator-urlstring—WebSocket URL of the Embeddable orchestrator backend (ws:// or wss://)
embeddable-tokensstring—JSON-encoded array of security tokens. The first token is used as the Bearer credential.
client-contextstring—JSON-encoded dashboard client context (the same object passed to embeddables). Its timezone resolves dates consistently with the dashboard. Forwarded to the orchestrator and to injected components.
mode"modal" | "inline""inline"modal opens a floating draggable panel; inline fills its container
placement"bottom-right" | "bottom-left" | "top-right" | "top-left""top-right"Where the modal panel appears relative to the trigger element
chart-preview-supported"true" | "false""true"Tells the orchestrator whether this client can render Embeddable chart previews. Sent as the Embeddable-Chart-Preview-Supported header on the STOMP CONNECT frame.
labelsPartial<ChatLabels>—Overrides the widget's UI text (welcome message, input placeholder, feedback dialog copy). This is an object property, not a string attribute — set it in JS via the DOM property (el.labels = {…}), not as an HTML attribute. See Labels below.

Labels

All user-facing text is customized through the labels property (type ChatLabels). Provide any subset of the keys below; omitted keys fall back to the defaults.

KeyDefaultDescription
welcomeMessage(built-in greeting)Message shown in the empty state before the first user message
inputPlaceholder"Ask anything..."Placeholder text inside the message input
feedbackTitlePositive"Tell us what you liked"Title of the feedback comment dialog after a thumbs-up rating
feedbackTitleNegative"How can we improve?"Title of the feedback comment dialog after a thumbs-down rating
feedbackPlaceholderPositive"Share more"Placeholder text inside the feedback comment input after a thumbs-up
feedbackPlaceholderNegative"Share more"Placeholder text inside the feedback comment input after a thumbs-down
feedbackDismiss"Dismiss"Label for the dismiss button in the feedback dialog
feedbackSubmit"Submit feedback"Label for the submit button in the feedback dialog
feedbackThanksForFeedback"Thanks for your feedback"Confirmation message shown after a written comment is submitted
feedbackThanksForRating"Thanks for your rating"Confirmation message shown after only a thumbs up/down rating is given
addToDashboardConfirmationText"Shall I add this to your dashboard?"Prompt shown alongside a generated chart, asking whether to add it to the dashboard
addToDashboard"Add to dashboard"Label for the button that adds a generated chart to the dashboard
addingToDashboard"Adding to dashboard…"Label shown on the button while the add-to-dashboard action is in progress
newConversation"New conversation"Label for the button/action that starts a new conversation
ratePositive"Rate this positive"Accessible label for the thumbs-up rating button
rateNegative"Rate this negative"Accessible label for the thumbs-down rating button
addToDashboardMessageWithTitle'Add the chart "{title}" to the dashboard'User-message text sent when clicking "Add to dashboard" on a titled chart ({title} is substituted)
addToDashboardMessage"Add the chart to the dashboard"User-message text sent when clicking "Add to dashboard" on a chart without a title
conversationTooLongError"This conversation has become too long to continue. Please start a new conversation to keep chatting."Shown when the conversation transcript grows too large to continue
unknownError"An unknown error occurred"Shown when a server error arrives without a specific error message
const chat = document.querySelector('em-ai-chat');
chat.labels = {
  welcomeMessage: 'Hi! Ask me anything about your dashboard.',
  inputPlaceholder: 'Type a question…',
};

Slots

NameDescription
trigger(modal mode only) The element that toggles the chat panel open/closed

Theming

The component's visual properties are defined as --em-ai-chat-* CSS custom properties. By default, these resolve to tokens from the remarkable-ui design system — the --em-sem-* (semantic) and --em-core-* (primitive) token layers. You can see the full mapping in src/em-ai-chat/em-ai-chat.tokens.css.

If an <em-beddable> is already present in your app, the tokens --em-sem-* (semantic) and --em-core-* (primitive) will be automatically injected into the :root, and the style will be applied automatically.

If no <em-beddable> is present, or if you need specific styles for the chat, set the --em-ai-chat-* variables directly on em-ai-chat to match your own design:

em-ai-chat {
  /* Shell */
  --em-ai-chat-shell-background: #ffffff;
  --em-ai-chat-shell-border-color: #e4e4ea;

  /* Input composer */
  --em-ai-chat-composer-input-border-color: #e4e4ea;
  --em-ai-chat-composer-input-border-color--focus: #2d52cc;

  /* Primary icon button (send / cancel) */
  --em-ai-chat-icon-button-primary-background: #2d52cc;
  --em-ai-chat-icon-button-primary-color: #ffffff;

  /* Panel size (modal mode) */
  --em-ai-chat-panel-width: 23.75rem;
  --em-ai-chat-panel-height: 32.5rem;

  ...;
}

The full list of available variables is in src/em-ai-chat/em-ai-chat.tokens.css.


Framework integration

React / Vue / Angular (ESM import)

import { defineCustomElements } from '@embeddable.com/ai-chat/loader';
defineCustomElements();

Then use <em-ai-chat> like any other HTML element:

return (
  <em-ai-chat embeddable-tokens={JSON.stringify([token])} orchestrator-url="wss://..." mode="modal">
    <button slot="trigger">Chat</button>
  </em-ai-chat>
);

Vite users — add this to vite.config.ts to prevent Vite from pre-bundling the loader (which breaks Stencil's lazy chunk resolution):

export default defineConfig({
  optimizeDeps: {
    exclude: ['@embeddable.com/ai-chat'],
  },
});

Local development

npm install
npm start        # dev server with hot reload at http://localhost:3333

Edit src/index.html to change props or tokens while developing locally. The orchestrator backend is expected at ws://localhost:8080/ws by default.

npm run build    # production build → dist/

Architecture

em-ai-chat is the root component. It owns the STOMP WebSocket connection, holds all message state, and coordinates the child components below.

em-ai-chat
│   Root. Manages the STOMP WebSocket lifecycle, accumulates streaming
│   events into a display list, and switches between modal and inline modes.
│
├── em-ai-chat-modal-shell   (modal mode only)
│   Floating panel with trigger-based open/close, drag-to-reposition,
│   and mouse/keyboard resize. Persists panel size and position across toggles.
│
├── em-ai-chat-messages
│   Scrolling feed of user messages, assistant responses, tool calls, errors,
│   and injected components. Groups tool calls under their parent message
│   and auto-scrolls to the latest entry.
│
│   ├── em-ai-chat-message-feedback
│   │   Thumbs up/down rating attached to each assistant message.
│   │
│   └── em-ai-chat-component
│       Sandboxed host for Embeddable component bundles injected by the AI.
│       Injects theme tokens, scales height via ResizeObserver, and proxies
│       data-fetch requests to the orchestrator.
│
└── em-ai-chat-input
    Textarea composer. Enter sends, Shift+Enter adds a newline. Auto-focuses
    on visibility and toggles the action button between send and cancel
    while a response is streaming.

Incoming server events are processed by reduceEvent() in src/utils/messages.utils.ts. It maintains a Map<id, message> for O(1) streaming updates and returns a new array reference on each change to trigger Stencil re-renders.

版本与发布记录

@embeddable.com/ai-chat 共发布 16 个版本,首次发布于 2026/07/09;过去 12 个月发布了 16 个版本。

版本发布日期距今
0.3.4latest2026/10/2123 天前
0.3.32026/10/2123 天前
0.3.22026/10/2124 天前
0.3.12026/10/011 个月前
0.3.02026/09/221 个月前
0.2.32026/07/273 个月前

关于 @embeddable.com/ai-chat 的常见问题

@embeddable.com/ai-chat 是什么?

A framework-agnostic Web Component that renders a streaming AI chat widget and connects to an Embeddable orchestrator backend over a STOMP WebSocket.

如何安装 @embeddable.com/ai-chat?

在项目目录运行 npm install @embeddable.com/ai-chat,或使用 pnpm add / yarn add / bun add。

@embeddable.com/ai-chat 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@embeddable.com/ai-chat 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@embeddable.com/ai-chat 可以商用吗?

@embeddable.com/ai-chat 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@embeddable.com/ai-chat 的下载量有多少?

根据 npm 官方下载统计,@embeddable.com/ai-chat 在 2026/10/14 – 2026/11/12 这 30 天内被下载 2,810 次,日均约 94 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@embeddable.com/ai-chat 还在维护吗?

最新版本 0.3.4 发布于 2026/10/21(23 天前);至今共发布 16 个版本,其中过去 12 个月发布了 16 个;首次发布于 2026/07/09。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。