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
Remove unused /api/llm/generate-sql endpoint (#82380)
Maksym Yakubych670c7c3555f6
diff --git a/.clj-kondo/config/modules/config.edn b/.clj-kondo/config/modules/config.ednindex 009e24be8c3..6f3c40dcf34 100644--- a/.clj-kondo/config/modules/config.edn+++ b/.clj-kondo/config/modules/config.edn@@ -1554,16 +1554,13 @@metabase.llm.providermetabase.llm.settingsmetabase.llm.startup}- :uses #{analytics- api- driver+ :uses #{apiliblib.belib.metadatalib.schemametabotmodels- parameterspermissionspremium-featuresrequest@@ -1571,11 +1568,9 @@setupsql-toolsstartup- syncutilutil.config- warehouse-schema-overlay- warehouses.schema}+ warehouse-schema-overlay}:model-imports #{:model/Card:model/Database:model/Fielddiff --git a/enterprise/backend/test/metabase_enterprise/impersonation/llm_context_test.clj b/enterprise/backend/test/metabase_enterprise/impersonation/llm_context_test.cljdeleted file mode 100644index bbc5bd798fb..00000000000--- a/enterprise/backend/test/metabase_enterprise/impersonation/llm_context_test.clj+++ /dev/null@@ -1,99 +0,0 @@-(ns metabase-enterprise.impersonation.llm-context-test- "Tests that the LLM schema context respects connection impersonation when it fetches field values."- (:require- [clojure.string :as str]- [clojure.test :refer :all]- [metabase-enterprise.impersonation.util-test :as impersonation.util-test]- [metabase.api.common :as api]- [metabase.llm.context :as llm.context]- [metabase.sync.core :as sync]- [metabase.test :as mt]- [toucan2.core :as t2]))--(set! *warn-on-reflection* true)--(defn- do-with-full-field-values!- "Sets the full (unrestricted) FieldValues of `field-id` to `values` for the duration of `thunk`.- Restores whatever sync left behind, and deletes any per-role FieldValues the body created."- [field-id values thunk]- (let [existing (t2/select-one :model/FieldValues :field_id field-id :type :full)]- (try- (if existing- (t2/update! :model/FieldValues (:id existing) {:values values, :last_used_at :%now})- (t2/insert! :model/FieldValues {:field_id field-id, :type :full, :values values, :last_used_at :%now}))- (thunk)- (finally- (t2/delete! :model/FieldValues :field_id field-id :type :advanced)- (if existing- (t2/update! :model/FieldValues (:id existing) (select-keys existing [:values :last_used_at]))- (t2/delete! :model/FieldValues :field_id field-id :type :full))))))--(defn- column-comment- "Returns the DDL comment line `ddl` carries for `col-name`, or nil if there isn't one."- [ddl col-name]- (->> (str/split-lines ddl)- (partition 2 1)- (some (fn [[comment-line col-line]]- (when (and (str/includes? col-line (str " " col-name " "))- (str/starts-with? (str/triml comment-line) "--"))- comment-line)))))--(deftest schema-context-field-values-respect-impersonation-test- (testing "sample values in the LLM schema context come from the impersonated role, not the unrestricted cache"- (mt/with-premium-features #{:advanced-permissions}- (let [field-id (mt/id :venues :price)]- (mt/with-temp-vals-in-db :model/Field field-id {:has_field_values :list}- ;; Stand in for values sync cached under the unrestricted default role. These sentinels cannot come- ;; back from a query against the test warehouse, so seeing them in the DDL means the unrestricted- ;; cache was handed to the LLM verbatim.- (do-with-full-field-values!- field-id [-11 -22 -33]- (fn []- (impersonation.util-test/with-impersonations!- {:impersonations [{:db-id (mt/id) :attribute "impersonation_attr"}]- :attributes {"impersonation_attr" "impersonation_role"}}- (let [{:keys [ddl]} (llm.context/build-schema-context (mt/id) #{(mt/id :venues)})- comment (column-comment ddl "PRICE")]- (is (some? comment)- "the price column gets a DDL comment with sample values")- (is (not (str/includes? (str comment) "-11"))- "values cached for the unrestricted role are not sent to the LLM")- (is (t2/exists? :model/FieldValues :field_id field-id :type :advanced)- "values are fetched and cached per impersonation role instead"))))))))))--(deftest schema-context-omits-fingerprints-for-impersonated-users-test- (testing "fingerprint statistics describe every row, so an impersonated user gets none of them"- (mt/with-premium-features #{:advanced-permissions}- (impersonation.util-test/with-impersonations!- {:impersonations [{:db-id (mt/id) :attribute "impersonation_attr"}]- :attributes {"impersonation_attr" "impersonation_role"}}- (let [{:keys [ddl]} (llm.context/build-schema-context (mt/id) #{(mt/id :venues)})]- (is (str/includes? ddl "CREATE TABLE")- "the table itself is still described")- (is (not (str/includes? ddl "range: "))- "no numeric ranges from the unrestricted fingerprint")- (is (not (str/includes? ddl "distinct: "))- "no distinct counts from the unrestricted fingerprint"))))))--(deftest schema-context-skips-on-demand-fingerprinting-for-impersonated-users-test- (testing "an impersonated user never triggers fingerprinting, whose result would be cached for everyone"- (mt/with-premium-features #{:advanced-permissions}- (let [field-id (mt/id :venues :price)- calls (atom [])]- (mt/with-temp-vals-in-db :model/Field field-id {:fingerprint nil}- (mt/with-dynamic-fn-redefs [sync/refingerprint-field! (fn [field]- (swap! calls conj (:id field))- {:updated-fingerprints 0})]- (impersonation.util-test/with-impersonations!- {:impersonations [{:db-id (mt/id) :attribute "impersonation_attr"}]- :attributes {"impersonation_attr" "impersonation_role"}}- (llm.context/build-schema-context (mt/id) #{(mt/id :venues)}))- (is (= [] @calls))- (testing "but an unrestricted user still gets on-demand fingerprinting, in an admin context"- (let [superuser (atom ::not-called)]- (mt/with-dynamic-fn-redefs [sync/refingerprint-field! (fn [_field]- (reset! superuser api/*is-superuser?*)- {:updated-fingerprints 0})]- (mt/with-test-user :rasta- (llm.context/build-schema-context (mt/id) #{(mt/id :venues)}))- (is (true? @superuser)))))))))))diff --git a/enterprise/backend/test/metabase_enterprise/sandbox/llm_context_test.clj b/enterprise/backend/test/metabase_enterprise/sandbox/llm_context_test.cljindex b0db366b0af..dbea135fb0c 100644--- a/enterprise/backend/test/metabase_enterprise/sandbox/llm_context_test.clj+++ b/enterprise/backend/test/metabase_enterprise/sandbox/llm_context_test.clj@@ -1,26 +1,15 @@(ns metabase-enterprise.sandbox.llm-context-test- "Tests that the LLM schema context respects sandboxing when it fetches fingerprint statistics."+ "Tests that native query source extraction respects column-level sandboxing."{:clj-kondo/config '{:linters {:deprecated-var {:exclude {metabase.test.data/mbql-query {:namespaces [metabase-enterprise.sandbox.llm-context-test]}}}}}}(:require- [clojure.string :as str][clojure.test :refer :all][metabase-enterprise.sandbox.test-util :as met]- [metabase.lib.core :as lib]- [metabase.lib.metadata :as lib.metadata][metabase.llm.context :as llm.context][metabase.permissions.core :as perms][metabase.test :as mt]))(set! *warn-on-reflection* true)-(defn- row-restricting-query- "A GTAP query that restricts rows (not columns) of `:categories`."- []- (let [mp (mt/metadata-provider)- table (lib.metadata/table mp (mt/id :categories))- id-field (lib.metadata/field mp (mt/id :categories :id))]- (lib/filter (lib/query mp table) (lib/< id-field 3))))-(defn- column-restricting-query"A GTAP query that restricts `:categories` to only its `:id` column, so the resulting sandboxcard's result_metadata -- and therefore sandbox-restricted-fields -- excludes every other column."@@ -28,86 +17,24 @@(mt/mbql-query categories{:fields [$id]}))-(defn- table-ddl- "The DDL substring for `table-name` (unqualified) within a multi-table `ddl` string, whether or- not the table is schema-qualified in the output (e.g. \"PUBLIC.CATEGORIES\")."- [ddl table-name]- (some (fn [chunk]- (let [header (first (str/split-lines chunk))]- (when (or (str/starts-with? header (str table-name " ("))- (str/includes? header (str "." table-name " (")))- (str "CREATE TABLE " chunk))))- (rest (str/split ddl #"CREATE TABLE "))))--(defn- column-comment- "Returns the DDL comment line `ddl` carries for `col-name`, or nil if there isn't one."- [ddl col-name]- (->> (str/split-lines ddl)- (partition 2 1)- (some (fn [[comment-line col-line]]- (when (and (str/includes? col-line (str " " col-name " "))- (str/starts-with? (str/triml comment-line) "--"))- comment-line)))))--(deftest schema-context-drops-fingerprints-only-for-sandboxed-table-test- (testing "fingerprint dropping is decided per table: a sandboxed table's stats are omitted, but another- accessible table in the same request keeps its stats"- (met/with-gtaps! {:gtaps {:categories {:query (row-restricting-query)}}}- ;; A freshly-sandboxed group only has :query-builder (not :query-builder-and-native) on the- ;; sandboxed table, so it wouldn't pass fetch-accessible-tables' check at all without this --- ;; see schema-context-sandbox-survives-native-regrant-test for why that's not a safe assumption- ;; to build on.- (perms/set-table-permission! &group (mt/id :categories) :perms/create-queries :query-builder-and-native)- (perms/set-table-permission! &group (mt/id :venues) :perms/create-queries :query-builder-and-native)- (let [{:keys [ddl]} (llm.context/build-schema-context (mt/id) #{(mt/id :categories) (mt/id :venues)})- categories-ddl (table-ddl ddl "CATEGORIES")- venues-ddl (table-ddl ddl "VENUES")]- (testing "the sandboxed table's column loses fingerprint stats"- (is (some? (column-comment categories-ddl "NAME")))- (is (not (str/includes? (str (column-comment categories-ddl "NAME")) "distinct: "))))- (testing "the unsandboxed table's column keeps fingerprint stats"- (is (some? (column-comment venues-ddl "PRICE")))- (is (str/includes? (str (column-comment venues-ddl "PRICE")) "range: ")))))))--(deftest schema-context-sandbox-survives-native-regrant-test- (testing "granting native query access back to a sandboxed group doesn't lift the row restriction"- (met/with-gtaps! {:gtaps {:categories {:query (row-restricting-query)}}}- ;; Regrant native access to the SAME sandboxed group. Per enforce-sandbox?, the sandboxed group is- ;; excluded from the groups checked for de-enforcement, so the sandbox stays enforced even though- ;; the table now also passes the :query-builder-and-native check in fetch-accessible-tables.- (perms/set-table-permission! &group (mt/id :categories) :perms/create-queries :query-builder-and-native)- (let [{:keys [ddl]} (llm.context/build-schema-context (mt/id) #{(mt/id :categories)})- categories-ddl (table-ddl ddl "CATEGORIES")]- (testing "the table is now reachable"- (is (some? categories-ddl)))- (testing "but fingerprint stats are still withheld"- (is (some? (column-comment categories-ddl "NAME")))- (is (not (str/includes? (str (column-comment categories-ddl "NAME")) "distinct: "))))))))--(deftest schema-context-omits-sandbox-restricted-source-columns-test+(deftest get-tables-with-columns-omits-sandbox-restricted-source-columns-test(testing "column-level sandbox restrictions apply to a requested table even when native access is regranted"(met/with-gtaps! {:gtaps {:categories {:query (column-restricting-query)}}}(perms/set-table-permission! &group (mt/id :categories) :perms/create-queries :query-builder-and-native)- (let [{:keys [ddl tables]} (llm.context/build-schema-context (mt/id) #{(mt/id :categories)})- categories-ddl (table-ddl ddl "CATEGORIES")- response-fields (into #{} (map :name) (-> tables first :columns))- lightweight-fields (into #{} (map :name)- (-> (llm.context/get-tables-with-columns- (mt/id) #{(mt/id :categories)})- first- :columns))]- (testing "the DDL contains only the sandbox source card's columns"- (is (str/includes? categories-ddl " ID "))- (is (not (str/includes? categories-ddl " NAME "))))- (testing "both structured metadata paths contain only allowed columns"- (is (= #{"ID"} response-fields))- (is (= #{"ID"} lightweight-fields)))))))--(deftest schema-context-fk-target-sandbox-restricted-field-omitted-test- (testing "an FK target field hidden by column-level sandboxing is not named in the DDL"+ (is (= #{"ID"}+ (into #{} (map :name)+ (-> (llm.context/get-tables-with-columns (mt/id) #{(mt/id :categories)})+ first+ :columns)))))))++(deftest get-tables-with-columns-fk-target-sandbox-restricted-field-omitted-test+ (testing "an FK target field hidden by column-level sandboxing is not named in the FK target"(met/with-gtaps! {:gtaps {:categories {:query (column-restricting-query)}}}(perms/set-table-permission! &group (mt/id :venues) :perms/create-queries :query-builder-and-native)- (let [name-field-id (mt/id :categories :name)]- (mt/with-temp-vals-in-db :model/Field (mt/id :venues :category_id) {:fk_target_field_id name-field-id}- (let [{:keys [ddl]} (llm.context/build-schema-context (mt/id) #{(mt/id :venues)})]- (is (not (str/includes? ddl "FK->CATEGORIES.NAME")))))))))+ (mt/with-temp-vals-in-db :model/Field (mt/id :venues :category_id) {:fk_target_field_id (mt/id :categories :name)}+ (let [category-id-col (->> (llm.context/get-tables-with-columns (mt/id) #{(mt/id :venues)})+ first+ :columns+ (some #(when (= "CATEGORY_ID" (:name %)) %)))]+ (is (some? category-id-col))+ (is (not (contains? category-id-col :fk_target))))))))diff --git a/frontend/src/metabase-types/api/mocks/metabot.ts b/frontend/src/metabase-types/api/mocks/metabot.tsindex 73bf9428e5d..a435297da20 100644--- a/frontend/src/metabase-types/api/mocks/metabot.ts+++ b/frontend/src/metabase-types/api/mocks/metabot.ts@@ -147,7 +147,6 @@ export const MCP_APPS_BOOTSTRAP_SETTING_KEYS = ["last-used-native-database-id","ldap-configured?","ldap-enabled",- "llm-anthropic-api-key-configured?","loading-message","map-tile-server-url","mcp-enabled?",diff --git a/frontend/src/metabase-types/api/mocks/settings.ts b/frontend/src/metabase-types/api/mocks/settings.tsindex d17e19d9e8c..f710606d516 100644--- a/frontend/src/metabase-types/api/mocks/settings.ts+++ b/frontend/src/metabase-types/api/mocks/settings.ts@@ -244,7 +244,6 @@ export const createMockSettings = ("disable-cors-on-localhost": false,"llm-openai-model": "","llm-openai-api-key": "",- "llm-anthropic-model": "","email-configured?": false,"email-smtp-host": null,"email-smtp-port": null,@@ -326,7 +325,6 @@ export const createMockSettings = ("ldap-group-mappings": null,"ldap-group-membership-filter": "(member={dn})","loading-message": "doing-science",- "llm-anthropic-api-key-configured?": false,"mcp-enabled?": true,"map-tile-server-url": "https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png","native-query-autocomplete-match-style": "substring",diff --git a/frontend/src/metabase-types/api/settings.ts b/frontend/src/metabase-types/api/settings.tsindex 9933aed42b4..aa02a7c45e3 100644--- a/frontend/src/metabase-types/api/settings.ts+++ b/frontend/src/metabase-types/api/settings.ts@@ -474,7 +474,6 @@ interface InstanceSettings {"example-dashboard-id": number | null;"has-sample-database?"?: boolean; // Careful! This can be undefined during setup!"instance-creation": string;- "llm-anthropic-api-key-configured?": boolean;"read-only-mode": boolean;"search-typeahead-enabled": boolean;"show-homepage-data": boolean;@@ -853,7 +852,6 @@ export interface EnterpriseSettings extends Settings {"llm-mini-model"?: string | null;"llm-fast-mode"?: boolean | null;"llm-anthropic-api-key"?: string | null;- "llm-anthropic-model": string;"llm-proxy-configured?"?: boolean | null;"metabot-slack-signing-secret"?: string | null;"slack-connect-enabled"?: boolean | null;diff --git a/frontend/src/metabase/metabot/components/AIProviderConfigurationForm/AIProviderList.tsx b/frontend/src/metabase/metabot/components/AIProviderConfigurationForm/AIProviderList.tsxindex 40246bcc7b8..6f83a0d6fad 100644--- a/frontend/src/metabase/metabot/components/AIProviderConfigurationForm/AIProviderList.tsx+++ b/frontend/src/metabase/metabot/components/AIProviderConfigurationForm/AIProviderList.tsx@@ -185,8 +185,6 @@ export function AIProviderList() {// Features that read a fixed connection key directly rather than following the Metabot selection: deleting// the connection they name turns them off, which the admin deserves to hear before confirming.const KEYED_DEPENDENTS: Record<string, () => string> = {- anthropic: () =>- t`SQL generation also runs on this connection, and will stop working without it.`,openai: () =>t`Semantic search also runs on this connection, and will stop working without it.`,};diff --git a/frontend/src/metabase/metabot/components/AIProviderConfigurationForm/AIProviderList.unit.spec.tsx b/frontend/src/metabase/metabot/components/AIProviderConfigurationForm/AIProviderList.unit.spec.tsxindex 719ebdde656..d4af6da5035 100644--- a/frontend/src/metabase/metabot/components/AIProviderConfigurationForm/AIProviderList.unit.spec.tsx+++ b/frontend/src/metabase/metabot/components/AIProviderConfigurationForm/AIProviderList.unit.spec.tsx@@ -127,27 +127,31 @@ describe("AIProviderList", () => {);});- it.each([- ["anthropic", "SQL generation also runs on this connection"],- ["openai", "Semantic search also runs on this connection"],- ])(- "warns that removing the %s connection also turns off the feature reading it",- async (key, warning) => {- setup();-- const row = await screen.findByTestId(`provider-${key}`);- await userEvent.click(within(row).getByLabelText("Provider options"));- await userEvent.click(await screen.findByText("Remove"));-- const modal = await screen.findByRole("dialog", {- name: "Remove this provider?",- });- expect(within(modal).getByText(new RegExp(warning))).toBeInTheDocument();- expect(- within(modal).getByText(/saved credentials will be deleted/),- ).toBeInTheDocument();- },- );+ it("warns that removing the openai connection also turns off semantic search", async () => {+ setup();++ const modal = await openRemoveDialog("openai");++ expect(+ within(modal).getByText(/Semantic search also runs on this connection/),+ ).toBeInTheDocument();+ expect(+ within(modal).getByText(/saved credentials will be deleted/),+ ).toBeInTheDocument();+ });++ it("does not warn about dependent features when removing the anthropic connection", async () => {+ setup();++ const modal = await openRemoveDialog("anthropic");++ expect(+ within(modal).getByText(/saved credentials will be deleted/),+ ).toBeInTheDocument();+ expect(+ within(modal).queryByText(/also runs on this connection/),+ ).not.toBeInTheDocument();+ });it("shows the skeleton until the connections have loaded", async () => {setup();@@ -160,3 +164,10 @@ describe("AIProviderList", () => {).not.toBeInTheDocument();});});++async function openRemoveDialog(key: string) {+ const row = await screen.findByTestId(`provider-${key}`);+ await userEvent.click(within(row).getByLabelText("Provider options"));+ await userEvent.click(await screen.findByText("Remove"));+ return screen.findByRole("dialog", { name: "Remove this provider?" });+}diff --git a/resources/metabot/prompts/system/one-shot-sql-generation.mustache b/resources/metabot/prompts/system/one-shot-sql-generation.mustachedeleted file mode 100644index f4480d815a5..00000000000--- a/resources/metabot/prompts/system/one-shot-sql-generation.mustache+++ /dev/null@@ -1,44 +0,0 @@-You are a SQL query generator for a {{dialect}} database.--Your task is to convert natural language questions into valid SQL queries.--## Available Tables--{{{schema}}}--## Instructions--- Use only the tables and columns shown above-- Always use fully qualified table names (include schema/catalog if present in the DDL)-- If the request is ambiguous, make reasonable assumptions-- If the request cannot be fulfilled, return an explanatory message as the sql value--## Aggregation with JOINs--When counting or summing across joined tables, be aware of row multiplication:--- JOINs can produce multiple rows per entity (e.g., one order with 3 line items = 3 rows)-- Use `COUNT(DISTINCT ...)` when counting entities from a table that might have multiple matches-- Use `COUNT(...)` only when you genuinely want to count all matched rows--{{#current_time}}-## Current Context--Current date and time: {{current_time}}-{{/current_time}}--{{#source_sql}}-## Existing Query--The user is viewing this SQL query:--```sql-{{{source_sql}}}-```-{{/source_sql}}--{{#dialect_instructions}}-## {{dialect}} Specific Rules--{{{dialect_instructions}}}-{{/dialect_instructions}}diff --git a/resources/openapi/openapi.json b/resources/openapi/openapi.jsonindex e70f686f766..1b983c5911f 100644--- a/resources/openapi/openapi.json+++ b/resources/openapi/openapi.json@@ -34774,166 +34774,6 @@"tags" : [ "/api/llm" ]}},- "/api/llm/generate-sql" : {- "post" : {- "description" : "Generate SQL from a natural language prompt.\n\n Requires:\n - LLM to be configured (Anthropic API key set in admin settings)\n - At least one table reference (explicit @mention or implicit from source_sql)\n - A database_id parameter\n\n Returns generated SQL and the list of tables used for context.",- "operationId" : "post-api-llm-generate-sql",- "parameters" : [ ],- "requestBody" : {- "content" : {- "application/json" : {- "schema" : {- "properties" : {- "database_id" : {- "minimum" : 1,- "type" : "integer"- },- "prompt" : {- "type" : "string"- },- "referenced_entities" : {- "items" : {- "properties" : {- "id" : {- "minimum" : 1,- "type" : "integer"- },- "model" : {- "type" : "string"- }- },- "required" : [ "model", "id" ],- "type" : "object"- },- "type" : "array"- },- "source_sql" : {- "type" : "string"- }- },- "required" : [ "prompt", "database_id" ],- "type" : "object"- }- }- }- },- "responses" : {- "2XX" : {- "content" : {- "application/json" : {- "schema" : {- "properties" : {- "referenced_entities" : {- "items" : {- "properties" : {- "columns" : {- "items" : {- "properties" : {- "database_type" : {- "oneOf" : [ {- "type" : "string"- }, {- "type" : "null"- } ]- },- "description" : {- "oneOf" : [ {- "type" : "string"- }, {- "type" : "null"- } ]- },- "fk_target" : {- "properties" : {- "field_name" : {- "type" : "string"- },- "table_name" : {- "type" : "string"- }- },- "required" : [ "table_name", "field_name" ],- "type" : "object"- },- "id" : {- "minimum" : 1,- "type" : "integer"- },- "name" : {- "type" : "string"- },- "semantic_type" : {- "oneOf" : [ {- "type" : "string"- }, {- "type" : "null"- } ]- }- },- "required" : [ "id", "name" ],- "type" : "object"- },- "type" : "array"- },- "description" : {- "oneOf" : [ {- "type" : "string"- }, {- "type" : "null"- } ]- },- "display_name" : {- "oneOf" : [ {- "type" : "string"- }, {- "type" : "null"- } ]- },- "id" : {- "minimum" : 1,- "type" : "integer"- },- "model" : {- "type" : "string"- },- "name" : {- "type" : "string"- },- "schema" : {- "oneOf" : [ {- "type" : "string"- }, {- "type" : "null"- } ]- }- },- "required" : [ "model", "id", "name", "columns" ],- "type" : "object"- },- "type" : "array"- },- "sql" : {- "type" : "string"- }- },- "required" : [ "sql", "referenced_entities" ],- "type" : "object"- }- }- },- "description" : "Successful response"- },- "4XX" : {- "description" : "Client error response"- },- "5XX" : {- "description" : "Server error response"- }- },- "summary" : "POST /api/llm/generate-sql",- "tags" : [ "/api/llm" ]- }- },"/api/llm/list-models" : {"get" : {"description" : "List available LLM models from the configured provider.\n\n Requires LLM to be configured for the selected provider in admin settings.",diff --git a/src/metabase/llm/anthropic.clj b/src/metabase/llm/anthropic.cljdeleted file mode 100644index 5a1fb7915e3..00000000000--- a/src/metabase/llm/anthropic.clj+++ /dev/null@@ -1,122 +0,0 @@-(ns metabase.llm.anthropic- "Anthropic API client for OSS LLM integration.-- Provides synchronous chat completions for text-to-SQL generation- using tool_use for structured output."- (:require- [clj-http.client :as http]- [clojure.string :as str]- [metabase.llm.settings :as llm.settings]- [metabase.util :as u]- [metabase.util.json :as json])- (:import- (com.fasterxml.jackson.core JsonParseException)))--(set! *warn-on-reflection* true)--(def ^:private generate-sql-tool- "Tool definition for structured SQL output.- Forces the model to return a JSON object with sql and optional explanation."- {:name "generate_sql"- :description "Generate SQL query from the user's request. Always use this tool to return your response."- :input_schema {:type "object"- :properties {:sql {:type "string"- :description "The generated SQL query"}- :explanation {:type "string"- :description "Brief explanation of the query"}}- :required ["sql"]}})--(defn- build-request-headers- "Build headers for Anthropic API request."- [api-key]- {"x-api-key" api-key- "anthropic-version" (llm.settings/llm-anthropic-api-version)- "content-type" "application/json"})--(defn- build-request-body- "Build the request body for Anthropic messages API."- [{:keys [model system messages]}]- (cond-> {:model model- :max_tokens (llm.settings/llm-max-tokens)- :messages messages- :tools [generate-sql-tool]- :tool_choice {:type "tool" :name "generate_sql"}}- system (assoc :system system)))--(defn- extract-tool-input- "Extract the tool input from Anthropic messages response.- Returns the parsed JSON input from the tool_use content block."- [response-body]- (let [content (:content response-body)]- (->> content- (filter #(= "tool_use" (:type %)))- first- :input)))--(defn- handle-api-error- "Handle HTTP errors from Anthropic API."- [exception]- (if-let [response-body (some-> exception ex-data :body)]- (let [parsed (try- (json/decode response-body)- (catch JsonParseException _- {:error {:message response-body}}))]- (throw (ex-info (or (-> parsed :error :message)- "Anthropic API request failed")- {:type :anthropic-api-error- :status (some-> exception ex-data :status)- :body parsed}- exception)))- (throw exception)))--(defn- get-api-key-or-throw- "Gets Anthropic API key from settings or throws an unconfigured error."- []- (let [api-key (llm.settings/llm-anthropic-api-key)]- (when (str/blank? api-key)- (throw (ex-info "LLM is not configured. Please set an Anthropic API key via MB_LLM_ANTHROPIC_API_KEY."- {:type :llm-not-configured})))- api-key))--(defn chat-completion- "Send a chat completion request to Anthropic.- Returns a map with:- - :result - Map with :sql and optionally :explanation from the tool response- - :usage - Map with :model, :prompt (input tokens), :completion (output tokens)- - :duration-ms - Request duration in milliseconds-- Options:- - :model - Model to use; defaults to the `llm-anthropic-model` setting- - :system - System prompt- - :messages - Vector of {:role :content} maps for conversation history"- [{:keys [model system messages]}]- (let [model (or model (llm.settings/llm-anthropic-model))- request {:model model- :system system- :messages messages}- start-time (u/start-timer)- url (str (llm.settings/llm-anthropic-api-base-url) "/v1/messages")]- ;; Outside the try so the e2e guard and a malformed URL fail loudly instead of being- ;; routed through `handle-api-error` (mirrors `metabase.metabot.self.core/request`).- (llm.settings/assert-llm-host-allowed! url)- (let [policy-opts (llm.settings/llm-request-opts url)]- (try- (let [response (http/post url- (merge {:headers (build-request-headers (get-api-key-or-throw))- :body (json/encode (build-request-body request))- :as :json- :content-type :json- :socket-timeout (llm.settings/llm-request-timeout-ms)- :connection-timeout (llm.settings/llm-connection-timeout-ms)}- policy-opts))- duration-ms (u/since-ms start-time)- body (:body response)- usage (:usage body)]- {:result (extract-tool-input body)- :duration-ms duration-ms- :usage {:model model- :prompt (:input_tokens usage)- :completion (:output_tokens usage)}})- (catch Exception e- (llm.settings/rethrow-if-llm-network-policy-error! e url)- (handle-api-error e))))))diff --git a/src/metabase/llm/api.clj b/src/metabase/llm/api.cljindex 8d9137a4f8c..289aee9769c 100644--- a/src/metabase/llm/api.clj+++ b/src/metabase/llm/api.clj@@ -1,90 +1,14 @@(ns metabase.llm.api- "API endpoints for OSS BYOK SQL generation."+ "API endpoints for LLM provider connections and native query source extraction."(:require- [clojure.java.io :as io]- [clojure.set :as set]- [metabase.analytics.core :as analytics]- [metabase.api.common :as api][metabase.api.macros :as api.macros][metabase.api.routes.common :refer [+auth]][metabase.api.util.handlers :as handlers]- [metabase.driver :as driver]- [metabase.llm.anthropic :as llm.anthropic][metabase.llm.api.provider]- [metabase.llm.context :as llm.context]- [metabase.llm.db :as llm.db]- [metabase.llm.settings :as llm.settings]- [metabase.metabot.core :as metabot]- [metabase.request.core :as request]- [metabase.util :as u]- [metabase.util.i18n :refer [tru]]- [stencil.core :as stencil]- [throttle.core :as throttle])- (:import- (java.time LocalDateTime)- (java.time.format DateTimeFormatter)))+ [metabase.llm.context :as llm.context]))(set! *warn-on-reflection* true)-(def ^:private sql-gen-throttlers- "Throttlers for SQL generation endpoints.- - :user-id limits requests per user (default 20/minute)- - :ip-address limits requests per IP (default 100/minute)"- {:user-id (throttle/make-throttler :user-id- :attempts-threshold (llm.settings/llm-rate-limit-per-user)- :attempt-ttl-ms 60000)- :ip-address (throttle/make-throttler :ip-address- :attempts-threshold (llm.settings/llm-rate-limit-per-ip)- :attempt-ttl-ms 60000)})--(defn- database-engine- "Get the engine keyword for a database."- [database-id]- (when database-id- (llm.db/database-engine database-id)))--(def ^:private load-dialect-instructions- "Load dialect-specific instructions from resources, if available.- Returns nil if no instructions file exists for the given engine.- Memoized since dialect files are static resources."- (memoize- (fn [engine]- (when engine- (when-let [resource-path (driver/llm-sql-dialect-resource engine)]- (when-let [resource (io/resource resource-path)]- (slurp resource)))))))--(def ^:private sql-generation-prompt-template "metabot/prompts/system/one-shot-sql-generation.mustache")--(def ^:private datetime-formatter- (DateTimeFormatter/ofPattern "yyyy-MM-dd HH:mm:ss"))--(defn- current-datetime-str- "Get current date/time as a formatted string for prompt context."- []- (.format (LocalDateTime/now) datetime-formatter))--(defn- build-system-prompt- "Build the system prompt for SQL generation with dialect, schema, and optional dialect instructions.- When source-sql is provided, includes the existing query for context."- [{:keys [dialect schema-ddl dialect-instructions source-sql]}]- (stencil/render-file sql-generation-prompt-template- (cond-> {:dialect dialect- :schema schema-ddl- :current_time (current-datetime-str)- :dialect_instructions dialect-instructions}- source-sql (assoc :source_sql source-sql))))--(defn- track-sqlgen-event!- "Track SQL generation usage via Snowplow simple_event."- [{:keys [duration-ms result engine]}]- (analytics/track-event! :snowplow/simple_event- {:event "metabot_oss_sqlgen_used"- :event_detail (some-> engine name)- :duration_ms (some-> duration-ms long)- :result result}- api/*current-user-id*))-(def ^:private table-with-columns-schema"Schema for table metadata with columns returned by /extract-sources."[:map@@ -136,124 +60,6 @@{:tables (or tables []):card_ids (sort (or (llm.context/get-accessible-card-ids card-ids) #{}))}))-(api.macros/defendpoint :post "/generate-sql"- :- [:map- [:sql :string]- [:referenced_entities [:sequential- [:map- [:model :string]- [:id pos-int?]- [:name :string]- [:schema {:optional true} [:maybe :string]]- [:display_name {:optional true} [:maybe :string]]- [:description {:optional true} [:maybe :string]]- [:columns [:sequential- [:map- [:id pos-int?]- [:name :string]- [:database_type {:optional true} [:maybe :string]]- [:description {:optional true} [:maybe :string]]- [:semantic_type {:optional true} [:maybe :string]]- [:fk_target {:optional true}- [:map- [:table_name :string]- [:field_name :string]]]]]]]]]]- "Generate SQL from a natural language prompt.-- Requires:- - LLM to be configured (Anthropic API key set in admin settings)- - At least one table reference (explicit @mention or implicit from source_sql)- - A database_id parameter-- Returns generated SQL and the list of tables used for context."- [_route-params- _query-params- body :- [:map {:closed true}- [:prompt :string]- [:database_id pos-int?]- [:source_sql {:optional true} :string]- [:referenced_entities {:optional true}- [:sequential [:map {:closed true}- [:model :string]- [:id pos-int?]]]]]- request]- (when-not (llm.settings/llm-anthropic-api-key)- (throw (ex-info (tru "LLM SQL generation is not configured. Please set an Anthropic API key in admin settings.")- {:status-code 403})))- (when-let [limit-msg (metabot/check-usage-limits!)]- (throw (ex-info limit-msg {:status-code 429})))- (throttle/with-throttling [(sql-gen-throttlers :ip-address) (request/ip-address request)- (sql-gen-throttlers :user-id) api/*current-user-id*]- (let [{:keys [prompt database_id source_sql referenced_entities]} body- ;; 2. Extract table IDs from all sources and merge them- frontend-table-ids (when (seq referenced_entities)- (->> referenced_entities- (filter #(= "table" (:model %)))- (map :id)- set))- explicit-table-ids (llm.context/parse-table-mentions prompt)- implicit-table-ids (when source_sql- (llm.context/extract-tables-from-sql database_id source_sql))- table-ids (set/union (or frontend-table-ids #{})- (or explicit-table-ids #{})- (or implicit-table-ids #{}))]- (when (empty? table-ids)- (throw (ex-info (if (and source_sql (empty? implicit-table-ids))- (tru "Failed to parse SQL. Use @mentions to provide table references.")- (tru "No tables found. Use @mentions or provide source SQL with table references."))- {:status-code 400})))- (let [{:keys [ddl tables]} (llm.context/build-schema-context database_id table-ids)]- (when-not ddl- (throw (ex-info (tru "No accessible tables found. Check table permissions.")- {:status-code 400})))- (let [engine (database-engine database_id)- dialect (if engine (driver/display-name engine) "SQL")- dialect-instructions (load-dialect-instructions engine)- system-prompt (build-system-prompt {:dialect dialect- :schema-ddl ddl- :dialect-instructions dialect-instructions- :source-sql source_sql})- start-timer (u/start-timer)]- (try- (let [{:keys [result usage duration-ms]} (llm.anthropic/chat-completion- {:system system-prompt- :messages [{:role "user" :content prompt}]})]- (analytics/track-token-usage!- {:snowplow true- :prometheus true- :user-id api/*current-user-id*- :request-id (analytics/uuid->ai-service-hex-uuid (random-uuid))- :model-id (:model usage)- :provider "anthropic"- :prompt-tokens (:prompt usage)- :completion-tokens (:completion usage)- :total-tokens (+ (:prompt usage) (:completion usage))- :estimated-costs-usd 0.0- :duration-ms (some-> duration-ms long)- ;; for some reason, :source convention is snake_case and :tag is (mostly) kebab- :source "oss_metabot"- :tag "oss-sqlgen"})- (metabot/log-ai-usage!- {:source "sql-gen"- :model (:model usage)- :provider "anthropic"- :model-name (:model usage)- :prompt-tokens (:prompt usage)- :completion-tokens (:completion usage)})- (track-sqlgen-event!- {:duration-ms (u/since-ms start-timer)- :result "success"- :engine engine})- (let [sql (:sql result)- referenced-entities (mapv #(assoc % :model "table") tables)]- {:sql sql- :referenced_entities referenced-entities}))- (catch Exception e- (track-sqlgen-event! {:duration-ms (u/since-ms start-timer)- :result "failure"- :engine engine})- (throw e))))))))-(def ^{:arglists '([request respond raise])} routes"`/api/llm` routes."(handlers/routesdiff --git a/src/metabase/llm/context.clj b/src/metabase/llm/context.cljindex a53882e3e37..b430bf236ef 100644--- a/src/metabase/llm/context.clj+++ b/src/metabase/llm/context.clj@@ -1,8 +1,6 @@(ns metabase.llm.context- "Schema extraction for LLM context. Parses table mentions from prompts- and fetches table metadata formatted as DDL for SQL generation."+ "Resolves the tables and cards a native query references, with permission-filtered column metadata."(:require- [clojure.string :as str][metabase.api.common :as api][metabase.lib-be.core :as lib-be][metabase.lib.core :as lib]@@ -10,38 +8,11 @@[metabase.llm.db :as llm.db][metabase.metabot.metadata-perms :as metabot.perms][metabase.models.interface :as mi]- [metabase.parameters.field-values :as params.field-values]- [metabase.request.core :as request][metabase.sql-tools.core :as sql-tools]- [metabase.sync.core :as sync]- [metabase.util.log :as log]- [metabase.warehouse-schema.models.field-values :as field-values])- (:import- (java.io StringWriter Writer)))+ [metabase.util.log :as log]))(set! *warn-on-reflection* true)-;;; ------------------------------------------------ Mention Parsing --------------------------------------------------(def ^:private table-mention-pattern- "Regex to extract table IDs from markdown-style metabase:// links.- Frontend serializes @mentions as: [Display Name](metabase://table/123)"- #"\[[^\]]+\]\(metabase://table/(\d+)\)")--(defn parse-table-mentions- "Extract table IDs from metabase://table/{id} links in prompt text.-- Frontend serializes @mentions as markdown links:- [Display Name](metabase://table/123)-- Returns a set of table IDs (integers), or nil if input is nil."- [prompt-text]- (when (string? prompt-text)- (->> (re-seq table-mention-pattern prompt-text)- (keep (fn [[_ id-str]]- (parse-long id-str)))- set)))-(defn extract-tables-from-sql"Extract table IDs from a raw SQL string.@@ -103,26 +74,21 @@(defn- fetch-table-columns"Use metadata provider to get visible columns for a table.- Returns sequence of column maps with metadata for DDL generation.- By default excludes implicitly-joinable columns; pass opts to override."- ([mp table-id]- (fetch-table-columns mp table-id {}))- ([mp table-id opts]- (when-let [table-meta (lib.metadata/table mp table-id)]- (let [table-query (lib/query mp table-meta)- vis-opts (merge {:include-implicitly-joinable? false} opts)- columns (lib/visible-columns table-query -1 vis-opts)]- (mapv (fn [col]- {:id (:id col)- :table-id table-id- :name (:name col)- :database_type (or (:database-type col)- (some-> (:base-type col) name))- :description (:description col)- :semantic_type (:semantic-type col)- :fingerprint (:fingerprint col)- :fk_target_field_id (:fk-target-field-id col)})- columns)))))+ Returns sequence of column maps with the metadata the API response needs.+ Excludes implicitly-joinable columns."+ [mp table-id]+ (when-let [table-meta (lib.metadata/table mp table-id)]+ (let [table-query (lib/query mp table-meta)+ columns (lib/visible-columns table-query -1 {:include-implicitly-joinable? false})]+ (mapv (fn [col]+ {:id (:id col)+ :name (:name col)+ :database_type (or (:database-type col)+ (some-> (:base-type col) name))+ :description (:description col)+ :semantic_type (:semantic-type col)+ :fk_target_field_id (:fk-target-field-id col)})+ columns))))(defn- filter-sandbox-restricted-columns"Remove columns that the current user's column-level sandbox does not expose for `table-id`."@@ -131,48 +97,6 @@(filterv #(contains? allowed-field-ids (:id %)) columns)columns))-(def ^:private max-restricted-field-values-fetches- "Per-table cap on how many columns of a row-restricted table [[fetch-field-values]] will fetch- synchronously. A restricted table's FieldValues can't be served from the cheap shared cache --- each one is a real warehouse query -- so an unbounded table can otherwise turn one request into- hundreds of synchronous queries. Unrestricted columns are not capped: they're served by the existing- shared FieldValues cache."- 25)--(defn- cap-restricted-fields- "Caps each restricted table's fields at [[max-restricted-field-values-fetches]] independently, so one- large restricted table can't starve another restricted table's fields of any fetches at all."- [restricted-fields-by-table]- (into []- (mapcat (fn [[table-id fields]]- (when (> (count fields) max-restricted-field-values-fetches)- (log/infof "Capping restricted-table field values fetch to %d of %d columns for table %d."- max-restricted-field-values-fetches (count fields) table-id))- (take max-restricted-field-values-fetches fields)))- restricted-fields-by-table))--(defn- fetch-field-values- "Returns a map of field-id -> values vector for those `columns` that should have FieldValues.- Values are the ones the current user is allowed to see, and are fetched from the source database when- nothing suitable is cached. Fields belonging to a table in `restricted-table-ids` are capped at- [[max-restricted-field-values-fetches]] per table -- applied only after narrowing to fields that- should have FieldValues, so ineligible fields can't consume another field's budget."- [columns restricted-table-ids]- (let [field-ids (->> columns (keep :id) (filter pos-int?) set)]- (when (seq field-ids)- (let [;; Grouped by the persisted Field's own table_id, not the caller-supplied column's- ;; :table-id, consistent with the permission checks elsewhere in this namespace.- fields (filter field-values/field-should-have-field-values?- (llm.db/fields field-ids))- {restricted true, unrestricted false} (group-by #(contains? restricted-table-ids (:table_id %)) fields)- capped-fields (concat unrestricted (cap-restricted-fields (group-by :table_id restricted)))]- (into {}- (keep (fn [field]- (when-let [fv (params.field-values/get-or-create-field-values! field)]- (when-let [values (not-empty (:values fv))]- [(:id field) values]))))- capped-fields)))))-(defn- fetch-fk-targets"Fetch table.field names for FK target fields.Only includes targets in `database-id` whose Table the current user can access and whose column,@@ -195,206 +119,12 @@[id {:table (:name (get accessible-tables table_id)) :field name}]))))fields)))))-;;; ----------------------------------------- On-Demand Metadata Enrichment -------------------------------------------(defn- drop-fingerprints- "Removes `:fingerprint` from every column of `table`."- [table]- (update table :columns #(mapv (fn [col] (dissoc col :fingerprint)) %)))--(defn- enrich-fingerprints-on-demand!- "For columns missing fingerprints, trigger re-fingerprinting.- Returns a map of field-id -> fingerprint for columns that were missing them.- This queries the source database to compute fingerprints if they don't exist.- Only call this for a user who can see every row: the computed fingerprint is stored on the Field and- served to every user."- [columns]- (let [missing-fp-ids (->> columns- (filter #(and (:id %) (nil? (:fingerprint %))))- (map :id)- (filter pos-int?)- set)]- (when (seq missing-fp-ids)- (let [fields (llm.db/fields missing-fp-ids)]- (doseq [field fields]- ;; Run with admin perms to match behavior during normal sync.- (request/as-admin (sync/refingerprint-field! field)))- (llm.db/field-fingerprints missing-fp-ids)))))--;;; ------------------------------------------- Fingerprint Formatting ---------------------------------------------(defn- format-numeric-stats- "Format numeric fingerprint as readable string."- [{:keys [min max avg]}]- (when (and min max)- (let [fmt #(if (integer? %) (str %) (format "%.2f" (double %)))]- (cond-> (str "range: " (fmt min) "-" (fmt max))- avg (str ", avg: " (fmt avg))))))--(defn- format-temporal-stats- "Format temporal fingerprint as readable string."- [{:keys [earliest latest]}]- (when (and earliest latest)- (let [fmt-date #(some-> % (subs 0 (min 10 (count %))))]- (str (fmt-date earliest) " to " (fmt-date latest)))))--(defn- format-text-stats- "Format text fingerprint as readable string.- Includes average-length from type fingerprint and distinct-count/nil% from global."- [type-fp global-fp]- (let [{:keys [average-length]} type-fp- {:keys [distinct-count nil%]} global-fp- parts (cond-> []- distinct-count- (conj (str "distinct: " distinct-count))-- (and nil% (pos? nil%))- (conj (str "nil: " (format "%.0f%%" (* 100 nil%))))-- (and average-length (> average-length 0))- (conj (str "avg-len: " (format "%.0f" (double average-length)))))]- (when (seq parts)- (str/join ", " parts))))--(defn- semantic-type->hint- "Extract the type name from a semantic type keyword for DDL comments.- e.g. :type/Email -> \"Email\", :type/CreationTimestamp -> \"CreationTimestamp\"- Returns nil if semantic-type is nil."- [semantic-type]- (some-> semantic-type name))--;;; -------------------------------------------- Column Comment Building ----------------------------------------------(def ^:private max-sample-values 6)-(def ^:private max-sample-value-length 30)--(defn- truncate-value- "Truncate a sample value if too long."- [v]- (let [s (str v)]- (if (> (count s) max-sample-value-length)- (str (subs s 0 (- max-sample-value-length 3)) "...")- s)))--(defn- build-column-comment- "Build an informative comment for a column based on available metadata.- Returns nil if no useful metadata is available."- [{:keys [description semantic_type fingerprint fk_target_field_id]}- field-values- fk-target-info]- (let [has-sample-values? (and (not-empty field-values)- (<= (count field-values) max-sample-values))- fp-global (get fingerprint :global)- fp-type (some-> fingerprint :type vals first)-- parts (cond-> []- ;; User-provided description takes priority- (not-empty description)- (conj description)-- ;; FK relationship- (and fk_target_field_id fk-target-info)- (conj (str "FK->" (:table fk-target-info) "." (:field fk-target-info))))-- ;; Sample values for low-cardinality fields- parts (if has-sample-values?- (conj parts (str/join ", " (map truncate-value field-values)))- ;; Semantic type hint only when no description and no sample values- (if-let [sem-hint (and (nil? description)- semantic_type- (semantic-type->hint semantic_type))]- (conj parts sem-hint)- parts))-- ;; Fingerprint stats based on field type- stats (cond- ;; Numeric range- (and (:min fp-type) (:max fp-type))- (format-numeric-stats fp-type)-- ;; Temporal range- (and (:earliest fp-type) (:latest fp-type))- (format-temporal-stats fp-type)-- ;; Text stats (distinct count, nil%, avg length)- (or (:average-length fp-type) (:distinct-count fp-global))- (format-text-stats fp-type fp-global))-- all-parts (cond-> parts- stats (conj stats))]- (when (seq all-parts)- (str/join "; " all-parts))))--;;; ------------------------------------------------ DDL Formatting --------------------------------------------------(defn- format-escaped- "Escape identifier if it contains special characters."- [^String identifier ^Writer writer]- (if (re-matches #"[\p{Alpha}_][\p{Alnum}_]*" identifier)- (.append writer identifier)- (do- (.append writer \")- (doseq [^Character c identifier]- (when (= c \")- (.append writer c))- (.append writer c))- (.append writer \"))))--(defn- format-column-ddl- "Format a single column definition. If column has a :comment, emit it as a SQL comment- on the line before the column definition."- [{:keys [^String database_type ^String comment], col-name :name} ^Writer writer first?]- (when comment- (when-not first?- (.append writer "\n"))- (.append writer " -- ")- (.append writer comment)- (.append writer "\n"))- (when-not (or first? comment)- (.append writer "\n"))- (.append writer " ")- (format-escaped col-name writer)- (.append writer " ")- (.append writer (or database_type "UNKNOWN")))--(defn- format-table-ddl- [{:keys [schema columns description], table-name :name} ^Writer writer]- (when (not-empty description)- (.append writer "-- ")- (.append writer ^String description)- (.append writer "\n"))- (.append writer "CREATE TABLE ")- (when (seq schema)- (format-escaped schema writer)- (.append writer \.))- (format-escaped table-name writer)- (.append writer " (")- (when (seq columns)- (.append writer "\n")- (format-column-ddl (first columns) writer true)- (doseq [column (rest columns)]- (.append writer ",")- (format-column-ddl column writer false)))- (.append writer "\n);"))--(defn- format-schema-ddl- "Format multiple tables as DDL string."- [tables]- (let [sw (StringWriter.)]- (doseq [table tables]- (format-table-ddl table sw)- (.append sw \newline))- (str/trimr (str sw))))-(defn- fetch-accessible-tables-with-columns- "Shared prelude for [[build-schema-context]] and [[get-tables-with-columns]]: fetch the tables in- `table-ids` the current user can access in `database-id`, and build each one's sandbox-filtered- column list (via the metadata provider, so numbers/joins resolve the same way for both callers).+ "Fetch the tables in `table-ids` the current user can access in `database-id`, and build each one's+ sandbox-filtered column list via the metadata provider.- Does not itself require read access to `database-id` -- a caller that needs a hard 403 for that- (like [[build-schema-context]]) must check it before calling this. [[get-tables-with-columns]]- deliberately doesn't: it shares this prelude only for its `:tables` behavior, and a caller that- only wants its `:card_ids` behavior shouldn't be denied over unrelated table access.+ Does not require read access to `database-id`: a user who can't reach any of the requested tables+ gets nil rather than a 403.Returns nil when the user can't reach any of the requested tables in `database-id`; otherwise avector of `{:id :name :schema :display_name :description :columns}` maps -- possibly empty, if@@ -421,29 +151,6 @@;;; ------------------------------------------------- Public API --------------------------------------------------(defn- enrich-columns-with-comments- "Add :comment to each column based on available metadata."- [columns field-values-map fk-targets-map]- (mapv (fn [col]- (let [fv (get field-values-map (:id col))- fk-info (get fk-targets-map (:fk_target_field_id col))- comment (build-column-comment col fv fk-info)]- (cond-> col- comment (assoc :comment comment))))- columns))--(defn- merge-enriched-fingerprints- "Merge on-demand fingerprints into columns that were missing them."- [columns enriched-fp-map]- (if (seq enriched-fp-map)- (mapv (fn [col]- (if (and (nil? (:fingerprint col))- (contains? enriched-fp-map (:id col)))- (assoc col :fingerprint (get enriched-fp-map (:id col)))- col))- columns)- columns))-(defn- format-columns-for-response"Format columns for API response, resolving FK targets."[columns fk-targets-map]@@ -458,79 +165,6 @@:field_name (:field fk-info)}))))columns))-(defn- drop-or-enrich-fingerprints- "For each of `tables-with-columns`: drop fingerprints from a table in `restricted-table-ids`- (see [[build-schema-context]]'s docstring), or merge in any on-demand fingerprints computed for- the columns of one that isn't."- [tables-with-columns restricted-table-ids]- (let [;; On-demand enrichment: trigger fingerprinting only for columns of tables the current- ;; user can see every row of -- a fingerprint covers every row of the field and is- ;; computed under the database's default role, with no per-user variant to fall back on.- unrestricted-columns (mapcat :columns (remove #(contains? restricted-table-ids (:id %))- tables-with-columns))- enriched-fp-map (enrich-fingerprints-on-demand! unrestricted-columns)]- ;; For a restricted table the only honest answer is to say nothing about ranges or- ;; distinct counts.- (mapv (fn [table]- (if (contains? restricted-table-ids (:id table))- (drop-fingerprints table)- (update table :columns merge-enriched-fingerprints enriched-fp-map)))- tables-with-columns)))--(defn build-schema-context- "Fetch table metadata for mentioned tables and format as DDL for LLM context.-- Uses the metadata provider to get visible columns, respecting field- visibility settings. Includes field descriptions, sample values, and- statistical information when available.-- For fields missing fingerprints or field values, this function will- trigger on-demand creation by querying the source database.-- For a table where the user's row access is narrowed by sandboxing, connection impersonation, or- database routing, sample values are fetched under their own effective access and fingerprint- statistics are omitted for that table's columns -- this is decided per table, since sandboxing- varies by table even within one request.-- Parameters:- - database-id: Database containing the tables- - table-ids: Set of table IDs to include-- Returns a map with:- - :ddl - DDL string for LLM context- - :tables - structured table metadata for API response- Or nil if no accessible tables found."- [database-id table-ids]- (when (and database-id (seq table-ids))- (api/read-check :model/Database database-id)- (metabot.perms/with-cache- (when-let [tables-with-columns (fetch-accessible-tables-with-columns database-id table-ids)]- (let [restricted-table-ids (metabot.perms/row-restricted-table-ids (into #{} (map :id) tables-with-columns))- tables-with-enriched-fps (drop-or-enrich-fingerprints tables-with-columns restricted-table-ids)- all-enriched-columns (mapcat :columns tables-with-enriched-fps)-- ;; Batch fetch FieldValues (on-demand) and FK targets- field-values-map (fetch-field-values all-enriched-columns restricted-table-ids)- fk-targets-map (fetch-fk-targets database-id all-enriched-columns)-- ;; Enrich columns with comments for DDL- enriched-tables- (mapv (fn [table]- (update table :columns- enrich-columns-with-comments- field-values-map- fk-targets-map))- tables-with-enriched-fps)-- ;; Format tables for API response (without :comment, with :fk_target)- response-tables- (mapv (fn [table]- (update table :columns format-columns-for-response fk-targets-map))- tables-with-enriched-fps)]- (when (seq enriched-tables)- {:ddl (format-schema-ddl enriched-tables)- :tables response-tables}))))))-(defn get-tables-with-columns"Fetch tables with their columns for the extract-sources endpoint.Returns lightweight metadata without triggering fingerprinting or field values.diff --git a/src/metabase/llm/db.clj b/src/metabase/llm/db.cljindex 9d3fc7616cf..46205b4e840 100644--- a/src/metabase/llm/db.clj+++ b/src/metabase/llm/db.clj@@ -65,17 +65,7 @@[card-ids :- [:set ::lib.schema.id/card]](t2/select :model/Card :id [:in card-ids] :archived false))-(mu/defn fields- "The Fields with `field-ids`."- [field-ids :- [:set ::lib.schema.id/field]]- (t2/select :model/Field :id [:in field-ids] {:from [(warehouse-schema-overlay/field-query)]}))-(mu/defn field-names-and-tables"The id, name, and Table id of the Fields with `field-ids`."[field-ids :- [:set ::lib.schema.id/field]](t2/select [:model/Field :id :name :table_id] :id [:in field-ids] {:from [(warehouse-schema-overlay/field-query {:user-settings? false})]}))--(mu/defn field-fingerprints- "A map of Field id to fingerprint for the Fields with `field-ids`."- [field-ids :- [:set ::lib.schema.id/field]]- (t2/select-pk->fn :fingerprint :model/Field :id [:in field-ids] {:from [(warehouse-schema-overlay/field-query {:user-settings? false})]}))diff --git a/src/metabase/llm/settings.clj b/src/metabase/llm/settings.cljindex 205d0440210..a32704aba20 100644--- a/src/metabase/llm/settings.clj+++ b/src/metabase/llm/settings.clj@@ -58,8 +58,8 @@{:status-code 400:llm-url url}))))))-;; TODO (Chris 2026-08-17) -- BOT-2005: generate-sql and semantic search read these settings directly, so-;; deleting the connection they key off turns those features off. They should name a connection instead.+;; TODO (Chris 2026-08-17) -- BOT-2005: semantic search reads these settings directly, so deleting the+;; connection it keys off turns it off. It should name a connection instead.(defn- connection-field-getter"Getter for a per-provider credential setting whose value lives on the `llm-providers` connection list."[setting-kw]@@ -85,22 +85,6 @@:setter (connection-field-setter :llm-anthropic-api-key):doc "Backed by the anthropic connection in the admin AI settings provider list: reads and writes go through the llm-providers connection list, and a value set by this environment variable shadows this one field of that connection.")-(defsetting llm-anthropic-api-key-configured?- "Whether an Anthropic API key has been configured."- :type :boolean- :visibility :public- :setter :none- :export? false- :getter #(some? (llm-anthropic-api-key))- :doc false)--(defsetting llm-anthropic-model- (deferred-tru "The Anthropic model to use.")- :encryption :no- :visibility :settings-manager- :default "claude-opus-4-5-20251101"- :export? false)-(defsetting llm-anthropic-api-base-url(deferred-tru "The Anthropic API base URL."):encryption :when-encryption-key-set@@ -112,14 +96,6 @@:deprecated-name :ee-anthropic-api-base-url:doc "Backed by the anthropic connection in the admin AI settings provider list: reads and writes go through the llm-providers connection list, and a value set by this environment variable shadows this one field of that connection.")-(defsetting llm-anthropic-api-version- (deferred-tru "The Anthropic API version.")- :encryption :no- :visibility :internal- :default "2023-06-01"- :export? false- :doc false)-;;; -------------------------------------------------- OpenAI ---------------------------------------------------(defsetting llm-openai-model@@ -480,17 +456,3 @@:default 10000:visibility :settings-manager:export? false)--(defsetting llm-rate-limit-per-user- (deferred-tru "Maximum SQL generation requests per user per minute.")- :type :integer- :default 20- :visibility :settings-manager- :export? false)--(defsetting llm-rate-limit-per-ip- (deferred-tru "Maximum SQL generation requests per IP address per minute.")- :type :integer- :default 100- :visibility :settings-manager- :export? false)diff --git a/src/metabase/metabot/self/core.clj b/src/metabase/metabot/self/core.cljindex 07104eb35f0..f68f049b418 100644--- a/src/metabase/metabot/self/core.clj+++ b/src/metabase/metabot/self/core.clj@@ -1282,7 +1282,7 @@never block the caller forever. The timeouts default to the operator-tunable[[metabase.llm.settings/llm-connection-timeout-ms]] and[[metabase.llm.settings/llm-request-timeout-ms]] settings (read- at call time), the same knobs `metabase.llm.anthropic` uses. Callers can+ at call time). Callers canoverride either timeout per request by passing `:connection-timeout` /`:socket-timeout` in `req`.diff --git a/test/metabase/llm/anthropic_test.clj b/test/metabase/llm/anthropic_test.cljdeleted file mode 100644index a91c75a639e..00000000000--- a/test/metabase/llm/anthropic_test.clj+++ /dev/null@@ -1,195 +0,0 @@-(ns metabase.llm.anthropic-test- (:require- [clj-http.client :as http]- [clojure.test :refer :all]- [metabase.config.core :as config]- [metabase.llm.anthropic :as anthropic]- [metabase.llm.settings :as llm.settings]- [metabase.test :as mt]- [metabase.util.http :as u.http]))--(set! *warn-on-reflection* true)--;;; ------------------------------------------- extract-tool-input Tests ---------------------------------------------(deftest ^:parallel extract-tool-input-test- (testing "valid tool_use response extracts input"- (let [response {:content [{:type "tool_use"- :id "123"- :name "generate_sql"- :input {:sql "SELECT 1"}}]}]- (is (= {:sql "SELECT 1"}- (#'anthropic/extract-tool-input response)))))- (testing "multiple content blocks finds tool_use"- (let [response {:content [{:type "text" :text "thinking..."}- {:type "tool_use"- :id "456"- :name "generate_sql"- :input {:sql "SELECT 1" :explanation "Simple query"}}]}]- (is (= {:sql "SELECT 1" :explanation "Simple query"}- (#'anthropic/extract-tool-input response)))))- (testing "no tool_use block returns nil"- (let [response {:content [{:type "text" :text "no tool"}]}]- (is (nil? (#'anthropic/extract-tool-input response)))))- (testing "empty content returns nil"- (is (nil? (#'anthropic/extract-tool-input {:content []})))- (is (nil? (#'anthropic/extract-tool-input {}))))- (testing "tool_use without input returns nil"- (let [response {:content [{:type "tool_use" :id "123" :name "generate_sql"}]}]- (is (nil? (#'anthropic/extract-tool-input response)))))- (testing "returns first tool_use when multiple present"- (let [response {:content [{:type "tool_use"- :id "1"- :name "generate_sql"- :input {:sql "SELECT 1"}}- {:type "tool_use"- :id "2"- :name "generate_sql"- :input {:sql "SELECT 2"}}]}]- (is (= {:sql "SELECT 1"}- (#'anthropic/extract-tool-input response))))))--;;; ------------------------------------------- build-request-headers Tests ---------------------------------------------(deftest ^:parallel build-request-headers-test- (testing "includes required headers"- (let [headers (#'anthropic/build-request-headers "sk-test-key")]- (is (= "sk-test-key" (get headers "x-api-key")))- (is (= "2023-06-01" (get headers "anthropic-version")))- (is (= "application/json" (get headers "content-type"))))))--;;; ------------------------------------------- build-request-body Tests ---------------------------------------------(deftest build-request-body-test- (testing "includes required fields with default max_tokens"- (mt/with-temporary-setting-values [llm-max-tokens nil]- (let [body (#'anthropic/build-request-body {:model "claude-sonnet-4-5-20250929"- :messages [{:role "user" :content "test"}]})]- (is (= "claude-sonnet-4-5-20250929" (:model body)))- (is (= 4096 (:max_tokens body)))- (is (= [{:role "user" :content "test"}] (:messages body)))- (is (vector? (:tools body)))- (is (= {:type "tool" :name "generate_sql"} (:tool_choice body))))))- (testing "uses configured max_tokens setting"- (mt/with-temporary-setting-values [llm-max-tokens 8192]- (let [body (#'anthropic/build-request-body {:model "claude-sonnet-4-5-20250929"- :messages [{:role "user" :content "test"}]})]- (is (= 8192 (:max_tokens body))))))- (testing "includes system prompt when provided"- (let [body (#'anthropic/build-request-body {:model "claude-sonnet-4-5-20250929"- :system "You are a SQL expert"- :messages [{:role "user" :content "test"}]})]- (is (= "You are a SQL expert" (:system body)))))- (testing "omits system when not provided"- (let [body (#'anthropic/build-request-body {:model "claude-sonnet-4-5-20250929"- :messages [{:role "user" :content "test"}]})]- (is (not (contains? body :system))))))--;;; ------------------------------------------- generate-sql-tool Tests ---------------------------------------------(deftest ^:parallel generate-sql-tool-test- (testing "tool definition has correct structure"- (let [tool @#'anthropic/generate-sql-tool]- (is (= "generate_sql" (:name tool)))- (is (string? (:description tool)))- (is (= "object" (get-in tool [:input_schema :type])))- (is (contains? (get-in tool [:input_schema :properties]) :sql))- (is (= ["sql"] (get-in tool [:input_schema :required]))))))--;;; ------------------------------------------- chat-completion Tests ---------------------------------------------(deftest chat-completion-not-configured-test- (testing "throws when API key not configured"- (mt/with-dynamic-fn-redefs [llm.settings/llm-anthropic-api-key (constantly nil)]- (is (thrown-with-msg?- clojure.lang.ExceptionInfo- #"not configured"- (anthropic/chat-completion {:messages [{:role "user" :content "test"}]}))))))--(deftest chat-completion-e2e-localhost-safeguard-test- (testing "during e2e tests, refuses a non-localhost base URL before making any request"- (with-redefs [config/is-e2e? true]- (mt/with-temporary-setting-values [llm-anthropic-api-key "sk-ant-test-key"- llm-anthropic-api-base-url "https://api.anthropic.com"]- (mt/with-dynamic-fn-redefs [http/post (fn [& _] (throw (ex-info "http/post should not be called" {})))]- (is (thrown-with-msg?- clojure.lang.ExceptionInfo- #"non-localhost"- (anthropic/chat-completion {:messages [{:role "user" :content "test"}]})))))))- (testing "during e2e tests, a localhost base URL is allowed through to the request"- (let [mock-response {:body {:content [{:type "tool_use" :name "generate_sql" :input {:sql "SELECT 1"}}]- :usage {:input_tokens 1 :output_tokens 1}}}]- (with-redefs [config/is-e2e? true]- ;; the e2e runner pins the network policy the same way, since the mock LLM server is on localhost- (mt/with-temp-env-var-value! [mb-llm-allowed-networks "allow-all"]- (mt/with-temporary-setting-values [llm-anthropic-api-key "sk-ant-test-key"- llm-anthropic-api-base-url "http://localhost:6123"]- (mt/with-dynamic-fn-redefs [http/post (constantly mock-response)]- (is (=? {:result {:sql "SELECT 1"}}- (anthropic/chat-completion {:messages [{:role "user" :content "test"}]}))))))))))--(deftest chat-completion-network-policy-test- (testing "a base URL on a network llm-allowed-networks forbids is refused when the connection resolves it"- ;; the URL is redefined rather than set, the way one saved before the policy was tightened would be stored;- ;; the mock stands in for clj-http far enough to run the request's `:dns-resolver` on the host- (mt/with-temp-env-var-value! [mb-llm-allowed-networks "external-only"]- (mt/with-dynamic-fn-redefs [llm.settings/llm-anthropic-api-key (constantly "sk-ant-test-key")- llm.settings/llm-anthropic-api-base-url (constantly "http://127.0.0.1:9")- http/post (fn [url opts]- (.resolve ^org.apache.http.conn.DnsResolver (:dns-resolver opts)- (u.http/->hostname url))- (is false "the resolver should have refused the address"))]- (is (=? {:status-code 400 :status 400 :error-code :llm-host-not-allowed :llm-host "127.0.0.1"}- (try (anthropic/chat-completion {:messages [{:role "user" :content "test"}]})- (catch clojure.lang.ExceptionInfo e (ex-data e))))))))- (testing "a permitted base URL goes out with the policy-enforcing DNS resolver on the connection"- (let [captured (atom nil)- mock-response {:body {:content [{:type "tool_use" :name "generate_sql" :input {:sql "SELECT 1"}}]- :usage {:input_tokens 1 :output_tokens 1}}}]- (mt/with-temp-env-var-value! [mb-llm-allowed-networks "external-only"]- (mt/with-temporary-setting-values [llm-anthropic-api-key "sk-ant-test-key"- llm-anthropic-api-base-url "https://8.8.8.8"]- (mt/with-dynamic-fn-redefs [http/post (fn [_url opts] (reset! captured opts) mock-response)]- (is (=? {:result {:sql "SELECT 1"}}- (anthropic/chat-completion {:messages [{:role "user" :content "test"}]})))- (is (= :none (:redirect-strategy @captured)))- (is (instance? org.apache.http.conn.DnsResolver (:dns-resolver @captured))))))- (testing "a connection-time DNS policy rejection has the same 400 shape as the upfront check"- (mt/with-temp-env-var-value! [mb-llm-allowed-networks "external-only"]- (mt/with-temporary-setting-values [llm-anthropic-api-key "sk-ant-test-key"- llm-anthropic-api-base-url "https://8.8.8.8"]- (mt/with-dynamic-fn-redefs [http/post (fn [& _] (throw (ex-info "blocked" {:ssrf true})))]- (is (=? {:status-code 400 :api-error true :error-code :llm-host-not-allowed}- (try (anthropic/chat-completion {:messages [{:role "user" :content "test"}]})- (catch clojure.lang.ExceptionInfo e (ex-data e)))))))))- (testing "and under :allow-all on clj-http's default resolver"- (mt/with-temp-env-var-value! [mb-llm-allowed-networks "allow-all"]- (mt/with-temporary-setting-values [llm-anthropic-api-key "sk-ant-test-key"- llm-anthropic-api-base-url "http://127.0.0.1:9"]- (mt/with-dynamic-fn-redefs [http/post (fn [_url opts] (reset! captured opts) mock-response)]- (anthropic/chat-completion {:messages [{:role "user" :content "test"}]})- (is (not (contains? @captured :dns-resolver))))))))))--(deftest chat-completion-returns-usage-test- (testing "chat-completion returns result, usage, and duration"- (let [mock-response {:body {:id "msg_123"- :model "claude-sonnet-4-5-20250929"- :content [{:type "tool_use"- :id "tool_123"- :name "generate_sql"- :input {:sql "SELECT * FROM users"- :explanation "Fetches all users"}}]- :usage {:input_tokens 1500- :output_tokens 250}}}]- (mt/with-temporary-setting-values [llm-anthropic-api-key "sk-ant-test-key"- llm-anthropic-model "claude-sonnet-4-5-20250929"]- (mt/with-dynamic-fn-redefs [http/post (constantly mock-response)]- (let [result (anthropic/chat-completion {:system "You are a SQL expert"- :messages [{:role "user" :content "get all users"}]})]- (is (=? {:result {:sql "SELECT * FROM users"- :explanation "Fetches all users"}- :duration-ms #(and (number? %) (pos? %))- :usage {:model "claude-sonnet-4-5-20250929"- :prompt 1500- :completion 250}}- result))))))))diff --git a/test/metabase/llm/api_test.clj b/test/metabase/llm/api_test.cljindex f12875673b1..5c7fa631d51 100644--- a/test/metabase/llm/api_test.clj+++ b/test/metabase/llm/api_test.clj@@ -1,134 +1,10 @@(ns metabase.llm.api-test(:require- [clojure.set :as set]- [clojure.string :as str][clojure.test :refer :all]- [metabase.analytics.snowplow-test :as snowplow-test]- [metabase.llm.anthropic :as llm.anthropic]- [metabase.llm.api :as api]- [metabase.llm.context :as llm.context]- [metabase.llm.settings :as llm.settings][metabase.test :as mt]))(set! *warn-on-reflection* true)-;;; ------------------------------------------- database-dialect Tests ---------------------------------------------(deftest database-engine-test- (mt/with-temp [:model/Database postgres-db {:engine :postgres}- :model/Database mysql-db {:engine :mysql}- :model/Database bigquery-db {:engine :bigquery}]- (testing "returns engine keyword for database"- (is (= :postgres (#'api/database-engine (:id postgres-db))))- (is (= :mysql (#'api/database-engine (:id mysql-db))))- (is (= :bigquery (#'api/database-engine (:id bigquery-db)))))- (testing "nil database returns nil"- (is (nil? (#'api/database-engine nil))))- (testing "non-existent database returns nil"- (is (nil? (#'api/database-engine 99999999))))))--;;; ------------------------------------------- load-dialect-instructions Tests ---------------------------------------------(deftest load-dialect-instructions-test- (testing "known engine with file returns content"- (let [instructions (#'api/load-dialect-instructions :postgres)]- (is (string? instructions))- (is (str/includes? instructions "PostgreSQL"))))- (testing "nil engine returns nil"- (is (nil? (#'api/load-dialect-instructions nil)))))--;;; ------------------------------------------- Table ID extraction Tests ---------------------------------------------(deftest extract-frontend-table-ids-test- (testing "extracts table IDs from referenced_entities"- (let [entities [{:model "table" :id 1}- {:model "table" :id 2}- {:model "card" :id 999}- {:model "table" :id 3}]]- (is (= #{1 2 3}- (->> entities- (filter #(= "table" (:model %)))- (map :id)- set)))))- (testing "returns empty set for empty input"- (is (= #{}- (->> []- (filter #(= "table" (:model %)))- (map :id)- set))))- (testing "returns empty set when no tables present"- (let [entities [{:model "card" :id 1}- {:model "question" :id 2}]]- (is (= #{}- (->> entities- (filter #(= "table" (:model %)))- (map :id)- set))))))--(deftest table-id-union-test- (testing "all sources merged via set union"- (let [frontend #{1 2}- explicit #{2 3}- implicit #{3 4}]- (is (= #{1 2 3 4}- (set/union (or frontend #{})- (or explicit #{})- (or implicit #{}))))))- (testing "nil sources treated as empty sets"- (is (= #{1 2}- (set/union (or nil #{})- (or #{1 2} #{})- (or nil #{}))))))--;;; ------------------------------------------- Integration with context Tests ---------------------------------------------(deftest table-mention-parsing-integration-test- (testing "explicit mentions parsed from prompt"- (let [prompt "Join [Orders](metabase://table/123) with [Users](metabase://table/456)"]- (is (= #{123 456}- (llm.context/parse-table-mentions prompt)))))- (testing "multiple mentions of same table deduplicated"- (let [prompt "[Orders](metabase://table/123) and again [Orders](metabase://table/123)"]- (is (= #{123}- (llm.context/parse-table-mentions prompt))))))--;;; ------------------------------------------- build-system-prompt Tests ---------------------------------------------(deftest build-system-prompt-test- (testing "builds prompt with required parameters"- (let [prompt (#'api/build-system-prompt {:dialect "PostgreSQL"- :schema-ddl "CREATE TABLE users (id INTEGER);"})]- (is (string? prompt))- (is (str/includes? prompt "PostgreSQL"))- (is (str/includes? prompt "CREATE TABLE users"))))- (testing "includes dialect instructions when provided"- (let [prompt (#'api/build-system-prompt {:dialect "PostgreSQL"- :schema-ddl "CREATE TABLE users (id INTEGER);"- :dialect-instructions "Use LIMIT instead of TOP"})]- (is (str/includes? prompt "Use LIMIT instead of TOP"))))- (testing "includes source SQL when provided"- (let [prompt (#'api/build-system-prompt {:dialect "PostgreSQL"- :schema-ddl "CREATE TABLE users (id INTEGER);"- :source-sql "SELECT * FROM users"})]- (is (str/includes? prompt "SELECT * FROM users")))))--;;; ------------------------------------------- Error handling Tests ---------------------------------------------(deftest generate-sql-error-handling-test- (mt/with-temp [:model/Database db {:engine :postgres}]- (testing "403 when LLM not configured"- (mt/with-dynamic-fn-redefs [llm.settings/llm-anthropic-api-key (constantly nil)]- (let [response (mt/user-http-request :rasta :post 403 "llm/generate-sql"- {:prompt "test"- :database_id (:id db)})]- (is (str/includes? (str response) "not configured")))))- (testing "400 when no tables found"- (mt/with-dynamic-fn-redefs [llm.settings/llm-anthropic-api-key (constantly "sk-ant-test")]- (let [response (mt/user-http-request :rasta :post 400 "llm/generate-sql"- {:prompt "no table mentions here"- :database_id (:id db)})]- (is (str/includes? (str response) "No tables found")))))))-(deftest extract-sources-test(testing "POST /api/llm/extract-sources returns SQL tables and native card/model references"(mt/with-temp [:model/Database db {:engine :h2}@@ -175,79 +51,3 @@:sql "SELECT * FROM orders":template_tags {"#model" {:type "card":card-id (:id model)}}})))))))--;;; ------------------------------------------- Snowplow Tests ---------------------------------------------(defn- token-usage-event? [event]- (-> event- :data- (contains? "total_tokens")))--(defn- simple-event? [event]- (-> event- :data- (get "event")- (some-> (str/starts-with? "metabot_"))))--(deftest generate-sql-snowplow-success-test- (testing "successful /generate-sql call tracks both token_usage and simple_event"- (mt/with-temp [:model/Database db {:engine :postgres}- :model/Table table {:db_id (:id db) :name "users" :schema "public"}- :model/Field _ {:table_id (:id table) :name "id" :base_type :type/Integer}- :model/Field _ {:table_id (:id table) :name "name" :base_type :type/Text}]- (let [mock-chat-response {:result {:sql "SELECT * FROM users"}- :usage {:model "claude-sonnet-4-5-20250929"- :prompt 1000- :completion 200}- :duration-ms 500}]- (snowplow-test/with-fake-snowplow-collector- (mt/with-dynamic-fn-redefs [llm.settings/llm-anthropic-api-key (constantly "sk-ant-test")- llm.anthropic/chat-completion (constantly mock-chat-response)]- (let [response (mt/user-http-request :rasta :post 200 "llm/generate-sql"- {:prompt "get all users"- :database_id (:id db)- :referenced_entities [{:model "table" :id (:id table)}]})- events (snowplow-test/pop-event-data-and-user-id!)- token-events (filter token-usage-event? events)- simple-events (filter simple-event? events)]- (is (= "SELECT * FROM users" (:sql response)))- (testing "token_usage event"- (is (=? [{:data {"model_id" "claude-sonnet-4-5-20250929"- "prompt_tokens" 1000- "completion_tokens" 200- "total_tokens" 1200- "estimated_costs_usd" 0.0- "duration_ms" 500- "source" "oss_metabot"- "tag" "oss-sqlgen"}}]- token-events)))- (testing "simple_event"- (is (=? [{:data {"event" "metabot_oss_sqlgen_used"- "duration_ms" int?- "result" "success"- "event_detail" "postgres"}}]- simple-events))))))))))--(deftest generate-sql-snowplow-failure-test- (testing "failed /generate-sql call tracks simple_event with failure result"- (mt/with-temp [:model/Database db {:engine :postgres}- :model/Table table {:db_id (:id db) :name "users" :schema "public"}- :model/Field _ {:table_id (:id table) :name "id" :base_type :type/Integer}]- (snowplow-test/with-fake-snowplow-collector- (mt/with-dynamic-fn-redefs [llm.settings/llm-anthropic-api-key (constantly "sk-ant-test")- llm.anthropic/chat-completion (fn [_] (throw (Exception. "API error")))]- (mt/user-http-request :rasta :post 500 "llm/generate-sql"- {:prompt "get all users"- :database_id (:id db)- :referenced_entities [{:model "table" :id (:id table)}]})- (let [events (snowplow-test/pop-event-data-and-user-id!)- token-events (filter token-usage-event? events)- simple-events (filter simple-event? events)]- (testing "no token_usage event on failure (chat-completion call failed)"- (is (empty? token-events)))- (testing "simple_event with failure result"- (is (=? [{:data {"event" "metabot_oss_sqlgen_used"- "duration_ms" int?- "result" "failure"- "event_detail" "postgres"}}]- simple-events)))))))))diff --git a/test/metabase/llm/context_test.clj b/test/metabase/llm/context_test.cljindex ec9f70bdba8..cdc66a0688f 100644--- a/test/metabase/llm/context_test.clj+++ b/test/metabase/llm/context_test.clj@@ -3,293 +3,12 @@[clojure.string :as str][clojure.test :refer :all][metabase.llm.context :as context]- [metabase.parameters.field-values :as params.field-values][metabase.permissions.core :as perms][metabase.permissions.models.permissions-group :as perms-group]- [metabase.test :as mt]- [toucan2.core :as t2]))+ [metabase.test :as mt]))(set! *warn-on-reflection* true)-;;; ------------------------------------------- parse-table-mentions Tests ---------------------------------------------(deftest parse-table-mentions-test- (testing "extracts single table ID"- (is (= #{42}- (context/parse-table-mentions "Show [Orders](metabase://table/42)"))))- (testing "extracts multiple table IDs"- (is (= #{42 15}- (context/parse-table-mentions- "Join [Orders](metabase://table/42) with [Products](metabase://table/15)"))))- (testing "handles no mentions"- (is (= #{} (context/parse-table-mentions "Show me all sales"))))- (testing "handles nil input"- (is (nil? (context/parse-table-mentions nil))))- (testing "handles empty string"- (is (= #{} (context/parse-table-mentions ""))))- (testing "ignores malformed mentions - invalid ID"- (is (= #{42}- (context/parse-table-mentions- "[Valid](metabase://table/42) [Invalid](metabase://table/abc)"))))- (testing "handles display names with special characters"- (is (= #{123}- (context/parse-table-mentions- "[Order's & Items](metabase://table/123)"))))- (testing "handles multiple mentions of same table (returns set)"- (is (= #{42}- (context/parse-table-mentions- "[Orders](metabase://table/42) and also [Orders Table](metabase://table/42)"))))- (testing "handles text before and after mentions"- (is (= #{1 2}- (context/parse-table-mentions- "Please show me data from [Users](metabase://table/1) joined with [Orders](metabase://table/2) filtered by date")))))--;;; ------------------------------------------ DDL Formatting Tests --------------------------------------------(deftest format-schema-ddl-test- (testing "formats simple table"- (let [tables [{:name "users" :schema nil :columns [{:name "id" :database_type "INTEGER"}]}]- result (#'context/format-schema-ddl tables)]- (is (= "CREATE TABLE users (\n id INTEGER\n);" result))))- (testing "formats table with schema"- (let [tables [{:name "users" :schema "public" :columns [{:name "id" :database_type "INTEGER"}]}]- result (#'context/format-schema-ddl tables)]- (is (= "CREATE TABLE public.users (\n id INTEGER\n);" result))))- (testing "formats table with multiple columns"- (let [tables [{:name "orders"- :schema nil- :columns [{:name "id" :database_type "INTEGER"}- {:name "total" :database_type "DECIMAL"}- {:name "created_at" :database_type "TIMESTAMP"}]}]- result (#'context/format-schema-ddl tables)]- (is (str/includes? result "id INTEGER"))- (is (str/includes? result "total DECIMAL"))- (is (str/includes? result "created_at TIMESTAMP"))))- (testing "escapes special characters in identifiers"- (let [tables [{:name "user data" :schema nil :columns [{:name "first name" :database_type "VARCHAR"}]}]- result (#'context/format-schema-ddl tables)]- (is (str/includes? result "\"user data\""))- (is (str/includes? result "\"first name\""))))- (testing "formats multiple tables"- (let [tables [{:name "users" :schema nil :columns [{:name "id" :database_type "INTEGER"}]}- {:name "orders" :schema nil :columns [{:name "id" :database_type "INTEGER"}]}]- result (#'context/format-schema-ddl tables)]- (is (str/includes? result "CREATE TABLE users"))- (is (str/includes? result "CREATE TABLE orders"))))- (testing "formats table with description"- (let [tables [{:name "orders"- :schema "public"- :description "Customer purchase transactions"- :columns [{:name "id" :database_type "INTEGER"}]}]- result (#'context/format-schema-ddl tables)]- (is (= "-- Customer purchase transactions\nCREATE TABLE public.orders (\n id INTEGER\n);" result))))- (testing "formats table without description (no comment line)"- (let [tables [{:name "orders"- :schema nil- :description nil- :columns [{:name "id" :database_type "INTEGER"}]}]- result (#'context/format-schema-ddl tables)]- (is (= "CREATE TABLE orders (\n id INTEGER\n);" result)))))--;;; ----------------------------------------- build-schema-context Tests -------------------------------------------(deftest build-schema-context-test- (mt/with-test-user :crowberto- (mt/with-temp [:model/Database db {}- :model/Table table1 {:db_id (:id db) :name "orders" :schema "public"}- :model/Field _f1 {:table_id (:id table1) :name "id" :database_type "INTEGER" :base_type :type/Integer}- :model/Field _f2 {:table_id (:id table1) :name "total" :database_type "DECIMAL" :base_type :type/Decimal}]- (testing "returns DDL for accessible tables"- (let [result (context/build-schema-context (:id db) #{(:id table1)})]- (is (some? result))- (is (str/includes? result "CREATE TABLE"))- (is (str/includes? result "orders"))- (is (str/includes? result "id"))- (is (str/includes? result "total"))))- (testing "returns nil for empty table-ids"- (is (nil? (context/build-schema-context (:id db) #{}))))- (testing "returns nil for nil table-ids"- (is (nil? (context/build-schema-context (:id db) nil))))- (testing "returns nil for nil database-id"- (is (nil? (context/build-schema-context nil #{(:id table1)}))))- (testing "returns nil for non-existent tables"- (is (nil? (context/build-schema-context (:id db) #{99999})))))))--(deftest build-schema-context-multiple-tables-test- (mt/with-test-user :crowberto- (mt/with-temp [:model/Database db {}- :model/Table t1 {:db_id (:id db) :name "users" :schema "public"}- :model/Field _f1 {:table_id (:id t1) :name "id" :database_type "INTEGER" :base_type :type/Integer}- :model/Field _f2 {:table_id (:id t1) :name "email" :database_type "VARCHAR" :base_type :type/Text}- :model/Table t2 {:db_id (:id db) :name "orders" :schema "public"}- :model/Field _f3 {:table_id (:id t2) :name "id" :database_type "INTEGER" :base_type :type/Integer}- :model/Field _f4 {:table_id (:id t2) :name "user_id" :database_type "INTEGER" :base_type :type/Integer}]- (testing "returns DDL for multiple tables"- (let [result (context/build-schema-context (:id db) #{(:id t1) (:id t2)})]- (is (some? result))- (is (str/includes? result "users"))- (is (str/includes? result "orders"))- (is (str/includes? result "email"))- (is (str/includes? result "user_id")))))))--;;; ----------------------------------------- Fingerprint Formatting Tests -------------------------------------------(deftest format-numeric-stats-test- (testing "formats integer range"- (is (= "range: 1-100, avg: 50"- (#'context/format-numeric-stats {:min 1 :max 100 :avg 50}))))- (testing "formats decimal range"- (is (= "range: 0.00-999.99, avg: 127.50"- (#'context/format-numeric-stats {:min 0.0 :max 999.99 :avg 127.5}))))- (testing "handles missing avg"- (is (= "range: 0-100"- (#'context/format-numeric-stats {:min 0 :max 100}))))- (testing "returns nil when min/max missing"- (is (nil? (#'context/format-numeric-stats {:avg 50})))- (is (nil? (#'context/format-numeric-stats {})))))--(deftest format-temporal-stats-test- (testing "formats date range"- (is (= "2020-01-01 to 2024-12-31"- (#'context/format-temporal-stats {:earliest "2020-01-01T00:00:00Z"- :latest "2024-12-31T23:59:59Z"}))))- (testing "handles short date strings"- (is (= "2020-01-01 to 2024-12-31"- (#'context/format-temporal-stats {:earliest "2020-01-01"- :latest "2024-12-31"}))))- (testing "returns nil when dates missing"- (is (nil? (#'context/format-temporal-stats {:earliest "2020-01-01"})))- (is (nil? (#'context/format-temporal-stats {})))))--;;; ----------------------------------------- Column Comment Building Tests -------------------------------------------(deftest build-column-comment-test- (testing "description takes priority"- (is (= "Customer email address"- (#'context/build-column-comment- {:description "Customer email address"- :semantic_type :type/Email}- nil nil))))- (testing "sample values for category"- (is (= "active, inactive, pending"- (#'context/build-column-comment- {:semantic_type :type/Category}- ["active" "inactive" "pending"]- nil))))- (testing "FK reference"- (is (= "FK->users.id"- (#'context/build-column-comment- {:fk_target_field_id 123}- nil- {:table "users" :field "id"}))))- (testing "semantic type hints"- (is (= "PK"- (#'context/build-column-comment {:semantic_type :type/PK} nil nil)))- (is (= "Email"- (#'context/build-column-comment {:semantic_type :type/Email} nil nil))))- (testing "numeric fingerprint stats"- (is (= "range: 0-1000, avg: 127.50"- (#'context/build-column-comment- {:fingerprint {:type {:type/Number {:min 0 :max 1000 :avg 127.5}}}}- nil nil))))- (testing "temporal fingerprint stats"- (is (= "2020-01-01 to 2024-12-31"- (#'context/build-column-comment- {:fingerprint {:type {:type/DateTime {:earliest "2020-01-01T00:00:00Z"- :latest "2024-12-31T23:59:59Z"}}}}- nil nil))))- (testing "combined metadata"- (is (= "Order status; pending, shipped, delivered"- (#'context/build-column-comment- {:description "Order status"}- ["pending" "shipped" "delivered"]- nil))))- (testing "returns nil for no metadata"- (is (nil? (#'context/build-column-comment {} nil nil)))))--(deftest truncate-value-test- (testing "short values unchanged"- (is (= "active" (#'context/truncate-value "active"))))- (testing "long values truncated"- (is (= "this is a very long value t..."- (#'context/truncate-value "this is a very long value that exceeds the limit")))))--;;; ----------------------------------------- DDL with Comments Tests -------------------------------------------(deftest format-schema-ddl-with-comments-test- (testing "formats table with column comments"- (let [tables [{:name "orders"- :schema nil- :columns [{:name "id" :database_type "INTEGER" :comment "PK"}- {:name "status" :database_type "VARCHAR" :comment "pending, shipped, delivered"}- {:name "total" :database_type "DECIMAL" :comment "range: 0-9999.99"}]}]- result (#'context/format-schema-ddl tables)]- (is (str/includes? result "-- PK"))- (is (str/includes? result "-- pending, shipped, delivered"))- (is (str/includes? result "-- range: 0-9999.99"))- (is (str/includes? result "id INTEGER"))- (is (str/includes? result "status VARCHAR"))- (is (str/includes? result "total DECIMAL"))))- (testing "formats table with mixed commented and non-commented columns"- (let [tables [{:name "users"- :schema nil- :columns [{:name "id" :database_type "INTEGER" :comment "PK"}- {:name "name" :database_type "VARCHAR"}- {:name "email" :database_type "VARCHAR" :comment "email"}]}]- result (#'context/format-schema-ddl tables)]- (is (str/includes? result "-- PK"))- (is (str/includes? result "-- email"))- (is (str/includes? result "id INTEGER"))- (is (str/includes? result "name VARCHAR"))- (is (str/includes? result "email VARCHAR"))))- (testing "formats table without any comments (backward compatible)"- (let [tables [{:name "simple"- :schema nil- :columns [{:name "a" :database_type "INT"}- {:name "b" :database_type "TEXT"}]}]- result (#'context/format-schema-ddl tables)]- (is (= "CREATE TABLE simple (\n a INT,\n b TEXT\n);" result)))))--;;; ----------------------------------------- Enriched Context Integration Tests -------------------------------------------(deftest build-schema-context-with-description-test- (mt/with-test-user :crowberto- (mt/with-temp [:model/Database db {}- :model/Table table {:db_id (:id db) :name "products" :schema "public"}- :model/Field _f1 {:table_id (:id table)- :name "id"- :database_type "INTEGER"- :base_type :type/Integer- :semantic_type :type/PK}- :model/Field _f2 {:table_id (:id table)- :name "name"- :database_type "VARCHAR"- :base_type :type/Text- :description "Product display name"}]- (testing "includes field description in DDL comments"- (let [result (context/build-schema-context (:id db) #{(:id table)})]- (is (some? result))- (is (str/includes? result "products"))- (is (str/includes? result "-- Product display name")))))))--(deftest build-schema-context-with-fk-test- (mt/with-test-user :crowberto- (mt/with-temp [:model/Database db {}- :model/Table users {:db_id (:id db) :name "users" :schema "public"}- :model/Field uid {:table_id (:id users) :name "id" :database_type "INTEGER" :base_type :type/Integer}- :model/Table orders {:db_id (:id db) :name "orders" :schema "public"}- :model/Field _oid {:table_id (:id orders) :name "id" :database_type "INTEGER" :base_type :type/Integer}- :model/Field _fk {:table_id (:id orders)- :name "user_id"- :database_type "INTEGER"- :base_type :type/Integer- :semantic_type :type/FK- :fk_target_field_id (:id uid)}]- (testing "includes FK relationship in DDL comments"- (let [result (context/build-schema-context (:id db) #{(:id orders)})]- (is (some? result))- (is (str/includes? result "FK->users.id")))))))-(deftest get-tables-with-columns-hides-unreadable-fk-target-test(testing "an FK on a readable table does not reveal an unreadable target table or field"(mt/with-temp [:model/Database db {}@@ -324,77 +43,6 @@(is (not (str/includes? (pr-str result) "secret_table")))(is (not (str/includes? (pr-str result) "secret_id")))))))))-(deftest build-schema-context-with-field-values-test- (mt/with-test-user :crowberto- (mt/with-temp [:model/Database db {}- :model/Table table {:db_id (:id db) :name "orders" :schema "public"}- :model/Field field {:table_id (:id table)- :name "status"- :database_type "VARCHAR"- :base_type :type/Text- :has_field_values :list}- :model/FieldValues _fv {:field_id (:id field)- :values ["pending" "shipped" "delivered"]- :type :full}]- (testing "includes sample values in DDL comments"- (let [result (context/build-schema-context (:id db) #{(:id table)})]- (is (some? result))- (is (str/includes? result "pending"))- (is (str/includes? result "shipped"))- (is (str/includes? result "delivered")))))))--(deftest build-schema-context-with-table-description-test- (mt/with-test-user :crowberto- (mt/with-temp [:model/Database db {}- :model/Table table {:db_id (:id db)- :name "orders"- :schema "public"- :description "Customer purchase transactions"}- :model/Field _f1 {:table_id (:id table)- :name "id"- :database_type "INTEGER"- :base_type :type/Integer}]- (testing "includes table description as comment above CREATE TABLE"- (let [result (context/build-schema-context (:id db) #{(:id table)})]- (is (some? result))- (is (str/includes? result "-- Customer purchase transactions"))- (is (str/includes? result "CREATE TABLE")))))))--(deftest build-schema-context-constrains-tables-to-requested-database-test- (mt/with-test-user :crowberto- (mt/with-temp [:model/Database other-db {}- :model/Table other-table {:db_id (:id other-db) :name "secret" :schema "public"}- :model/Field _of {:table_id (:id other-table)- :name "id"- :database_type "INTEGER"- :base_type :type/Integer}- :model/Database db {}- :model/Table table {:db_id (:id db) :name "orders" :schema "public"}- :model/Field _f {:table_id (:id table)- :name "id"- :database_type "INTEGER"- :base_type :type/Integer}]- (testing "a table ID from a different database is not included in the DDL, even though the user can read it"- (let [{:keys [ddl tables]} (context/build-schema-context (:id db) #{(:id table) (:id other-table)})]- (is (str/includes? ddl "orders"))- (is (not (str/includes? ddl "secret")))- (is (= [(:id table)] (map :id tables)))))- (testing "requesting only the other database's table returns nil (no accessible tables in the requested db)"- (is (nil? (context/build-schema-context (:id db) #{(:id other-table)})))))))--(deftest build-schema-context-requires-database-read-access-test- (mt/with-temp [:model/Database db {}- :model/Table table {:db_id (:id db) :name "orders" :schema "public"}- :model/Field _f {:table_id (:id table)- :name "id"- :database_type "INTEGER"- :base_type :type/Integer}]- (mt/with-no-data-perms-for-all-users!- (mt/with-test-user :rasta- (testing "a user with no access to the database is denied, rather than silently returning nil"- (is (thrown-with-msg? clojure.lang.ExceptionInfo #"You don't have permissions to do that\."- (context/build-schema-context (:id db) #{(:id table)}))))))))-(deftest get-tables-with-columns-does-not-require-database-read-access-test(mt/with-temp [:model/Database db {}:model/Table table {:db_id (:id db) :name "orders" :schema "public"}@@ -405,68 +53,10 @@(mt/with-no-data-perms-for-all-users!(mt/with-test-user :rasta(testing "a user with no access to the database gets an empty result, rather than a hard 403 -- this- endpoint (POST /api/llm/extract-sources) shares fetch-accessible-tables-with-columns with- build-schema-context, but must not deny its :card_ids behavior over unrelated table access- (that 403 belongs to generate-sql, see build-schema-context-requires-database-read-access-test)"+ endpoint (POST /api/llm/extract-sources) must not deny its :card_ids behavior over unrelated+ table access"(is (nil? (context/get-tables-with-columns (:id db) #{(:id table)}))))))))-(deftest fetch-field-values-caps-restricted-columns-test- (testing "columns of a row-restricted table are capped at max-restricted-field-values-fetches per request;- columns of an unrestricted table are not capped"- (mt/with-temp [:model/Database db {}- :model/Table restricted-table {:db_id (:id db)}- :model/Table open-table {:db_id (:id db)}]- (let [field-defs (fn [table n prefix]- (for [i (range n)]- {:table_id (:id table) :name (str prefix i) :database_type "VARCHAR"- :base_type :type/Text :has_field_values :list}))- restricted-fields (t2/insert-returning-instances!- :model/Field (field-defs restricted-table 40 "r"))- open-fields (t2/insert-returning-instances!- :model/Field (field-defs open-table 3 "o"))- columns (fn [fields table-id]- (mapv (fn [f] {:id (:id f) :table-id table-id}) fields))- all-columns (into (columns restricted-fields (:id restricted-table))- (columns open-fields (:id open-table)))- calls (atom 0)]- (try- (mt/with-dynamic-fn-redefs [params.field-values/get-or-create-field-values!- (fn [_field] (swap! calls inc) nil)]- (#'context/fetch-field-values all-columns #{(:id restricted-table)}))- (is (= (+ 3 @#'context/max-restricted-field-values-fetches) @calls)- "3 unrestricted + the restricted cap, not all 40 restricted columns")- (finally- (t2/delete! :model/Field :id [:in (map :id (concat restricted-fields open-fields))])))))))--(deftest fetch-field-values-applies-cap-after-eligibility-filter-test- (testing "the restricted-table cap is applied after narrowing to fields that should have FieldValues,- so ineligible fields ahead of an eligible one can't consume its budget"- (mt/with-temp [:model/Database db {}- :model/Table restricted-table {:db_id (:id db)}]- (let [ineligible-fields (t2/insert-returning-instances!- :model/Field- (for [i (range (inc @#'context/max-restricted-field-values-fetches))]- {:table_id (:id restricted-table) :name (str "ineligible" i)- :database_type "TEXT" :base_type :type/Text- :has_field_values :none}))- eligible-field (first (t2/insert-returning-instances!- :model/Field- [{:table_id (:id restricted-table) :name "eligible"- :database_type "VARCHAR" :base_type :type/Text- :has_field_values :list}]))- all-columns (mapv (fn [f] {:id (:id f) :table-id (:id restricted-table)})- (concat ineligible-fields [eligible-field]))- calls (atom 0)]- (try- (mt/with-dynamic-fn-redefs [params.field-values/get-or-create-field-values!- (fn [_field] (swap! calls inc) nil)]- (#'context/fetch-field-values all-columns #{(:id restricted-table)}))- (is (= 1 @calls)- "only the one eligible field is fetched -- the ineligible fields ahead of it in the raw- column list didn't consume its slot in the cap")- (finally- (t2/delete! :model/Field :id [:in (map :id (conj ineligible-fields eligible-field))])))))))-;;; ----------------------------------------- extract-tables-from-sql Tests -----------------------------------------(deftest extract-tables-from-sql-testdiff --git a/test/metabase/llm/settings_test.clj b/test/metabase/llm/settings_test.cljindex e7da5d609ba..9115f9a1689 100644--- a/test/metabase/llm/settings_test.clj+++ b/test/metabase/llm/settings_test.clj@@ -62,16 +62,6 @@(mt/with-temp-env-var-value! [mb-llm-anthropic-api-base-url "https://env-only.example"](is (= "https://env-only.example" (llm.settings/llm-anthropic-api-base-url)))))))-;;; ------------------------------------------- llm-anthropic-api-key Tests ---------------------------------------------(deftest llm-anthropic-api-key-configured?-test- (testing "returns false when no API key is set"- (mt/with-dynamic-fn-redefs [llm.settings/llm-anthropic-api-key (constantly nil)]- (is (false? (llm.settings/llm-anthropic-api-key-configured?)))))- (testing "returns true when API key is set"- (mt/with-temporary-setting-values [llm-anthropic-api-key "sk-ant-test"]- (is (true? (llm.settings/llm-anthropic-api-key-configured?))))))-;;; ------------------------------------------- Google credential validation -------------------------------------------(deftest valid-google-project-id?-test@@ -431,22 +421,6 @@(mt/with-temporary-setting-values [llm-connection-timeout-ms 3000](is (= 3000 (llm.settings/llm-connection-timeout-ms))))))-(deftest llm-rate-limit-per-user-test- (testing "default value is 20 requests per minute"- (mt/with-temporary-setting-values [llm-rate-limit-per-user nil]- (is (= 20 (llm.settings/llm-rate-limit-per-user)))))- (testing "can be overridden"- (mt/with-temporary-setting-values [llm-rate-limit-per-user 50]- (is (= 50 (llm.settings/llm-rate-limit-per-user))))))--(deftest llm-rate-limit-per-ip-test- (testing "default value is 100 requests per minute"- (mt/with-temporary-setting-values [llm-rate-limit-per-ip nil]- (is (= 100 (llm.settings/llm-rate-limit-per-ip)))))- (testing "can be overridden"- (mt/with-temporary-setting-values [llm-rate-limit-per-ip 200]- (is (= 200 (llm.settings/llm-rate-limit-per-ip))))))-(deftest llm-allowed-networks-startup-validation-test(testing "a policy the environment names but Metabase does not recognize stops the boot, rather than waitingfor the first LLM request to discover it"