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
Stop the embedded Metabot from drafting SQL (#83565)
lbrdnk6b1873023ba9
diff --git a/.clj-kondo/config/modules/config.edn b/.clj-kondo/config/modules/config.ednindex 69ffb6cfb88..2280649bfb0 100644--- a/.clj-kondo/config/modules/config.edn+++ b/.clj-kondo/config/modules/config.edn@@ -1523,6 +1523,7 @@collectionsdocumentsdriver+ embeddingeventsexplorationsinterestingnessdiff --git a/docs/embedding/ai-chat.md b/docs/embedding/ai-chat.mdindex 0c411c28a86..ae37bd3a4bc 100644--- a/docs/embedding/ai-chat.md+++ b/docs/embedding/ai-chat.md@@ -15,7 +15,7 @@ You can embed an AI chat in your app, so people can ask questions of their dataTo build that question, embedded chat first searches your Metabase for the best thing to build on: a [metric](../data-modeling/semantic-layer/metrics.md), a [model](../data-modeling/models/models.md), a saved question, or a table (tables drop out once you [scope the chat to a collection](#set-up-ai-chat-in-metabase)). Then it writes a query against whatever it picked. So embedded chat does look through your saved content, but as raw material for a new question, not as results to hand back. What people get back is always a new question they can drill into, and save if you [turn saving on](#let-people-save-questions-metabot-creates).-Embedded chat won't write SQL, build or edit dashboards, or create metrics and models — it builds on the ones you already have. It also won't work as a search box for finding existing content. For those, chat will suggest doing the work in Metabase itself.+Embedded chat won't write SQL, build or edit dashboards, or create metrics and models. The chat also won't work as a search box for finding existing content. If someone asks for one of those, chat says it can't do that here and offers the closest question it can build.AI chat requires the embed to use SSO authentication that signs people into your Metabase.diff --git a/resources/metabot/prompts/llm_shape.selmer b/resources/metabot/prompts/llm_shape.selmerindex 9e292a13035..49bc563924b 100644--- a/resources/metabot/prompts/llm_shape.selmer+++ b/resources/metabot/prompts/llm_shape.selmer@@ -79,8 +79,8 @@ The following fields are available in this table.{% if table_related_tables_xml %}### Related TablesForeign key fields from related tables. Usage patterns:-- Can be used directly in notebook queries (non-sql) as if they were part of the table.-- For SQL queries: Use "fieldname" with explicit JOINs+- Can be used directly in notebook queries as if they were part of the table.+- They are not columns of the table itself; any other kind of query must join the related table through the listed foreign key.{{table_related_tables_xml|safe}}{% endif %}@@ -133,8 +133,8 @@ The following fields are available in this model.### Related TablesForeign key fields from related tables. Usage patterns:-- Can be used directly in notebook queries (non-sql) as if they were part of the model.-- For SQL queries: Use "fieldname" with explicit JOINs+- Can be used directly in notebook queries as if they were part of the model.+- They are not columns of the model itself; any other kind of query must join the related table through the listed foreign key.{{model_related_tables_xml|safe}}{% endif %}diff --git a/resources/metabot/prompts/shared/prompt_snippets/semantic-layer-discovery.selmer b/resources/metabot/prompts/shared/prompt_snippets/semantic-layer-discovery.selmerindex 66cb6a8001e..824319b3294 100644--- a/resources/metabot/prompts/shared/prompt_snippets/semantic-layer-discovery.selmer+++ b/resources/metabot/prompts/shared/prompt_snippets/semantic-layer-discovery.selmer@@ -6,4 +6,4 @@ When the user names a business quantity — a **rate or ratio** ("open rate", "b- **Measures** — a named aggregation attached to a table. Search for it (`entity_types: ["measure"]`), or read the table's details: its `<measure>` elements are the curated aggregations for that table. Prefer `["measure", {}, "<portable_entity_id>"]` over hand-writing the same calculation.- **Segments** — a named, reusable filter attached to a table. When a request names a cohort, search for it (`entity_types: ["segment"]`) or check the table's `<segment>` elements, and prefer `["segment", {}, "<portable_entity_id>"]` over re-deriving the filter conditions.-Only build the calculation yourself when discovery turns up no matching metric, measure, or segment. (See the construct skills for the exact clause syntax — this opaque-id syntax is for notebook queries. When writing raw SQL there's no equivalent clause, so query the underlying table or an existing model that already encodes the same logic instead.) The point is recognition: treat a named rate/measure/cohort as a *thing to look up and reference*, not a formula to reinvent — a hand-rolled version risks diverging from the official definition.+Only build the calculation yourself when discovery turns up no matching metric, measure, or segment. (See the construct skills for the exact clause syntax — this opaque-id syntax is for notebook queries.) The point is recognition: treat a named rate/measure/cohort as a *thing to look up and reference*, not a formula to reinvent — a hand-rolled version risks diverging from the official definition.diff --git a/resources/metabot/prompts/system/embedding-next.selmer b/resources/metabot/prompts/system/embedding-next.selmerindex 7e015833398..5f335b0cdaa 100644--- a/resources/metabot/prompts/system/embedding-next.selmer+++ b/resources/metabot/prompts/system/embedding-next.selmer@@ -30,11 +30,13 @@ You don't need to be silent between tool calls — short thinking-out-loud is fi# Scope-Your job is to answer analytical questions by producing visualizations. For other needs:+{% if in_host_app %}Your job is to answer analytical questions by producing visualizations with the notebook query tool. You are running inside the user's own application: there is no SQL editor, dashboard builder, or search page here for you to open or hand off to.++**Never write SQL.** Not as a draft, not as a snippet to paste somewhere, not "for reference", and not because the user asked for SQL or for something a notebook query can't express. When a request can't be expressed as a notebook query (set operations like UNION, engine-specific functions, or SQL the user hands you to run as-is), say plainly that it isn't something you can do here, and offer the closest version you can build. Likewise, don't offer to build a new dashboard or to act as a search box over the user's saved content — explain that's outside what you can do in this view. You can still save a chart you built into an existing dashboard, and still start from a saved question, model, or metric as the data source.{% else %}Your job is to answer analytical questions by producing visualizations. For other needs:- Dashboards: direct the user to the dashboard builder.- SQL queries: direct the user to the SQL editor.-- Finding existing saved content: direct the user to search/browse.+- Finding existing saved content: direct the user to search/browse.{% endif %}{% include "metabot/prompts/shared/skills.selmer" %}diff --git a/resources/metabot/prompts/system/internal.selmer b/resources/metabot/prompts/system/internal.selmerindex af224721ded..281e09883e7 100644--- a/resources/metabot/prompts/system/internal.selmer+++ b/resources/metabot/prompts/system/internal.selmer@@ -19,7 +19,7 @@ A single objective: **the query you build should return the data the user asked{% endif %}{% if has_sql_generation %}# Writing SQL-Metabase is read-only: your SQL is always a `SELECT` (CTEs/`WITH` are fine for transforms; never `CREATE`, `INSERT`, `UPDATE`, `DELETE`, `ALTER`, `DROP`, `TRUNCATE`). Deliver SQL through the SQL tools rather than pasting it into chat — the tools place it in the editor for the user. Verify the format of any literal you filter or branch on before writing it (see grounding above). The full SQL contract — model reference syntax, fully-qualified table names — is in the SQL skills (load them via `load_skill`).{% if sql_dialect_loaded %} When the user is in the SQL editor, dialect-specific instructions for **{{ sql_dialect }}** have already been loaded into this conversation — follow them.{% endif %}+Metabase is read-only: your SQL is always a `SELECT` (CTEs/`WITH` are fine for transforms; never `CREATE`, `INSERT`, `UPDATE`, `DELETE`, `ALTER`, `DROP`, `TRUNCATE`). Deliver SQL through the SQL tools rather than pasting it into chat — the tools place it in the editor for the user. Verify the format of any literal you filter or branch on before writing it (see grounding above). The full SQL contract — model reference syntax, fully-qualified table names — is in the SQL skills (load them via `load_skill`). When writing raw SQL there's no equivalent of the metric, measure, or segment clauses, so query the underlying table or an existing model that already encodes the same logic instead.{% if sql_dialect_loaded %} When the user is in the SQL editor, dialect-specific instructions for **{{ sql_dialect }}** have already been loaded into this conversation — follow them.{% endif %}{% endif %}{% else %}# Discovery onlydiff --git a/resources/metabot/skills/read-resource.md b/resources/metabot/skills/read-resource.mdindex 15d9f386842..d863499de47 100644--- a/resources/metabot/skills/read-resource.md+++ b/resources/metabot/skills/read-resource.md@@ -54,13 +54,13 @@ You can request multiple resources in one call by providing a list of URIs (max- `metabase://database/{id}/schemas/{schemaName}/tables` — tables in a specific schema**Examples:**-- Want to see warehouse layout before writing SQL? → `metabase://database/2/schemas` then `metabase://database/2/schemas/public/tables`+- Want to see warehouse layout before building a query? → `metabase://database/2/schemas` then `metabase://database/2/schemas/public/tables`- Database without schemas, like the Sample Database (its `/schemas` list is empty)? → `metabase://database/1/tables`- Want curated models in a specific warehouse? → `metabase://database/1/models`**Best Practices:**- For a high-cardinality database, prefer schema → tables drill-down over fetching every table at once.-- In the SQL editor, `search` already scopes to the current database via its own `database_id` argument — no need to filter further. Elsewhere, `search` has no per-database filter; narrow with `entity_types` and topic terms instead.+- When `search` takes a `database_id` argument, it already scopes to the current database — no need to filter further. Elsewhere, `search` has no per-database filter; narrow with `entity_types` and topic terms instead.## Collection resources@@ -88,7 +88,7 @@ You can request multiple resources in one call by providing a list of URIs (max- "What's already built on this table?" before suggesting a new query → `metabase://table/123/derived`**Best Practices:**-- Before recommending raw-table SQL, check `/derived` — there may be a curated model or saved question that already answers the user's need.+- Before building on a raw table, check `/derived` — there may be a curated model or saved question that already answers the user's need.## Model resourcesdiff --git a/src/metabase/metabot/agent/core.clj b/src/metabase/metabot/agent/core.cljindex 8edb6b7dfdb..7e8afbc22fc 100644--- a/src/metabase/metabot/agent/core.clj+++ b/src/metabase/metabot/agent/core.clj@@ -300,9 +300,9 @@Rebuilding the history fetches the viewing context again and inverts links against a registry that grows withinthe turn, and Claude Opus, Sonnet and Haiku 5.5 and Fable 5.1 reject a replayed thinking block once anythingbefore it has changed."- [sent-parts context memory link-registry]+ [sent-parts context memory tools link-registry](into sent-parts- (invert-links (subvec (messages/build-message-history context memory) (count sent-parts))+ (invert-links (subvec (messages/build-message-history context memory tools) (count sent-parts))link-registry)))(defn- call-llm@@ -640,7 +640,7 @@memory @memory-atomparts-atom (atom [])link-registry-atom (atom (get-in memory [:state :link-registry] {}))- input-parts (turn-input-parts sent-parts context memory @link-registry-atom)+ input-parts (turn-input-parts sent-parts context memory tools @link-registry-atom)xf (comp (accumulate-usage-xf usage-atom (:model profile))(u/tee-xf parts-atom));; We use `reduce` instead of `transduce` because rf is the outer reducingdiff --git a/src/metabase/metabot/agent/messages.clj b/src/metabase/metabot/agent/messages.cljindex eb0bce44b30..9b9bf8dcc99 100644--- a/src/metabase/metabot/agent/messages.clj+++ b/src/metabase/metabot/agent/messages.clj@@ -169,24 +169,34 @@- `{:type :tool-input, :id ..., :function ..., :arguments ...}` for tool calls- `{:type :tool-output, :id ..., :result ...}` for tool results+ `tools` is the active tool registry (name -> tool). The SQL dialect skill is preloaded only when it+ contains a SQL-writing tool: the dialect body is SQL-writing guidance, and a profile without those+ tools (e.g. `:embedding_next` with the native editor open in a full-app embed) has no tool that could+ act on it, and its prompt makes no SQL promise the preload would have to back. The 2-arity has no+ tools and never preloads.+Each LLM adapter converts this to its own wire format."- [context memory]- (let [input-messages (messages-with-injected-context context memory)- steps (memory/get-steps memory)- input-parts (mapcat input-message->parts input-messages)- step-parts (mapcat step->parts steps)- ;; Preload the active SQL dialect (if any) as a synthetic load_skill- ;; tool-call/result pair. It is placed after the input messages (so the- ;; first message is still the user's) and before this turn's steps, which- ;; keeps it below the system cache breakpoint.- preload-parts (skills/dialect-preload-parts (user-context/extract-sql-dialect context))- result (vec (concat input-parts preload-parts step-parts))]- (log/info "Building message history"- {:input-message-count (count input-messages)- :step-count (count steps)- :preload-parts (count preload-parts)- :total-parts (count result)})- result))+ ([context memory]+ (build-message-history context memory nil))+ ([context memory tools]+ (let [input-messages (messages-with-injected-context context memory)+ steps (memory/get-steps memory)+ input-parts (mapcat input-message->parts input-messages)+ step-parts (mapcat step->parts steps)+ ;; Preload the active SQL dialect (if any) as a synthetic load_skill+ ;; tool-call/result pair. It is placed after the input messages (so the+ ;; first message is still the user's) and before this turn's steps, which+ ;; keeps it below the system cache breakpoint.+ preload-parts (if (prompts/sql-generation-tools? tools)+ (skills/dialect-preload-parts (user-context/extract-sql-dialect context))+ [])+ result (vec (concat input-parts preload-parts step-parts))]+ (log/info "Building message history"+ {:input-message-count (count input-messages)+ :step-count (count steps)+ :preload-parts (count preload-parts)+ :total-parts (count result)})+ result)));;; ──────────────────────────────────────────────────────────────────;;; System messagediff --git a/src/metabase/metabot/agent/profiles.clj b/src/metabase/metabot/agent/profiles.cljindex 42d08b2fd6d..c0491b15e5a 100644--- a/src/metabase/metabot/agent/profiles.clj+++ b/src/metabase/metabot/agent/profiles.clj@@ -115,6 +115,17 @@{:profile (:name profile) :unknown-terminal-tools unknown}))))(swap! *profiles assoc (:name profile) profile))+(defn- embedding-system-prompt-context+ "Template vars for `embedding-next.selmer`. `in_host_app` is set by the API from the request's client+ header (see [[metabase.metabot.context/host-app-request?]]): true for the SDK, modular embedding and+ data apps, where no Metabase pages exist to hand off to; false for a full-app iframe embed, which+ keeps the hand-off to the SQL editor, dashboard builder and search."+ [context]+ {:in_host_app (boolean (:in_host_app context))})++;; Serves every embedded surface — the SDK `MetabotQuestion`, modular embedding, data apps, and full-app+;; iframe embeds — and has no SQL tools in any of them. The prompt decides per request whether there is+;; a Metabase UI around it to hand off to (see [[embedding-system-prompt-context]]).;; TODO (Chris 2026-10-14) -- Offer run_query here once embedded Metabot has its own query execution setting.;; Queries run as the signed-in user, so sandboxing and impersonation apply,;; but the rows are the embedding customer's end users' data, and they go to the LLM provider.@@ -123,6 +134,7 @@{:name :embedding_next:prompt-template "embedding-next.selmer":max-iterations 15+ :system-prompt-context #'embedding-system-prompt-context:tools [#'tools/nlq-search-tool#'tools/read-resource-tool#'tools/construct-notebook-query-tooldiff --git a/src/metabase/metabot/agent/prompts.clj b/src/metabase/metabot/agent/prompts.cljindex b118ffed36f..0e1e89ad239 100644--- a/src/metabase/metabot/agent/prompts.clj+++ b/src/metabase/metabot/agent/prompts.clj@@ -20,13 +20,20 @@;; Kept local rather than required from metabase.metabot.tools to avoid a prompts->tools cycle;;; mirrors the SQL entries in metabase.metabot.tools/query-generation-tool-names.-(def ^:private sql-generation-tool-names+(def sql-generation-tool-names"SQL-writing tools.Their presence in the capability-filtered tool set — not the `:permission/metabot-sql-generation`permission alone — is what lets the model write SQL, since they're gated by the`permission:write_sql_queries` capability."#{"create_sql_query" "edit_sql_query" "replace_sql_query"})+(defn sql-generation-tools?+ "True when the active tool registry `tools` (name -> tool) contains a SQL-writing tool. The prompt's+ SQL guidance and the message stream's SQL dialect preload both gate on this, so a profile that cannot+ write SQL is never told how to."+ [tools]+ (boolean (some sql-generation-tool-names (keys tools))))+;;; Template Loading(defn- load-resource@@ -160,7 +167,7 @@;; on those tools actually being active — the permission can be `:yes` while the request;; lacks the `permission:write_sql_queries` capability that registers them.has-sql? (and (= :yes (:permission/metabot-sql-generation perms))- (boolean (some sql-generation-tool-names (keys tools))))+ (sql-generation-tools? tools))has-nlq? (= :yes (:permission/metabot-nlq perms));; The NLQ permission does not by itself give the model the notebook builder (:internal-sql omits;; it), so guidance that names the builder needs the tool too, as the SQL guidance does.@@ -170,7 +177,11 @@(scope/sql-execution-allowed?))template-context {:metabot_name (metabot.settings/metabot-name):sql_dialect sql-dialect- :sql_dialect_loaded (some? (skills/dialect-skill sql-dialect))+ ;; Must agree with the preload gate in `messages/build-message-history`: the+ ;; template says the dialect skill "has already been loaded", which is only+ ;; true when a SQL-writing tool is active.+ :sql_dialect_loaded (and (sql-generation-tools? tools)+ (some? (skills/dialect-skill sql-dialect)));; `not-empty` so an empty catalog is nil (falsy) — Selmer treats;; an empty vector as truthy, which would render the "# Available;; skills … load the skill(s) you need" header with nothing todiff --git a/src/metabase/metabot/agent/user_context.clj b/src/metabase/metabot/agent/user_context.cljindex fa9af7df856..34465cdf12e 100644--- a/src/metabase/metabot/agent/user_context.clj+++ b/src/metabase/metabot/agent/user_context.clj@@ -202,11 +202,15 @@:query-str (metabot.u/extract-sql-content query)})(defn- format-native-query- "Format viewing `item`"+ "Format viewing `item`. In a host app (`:in_host_app`, stamped on the item by+ [[format-viewing-context]]) there is no SQL editor, so the item is described as a query the user is+ looking at rather than an editor they are in."[item](let [{:keys [database-id query-str]} (native-query-details (:query item))](te/lines- "The user is currently in the SQL editor."+ (if (:in_host_app item)+ "The user is currently looking at a SQL query."+ "The user is currently in the SQL editor.")(when (:id item)(te/field "Query ID" (:id item)))(te/field "Current SQL query" (te/code query-str "sql"))@@ -292,8 +296,8 @@"Format user's current viewing context.Handles different context types:- - adhoc: Notebook query editor- - native: SQL editor with schema context+ - adhoc: Notebook query editor, or the SQL editor when the query is native (described as a query the+ user is looking at when the context carries the server-set `:in_host_app`)- code_editor: Code editor buffers with cursor position- table/model/question/metric/dashboard: Entity details@@ -302,7 +306,9 @@(str/join "\n\n"(for [item (:user_is_viewing context)](try- (format-entity item)+ ;; The server-decided host-app flag travels with each item so native items can be+ ;; described without naming an editor that does not exist there.+ (format-entity (cond-> item (:in_host_app context) (assoc :in_host_app true)))(catch Exception e(log/error "Error formatting viewing context item:" (:type item) (ex-message e))"")))))diff --git a/src/metabase/metabot/api.clj b/src/metabase/metabot/api.cljindex 7f5b81cd4ab..1340198e25f 100644--- a/src/metabase/metabot/api.clj+++ b/src/metabase/metabot/api.clj@@ -202,8 +202,12 @@it seeds the agent loop as the immutable baseline for this turn's state."[{:keys [metabot profile-id message context history conversation-id state debug?eval-session-id assistant-msg-id external-id user-external-id title-job]}]- (let [enriched-context (metabot.context/create-context context {:metabot metabot- :profile-id (keyword profile-id)})+ (let [enriched-context (metabot.context/create-context+ ;; Server-authoritative: decided from the request's client header here, on the+ ;; handler thread, before the agent moves to the streaming thread.+ (assoc context :in_host_app (metabot.context/host-app-request? (request/current-request)))+ {:metabot metabot+ :profile-id (keyword profile-id)})messages (concat history [message])];; a reasoning model can spend longer than MB_JETTY_ASYNC_RESPONSE_TIMEOUT on one turn(sr/streaming-response {:content-type "text/event-stream"diff --git a/src/metabase/metabot/context.clj b/src/metabase/metabot/context.cljindex 2d6945c98f7..cc7ab1662f8 100644--- a/src/metabase/metabot/context.clj+++ b/src/metabase/metabot/context.clj@@ -5,6 +5,7 @@[metabase.activity-feed.core :as activity-feed][metabase.api.common :as api][metabase.config.core :as config]+ [metabase.embedding.util :as embedding.util][metabase.lib-be.core :as lib-be][metabase.lib-be.schema :as lib-be.schema][metabase.lib.core :as lib]@@ -264,7 +265,23 @@[:default_database_id {:optional true} [:maybe :int]][:code_editor {:optional true} [:maybe CodeEditorContextSchema]][:research_plan {:optional true} [:maybe ::research-plan]]- [:references {:optional true} [:maybe ms/OpaqueJSONObject]]])+ [:references {:optional true} [:maybe ms/OpaqueJSONObject]]+ ;; The agent-streaming API overwrites this from the request's client header (see [[host-app-request?]]),+ ;; so a value sent by the client has no effect.+ [:in_host_app {:optional true} [:maybe :boolean]]])++(defn host-app-request?+ "True when `request` comes from a surface that renders Metabot inside the customer's own application —+ the React SDK, modular embedding, or a data app — so none of Metabase's own pages (SQL editor,+ dashboard builder, search) surround it. A full-app iframe embed is *not* a host app: it carries the+ `embedding-iframe-full-app` client header and shows the whole Metabase UI. (A data-app session is+ confined to the `data-apps:base` scope and `/agent-streaming` declares no scope, so today it gets a 403+ before this runs; the branch is here so the rule stays true if that changes. `mcp-apps` has no Metabot+ today; if it gets one it belongs on this list, since an MCP client shows no Metabase UI either.)"+ [request]+ (boolean (and request+ (or (embedding.util/is-modular-embedding-request? request)+ (embedding.util/has-data-app-header? request)))))(defn- query-for-sql-parsing"Return the native query in a viewing-context item, or nil."diff --git a/src/metabase/metabot/skills.clj b/src/metabase/metabot/skills.cljindex a673bb9c209..e57c9d67406 100644--- a/src/metabase/metabot/skills.clj+++ b/src/metabase/metabot/skills.clj@@ -305,7 +305,9 @@databases.Returns [] when `engine` is nil or has no matching dialect skill.- Dialect context only arises in SQL-editor sessions, so its presence is itself the gate.+ Dialect context arises in SQL-editor sessions, but the editor can be open under a profile without+ SQL tools (a full-app embed's Metabot sidebar), so the caller+ ([[metabase.metabot.agent.messages/build-message-history]]) also gates on the active tools.Invariant: the emitted pair references the `load_skill` tool, which[[metabase.metabot.agent.profiles/get-tools-for-profile]] registers whenever the skill manifest isdiff --git a/test/metabase/metabot/agent/messages_test.clj b/test/metabase/metabot/agent/messages_test.cljindex ed82ecfc280..ae490222f07 100644--- a/test/metabase/metabot/agent/messages_test.clj+++ b/test/metabase/metabot/agent/messages_test.clj@@ -2,11 +2,14 @@(:require[clojure.string :as str][clojure.test :refer :all]+ [metabase.api-scope.core :as api-scope][metabase.lib.core :as lib][metabase.metabot.agent.memory :as memory][metabase.metabot.agent.messages :as messages]+ [metabase.metabot.agent.profiles :as profiles][metabase.metabot.agent.user-context :as user-context][metabase.metabot.persistence :as metabot.persistence]+ [metabase.metabot.scope :as scope][metabase.metabot.self.openai.chat-completions :as chat-completions][metabase.test :as mt]))@@ -364,3 +367,52 @@context(memory/initialize [{:role :user :content "Hello"}] {}))(is (= 1 @calls))))))++(deftest ^:parallel build-message-history-dialect-preload-gates-on-sql-tools-test+ (let [context {:user_is_viewing [{:type "adhoc"+ :sql_engine "postgres"+ :query {:type "native" :database 1 :native {:query "SELECT 1"}}}]}+ memory (memory/initialize [{:role :user :content "Hello"}] {})+ preload? (fn [parts]+ (boolean (some #(and (= :tool-input (:type %)) (= "load_skill" (:function %))) parts)))]+ (testing "a profile with a SQL-writing tool gets the dialect skill preloaded"+ (is (preload? (messages/build-message-history context memory {"create_sql_query" nil}))))+ (testing "a profile without SQL tools does not, even with the native editor open"+ (is (not (preload? (messages/build-message-history context memory {"construct_notebook_query" nil})))))+ (testing "the 2-arity has no tools and never preloads"+ (is (not (preload? (messages/build-message-history context memory)))))))++(deftest ^:parallel host-app-native-viewing-context-does-not-claim-sql-editor-test+ (testing "the host-app system prompt says there is no SQL editor; the injected user context must not say the user is in one"+ (let [context {:in_host_app true+ :user_is_viewing [{:type "adhoc"+ :sql_engine "postgres"+ :query {:type "native" :database 1 :native {:query "SELECT 1"}}}]}+ profile (profiles/get-profile :embedding_next)+ system (binding [scope/*current-user-scope* api-scope/unrestricted]+ (:content (messages/build-system-message context profile+ (profiles/profile->tools profile []))))+ user (->> (messages/build-message-history context+ (memory/initialize [{:role :user :content "Hi"}] {})+ {"construct_notebook_query" nil})+ (filter #(= :user (:role %))) last :content)]+ (is (str/includes? system "there is no SQL editor") "premise")+ (is (not (str/includes? user "The user is currently in the SQL editor"))))))++(deftest ^:parallel sql-profile-dialect-claim-matches-preload-test+ (testing "sql-querying-only.selmer claims the dialect skill 'has already been loaded'; that claim and the preload must agree now that the preload gates on SQL tools"+ (binding [scope/*current-user-scope* api-scope/unrestricted]+ (let [profile (profiles/get-profile :sql)+ context {:user_is_viewing [{:type "adhoc"+ :sql_engine "postgres"+ :query {:type "native" :database 1 :native {:query "SELECT 1"}}}]}+ memory (memory/initialize [{:role :user :content "Hi"}] {})]+ (doseq [[label caps] {"with write_sql_queries" ["permission:write_sql_queries"]+ "without it" []}]+ (testing label+ (let [tools (profiles/profile->tools profile caps)+ system (:content (messages/build-system-message (assoc context :capabilities caps) profile tools))+ parts (messages/build-message-history context memory tools)+ claims? (str/includes? system "have already been loaded into this conversation")+ preloaded? (boolean (some #(= "load_skill" (:function %)) parts))]+ (is (= claims? preloaded?) (pr-str {:claims? claims? :preloaded? preloaded?})))))))))diff --git a/test/metabase/metabot/agent/prompts_test.clj b/test/metabase/metabot/agent/prompts_test.cljindex f86a89eb4b8..f7949658bfe 100644--- a/test/metabase/metabot/agent/prompts_test.clj+++ b/test/metabase/metabot/agent/prompts_test.clj@@ -6,6 +6,7 @@[metabase.agent-api.api][metabase.api-scope.core :as api-scope][metabase.api.macros :as api.macros]+ [metabase.metabot.agent.messages :as messages][metabase.metabot.agent.profiles :as profiles][metabase.metabot.agent.prompts :as prompts][metabase.metabot.scope :as scope]@@ -207,6 +208,54 @@:construct-notebook-query-operators]](is (str/includes? content (:description (skills/get-skill skill-id)))))))))+;;; Embedded profile (BOT-1891)+;;;+;;; The embedded profile has no SQL tools, so everything it says about SQL is prose in the prompt.+;;; These tests render through [[messages/build-system-message]] so the profile's+;;; `:system-prompt-context` hook, which maps the request's `:in_host_app` onto the template, is+;;; exercised too.++(defn- embedded-prompt+ [context]+ (binding [scope/*current-user-scope* api-scope/unrestricted]+ (let [profile (profiles/get-profile :embedding_next)]+ (:content (messages/build-system-message context profile (profiles/profile->tools profile []))))))++(deftest ^:parallel embedding-profile-has-no-sql-tools-test+ (testing "premise of the prompt rules below: no surface gives this profile a SQL-writing tool"+ (binding [scope/*current-user-scope* api-scope/unrestricted]+ (let [tools (profiles/profile->tools (profiles/get-profile :embedding_next) [])]+ (is (empty? (filter prompts/sql-generation-tool-names (keys tools))))))))++(deftest ^:parallel embedding-prompt-in-host-app-test+ (testing "SDK, modular embedding, data app: no Metabase pages exist, so no hand-off and no SQL"+ (let [content (embedded-prompt {:in_host_app true})]+ (is (str/includes? content "Never write SQL"))+ (is (not (str/includes? content "direct the user to the SQL editor")))+ (is (not (str/includes? content "direct the user to the dashboard builder")))+ (is (not (str/includes? content "When writing raw SQL"))+ "the shared data-sources snippet must not presuppose SQL writing here"))))++(deftest ^:parallel embedding-prompt-in-full-app-embed-test+ (testing "full-app iframe embed: the SQL editor, dashboard builder and search exist, so the hand-off stays"+ (doseq [context [{} {:in_host_app false}]]+ (let [content (embedded-prompt context)]+ (is (str/includes? content "direct the user to the SQL editor") (pr-str context))+ (is (str/includes? content "direct the user to the dashboard builder") (pr-str context))+ (is (not (str/includes? content "Never write SQL")) (pr-str context))+ (is (not (str/includes? content "When writing raw SQL"))+ (str "no SQL tools in this surface either: " (pr-str context)))))))++(deftest ^:parallel data-sources-raw-sql-sentence-gates-on-sql-tools-test+ (testing "the raw-SQL aside (now in the templates, not the directive-free shared snippet) renders only when SQL tools are active"+ (binding [scope/*current-user-metabot-permissions* {:permission/metabot-sql-generation :yes+ :permission/metabot-nlq :yes+ :permission/metabot-other-tools :yes}]+ (let [render (fn [tools]+ (prompts/build-system-message-content {:prompt-template "internal.selmer"} {} tools []))]+ (is (str/includes? (render {"create_sql_query" nil}) "When writing raw SQL"))+ (is (not (str/includes? (render {"construct_notebook_query" nil}) "When writing raw SQL")))))))+(deftest ^:parallel build-system-message-content-test-9(testing "renders sql querying template with literal model syntax"(let [profile {:prompt-template "sql-querying-only.selmer"}@@ -224,3 +273,37 @@(is (not (str/includes? content "{%raw%}")))(is (not (str/includes? content "{% safe %}")))(is (not (str/includes? content "verbatim"))))))++(deftest ^:parallel embedding-loadable-skills-do-not-presuppose-sql-test+ (testing "every skill the embedded profile can load is free of SQL-writing guidance, since it has no SQL tools"+ (binding [scope/*current-user-scope* api-scope/unrestricted]+ (let [profile (profiles/get-profile :embedding_next)+ tools (profiles/profile->tools profile [])+ {:keys [catalog always-on]} (skills/build-skill-manifest profile (keys tools) [])+ ids (concat (map (comp keyword :id) catalog) (map :id always-on))]+ (is (some #{:read-resource} ids) "premise: read-resource is loadable here")+ (doseq [id ids]+ (testing id+ (is (not (re-find #"(?i)before writing SQL|recommending raw-table SQL"+ (:body (skills/get-skill id)))))))))))++(deftest ^:parallel embedding-prompt-full-app-scope-text-unchanged-test+ (testing "full-app embed: the Scope section is byte-identical to the pre-BOT-1891 text (no blank lines left by the Selmer tags)"+ (let [content (embedded-prompt {})]+ (is (str/includes? content+ (str "# Scope\n\n"+ "Your job is to answer analytical questions by producing visualizations. For other needs:\n\n"+ "- Dashboards: direct the user to the dashboard builder.\n"+ "- SQL queries: direct the user to the SQL editor.\n"+ "- Finding existing saved content: direct the user to search/browse.\n\n")))+ (is (not (str/includes? content "search/browse.\n\n\n\n"))+ "the {% endif %} must not add a blank line after the hand-off"))))++(deftest ^:parallel raw-sql-aside-in-internal-sql-section-test+ (testing "the raw-SQL aside left the directive-free shared snippet, so internal.selmer carries it in its SQL section"+ (binding [scope/*current-user-metabot-permissions* {:permission/metabot-sql-generation :yes+ :permission/metabot-nlq :yes+ :permission/metabot-other-tools :yes}]+ (is (str/includes? (prompts/build-system-message-content {:prompt-template "internal.selmer"} {}+ {"create_sql_query" nil} [])+ "When writing raw SQL")))))diff --git a/test/metabase/metabot/api_test.clj b/test/metabase/metabot/api_test.cljindex a210cac603d..e5a508271c6 100644--- a/test/metabase/metabot/api_test.clj+++ b/test/metabase/metabot/api_test.clj@@ -1779,3 +1779,57 @@:context {}:conversation_id (str (random-uuid)):state {}}))))++(defn- llm-request-for!+ "The last LLM request of one `metabot/agent-streaming` turn for `profile-id`, sent with `headers` and `context`."+ [profile-id headers context]+ (let [requests (atom [])]+ (with-captured-llm-requests!+ requests "ok"+ (fn []+ (mt/user-http-request :rasta :post 202 "metabot/agent-streaming"+ {:request-options {:headers headers}}+ {:message "show me orders as SQL"+ :context context+ :conversation_id (str (random-uuid))+ :profile_id profile-id+ :state {}})))+ (last @requests)))++(defn- embedded-system-prompt-for!+ "The system prompt the LLM receives for an `embedding_next` turn sent with `headers` and `context`."+ [headers context]+ (:system (llm-request-for! "embedding_next" headers context)))++(deftest embedding-host-app-header-reaches-prompt-test+ (testing "SDK header: host-app Scope text, no hand-off"+ (let [s (embedded-system-prompt-for! {"x-metabase-client" "embedding-sdk-react"} {})]+ (is (str/includes? s "Never write SQL"))+ (is (not (str/includes? s "direct the user to the SQL editor")))))+ (testing "modular embedding header: host-app Scope text"+ (is (str/includes? (embedded-system-prompt-for! {"x-metabase-client" "embedding-simple"} {})+ "Never write SQL")))+ (testing "full-app iframe header: the hand-off stays"+ (is (str/includes? (embedded-system-prompt-for! {"x-metabase-client" "embedding-iframe-full-app"} {})+ "direct the user to the SQL editor")))+ (testing "a client-sent in_host_app is overridden by the server in both directions"+ (is (str/includes? (embedded-system-prompt-for! {} {:in_host_app true})+ "direct the user to the SQL editor"))+ (is (str/includes? (embedded-system-prompt-for! {"x-metabase-client" "embedding-sdk-react"} {:in_host_app false})+ "Never write SQL"))))++(deftest dialect-preload-gates-on-sql-tools-through-the-loop-test+ (testing "the loop hands its tools to the history builder, so the dialect skill is preloaded only where a tool can write SQL"+ (let [native-item {:type "adhoc"+ :sql_engine "postgres"+ :query {:database (mt/id) :type "native" :native {:query "SELECT 1"}}}+ preloaded? (fn [request]+ (boolean (some #(and (= :tool-input (:type %)) (= "load_skill" (:function %)))+ (:input request))))]+ (testing "the SQL profile with the write_sql_queries capability gets the preload"+ (is (preloaded? (llm-request-for! "sql" {} {:user_is_viewing [native-item]+ :capabilities ["permission:write_sql_queries"]}))))+ (testing "the embedded profile with the same native item, as a full-app embed, does not"+ (is (not (preloaded? (llm-request-for! "embedding_next"+ {"x-metabase-client" "embedding-iframe-full-app"}+ {:user_is_viewing [native-item]}))))))))diff --git a/test/metabase/metabot/context_test.clj b/test/metabase/metabot/context_test.cljindex 29b4c8d1df5..3ed4b417ebc 100644--- a/test/metabase/metabot/context_test.clj+++ b/test/metabase/metabot/context_test.clj@@ -325,3 +325,17 @@(mt/with-dynamic-fn-redefs [curation/curated-ids (constantly #{["card" 1] ["table" 2]})](is (= [{:model :card :id 1} {:model :table :id 2}](#'context/filter-recents-to-curated recents)))))))++(deftest ^:parallel host-app-request?-test+ (testing "the client header decides whether Metabase's own pages surround Metabot"+ (doseq [[client expected] {"embedding-sdk-react" true+ "embedding-simple" true+ "data-app" true+ "embedding-iframe-full-app" false+ "embedding-iframe-static" false+ nil false}]+ (testing (pr-str client)+ (is (= expected+ (context/host-app-request? {:headers (cond-> {} client (assoc "x-metabase-client" client))}))))))+ (testing "no request bound, e.g. a caller outside an HTTP handler"+ (is (false? (context/host-app-request? nil)))))diff --git a/test/metabase/metabot/tools/resources_test.clj b/test/metabase/metabot/tools/resources_test.cljindex 75680390950..3d471889ac8 100644--- a/test/metabase/metabot/tools/resources_test.clj+++ b/test/metabase/metabot/tools/resources_test.clj@@ -1687,3 +1687,10 @@(is (str/includes? output "VISIBLE-DOC"))(is (not (str/includes? output "SUMMARY-DOC"))"a Summary document is reachable only through its exploration, so it must not be listed"))))))++(deftest read-resource-table-output-does-not-presuppose-sql-test+ (testing "read_resource on ORDERS (FKs to PEOPLE and PRODUCTS) as the embedded profile would call it"+ (mt/with-test-user :crowberto+ (let [output (:output (read-uris {:uris [(str "metabase://table/" (mt/id :orders))]}))]+ (is (str/includes? output "### Related Tables") "premise: ORDERS renders related tables")+ (is (not (re-find #"(?i)for SQL queries" output)))))))diff --git a/test/metabase/metabot/tools/shared/llm_shape_test.clj b/test/metabase/metabot/tools/shared/llm_shape_test.cljindex 60a0110c588..4622b028cbe 100644--- a/test/metabase/metabot/tools/shared/llm_shape_test.clj+++ b/test/metabase/metabot/tools/shared/llm_shape_test.clj@@ -1031,3 +1031,17 @@(is (str/includes? xml "<query>\n```json"))(is (str/includes? xml "```\n</query>"))(is (str/includes? xml "\"PRODUCTS\"")))))++(deftest ^:parallel related-tables-note-does-not-presuppose-sql-test+ (testing "table/model XML reaches profiles without SQL tools (read_resource, viewing context), so the related-tables usage note carries no SQL-writing guidance (BOT-1891)"+ (let [related [{:id 20 :name "orders" :database_schema "public"+ :related_by {:id 91 :name "user_id"} :fields []}]]+ (doseq [[label xml] {"table" (llm-shape/table->xml {:id 10 :name "users" :database_id 1+ :database_engine "postgres"+ :related_tables related})+ "model" (llm-shape/model->xml {:id 5 :name "Sales Model" :database_id 1+ :database_engine "postgres"+ :related_tables related})}]+ (testing label+ (is (str/includes? xml "Foreign key fields from related tables") "premise: the section renders")+ (is (not (re-find #"(?i)for SQL queries" xml))))))))