The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:
TypeScript analyticsbibusiness-intelligencebusinessintelligenceclojuredashboarddatadata-analysisdata-visualizationdatabasemetabasemysqlpostgrespostgresqlreportingslacksql-editorvisualization
docs - useMetabot hook (#73692)
Jeff Bruemmer36321a578a4a
diff --git a/docs/embedding/components.md b/docs/embedding/components.mdindex b491cce607b..3767c7ccec7 100644--- a/docs/embedding/components.md+++ b/docs/embedding/components.md@@ -102,6 +102,8 @@ To render the AI chat interface:<metabase-metabot></metabase-metabot>```+If you're using the SDK, you can use either the [`MetabotQuestion`](./sdk/ai-chat.md#example) component or the [`useMetabot`](./sdk/ai-chat.md#building-custom-ai-chat-uis-with-usemetabot) hook for a custom UI.+### Attributes{% include_file "{{ dirname }}/eajs/snippets/MetabaseMetabotAttributes.md" snippet="properties" %}diff --git a/docs/embedding/images/ai-chat-dedicated-chart.png b/docs/embedding/images/ai-chat-dedicated-chart.pngnew file mode 100644index 00000000000..546056b196aBinary files /dev/null and b/docs/embedding/images/ai-chat-dedicated-chart.png differdiff --git a/docs/embedding/images/ai-chat-inline-chart.png b/docs/embedding/images/ai-chat-inline-chart.pngnew file mode 100644index 00000000000..c08e2895400Binary files /dev/null and b/docs/embedding/images/ai-chat-inline-chart.png differdiff --git a/docs/embedding/sdk/ai-chat.md b/docs/embedding/sdk/ai-chat.mdindex 4c6fe2be7a9..9e22d3375b1 100644--- a/docs/embedding/sdk/ai-chat.md+++ b/docs/embedding/sdk/ai-chat.md@@ -56,3 +56,33 @@ Use the `layout` prop to specify which layout to use for the Metabot component:- `auto` (default): Metabot uses the `stacked` layout on mobile screens, and a `sidebar` layout on larger screens.- `stacked`: the question visualization stacks on top of the chat interface.- `sidebar`: the question visualization appears to the left of the chat interface, which is on a sidebar on the right.++## Building custom AI chat UIs with `useMetabot`++If `MetabotQuestion`'s built-in layouts don't fit your app, use the `useMetabot` hook to read Metabot's conversation state directly and render your own UI. The hook gives you the messages, the chart the agent most recently produced, processing and error state, and actions to submit, cancel, retry, or reset the conversation.++### AI chat with inline charts++++When an agent responds, the message can contain a `Chart` component. You can walk the agent's messages and render charts inline alongside the chat transcript:++```typescript+{% include_file "{{ dirname }}/snippets/questions/use-metabot-inline-charts.tsx" %}+```++### AI chat with dedicated chart panel++++The `CurrentChart` component is bound to the latest chart the agent produced. Render `CurrentChart` once, and it will swap in new charts as the agent creates them. You'll want to filter chart messages out of the transcript so they don't render twice:++```typescript+{% include_file "{{ dirname }}/snippets/questions/use-metabot-dedicated-chart.tsx" %}+```++### Notes on `useMetabot`++- **Guard against null while waiting for the SDK bundle**: `useMetabot` returns `null` until the SDK bundle has loaded and `<MetabaseProvider>` has mounted. Always guard before use. If you don't guard it, the first render will throw `Cannot read properties of null` when you reach for `metabot.messages`, `metabot.submitMessage`, etc., because the SDK ships its Metabot internals via a code-split chunk that isn't available synchronously.+- **Bring your own Markdown renderer**: `MetabotQuestion` renders agent text messages internally, including markdown formatting, transcript scrolling, and input styling. The `useMetabot` hook hands you the raw conversation state, which means you own the rendering. In particular, agent text messages (`message.type === 'text'`) contain **markdown**: links, bold, lists, inline code. The snippets above render `message.message` as plain text for brevity, but production usage should pass the text through a markdown renderer (`react-markdown`, `markdown-to-jsx`, or your own) so links and formatting display correctly.+- **Strip links returned by the agent**: the agent text may include links pointing back to the host Metabase (like a link to a chart it created). Those links require an authenticated Metabase session, so people won't be able to view the links.diff --git a/docs/embedding/sdk/snippets/questions/use-metabot-dedicated-chart.tsx b/docs/embedding/sdk/snippets/questions/use-metabot-dedicated-chart.tsxnew file mode 100644index 00000000000..843d5dd8a93--- /dev/null+++ b/docs/embedding/sdk/snippets/questions/use-metabot-dedicated-chart.tsx@@ -0,0 +1,113 @@+import React, { useState } from "react";+import {+ MetabaseProvider,+ defineMetabaseAuthConfig,+ useMetabot,+} from "@metabase/embedding-sdk-react";++const authConfig = defineMetabaseAuthConfig({+ metabaseInstanceUrl: "https://your-metabase.example.com",+});++function MetabotChat() {+ const metabot = useMetabot();+ const [prompt, setPrompt] = useState("");++ // useMetabot returns null until the SDK bundle has loaded+ // and <MetabaseProvider> has mounted. Always guard before use.+ if (!metabot) {+ return <div>Loading…</div>;+ }++ const handleSubmit = (event: React.FormEvent) => {+ event.preventDefault();+ if (!prompt.trim()) {+ return;+ }+ metabot.submitMessage(prompt);+ setPrompt("");+ };++ const { CurrentChart } = metabot;++ return (+ <div style={{ display: "flex", gap: 16, height: 600 }}>+ <div style={{ flex: 1 }}>+ {CurrentChart ? (+ <CurrentChart drills height="100%" />+ ) : (+ <div+ style={{ display: "grid", placeItems: "center", height: "100%" }}+ >+ Ask Metabot to generate a chart+ </div>+ )}+ </div>++ <div+ style={{+ width: 380,+ display: "flex",+ flexDirection: "column",+ gap: 12,+ }}+ >+ <div+ style={{+ flex: 1,+ overflowY: "auto",+ display: "flex",+ flexDirection: "column",+ gap: 4,+ }}+ >+ {metabot.messages.map((message) => {+ // Chart messages render in the dedicated panel on the left,+ // so you should filter them out in the chat transcript+ // so they don't render twice.+ if (message.role === "agent" && message.type === "chart") {+ return null;+ }+ // Agent text (message.role === "agent") is markdown: links,+ // bold, lists, code, etc. Wrap in a markdown renderer (react-markdown,+ // markdown-to-jsx, etc.). Rendered as plain+ // text here for brevity. User text (message.role === "user") is+ // raw, so no markdown rendering needed.+ return (+ <div+ key={message.id}+ style={{+ alignSelf:+ message.role === "user" ? "flex-end" : "flex-start",+ }}+ >+ {message.message}+ </div>+ );+ })}+ </div>++ <form onSubmit={handleSubmit} style={{ display: "flex", gap: 8 }}>+ <input+ value={prompt}+ onChange={(event) => setPrompt(event.target.value)}+ placeholder="Ask Metabot…"+ disabled={metabot.isProcessing}+ style={{ flex: 1 }}+ />+ <button type="submit" disabled={metabot.isProcessing}>+ Send+ </button>+ </form>+ </div>+ </div>+ );+}++export default function App() {+ return (+ <MetabaseProvider authConfig={authConfig}>+ <MetabotChat />+ </MetabaseProvider>+ );+}diff --git a/docs/embedding/sdk/snippets/questions/use-metabot-inline-charts.tsx b/docs/embedding/sdk/snippets/questions/use-metabot-inline-charts.tsxnew file mode 100644index 00000000000..daafb0dc236--- /dev/null+++ b/docs/embedding/sdk/snippets/questions/use-metabot-inline-charts.tsx@@ -0,0 +1,80 @@+import React, { useState } from "react";+import {+ MetabaseProvider,+ defineMetabaseAuthConfig,+ useMetabot,+} from "@metabase/embedding-sdk-react";++const authConfig = defineMetabaseAuthConfig({+ metabaseInstanceUrl: "https://your-metabase.example.com",+});++function MetabotChat() {+ const metabot = useMetabot();+ const [prompt, setPrompt] = useState("");++ // useMetabot returns null until the SDK bundle has loaded+ // and <MetabaseProvider> has mounted. Always guard before use.+ if (!metabot) {+ return <div>Loading…</div>;+ }++ const handleSubmit = (event: React.FormEvent) => {+ event.preventDefault();+ if (!prompt.trim()) {+ return;+ }+ metabot.submitMessage(prompt);+ setPrompt("");+ };++ return (+ <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>+ <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>+ {metabot.messages.map((message) => {+ if (message.role === "user") {+ return (+ <div key={message.id} style={{ alignSelf: "flex-end" }}>+ {message.message}+ </div>+ );+ }+ if (message.type === "text") {+ // message.message is markdown: links, bold, lists, code.+ // Wrap in a markdown renderer (react-markdown, markdown-to-jsx,+ // etc.) for production use; rendered as plain text here for brevity.+ return <div key={message.id}>{message.message}</div>;+ }+ // Agent chart message — render its bound Chart inline.+ const { Chart } = message;+ return (+ <div key={message.id} style={{ height: 400 }}>+ <Chart drills height="100%" />+ </div>+ );+ })}+ </div>++ <form onSubmit={handleSubmit} style={{ display: "flex", gap: 8 }}>+ <input+ value={prompt}+ onChange={(event) => setPrompt(event.target.value)}+ placeholder="Ask Metabot…"+ disabled={metabot.isProcessing}+ style={{ flex: 1 }}+ />+ <button type="submit" disabled={metabot.isProcessing}>+ Send+ </button>+ </form>+ </div>+ );+}++export default function App() {+ return (+ <MetabaseProvider authConfig={authConfig}>+ <MetabotChat />+ </MetabaseProvider>+ );+}diff --git a/frontend/src/embedding-sdk-bundle/types/metabot.ts b/frontend/src/embedding-sdk-bundle/types/metabot.tsindex 2f2ad8df465..f0e48f6dbc4 100644--- a/frontend/src/embedding-sdk-bundle/types/metabot.ts+++ b/frontend/src/embedding-sdk-bundle/types/metabot.ts@@ -31,17 +31,22 @@ export type MetabotAgentChartMessage = {Chart: React.ComponentType<MetabotChartProps>;};-// Internal variants intentionally omitted. `use-metabot.tsx` filters these out before mapping:-// - `tool_call`: debug-only, gated on metabot's `debugMode`.-// - `edit_suggestion`: targets the in-app Transform editor, which the SDK does not render.-// - `action`: unused in shipped code.-// - `todo_list`: only reachable via the `codegen/transforms` profile, not the SDK.+// Internal variants intentionally omitted. `use-metabot.tsx` only exposes+// `type === "text"` messages `:+// - `tool_call` messages: debug-only, gated on metabot's `debugMode`.+// - `action` user messages: produced only when replaying historical audit conversations,+// never via the SDK input path.+// - `data_part` messages other than `navigate_to` (`code_edit`, `transform_suggestion`,+// `todo_list`, `adhoc_viz`, `static_viz`, `state`): in-app surfaces (Transform editor,+// codegen profiles) the SDK does not render.export type MetabotAgentMessage =| MetabotAgentTextMessage| MetabotAgentChartMessage;+/** @category useMetabot */export type MetabotMessage = MetabotUserTextMessage | MetabotAgentMessage;+/** @category useMetabot */export type MetabotChartProps =| (Omit<StaticQuestionProps, "questionId" | "token" | "query"> & {drills?: false;@@ -50,12 +55,14 @@ export type MetabotChartProps =drills: true;});+/** @category useMetabot */export type MetabotErrorMessage = {/** `"alert"` renders with a warning icon and error color; `"message"` renders as plain text. */type: "message" | "alert" | "locked";message: string;};+/** @category useMetabot */export type UseMetabotResult = {/** Submit a new message to the conversation. */submitMessage: (message: string) => Promise<void>;