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
clean up references to ai-service (#71353)
Oleksandr Solovyov311b735ae5d3
diff --git a/.clj-kondo/config/modules/config.edn b/.clj-kondo/config/modules/config.ednindex 3a6c3a8bf31..75cf6a00e27 100644--- a/.clj-kondo/config/modules/config.edn+++ b/.clj-kondo/config/modules/config.edn@@ -147,6 +147,7 @@:friends #{enterprise/agent-api}:uses #{apiauth-identity+ libmetabotquery-processorrequest@@ -1210,8 +1211,6 @@{:team "Metabot":api #{metabase.metabot.apimetabase.metabot.api.entity-analysis- metabase.metabot.api.sql-fixer- metabase.metabot.api.sql-generationmetabase.metabot.init}:friends #{agent-apienterprise/metabot@@ -1228,7 +1227,6 @@documentsdriverinternal-stats- legacy-mbqlliblib-bellmdiff --git a/.gitignore b/.gitignoreindex abe9ff231dd..141d4f3f114 100644--- a/.gitignore+++ b/.gitignore@@ -96,7 +96,7 @@ coverage-summary.jsonjunit.xmlpom.xmlpom.xml.asc-profiles.clj+/profiles.cljtarget/checksum.txtxcshareddataxcuserdatadiff --git a/e2e/test/scenarios/native/ai-sql-fixer.cy.spec.ts b/e2e/test/scenarios/native/ai-sql-fixer.cy.spec.tsdeleted file mode 100644index 6cdf18656d5..00000000000--- a/e2e/test/scenarios/native/ai-sql-fixer.cy.spec.ts+++ /dev/null@@ -1,44 +0,0 @@-import { SAMPLE_DB_ID } from "e2e/support/cypress_data";--const { H } = cy;--describe("scenarios > native > ai sql fixer", () => {- beforeEach(() => {- H.resetSnowplow();- H.restore();- cy.signInAsAdmin();- H.enableTracking();- H.activateToken("bleeding-edge");- });-- afterEach(() => {- H.expectNoBadSnowplowEvents();- });-- it("should be able to fix SQL with AI", () => {- H.visitQuestionAdhoc({- display: "table",- dataset_query: {- database: SAMPLE_DB_ID,- type: "native",- native: {- query: "SELECT1",- },- },- });- cy.findByTestId("query-visualization-root").within(() => {- cy.button(/Have Metabot fix it/).click();- });-- H.expectUnstructuredSnowplowEvent({- event: "metabot_fix_query_clicked",- });-- // TODO: Unskip this part once we have the means to run AI in CI- // cy.findByTestId("metabot-chat-messages").should(- // "contain",- // "Fix this SQL query",- // );- // H.NativeEditor.get().should("be.visible").and("contain", "SELECT 1");- });-});diff --git a/enterprise/backend/src/metabase_enterprise/metabot/tools/api.clj b/enterprise/backend/src/metabase_enterprise/metabot/tools/api.cljdeleted file mode 100644index 131e30b75d6..00000000000--- a/enterprise/backend/src/metabase_enterprise/metabot/tools/api.clj+++ /dev/null@@ -1,126 +0,0 @@-(ns metabase-enterprise.metabot.tools.api- "EE-only metabot tool endpoints for transforms and dependencies."- (:require- [clojure.set :as set]- [metabase-enterprise.metabot.tools.dependencies :as metabot.tools.dependencies]- [metabase-enterprise.metabot.tools.transforms-write :as metabot.tools.transforms-write]- [metabase.metabot.tools.deftool :refer [deftool]]- [metabase.metabot.tools.transforms :as metabot.tools.transforms]- [metabase.metabot.util :as metabot.u]- [metabase.util.malli.registry :as mr]- [metabase.util.malli.schema :as ms]))--;;; ------------------------------------------------ Transform Schemas --------------------------------------------------(mr/def ::basic-transform- [:map- {:decode/tool-api-response #(update-keys % metabot.u/safe->snake_case_en)}- [:id :int]- [:name :string]- [:type [:enum {:decode/tool-api-response name} "mbql" "native" "python"]]- [:description {:optional true} [:maybe :string]]- [:entity_id {:optional true} [:maybe :string]]- ;; :source keys are not snake_cased to match what the FE expects / provides in user_is_viewing context- [:source ::metabot.tools.transforms/transform-source]])--(mr/def ::full-transform- [:merge- ::basic-transform- [:map {:decode/tool-api-response #(update-keys % metabot.u/safe->snake_case_en)}- [:created_at ms/TemporalString]- [:updated_at ms/TemporalString]- ;; :target keys are not snake_cased to match what the FE expects / provides in user_is_viewing context- [:target ::metabot.tools.transforms/transform-target]]])--;;; ------------------------------------------------ Transform Tools ----------------------------------------------------(mr/def ::get-transforms-result- [:or- [:map- {:decode/tool-api-response #(update-keys % metabot.u/safe->snake_case_en)}- [:structured_output [:sequential ::basic-transform]]]- [:map [:output :string]]])--(deftool "/get-transforms"- "Get a list of all known transforms."- {:result-schema ::get-transforms-result- :handler metabot.tools.transforms/get-transforms})--(mr/def ::get-transform-details-arguments- [:and- [:map- [:transform_id :int]]- [:map {:encode/tool-api-request- #(set/rename-keys % {:transform_id :transform-id})}]])--(mr/def ::get-transform-details-result- [:or- [:map {:decode/tool-api-response #(update-keys % metabot.u/safe->snake_case_en)}- [:structured_output [:sequential ::full-transform]]]- [:map [:output :string]]])--(deftool "/get-transform-details"- "Get information about a transform."- {:args-schema ::get-transform-details-arguments- :result-schema ::get-transform-details-result- :handler metabot.tools.transforms/get-transform-details})--(mr/def ::get-transform-python-library-details-arguments- [:and- [:map- [:path :string]]- [:map {:encode/tool-api-request- #(update-keys % metabot.u/safe->kebab-case-en)}]])--(mr/def ::get-transform-python-library-details-result- [:or- [:map {:decode/tool-api-response #(update-keys % metabot.u/safe->snake_case_en)}- [:structured_output [:map {:decode/tool-api-response #(update-keys % metabot.u/safe->snake_case_en)}- [:source :string]- [:path :string]- [:created_at ms/TemporalString]- [:updated_at ms/TemporalString]]]]- [:map [:output :string]]])--(deftool "/get-transform-python-library-details"- "Get information about a Python library by path."- {:args-schema ::get-transform-python-library-details-arguments- :result-schema ::get-transform-python-library-details-result- :handler metabot.tools.transforms-write/get-transform-python-library-details})--;;; --------------------------------------------- Dependency Tools ------------------------------------------------------(mr/def ::check-transform-dependencies-arguments- [:and- [:map- [:transform_id :int]- [:source ::metabot.tools.transforms/transform-source]]- [:map {:encode/tool-api-request- #(set/rename-keys % {:transform_id :id})}]])--(mr/def ::broken-question- [:map {:decode/tool-api-response #(update-keys % metabot.u/safe->snake_case_en)}- [:id :int]- [:name :string]])--(mr/def ::broken-transform- [:map {:decode/tool-api-response #(update-keys % metabot.u/safe->snake_case_en)}- [:id :int]- [:name :string]])--(mr/def ::check-transform-dependencies-result- [:or- [:map {:decode/tool-api-response #(update-keys % metabot.u/safe->snake_case_en)}- [:structured_output [:map- [:success :boolean]- [:bad_transform_count :int]- [:bad_transforms [:sequential ::broken-transform]]- [:bad_question_count :int]- [:bad_questions [:sequential ::broken-question]]]]]- [:map [:output :string]]])--(deftool "/check-transform-dependencies"- "Check a proposed edit to a transform and return details of cards or transforms that would be broken by the change."- {:args-schema ::check-transform-dependencies-arguments- :result-schema ::check-transform-dependencies-result- :handler metabot.tools.dependencies/check-transform-dependencies})diff --git a/enterprise/backend/src/metabase_enterprise/metabot/agent/tools/transforms.clj b/enterprise/backend/src/metabase_enterprise/metabot/tools/transforms.cljsimilarity index 90%rename from enterprise/backend/src/metabase_enterprise/metabot/agent/tools/transforms.cljrename to enterprise/backend/src/metabase_enterprise/metabot/tools/transforms.cljindex 3a2a7974d9a..350cfcac188 100644--- a/enterprise/backend/src/metabase_enterprise/metabot/agent/tools/transforms.clj+++ b/enterprise/backend/src/metabase_enterprise/metabot/tools/transforms.clj@@ -1,9 +1,9 @@-(ns metabase-enterprise.metabot.agent.tools.transforms+(ns metabase-enterprise.metabot.tools.transforms"Enterprise implementations of Python transform tools."(:require- [metabase-enterprise.metabot.tools.transforms-write :as transforms-write-tools]- [metabase.metabot.agent.tools.shared :as shared]- [metabase.metabot.agent.tools.transforms :as agent-transforms]+ [metabase-enterprise.metabot.tools.transforms.write :as transforms-write-tools]+ [metabase.metabot.tools.shared :as shared]+ [metabase.metabot.tools.transforms :as tools.transforms][metabase.metabot.util :as metabot.u][metabase.premium-features.core :refer [defenterprise-schema]]))@@ -27,7 +27,7 @@"Get information about a Python library by path.":feature :none[{:keys [path]} :- [:map {:closed true} [:path :string]]]- (agent-transforms/add-output (transforms-write-tools/get-transform-python-library-details {:path path})+ (tools.transforms/add-output (transforms-write-tools/get-transform-python-library-details {:path path})format-python-library-output))(defenterprise-schema write-transform-python-tool@@ -61,7 +61,7 @@[:source_database {:optional true} [:maybe :int]][:source_tables {:optional true} [:maybe :map]]]](try- (agent-transforms/add-output+ (tools.transforms/add-output(transforms-write-tools/write-transform-python{:transform_id transform_id:edit_action edit_action@@ -72,7 +72,7 @@:source_tables source_tables:memory-atom shared/*memory-atom*:context (shared/current-context)})- agent-transforms/format-transform-write-output)+ tools.transforms/format-transform-write-output)(catch Exception e(if (:agent-error? (ex-data e)){:output (ex-message e)}diff --git a/enterprise/backend/src/metabase_enterprise/metabot/tools/transforms_write.clj b/enterprise/backend/src/metabase_enterprise/metabot/tools/transforms/write.cljsimilarity index 97%rename from enterprise/backend/src/metabase_enterprise/metabot/tools/transforms_write.cljrename to enterprise/backend/src/metabase_enterprise/metabot/tools/transforms/write.cljindex 64c6ebe4f96..1c67850fcbf 100644--- a/enterprise/backend/src/metabase_enterprise/metabot/tools/transforms_write.clj+++ b/enterprise/backend/src/metabase_enterprise/metabot/tools/transforms/write.clj@@ -1,9 +1,9 @@-(ns metabase-enterprise.metabot.tools.transforms-write+(ns metabase-enterprise.metabot.tools.transforms.write"Tools for writing/editing Python transform source code."(:require[metabase-enterprise.transforms-python.api :as transforms-python.api][metabase.metabot.agent.streaming :as streaming]- [metabase.metabot.tools.transforms-write :as transforms-write]+ [metabase.metabot.tools.transforms.write :as transforms-write][metabase.metabot.tools.util :as metabot.tools.u][metabase.util.log :as log]))diff --git a/enterprise/backend/test/metabase_enterprise/metabot/tools/api_test.clj b/enterprise/backend/test/metabase_enterprise/metabot/tools/api_test.cljdeleted file mode 100644index d8ede0c0679..00000000000--- a/enterprise/backend/test/metabase_enterprise/metabot/tools/api_test.clj+++ /dev/null@@ -1,124 +0,0 @@-(ns metabase-enterprise.metabot.tools.api-test- "Tests for EE-only metabot tool handlers (transforms and python libraries).- These test the handler functions directly rather than via HTTP endpoints."- (:require- [clojure.test :refer :all]- [metabase-enterprise.metabot.tools.transforms-write :as metabot.tools.transforms-write]- [metabase.lib.core :as lib]- [metabase.metabot.tools.transforms :as metabot.tools.transforms]- [metabase.test :as mt]- [toucan2.core :as t2]))--(deftest get-transforms-test- (mt/with-premium-features #{:metabot-v3 :transforms-basic :transforms-python}- (mt/with-temp [:model/Transform t1 {:name "People Transform"- :description "Simple select on People table"- :source {:type "query"- :query (lib/native-query (mt/metadata-provider) "SELECT * FROM PEOPLE")}- :target {:type "table"- :name "t1_table"}}- :model/Transform t2 {:name "MBQL Transform"- :description "Simple MBQL query on Products table"- :source {:type "query"- :query (mt/mbql-query products)}- :target {:type "table"- :name "t2_table"}}- :model/Transform t3 {:name "Python Transform"- :description "Simple python transform"- :source {:type "python"- :source-database (mt/id)- :body "print('hello world')"- :source-tables []}- :target {:type "table"- :name "t3_table"}}]- (testing "Non-superuser gets 403"- (mt/with-current-user (mt/user->id :rasta)- (is (thrown-with-msg?- clojure.lang.ExceptionInfo #"You don't have permissions to do that"- (metabot.tools.transforms/get-transforms {})))))- (testing "Superuser gets native and python transforms (not plain MBQL)"- (mt/with-current-user (mt/user->id :crowberto)- (let [result (metabot.tools.transforms/get-transforms {})- test-ids #{(:id t1) (:id t2) (:id t3)}- filtered (->> (:structured_output result)- (filter #(test-ids (:id %)))- (sort-by :id))]- ;; t2 (non-native MBQL) should be excluded- (is (= (map :id filtered) [(:id t1) (:id t3)]))- (is (=? [{:id (:id t1)- :name "People Transform"- :description "Simple select on People table"}- {:id (:id t3)- :name "Python Transform"- :description "Simple python transform"}]- filtered))))))))--(deftest get-transform-details-test- (mt/with-premium-features #{:metabot-v3 :transforms-basic :transforms-python}- (mt/with-temp [:model/Transform t1 {:name "People Transform"- :description "Simple select on People table"- :source {:type "query"- :query (mt/native-query {:query "SELECT * FROM PEOPLE"})}- :target {:type "table"- :name "t1_table"}}- :model/Transform t2 {:name "Python Transform"- :description "Simple Python transform"- :source {:type "python"- :body "print('hello world')"- :source-database (mt/id)- :source-tables []}- :target {:type "table"- :name "t2_table"- :database (mt/id)}}]- (testing "Non-superuser gets 403"- (mt/with-current-user (mt/user->id :rasta)- (is (thrown-with-msg?- clojure.lang.ExceptionInfo #"You don't have permissions to do that"- (metabot.tools.transforms/get-transform-details {:transform-id (:id t1)})))))- (testing "Non-existent transform returns 404"- (mt/with-current-user (mt/user->id :crowberto)- (is (thrown-with-msg?- clojure.lang.ExceptionInfo #"Not found"- (metabot.tools.transforms/get-transform-details {:transform-id (+ 10000 (:id t2))})))))- (testing "Superuser can get transform details"- (mt/with-current-user (mt/user->id :crowberto)- (doseq [transform [t1 t2]]- (testing (:name transform)- (is (=? {:structured_output {:id (:id transform)- :name (:name transform)- :description (:description transform)- :entity_id (:entity_id transform)- :target {:name (:name (:target transform))}}}- (metabot.tools.transforms/get-transform-details {:transform-id (:id transform)}))))))))))--(deftest get-transform-python-library-details-test- (mt/with-premium-features #{:metabot-v3 :python-transforms :transforms-basic}- (let [saved-python-library (t2/select-one :model/PythonLibrary :path "common.py")]- (when (seq saved-python-library)- (t2/delete! :model/PythonLibrary))- (try- (testing "With no Python library present, throws 404"- (mt/with-current-user (mt/user->id :crowberto)- (is (thrown-with-msg?- clojure.lang.ExceptionInfo #"Not found"- (metabot.tools.transforms-write/get-transform-python-library-details {:path "common.py"})))))- (mt/with-temp [:model/PythonLibrary lib1 {:path "common.py"- :source "def hello():\n return 'world'"}]- (testing "Non-superuser gets 403"- (mt/with-current-user (mt/user->id :rasta)- (is (thrown-with-msg?- clojure.lang.ExceptionInfo #"You don't have permissions to do that"- (metabot.tools.transforms-write/get-transform-python-library-details {:path (:path lib1)})))))- (testing "Non-existent library path throws 400"- (mt/with-current-user (mt/user->id :crowberto)- (is (thrown-with-msg?- clojure.lang.ExceptionInfo #"Invalid library path"- (metabot.tools.transforms-write/get-transform-python-library-details {:path "nonexistent.py"})))))- (testing "Superuser can get library details"- (mt/with-current-user (mt/user->id :crowberto)- (is (=? {:structured_output {:source (:source lib1)- :path (:path lib1)}}- (metabot.tools.transforms-write/get-transform-python-library-details {:path (:path lib1)}))))))- (finally- (when (seq saved-python-library)- (t2/insert! :model/PythonLibrary saved-python-library)))))))diff --git a/enterprise/backend/test/metabase_enterprise/metabot/tools/transforms_write_test.clj b/enterprise/backend/test/metabase_enterprise/metabot/tools/transforms/write_test.cljsimilarity index 85%rename from enterprise/backend/test/metabase_enterprise/metabot/tools/transforms_write_test.cljrename to enterprise/backend/test/metabase_enterprise/metabot/tools/transforms/write_test.cljindex 75fe31458aa..6bfc67f1b11 100644--- a/enterprise/backend/test/metabase_enterprise/metabot/tools/transforms_write_test.clj+++ b/enterprise/backend/test/metabase_enterprise/metabot/tools/transforms/write_test.clj@@ -1,8 +1,8 @@-(ns metabase-enterprise.metabot.tools.transforms-write-test+(ns metabase-enterprise.metabot.tools.transforms.write-test(:require[clojure.test :refer :all]- [metabase-enterprise.metabot.tools.transforms-write :as transforms-write]- [metabase.metabot.tools.transforms-write :as oss-transforms-write]))+ [metabase-enterprise.metabot.tools.transforms.write :as transforms-write]+ [metabase.metabot.tools.transforms.write :as oss-transforms-write]))(deftest create-fresh-python-template-test(testing "fresh Python transforms include common import"diff --git a/frontend/src/metabase-types/api/index.ts b/frontend/src/metabase-types/api/index.tsindex cccb515753f..45aae1cb529 100644--- a/frontend/src/metabase-types/api/index.ts+++ b/frontend/src/metabase-types/api/index.ts@@ -2,7 +2,6 @@ export * from "./actions";export * from "./activity";export * from "./admin";export * from "./ai-entity-analysis";-export * from "./ai-sql-fixer";export * from "./alert";export * from "./autocomplete";export * from "./automagic-dashboards";diff --git a/frontend/src/metabase-types/api/mocks/ai-sql-fixer.ts b/frontend/src/metabase-types/api/mocks/ai-sql-fixer.tsdeleted file mode 100644index 58a996e2ae3..00000000000--- a/frontend/src/metabase-types/api/mocks/ai-sql-fixer.ts+++ /dev/null@@ -1,36 +0,0 @@-import type {- FixSqlQueryRequest,- FixSqlQueryResponse,- SqlQueryFix,-} from "metabase-types/api";--import { createMockNativeDatasetQuery } from "./query";--export function createMockSqlQueryFix(- opts?: Partial<SqlQueryFix>,-): SqlQueryFix {- return {- line_number: 1,- fixed_sql: "",- ...opts,- };-}--export function createMockFixSqlQueryRequest(- opts?: Partial<FixSqlQueryRequest>,-): FixSqlQueryRequest {- return {- query: createMockNativeDatasetQuery(),- error_message: "",- ...opts,- };-}--export function createMockFixSqlQueryResponse(- opts?: Partial<FixSqlQueryResponse>,-): FixSqlQueryResponse {- return {- fixes: [],- ...opts,- };-}diff --git a/frontend/src/metabase-types/api/mocks/index.ts b/frontend/src/metabase-types/api/mocks/index.tsindex 7d9324b83fc..68ac1cd37c6 100644--- a/frontend/src/metabase-types/api/mocks/index.ts+++ b/frontend/src/metabase-types/api/mocks/index.ts@@ -1,6 +1,5 @@export * from "./actions";export * from "./activity";-export * from "./ai-sql-fixer";export * from "./alert";export * from "./automagic-dashboards";export * from "./bookmark";diff --git a/frontend/test/__support__/server-mocks/ai-sql-fixer.ts b/frontend/test/__support__/server-mocks/ai-sql-fixer.tsdeleted file mode 100644index 1790e809e2e..00000000000--- a/frontend/test/__support__/server-mocks/ai-sql-fixer.ts+++ /dev/null@@ -1,11 +0,0 @@-import fetchMock from "fetch-mock";--import type { FixSqlQueryResponse } from "metabase-types/api";--export function setupFixNativeQueryEndpoint(response: FixSqlQueryResponse) {- fetchMock.post("path:/api/ai-sql-fixer/fix", response);-}--export function setupErrorFixNativeQueryEndpoint() {- fetchMock.post("path:/api/ai-sql-fixer/fix", 500);-}diff --git a/frontend/test/__support__/server-mocks/index.ts b/frontend/test/__support__/server-mocks/index.tsindex f811cf41636..0295d8c8ab0 100644--- a/frontend/test/__support__/server-mocks/index.ts+++ b/frontend/test/__support__/server-mocks/index.ts@@ -1,7 +1,6 @@export * from "./action";export * from "./activity";export * from "./ai-entity-analysis";-export * from "./ai-sql-fixer";export * from "./alert";export * from "./api-key";export * from "./audit";diff --git a/src/metabase/agent_api/api.clj b/src/metabase/agent_api/api.cljindex 90ec4a1bcb7..7be34499f61 100644--- a/src/metabase/agent_api/api.clj+++ b/src/metabase/agent_api/api.clj@@ -9,7 +9,7 @@[metabase.api.macros.scope :as scope][metabase.api.routes.common :as api.routes.common][metabase.auth-identity.core :as auth-identity]- [metabase.metabot.tools.api :as tools.api]+ [metabase.lib.schema.temporal-bucketing :as lib.schema.temporal-bucketing][metabase.metabot.tools.deftool :as deftool][metabase.metabot.tools.entity-details :as entity-details][metabase.metabot.tools.field-stats :as field-stats]@@ -305,6 +305,190 @@;; These use snake_case keys for validation and OpenAPI generation,;; with :encode/tool-api-request transformers for converting to the internal format.+(mr/def ::bucket+ (into [:enum {:error/message "Valid bucket"+ :encode/tool-api-request keyword}]+ (map name)+ lib.schema.temporal-bucketing/ordered-datetime-bucketing-units))++(mr/def ::existence-filter+ [:and+ [:map+ [:field_id :string]+ [:operation [:enum {:encode/tool-api-request keyword}+ "is-null" "is-not-null"+ "string-is-empty" "string-is-not-empty"+ "is-true" "is-false"]]]+ [:map {:encode/tool-api-request #(update-keys % metabot.u/safe->kebab-case-en)}]])++(mr/def ::temporal-extraction-filter+ [:and+ [:map+ [:field_id :string]+ [:operation [:enum {:encode/tool-api-request keyword}+ "year-equals" "year-not-equals"+ "quarter-equals" "quarter-not-equals"+ "month-equals" "month-not-equals"+ "day-of-week-equals" "day-of-week-not-equals"+ "hour-equals" "hour-not-equals"+ "minute-equals" "minute-not-equals"+ "second-equals" "second-not-equals"]]+ [:value :int]]+ [:map {:encode/tool-api-request #(update-keys % metabot.u/safe->kebab-case-en)}]])++(mr/def ::disjunctive-temporal-extraction-filter+ [:and+ [:map+ [:field_id :string]+ [:operation [:enum {:encode/tool-api-request keyword}+ "year-equals" "year-not-equals"+ "quarter-equals" "quarter-not-equals"+ "month-equals" "month-not-equals"+ "day-of-week-equals" "day-of-week-not-equals"+ "hour-equals" "hour-not-equals"+ "minute-equals" "minute-not-equals"+ "second-equals" "second-not-equals"]]+ [:values [:sequential :int]]]+ [:map {:encode/tool-api-request #(update-keys % metabot.u/safe->kebab-case-en)}]])++(mr/def ::temporal-filter+ [:and+ [:map+ [:field_id :string]+ [:bucket {:optional true} ::bucket]+ [:operation [:enum {:encode/tool-api-request keyword}+ "equals" "not-equals"+ "greater-than" "greater-than-or-equal"+ "less-than" "less-than-or-equal"]]+ [:value [:or :string :int]]]+ [:map {:encode/tool-api-request #(update-keys % metabot.u/safe->kebab-case-en)}]])++(mr/def ::disjunctive-temporal-filter+ [:and+ [:map+ [:field_id :string]+ [:bucket {:optional true} ::bucket]+ [:operation [:enum {:encode/tool-api-request keyword}+ "equals" "not-equals"+ "greater-than" "greater-than-or-equal"+ "less-than" "less-than-or-equal"]]+ [:values [:sequential [:or :string :int]]]]+ [:map {:encode/tool-api-request #(update-keys % metabot.u/safe->kebab-case-en)}]])++(mr/def ::string-filter+ [:and+ [:map+ [:field_id :string]+ [:operation [:enum {:encode/tool-api-request keyword}+ "equals" "not-equals"+ "string-contains" "string-not-contains"+ "string-starts-with" "string-ends-with"]]+ [:value :string]]+ [:map {:encode/tool-api-request #(update-keys % metabot.u/safe->kebab-case-en)}]])++(mr/def ::disjunctive-string-date-filter+ [:and+ [:map+ [:field_id :string]+ [:operation [:enum {:encode/tool-api-request keyword}+ "equals" "not-equals"+ "string-contains" "string-not-contains"+ "string-starts-with" "string-ends-with"]]+ [:values [:sequential :string]]]+ [:map {:encode/tool-api-request #(update-keys % metabot.u/safe->kebab-case-en)}]])++(mr/def ::numeric-filter+ [:and+ [:map+ [:field_id :string]+ [:operation [:enum {:encode/tool-api-request keyword}+ "equals" "not-equals"+ "greater-than" "greater-than-or-equal"+ "less-than" "less-than-or-equal"]]+ [:value [:or :int :double]]]+ [:map {:encode/tool-api-request #(update-keys % metabot.u/safe->kebab-case-en)}]])++(mr/def ::disjunctive-numeric-filter+ [:and+ [:map+ [:field_id :string]+ [:operation [:enum {:encode/tool-api-request keyword}+ "equals" "not-equals"]]+ [:values [:sequential [:or :int :double]]]]+ [:map {:encode/tool-api-request #(update-keys % metabot.u/safe->kebab-case-en)}]])++(mr/def ::segment-filter+ "Filter using a pre-defined segment."+ [:and+ [:map+ [:segment_id :int]]+ [:map {:encode/tool-api-request #(update-keys % metabot.u/safe->kebab-case-en)}]])++(mr/def ::filter+ [:or+ ::segment-filter+ ::existence-filter+ ::temporal-extraction-filter ::disjunctive-temporal-extraction-filter+ ::temporal-filter ::disjunctive-temporal-filter+ ::string-filter ::disjunctive-string-date-filter+ ::numeric-filter ::disjunctive-numeric-filter])++(mr/def ::group-by+ [:and+ [:map+ [:field_id :string]+ [:field_granularity {:optional true}+ [:maybe [:enum {:encode/tool-api-request keyword}+ "minute", "hour" "day" "week" "month" "quarter" "year" "day-of-week"]]]]+ [:map {:encode/tool-api-request #(update-keys % metabot.u/safe->kebab-case-en)}]])++(mr/def ::count-aggregation+ "Count aggregation — counts rows, no field_id needed.+ Use sort_order to order results by this aggregation ('asc' or 'desc')."+ [:and+ [:map+ [:function [:= {:encode/tool-api-request keyword} "count"]]+ [:bucket {:optional true} ::bucket]+ [:sort_order {:optional true} [:maybe [:enum {:encode/tool-api-request keyword} "asc" "desc"]]]]+ [:map {:encode/tool-api-request #(update-keys % metabot.u/safe->kebab-case-en)}]])++(mr/def ::field-aggregation+ "Aggregation using a field and function. field_id is required.+ Use sort_order to order results by this aggregation ('asc' or 'desc')."+ [:and+ [:map+ [:field_id :string]+ [:bucket {:optional true} ::bucket]+ [:sort_order {:optional true} [:maybe [:enum {:encode/tool-api-request keyword} "asc" "desc"]]]+ [:function [:enum {:encode/tool-api-request keyword}+ "avg" "count-distinct" "max" "min" "sum"]]]+ [:map {:encode/tool-api-request #(update-keys % metabot.u/safe->kebab-case-en)}]])++(mr/def ::measure-aggregation+ "Aggregation using a pre-defined measure."+ [:and+ [:map+ [:measure_id :int]+ [:sort_order {:optional true} [:maybe [:enum {:encode/tool-api-request keyword} "asc" "desc"]]]]+ [:map {:encode/tool-api-request #(update-keys % metabot.u/safe->kebab-case-en)}]])++(mr/def ::aggregation+ "Aggregation — count (field optional), field-based (field required), or measure-based."+ [:or ::count-aggregation ::field-aggregation ::measure-aggregation])++(mr/def ::field+ [:and+ [:map+ [:field_id :string]+ [:bucket {:optional true} ::bucket]]+ [:map {:encode/tool-api-request #(update-keys % metabot.u/safe->kebab-case-en)}]])++(mr/def ::order-by+ "Order by item specifying a field and sort direction."+ [:map+ [:field ::field]+ [:direction [:enum {:encode/tool-api-request keyword} "asc" "desc"]]])+(mr/def ::construct-query-table-request"Request schema for constructing a query from a table.@@ -318,13 +502,13 @@[:and[:map[:table_id ms/PositiveInt]- [:filters {:optional true} [:maybe [:sequential ::tools.api/filter]]]- [:fields {:optional true} [:maybe [:sequential ::tools.api/field]]]- [:aggregations {:optional true} [:maybe [:sequential ::tools.api/aggregation]]]- [:group_by {:optional true} [:maybe [:sequential ::tools.api/group-by]]]+ [:filters {:optional true} [:maybe [:sequential ::filter]]]+ [:fields {:optional true} [:maybe [:sequential ::field]]]+ [:aggregations {:optional true} [:maybe [:sequential ::aggregation]]]+ [:group_by {:optional true} [:maybe [:sequential ::group-by]]][:order_by {:optional true:description "Order by regular fields only. To order by aggregation results, use sort_order on the aggregation."}- [:maybe [:sequential ::tools.api/order-by]]]+ [:maybe [:sequential ::order-by]]][:limit {:optional true} [:maybe ms/PositiveInt]]][:map {:encode/tool-api-request #(update-keys % metabot.u/safe->kebab-case-en)}]])@@ -334,8 +518,8 @@[:and[:map[:metric_id ms/PositiveInt]- [:filters {:optional true} [:maybe [:sequential ::tools.api/filter]]]- [:group_by {:optional true} [:maybe [:sequential ::tools.api/group-by]]]]+ [:filters {:optional true} [:maybe [:sequential ::filter]]]+ [:group_by {:optional true} [:maybe [:sequential ::group-by]]]][:map {:encode/tool-api-request #(update-keys % metabot.u/safe->kebab-case-en)}]])(mr/def ::construct-query-requestdiff --git a/src/metabase/api_routes/routes.clj b/src/metabase/api_routes/routes.cljindex 66a1cb02f35..6b5240897f0 100644--- a/src/metabase/api_routes/routes.clj+++ b/src/metabase/api_routes/routes.clj@@ -36,8 +36,6 @@[metabase.measures.api][metabase.metabot.api][metabase.metabot.api.entity-analysis]- [metabase.metabot.api.sql-fixer]- [metabase.metabot.api.sql-generation][metabase.metrics.api][metabase.model-persistence.api][metabase.native-query-snippets.api]@@ -159,8 +157,6 @@"/activity" (+auth 'metabase.activity-feed.api)"/agent" metabase.agent-api.api/routes"/ai-entity-analysis" metabase.metabot.api.entity-analysis/routes- "/ai-sql-fixer" metabase.metabot.api.sql-fixer/routes- "/ai-sql-generation" metabase.metabot.api.sql-generation/routes"/alert" (+auth metabase.pulse.api/alert-routes)"/analytics" (+auth 'metabase.analytics.api)"/api-key" (+auth 'metabase.api-keys.api)diff --git a/src/metabase/metabot/agent/core.clj b/src/metabase/metabot/agent/core.cljindex 607183eb50f..cc065c57e7d 100644--- a/src/metabase/metabot/agent/core.clj+++ b/src/metabase/metabot/agent/core.clj@@ -11,9 +11,9 @@[metabase.metabot.agent.messages :as messages][metabase.metabot.agent.profiles :as profiles][metabase.metabot.agent.streaming :as streaming]- [metabase.metabot.agent.tools :as agent-tools][metabase.metabot.self :as self][metabase.metabot.settings :as metabot.settings]+ [metabase.metabot.tools :as tools][metabase.util :as u][metabase.util.json :as json][metabase.util.log :as log]@@ -376,7 +376,7 @@(memory/load-todos-from-state seeded)(memory/load-link-registry-from-state seeded))memory-atom (atom memory)- tools (agent-tools/wrap-tools-with-state base-tools memory-atom metabot-id)]+ tools (tools/wrap-tools-with-state base-tools memory-atom metabot-id)](log/info "Starting agent" {:profile profile-id:tools (count tools):max-iter (:max-iterations profile)@@ -435,14 +435,14 @@parts-atom (atom [])link-registry-atom (atom (get-in memory [:state :link-registry] {}))llm-call (call-llm memory context profile tools iteration tracking-opts link-registry-atom)- xf (comp (accumulate-usage-xf usage-atom)- (u/tee-xf parts-atom))+ xf (comp (accumulate-usage-xf usage-atom)+ (u/tee-xf parts-atom));; We use `reduce` instead of `transduce` because rf is the outer reducing;; function (e.g. aisdk-line-xf wrapping streaming-writer-rf) whose completion;; arity emits a finish message — that must only fire once, at the end of the;; entire agent loop, not after every iteration.- result' (reduce (xf rf) result llm-call)- parts @parts-atom]+ result' (reduce (xf rf) result llm-call)+ parts @parts-atom];; Sync link registry back to memory after streaming completes(swap! memory-atom assoc-in [:state :link-registry] @link-registry-atom);; Capture response for debug logdiff --git a/src/metabase/metabot/agent/profiles.clj b/src/metabase/metabot/agent/profiles.cljindex d3f9d5b3367..794d6f26576 100644--- a/src/metabase/metabot/agent/profiles.clj+++ b/src/metabase/metabot/agent/profiles.clj@@ -9,8 +9,8 @@(:require[clojure.string :as str][malli.error :as me]- [metabase.metabot.agent.tools :as agent-tools][metabase.metabot.settings :as metabot.settings]+ [metabase.metabot.tools :as tools][metabase.premium-features.core :as premium-features][metabase.util.malli :as mu][metabase.util.malli.registry :as mr]))@@ -45,7 +45,7 @@- :prompt-template - Selmer template name from resources/metabot/prompts/system/- :max-iterations - Maximum agent loop iterations- :temperature - LLM temperature setting- - :tools - Vector of tool vars (e.g. #'agent-tools/search-tool)+ - :tools - Vector of tool vars (e.g. #'tools/search-tool)Tool vars are validated at registration time to ensure they have required metadata."[profile :- [:map@@ -68,44 +68,44 @@:prompt-template "embedding-next.selmer":max-iterations 10:temperature 0.3- :tools [#'agent-tools/construct-notebook-query-tool- #'agent-tools/read-resource-tool- #'agent-tools/list-available-data-sources-tool]})+ :tools [#'tools/construct-notebook-query-tool+ #'tools/read-resource-tool+ #'tools/list-available-data-sources-tool]})(register-profile!{:name :internal:prompt-template "internal.selmer":max-iterations 10:temperature 0.3- :tools [#'agent-tools/search-tool- #'agent-tools/construct-notebook-query-tool- #'agent-tools/read-resource-tool- #'agent-tools/create-sql-query-tool- #'agent-tools/edit-sql-query-tool- #'agent-tools/replace-sql-query-tool- #'agent-tools/edit-chart-tool- #'agent-tools/navigate-user-tool- #'agent-tools/create-chart-tool- #'agent-tools/create-autogenerated-dashboard-tool- #'agent-tools/create-dashboard-subscription-tool- #'agent-tools/analyze-chart-tool]})+ :tools [#'tools/search-tool+ #'tools/construct-notebook-query-tool+ #'tools/read-resource-tool+ #'tools/create-sql-query-tool+ #'tools/edit-sql-query-tool+ #'tools/replace-sql-query-tool+ #'tools/edit-chart-tool+ #'tools/navigate-user-tool+ #'tools/create-chart-tool+ #'tools/create-autogenerated-dashboard-tool+ #'tools/create-dashboard-subscription-tool+ #'tools/analyze-chart-tool]})(register-profile!{:name :transforms_codegen:prompt-template "transform-codegen.selmer":max-iterations 30:temperature 0.3- :tools [#'agent-tools/transform-search-tool- #'agent-tools/get-transform-details-tool- #'agent-tools/get-transform-python-library-details-tool- #'agent-tools/write-transform-sql-tool- #'agent-tools/write-transform-python-tool- #'agent-tools/list-snippets-tool- #'agent-tools/get-snippet-details-tool- #'agent-tools/list-available-fields-tool- #'agent-tools/get-field-values-tool- #'agent-tools/todo-write-tool- #'agent-tools/todo-read-tool]})+ :tools [#'tools/transform-search-tool+ #'tools/get-transform-details-tool+ #'tools/get-transform-python-library-details-tool+ #'tools/write-transform-sql-tool+ #'tools/write-transform-python-tool+ #'tools/list-snippets-tool+ #'tools/get-snippet-details-tool+ #'tools/list-available-fields-tool+ #'tools/get-field-values-tool+ #'tools/todo-write-tool+ #'tools/todo-read-tool]});; SQL responses are rendered from tool results in the native port, so this;; profile must always end with a tool call rather than free-form assistant text.@@ -115,24 +115,24 @@:max-iterations 10:temperature 0.3:required-tool-call? true- :tools [#'agent-tools/sql-search-tool- #'agent-tools/read-resource-tool- #'agent-tools/create-sql-query-code-edit-tool- #'agent-tools/edit-sql-query-code-edit-tool- #'agent-tools/replace-sql-query-code-edit-tool- #'agent-tools/ask-for-sql-clarification-tool]})+ :tools [#'tools/sql-search-tool+ #'tools/read-resource-tool+ #'tools/create-sql-query-code-edit-tool+ #'tools/edit-sql-query-code-edit-tool+ #'tools/replace-sql-query-code-edit-tool+ #'tools/ask-for-sql-clarification-tool]})(register-profile!{:name :nlq:prompt-template "natural-language-querying-only.selmer":max-iterations 10:temperature 0.3- :tools [#'agent-tools/nlq-search-tool- #'agent-tools/read-resource-tool- #'agent-tools/construct-notebook-query-tool- #'agent-tools/navigate-user-tool- #'agent-tools/create-chart-tool- #'agent-tools/edit-chart-tool]})+ :tools [#'tools/nlq-search-tool+ #'tools/read-resource-tool+ #'tools/construct-notebook-query-tool+ #'tools/navigate-user-tool+ #'tools/create-chart-tool+ #'tools/edit-chart-tool]})(register-profile!{:name :document-generate-content@@ -140,25 +140,25 @@:max-iterations 10:temperature 0.3:required-tool-call? true- :tools [#'agent-tools/list-available-data-sources-tool- #'agent-tools/list-available-fields-tool- #'agent-tools/get-field-values-tool- #'agent-tools/document-schema-collect-tool- #'agent-tools/document-construct-model-chart-tool- #'agent-tools/document-construct-sql-chart-tool]})+ :tools [#'tools/list-available-data-sources-tool+ #'tools/list-available-fields-tool+ #'tools/get-field-values-tool+ #'tools/document-schema-collect-tool+ #'tools/document-construct-model-chart-tool+ #'tools/document-construct-sql-chart-tool]})(register-profile!{:name :slackbot:prompt-template "slackbot.selmer":max-iterations 10:temperature 0.3- :tools [#'agent-tools/search-tool- #'agent-tools/slackbot-construct-notebook-query-tool- #'agent-tools/list-available-fields-tool- #'agent-tools/get-field-values-tool- #'agent-tools/static-viz-tool- #'agent-tools/create-alert-tool- #'agent-tools/slackbot-create-dashboard-subscription-tool]})+ :tools [#'tools/search-tool+ #'tools/slackbot-construct-notebook-query-tool+ #'tools/list-available-fields-tool+ #'tools/get-field-values-tool+ #'tools/static-viz-tool+ #'tools/create-alert-tool+ #'tools/slackbot-create-dashboard-subscription-tool]})(def ^:private api-string->capability-keyword"Map from API capability strings (as sent by the frontend) to the keywordsdiff --git a/src/metabase/metabot/agent/tools/autogen_dashboard.clj b/src/metabase/metabot/agent/tools/autogen_dashboard.cljdeleted file mode 100644index ff9b0d93108..00000000000--- a/src/metabase/metabot/agent/tools/autogen_dashboard.clj+++ /dev/null@@ -1,51 +0,0 @@-(ns metabase.metabot.agent.tools.autogen-dashboard- "Autogenerated dashboard tool wrappers."- (:require- [metabase.metabot.agent.tools.shared :as shared]- [metabase.metabot.tools.create-autogenerated-dashboard :as autogen-dashboard-tools]- [metabase.util.log :as log]- [metabase.util.malli :as mu]))--(set! *warn-on-reflection* true)--(def ^:private autogen-dashboard-schema- [:map {:closed true}- [:source [:map- [:table_id {:optional true} [:maybe :int]]- [:model_id {:optional true} [:maybe :int]]- [:metric_id {:optional true} [:maybe :int]]- [:query_id {:optional true} [:maybe :string]]- [:report_id {:optional true} [:maybe :int]]]]])--(mu/defn ^{:tool-name "create_autogenerated_dashboard"- :capabilities #{:automagic-dashboards}}- create-autogenerated-dashboard-tool- "Create an automatically generated dashboard using Metabase's X-ray feature.-- X-ray builds complete dashboards with multiple visualizations that showcase- different aspects of your data - distributions, breakdowns by categories,- trends over time, and relationships between fields.-- Specify one source type:- - table_id: Create dashboard for a table- - model_id: Create dashboard for a model- - metric_id: Create dashboard for a metric- - query_id: Create dashboard for query results from this conversation- - report_id: Create dashboard for an existing report/question"- [{:keys [source]} :- autogen-dashboard-schema]- (try- (let [result (autogen-dashboard-tools/create-autogenerated-dashboard- {:source source- :memory-atom shared/*memory-atom*})- structured (:structured-output result)- reactions (:reactions result)]- (cond-> {:output (:message structured)- :structured-output structured- :final-response? (:final-response? result)- :instructions (:instructions result)}- (seq reactions) (assoc :reactions reactions)))- (catch Exception e- (log/error e "Error creating autogenerated dashboard")- (if (:agent-error? (ex-data e))- {:output (ex-message e)}- {:output (str "Failed to create autogenerated dashboard: " (or (ex-message e) "Unknown error"))}))))diff --git a/src/metabase/metabot/agent/tools/clarification.clj b/src/metabase/metabot/agent/tools/clarification.cljdeleted file mode 100644index 9757df51961..00000000000--- a/src/metabase/metabot/agent/tools/clarification.clj+++ /dev/null@@ -1,30 +0,0 @@-(ns metabase.metabot.agent.tools.clarification- "Clarification tool wrappers."- (:require- [clojure.string :as str]- [metabase.metabot.tools.ask-clarification :as ask-clarification-tools]- [metabase.util.malli :as mu]))--(set! *warn-on-reflection* true)--(defn- format-clarification-output- [{:keys [question options]}]- (str question- (when (seq options)- (str "\n\nOptions:\n" (str/join "\n" (map #(str "- " %) options))))))--(mu/defn ^{:tool-name "ask_for_sql_clarification"}- ask-for-sql-clarification-tool- "Ask the user for clarification about their SQL query request.-- Use this tool when you need more information from the user to properly- complete their SQL request. The agent will stop and wait for the user's response."- [{:keys [question options]} :- [:map {:closed true}- [:question :string]- [:options {:optional true} [:maybe [:sequential :string]]]]]- (try- (let [result (ask-clarification-tools/ask-for-sql-clarification {:question question- :options options})]- (assoc result :output (format-clarification-output (:structured-output result))))- (catch Exception e- {:output (str "Failed to ask clarification: " (or (ex-message e) "Unknown error"))})))diff --git a/src/metabase/metabot/agent/tools/create_alert.clj b/src/metabase/metabot/agent/tools/create_alert.cljdeleted file mode 100644index 819cc215716..00000000000--- a/src/metabase/metabot/agent/tools/create_alert.clj+++ /dev/null@@ -1,90 +0,0 @@-(ns metabase.metabot.agent.tools.create-alert- "Agent tool wrapper for creating alerts on saved questions.- Gets slack_channel_id from agent context and calls the create-alert tool endpoint directly."- (:require- [metabase.metabot.agent.tools.shared :as shared]- [metabase.metabot.tools.create-alert :as tools.create-alert]- [metabase.util.log :as log]- [metabase.util.malli :as mu]))--(set! *warn-on-reflection* true)--(def schedule-schema- "Schedule schema shared with create-dashboard-subscription tool."- [:or- [:map {:closed true}- [:frequency [:= "hourly"]]]- [:map {:closed true}- [:frequency [:= "daily"]]- [:hour [:int {:min 0 :max 23}]]]- [:map {:closed true}- [:frequency [:= "weekly"]]- [:day_of_week [:enum "sunday" "monday" "tuesday" "wednesday" "thursday" "friday" "saturday"]]- [:hour [:int {:min 0 :max 23}]]]- [:map {:closed true}- [:frequency [:= "monthly"]]- [:day_of_month [:enum "first-calendar-day"- "first-sunday" "first-monday" "first-tuesday" "first-wednesday"- "first-thursday" "first-friday" "first-saturday"- "middle-of-month"- "last-calendar-day"- "last-sunday" "last-monday" "last-tuesday" "last-wednesday"- "last-thursday" "last-friday" "last-saturday"]]- [:hour [:int {:min 0 :max 23}]]]])--(def ^:private create-alert-system-instructions- "## Alerts--You can create alerts that notify the user's current Slack channel based on a saved question's results on a-recurring schedule.--### Required information--Before calling the tool, ensure you have ALL of the following:-1. **Card ID** — the ID of a saved question, obtained from a prior search result or conversation context-2. **Send condition** — determines when the alert fires:- - `has_result` — sends when the question returns any rows- - `goal_above` — sends when the result exceeds the goal line set on the question- - `goal_below` — sends when the result drops below the goal line-3. **Schedule** — frequency (hourly, daily, weekly, monthly) with the appropriate time fields-4. **Send once** (optional, defaults to false) — if true, the alert is automatically deleted after it fires once--### Important notes--* Alerts are for **saved questions** (cards), not dashboards. For dashboard delivery, use the dashboard subscription tool.-* `goal_above` and `goal_below` only work on questions that have a goal line configured.-* If the user doesn't specify a send condition, default to `has_result`.--CRITICAL: When a user asks to be alerted or notified about a saved question's results, you MUST call the create_alert tool.-NEVER tell the user you have created an alert without actually calling the create_alert tool. If you cannot call the tool-(e.g. missing required information), explain what is needed instead of pretending the alert was created.")--(def ^:private alert-schema- [:map {:closed true}- [:card_id :int]- [:send_condition [:enum "has_result" "goal_above" "goal_below"]]- [:schedule schedule-schema]- [:send_once {:optional true :default false} :boolean]])--(mu/defn ^{:tool-name "create_alert"- :system-instructions create-alert-system-instructions}- create-alert-tool- "Create an alert based on a saved question's results on a recurring schedule."- [{:keys [card_id send_condition schedule send_once]} :- alert-schema]- (let [slack-channel-id (:slack_channel_id (shared/current-context))]- (when-not slack-channel-id- (throw (ex-info "This tool can only be used from a Slack channel"- {:agent-error? true})))- (try- (let [result (tools.create-alert/create-alert- {:card-id card_id- :send-condition (keyword send_condition)- :schedule schedule- :send-once (boolean send_once)- :slack-channel slack-channel-id})]- (if (:error result)- {:output (:error result)}- {:output (or (:output result) "Alert created successfully.")}))- (catch Exception e- (log/error e "Failed to create alert")- {:output (str "Failed to create alert: " (or (ex-message e) "Unknown error"))}))))diff --git a/src/metabase/metabot/agent/tools/create_dashboard_subscription.clj b/src/metabase/metabot/agent/tools/create_dashboard_subscription.cljdeleted file mode 100644index dd2505dbfa5..00000000000--- a/src/metabase/metabot/agent/tools/create_dashboard_subscription.clj+++ /dev/null@@ -1,55 +0,0 @@-(ns metabase.metabot.agent.tools.create-dashboard-subscription- "Agent tool wrapper for creating dashboard subscriptions.- Gets slack_channel_id from agent context and calls the create-dashboard-subscription tool endpoint directly."- (:require- [metabase.metabot.agent.tools.create-alert :as tools.create-alert]- [metabase.metabot.agent.tools.shared :as shared]- [metabase.metabot.tools.create-dashboard-subscription :as tools.create-dashboard-subscription]- [metabase.util.log :as log]- [metabase.util.malli :as mu]))--(set! *warn-on-reflection* true)--(def ^:private create-dashboard-subscription-system-instructions- "## Dashboard Subscriptions--You can create dashboard subscriptions that deliver dashboard contents to the user's current slack channel on a-recurring schedule.--### CRITICAL: You MUST call the create_dashboard_subscription tool--When a user asks to subscribe to a dashboard, set up scheduled delivery, or receive regular updates for a dashboard,-you MUST call the create_dashboard_subscription tool. Never tell the user you have created a subscription without-actually calling the tool. If you cannot call the tool (e.g. missing required information), explain what is needed-instead of pretending the subscription was created.--### Required information--Before calling the tool, ensure you have ALL of the following:-1. **Dashboard ID** — obtained from a prior search result or conversation context-2. **Schedule** — frequency (hourly, daily, weekly, monthly) with the appropriate time fields--If any required information is missing, ask the user for it rather than assuming or fabricating values.")--(mu/defn ^{:tool-name "create_dashboard_subscription"- :system-instructions create-dashboard-subscription-system-instructions}- slackbot-create-dashboard-subscription-tool- "Create a recurring subscription that delivers a dashboard's contents to a Slack channel."- [{:keys [dashboard_id schedule]} :- [:map {:closed true}- [:dashboard_id :int]- [:schedule tools.create-alert/schedule-schema]]]- (let [slack-channel-id (:slack_channel_id (shared/current-context))]- (when-not slack-channel-id- (throw (ex-info "This tool can only be used from a Slack channel"- {:agent-error? true})))- (try- (let [result (tools.create-dashboard-subscription/create-dashboard-subscription- {:dashboard-id dashboard_id- :schedule schedule- :slack-channel slack-channel-id})]- (if (:error result)- {:output (:error result)}- {:output (or (:output result) "Dashboard subscription created successfully.")}))- (catch Exception e- (log/error e "Failed to create dashboard subscription")- {:output (str "Failed to create dashboard subscription: " (or (ex-message e) "Unknown error"))}))))diff --git a/src/metabase/metabot/agent/tools/metadata.clj b/src/metabase/metabot/agent/tools/metadata.cljdeleted file mode 100644index 9fef78349ab..00000000000--- a/src/metabase/metabot/agent/tools/metadata.clj+++ /dev/null@@ -1,89 +0,0 @@-(ns metabase.metabot.agent.tools.metadata- "Metadata tool wrappers."- (:require- [clojure.string :as str]- [medley.core :as m]- [metabase.metabot.agent.tools.shared :as shared]- [metabase.metabot.tools.entity-details :as entity-details-tools]- [metabase.metabot.tools.field-stats :as field-stats-tools]- [metabase.metabot.tools.get-metadata :as metadata-tools]- [metabase.metabot.tools.instructions :as instructions]- [metabase.metabot.tools.llm-representations :as llm-rep]- [metabase.util.malli :as mu]))--(set! *warn-on-reflection* true)--(defn- format-with-instructions- [data instruction-text]- (str "<result>\n" data "\n</result>\n"- "<instructions>\n" instruction-text "\n</instructions>"))--(defn- format-answer-sources-output- [{:keys [metrics models]}]- (let [content (str (when (seq metrics)- (str "<metrics>\n"- (str/join "\n" (map llm-rep/metric->xml metrics))- "\n</metrics>\n"))- (when (seq models)- (str "<metabase-models>\n"- (str/join "\n" (map llm-rep/model->xml models))- "\n</metabase-models>")))]- (format-with-instructions content instructions/answer-sources-instructions)))--(defn- format-metadata-output- [structured]- (llm-rep/get-metadata-result->xml structured))--(defn- format-field-metadata-output- ;; NOTE: keep in sync with read_resource.clj/format-content :field-metadata branch- [{:keys [field_id value_metadata]}]- (format-with-instructions- (llm-rep/field-metadata->xml {:field_id field_id :value_metadata value_metadata})- instructions/field-metadata-instructions))--(defn- add-output- "Add :output to a tool result that has :structured-output, using the given format-fn."- [result format-fn]- (m/assoc-some result :output (some-> result :structured-output format-fn)))--(mu/defn ^{:tool-name "list_available_data_sources"}- list-available-data-sources-tool- "List all data sources (metrics and models) available to the metabot instance."- [_args :- [:maybe [:map {:closed true}]]]- (add-output- (entity-details-tools/answer-sources {:metabot-id shared/*metabot-id*- :with-field-values? false})- format-answer-sources-output))--(def ^:private list-available-fields-schema- [:map {:closed true}- [:table_ids [:sequential :int]]- [:model_ids [:sequential :int]]- [:metric_ids [:sequential :int]]])--(mu/defn ^{:tool-name "list_available_fields"}- list-available-fields-tool- "Retrieve metadata for tables, models, and metrics."- [{:keys [table_ids model_ids metric_ids]} :- list-available-fields-schema]- (add-output- (metadata-tools/get-metadata {:table-ids table_ids- :model-ids model_ids- :metric-ids metric_ids})- format-metadata-output))--(def ^:private get-field-values-schema- [:map {:closed true}- [:data_source [:enum "table" "model" "metric"]]- [:source_id :int]- [:field_id :string]])--(mu/defn ^{:tool-name "get_field_values"}- get-field-values-tool- "Return metadata for a given field of a given data source."- [{:keys [data_source source_id field_id]} :- get-field-values-schema]- (add-output- (field-stats-tools/field-values {:entity-type data_source- :entity-id source_id- :field-id field_id- :limit nil})- format-field-metadata-output))diff --git a/src/metabase/metabot/agent/tools/navigation.clj b/src/metabase/metabot/agent/tools/navigation.cljdeleted file mode 100644index c602e0f2de1..00000000000--- a/src/metabase/metabot/agent/tools/navigation.clj+++ /dev/null@@ -1,49 +0,0 @@-(ns metabase.metabot.agent.tools.navigation- "Navigation tool wrappers."- (:require- [metabase.metabot.agent.tools.shared :as shared]- [metabase.metabot.tools.navigate :as navigate-tools]- [metabase.util.log :as log]- [metabase.util.malli :as mu]))--(set! *warn-on-reflection* true)--(def ^:private navigation-schema- [:map {:closed true}- [:destination [:or- [:map {:closed true}- [:page [:enum "notebook_editor" "metrics_browser" "model_browser" "database_browser"]]]- [:map {:closed true}- [:page [:enum "sql_editor"]]- [:database_id :int]]- [:map {:closed true}- [:entity_type [:enum "table" "model" "question" "metric" "dashboard"]]- [:entity_id :int]]- [:map {:closed true}- [:query_id :string]]- [:map {:closed true}- [:chart_id :string]]]]])--(mu/defn ^{:tool-name "navigate_user"- :capabilities #{:frontend-navigate-user-v1}}- navigate-user-tool- "Navigate the user to a specific page or entity in Metabase.-- Use this tool to direct users to:- - Pages: notebook_editor, metrics_browser, model_browser, database_browser, sql_editor- - Entities: table, model, question, metric, dashboard- - Query results or charts from the current conversation"- [{:keys [destination]} :- navigation-schema]- (try- (let [result (navigate-tools/navigate {:destination destination- :memory-atom shared/*memory-atom*})- structured (:structured-output result)- reactions (:reactions result)]- (cond-> {:output (:message structured)- :structured-output structured}- (seq reactions) (assoc :reactions reactions)))- (catch Exception e- (log/error e "Error navigating")- (if (:agent-error? (ex-data e))- {:output (ex-message e)}- {:output (str "Failed to navigate: " (or (ex-message e) "Unknown error"))}))))diff --git a/src/metabase/metabot/agent/tools/resources.clj b/src/metabase/metabot/agent/tools/resources.cljdeleted file mode 100644index c6d2d1def51..00000000000--- a/src/metabase/metabot/agent/tools/resources.clj+++ /dev/null@@ -1,26 +0,0 @@-(ns metabase.metabot.agent.tools.resources- "Resource reading tool wrappers."- (:require- [metabase.metabot.tools.read-resource :as read-resource-tools]- [metabase.util.log :as log]- [metabase.util.malli :as mu]))--(set! *warn-on-reflection* true)--(mu/defn ^{:tool-name "read_resource"}- read-resource-tool- "Read detailed information about Metabase resources via URI patterns.-- Supports fetching multiple resources in parallel using metabase:// URIs:- - metabase://table/{id}/fields - Get table structure with fields- - metabase://model/{id}/fields/{field_id} - Get specific field details- - metabase://metric/{id}/dimensions - Get metric dimensions- - metabase://transform/{id} - Get transform details- - metabase://dashboard/{id} - Get dashboard details"- [{:keys [uris]} :- [:map {:closed true}- [:uris [:sequential [:string {:description "Metabase resource URIs to fetch"}]]]]]- (try- (read-resource-tools/read-resource {:uris uris})- (catch Exception e- (log/error e "Error in read_resource tool")- {:output (str "Failed to read resources: " (or (ex-message e) "Unknown error"))})))diff --git a/src/metabase/metabot/agent/tools/search.clj b/src/metabase/metabot/agent/tools/search.cljdeleted file mode 100644index 4534a34220c..00000000000--- a/src/metabase/metabot/agent/tools/search.clj+++ /dev/null@@ -1,109 +0,0 @@-(ns metabase.metabot.agent.tools.search- "Search tool wrappers for Metabot v3."- (:require- [clojure.string :as str]- [metabase.metabot.agent.tools.shared :as shared]- [metabase.metabot.tmpl :as te]- [metabase.metabot.tools.instructions :as instructions]- [metabase.metabot.tools.llm-representations :as llm-rep]- [metabase.metabot.tools.search :as search-tools]- [metabase.util.log :as log]- [metabase.util.malli :as mu]))--(set! *warn-on-reflection* true)--(defn- format-search-output- "Format search results as an LLM-ready string."- [results]- (let [results-xml (llm-rep/search-results->xml results)]- (te/lines- "<result>"- results-xml- ""- (str "Total results: " (count results))- "</result>"- "<instructions>"- instructions/search-result-instructions "</instructions>")))--(defn- invalid-entity-types- [entity-types allowed]- (when (seq entity-types)- (seq (remove allowed entity-types))))--(defn- do-search- [label allowed-types search-opts {:keys [semantic_queries keyword_queries entity_types] :as _args}]- (if-let [invalid (invalid-entity-types entity_types allowed-types)]- {:output (str "Invalid entity_types for " label ": " (pr-str (vec invalid))- ". Allowed types: " (str/join ", " (sort allowed-types)) ".")}- (try- (let [results (search-tools/search (merge {:semantic-queries semantic_queries- :term-queries keyword_queries- :entity-types entity_types- :metabot-id shared/*metabot-id*- :limit 10}- search-opts))]- {:output (format-search-output results)- :structured-output {:result-type :search- :data results- :total_count (count results)}})- (catch Exception e- (log/error e (str "Error in " label))- {:output (str "Search failed: " (or (ex-message e) "Unknown error"))}))))--(def ^:private search-schema- [:map {:closed true}- [:semantic_queries {:feature :semantic-search} [:sequential :string]]- [:keyword_queries [:sequential :string]]- [:entity_types {:optional true}- [:maybe [:sequential [:enum "table" "model" "metric" "dashboard" "question"]]]]])--(mu/defn ^{:tool-name "search"}- search-tool- "Search for tables, models, metrics, dashboards, and saved questions."- [args :- search-schema]- (do-search "search" #{"table" "model" "metric" "dashboard" "question"} {} args))--(def ^:private sql-search-schema- [:map {:closed true}- [:semantic_queries {:feature :semantic-search} [:sequential :string]]- [:keyword_queries [:sequential :string]]- [:database_id :int]- [:entity_types {:optional true}- [:maybe [:sequential [:enum "table" "model"]]]]])--(mu/defn ^{:tool-name "search"- :prompt "sql_search.md"}- sql-search-tool- "Search for SQL-queryable data sources (tables and models) within a database."- [{:keys [database_id] :as args} :- sql-search-schema]- (do-search "SQL search" #{"table" "model"} {:database-id database_id} args))--(def ^:private nlq-search-schema- [:map {:closed true}- [:semantic_queries {:feature :semantic-search} [:sequential :string]]- [:keyword_queries [:sequential :string]]- [:entity_types {:optional true}- [:maybe [:sequential [:enum "model" "metric" "table"]]]]])--(mu/defn ^{:tool-name "search"- :prompt "nql_search.md"}- nlq-search-tool- "Search for NLQ-queryable data sources (models, metrics, tables)."- [args :- nlq-search-schema]- (do-search "NLQ search" #{"model" "metric" "table"} {:profile-id "nlq"} args))--(def ^:private transform-search-schema- [:map {:closed true}- [:semantic_queries {:feature :semantic-search} [:sequential :string]]- [:keyword_queries [:sequential :string]]- [:search_native_query {:optional true} [:maybe :boolean]]- [:entity_types {:optional true}- [:maybe [:sequential [:enum "table" "model" "transform"]]]]])--(mu/defn ^{:tool-name "search"- :prompt "transform_search"}- transform-search-tool- "Search for transforms, tables, and models."- [{:keys [search_native_query] :as args} :- transform-search-schema]- (do-search "transform search" #{"table" "model" "transform"}- {:search-native-query search_native_query} args))diff --git a/src/metabase/metabot/agent/tools/snippets.clj b/src/metabase/metabot/agent/tools/snippets.cljdeleted file mode 100644index db6249f9521..00000000000--- a/src/metabase/metabot/agent/tools/snippets.clj+++ /dev/null@@ -1,55 +0,0 @@-(ns metabase.metabot.agent.tools.snippets- "Snippet tool wrappers."- (:require- [clojure.string :as str]- [metabase.metabot.tools.snippets :as snippet-tools]- [metabase.util.malli :as mu]))--(set! *warn-on-reflection* true)--(defn- format-snippet-list-output- [snippets]- (if (seq snippets)- (str "<snippets>\n"- (str/join "\n" (map (fn [{:keys [id name description]}]- (str "<snippet id=\"" id "\" name=\"" name "\">"- (when description description)- "</snippet>"))- snippets))- "\n</snippets>")- "No snippets available."))--(defn- format-snippet-details-output- [{:keys [id name description content]}]- (str "<snippet id=\"" id "\" name=\"" name "\">\n"- (when description (str "<description>" description "</description>\n"))- (when content (str "<content>\n" content "\n</content>\n"))- "</snippet>"))--(defn- add-output- "Add :output to a tool result. Handles both :structured_output and :structured-output."- [result format-fn]- (if-let [structured (or (:structured_output result) (:structured-output result))]- (assoc result :output (format-fn structured))- result))--(mu/defn ^{:tool-name "list_snippets"- :capabilities #{:feature-snippets}}- list-snippets-tool- "List all SQL snippets available in the Metabase instance.-- Use this tool before editing or creating SQL transforms to understand what- snippets are available. If any snippets may be relevant to the user's request,- fetch their content using the get_snippet_details tool."- [_args :- [:maybe [:map {:closed true}]]]- (add-output (snippet-tools/get-snippets {}) format-snippet-list-output))--(mu/defn ^{:tool-name "get_snippet_details"- :capabilities #{:feature-snippets}}- get-snippet-details-tool- "Get the full details of a SQL snippet including its content.-- Use this tool to retrieve the actual SQL content of a snippet after identifying- it with list_snippets."- [{:keys [snippet_id]} :- [:map {:closed true} [:snippet_id :int]]]- (add-output (snippet-tools/get-snippet-details {:snippet-id snippet_id}) format-snippet-details-output))diff --git a/src/metabase/metabot/agent/tools/subscriptions.clj b/src/metabase/metabot/agent/tools/subscriptions.cljdeleted file mode 100644index 793229a9447..00000000000--- a/src/metabase/metabot/agent/tools/subscriptions.clj+++ /dev/null@@ -1,48 +0,0 @@-(ns metabase.metabot.agent.tools.subscriptions- "Dashboard subscription tool wrapper."- (:require- [metabase.metabot.tools.create-dashboard-subscription :as subscription-tools]- [metabase.util.log :as log]- [metabase.util.malli :as mu]))--(set! *warn-on-reflection* true)--(def ^:private subscription-schema- [:map {:closed true}- [:dashboard_id :int]- [:email {:optional true} [:maybe :string]]- [:slack_channel {:optional true} [:maybe :string]]- [:schedule [:map- [:frequency [:enum "hourly" "daily" "weekly" "monthly"]]- [:hour {:optional true} [:maybe :int]]- [:day_of_week {:optional true} [:maybe :string]]- [:day_of_month {:optional true} [:maybe :string]]]]])--(mu/defn ^{:tool-name "create_dashboard_subscription"}- create-dashboard-subscription-tool- "Create a dashboard subscription to send regular updates via email or Slack.-- Use when a user wants to receive or send regular updates on a dashboard's contents.- Requires a valid dashboard ID, either an email address or a Slack channel name, and a schedule.-- Do NOT infer email addresses from usernames or other information.- If the email address is incomplete or missing a part like the TLD,- ask the user for clarification before proceeding."- [{:keys [dashboard_id email slack_channel schedule]} :- subscription-schema]- (try- (subscription-tools/create-dashboard-subscription- {:dashboard-id dashboard_id- :email email- :slack-channel slack_channel- :schedule (-> schedule- (update :frequency keyword)- (cond->- (:day_of_week schedule) (-> (assoc :day-of-week (keyword (:day_of_week schedule)))- (dissoc :day_of_week))- (:day_of_month schedule) (-> (assoc :day-of-month (keyword (:day_of_month schedule)))- (dissoc :day_of_month))))})- (catch Exception e- (log/error e "Error creating dashboard subscription")- (if (:agent-error? (ex-data e))- {:output (ex-message e)}- {:output (str "Failed to create dashboard subscription: " (or (ex-message e) "Unknown error"))}))))diff --git a/src/metabase/metabot/agent/tools/todo.clj b/src/metabase/metabot/agent/tools/todo.cljdeleted file mode 100644index fea084daadb..00000000000--- a/src/metabase/metabot/agent/tools/todo.clj+++ /dev/null@@ -1,69 +0,0 @@-(ns metabase.metabot.agent.tools.todo- "Todo tool wrappers."- (:require- [clojure.string :as str]- [metabase.metabot.agent.tools.shared :as shared]- [metabase.metabot.tools.todo :as todo-tools]- [metabase.util.malli :as mu]))--(set! *warn-on-reflection* true)--(defn- format-todo-write-output- [{:keys [todo_count]}]- (str "Todo list updated successfully. " todo_count " item(s)."))--(defn- format-todo-read-output- [{:keys [todos todo_count]}]- (if (seq todos)- (str "Current todo list (" todo_count " items):\n"- (str/join "\n" (map (fn [{:keys [id content status priority]}]- (str "- [" status "] " content " (id=" id ", priority=" priority ")"))- todos)))- "No todos found."))--(defn- add-output- [result format-fn]- (if-let [structured (:structured-output result)]- (assoc result :output (format-fn structured))- result))--(def ^:private todo-write-schema- [:map {:closed true}- [:todos [:sequential [:map {:closed true}- [:id :string]- [:content :string]- [:status [:enum "pending" "in_progress" "completed" "cancelled"]]- [:priority [:enum "high" "medium" "low"]]]]]])--(mu/defn ^{:tool-name "todo_write"}- todo-write-tool- "Create and manage a structured task list.- Write or update the todo list with tasks for tracking progress.-- Each todo item must have:- - id: Unique identifier for the task- - content: Description of what needs to be done- - status: One of 'pending', 'in_progress', 'completed', 'cancelled'- - priority: One of 'high', 'medium', 'low'"- [{:keys [todos]} :- todo-write-schema]- (try- (add-output- (todo-tools/todo-write {:todos todos- :memory-atom shared/*memory-atom*})- format-todo-write-output)- (catch Exception e- (if (:agent-error? (ex-data e))- {:output (ex-message e)}- {:output (str "Failed to update todo list: " (or (ex-message e) "Unknown error"))}))))--(mu/defn ^{:tool-name "todo_read"}- todo-read-tool- "Read the current todo list from memory.- Returns the list of todos that have been created during this conversation."- [_args :- [:maybe [:map {:closed true}]]]- (try- (add-output- (todo-tools/todo-read {:memory-atom shared/*memory-atom*})- format-todo-read-output)- (catch Exception e- {:output (str "Failed to read todo list: " (or (ex-message e) "Unknown error"))})))diff --git a/src/metabase/metabot/agent/tools/transforms.clj b/src/metabase/metabot/agent/tools/transforms.cljdeleted file mode 100644index 50a2726cc41..00000000000--- a/src/metabase/metabot/agent/tools/transforms.clj+++ /dev/null@@ -1,159 +0,0 @@-(ns metabase.metabot.agent.tools.transforms- "Transform tool definitions.- SQL transform tools are implemented directly in OSS.- Python transform tools use defenterprise (return nil/error in OSS, real impl in EE)."- (:require- [metabase.metabot.agent.tools.shared :as shared]- [metabase.metabot.tools.dependencies :as deps]- [metabase.metabot.tools.transforms :as transform-tools]- [metabase.metabot.tools.transforms-write :as transforms-write-tools]- [metabase.metabot.util :as metabot.u]- [metabase.premium-features.core :refer [defenterprise]]- [metabase.util.log :as log]- [metabase.util.malli :as mu]))--(set! *warn-on-reflection* true)--;;; ──────────────────────────────────────────────────────────────────-;;; Formatting helpers-;;; ──────────────────────────────────────────────────────────────────--(defn- format-transform-details-output- [{:keys [id name description source target] :as _transform}]- (metabot.u/xml- [:transform {:id id :name name}- (when description [:description description])- (when source- [:source {:type (:type source)}- (when (:query source) [:query (:query source)])- (when (:source-database source) [:database (:source-database source)])])- (when target [:target (pr-str target)])]))--(defn format-transform-write-output- "Format the output of a transform write operation."- [{:keys [message]}]- (or message "Transform updated successfully."))--(defn add-output- "Add :output to a tool result. Handles both :structured_output and :structured-output."- [result format-fn]- (if-let [structured (or (:structured_output result) (:structured-output result))]- (assoc result :output (format-fn structured))- result))--(defn- check-dependencies- "Check for downstream breakages after a SQL transform edit.- Returns nil if no issues found or the check fails, otherwise a map with- :bad_transforms and :bad_questions."- [transform-id source]- (when transform-id- (try- (let [{:keys [structured_output]} (deps/check-transform-dependencies- {:id transform-id :source source})]- (when (and structured_output- (or (seq (:bad_transforms structured_output))- (seq (:bad_questions structured_output))))- structured_output))- (catch Exception e- (log/error e "Dependency check failed for transform" transform-id)- nil))))--(defn- format-dependency-warnings- "Format dependency check results into instructions for the agent."- [{:keys [bad_transforms bad_questions]}]- (str "\n\n**Dependency issues detected.**\n"- "Your proposed changes would break downstream dependencies.\n\n"- (when (seq bad_transforms)- (str "Broken transforms:\n"- (apply str (for [{:keys [transform]} bad_transforms]- (str "- [" (:name transform) "](metabase://transform/" (:id transform) ")\n")))))- (when (seq bad_questions)- (str "Broken questions:\n"- (apply str (for [{:keys [question]} bad_questions]- (str "- [" (:name question) "](metabase://question/" (:id question) ")\n")))))- "\nYou must summarize these dependency issues for the user. "- "Do not propose or apply fixes yourself."))--;;; ──────────────────────────────────────────────────────────────────-;;; Tool definitions-;;; ──────────────────────────────────────────────────────────────────--(mu/defn ^{:tool-name "get_transform_details"}- get-transform-details-tool- "Get information about a transform."- [{:keys [transform_id]} :- [:map {:closed true} [:transform_id :int]]]- (add-output (transform-tools/get-transform-details {:transform-id transform_id})- format-transform-details-output))--(def ^:private python-lib-schema- [:map {:closed true} [:path :string]])--(defenterprise ^{:tool-name "get_transform_python_library_details"- :schema [:=> [:cat python-lib-schema] :map]- :ee-feature :transforms}- get-transform-python-library-details-tool- "Get Python library details. EE-only; returns an error in OSS."- metabase-enterprise.metabot.agent.tools.transforms- [{:keys [_path]}]- {:output "Python transform tools are only available in Metabase Enterprise Edition."})--(def ^:private write-transform-sql-schema- [:map {:closed true}- [:transform_id {:optional true} [:maybe :int]]- [:edit_action [:map- [:mode [:enum "edit" "replace"]]- [:edits {:optional true} [:maybe [:sequential [:map- [:old_string :string]- [:new_string :string]- [:replace_all {:optional true} [:maybe :boolean]]]]]]- [:new_content {:optional true} [:maybe :string]]]]- [:thinking {:optional true} [:maybe :string]]- [:transform_name {:optional true} [:maybe :string]]- [:transform_description {:optional true} [:maybe :string]]- [:source_database {:optional true} [:maybe :int]]- [:source_tables {:optional true} [:maybe :map]]])--(mu/defn ^{:tool-name "write_transform_sql"- :capabilities #{:feature-transforms :permission-write-transforms}}- write-transform-sql-tool- "Write new SQL queries or edit existing queries for transforms.-- Supports two modes:- - edit: Targeted string replacements with partial edits- - replace: Replace entire query atomically-- For edit mode, provide edits as an array of {old_string, new_string, replace_all} objects.- For replace mode, provide new_content with the complete SQL."- [{:keys [transform_id edit_action thinking transform_name transform_description- source_database source_tables]} :- write-transform-sql-schema]- (try- (let [result (add-output- (transforms-write-tools/write-transform-sql- {:transform_id transform_id- :edit_action edit_action- :thinking thinking- :transform_name transform_name- :transform_description transform_description- :source_database source_database- :source_tables source_tables- :memory-atom shared/*memory-atom*- :context (shared/current-context)})- format-transform-write-output)- transform (get-in result [:structured-output :transform])- dep-issues (check-dependencies transform_id (:source transform))]- (cond-> result- dep-issues (update :instructions str (format-dependency-warnings dep-issues))))- (catch Exception e- (if (:agent-error? (ex-data e))- {:output (ex-message e)}- {:output (str "Failed to write SQL transform: " (or (ex-message e) "Unknown error"))}))))--(defenterprise ^{:tool-name "write_transform_python"- :schema [:=> [:cat write-transform-sql-schema] :map]- :capabilities #{:feature-transforms :feature-transforms-python :permission-write-transforms}- :ee-feature :transforms}- write-transform-python-tool- "Write Python transforms. EE-only; returns an error in OSS."- metabase-enterprise.metabot.agent.tools.transforms- [{:keys [_transform_id]}]- {:output "Python transform tools are only available in Metabase Enterprise Edition."})diff --git a/src/metabase/metabot/agent/user_context.clj b/src/metabase/metabot/agent/user_context.cljindex 9aff3c6cfa6..9341c1a8a35 100644--- a/src/metabase/metabot/agent/user_context.clj+++ b/src/metabase/metabot/agent/user_context.clj@@ -9,7 +9,7 @@[metabase.lib.core :as lib][metabase.metabot.tmpl :as te][metabase.metabot.tools.entity-details :as entity-details]- [metabase.metabot.tools.llm-representations :as llm-rep]+ [metabase.metabot.tools.shared.llm-representations :as llm-rep][metabase.util :as u][metabase.util.log :as log])(:importdiff --git a/src/metabase/metabot/api.clj b/src/metabase/metabot/api.cljindex 4743b02792c..1b2e56cd4fd 100644--- a/src/metabase/metabot/api.clj+++ b/src/metabase/metabot/api.clj@@ -12,16 +12,13 @@[metabase.metabot.api.describe][metabase.metabot.api.document][metabase.metabot.api.metabot]- [metabase.metabot.client :as metabot.client]- [metabase.metabot.client.schema :as metabot.client.schema][metabase.metabot.config :as metabot.config][metabase.metabot.context :as metabot.context][metabase.metabot.envelope :as metabot.envelope][metabase.metabot.feedback :as metabot.feedback]+ [metabase.metabot.schema :as metabot.schema][metabase.metabot.self.core :as self.core][metabase.metabot.settings :as metabot.settings]- [metabase.metabot.tools.api]- [metabase.metabot.util :as metabot.u][metabase.server.streaming-response :as sr][metabase.slackbot.api][metabase.util :as u]@@ -32,8 +29,7 @@(java.io OutputStream)))(comment- metabase.metabot.api.describe/keep-me- metabase.metabot.tools.api/keep-me)+ metabase.metabot.api.describe/keep-me)(set! *warn-on-reflection* true)@@ -210,36 +206,15 @@debug? (and config/is-dev? (boolean debug))](store-aiservice-messages! conversation_id profile-id [message])- (if (metabot.settings/use-native-agent)- ;; Use native Clojure agent- (do- (log/info "Using native Clojure agent" {:profile-id profile-id :debug? debug?})- (native-agent-streaming-request- {:metabot-id metabot-id- :profile-id profile-id- :message message- :context context- :history history- :conversation-id conversation_id- :state state- :debug? debug?}))-- ;; Fallback to Python AI Service- (let [session-id (metabot.client/get-ai-service-token api/*current-user-id* metabot-id)]- (log/info "Using Python AI Service" {:profile-id profile-id :debug? debug?})- (metabot.client/streaming-request- {:context (metabot.context/create-context context)- :metabot-id metabot-id- :profile-id profile-id- :session-id session-id- :conversation-id conversation_id- :message message- :history history- :state state- :debug? debug?- :on-complete (fn [lines]- (store-aiservice-messages! conversation_id profile-id (metabot.u/aisdk->messages :assistant lines))- :store-in-db)})))))+ (log/info "Using native Clojure agent" {:profile-id profile-id :debug? debug?})+ (native-agent-streaming-request+ {:profile-id profile-id+ :message message+ :context context+ :history history+ :conversation-id conversation_id+ :state state+ :debug? debug?})));; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to;; use our API + we will need it when we make auto-TypeScript-signature generation happen@@ -255,7 +230,7 @@[:message ms/NonBlankString][:context ::metabot.context/context][:conversation_id ms/UUIDString]- [:history [:maybe ::metabot.client.schema/messages]]+ [:history [:maybe ::metabot.schema/messages]][:state :map][:debug {:optional true} [:maybe :boolean]]]](metabot.context/log body :llm.log/fe->be)@@ -285,7 +260,6 @@{"/metabot" metabase.metabot.api.metabot/routes"/document" metabase.metabot.api.document/routes;; premium check happens in the route so we still ack events to prevent slack retrying- "/slack" metabase.slackbot.api/routes- "/tools" (api.macros/ns-handler 'metabase.metabot.tools.api +auth)})+ "/slack" metabase.slackbot.api/routes})(api.macros/ns-handler 'metabase.metabot.api.describe +auth)(api.macros/ns-handler *ns* +auth)))diff --git a/src/metabase/metabot/api/document.clj b/src/metabase/metabot/api/document.cljindex b77c1ef2839..bdcc257e1f3 100644--- a/src/metabase/metabot/api/document.clj+++ b/src/metabase/metabot/api/document.clj@@ -2,66 +2,29 @@"`/api/metabot/document` routes"(:require[clojure.string :as str]- [metabase.api.common :as api][metabase.api.macros :as api.macros][metabase.api.routes.common :refer [+auth]][metabase.metabot.agent.core :as metabot.agent]- [metabase.metabot.client :as metabot.client][metabase.metabot.context :as metabot.context]- [metabase.metabot.table-utils :as table-utils]- [metabase.query-processor.core :as qp]- [metabase.util.malli.schema :as ms]- [metabase.warehouses.core :as warehouses]))+ [metabase.util.malli.schema :as ms]))(set! *warn-on-reflection* true)-(defn- fix-sql [fix-request]- (let [response (metabot.client/fix-sql fix-request)- return-sql (:sql fix-request)]- (when-let [fixes (:fixes response)]- (str/join "\n" (reduce- (fn [sql-lines fix]- (assoc sql-lines (dec (:line_number fix)) (:fixed_sql fix)))- (vec (str/split-lines return-sql))- fixes)))))+(def ^:private generate-content-body-schema+ [:map+ [:instructions ms/NonBlankString]+ [:references {:optional true} ms/Map]])-(defn- check-query- "If the query is valid, return nil. If not, return the error message."- [query]- (try- (qp/process-query query)- nil- (catch Exception e- (ex-message e))))--(defn- maybe-fix-native-sql- [response references]- (let [query (get-in response [:draft_card :dataset_query])]- (if-let [error (when (= "native" (name (:type query))) (check-query query))]- (let [db-id (-> references- keys- first- name- (#(str/split % #":"))- last- Integer/parseInt)- db (warehouses/get-database db-id)- schema-ddl (table-utils/schema-full db-id)]- ;; Attempt to fix SQL 5 times before returning.- (loop [attempts-left 5- sql (get-in query [:native :query])- error error]- (let [fixed-sql (fix-sql {:sql sql- :dialect (:engine db)- :error_message error- :schema_ddl schema-ddl})- ;; Only re-check query if new SQL was produced.- error (when fixed-sql- (check-query (assoc-in query [:native :query] fixed-sql)))]- (if (and error (> attempts-left 1))- (recur (dec attempts-left) fixed-sql error)- (assoc-in response [:draft_card :dataset_query :native :query] (or fixed-sql sql))))))- response)))+(def ^:private generate-content-response-schema+ [:map+ [:draft_card [:maybe [:map+ [:name ms/NonBlankString]+ [:dataset_query ms/Map]+ [:database_id ms/PositiveInt]+ [:parameters [:maybe [:sequential ms/Map]]]+ [:visualization_settings ms/Map]]]]+ [:error [:maybe ms/NonBlankString]]+ [:description [:maybe ms/NonBlankString]]])(defn- part->structured-output[part]@@ -93,6 +56,17 @@:parameters []:visualization_settings {}})))+(defn- last-tool-output-message+ [parts]+ (some->> parts+ reverse+ (keep (fn [part]+ (when (= :tool-output (:type part))+ (or (get-in part [:result :output])+ (some-> part :error :message)))))+ (remove str/blank?)+ first))+(defn- last-agent-message[parts](let [text-groups (reduce (fn [groups part]@@ -106,72 +80,39 @@(map #(str/trim (str/join "" %)))(remove str/blank?)first)]- last-text-message))--(defn- native-generate-content- [{:keys [instructions references]}]- (let [context (assoc- (metabot.context/create-context {:capabilities #{"permission:write_sql_queries"}})- :references references)- parts (into [] (metabot.agent/run-agent-loop- {:messages [{:role :user- :content instructions}]- :profile-id :document-generate-content- :state {}- :context context- :tracking-opts {:source "document_generate_content"- :track-user-intent? true}}))- chart-output (latest-chart-structured-output parts)- draft-card (draft-card-from-chart-output chart-output)- description (or (:description chart-output)- (:name chart-output)- (:name draft-card))]-- (if draft-card- (maybe-fix-native-sql {:draft_card draft-card- :description description- :error nil} references)- {:draft_card nil- :description nil- :error (or- (last-agent-message parts)- "Unable to generate chart content.")})))+ (or last-text-message+ (last-tool-output-message parts))))-;; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to-;; use our API + we will need it when we make auto-TypeScript-signature generation happen-;;-#_{:clj-kondo/ignore [:metabase/validate-defendpoint-has-response-schema]}-(api.macros/defendpoint :post "/generate-content"- "Create a new piece of content to insert into the document."+(api.macros/defendpoint :post "/generate-content" :- generate-content-response-schema+ "Create a new piece of content to insert into the document. Kept for backwards compatibility; now uses the native Clojure agent."[_route-params_query-params- body :- [:map- [:instructions ms/NonBlankString]- [:references {:optional true} ms/Map]]]- (let [response (metabot.client/document-generate-content {:instructions (:instructions body)- :references (:references body)- :user_id api/*current-user-id*- :conversation_id (str (random-uuid))})]- (maybe-fix-native-sql response (:references body))))--(api.macros/defendpoint :post "/native-generate-content" :- [:map- [:draft_card [:maybe [:map- [:name ms/NonBlankString]- [:dataset_query ms/Map]- [:database_id ms/PositiveInt]- [:parameters [:maybe [:sequential ms/Map]]]- [:visualization_settings ms/Map]]]]- [:error [:maybe ms/NonBlankString]]- [:description [:maybe ms/NonBlankString]]]- "Create a new piece of content to insert into the document using the native Clojure agent."- [_route-params- _query-params-- body :- [:map- [:instructions ms/NonBlankString]- [:references {:optional true} ms/Map]]]- (native-generate-content body))+ {:keys [instructions references]} :- generate-content-body-schema]+ (let [context (assoc+ (metabot.context/create-context {:capabilities #{"permission:write_sql_queries"}})+ :references references)+ parts (into [] (metabot.agent/run-agent-loop+ {:messages [{:role :user+ :content instructions}]+ :profile-id :document-generate-content+ :state {}+ :context context+ :tracking-opts {:source "document_generate_content"+ :track-user-intent? true}}))+ chart-output (latest-chart-structured-output parts)+ draft-card (draft-card-from-chart-output chart-output)+ description (or (:description chart-output)+ (:name chart-output)+ (:name draft-card))]+ (if draft-card+ {:draft_card draft-card+ :description description+ :error nil}+ {:draft_card nil+ :description nil+ :error (or (last-agent-message parts)+ "Unable to generate chart content.")})))(def ^{:arglists '([request respond raise])} routes"`/api/metabot/document` routes."diff --git a/src/metabase/metabot/api/sql_fixer.clj b/src/metabase/metabot/api/sql_fixer.cljdeleted file mode 100644index ab1b01148e9..00000000000--- a/src/metabase/metabot/api/sql_fixer.clj+++ /dev/null@@ -1,38 +0,0 @@-(ns metabase.metabot.api.sql-fixer- "`/api/ai-sql-fixer/` routes"- (:require- [metabase.api.macros :as api.macros]- [metabase.api.routes.common :refer [+auth]]- [metabase.driver.util :as driver.u]- [metabase.lib-be.core :as lib-be]- [metabase.lib.core :as lib]- [metabase.metabot.core :as metabot]- [metabase.query-processor.middleware.permissions :as qp.perms]- [metabase.util.malli.schema :as ms]))--(set! *warn-on-reflection* true)--;; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to-;; use our API + we will need it when we make auto-TypeScript-signature generation happen-;;-#_{:clj-kondo/ignore [:metabase/validate-defendpoint-has-response-schema]}-(api.macros/defendpoint :post "/fix"- "Suggest fixes for a SQL query."- [_route-params- _query-params- {:keys [query error_message]} :- [:map- [:query [:map- [:database ms/PositiveInt]]]- [:error_message :string]]]- (qp.perms/check-current-user-has-adhoc-native-query-perms query)- (let [driver (-> query :database driver.u/database->driver)- normalized-query (lib-be/normalize-query query)]- (-> (metabot/fix-sql {:sql (lib/raw-native-query normalized-query)- :dialect driver- :error_message error_message- :schema_ddl (metabot/schema-sample normalized-query)})- (select-keys [:fixes]))))--(def ^{:arglists '([request respond raise])} routes- "`/api/ai-sql-fixer` routes."- (api.macros/ns-handler *ns* +auth))diff --git a/src/metabase/metabot/api/sql_generation.clj b/src/metabase/metabot/api/sql_generation.cljdeleted file mode 100644index 21de66487c2..00000000000--- a/src/metabase/metabot/api/sql_generation.clj+++ /dev/null@@ -1,30 +0,0 @@-(ns metabase.metabot.api.sql-generation- "`/api/ai-sql-generation/` routes"- (:require- [metabase.api.macros :as api.macros]- [metabase.api.routes.common :refer [+auth]]- [metabase.driver.util :as driver.u]- [metabase.metabot.core :as metabot]- [metabase.util.malli.schema :as ms]))--(set! *warn-on-reflection* true)--;; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to-;; use our API + we will need it when we make auto-TypeScript-signature generation happen-;;-#_{:clj-kondo/ignore [:metabase/validate-defendpoint-has-response-schema]}-(api.macros/defendpoint :post "/generate"- "Generate a SQL query."- [_route-params- _query-params- {:keys [prompt database_id]} :- [:map- [:prompt ms/NonBlankString]- [:database_id ms/PositiveInt]]]- (-> (metabot/generate-sql {:dialect (driver.u/database->driver database_id)- :instructions prompt- :tables (metabot/database-tables database_id)})- (select-keys [:generated_sql])))--(def ^{:arglists '([request respond raise])} routes- "`/api/ai-sql-generation` routes."- (api.macros/ns-handler *ns* +auth))diff --git a/src/metabase/metabot/client.clj b/src/metabase/metabot/client.cljdeleted file mode 100644index 5925179a917..00000000000--- a/src/metabase/metabot/client.clj+++ /dev/null@@ -1,380 +0,0 @@-(ns metabase.metabot.client- (:require- [buddy.core.hash :as buddy-hash]- [buddy.sign.jwt :as jwt]- [clj-http.client :as http]- [clojure.core.async :as a]- [clojure.java.io :as io]- [clojure.set :as set]- [clojure.string :as str]- [java-time.api :as t]- [malli.core :as mc]- [malli.transform :as mtx]- [metabase.api.common :as api]- [metabase.metabot.client.schema :as metabot.client.schema]- [metabase.metabot.config :as metabot.config]- [metabase.metabot.context :as metabot.context]- [metabase.metabot.settings :as metabot.settings]- [metabase.premium-features.core :as premium-features]- [metabase.server.streaming-response :as sr]- [metabase.system.core :as system]- [metabase.util :as u]- [metabase.util.json :as json]- [metabase.util.log :as log]- [metabase.util.malli :as mu]- [metabase.util.malli.registry :as mr]- [metabase.util.o11y :refer [with-span]])- (:import- (java.io BufferedReader Closeable FilterInputStream InputStream)- (org.eclipse.jetty.io EofException)))--(set! *warn-on-reflection* true)--(def ^:dynamic ^:private *debug* false)--(defn get-ai-service-token- "Get the token for the AI service."- ([]- (get-ai-service-token api/*current-user-id* metabot.config/internal-metabot-id))-- ([user-id metabot-id]- (let [secret (buddy-hash/sha256 (metabot.settings/site-uuid-for-metabot-tools))- claims {:user user-id- :exp (t/plus (t/instant) (t/seconds (metabot.settings/metabot-ai-service-token-ttl)))- :metabot-id metabot-id}]- (jwt/encrypt claims secret {:alg :dir, :enc :a128cbc-hs256}))))--(defn- ->json-bytes ^bytes [x]- (with-open [os (java.io.ByteArrayOutputStream.)- w (java.io.OutputStreamWriter. os)]- (json/encode-to x w nil)- (.toByteArray os)))--(defn- build-request-options [body]- (merge- {:headers {"Accept" "application/json"- "Content-Type" "application/json;charset=UTF-8"- "x-metabase-instance-token" (premium-features/premium-embedding-token)}- :body (->json-bytes body)- :follow-redirects true- :throw-exceptions false}- (when *debug*- {:debug true})))--(mu/defn- maybe-parse-response-body-as-json :- :map- [response :- :map]- (let [json? (some-> (get-in response [:headers "Content-Type"]) (str/starts-with? "application/json"))]- (cond-> response- json? (update :body #(json/decode % true)))))--(defn- post! [url options]- (let [response-metadata (promise)- response-status (promise)]- (with-span :info {:name :metabot.client/request- :url url- :metadata response-metadata- :status response-status}- (u/prog1 (maybe-parse-response-body-as-json (http/post url options))- (deliver response-metadata (some-> <> :body :metadata))- (deliver response-status (some-> <> :status))))))--(defn- ai-url [path]- (str (metabot.settings/ai-service-base-url) path))--(defn- check-response!- "Returns response body on success (200 or 202), throws on failure."- [response request]- (if (#{200 202} (:status response))- (:body response)- (throw (ex-info (format "Unexpected status code: %d %s"- (:status response) (:reason-phrase response))- {:request (dissoc request :headers)- :response (dissoc response :headers)}))))--(defn- metric-selection-endpoint-url []- (str (metabot.settings/ai-service-base-url) "/v1/select-metric"))--(defn- fix-sql-endpoint []- (str (metabot.settings/ai-service-base-url) "/v1/sql/fix"))--(defn- generate-sql-endpoint []- (str (metabot.settings/ai-service-base-url) "/v1/sql/generate"))--(defn- analyze-chart-endpoint []- (str (metabot.settings/ai-service-base-url) "/v1/analyze/chart"))--(defn- analyze-dashboard-endpoint []- (str (metabot.settings/ai-service-base-url) "/v1/analyze/dashboard"))--(defn- example-question-generation-endpoint []- (str (metabot.settings/ai-service-base-url) "/v1/example-question-generation/batch"))--(defn- document-generate-content-endpoint []- (str (metabot.settings/ai-service-base-url) "/v1/document/generate-content"))--(defn- quick-closing-body- "Some requests come with body wrapped in ContentLengthInputStream, and that will never close the underlying stream.- So we just close the client itself.-- Please use `Connection: close` header when using this function to prevent connection being reused by HttpClient.-- See: https://github.com/dakrone/clj-http/issues/627- Also: metabase.metabot.api-test/closing-connection-test (for 'chunked')"- [response]- (proxy [FilterInputStream] [^InputStream (:body response)]- (close []- (.close ^Closeable (:http-client response)))))--(defn- open-ai-stream!- "Make a streaming request to the AI service. Returns the HTTP response.- Caller is responsible for reading from the response body and closing it."- [{:keys [context message history profile-id conversation-id session-id state debug?]}]- (let [url (ai-url "/v2/agent/stream")- body (cond-> {:messages (conj (vec history) message)- :context context- :conversation_id conversation-id- :profile_id profile-id- :user_id api/*current-user-id*- :state state}- debug? (assoc :debug true))- _ (metabot.context/log body :llm.log/be->llm)- _ (log/debugf "V2 request to AI Proxy:\n%s" (u/pprint-to-str body))- options (cond-> {:headers {"Accept" "text/event-stream"- "Content-Type" "application/json;charset=UTF-8"- "x-metabase-instance-token" (premium-features/premium-embedding-token)- "x-metabase-session-token" session-id- "x-metabase-url" (system/site-url)- "Connection" "close"}- :body (->json-bytes body)- :throw-exceptions false- :as :stream- :decompress-body false}- *debug* (assoc :debug true))- response (post! url options)]- (log/debugf "Response from AI Proxy:\n%s" (u/pprint-to-str (select-keys response #{:body :status :headers})))- (when-not (#{200 202} (:status response))- (check-response! response body))- response))--(mu/defn streaming-request :- :any- "Make a streaming V2 request to the AI Service-- This implements the streaming support for Metabot-- Clojure backend makes the request to the AI Service which respond immediately with a response and starts- streaming the response chunks back. We want to ship these to the frontend as soon as possible to give- the user the ability to consume the response before it's done.-- Since we want to send the chunks to the frontend as soon as possible, we manually write to the output stream- and flush after every chunk. If we've just returned the `response` object, ring would handle it correctly- but would also buffer the response.-- Response chunks are encoded in the format understood by the frontend and AI Service, Clojure backend doesn't- know anything about it and just shuttles them over.- "- [{:keys [on-complete] :as opts}- :- [:map- [:context :map]- [:message ::metabot.client.schema/message]- [:history ::metabot.client.schema/messages]- [:profile-id :string]- [:conversation-id :string]- [:session-id :string]- [:state :map]- [:debug? {:optional true} [:maybe :boolean]]- [:on-complete {:optional true} [:function [:=> [:cat :any] :any]]]]]- (try- (let [response (open-ai-stream! opts)- lines (when on-complete (atom []))- canceled (atom nil)]- (sr/streaming-response {:content-type "text/event-stream; charset=utf-8"} [os canceled-chan]- (with-open [^BufferedReader response-reader (io/reader (quick-closing-body response))]- (loop [^String line (.readLine response-reader)]- (cond- (nil? line) nil- (a/poll! canceled-chan) (do (reset! canceled true)- (log/debug "Request cancelled"))- :else- (do- (when on-complete- (swap! lines conj line))- (try- (doto os- (.write (.getBytes line "UTF-8"))- (.write (.getBytes "\n"))- (.flush))- (catch EofException _- (reset! canceled true)- (log/debug "Request cancelled, through exception")))- (when-not @canceled- (recur (.readLine response-reader)))))))- (when on-complete- (on-complete @lines))))- (catch Throwable e- (throw (ex-info (format "Error in request to AI Proxy: %s" (ex-message e)) {} e)))))--(mu/defn streaming-request-with-callback :- [:sequential :string]- "Make a streaming V2 request to the AI Service, invoking a callback for each line.- Unlike `streaming-request`, this doesn't return a StreamingResponse - it processes- the stream internally and calls `on-line` for each line as it arrives.- Returns the collected lines when complete."- [{:keys [on-line on-complete] :as opts}- :- [:map- [:context :map]- [:message ::metabot.client.schema/message]- [:history ::metabot.client.schema/messages]- [:profile-id :string]- [:conversation-id :string]- [:session-id :string]- [:state :map]- [:on-line {:optional true} [:function [:=> [:cat :string] :any]]]- [:on-complete {:optional true} [:function [:=> [:cat :any] :any]]]]]- (let [response (open-ai-stream! opts)- lines (atom [])]- (try- (with-open [^BufferedReader response-reader (io/reader (quick-closing-body response))]- (loop [^String line (.readLine response-reader)]- (when line- (swap! lines conj line)- (when on-line (on-line line))- (recur (.readLine response-reader)))))- (when on-complete- (on-complete @lines))- (catch java.io.IOException e- (log/debugf e "Stream closed while reading AI response (%d lines collected)" (count @lines))))- @lines))--(mu/defn select-metric-request- "Make a request to AI Service to select a metric."- [metrics :- [:sequential ::metabot.client.schema/metric]- query :- :string]- (try- (let [url (metric-selection-endpoint-url)- body {:metrics metrics- :query query}- options (build-request-options body)- response (post! url options)]- (u/prog1 (check-response! response body)- (log/debugf "Response:\n%s" (u/pprint-to-str <>))))- (catch Throwable e- (throw (ex-info (format "Error in request to AI Service: %s" (ex-message e))- {}- e)))))--(mu/defn fix-sql- "Ask the AI service to propose fixes a SQL query and a given error."- [body :- [:map- [:sql :string]- [:dialect :keyword]- [:error_message :string]- [:schema_ddl {:optional true} :string]]]- (let [url (fix-sql-endpoint)- options (build-request-options body)- response (post! url options)]- (check-response! response body)))--(mu/defn generate-sql- "Ask the AI service to generate a SQL query based on provided instructions."- [body :- [:map- [:dialect :keyword]- [:instructions :string]- [:tables [:sequential [:map- [:name :string]- [:schema {:optional true} [:maybe :string]]- [:description {:optional true} [:maybe :string]]- [:columns [:sequential [:map- [:name :string]- [:data_type :string]- [:description {:optional true} [:maybe :string]]]]]]]]]]- (let [url (generate-sql-endpoint)- options (build-request-options body)- response (post! url options)]- (check-response! response body)))--(mu/defn document-generate-content- "Ask the AI service to generate a new node for a document."- [body :- [:map- [:instructions :string]]]- (let [url (document-generate-content-endpoint)- options (build-request-options body)- headers (merge (:headers options) {"x-metabase-session-token" (get-ai-service-token)- "x-metabase-url" (system/site-url)})- options (assoc options :headers headers)- response (post! url options)]- (check-response! response body)))--(def chart-analysis-schema- "Schema for chart analysis data input."- [:map- [:image_base64 :string]- [:chart {:optional true} [:map- [:name {:optional true} [:maybe :string]]- [:description {:optional true} [:maybe :string]]]]- [:timeline_events {:optional true} [:sequential [:map- [:name :string]- [:description {:optional true} [:maybe :string]]- [:timestamp :string]]]]])--(mu/defn analyze-chart- "Ask the AI service to analyze a chart image."- [chart-data :- chart-analysis-schema]- (let [url (analyze-chart-endpoint)- options (build-request-options chart-data)- response (post! url options)]- (check-response! response chart-data)))--(def dashboard-analysis-schema- "Schema for dashboard analysis data input."- [:map- [:image_base64 :string]- [:dashboard {:optional true} [:map- [:name {:optional true} [:maybe :string]]- [:description {:optional true} [:maybe :string]]- [:tab_name {:optional true} [:maybe :string]]]]])--(mu/defn analyze-dashboard- "Ask the AI service to analyze a dashboard image."- [dashboard-data :- dashboard-analysis-schema]- (let [url (analyze-dashboard-endpoint)- options (build-request-options dashboard-data)- response (post! url options)]- (check-response! response dashboard-data)))--(mr/def ::example-generation-column- [:and- [:map- [:name :string]- [:type [:enum :number, :string, :date, :datetime, :time, :boolean, nil]]- [:description {:optional true} [:maybe :string]]- [:table-reference {:optional true} :string]]- [:map {:encode/ai-service-request #(set/rename-keys % {:table-reference :table_reference})}]])--(mr/def ::example-generation-payload- [:map- [:tables {:optional true}- [:sequential- [:map- [:name :string]- [:description {:optional true} [:maybe :string]]- [:fields [:sequential ::example-generation-column]]]]]- [:metrics {:optional true}- [:sequential- [:and- [:map- [:name :string]- [:description {:optional true} [:maybe :string]]- [:queryable-dimensions [:sequential ::example-generation-column]]- [:default-time-dimension {:optional true} ::example-generation-column]]- [:map {:encode/ai-service-request #(set/rename-keys % {:default-time-dimension :default_time_dimension- :queryable-dimensions :queryable_dimensions})}]]]]])--(mu/defn generate-example-questions- "Generate example questions for the given models and metrics."- [promptables :- ::example-generation-payload]- (let [url (example-question-generation-endpoint)- payload (mc/encode ::example-generation-payload- promptables- (mtx/transformer {:name :ai-service-request}))- options (build-request-options payload)- response (post! url options)]- (check-response! response payload)))diff --git a/src/metabase/metabot/config.clj b/src/metabase/metabot/config.cljindex 433058687e9..c0ab9a6789c 100644--- a/src/metabase/metabot/config.clj+++ b/src/metabase/metabot/config.clj@@ -56,6 +56,5 @@(resolve-dynamic-profile-id profile-id (resolve-dynamic-metabot-id nil)))([profile-id metabot-id](or profile-id- (metabot.settings/ai-service-profile-id)(metabot-id->profile-id metabot-id)"embedding_next")))diff --git a/src/metabase/metabot/core.clj b/src/metabase/metabot/core.cljindex 2245653a19a..1e22e3c21bb 100644--- a/src/metabase/metabot/core.clj+++ b/src/metabase/metabot/core.clj@@ -2,20 +2,19 @@"API namespace for the `metabase.metabot` module."(:require[metabase.metabot.api]- [metabase.metabot.client]- [metabase.metabot.table-utils]- [metabase.metabot.util][potemkin :as p]))(p/import-vars[metabase.metabot.api- routes]- [metabase.metabot.client- analyze-chart- analyze-dashboard- fix-sql- generate-sql]- [metabase.metabot.table-utils- database-tables- used-tables- schema-sample])+ routes])++;; TODO: Port analyze-chart to use the native LLM infrastructure+;; instead of the deleted `metabase.metabot.client`.+;; The frontend (`AIQuestionAnalysisSidebar`, `useDashCardAnalysis`) actively calls+;; `POST /api/ai-entity-analysis/analyze-chart` which hits this function.+(defn analyze-chart+ "Stub for legacy analyze-chart"+ [_chart-data]+ (throw (ex-info "Legacy Metabot AI-service function is no longer available: analyze-chart"+ {:status-code 501+ :function :analyze-chart})))diff --git a/src/metabase/metabot/example_question_generator.clj b/src/metabase/metabot/example_question_generator.cljindex bbc57d33e85..178a0239a70 100644--- a/src/metabase/metabot/example_question_generator.clj+++ b/src/metabase/metabot/example_question_generator.clj@@ -1,9 +1,6 @@(ns metabase.metabot.example-question-generator"Native Clojure generator for example questions (prompts) for Metabot.- Replaces the Python ai-service `/v1/example-question-generation/batch` endpoint- when `use-native-agent` is true.-Architecture mirrors the Python service:- Separate LLM call per table/metric (not one batch prompt)- Two distinct prompt templates: table.jinja → table.selmer, metric.jinja → metric.selmer@@ -161,11 +158,11 @@(defn generate-example-questions"Generate example questions natively using LLM via OpenRouter.- Accepts the same payload shape as `metabot.client/generate-example-questions`:+ Accepts a payload of the shape:{:tables [{:name ... :fields [...]}]:metrics [{:name ... :queryable-dimensions [...]}]}- Returns the same shape:+ Returns:{:table_questions [{:questions [...]}]:metric_questions [{:questions [...]}]}"[payload]diff --git a/src/metabase/metabot/client/schema.clj b/src/metabase/metabot/schema.cljsimilarity index 59%rename from src/metabase/metabot/client/schema.cljrename to src/metabase/metabot/schema.cljindex 1e56e693ecd..f1e4199d2c0 100644--- a/src/metabase/metabot/client/schema.clj+++ b/src/metabase/metabot/schema.clj@@ -1,4 +1,4 @@-(ns metabase.metabot.client.schema+(ns metabase.metabot.schema(:require[metabase.util :as u][metabase.util.malli.registry :as mr]))@@ -21,23 +21,3 @@(mr/def ::messages[:sequential ::message])--(mr/def ::metric- "A metric as sent to the AI Service"- [:map- [:id integer?]- [:name :string]- [:description [:maybe :string]]])--(mr/def ::usage- "Usage information with break down by model"- [:map-of :string [:map- [:prompt number?]- [:completion number?]]])--(mr/def ::ai-service.response- "Schema of the AI agent response."- [:map- [:messages ::messages]- [:state :map]- [:usage ::usage]])diff --git a/src/metabase/metabot/settings.clj b/src/metabase/metabot/settings.cljindex e58f49d6ba3..155bce5cbaf 100644--- a/src/metabase/metabot/settings.clj+++ b/src/metabase/metabot/settings.clj@@ -4,37 +4,6 @@[metabase.settings.core :as setting :refer [defsetting]][metabase.util.i18n :refer [deferred-tru tru]]))-;; TODO: these three settings support the external AI service, which is being removed.-;; Remove these (and the functions in metabase.metabot.client that use them) once-;; all code paths use the native Clojure agent.--(defsetting ai-service-base-url- (deferred-tru "URL for the AI Service")- :type :string- :encryption :no- :default "http://localhost:8000"- :visibility :internal- :export? false- :doc false)--(defsetting site-uuid-for-metabot-tools- "UUID that we use for encrypting JWT tokens given to the AI service to make callbacks with."- :encryption :when-encryption-key-set- :visibility :internal- :sensitive? true- :doc false- :export? false- :base setting/uuid-nonce-base)--(defsetting metabot-ai-service-token-ttl- (deferred-tru "The number of seconds the tokens passed to AI service should be valid.")- :type :integer- :visibility :settings-manager- :default 180- :doc false- :export? true- :audit :never)-(defsetting metabot-id(deferred-tru "Override Metabot ID for agent streaming requests."):type :string@@ -43,14 +12,6 @@:export? false:doc false)-(defsetting ai-service-profile-id- (deferred-tru "Override Metabot profile ID for agent streaming requests.")- :type :string- :visibility :internal- :encryption :no- :export? false- :doc false)-(defsetting metabot-enabled?(deferred-tru "Whether Metabot is enabled for regular usage."):type :boolean@@ -67,14 +28,6 @@:export? true:doc false)-(defsetting use-native-agent- (deferred-tru "Enable native Clojure agent instead of external Python AI Service.")- :type :boolean- :default true- :visibility :internal- :export? false- :doc false)-;;; ------------------------------------------------- LLM Provider ------------------------------------------------(def ^:private supported-metabot-providersdiff --git a/src/metabase/metabot/suggested_prompts.clj b/src/metabase/metabot/suggested_prompts.cljindex 2cf24cca0fc..883c4f542b2 100644--- a/src/metabase/metabot/suggested_prompts.clj+++ b/src/metabase/metabot/suggested_prompts.clj@@ -2,9 +2,7 @@(:require[medley.core :as m][metabase.lib-be.core :as lib-be]- [metabase.metabot.client :as metabot.client][metabase.metabot.example-question-generator :as native-generator]- [metabase.metabot.settings :as metabot.settings][metabase.metabot.tools.entity-details :as metabot.tools.entity-details][metabase.metabot.tools.util :as metabot.tools.u][metabase.util.log :as log]@@ -37,28 +35,13 @@{:limit 20})(defn- generate-questions-with-fallback- "Generate example questions using the configured path.-- When `use-native-agent` is true, calls the native Clojure generator.- On native failure, falls back to the Python ai-service and logs the error.- When `use-native-agent` is false, calls the Python ai-service directly."+ "Generate example questions using the configured path."[payload]- (if (metabot.settings/use-native-agent)- (try- (log/info "Using native generator for example questions"- {:table-count (count (:tables payload))- :metric-count (count (:metrics payload))})- (let [result (native-generator/generate-example-questions payload)]- (log/info "Native example question generation succeeded"- {:table-results (count (:table_questions result))- :metric-results (count (:metric_questions result))})- result)- (catch Exception e- (log/error e "Native example question generation failed, falling back to Python ai-service"- {:error-class (.getName (class e))- :error-msg (ex-message e)})- (metabot.client/generate-example-questions payload)))- (metabot.client/generate-example-questions payload)))+ (let [result (native-generator/generate-example-questions payload)]+ (log/info "Native example question generation succeeded"+ {:table-results (count (:table_questions result))+ :metric-results (count (:metric_questions result))})+ result))(defn generate-sample-prompts"Generate suggested prompts for instance of Metabot."diff --git a/src/metabase/metabot/agent/tools.clj b/src/metabase/metabot/tools.cljsimilarity index 75%rename from src/metabase/metabot/agent/tools.cljrename to src/metabase/metabot/tools.cljindex e1a5cc57a78..442cf55a70c 100644--- a/src/metabase/metabot/agent/tools.clj+++ b/src/metabase/metabot/tools.clj@@ -1,4 +1,4 @@-(ns metabase.metabot.agent.tools+(ns metabase.metabot.tools"Tool registry for the agent loop.Provides tool vars and state-aware wrapping.@@ -6,26 +6,26 @@`:capabilities`, `:prompt`, `:decode`, and `:system-instructions`. The var itselfis a function that takes the tool arguments and returns a result map."(:require- [metabase.metabot.agent.tools.analyze-chart :as tools.analyze-chart]- [metabase.metabot.agent.tools.autogen-dashboard :as tools.autogen-dashboard]- [metabase.metabot.agent.tools.charts :as tools.charts]- [metabase.metabot.agent.tools.clarification :as tools.clarification]- [metabase.metabot.agent.tools.construct :as tools.construct]- [metabase.metabot.agent.tools.create-alert :as tools.create-alert]- [metabase.metabot.agent.tools.create-dashboard-subscription :as tools.create-dashboard-subscription]- [metabase.metabot.agent.tools.document :as tools.document]- [metabase.metabot.agent.tools.metadata :as tools.metadata]- [metabase.metabot.agent.tools.navigation :as tools.navigation]- [metabase.metabot.agent.tools.resources :as tools.resources]- [metabase.metabot.agent.tools.search :as tools.search]- [metabase.metabot.agent.tools.shared :as shared]- [metabase.metabot.agent.tools.slackbot-query :as tools.slackbot-query]- [metabase.metabot.agent.tools.snippets :as tools.snippets]- [metabase.metabot.agent.tools.sql :as tools.sql]- [metabase.metabot.agent.tools.static-viz :as tools.static-viz]- [metabase.metabot.agent.tools.subscriptions :as tools.subscriptions]- [metabase.metabot.agent.tools.todo :as tools.todo]- [metabase.metabot.agent.tools.transforms :as tools.transforms]+ [metabase.metabot.tools.analyze-chart :as tools.analyze-chart]+ [metabase.metabot.tools.autogen-dashboard :as tools.autogen-dashboard]+ [metabase.metabot.tools.charts :as tools.charts]+ [metabase.metabot.tools.clarification :as tools.clarification]+ [metabase.metabot.tools.construct :as tools.construct]+ [metabase.metabot.tools.create-alert :as tools.create-alert]+ [metabase.metabot.tools.create-dashboard-subscription :as tools.create-dashboard-subscription]+ [metabase.metabot.tools.document :as tools.document]+ [metabase.metabot.tools.metadata :as tools.metadata]+ [metabase.metabot.tools.navigation :as tools.navigation]+ [metabase.metabot.tools.resources :as tools.resources]+ [metabase.metabot.tools.search :as tools.search]+ [metabase.metabot.tools.shared :as shared]+ [metabase.metabot.tools.slackbot-query :as tools.slackbot-query]+ [metabase.metabot.tools.snippets :as tools.snippets]+ [metabase.metabot.tools.sql :as tools.sql]+ [metabase.metabot.tools.static-viz :as tools.static-viz]+ [metabase.metabot.tools.subscriptions :as tools.subscriptions]+ [metabase.metabot.tools.todo :as tools.todo]+ [metabase.metabot.tools.transforms :as tools.transforms][potemkin :as p]))(set! *warn-on-reflection* true)diff --git a/src/metabase/metabot/agent/tools/analyze_chart.clj b/src/metabase/metabot/tools/analyze_chart.cljsimilarity index 97%rename from src/metabase/metabot/agent/tools/analyze_chart.cljrename to src/metabase/metabot/tools/analyze_chart.cljindex 0d83256af25..74eb2e50885 100644--- a/src/metabase/metabot/agent/tools/analyze_chart.clj+++ b/src/metabase/metabot/tools/analyze_chart.clj@@ -1,13 +1,13 @@-(ns metabase.metabot.agent.tools.analyze-chart+(ns metabase.metabot.tools.analyze-chart"Native agent tool for chart statistics analysis.Analyzes charts from viewing context. The frontend provides pre-materializedseries data in chart_configs, which is seeded into agent memory duringinitialization. This avoids re-executing queries."(:require- [metabase.metabot.agent.tools.shared :as shared][metabase.metabot.stats.core :as stats.core][metabase.metabot.stats.repr :as stats.repr]+ [metabase.metabot.tools.shared :as shared][metabase.util.log :as log][metabase.util.malli :as mu][tech.v3.resource :as resource]))diff --git a/src/metabase/metabot/tools/api.clj b/src/metabase/metabot/tools/api.cljdeleted file mode 100644index c101408adef..00000000000--- a/src/metabase/metabot/tools/api.clj+++ /dev/null@@ -1,867 +0,0 @@-(ns metabase.metabot.tools.api- "Tool definitions for the Metabot agent."- (:require- [clojure.set :as set]- ;; TODO (Cam 10/10/25) -- update MetaBot to use Lib + MBQL 5- ^{:clj-kondo/ignore [:discouraged-namespace]} [metabase.legacy-mbql.schema :as mbql.s]- [metabase.lib.schema.temporal-bucketing :as lib.schema.temporal-bucketing]- [metabase.metabot.reactions]- [metabase.metabot.table-utils :as table-utils]- [metabase.metabot.tools.create-alert :as metabot.tools.create-alert]- [metabase.metabot.tools.create-dashboard-subscription :as metabot.tools.create-dashboard-subscription]- [metabase.metabot.tools.deftool :refer [deftool]]- [metabase.metabot.tools.entity-details :as metabot.tools.entity-details]- [metabase.metabot.tools.field-stats :as metabot.tools.field-stats]- [metabase.metabot.tools.filters :as metabot.tools.filters]- [metabase.metabot.tools.generate-insights :as metabot.tools.generate-insights]- [metabase.metabot.tools.search :as metabot.tools.search]- [metabase.metabot.tools.snippets :as metabot.tools.snippets]- [metabase.metabot.util :as metabot.u]- [metabase.util :as u]- [metabase.util.malli.registry :as mr]- [metabase.util.malli.schema :as ms]))--;;; ------------------------------------------------ Shared Schemas --------------------------------------------------;; NOTE: Some of these schemas are duplicated with small differences in the Agent API-;; (metabase.agent-api.api). If you update schemas here, check if the-;; corresponding Agent API schemas need updating too.--(mr/def ::bucket- (into [:enum {:error/message "Valid bucket"- :encode/tool-api-request keyword}]- (map name)- lib.schema.temporal-bucketing/ordered-datetime-bucketing-units))--(mr/def ::existence-filter- [:and- [:map- [:field_id :string]- [:operation [:enum {:encode/tool-api-request keyword}- "is-null" "is-not-null"- "string-is-empty" "string-is-not-empty"- "is-true" "is-false"]]]- [:map {:encode/tool-api-request #(update-keys % metabot.u/safe->kebab-case-en)}]])--(mr/def ::temporal-extraction-filter- [:and- [:map- [:field_id :string]- [:operation [:enum {:encode/tool-api-request keyword}- "year-equals" "year-not-equals"- "quarter-equals" "quarter-not-equals"- "month-equals" "month-not-equals"- "day-of-week-equals" "day-of-week-not-equals"- "hour-equals" "hour-not-equals"- "minute-equals" "minute-not-equals"- "second-equals" "second-not-equals"]]- [:value :int]]- [:map {:encode/tool-api-request #(update-keys % metabot.u/safe->kebab-case-en)}]])--(mr/def ::disjunctive-temporal-extraction-filter- [:and- [:map- [:field_id :string]- [:operation [:enum {:encode/tool-api-request keyword}- "year-equals" "year-not-equals"- "quarter-equals" "quarter-not-equals"- "month-equals" "month-not-equals"- "day-of-week-equals" "day-of-week-not-equals"- "hour-equals" "hour-not-equals"- "minute-equals" "minute-not-equals"- "second-equals" "second-not-equals"]]- [:values [:sequential :int]]]- [:map {:encode/tool-api-request #(update-keys % metabot.u/safe->kebab-case-en)}]])--(mr/def ::temporal-filter- [:and- [:map- [:field_id :string]- [:bucket {:optional true} ::bucket]- [:operation [:enum {:encode/tool-api-request keyword}- "equals" "not-equals"- "greater-than" "greater-than-or-equal"- "less-than" "less-than-or-equal"]]- [:value [:or :string :int]]]- [:map {:encode/tool-api-request #(update-keys % metabot.u/safe->kebab-case-en)}]])--(mr/def ::disjunctive-temporal-filter- [:and- [:map- [:field_id :string]- [:bucket {:optional true} ::bucket]- [:operation [:enum {:encode/tool-api-request keyword}- "equals" "not-equals"- "greater-than" "greater-than-or-equal"- "less-than" "less-than-or-equal"]]- [:values [:sequential [:or :string :int]]]]- [:map {:encode/tool-api-request #(update-keys % metabot.u/safe->kebab-case-en)}]])--(mr/def ::string-filter- [:and- [:map- [:field_id :string]- [:operation [:enum {:encode/tool-api-request keyword}- "equals" "not-equals"- "string-contains" "string-not-contains"- "string-starts-with" "string-ends-with"]]- [:value :string]]- [:map {:encode/tool-api-request #(update-keys % metabot.u/safe->kebab-case-en)}]])--(mr/def ::disjunctive-string-date-filter- [:and- [:map- [:field_id :string]- [:operation [:enum {:encode/tool-api-request keyword}- "equals" "not-equals"- "string-contains" "string-not-contains"- "string-starts-with" "string-ends-with"]]- [:values [:sequential :string]]]- [:map {:encode/tool-api-request #(update-keys % metabot.u/safe->kebab-case-en)}]])--(mr/def ::numeric-filter- [:and- [:map- [:field_id :string]- [:operation [:enum {:encode/tool-api-request keyword}- "equals" "not-equals"- "greater-than" "greater-than-or-equal"- "less-than" "less-than-or-equal"]]- [:value [:or :int :double]]]- [:map {:encode/tool-api-request #(update-keys % metabot.u/safe->kebab-case-en)}]])--(mr/def ::disjunctive-numeric-filter- [:and- [:map- [:field_id :string]- [:operation [:enum {:encode/tool-api-request keyword}- "equals" "not-equals"]]- [:values [:sequential [:or :int :double]]]]- [:map {:encode/tool-api-request #(update-keys % metabot.u/safe->kebab-case-en)}]])--(mr/def ::segment-filter- "Filter using a pre-defined segment."- [:and- [:map- [:segment_id :int]]- [:map {:encode/tool-api-request #(update-keys % metabot.u/safe->kebab-case-en)}]])--(mr/def ::filter- [:or- ::segment-filter- ::existence-filter- ::temporal-extraction-filter ::disjunctive-temporal-extraction-filter- ::temporal-filter ::disjunctive-temporal-filter- ::string-filter ::disjunctive-string-date-filter- ::numeric-filter ::disjunctive-numeric-filter])--(mr/def ::group-by- [:and- [:map- [:field_id :string]- [:field_granularity {:optional true}- [:maybe [:enum {:encode/tool-api-request keyword}- "minute", "hour" "day" "week" "month" "quarter" "year" "day-of-week"]]]]- [:map {:encode/tool-api-request #(update-keys % metabot.u/safe->kebab-case-en)}]])--(mr/def ::count-aggregation- "Count aggregation — counts rows, no field_id needed.- Use sort_order to order results by this aggregation ('asc' or 'desc')."- [:and- [:map- [:function [:= {:encode/tool-api-request keyword} "count"]]- [:bucket {:optional true} ::bucket]- [:sort_order {:optional true} [:maybe [:enum {:encode/tool-api-request keyword} "asc" "desc"]]]]- [:map {:encode/tool-api-request #(update-keys % metabot.u/safe->kebab-case-en)}]])--(mr/def ::field-aggregation- "Aggregation using a field and function. field_id is required.- Use sort_order to order results by this aggregation ('asc' or 'desc')."- [:and- [:map- [:field_id :string]- [:bucket {:optional true} ::bucket]- [:sort_order {:optional true} [:maybe [:enum {:encode/tool-api-request keyword} "asc" "desc"]]]- [:function [:enum {:encode/tool-api-request keyword}- "avg" "count-distinct" "max" "min" "sum"]]]- [:map {:encode/tool-api-request #(update-keys % metabot.u/safe->kebab-case-en)}]])--(mr/def ::measure-aggregation- "Aggregation using a pre-defined measure."- [:and- [:map- [:measure_id :int]- [:sort_order {:optional true} [:maybe [:enum {:encode/tool-api-request keyword} "asc" "desc"]]]]- [:map {:encode/tool-api-request #(update-keys % metabot.u/safe->kebab-case-en)}]])--(mr/def ::aggregation- "Aggregation — count (field optional), field-based (field required), or measure-based."- [:or ::count-aggregation ::field-aggregation ::measure-aggregation])--(mr/def ::field- [:and- [:map- [:field_id :string]- [:bucket {:optional true} ::bucket]]- [:map {:encode/tool-api-request #(update-keys % metabot.u/safe->kebab-case-en)}]])--(mr/def ::order-by- "Order by item specifying a field and sort direction."- [:map- [:field ::field]- [:direction [:enum {:encode/tool-api-request keyword} "asc" "desc"]]])--(mr/def ::count- [:and- :int- [:fn- {:error/message "Valid count, a natural number"}- #(<= 0 %)]])--(mr/def ::proportion- [:and- number?- [:fn- {:error/message "Valid proportion between (inclusive) 0 and 1."}- #(<= 0 % 1)]])--(mr/def ::field-values- [:or- [:sequential :boolean]- [:sequential number?]- [:sequential :string]])--(mr/def ::statistics- [:map {:decode/tool-api-response #(update-keys % metabot.u/safe->snake_case_en)}- [:distinct_count {:optional true} [:maybe ::count]]- [:percent_null {:optional true} [:maybe ::proportion]]- [:min {:optional true} [:maybe number?]]- [:max {:optional true} [:maybe number?]]- [:avg {:optional true} [:maybe number?]]- [:q1 {:optional true} [:maybe number?]]- [:q3 {:optional true} [:maybe number?]]- [:sd {:optional true} [:maybe number?]]- [:percent_json {:optional true} [:maybe ::proportion]]- [:percent_url {:optional true} [:maybe ::proportion]]- [:percent_email {:optional true} [:maybe ::proportion]]- [:percent_state {:optional true} [:maybe ::proportion]]- [:average_length {:optional true} [:maybe number?]]- [:earliest {:optional true} [:maybe :string]]- [:latest {:optional true} [:maybe :string]]- [:values {:optional true} [:maybe ::field-values]]])--(mr/def ::field-type- [:enum {:decode/tool-api-response #(when % (-> % name u/->snake_case_en))}- "boolean" "date" "datetime" "time" "number" "string"])--(mr/def ::column- [:map {:decode/tool-api-response #(update-keys % metabot.u/safe->snake_case_en)}- [:field_id :string]- [:name :string]- [:type [:maybe ::field-type]]- [:description {:optional true} [:maybe :string]]- [:database_type {:optional true- :decode/tool-api-response #(some-> % name u/->snake_case_en)}- [:maybe :string]]- [:semantic_type {:optional true- :decode/tool-api-response #(some-> % name u/->snake_case_en)}- [:maybe :string]]- [:field_values {:optional true} ::field-values]])--(mr/def ::columns- [:sequential ::column])--(mr/def ::filtering-result- [:or- [:map {:decode/tool-api-response #(update-keys % metabot.u/safe->snake_case_en)}- [:structured_output- [:map {:decode/tool-api-response #(update-keys % metabot.u/safe->snake_case_en)}- [:type [:= :query]]- [:query_id :string]- [:query ::mbql.s/Query]- [:result_columns [:sequential ::column]]]]]- [:map- [:output :string]]])--(mr/def ::basic-metric- [:map {:decode/tool-api-response #(update-keys % metabot.u/safe->snake_case_en)}- [:id :int]- [:type [:= :metric]]- [:name :string]- [:description {:optional true} [:maybe :string]]- [:default_time_dimension_field_id {:optional true} [:maybe :string]]])--(mr/def ::full-metric- [:merge- ::basic-metric- [:map {:decode/tool-api-response #(update-keys % metabot.u/safe->snake_case_en)}- [:queryable_dimensions {:optional true} ::columns]- [:segments {:optional true} [:sequential ::segment]]- [:verified {:optional true} :boolean]]])--(mr/def ::measure- [:map {:decode/tool-api-response #(update-keys % metabot.u/safe->snake_case_en)}- [:id :int]- [:name :string]- [:display_name {:optional true} [:maybe :string]]- [:description {:optional true} [:maybe :string]]- [:definition {:optional true} [:maybe :map]]])--(mr/def ::segment- [:map {:decode/tool-api-response #(update-keys % metabot.u/safe->snake_case_en)}- [:id :int]- [:name :string]- [:display_name {:optional true} [:maybe :string]]- [:description {:optional true} [:maybe :string]]- [:definition {:optional true} [:maybe :map]]])--(mr/def ::table-result- [:map- [:id :int]- [:type [:enum :model :table]]- [:name :string]- [:display_name :string]- [:database_id :int]- [:database_engine :string]- [:database_schema {:optional true} [:maybe :string]] ; Schema name, if applicable- [:fields ::columns]- [:related_tables {:optional true} [:sequential [:ref ::table-result]]]- [:related_by {:optional true} [:maybe :string]]- [:description {:optional true} [:maybe :string]]- [:metrics {:optional true} [:sequential ::basic-metric]]- [:measures {:optional true} [:sequential ::measure]]- [:segments {:optional true} [:sequential ::segment]]])--(mr/def ::basic-snippet- [:map {:decode/tool-api-response #(update-keys % metabot.u/safe->snake_case_en)}- [:id :int]- [:name :string]- [:description {:optional true} [:maybe :string]]])--(mr/def ::full-snippet- [:merge- ::basic-snippet- [:map {:decode/tool-api-response #(update-keys % metabot.u/safe->snake_case_en)}- [:content :string]]])--;;; ---------------------------------------------- Discovery & Search -------------------------------------------------(mr/def ::answer-sources-arguments- [:and- [:map- [:with_model_fields {:optional true, :default true} :boolean]- [:with_model_metrics {:optional true, :default true} :boolean]- [:with_metric_default_temporal_breakout {:optional true, :default true} :boolean]- [:with_metric_queryable_dimensions {:optional true, :default true} :boolean]]- [:map {:encode/tool-api-request- #(set/rename-keys % {:with_model_fields :with-fields?- :with_model_metrics :with-metrics?- :with_metric_default_temporal_breakout :with-default-temporal-breakout?- :with_metric_queryable_dimensions :with-queryable-dimensions?})}]])--(mr/def ::answer-sources-result- [:or- [:map- {:decode/tool-api-response #(update-keys % metabot.u/safe->snake_case_en)}- [:structured_output [:map- [:metrics [:sequential ::full-metric]]- [:models [:sequential ::table-result]]]]]- [:map [:output :string]]])--(deftool "/answer-sources"- "Return top level meta information about available information sources."- {:args-schema ::answer-sources-arguments- :args-optional? true- :result-schema ::answer-sources-result- :handler metabot.tools.entity-details/answer-sources})--(mr/def ::search-arguments- [:and- [:map- [:term_queries {:optional true} [:maybe [:sequential :string]]]- [:semantic_queries {:optional true} [:maybe [:sequential :string]]]- [:entity_types {:optional true} [:maybe [:sequential [:enum "table" "model" "question" "dashboard" "metric" "database" "transform"]]]]- [:database_id {:optional true} [:maybe :int]]- [:created_at {:optional true} [:maybe ms/NonBlankString]]- [:last_edited_at {:optional true} [:maybe ms/NonBlankString]]- [:search_native_query {:optional true, :default false} [:maybe :boolean]]- [:limit {:optional true, :default 50} [:and :int [:fn #(<= 1 % 100)]]]- [:weights {:optional true} [:map-of :keyword number?]]]- [:map {:encode/tool-api-request- #(update-keys % (comp keyword u/->kebab-case-en))}]])--(mr/def ::search-result-item- "Unified schema for search result items."- [:map {:decode/tool-api-response #(update-keys % metabot.u/safe->snake_case_en)}- [:id :int]- [:type [:enum :table :model :dashboard :question :metric :database :transform]]- [:name :string]- [:display_name {:optional true} [:maybe :string]]- [:description {:optional true} [:maybe :string]]- [:database_id {:optional true} [:maybe :int]]- [:database_schema {:optional true} [:maybe :string]]- [:verified {:optional true} [:maybe :boolean]]- [:updated_at {:optional true} [:maybe :string]]- [:created_at {:optional true} [:maybe :string]]- [:collection {:optional true} [:maybe [:map- [:name {:optional true} [:maybe :string]]- [:authority_level {:optional true} [:maybe :string]]- [:description {:optional true} [:maybe :string]]]]]])--(mr/def ::search-result- [:or- [:map- {:decode/tool-api-response #(update-keys % metabot.u/safe->snake_case_en)}- [:structured_output [:map- [:data [:sequential ::search-result-item]]- [:total_count :int]]]]- [:map [:output :string]]])--(deftool "/search"- "Enhanced search with term and semantic queries using Reciprocal Rank Fusion."- {:args-schema ::search-arguments- :args-optional? true- :result-schema ::search-result- :handler metabot.tools.search/search-tool})--;; TODO (Cam 10/28/25) -- fix this endpoint route to use kebab-case for consistency with the rest of our REST API-#_{:clj-kondo/ignore [:metabase/validate-defendpoint-route-uses-kebab-case]}-(deftool "/search_v2"- "Enhanced search with term and semantic queries using Reciprocal Rank Fusion. This is identical to /search, but- duplicated in order to add a new capability to AI service that indicates that Metabot can search transforms. The- /search endpoint is kept around for backward compatibility."- {:args-schema ::search-arguments- :args-optional? true- :result-schema ::search-result- :handler metabot.tools.search/search-tool})--;;; ----------------------------------------------------- Actions -------------------------------------------------------(mr/def ::subscription-schedule- (let [days ["sunday" "monday" "tuesday" "wednesday" "thursday" "friday" "saturday"]]- [:and- [:or- [:map- [:frequency [:= {:encode/tool-api-request keyword} "hourly"]]]- [:map- [:frequency [:= {:encode/tool-api-request keyword} "daily"]]- [:hour :int]]- [:map- [:frequency [:= {:encode/tool-api-request keyword} "weekly"]]- [:hour :int]- [:day_of_week (into [:enum {:encode/tool-api-request keyword}] days)]]- [:map- [:frequency [:= {:encode/tool-api-request keyword} "monthly"]]- [:hour :int]- [:day_of_month (into [:enum {:encode/tool-api-request keyword}- "first-calendar-day" "middle-of-month" "last-calendar-day"]- (for [fl ["first" "last"]- day days]- (str fl "-" day)))]]]- [:map {:encode/tool-api-request #(update-keys % metabot.u/safe->kebab-case-en)}]]))--(mr/def ::create-dashboard-subscription-arguments- [:and- [:map- [:dashboard_id :int]- [:slack_channel :string]- [:schedule ::subscription-schedule]]- [:map {:encode/tool-api-request #(update-keys % metabot.u/safe->kebab-case-en)}]])--(deftool "/create-dashboard-subscription"- "Create a dashboard subscription and send it to a slack channel."- {:args-schema ::create-dashboard-subscription-arguments- :result-schema [:map [:error {:optional true} :string- :output {:optional true} :string]]- :handler metabot.tools.create-dashboard-subscription/create-dashboard-subscription})--(mr/def ::create-alert-arguments- [:and- [:map- [:card_id :int]- [:send_condition [:enum {:encode/tool-api-request keyword} "has_result" "goal_above" "goal_below"]]- [:send_once {:optional true, :default false} :boolean]- [:schedule ::subscription-schedule]- [:slack_channel :string]]- [:map {:encode/tool-api-request #(update-keys % metabot.u/safe->kebab-case-en)}]])--(deftool "/create-alert"- "Create an alert for a saved question."- {:args-schema ::create-alert-arguments- :result-schema [:map [:error {:optional true} :string- :output {:optional true} :string]]- :handler metabot.tools.create-alert/create-alert})--;;; ---------------------------------------------------- Analytics ------------------------------------------------------(mr/def ::field-values-arguments- [:and- [:map- [:entity_type [:enum "table" "model" "metric"]]- [:entity_id :int]- [:field_id :string]- [:limit {:optional true} [:maybe :int]]]- [:map {:encode/tool-api-request #(update-keys % metabot.u/safe->kebab-case-en)}]])--(mr/def ::field-values-result- [:or- [:map {:decode/tool-api-response #(update-keys % metabot.u/safe->snake_case_en)}- [:structured_output- [:map {:decode/tool-api-response #(update-keys % metabot.u/safe->snake_case_en)}- [:field_id :string]- [:value_metadata [:map- [:field_values {:optional true} [:maybe [:sequential :any]]]- [:statistics {:optional true} [:maybe ::statistics]]]]]]]- [:map- [:output :string]]])--(deftool "/field-values"- "Return statistics and/or values for a given field of a given entity."- {:args-schema ::field-values-arguments- :result-schema ::field-values-result- :handler metabot.tools.field-stats/field-values})--(mr/def ::generate-insights-arguments- [:map- ;; query should not be changed to kebab-case- {:encode/tool-api-request #(update-keys % metabot.u/safe->kebab-case-en)}- [:for [:or- [:map [:metric_id :int]]- [:map [:table_id :string]]- [:map [:report_id :int]]- [:map [:query :map]]]]])--(deftool "/generate-insights"- "Generate insights."- {:args-schema ::generate-insights-arguments- :result-schema [:map- [:output :string]- [:reactions [:sequential :metabot.reaction/redirect]]]- :handler metabot.tools.generate-insights/generate-insights})--;;; -------------------------------------------------- Entity Details ---------------------------------------------------(mr/def ::get-current-user-result- [:or- [:map {:decode/tool-api-response #(update-keys % metabot.u/safe->snake_case_en)}- [:structured_output [:map {:decode/tool-api-response #(update-keys % metabot.u/safe->snake_case_en)}- [:id :int]- [:type [:= :user]]- [:name :string]- [:email_address :string]- [:glossary [:maybe [:map-of :string :string]]]]]]- [:map [:output :string]]])--(deftool "/get-current-user"- "Get information about user that started the conversation."- {:result-schema ::get-current-user-result- :handler metabot.tools.entity-details/get-current-user})--(mr/def ::get-dashboard-details-arguments- [:and- [:map [:dashboard_id :int]]- [:map {:encode/tool-api-request #(set/rename-keys % {:dashboard_id :dashboard-id})}]])--(mr/def ::get-dashboard-details-result- [:or- [:map- {:decode/tool-api-response #(update-keys % metabot.u/safe->snake_case_en)}- [:structured_output [:map- [:id :int]- [:type [:= :dashboard]]- [:name :string]- [:description {:optional true} :string]- [:verified {:optional true} :boolean]]]]- [:map [:output :string]]])--(deftool "/get-dashboard-details"- "Get information about a given dashboard."- {:args-schema ::get-dashboard-details-arguments- :result-schema ::get-dashboard-details-result- :handler metabot.tools.entity-details/get-dashboard-details})--(mr/def ::get-metric-details-arguments- [:and- [:map- [:metric_id :int]- [:with_default_temporal_breakout {:optional true, :default true} :boolean]- [:with_field_values {:optional true, :default true} :boolean]- [:with_queryable_dimensions {:optional true, :default true} :boolean]- [:with_segments {:optional true, :default false} :boolean]]- [:map {:encode/tool-api-request- #(set/rename-keys % {:metric_id :metric-id- :with_default_temporal_breakout :with-default-temporal-breakout?- :with_field_values :with-field-values?- :with_queryable_dimensions :with-queryable-dimensions?- :with_segments :with-segments?})}]])--(mr/def ::get-metric-details-result- [:or- [:map {:decode/tool-api-response #(update-keys % metabot.u/safe->snake_case_en)}- [:structured_output ::full-metric]]- [:map [:output :string]]])--(deftool "/get-metric-details"- "Get information about a given metric."- {:args-schema ::get-metric-details-arguments- :result-schema ::get-metric-details-result- :handler metabot.tools.entity-details/get-metric-details})--(mr/def ::get-query-details-arguments- [:map [:query :map]])--(mr/def ::get-query-details-result- [:or- [:map- {:decode/tool-api-response #(update-keys % metabot.u/safe->snake_case_en)}- [:structured_output [:map- {:decode/tool-api-response #(update-keys % metabot.u/safe->snake_case_en)}- [:type [:= :query]]- [:query_id :string]- [:query :map]- [:result_columns ::columns]]]]- [:map [:output :string]]])--(deftool "/get-query-details"- "Get information about a given query."- {:args-schema ::get-query-details-arguments- :result-schema ::get-query-details-result- :handler metabot.tools.entity-details/get-query-details})--(mr/def ::get-report-details-arguments- [:and- [:map- [:report_id :int]- [:with_fields {:optional true, :default true} :boolean]- [:with_field_values {:optional true, :default true} :boolean]]- [:map {:encode/tool-api-request- #(set/rename-keys % {:report_id :report-id- :with_fields :with-fields?- :with_field_values :with-field-values?})}]])--(mr/def ::get-report-details-result- [:or- [:map- {:decode/tool-api-response #(update-keys % metabot.u/safe->snake_case_en)}- [:structured_output [:map- {:decode/tool-api-response #(update-keys % metabot.u/safe->snake_case_en)}- [:id :int]- [:type [:= :question]]- [:name :string]- [:description {:optional true} [:maybe :string]]- [:result_columns ::columns]- [:verified {:optional true} :boolean]]]]- [:map [:output :string]]])--(deftool "/get-report-details"- "Get information about a given report."- {:args-schema ::get-report-details-arguments- :result-schema ::get-report-details-result- :handler metabot.tools.entity-details/get-report-details})--(mr/def ::get-document-details-arguments- [:and- [:map- [:document_id :int]]- [:map {:encode/tool-api-request- #(set/rename-keys % {:document_id :document-id})}]])--(mr/def ::get-document-details-result- [:or- [:map- {:decode/tool-api-response #(update-keys % metabot.u/safe->snake_case_en)}- [:structured_output [:map- {:decode/tool-api-response #(update-keys % metabot.u/safe->snake_case_en)}- [:id :int]- [:name :string]- [:document :string]]]]- [:map [:output :string]]])--(deftool "/get-document-details"- "Get information about a given document."- {:args-schema ::get-document-details-arguments- :result-schema ::get-document-details-result- :handler metabot.tools.entity-details/get-document-details})--(mr/def ::get-table-details-arguments- [:and- [:map- [:model_id {:optional true} :int]- [:table_id {:optional true} [:or :int :string]]- [:with_fields {:optional true, :default true} :boolean]- [:with_field_values {:optional true, :default true} :boolean]- [:with_related_tables {:optional true, :default true} :boolean]- [:with_metrics {:optional true, :default true} :boolean]- [:with_metric_default_temporal_breakout {:optional true, :default true} :boolean]- [:with_measures {:optional true, :default false} :boolean]- [:with_segments {:optional true, :default false} :boolean]]- [:fn {:error/message "Exactly one of model_id and table_id required"}- #(= (count (select-keys % [:model_id :table_id])) 1)]- [:map {:encode/tool-api-request- #(set/rename-keys % {:model_id :model-id- :table_id :table-id- :with_fields :with-fields?- :with_field_values :with-field-values?- :with_related_tables :with-related-tables?- :with_metrics :with-metrics?- :with_metric_default_temporal_breakout :with-default-temporal-breakout?- :with_measures :with-measures?- :with_segments :with-segments?})}]])--(mr/def ::get-table-details-result- [:or- [:map {:decode/tool-api-response #(update-keys % metabot.u/safe->snake_case_en)}- [:structured_output ::table-result]]- [:map [:output :string]]])--(deftool "/get-table-details"- "Get information about a given table or model."- {:args-schema ::get-table-details-arguments- :result-schema ::get-table-details-result- :handler metabot.tools.entity-details/get-table-details})--(mr/def ::get-tables-arguments- [:and- [:map- [:database_id :int]]- [:map {:encode/tool-api-request- #(set/rename-keys % {:database_id :database-id})}]])--(mr/def ::get-tables-result- [:or- [:map- {:decode/tool-api-response #(update-keys % metabot.u/safe->snake_case_en)}- [:structured_output- [:map- {:decode/tool-api-response #(update-keys % metabot.u/safe->snake_case_en)}- [:database [:map- [:id :int]- [:engine :string]- [:name :string]- [:description :string]]]- [:tables- [:sequential- [:map- [:id :int]- [:name :string]- [:description :string]- [:columns [:sequential- [:map- [:id :int]- [:name :string]- [:description :string]- [:type :string]]]]]]]]]]- [:map [:output :string]]])--(deftool "/get-tables"- "Get information about the tables in a given database."- {:args-schema ::get-tables-arguments- :result-schema ::get-tables-result- :handler table-utils/get-tables})--;;; ----------------------------------------------------- Querying ------------------------------------------------------(mr/def ::filter-records-arguments- [:and- [:map- [:data_source [:and- [:or- [:map- [:query [:map [:database :int]]]- [:query_id {:optional true} :string]]- [:map [:report_id :int]]- [:map [:table_id :string]]]- [:map {:encode/tool-api-request #(update-keys % metabot.u/safe->kebab-case-en)}]]]- [:filters [:sequential ::filter]]]- [:map {:encode/tool-api-request #(update-keys % metabot.u/safe->kebab-case-en)}]])--(deftool "/filter-records"- "Apply filters to records from a data source (query, report, or table)."- {:args-schema ::filter-records-arguments- :result-schema ::filtering-result- :handler metabot.tools.filters/filter-records})--(mr/def ::query-metric-arguments- [:and- [:map- [:metric_id :int]- [:filters {:optional true} [:maybe [:sequential ::filter]]]- [:group_by {:optional true} [:maybe [:sequential ::group-by]]]]- [:map {:encode/tool-api-request #(update-keys % metabot.u/safe->kebab-case-en)}]])--(deftool "/query-metric"- "Construct a query from a metric."- {:args-schema ::query-metric-arguments- :result-schema ::filtering-result- :handler metabot.tools.filters/query-metric})--(mr/def ::query-model-arguments- [:and- [:map- [:model_id :int]- [:fields {:optional true} [:maybe [:sequential ::field]]]- [:filters {:optional true} [:maybe [:sequential ::filter]]]- [:aggregations {:optional true} [:maybe [:sequential ::aggregation]]]- [:group_by {:optional true} [:maybe [:sequential ::group-by]]]- [:order_by {:optional true} [:maybe [:sequential ::order-by]]]- [:limit {:optional true} [:maybe :int]]]- [:map {:encode/tool-api-request #(update-keys % metabot.u/safe->kebab-case-en)}]])--;; TODO tsplude - drop the `/query-model` endpoint and filter logic in favor of this-(deftool "/query-model"- "Construct a query from a model."- {:args-schema ::query-model-arguments- :result-schema ::filtering-result- :handler metabot.tools.filters/query-model})--(mr/def ::query-datasource-arguments- [:and- [:map- [:table_id {:optional true} :int]- [:model_id {:optional true} :int]- [:fields {:optional true} [:maybe [:sequential ::field]]]- [:filters {:optional true} [:maybe [:sequential ::filter]]]- [:aggregations {:optional true} [:maybe [:sequential ::aggregation]]]- [:group_by {:optional true} [:maybe [:sequential ::group-by]]]- [:order_by {:optional true} [:maybe [:sequential ::order-by]]]- [:limit {:optional true} [:maybe :int]]]- [:fn {:error/message "Exactly one of table_id and model_id required"}- #(= (count (select-keys % [:table_id :model_id])) 1)]- [:map {:encode/tool-api-request #(update-keys % metabot.u/safe->kebab-case-en)}]])--;; TODO tsplude - drop the `/query-model` endpoint and filter logic in favor of this-(deftool "/query-datasource"- "Construct a query from a model or table data source."- {:args-schema ::query-datasource-arguments- :result-schema ::filtering-result- :handler metabot.tools.filters/query-datasource})--;;; --------------------------------------------------- SQL Snippets ----------------------------------------------------(mr/def ::get-snippets-result- "Schema for SQL snippet list results"- [:map- {:decode/tool-api-response #(update-keys % metabot.u/safe->snake_case_en)}- [:structured_output [:sequential ::basic-snippet]]])--(deftool "/get-snippets"- "Get a list of all known SQL snippets."- {:result-schema ::get-snippets-result- :handler metabot.tools.snippets/get-snippets})--(mr/def ::get-snippet-details-arguments- [:and- [:map- [:snippet_id :int]]- [:map {:encode/tool-api-request- #(set/rename-keys % {:snippet_id :snippet-id})}]])--(mr/def ::get-snippet-details-result- "Schema for SQL snippet detail results"- [:map {:decode/tool-api-response #(update-keys % metabot.u/safe->snake_case_en)}- [:structured_output ::full-snippet]])--(deftool "/get-snippet-details"- "Get the content of a single SQL snippet."- {:args-schema ::get-snippet-details-arguments- :result-schema ::get-snippet-details-result- :handler metabot.tools.snippets/get-snippet-details})diff --git a/src/metabase/metabot/tools/ask_clarification.clj b/src/metabase/metabot/tools/ask_clarification.cljdeleted file mode 100644index 3896d0a5b12..00000000000--- a/src/metabase/metabot/tools/ask_clarification.clj+++ /dev/null@@ -1,30 +0,0 @@-(ns metabase.metabot.tools.ask-clarification- "Tool for asking users clarification questions about SQL query requests.- This is an 'external' tool that signals the agent should stop and wait for user input."- (:require- [metabase.util.log :as log]))--(set! *warn-on-reflection* true)--(defn ask-for-sql-clarification- "Ask the user for clarification about their SQL query request.-- This tool is used when the agent needs more information from the user- to properly complete their SQL request. It returns a final response- that stops the agent loop and waits for user input.-- Parameters:- - question: The clarification question to ask the user- - options: Optional list of suggested answers/choices-- Returns map with:- - :structured-output - The question and options for the LLM- - :final-response? - Signals that the agent should stop and wait for user input- - :instructions - Instructions for the LLM"- [{:keys [question options]}]- (log/info "Asking for SQL clarification" {:question question- :option-count (count options)})- {:structured-output {:question question- :options (or options [])}- :final-response? true- :instructions "The clarification question has been presented to the user. Stop and wait for their response before continuing."})diff --git a/src/metabase/metabot/tools/create_autogenerated_dashboard.clj b/src/metabase/metabot/tools/autogen_dashboard.cljsimilarity index 70%rename from src/metabase/metabot/tools/create_autogenerated_dashboard.cljrename to src/metabase/metabot/tools/autogen_dashboard.cljindex 899bf1267b5..932c4274fe7 100644--- a/src/metabase/metabot/tools/create_autogenerated_dashboard.clj+++ b/src/metabase/metabot/tools/autogen_dashboard.clj@@ -1,10 +1,10 @@-(ns metabase.metabot.tools.create-autogenerated-dashboard- "Tool for creating auto-generated dashboards using Metabase's X-ray feature.- X-ray builds complete dashboards with multiple visualizations that showcase- different aspects of data - distributions, breakdowns, trends, and relationships."+(ns metabase.metabot.tools.autogen-dashboard+ "Autogenerated dashboard tool wrappers."(:require[clojure.string :as str]+ [metabase.metabot.tools.shared :as shared][metabase.util.log :as log]+ [metabase.util.malli :as mu][toucan2.core :as t2]))(set! *warn-on-reflection* true)@@ -103,7 +103,7 @@(log/info "Creating autogenerated dashboard" {:source source})(let [memory (when memory-atom @memory-atom)- {:keys [path]} (resolve-source source memory)+ {:keys [path]} (resolve-source source memory)response-message (str (random-response-message) "\n\nLet me know if you need anything else.")];; Note: The actual automagic analysis happens on navigation to the /auto/dashboard/... URL@@ -116,3 +116,45 @@:reactions [{:type :metabot.reaction/redirect :url path}]:final-response? true:instructions "The dashboard has been created and the user has been navigated to view it. Do not describe the dashboard contents."}))++(def ^:private autogen-dashboard-schema+ [:map {:closed true}+ [:source [:map+ [:table_id {:optional true} [:maybe :int]]+ [:model_id {:optional true} [:maybe :int]]+ [:metric_id {:optional true} [:maybe :int]]+ [:query_id {:optional true} [:maybe :string]]+ [:report_id {:optional true} [:maybe :int]]]]])++(mu/defn ^{:tool-name "create_autogenerated_dashboard"+ :capabilities #{:automagic-dashboards}}+ create-autogenerated-dashboard-tool+ "Create an automatically generated dashboard using Metabase's X-ray feature.++ X-ray builds complete dashboards with multiple visualizations that showcase+ different aspects of your data - distributions, breakdowns by categories,+ trends over time, and relationships between fields.++ Specify one source type:+ - table_id: Create dashboard for a table+ - model_id: Create dashboard for a model+ - metric_id: Create dashboard for a metric+ - query_id: Create dashboard for query results from this conversation+ - report_id: Create dashboard for an existing report/question"+ [{:keys [source]} :- autogen-dashboard-schema]+ (try+ (let [result (create-autogenerated-dashboard+ {:source source+ :memory-atom shared/*memory-atom*})+ structured (:structured-output result)+ reactions (:reactions result)]+ (cond-> {:output (:message structured)+ :structured-output structured+ :final-response? (:final-response? result)+ :instructions (:instructions result)}+ (seq reactions) (assoc :reactions reactions)))+ (catch Exception e+ (log/error e "Error creating autogenerated dashboard")+ (if (:agent-error? (ex-data e))+ {:output (ex-message e)}+ {:output (str "Failed to create autogenerated dashboard: " (or (ex-message e) "Unknown error"))}))))diff --git a/src/metabase/metabot/agent/tools/charts.clj b/src/metabase/metabot/tools/charts.cljsimilarity index 89%rename from src/metabase/metabot/agent/tools/charts.cljrename to src/metabase/metabot/tools/charts.cljindex 1c062bc2eee..982634528ce 100644--- a/src/metabase/metabot/agent/tools/charts.clj+++ b/src/metabase/metabot/tools/charts.clj@@ -1,12 +1,12 @@-(ns metabase.metabot.agent.tools.charts+(ns metabase.metabot.tools.charts"Chart tool wrappers."(:require[medley.core :as m]- [metabase.metabot.agent.tools.shared :as shared]- [metabase.metabot.tools.create-chart :as create-chart-tools]- [metabase.metabot.tools.edit-chart :as edit-chart-tools]- [metabase.metabot.tools.instructions :as instructions]- [metabase.metabot.tools.llm-representations :as llm-rep]+ [metabase.metabot.tools.charts.create :as create-chart-tools]+ [metabase.metabot.tools.charts.edit :as edit-chart-tools]+ [metabase.metabot.tools.shared :as shared]+ [metabase.metabot.tools.shared.instructions :as instructions]+ [metabase.metabot.tools.shared.llm-representations :as llm-rep][metabase.util.log :as log][metabase.util.malli :as mu]))diff --git a/src/metabase/metabot/tools/create_chart.clj b/src/metabase/metabot/tools/charts/create.cljsimilarity index 98%rename from src/metabase/metabot/tools/create_chart.cljrename to src/metabase/metabot/tools/charts/create.cljindex ea76faa6abe..63cf154e005 100644--- a/src/metabase/metabot/tools/create_chart.clj+++ b/src/metabase/metabot/tools/charts/create.clj@@ -1,4 +1,4 @@-(ns metabase.metabot.tools.create-chart+(ns metabase.metabot.tools.charts.create"Tool for creating charts from queries."(:require[buddy.core.codecs :as codecs]diff --git a/src/metabase/metabot/tools/edit_chart.clj b/src/metabase/metabot/tools/charts/edit.cljsimilarity index 98%rename from src/metabase/metabot/tools/edit_chart.cljrename to src/metabase/metabot/tools/charts/edit.cljindex cacec14d121..03b84b271c0 100644--- a/src/metabase/metabot/tools/edit_chart.clj+++ b/src/metabase/metabot/tools/charts/edit.clj@@ -1,4 +1,4 @@-(ns metabase.metabot.tools.edit-chart+(ns metabase.metabot.tools.charts.edit"Tool for editing chart visualization settings."(:require[metabase.util.log :as log]))diff --git a/src/metabase/metabot/tools/clarification.clj b/src/metabase/metabot/tools/clarification.cljnew file mode 100644index 00000000000..deec472b5bb--- /dev/null+++ b/src/metabase/metabot/tools/clarification.clj@@ -0,0 +1,53 @@+(ns metabase.metabot.tools.clarification+ "Clarification tool wrappers."+ (:require+ [clojure.string :as str]+ [metabase.util.log :as log]+ [metabase.util.malli :as mu]))++(set! *warn-on-reflection* true)++(defn ask-for-sql-clarification+ "Ask the user for clarification about their SQL query request.++ This tool is used when the agent needs more information from the user+ to properly complete their SQL request. It returns a final response+ that stops the agent loop and waits for user input.++ Parameters:+ - question: The clarification question to ask the user+ - options: Optional list of suggested answers/choices++ Returns map with:+ - :structured-output - The question and options for the LLM+ - :final-response? - Signals that the agent should stop and wait for user input+ - :instructions - Instructions for the LLM"+ [{:keys [question options]}]+ (log/info "Asking for SQL clarification" {:question question+ :option-count (count options)})+ {:structured-output {:question question+ :options (or options [])}+ :final-response? true+ :instructions "The clarification question has been presented to the user. Stop and wait for their response before continuing."})++(defn- format-clarification-output+ [{:keys [question options]}]+ (str question+ (when (seq options)+ (str "\n\nOptions:\n" (str/join "\n" (map #(str "- " %) options))))))++(mu/defn ^{:tool-name "ask_for_sql_clarification"}+ ask-for-sql-clarification-tool+ "Ask the user for clarification about their SQL query request.++ Use this tool when you need more information from the user to properly+ complete their SQL request. The agent will stop and wait for the user's response."+ [{:keys [question options]} :- [:map {:closed true}+ [:question :string]+ [:options {:optional true} [:maybe [:sequential :string]]]]]+ (try+ (let [result (ask-for-sql-clarification {:question question+ :options options})]+ (assoc result :output (format-clarification-output (:structured-output result))))+ (catch Exception e+ {:output (str "Failed to ask clarification: " (or (ex-message e) "Unknown error"))})))diff --git a/src/metabase/metabot/agent/tools/construct.clj b/src/metabase/metabot/tools/construct.cljsimilarity index 98%rename from src/metabase/metabot/agent/tools/construct.cljrename to src/metabase/metabot/tools/construct.cljindex 844fe68d7aa..666c111bddf 100644--- a/src/metabase/metabot/agent/tools/construct.clj+++ b/src/metabase/metabot/tools/construct.clj@@ -1,4 +1,4 @@-(ns metabase.metabot.agent.tools.construct+(ns metabase.metabot.tools.construct"Notebook query construction tool wrappers."(:require[clojure.walk :as walk]@@ -7,10 +7,10 @@[metabase.lib.core :as lib][metabase.metabot.agent.streaming :as streaming][metabase.metabot.tmpl :as te]- [metabase.metabot.tools.create-chart :as create-chart-tools]+ [metabase.metabot.tools.charts.create :as create-chart-tools][metabase.metabot.tools.filters :as filter-tools]- [metabase.metabot.tools.instructions :as instructions]- [metabase.metabot.tools.llm-representations :as llm-rep]+ [metabase.metabot.tools.shared.instructions :as instructions]+ [metabase.metabot.tools.shared.llm-representations :as llm-rep][metabase.metabot.util :as metabot-u][metabase.util.json :as json][metabase.util.log :as log]diff --git a/src/metabase/metabot/tools/create_alert.clj b/src/metabase/metabot/tools/create_alert.cljindex 29ab668fe72..e05af92a550 100644--- a/src/metabase/metabot/tools/create_alert.clj+++ b/src/metabase/metabot/tools/create_alert.clj@@ -1,13 +1,20 @@(ns metabase.metabot.tools.create-alert+ "Agent tool wrapper for creating alerts on saved questions.+ Gets slack_channel_id from agent context and calls the create-alert tool endpoint directly."(:require[clojure.set :as set][metabase.api.common :as api][metabase.channel.settings :as channel.settings]+ [metabase.metabot.tools.shared :as shared][metabase.metabot.tools.util :as metabot.tools.u][metabase.notification.api :as notification.api][metabase.util.cron :as u.cron]+ [metabase.util.log :as log]+ [metabase.util.malli :as mu][toucan2.core :as t2]))+(set! *warn-on-reflection* true)+(defn- schedule->cron"Convert the tool schedule format to a Quartz cron string.The schedule comes in as e.g. {:frequency :daily :hour 9} and needs to be@@ -72,3 +79,82 @@(catch Exception e(-> (metabot.tools.u/handle-agent-error e)(set/rename-keys {:output :error}))))))++(def schedule-schema+ "Schedule schema shared with create-dashboard-subscription tool."+ [:or+ [:map {:closed true}+ [:frequency [:= "hourly"]]]+ [:map {:closed true}+ [:frequency [:= "daily"]]+ [:hour [:int {:min 0 :max 23}]]]+ [:map {:closed true}+ [:frequency [:= "weekly"]]+ [:day_of_week [:enum "sunday" "monday" "tuesday" "wednesday" "thursday" "friday" "saturday"]]+ [:hour [:int {:min 0 :max 23}]]]+ [:map {:closed true}+ [:frequency [:= "monthly"]]+ [:day_of_month [:enum "first-calendar-day"+ "first-sunday" "first-monday" "first-tuesday" "first-wednesday"+ "first-thursday" "first-friday" "first-saturday"+ "middle-of-month"+ "last-calendar-day"+ "last-sunday" "last-monday" "last-tuesday" "last-wednesday"+ "last-thursday" "last-friday" "last-saturday"]]+ [:hour [:int {:min 0 :max 23}]]]])++(def ^:private create-alert-system-instructions+ "## Alerts++You can create alerts that notify the user's current Slack channel based on a saved question's results on a+recurring schedule.++### Required information++Before calling the tool, ensure you have ALL of the following:+1. **Card ID** — the ID of a saved question, obtained from a prior search result or conversation context+2. **Send condition** — determines when the alert fires:+ - `has_result` — sends when the question returns any rows+ - `goal_above` — sends when the result exceeds the goal line set on the question+ - `goal_below` — sends when the result drops below the goal line+3. **Schedule** — frequency (hourly, daily, weekly, monthly) with the appropriate time fields+4. **Send once** (optional, defaults to false) — if true, the alert is automatically deleted after it fires once++### Important notes++* Alerts are for **saved questions** (cards), not dashboards. For dashboard delivery, use the dashboard subscription tool.+* `goal_above` and `goal_below` only work on questions that have a goal line configured.+* If the user doesn't specify a send condition, default to `has_result`.++CRITICAL: When a user asks to be alerted or notified about a saved question's results, you MUST call the create_alert tool.+NEVER tell the user you have created an alert without actually calling the create_alert tool. If you cannot call the tool+(e.g. missing required information), explain what is needed instead of pretending the alert was created.")++(def ^:private alert-schema+ [:map {:closed true}+ [:card_id :int]+ [:send_condition [:enum "has_result" "goal_above" "goal_below"]]+ [:schedule schedule-schema]+ [:send_once {:optional true :default false} :boolean]])++(mu/defn ^{:tool-name "create_alert"+ :system-instructions create-alert-system-instructions}+ create-alert-tool+ "Create an alert based on a saved question's results on a recurring schedule."+ [{:keys [card_id send_condition schedule send_once]} :- alert-schema]+ (let [slack-channel-id (:slack_channel_id (shared/current-context))]+ (when-not slack-channel-id+ (throw (ex-info "This tool can only be used from a Slack channel"+ {:agent-error? true})))+ (try+ (let [result (create-alert {:card-id card_id+ :send-condition (keyword send_condition)+ :schedule schedule+ :send-once (boolean send_once)+ :slack-channel slack-channel-id})]+ (if (:error result)+ {:output (:error result)}+ {:output (or (:output result) "Alert created successfully.")}))+ (catch Exception e+ (log/error e "Failed to create alert")+ {:output (str "Failed to create alert: " (or (ex-message e) "Unknown error"))}))))diff --git a/src/metabase/metabot/tools/create_dashboard_subscription.clj b/src/metabase/metabot/tools/create_dashboard_subscription.cljindex f7e92cd2191..3633c3a9ce5 100644--- a/src/metabase/metabot/tools/create_dashboard_subscription.clj+++ b/src/metabase/metabot/tools/create_dashboard_subscription.clj@@ -3,8 +3,12 @@[clojure.set :as set][metabase.api.common :as api][metabase.channel.settings :as channel.settings]+ [metabase.metabot.tools.create-alert :as tools.create-alert]+ [metabase.metabot.tools.shared :as shared][metabase.metabot.tools.util :as metabot.tools.u][metabase.pulse.api :as pulse.api]+ [metabase.util.log :as log]+ [metabase.util.malli :as mu][toucan2.core :as t2]))(defn- make-slack-channel@@ -69,3 +73,47 @@(catch Exception e(-> (metabot.tools.u/handle-agent-error e)(set/rename-keys {:output :error}))))))++(def ^:private create-dashboard-subscription-system-instructions+ "## Dashboard Subscriptions++You can create dashboard subscriptions that deliver dashboard contents to the user's current slack channel on a+recurring schedule.++### CRITICAL: You MUST call the create_dashboard_subscription tool++When a user asks to subscribe to a dashboard, set up scheduled delivery, or receive regular updates for a dashboard,+you MUST call the create_dashboard_subscription tool. Never tell the user you have created a subscription without+actually calling the tool. If you cannot call the tool (e.g. missing required information), explain what is needed+instead of pretending the subscription was created.++### Required information++Before calling the tool, ensure you have ALL of the following:+1. **Dashboard ID** — obtained from a prior search result or conversation context+2. **Schedule** — frequency (hourly, daily, weekly, monthly) with the appropriate time fields++If any required information is missing, ask the user for it rather than assuming or fabricating values.")++(mu/defn ^{:tool-name "create_dashboard_subscription"+ :system-instructions create-dashboard-subscription-system-instructions}+ slackbot-create-dashboard-subscription-tool+ "Create a recurring subscription that delivers a dashboard's contents to a Slack channel."+ [{:keys [dashboard_id schedule]} :- [:map {:closed true}+ [:dashboard_id :int]+ [:schedule tools.create-alert/schedule-schema]]]+ (let [slack-channel-id (:slack_channel_id (shared/current-context))]+ (when-not slack-channel-id+ (throw (ex-info "This tool can only be used from a Slack channel"+ {:agent-error? true})))+ (try+ (let [result (create-dashboard-subscription+ {:dashboard-id dashboard_id+ :schedule schedule+ :slack-channel slack-channel-id})]+ (if (:error result)+ {:output (:error result)}+ {:output (or (:output result) "Dashboard subscription created successfully.")}))+ (catch Exception e+ (log/error e "Failed to create dashboard subscription")+ {:output (str "Failed to create dashboard subscription: " (or (ex-message e) "Unknown error"))}))))diff --git a/src/metabase/metabot/agent/tools/document.clj b/src/metabase/metabot/tools/document.cljsimilarity index 67%rename from src/metabase/metabot/agent/tools/document.cljrename to src/metabase/metabot/tools/document.cljindex c0b2f21e238..62efa06f42f 100644--- a/src/metabase/metabot/agent/tools/document.clj+++ b/src/metabase/metabot/tools/document.clj@@ -1,10 +1,12 @@-(ns metabase.metabot.agent.tools.document+(ns metabase.metabot.tools.document"Document-generation specific tool wrappers."(:require- [metabase.metabot.agent.tools.construct :as construct-tools]- [metabase.metabot.agent.tools.shared :as shared][metabase.metabot.table-utils :as table-utils]- [metabase.metabot.tools.create-sql-query :as create-sql-query-tools]+ [metabase.metabot.tools.construct :as construct-tools]+ [metabase.metabot.tools.shared :as shared]+ [metabase.metabot.tools.shared.instructions :as instructions]+ [metabase.metabot.tools.sql.create :as create-sql-query-tools]+ [metabase.query-processor.core :as qp][metabase.util.log :as log][metabase.util.malli :as mu][metabase.warehouses.core :as warehouses]))@@ -45,6 +47,41 @@(remove nil?))references))+(defn- sql-chart-error-output+ [instruction-text]+ (str "<result>\n"+ "SQL chart draft generation failed.\n"+ "</result>\n"+ "<instructions>\n"+ instruction-text+ "</instructions>"))++(defn- sql-validation-error-result+ [dialect error-message]+ (let [instruction-text (instructions/sql-validation-error-instructions dialect error-message)]+ {:output (sql-chart-error-output instruction-text)+ :instructions instruction-text}))++(defn- query-processing-error-result+ [error-message]+ (let [instruction-text (str "The SQL query could not be processed by Metabase.\n"+ "\n"+ "Error details:\n"+ error-message "\n"+ "\n"+ "Please fix the query and call `document_construct_sql_chart` again with corrected SQL.\n")]+ {:output (sql-chart-error-output instruction-text)+ :instructions instruction-text}))++(defn- check-query+ "If the query is valid, return nil. If not, return the error message."+ [query]+ (try+ (qp/process-query query)+ nil+ (catch Exception e+ (ex-message e))))+(mu/defn ^{:tool-name "document_schema_collect"}document-schema-collect-tool"Collects the schema of a database in order to construct a SQL query.@@ -103,25 +140,36 @@"Construct SQL-backed chart draft payload for document insertion."[{:keys [database_id name description analysis approach sql viz_settings]} :- sql-chart-schema](try- (let [result (create-sql-query-tools/create-sql-query {:database-id database_id- :sql sql})- chart-type (get viz_settings :chart_type)- query-id (:query-id result)- query (:query result)- structured {:tool "document_construct_sql_chart"- :name name- :description description- :analysis analysis- :approach approach- :dataset_query query- :display chart-type- :chart_type chart-type- :query_id query-id- :query query- :result-type :chart-draft}]- {:output "Draft chart payload generated from SQL query."- :structured-output structured- :final-response? true})+ (let [{:keys [validation-result action-result]}+ (create-sql-query-tools/create-sql-query {:database-id database_id+ :sql sql})+ {:keys [valid? dialect error-message]} validation-result+ {:keys [query-id query]} action-result+ chart-type (get viz_settings :chart_type)]+ (cond+ (not valid?)+ (sql-validation-error-result dialect error-message)++ (not (map? query))+ {:output "Failed to construct SQL chart draft."}++ :else+ (if-let [query-error (check-query query)]+ (query-processing-error-result query-error)+ (let [structured {:tool "document_construct_sql_chart"+ :name name+ :description description+ :analysis analysis+ :approach approach+ :dataset_query query+ :display chart-type+ :chart_type chart-type+ :query_id query-id+ :query query+ :result-type :chart-draft}]+ {:output "Draft chart payload generated from SQL query."+ :structured-output structured+ :final-response? true}))))(catch Exception e(log/error e "Error constructing SQL chart draft")(if (:agent-error? (ex-data e))diff --git a/src/metabase/metabot/tools/filters.clj b/src/metabase/metabot/tools/filters.cljindex 0f287a62bde..9c76d56c34b 100644--- a/src/metabase/metabot/tools/filters.clj+++ b/src/metabase/metabot/tools/filters.clj@@ -8,7 +8,7 @@[metabase.lib.types.isa :as lib.types.isa][metabase.lib.util :as lib.util][metabase.metabot.agent.streaming :as streaming]- [metabase.metabot.tools.instructions :as instructions]+ [metabase.metabot.tools.shared.instructions :as instructions][metabase.metabot.tools.util :as metabot.tools.u][metabase.util :as u][metabase.util.i18n :refer [tru]]diff --git a/src/metabase/metabot/tools/get_metadata.clj b/src/metabase/metabot/tools/metadata.cljsimilarity index 54%rename from src/metabase/metabot/tools/get_metadata.cljrename to src/metabase/metabot/tools/metadata.cljindex ce6ea2b8dde..c6e277136dc 100644--- a/src/metabase/metabot/tools/get_metadata.clj+++ b/src/metabase/metabot/tools/metadata.clj@@ -1,9 +1,16 @@-(ns metabase.metabot.tools.get-metadata- "Tool for retrieving metadata for tables, models, and metrics."+(ns metabase.metabot.tools.metadata+ "Metadata tool wrappers."(:require+ [clojure.string :as str]+ [medley.core :as m][metabase.metabot.tools.entity-details :as entity-details-tools]+ [metabase.metabot.tools.field-stats :as field-stats-tools]+ [metabase.metabot.tools.shared :as shared]+ [metabase.metabot.tools.shared.instructions :as instructions]+ [metabase.metabot.tools.shared.llm-representations :as llm-rep][metabase.util.i18n :refer [tru]]- [metabase.util.log :as log]))+ [metabase.util.log :as log]+ [metabase.util.malli :as mu]))(set! *warn-on-reflection* true)@@ -92,3 +99,78 @@(if (:agent-error? (ex-data e)){:output (ex-message e)}{:output (str "Failed to fetch metadata: " (or (ex-message e) "Unknown error"))}))))++(defn- format-with-instructions+ [data instruction-text]+ (str "<result>\n" data "\n</result>\n"+ "<instructions>\n" instruction-text "\n</instructions>"))++(defn- format-answer-sources-output+ [{:keys [metrics models]}]+ (let [content (str (when (seq metrics)+ (str "<metrics>\n"+ (str/join "\n" (map llm-rep/metric->xml metrics))+ "\n</metrics>\n"))+ (when (seq models)+ (str "<metabase-models>\n"+ (str/join "\n" (map llm-rep/model->xml models))+ "\n</metabase-models>")))]+ (format-with-instructions content instructions/answer-sources-instructions)))++(defn- format-metadata-output+ [structured]+ (llm-rep/get-metadata-result->xml structured))++(defn- format-field-metadata-output+ ;; NOTE: keep in sync with read_resource.clj/format-content :field-metadata branch+ [{:keys [field_id value_metadata]}]+ (format-with-instructions+ (llm-rep/field-metadata->xml {:field_id field_id :value_metadata value_metadata})+ instructions/field-metadata-instructions))++(defn- add-output+ "Add :output to a tool result that has :structured-output, using the given format-fn."+ [result format-fn]+ (m/assoc-some result :output (some-> result :structured-output format-fn)))++(mu/defn ^{:tool-name "list_available_data_sources"}+ list-available-data-sources-tool+ "List all data sources (metrics and models) available to the metabot instance."+ [_args :- [:maybe [:map {:closed true}]]]+ (add-output+ (entity-details-tools/answer-sources {:metabot-id shared/*metabot-id*+ :with-field-values? false})+ format-answer-sources-output))++(def ^:private list-available-fields-schema+ [:map {:closed true}+ [:table_ids [:sequential :int]]+ [:model_ids [:sequential :int]]+ [:metric_ids [:sequential :int]]])++(mu/defn ^{:tool-name "list_available_fields"}+ list-available-fields-tool+ "Retrieve metadata for tables, models, and metrics."+ [{:keys [table_ids model_ids metric_ids]} :- list-available-fields-schema]+ (add-output+ (get-metadata {:table-ids table_ids+ :model-ids model_ids+ :metric-ids metric_ids})+ format-metadata-output))++(def ^:private get-field-values-schema+ [:map {:closed true}+ [:data_source [:enum "table" "model" "metric"]]+ [:source_id :int]+ [:field_id :string]])++(mu/defn ^{:tool-name "get_field_values"}+ get-field-values-tool+ "Return metadata for a given field of a given data source."+ [{:keys [data_source source_id field_id]} :- get-field-values-schema]+ (add-output+ (field-stats-tools/field-values {:entity-type data_source+ :entity-id source_id+ :field-id field_id+ :limit nil})+ format-field-metadata-output))diff --git a/src/metabase/metabot/tools/navigate.clj b/src/metabase/metabot/tools/navigation.cljsimilarity index 72%rename from src/metabase/metabot/tools/navigate.cljrename to src/metabase/metabot/tools/navigation.cljindex c2aef365c90..2a2fe992479 100644--- a/src/metabase/metabot/tools/navigate.clj+++ b/src/metabase/metabot/tools/navigation.clj@@ -1,10 +1,12 @@-(ns metabase.metabot.tools.navigate- "Tool for navigating users to specific pages in Metabase UI."+(ns metabase.metabot.tools.navigation+ "Navigation tool wrappers."(:require[buddy.core.codecs :as codecs][metabase.metabot.agent.links :as links]+ [metabase.metabot.tools.shared :as shared][metabase.util.json :as json]- [metabase.util.log :as log]))+ [metabase.util.log :as log]+ [metabase.util.malli :as mu]))(set! *warn-on-reflection* true)@@ -126,3 +128,43 @@{:structured-output {:message message:path path}:reactions [{:type :metabot.reaction/redirect :url path}]}))++(def ^:private navigation-schema+ [:map {:closed true}+ [:destination [:or+ [:map {:closed true}+ [:page [:enum "notebook_editor" "metrics_browser" "model_browser" "database_browser"]]]+ [:map {:closed true}+ [:page [:enum "sql_editor"]]+ [:database_id :int]]+ [:map {:closed true}+ [:entity_type [:enum "table" "model" "question" "metric" "dashboard"]]+ [:entity_id :int]]+ [:map {:closed true}+ [:query_id :string]]+ [:map {:closed true}+ [:chart_id :string]]]]])++(mu/defn ^{:tool-name "navigate_user"+ :capabilities #{:frontend-navigate-user-v1}}+ navigate-user-tool+ "Navigate the user to a specific page or entity in Metabase.++ Use this tool to direct users to:+ - Pages: notebook_editor, metrics_browser, model_browser, database_browser, sql_editor+ - Entities: table, model, question, metric, dashboard+ - Query results or charts from the current conversation"+ [{:keys [destination]} :- navigation-schema]+ (try+ (let [result (navigate {:destination destination+ :memory-atom shared/*memory-atom*})+ structured (:structured-output result)+ reactions (:reactions result)]+ (cond-> {:output (:message structured)+ :structured-output structured}+ (seq reactions) (assoc :reactions reactions)))+ (catch Exception e+ (log/error e "Error navigating")+ (if (:agent-error? (ex-data e))+ {:output (ex-message e)}+ {:output (str "Failed to navigate: " (or (ex-message e) "Unknown error"))}))))diff --git a/src/metabase/metabot/tools/read_resource.clj b/src/metabase/metabot/tools/resources.cljsimilarity index 89%rename from src/metabase/metabot/tools/read_resource.cljrename to src/metabase/metabot/tools/resources.cljindex ded2b60bbb4..39fe38afb97 100644--- a/src/metabase/metabot/tools/read_resource.clj+++ b/src/metabase/metabot/tools/resources.clj@@ -1,4 +1,4 @@-(ns metabase.metabot.tools.read-resource+(ns metabase.metabot.tools.resources"Tool for reading Metabase resources via URI patterns.Implements 'Context Engineering with Links' pattern where URIs serve as lightweight,@@ -21,10 +21,11 @@[clojure.string :as str][metabase.metabot.tools.entity-details :as entity-details][metabase.metabot.tools.field-stats :as field-stats]- [metabase.metabot.tools.instructions :as instructions]- [metabase.metabot.tools.llm-representations :as llm-rep]- [metabase.metabot.tools.transforms :as transforms]- [metabase.util.log :as log]))+ [metabase.metabot.tools.shared.instructions :as instructions]+ [metabase.metabot.tools.shared.llm-representations :as llm-rep]+ [metabase.transforms.core :as transforms]+ [metabase.util.log :as log]+ [metabase.util.malli :as mu]))(set! *warn-on-reflection* true)@@ -156,10 +157,8 @@(when sub-resource(throw (ex-info (str "Transforms do not support sub-resources. Got: " sub-resource){:resource-id resource-id :sub-resource sub-resource})))- (let [result (transforms/get-transform-details {:transform-id (parse-long resource-id)})]- (if-let [transform (:structured_output result)]- {:structured-output (assoc transform :result-type :entity :type :transform)}- result)))+ {:structured-output (-> (transforms/get-transform (parse-long resource-id))+ (assoc :result-type :entity :type :transform))})(defn- fetch-dashboard-resource"Fetch dashboard resource."@@ -269,3 +268,21 @@{:resources resources:output formatted}))++(mu/defn ^{:tool-name "read_resource"}+ read-resource-tool+ "Read detailed information about Metabase resources via URI patterns.++ Supports fetching multiple resources in parallel using metabase:// URIs:+ - metabase://table/{id}/fields - Get table structure with fields+ - metabase://model/{id}/fields/{field_id} - Get specific field details+ - metabase://metric/{id}/dimensions - Get metric dimensions+ - metabase://transform/{id} - Get transform details+ - metabase://dashboard/{id} - Get dashboard details"+ [{:keys [uris]} :- [:map {:closed true}+ [:uris [:sequential [:string {:description "Metabase resource URIs to fetch"}]]]]]+ (try+ (read-resource {:uris uris})+ (catch Exception e+ (log/error e "Error in read_resource tool")+ {:output (str "Failed to read resources: " (or (ex-message e) "Unknown error"))})))diff --git a/src/metabase/metabot/tools/search.clj b/src/metabase/metabot/tools/search.cljindex 8d97457a7cc..30bcd48ee18 100644--- a/src/metabase/metabot/tools/search.clj+++ b/src/metabase/metabot/tools/search.clj@@ -1,18 +1,26 @@(ns metabase.metabot.tools.search+ "Search tool wrappers for Metabot v3."(:require[clojure.set :as set]+ [clojure.string :as str][medley.core :as m][metabase.api.common :as api][metabase.metabot.config :as metabot.config]- [metabase.metabot.reactions]+ [metabase.metabot.tmpl :as te]+ [metabase.metabot.tools.shared :as shared]+ [metabase.metabot.tools.shared.instructions :as instructions]+ [metabase.metabot.tools.shared.llm-representations :as llm-rep][metabase.permissions.core :as perms][metabase.search.core :as search][metabase.search.engine :as search.engine][metabase.transforms.core :as transforms][metabase.util :as u][metabase.util.log :as log]+ [metabase.util.malli :as mu][toucan2.core :as t2]))+(set! *warn-on-reflection* true)+(def ^:private metabot-search-models#{"table" "dataset" "card" "dashboard" "metric" "database" "transform"})@@ -244,15 +252,98 @@enrich-with-database-enginesremove-unreadable-transforms)))-(defn search-tool- "Handler for the /search and /search_v2 tool endpoints.- Wraps [[search]] with error handling and response formatting."- [args]- (try- (let [results (search args)]- {:structured_output {:result-type :search- :data results- :total_count (count results)}})- (catch Exception e- (log/error e "Error in search")- {:output (str "Search failed: " (or (ex-message e) "Unknown error"))})))+(defn- format-search-output+ "Format search results as an LLM-ready string."+ [results]+ (let [results-xml (llm-rep/search-results->xml results)]+ (te/lines+ "<result>"+ results-xml+ ""+ (str "Total results: " (count results))+ "</result>"+ "<instructions>"+ instructions/search-result-instructions "</instructions>")))++(defn- invalid-entity-types+ [entity-types allowed]+ (when (seq entity-types)+ (seq (remove allowed entity-types))))++(defn- do-search+ [label allowed-types search-opts {:keys [semantic_queries keyword_queries entity_types] :as _args}]+ (if-let [invalid (invalid-entity-types entity_types allowed-types)]+ {:output (str "Invalid entity_types for " label ": " (pr-str (vec invalid))+ ". Allowed types: " (str/join ", " (sort allowed-types)) ".")}+ (try+ (let [results (search (merge {:semantic-queries semantic_queries+ :term-queries keyword_queries+ :entity-types entity_types+ :metabot-id shared/*metabot-id*+ :limit 10}+ search-opts))]+ {:output (format-search-output results)+ :structured-output {:result-type :search+ :data results+ :total_count (count results)}})+ (catch Exception e+ (log/error e (str "Error in " label))+ {:output (str "Search failed: " (or (ex-message e) "Unknown error"))}))))++(def ^:private search-schema+ [:map {:closed true}+ [:semantic_queries {:feature :semantic-search} [:sequential :string]]+ [:keyword_queries [:sequential :string]]+ [:entity_types {:optional true}+ [:maybe [:sequential [:enum "table" "model" "metric" "dashboard" "question"]]]]])++(mu/defn ^{:tool-name "search"}+ search-tool+ "Search for tables, models, metrics, dashboards, and saved questions."+ [args :- search-schema]+ (do-search "search" #{"table" "model" "metric" "dashboard" "question"} {} args))++(def ^:private sql-search-schema+ [:map {:closed true}+ [:semantic_queries {:feature :semantic-search} [:sequential :string]]+ [:keyword_queries [:sequential :string]]+ [:database_id :int]+ [:entity_types {:optional true}+ [:maybe [:sequential [:enum "table" "model"]]]]])++(mu/defn ^{:tool-name "search"+ :prompt "sql_search.md"}+ sql-search-tool+ "Search for SQL-queryable data sources (tables and models) within a database."+ [{:keys [database_id] :as args} :- sql-search-schema]+ (do-search "SQL search" #{"table" "model"} {:database-id database_id} args))++(def ^:private nlq-search-schema+ [:map {:closed true}+ [:semantic_queries {:feature :semantic-search} [:sequential :string]]+ [:keyword_queries [:sequential :string]]+ [:entity_types {:optional true}+ [:maybe [:sequential [:enum "model" "metric" "table"]]]]])++(mu/defn ^{:tool-name "search"+ :prompt "nql_search.md"}+ nlq-search-tool+ "Search for NLQ-queryable data sources (models, metrics, tables)."+ [args :- nlq-search-schema]+ (do-search "NLQ search" #{"model" "metric" "table"} {:profile-id "nlq"} args))++(def ^:private transform-search-schema+ [:map {:closed true}+ [:semantic_queries {:feature :semantic-search} [:sequential :string]]+ [:keyword_queries [:sequential :string]]+ [:search_native_query {:optional true} [:maybe :boolean]]+ [:entity_types {:optional true}+ [:maybe [:sequential [:enum "table" "model" "transform"]]]]])++(mu/defn ^{:tool-name "search"+ :prompt "transform_search"}+ transform-search-tool+ "Search for transforms, tables, and models."+ [{:keys [search_native_query] :as args} :- transform-search-schema]+ (do-search "transform search" #{"table" "model" "transform"}+ {:search-native-query search_native_query} args))diff --git a/src/metabase/metabot/agent/tools/shared.clj b/src/metabase/metabot/tools/shared.cljsimilarity index 97%rename from src/metabase/metabot/agent/tools/shared.cljrename to src/metabase/metabot/tools/shared.cljindex 095605313e5..518e285b9b8 100644--- a/src/metabase/metabot/agent/tools/shared.clj+++ b/src/metabase/metabot/tools/shared.clj@@ -1,4 +1,4 @@-(ns metabase.metabot.agent.tools.shared+(ns metabase.metabot.tools.shared"Shared tool helpers and state accessors."(:require[metabase.util.log :as log]))diff --git a/src/metabase/metabot/tools/instructions.clj b/src/metabase/metabot/tools/shared/instructions.cljsimilarity index 99%rename from src/metabase/metabot/tools/instructions.cljrename to src/metabase/metabot/tools/shared/instructions.cljindex 3f21ffd640b..099113e1ad6 100644--- a/src/metabase/metabot/tools/instructions.clj+++ b/src/metabase/metabot/tools/shared/instructions.clj@@ -1,4 +1,4 @@-(ns metabase.metabot.tools.instructions+(ns metabase.metabot.tools.shared.instructions"Instruction constants for LLM tool results.These guide the LLM on how to interpret and use tool outputs.Matches Python AI Service InstructionResultSchema patterns exactly.")diff --git a/src/metabase/metabot/tools/llm_representations.clj b/src/metabase/metabot/tools/shared/llm_representations.cljsimilarity index 99%rename from src/metabase/metabot/tools/llm_representations.cljrename to src/metabase/metabot/tools/shared/llm_representations.cljindex 67562d582a8..3ab201271f8 100644--- a/src/metabase/metabot/tools/llm_representations.clj+++ b/src/metabase/metabot/tools/shared/llm_representations.clj@@ -1,4 +1,4 @@-(ns metabase.metabot.tools.llm-representations+(ns metabase.metabot.tools.shared.llm-representations"LLM representation utilities for formatting entities as XML.Matches Python AI Service patterns exactly for consistency."(:requirediff --git a/src/metabase/metabot/agent/tools/slackbot_query.clj b/src/metabase/metabot/tools/slackbot_query.cljsimilarity index 96%rename from src/metabase/metabot/agent/tools/slackbot_query.cljrename to src/metabase/metabot/tools/slackbot_query.cljindex e3799765251..0e6716c0845 100644--- a/src/metabase/metabot/agent/tools/slackbot_query.clj+++ b/src/metabase/metabot/tools/slackbot_query.clj@@ -1,10 +1,10 @@-(ns metabase.metabot.agent.tools.slackbot-query+(ns metabase.metabot.tools.slackbot-query"Slackbot-specific notebook query tool.Like construct-notebook-query-tool but emits adhoc_viz data partsinstead of creating charts. Does not save or navigate."(:require[metabase.metabot.agent.streaming :as streaming]- [metabase.metabot.agent.tools.construct :as construct]+ [metabase.metabot.tools.construct :as construct][metabase.util.log :as log][metabase.util.malli :as mu]))diff --git a/src/metabase/metabot/tools/snippets.clj b/src/metabase/metabot/tools/snippets.cljindex 8538c8b0160..99188ecce11 100644--- a/src/metabase/metabot/tools/snippets.clj+++ b/src/metabase/metabot/tools/snippets.clj@@ -1,7 +1,11 @@(ns metabase.metabot.tools.snippets(:require+ [clojure.string :as str][metabase.metabot.tools.util :as metabot.tools.u]- [metabase.native-query-snippets.core :as snippets]))+ [metabase.native-query-snippets.core :as snippets]+ [metabase.util.malli :as mu]))++(set! *warn-on-reflection* true)(defn get-snippets"Lists SQL snippets available to the current user."@@ -23,3 +27,50 @@(select-keys snippet [:id :name :description :content])))}(catch Exception e(metabot.tools.u/handle-agent-error e))))++(defn- format-snippet-list-output+ [snippets]+ (if (seq snippets)+ (str "<snippets>\n"+ (str/join "\n" (map (fn [{:keys [id name description]}]+ (str "<snippet id=\"" id "\" name=\"" name "\">"+ (when description description)+ "</snippet>"))+ snippets))+ "\n</snippets>")+ "No snippets available."))++(defn- format-snippet-details-output+ [{:keys [id name description content]}]+ (str "<snippet id=\"" id "\" name=\"" name "\">\n"+ (when description (str "<description>" description "</description>\n"))+ (when content (str "<content>\n" content "\n</content>\n"))+ "</snippet>"))++(defn- add-output+ "Add :output to a tool result. Handles both :structured_output and :structured-output."+ [result format-fn]+ (if-let [structured (or (:structured_output result) (:structured-output result))]+ (assoc result :output (format-fn structured))+ result))++(mu/defn ^{:tool-name "list_snippets"+ :capabilities #{:feature-snippets}}+ list-snippets-tool+ "List all SQL snippets available in the Metabase instance.++ Use this tool before editing or creating SQL transforms to understand what+ snippets are available. If any snippets may be relevant to the user's request,+ fetch their content using the get_snippet_details tool."+ [_args :- [:maybe [:map {:closed true}]]]+ (add-output (get-snippets {}) format-snippet-list-output))++(mu/defn ^{:tool-name "get_snippet_details"+ :capabilities #{:feature-snippets}}+ get-snippet-details-tool+ "Get the full details of a SQL snippet including its content.++ Use this tool to retrieve the actual SQL content of a snippet after identifying+ it with list_snippets."+ [{:keys [snippet_id]} :- [:map {:closed true} [:snippet_id :int]]]+ (add-output (get-snippet-details {:snippet-id snippet_id}) format-snippet-details-output))diff --git a/src/metabase/metabot/agent/tools/sql.clj b/src/metabase/metabot/tools/sql.cljsimilarity index 96%rename from src/metabase/metabot/agent/tools/sql.cljrename to src/metabase/metabot/tools/sql.cljindex 2682a69630c..4f198fac2cf 100644--- a/src/metabase/metabot/agent/tools/sql.clj+++ b/src/metabase/metabot/tools/sql.clj@@ -1,14 +1,14 @@-(ns metabase.metabot.agent.tools.sql+(ns metabase.metabot.tools.sql"SQL tool wrappers."(:require[metabase.metabot.agent.streaming :as streaming]- [metabase.metabot.agent.tools.shared :as shared][metabase.metabot.tmpl :as te]- [metabase.metabot.tools.create-sql-query :as create-sql-query-tools]- [metabase.metabot.tools.edit-sql-query :as edit-sql-query-tools]- [metabase.metabot.tools.instructions :as instructions]- [metabase.metabot.tools.llm-representations :as llm-rep]- [metabase.metabot.tools.replace-sql-query :as replace-sql-query-tools]+ [metabase.metabot.tools.shared :as shared]+ [metabase.metabot.tools.shared.instructions :as instructions]+ [metabase.metabot.tools.shared.llm-representations :as llm-rep]+ [metabase.metabot.tools.sql.create :as create-sql-query-tools]+ [metabase.metabot.tools.sql.edit :as edit-sql-query-tools]+ [metabase.metabot.tools.sql.replace :as replace-sql-query-tools][metabase.util :as u][metabase.util.log :as log][metabase.util.malli :as mu]))diff --git a/src/metabase/metabot/tools/create_sql_query.clj b/src/metabase/metabot/tools/sql/create.cljsimilarity index 98%rename from src/metabase/metabot/tools/create_sql_query.cljrename to src/metabase/metabot/tools/sql/create.cljindex f5ac3a2acfc..775de9b7620 100644--- a/src/metabase/metabot/tools/create_sql_query.clj+++ b/src/metabase/metabot/tools/sql/create.clj@@ -1,4 +1,4 @@-(ns metabase.metabot.tools.create-sql-query+(ns metabase.metabot.tools.sql.create"Tool for creating new SQL queries."(:require[metabase.api.common :as api]diff --git a/src/metabase/metabot/tools/edit_sql_query.clj b/src/metabase/metabot/tools/sql/edit.cljsimilarity index 98%rename from src/metabase/metabot/tools/edit_sql_query.cljrename to src/metabase/metabot/tools/sql/edit.cljindex a4f3715a9ad..740f5252da3 100644--- a/src/metabase/metabot/tools/edit_sql_query.clj+++ b/src/metabase/metabot/tools/sql/edit.clj@@ -1,4 +1,4 @@-(ns metabase.metabot.tools.edit-sql-query+(ns metabase.metabot.tools.sql.edit"Tool for editing existing SQL queries."(:require[clojure.string :as str]diff --git a/src/metabase/metabot/tools/replace_sql_query.clj b/src/metabase/metabot/tools/sql/replace.cljsimilarity index 98%rename from src/metabase/metabot/tools/replace_sql_query.cljrename to src/metabase/metabot/tools/sql/replace.cljindex d22011d4c4c..9cba5c54933 100644--- a/src/metabase/metabot/tools/replace_sql_query.clj+++ b/src/metabase/metabot/tools/sql/replace.clj@@ -1,4 +1,4 @@-(ns metabase.metabot.tools.replace-sql-query+(ns metabase.metabot.tools.sql.replace"Tool for replacing SQL query content entirely while preserving metadata."(:require[metabase.metabot.tools.sql.common :as metabot.tools.sql.common]diff --git a/src/metabase/metabot/agent/tools/static_viz.clj b/src/metabase/metabot/tools/static_viz.cljsimilarity index 96%rename from src/metabase/metabot/agent/tools/static_viz.cljrename to src/metabase/metabot/tools/static_viz.cljindex 95b9778a310..9d28d81f3bf 100644--- a/src/metabase/metabot/agent/tools/static_viz.clj+++ b/src/metabase/metabot/tools/static_viz.clj@@ -1,4 +1,4 @@-(ns metabase.metabot.agent.tools.static-viz+(ns metabase.metabot.tools.static-viz"Static visualization tool for the slackbot profile.Renders existing saved questions/metrics as PNG images in Slack."(:requirediff --git a/src/metabase/metabot/tools/subscriptions.clj b/src/metabase/metabot/tools/subscriptions.cljnew file mode 100644index 00000000000..a039ef68955--- /dev/null+++ b/src/metabase/metabot/tools/subscriptions.clj@@ -0,0 +1,162 @@+(ns metabase.metabot.tools.subscriptions+ "Dashboard subscription tool wrapper."+ (:require+ [clojure.set :as set]+ [metabase.api.common :as api]+ [metabase.channel.settings :as channel.settings]+ [metabase.metabot.tools.create-alert :as tools.create-alert]+ [metabase.metabot.tools.shared :as shared]+ [metabase.metabot.tools.util :as metabot.tools.u]+ [metabase.pulse.api :as pulse.api]+ [metabase.util.log :as log]+ [metabase.util.malli :as mu]+ [toucan2.core :as t2]))++(set! *warn-on-reflection* true)++(defn- make-slack-channel+ "Build a pulse channel for Slack delivery."+ [schedule slack-channel]+ (merge {:channel_type :slack+ :enabled true+ :details {:channel slack-channel}}+ (metabot.tools.u/schedule->schedule-map schedule)))++(defn- create-dashboard-subscription*+ "Private helper for create-dashboard-subscription (call that instead)."+ [{:keys [dashboard-id slack-channel schedule]}]+ (let [dashboard (some-> (t2/select-one :model/Dashboard dashboard-id)+ api/read-check+ (t2/hydrate [:dashcards :card]))+ cards (for [{:keys [id card]} (:dashcards dashboard)+ :when (-> card :id int?)]+ (-> card+ api/read-check+ (select-keys [:id :name :collection_id :description :display :parameter_mappings])+ (assoc :dashboard_card_id id :dashboard_id dashboard-id)))+ channel-name (some->> slack-channel+ channel.settings/find-cached-slack-channel-or-username+ ;; match existing code which stores display names like "#some-channel"+ :display-name)+ pulse-data (-> dashboard+ (select-keys [:collection_id :collection_position :name :parameters])+ (assoc :dashboard_id dashboard-id+ :creator_id api/*current-user-id*+ :skip_if_empty false))]+ (cond+ (nil? dashboard)+ {:error "no dashboard with this dashboard_id found"}++ (nil? channel-name)+ {:error "no slack channel found with this name"}++ :else+ (do (pulse.api/create-pulse-with-perm-checks!+ cards+ [(make-slack-channel schedule channel-name)]+ pulse-data)+ {:output "success"}))))++(defn create-dashboard-subscription+ "Create a dashboard subscription and send it to a slack channel."+ [{:keys [dashboard-id slack-channel] :as args}]+ (cond+ (not (int? dashboard-id))+ {:error "invalid dashboard_id"}++ (not (channel.settings/slack-configured?))+ {:error "slack is not configured. Ask an admin to connect slack in Metabase settings."}++ (empty? slack-channel)+ {:error "slack_channel is required"}++ :else+ (try+ (create-dashboard-subscription* args)+ (catch Exception e+ (-> (metabot.tools.u/handle-agent-error e)+ (set/rename-keys {:output :error}))))))++(def ^:private create-dashboard-subscription-system-instructions+ "## Dashboard Subscriptions++You can create dashboard subscriptions that deliver dashboard contents to the user's current slack channel on a+recurring schedule.++### CRITICAL: You MUST call the create_dashboard_subscription tool++When a user asks to subscribe to a dashboard, set up scheduled delivery, or receive regular updates for a dashboard,+you MUST call the create_dashboard_subscription tool. Never tell the user you have created a subscription without+actually calling the tool. If you cannot call the tool (e.g. missing required information), explain what is needed+instead of pretending the subscription was created.++### Required information++Before calling the tool, ensure you have ALL of the following:+1. **Dashboard ID** — obtained from a prior search result or conversation context+2. **Schedule** — frequency (hourly, daily, weekly, monthly) with the appropriate time fields++If any required information is missing, ask the user for it rather than assuming or fabricating values.")++(mu/defn ^{:tool-name "create_dashboard_subscription"+ :system-instructions create-dashboard-subscription-system-instructions}+ slackbot-create-dashboard-subscription-tool+ "Create a recurring subscription that delivers a dashboard's contents to a Slack channel."+ [{:keys [dashboard_id schedule]} :- [:map {:closed true}+ [:dashboard_id :int]+ [:schedule tools.create-alert/schedule-schema]]]+ (let [slack-channel-id (:slack_channel_id (shared/current-context))]+ (when-not slack-channel-id+ (throw (ex-info "This tool can only be used from a Slack channel"+ {:agent-error? true})))+ (try+ (let [result (create-dashboard-subscription+ {:dashboard-id dashboard_id+ :schedule schedule+ :slack-channel slack-channel-id})]+ (if (:error result)+ {:output (:error result)}+ {:output (or (:output result) "Dashboard subscription created successfully.")}))+ (catch Exception e+ (log/error e "Failed to create dashboard subscription")+ {:output (str "Failed to create dashboard subscription: " (or (ex-message e) "Unknown error"))}))))++(def ^:private subscription-schema+ [:map {:closed true}+ [:dashboard_id :int]+ [:email {:optional true} [:maybe :string]]+ [:slack_channel {:optional true} [:maybe :string]]+ [:schedule [:map+ [:frequency [:enum "hourly" "daily" "weekly" "monthly"]]+ [:hour {:optional true} [:maybe :int]]+ [:day_of_week {:optional true} [:maybe :string]]+ [:day_of_month {:optional true} [:maybe :string]]]]])++(mu/defn ^{:tool-name "create_dashboard_subscription"}+ create-dashboard-subscription-tool+ "Create a dashboard subscription to send regular updates via email or Slack.++ Use when a user wants to receive or send regular updates on a dashboard's contents.+ Requires a valid dashboard ID, either an email address or a Slack channel name, and a schedule.++ Do NOT infer email addresses from usernames or other information.+ If the email address is incomplete or missing a part like the TLD,+ ask the user for clarification before proceeding."+ [{:keys [dashboard_id email slack_channel schedule]} :- subscription-schema]+ (try+ (create-dashboard-subscription+ {:dashboard-id dashboard_id+ :email email+ :slack-channel slack_channel+ :schedule (-> schedule+ (update :frequency keyword)+ (cond->+ (:day_of_week schedule) (-> (assoc :day-of-week (keyword (:day_of_week schedule)))+ (dissoc :day_of_week))+ (:day_of_month schedule) (-> (assoc :day-of-month (keyword (:day_of_month schedule)))+ (dissoc :day_of_month))))})+ (catch Exception e+ (log/error e "Error creating dashboard subscription")+ (if (:agent-error? (ex-data e))+ {:output (ex-message e)}+ {:output (str "Failed to create dashboard subscription: " (or (ex-message e) "Unknown error"))}))))diff --git a/src/metabase/metabot/tools/todo.clj b/src/metabase/metabot/tools/todo.cljindex 2c3b4cc177a..b380b906ef3 100644--- a/src/metabase/metabot/tools/todo.clj+++ b/src/metabase/metabot/tools/todo.clj@@ -2,8 +2,11 @@"Tools for managing todo lists during agent conversations.Todos are stored in agent memory and streamed to the frontend via todo_list data parts."(:require+ [clojure.string :as str][metabase.metabot.agent.streaming :as streaming]- [metabase.util.log :as log]))+ [metabase.metabot.tools.shared :as shared]+ [metabase.util.log :as log]+ [metabase.util.malli :as mu]))(set! *warn-on-reflection* true)@@ -77,3 +80,63 @@{:structured-output {:todos todos:todo_count (count todos)}:instructions "You should call todo_write after reading this todo_list to make any updates."}))++(defn- format-todo-write-output+ [{:keys [todo_count]}]+ (str "Todo list updated successfully. " todo_count " item(s)."))++(defn- format-todo-read-output+ [{:keys [todos todo_count]}]+ (if (seq todos)+ (str "Current todo list (" todo_count " items):\n"+ (str/join "\n" (map (fn [{:keys [id content status priority]}]+ (str "- [" status "] " content " (id=" id ", priority=" priority ")"))+ todos)))+ "No todos found."))++(defn- add-output+ [result format-fn]+ (if-let [structured (:structured-output result)]+ (assoc result :output (format-fn structured))+ result))++(def ^:private todo-write-schema+ [:map {:closed true}+ [:todos [:sequential [:map {:closed true}+ [:id :string]+ [:content :string]+ [:status [:enum "pending" "in_progress" "completed" "cancelled"]]+ [:priority [:enum "high" "medium" "low"]]]]]])++(mu/defn ^{:tool-name "todo_write"}+ todo-write-tool+ "Create and manage a structured task list.+ Write or update the todo list with tasks for tracking progress.++ Each todo item must have:+ - id: Unique identifier for the task+ - content: Description of what needs to be done+ - status: One of 'pending', 'in_progress', 'completed', 'cancelled'+ - priority: One of 'high', 'medium', 'low'"+ [{:keys [todos]} :- todo-write-schema]+ (try+ (add-output+ (todo-write {:todos todos+ :memory-atom shared/*memory-atom*})+ format-todo-write-output)+ (catch Exception e+ (if (:agent-error? (ex-data e))+ {:output (ex-message e)}+ {:output (str "Failed to update todo list: " (or (ex-message e) "Unknown error"))}))))++(mu/defn ^{:tool-name "todo_read"}+ todo-read-tool+ "Read the current todo list from memory.+ Returns the list of todos that have been created during this conversation."+ [_args :- [:maybe [:map {:closed true}]]]+ (try+ (add-output+ (todo-read {:memory-atom shared/*memory-atom*})+ format-todo-read-output)+ (catch Exception e+ {:output (str "Failed to read todo list: " (or (ex-message e) "Unknown error"))})))diff --git a/src/metabase/metabot/tools/transforms.clj b/src/metabase/metabot/tools/transforms.cljindex 232f41f90f0..1b29f5c7ab2 100644--- a/src/metabase/metabot/tools/transforms.clj+++ b/src/metabase/metabot/tools/transforms.clj@@ -1,31 +1,163 @@(ns metabase.metabot.tools.transforms+ "Transform tool definitions.+ SQL transform tools are implemented directly in OSS.+ Python transform tools use defenterprise (return nil/error in OSS, real impl in EE)."(:require+ [metabase.metabot.tools.dependencies :as deps]+ [metabase.metabot.tools.shared :as shared]+ [metabase.metabot.tools.transforms.write :as transforms-write-tools][metabase.metabot.tools.util :as metabot.tools.u]+ [metabase.metabot.util :as metabot.u]+ [metabase.premium-features.core :refer [defenterprise]][metabase.transforms.core :as transforms]- [metabase.transforms.schema :as transforms.schema]- [metabase.util.malli.registry :as mr]))+ [metabase.util.log :as log]+ [metabase.util.malli :as mu]))-(mr/def ::transform-source ::transforms.schema/transform-source)-(mr/def ::transform-target ::transforms.schema/transform-target)+(set! *warn-on-reflection* true)-(defn get-transforms- "Get a list of all known transforms."- [_args]+;;; ──────────────────────────────────────────────────────────────────+;;; Formatting helpers+;;; ──────────────────────────────────────────────────────────────────++(defn- format-transform-details-output+ [{:keys [id name description source target] :as _transform}]+ (metabot.u/xml+ [:transform {:id id :name name}+ (when description [:description description])+ (when source+ [:source {:type (:type source)}+ (when (:query source) [:query (:query source)])+ (when (:source-database source) [:database (:source-database source)])])+ (when target [:target (pr-str target)])]))++(defn format-transform-write-output+ "Format the output of a transform write operation."+ [{:keys [message]}]+ (or message "Transform updated successfully."))++(defn add-output+ "Add :output to a tool result. Handles both :structured_output and :structured-output."+ [result format-fn]+ (if-let [structured (or (:structured_output result) (:structured-output result))]+ (assoc result :output (format-fn structured))+ result))++(defn- check-dependencies+ "Check for downstream breakages after a SQL transform edit.+ Returns nil if no issues found or the check fails, otherwise a map with+ :bad_transforms and :bad_questions."+ [transform-id source]+ (when transform-id+ (try+ (let [{:keys [structured_output]} (deps/check-transform-dependencies+ {:id transform-id :source source})]+ (when (and structured_output+ (or (seq (:bad_transforms structured_output))+ (seq (:bad_questions structured_output))))+ structured_output))+ (catch Exception e+ (log/error e "Dependency check failed for transform" transform-id)+ nil))))++(defn- format-dependency-warnings+ "Format dependency check results into instructions for the agent."+ [{:keys [bad_transforms bad_questions]}]+ (str "\n\n**Dependency issues detected.**\n"+ "Your proposed changes would break downstream dependencies.\n\n"+ (when (seq bad_transforms)+ (str "Broken transforms:\n"+ (apply str (for [{:keys [transform]} bad_transforms]+ (str "- [" (:name transform) "](metabase://transform/" (:id transform) ")\n")))))+ (when (seq bad_questions)+ (str "Broken questions:\n"+ (apply str (for [{:keys [question]} bad_questions]+ (str "- [" (:name question) "](metabase://question/" (:id question) ")\n")))))+ "\nYou must summarize these dependency issues for the user. "+ "Do not propose or apply fixes yourself."))++;;; ──────────────────────────────────────────────────────────────────+;;; Tool definitions+;;; ──────────────────────────────────────────────────────────────────++(mu/defn ^{:tool-name "get_transform_details"}+ get-transform-details-tool+ "Get information about a transform."+ [{:keys [transform_id]} :- [:map {:closed true} [:transform_id :int]]](try- {:structured_output- (->> (transforms/get-transforms)- (into [] (comp (filter #(or (transforms/python-transform? %)- (transforms/native-query-transform? %)))- (filter :source_readable)- (map #(select-keys % [:id :entity_id :name :type :description :source])))))}+ (add-output {:structured_output (transforms/get-transform transform_id)}+ format-transform-details-output)(catch Exception e(metabot.tools.u/handle-agent-error e))))-(defn get-transform-details- "Get information about a transform."- [{:keys [transform-id]}]+(def ^:private python-lib-schema+ [:map {:closed true} [:path :string]])++(defenterprise ^{:tool-name "get_transform_python_library_details"+ :schema [:=> [:cat python-lib-schema] :map]+ :ee-feature :transforms}+ get-transform-python-library-details-tool+ "Get Python library details. EE-only; returns an error in OSS."+ metabase-enterprise.metabot.tools.transforms+ [{:keys [_path]}]+ {:output "Python transform tools are only available in Metabase Enterprise Edition."})++(def ^:private write-transform-sql-schema+ [:map {:closed true}+ [:transform_id {:optional true} [:maybe :int]]+ [:edit_action [:map+ [:mode [:enum "edit" "replace"]]+ [:edits {:optional true} [:maybe [:sequential [:map+ [:old_string :string]+ [:new_string :string]+ [:replace_all {:optional true} [:maybe :boolean]]]]]]+ [:new_content {:optional true} [:maybe :string]]]]+ [:thinking {:optional true} [:maybe :string]]+ [:transform_name {:optional true} [:maybe :string]]+ [:transform_description {:optional true} [:maybe :string]]+ [:source_database {:optional true} [:maybe :int]]+ [:source_tables {:optional true} [:maybe :map]]])++(mu/defn ^{:tool-name "write_transform_sql"+ :capabilities #{:feature-transforms :permission-write-transforms}}+ write-transform-sql-tool+ "Write new SQL queries or edit existing queries for transforms.++ Supports two modes:+ - edit: Targeted string replacements with partial edits+ - replace: Replace entire query atomically++ For edit mode, provide edits as an array of {old_string, new_string, replace_all} objects.+ For replace mode, provide new_content with the complete SQL."+ [{:keys [transform_id edit_action thinking transform_name transform_description+ source_database source_tables]} :- write-transform-sql-schema](try- {:structured_output- (transforms/get-transform transform-id)}+ (let [result (add-output+ (transforms-write-tools/write-transform-sql+ {:transform_id transform_id+ :edit_action edit_action+ :thinking thinking+ :transform_name transform_name+ :transform_description transform_description+ :source_database source_database+ :source_tables source_tables+ :memory-atom shared/*memory-atom*+ :context (shared/current-context)})+ format-transform-write-output)+ transform (get-in result [:structured-output :transform])+ dep-issues (check-dependencies transform_id (:source transform))]+ (cond-> result+ dep-issues (update :instructions str (format-dependency-warnings dep-issues))))(catch Exception e- (metabot.tools.u/handle-agent-error e))))+ (if (:agent-error? (ex-data e))+ {:output (ex-message e)}+ {:output (str "Failed to write SQL transform: " (or (ex-message e) "Unknown error"))}))))++(defenterprise ^{:tool-name "write_transform_python"+ :schema [:=> [:cat write-transform-sql-schema] :map]+ :capabilities #{:feature-transforms :feature-transforms-python :permission-write-transforms}+ :ee-feature :transforms}+ write-transform-python-tool+ "Write Python transforms. EE-only; returns an error in OSS."+ metabase-enterprise.metabot.tools.transforms+ [{:keys [_transform_id]}]+ {:output "Python transform tools are only available in Metabase Enterprise Edition."})diff --git a/src/metabase/metabot/tools/transforms_write.clj b/src/metabase/metabot/tools/transforms/write.cljsimilarity index 99%rename from src/metabase/metabot/tools/transforms_write.cljrename to src/metabase/metabot/tools/transforms/write.cljindex 8a5337f9e3b..3625cd60198 100644--- a/src/metabase/metabot/tools/transforms_write.clj+++ b/src/metabase/metabot/tools/transforms/write.clj@@ -1,4 +1,4 @@-(ns metabase.metabot.tools.transforms-write+(ns metabase.metabot.tools.transforms.write"Tools for writing/editing SQL transform source code.Supports both partial edits (targeted string replacements) and full replacement modes."(:requirediff --git a/src/metabase/metabot/tools/util.clj b/src/metabase/metabot/tools/util.cljindex 97356ca53b1..d7667d8023a 100644--- a/src/metabase/metabot/tools/util.clj+++ b/src/metabase/metabot/tools/util.clj@@ -238,7 +238,6 @@(when api/*current-user-id*(collection/visible-collection-filter-clause :collection_id))]}](cond-> base-query-;; Prioritize verified content.(premium-features/has-feature? :content-verification)(assocdiff --git a/test/metabase/metabot/agent/tool_output_test.clj b/test/metabase/metabot/agent/tool_output_test.cljindex 05ce4d842aa..33ebd664952 100644--- a/test/metabase/metabot/agent/tool_output_test.clj+++ b/test/metabase/metabot/agent/tool_output_test.clj@@ -8,9 +8,9 @@[clojure.test :refer :all][metabase.lib.core :as lib][metabase.lib.metadata :as lib.metadata]- [metabase.metabot.agent.tools.metadata :as metadata-tools]- [metabase.metabot.agent.tools.resources :as resource-tools]- [metabase.metabot.agent.tools.search :as search-tools]+ [metabase.metabot.tools.metadata :as metadata-tools]+ [metabase.metabot.tools.resources :as resource-tools]+ [metabase.metabot.tools.search :as search-tools][metabase.test :as mt][metabase.test.fixtures :as fixtures][metabase.warehouse-schema.models.field-values :as field-values]diff --git a/test/metabase/metabot/agent/tools/transforms_test.clj b/test/metabase/metabot/agent/tools/transforms_test.cljdeleted file mode 100644index 296d929179b..00000000000--- a/test/metabase/metabot/agent/tools/transforms_test.clj+++ /dev/null@@ -1,123 +0,0 @@-(ns metabase.metabot.agent.tools.transforms-test- "Tests for agent-level transform tool wrappers, particularly the- dependency checking integration in write-transform-sql-tool."- (:require- [clojure.string :as str]- [clojure.test :refer :all]- [metabase.metabot.agent.tools.shared :as shared]- [metabase.metabot.agent.tools.transforms :as agent-transforms]- [metabase.metabot.tools.dependencies :as deps]- [metabase.metabot.tools.transforms-write :as transforms-write]))--;;; ----------------------------------- dependency check integration tests ---------------------------------------------(deftest write-transform-sql-dependency-check-no-issues-test- (testing "when check-dependencies returns nil (no issues) → result unchanged, no extra instructions"- (let [memory-atom (atom {:state {}})- base-result {:structured-output {:transform {:id 1- :name "Test"- :source {:type "query" :query "SELECT 1"}}- :message "Transform updated successfully."}- :data-parts [{:type :data :data-type "transform_suggestion" :version 1}]}]- (with-redefs [transforms-write/write-transform-sql (fn [_] base-result)- deps/check-transform-dependencies (fn [_] {:structured_output {:success true- :bad_transforms []- :bad_questions nil}})]- (let [result (binding [shared/*memory-atom* memory-atom]- (agent-transforms/write-transform-sql-tool- {:transform_id 1- :edit_action {:mode "replace" :new_content "SELECT 1"}}))]- (is (nil? (:instructions result)))- (is (some? (:output result))))))))--(deftest write-transform-sql-dependency-check-broken-transforms-test- (testing "when check-dependencies returns bad_transforms → instructions appended with transform links"- (let [memory-atom (atom {:state {}})- base-result {:structured-output {:transform {:id 1- :name "Test"- :source {:type "query" :query "SELECT id FROM orders"}}- :message "Transform updated successfully."}- :data-parts [{:type :data :data-type "transform_suggestion" :version 1}]}]- (with-redefs [transforms-write/write-transform-sql (fn [_] base-result)- deps/check-transform-dependencies (fn [_]- {:structured_output- {:success false- :bad_transform_count 1- :bad_transforms [{:transform {:id 2 :name "Downstream Transform"}- :errors ["Column 'total' not found"]}]- :bad_questions nil}})]- (let [result (binding [shared/*memory-atom* memory-atom]- (agent-transforms/write-transform-sql-tool- {:transform_id 1- :edit_action {:mode "replace" :new_content "SELECT id FROM orders"}}))]- (is (some? (:instructions result)))- (is (str/includes? (:instructions result) "Dependency issues detected"))- (is (str/includes? (:instructions result) "Broken transforms"))- (is (str/includes? (:instructions result) "Downstream Transform"))- (is (str/includes? (:instructions result) "metabase://transform/2")))))))--(deftest write-transform-sql-dependency-check-broken-questions-test- (testing "when check-dependencies returns bad_questions → instructions appended with question links"- (let [memory-atom (atom {:state {}})- base-result {:structured-output {:transform {:id 1- :name "Test"- :source {:type "query" :query "SELECT id FROM orders"}}- :message "Transform updated successfully."}- :data-parts [{:type :data :data-type "transform_suggestion" :version 1}]}]- (with-redefs [transforms-write/write-transform-sql (fn [_] base-result)- deps/check-transform-dependencies (fn [_]- {:structured_output- {:success false- :bad_transform_count 0- :bad_transforms []- :bad_question_count 2- :bad_questions [{:question {:id 10 :name "Revenue Report"}- :errors ["Column 'total' not found"]}- {:question {:id 11 :name "Monthly Summary"}- :errors ["Column 'total' not found"]}]}})]- (let [result (binding [shared/*memory-atom* memory-atom]- (agent-transforms/write-transform-sql-tool- {:transform_id 1- :edit_action {:mode "replace" :new_content "SELECT id FROM orders"}}))]- (is (some? (:instructions result)))- (is (str/includes? (:instructions result) "Broken questions"))- (is (str/includes? (:instructions result) "Revenue Report"))- (is (str/includes? (:instructions result) "metabase://question/10"))- (is (str/includes? (:instructions result) "Monthly Summary"))- (is (str/includes? (:instructions result) "metabase://question/11")))))))--(deftest write-transform-sql-dependency-check-error-test- (testing "when check-dependencies throws → graceful degradation (no crash, result unchanged)"- (let [memory-atom (atom {:state {}})- base-result {:structured-output {:transform {:id 1- :name "Test"- :source {:type "query" :query "SELECT 1"}}- :message "Transform updated successfully."}- :data-parts [{:type :data :data-type "transform_suggestion" :version 1}]}]- (with-redefs [transforms-write/write-transform-sql (fn [_] base-result)- deps/check-transform-dependencies (fn [_] (throw (Exception. "DB connection failed")))]- (let [result (binding [shared/*memory-atom* memory-atom]- (agent-transforms/write-transform-sql-tool- {:transform_id 1- :edit_action {:mode "replace" :new_content "SELECT 1"}}))]- ;; Should succeed without instructions — the dep check failure is logged but not propagated- (is (nil? (:instructions result)))- (is (some? (:output result))))))))--(deftest write-transform-sql-dependency-check-new-transform-test- (testing "new transforms (no transform_id) → dependency check skipped"- (let [memory-atom (atom {:state {}})- dep-called? (atom false)- base-result {:structured-output {:transform {:name "New Transform"- :source {:type "query" :query "SELECT 1"}}- :message "Transform created successfully."}- :data-parts [{:type :data :data-type "transform_suggestion" :version 1}]}]- (with-redefs [transforms-write/write-transform-sql (fn [_] base-result)- deps/check-transform-dependencies (fn [_] (reset! dep-called? true) nil)]- (let [result (binding [shared/*memory-atom* memory-atom]- (agent-transforms/write-transform-sql-tool- {:edit_action {:mode "replace" :new_content "SELECT 1"}- :transform_name "New Transform"}))]- (is (false? @dep-called?))- (is (nil? (:instructions result)))- (is (some? (:output result))))))))diff --git a/test/metabase/metabot/agent/user_context_test.clj b/test/metabase/metabot/agent/user_context_test.cljindex 97a21dc36e0..396f7d02436 100644--- a/test/metabase/metabot/agent/user_context_test.clj+++ b/test/metabase/metabot/agent/user_context_test.clj@@ -3,7 +3,7 @@[clojure.test :refer :all][metabase.metabot.agent.user-context :as user-context][metabase.metabot.tools.entity-details :as entity-details]- [metabase.metabot.tools.llm-representations :as llm-rep]+ [metabase.metabot.tools.shared.llm-representations :as llm-rep][metabase.test :as mt]))(deftest format-current-time-testdiff --git a/test/metabase/metabot/api/document_test.clj b/test/metabase/metabot/api/document_test.cljindex c067c3d1bd4..f095337b06a 100644--- a/test/metabase/metabot/api/document_test.clj+++ b/test/metabase/metabot/api/document_test.clj@@ -11,7 +11,23 @@(use-fixtures :once (fixtures/initialize :db :test-users))-(deftest native-generate-content-prometheus-test+(deftest generate-content-backwards-compatible-route-test+ (mt/with-premium-features #{:metabot-v3}+ (with-redefs [openrouter/openrouter+ (fn [_]+ (mut/mock-llm-response+ [{:type :start :id "msg-1"}+ {:type :text :text "No chart available"}+ {:type :usage :usage {:promptTokens 100 :completionTokens 20}+ :model "test-model" :id "msg-1"}]))]+ (is (= {:draft_card nil+ :description nil+ :error "No chart available"}+ (mt/user-http-request :crowberto+ :post 200 "metabot/document/generate-content"+ {:instructions "Show me sales data"}))))))++(deftest generate-content-prometheus-test(mt/with-premium-features #{:metabot-v3}(mt/with-prometheus-system! [_ system](with-redefs [openrouter/openrouter@@ -22,7 +38,7 @@{:type :usage :usage {:promptTokens 100 :completionTokens 20}:model "anthropic/claude-haiku-4-5" :id "msg-1"}]))](mt/user-http-request :crowberto- :post 200 "metabot/document/native-generate-content"+ :post 200 "metabot/document/generate-content"{:instructions "Show me sales data"}))(is (== 1 (mt/metric-value system :metabase-metabot/agent-requests{:profile-id "document-generate-content"})))@@ -35,7 +51,7 @@(is (== 20 (mt/metric-value system :metabase-metabot/llm-output-tokens{:model "openrouter/anthropic/claude-haiku-4-5" :source "agent"}))))))-(deftest native-generate-content-snowplow-test+(deftest generate-content-snowplow-test(mt/with-premium-features #{:metabot-v3}(let [rasta-id (mt/user->id :rasta)](with-redefs [openrouter/openrouter@@ -47,7 +63,7 @@:model "anthropic/claude-haiku-4-5" :id "msg-1"}]))](snowplow-test/with-fake-snowplow-collector(mt/user-http-request :rasta- :post 200 "metabot/document/native-generate-content"+ :post 200 "metabot/document/generate-content"{:instructions "Show me sales data"})(is (=? [{:user-id (str rasta-id):data {"model_id" "openrouter/anthropic/claude-haiku-4-5"diff --git a/test/metabase/metabot/api/entity_analysis_test.clj b/test/metabase/metabot/api/entity_analysis_test.cljindex c93036dd360..a94c467ff6c 100644--- a/test/metabase/metabot/api/entity_analysis_test.clj+++ b/test/metabase/metabot/api/entity_analysis_test.clj@@ -1,12 +1,12 @@(ns metabase.metabot.api.entity-analysis-test(:require[clojure.test :refer :all]- [metabase.metabot.client :as metabot-client]+ [metabase.metabot.core :as metabot][metabase.test :as mt]))(deftest analyze-chart-test(testing "POST /api/ai-entity-analysis/analyze-chart"- (with-redefs [metabot-client/analyze-chart (constantly {:analysis "This chart shows a steady increase in sales over time, with a notable peak in Q4."})]+ (with-redefs [metabot/analyze-chart (constantly {:analysis "This chart shows a steady increase in sales over time, with a notable peak in Q4."})](let [response (mt/user-http-request :rasta :post 200 "ai-entity-analysis/analyze-chart"{:image_base64 "base64encodedimage":name "Sales Trend"diff --git a/test/metabase/metabot/api/metabot_test.clj b/test/metabase/metabot/api/metabot_test.cljindex 5116b837164..e39f1aaed22 100644--- a/test/metabase/metabot/api/metabot_test.clj+++ b/test/metabase/metabot/api/metabot_test.clj@@ -5,7 +5,7 @@[metabase.collections.models.collection :as collection][metabase.lib.core :as lib][metabase.lib.metadata :as lib.metadata]- [metabase.metabot.client :as metabot.client]+ [metabase.metabot.example-question-generator :as metabot.example-question-generator][metabase.metabot.suggested-prompts :as metabot.suggested-prompts][metabase.permissions.core :as perms][metabase.permissions.models.permissions-group :as perms-group]@@ -66,7 +66,7 @@:tables :table_questions})))];; --------------------------- Generating sample prompts ---------------------------(testing "should generate prompt suggestions for metabot"- (with-redefs [metabot.client/generate-example-questions prompt-generator]+ (with-redefs [metabot.example-question-generator/generate-example-questions prompt-generator];; Trigger prompt generation by calling the regenerate endpoint(mt/user-http-request :crowberto :post 204(format "metabot/metabot/%d/prompt-suggestions/regenerate" metabot-id)))@@ -143,7 +143,7 @@(mt/user-http-request :rasta :post 403 url)(is (= remaining-prompt-ids (current-prompt-ids))))(testing "admin users are allowed"- (with-redefs [metabot.client/generate-example-questions prompt-generator]+ (with-redefs [metabot.example-question-generator/generate-example-questions prompt-generator](mt/user-http-request :crowberto :post 204 url)))))(let [new-prompt-ids (current-prompt-ids)]diff --git a/test/metabase/metabot/api/sql_fixer_test.clj b/test/metabase/metabot/api/sql_fixer_test.cljdeleted file mode 100644index 04c699fe3e5..00000000000--- a/test/metabase/metabot/api/sql_fixer_test.clj+++ /dev/null@@ -1,72 +0,0 @@-(ns metabase.metabot.api.sql-fixer-test- (:require- [clojure.string :as str]- [clojure.test :refer :all]- [metabase.lib.core :as lib]- [metabase.metabot.table-utils :as table-utils]- [metabase.test :as mt]))--(deftest ^:parallel schema-sample-test- (mt/test-driver :h2- (let [query (lib/native-query (mt/metadata-provider)- (str "SELECT * FROM x.orders1"- " INNER JOIN products ON orders1.product_id = products.id"- " INNER JOIN ANALYTIC_EVENT ON true"))- normalize #(into #{} (str/split % #"(?<=;)\n"))]- (is (= (-> (str "CREATE TABLE PUBLIC.PRODUCTS (\n"- " ID BIGINT,\n"- " EAN CHARACTER VARYING,\n"- " TITLE CHARACTER VARYING,\n"- " CATEGORY CHARACTER VARYING,\n"- " VENDOR CHARACTER VARYING,\n"- " PRICE DOUBLE PRECISION,\n"- " RATING DOUBLE PRECISION,\n"- " CREATED_AT TIMESTAMP WITH TIME ZONE\n"- ");\n"- "CREATE TABLE PUBLIC.ORDERS (\n"- " ID BIGINT,\n"- " USER_ID INTEGER,\n"- " PRODUCT_ID INTEGER,\n"- " SUBTOTAL DOUBLE PRECISION,\n"- " TAX DOUBLE PRECISION,\n"- " TOTAL DOUBLE PRECISION,\n"- " DISCOUNT DOUBLE PRECISION,\n"- " CREATED_AT TIMESTAMP WITH TIME ZONE,\n"- " QUANTITY INTEGER\n"- ");\n"- "CREATE TABLE PUBLIC.USERS (\n"- " ID BIGINT,\n"- " NAME CHARACTER VARYING,\n"- " LAST_LOGIN TIMESTAMP,\n"- " PASSWORD CHARACTER VARYING\n"- ");\n")- normalize)- (-> (mt/with-current-user (mt/user->id :crowberto)- (table-utils/schema-sample query {:all-tables-limit 5}))- normalize))))))--(deftest ^:parallel no-used-table-test- (mt/test-driver :postgres- (let [query (lib/native-query (mt/metadata-provider) "SELECT * FROM x.orders1")- normalize #(into #{} (str/split % #"(?<=;)\n"))]- (is (= (-> (str "CREATE TABLE public.orders (\n"- " id int4,\n"- " user_id int4,\n"- " product_id int4,\n"- " subtotal float8,\n"- " tax float8,\n"- " total float8,\n"- " discount float8,\n"- " created_at timestamptz,\n"- " quantity int4\n"- ");\n"- "CREATE TABLE public.users (\n"- " id int4,\n"- " name text,\n"- " last_login timestamp,\n"- " password text\n"- ");\n")- normalize)- (-> (mt/with-current-user (mt/user->id :crowberto)- (table-utils/schema-sample query {:all-tables-limit 5}))- normalize))))))diff --git a/test/metabase/metabot/api_test.clj b/test/metabase/metabot/api_test.cljindex d88d8c21185..440a3dfd336 100644--- a/test/metabase/metabot/api_test.clj+++ b/test/metabase/metabot/api_test.clj@@ -1,7 +1,6 @@(ns metabase.metabot.api-test(:require[clj-http.client :as http]- [clojure.core.async :as a][clojure.string :as str][clojure.test :refer :all][compojure.response]@@ -9,14 +8,10 @@[metabase.config.core :as config][metabase.llm.settings :as llm.settings][metabase.metabot.api :as api]- [metabase.metabot.client :as client]- [metabase.metabot.client-test :as client-test][metabase.metabot.config :as metabot.config][metabase.metabot.context :as metabot.context][metabase.metabot.self.openrouter :as openrouter]- [metabase.metabot.settings :as metabot.settings][metabase.metabot.test-util :as mut]- [metabase.metabot.util :as metabot.u][metabase.search.test-util :as search.tu][metabase.server.instance :as server.instance][metabase.server.streaming-response :as sr]@@ -27,168 +22,53 @@(set! *warn-on-reflection* true)-(deftest agent-streaming-test- (mt/with-premium-features #{:metabot-v3}- ;; Ensure we use the Python AI service path, not native agent- (mt/with-temporary-setting-values [metabot.settings/use-native-agent false]- (let [mock-response (client-test/make-mock-text-stream-response- ["Hello", " from", " streaming!"]- {"some-model" {:prompt 12 :completion 3}})- conversation-id (str (random-uuid))- question {:role "user" :content "Test streaming question"}- historical-message {:role "user" :content "previous message"}- ai-requests (atom [])]- (mt/with-dynamic-fn-redefs [client/post! (fn [url opts]- (swap! ai-requests conj (-> (String. ^bytes (:body opts) "UTF-8")- json/decode+kw))- ((client-test/mock-post! mock-response) url opts))]- (testing "Streaming request"- (doseq [metabot-id [nil (str (random-uuid))]]- (mt/with-model-cleanup [:model/MetabotMessage- [:model/MetabotConversation :created_at]]- (reset! ai-requests [])- (let [response (mt/user-http-request :rasta :post 202 "metabot/agent-streaming"- (-> {:message (:content question)- :context {}- :conversation_id conversation-id- :history [historical-message]- :state {}}- (m/assoc-some :metabot_id metabot-id)))- conv (t2/select-one :model/MetabotConversation :id conversation-id)- messages (t2/select :model/MetabotMessage :conversation_id conversation-id)]- (is (=? [{:messages [historical-message question]- :conversation_id conversation-id}]- @ai-requests))- (is (=? [{:_type :TEXT- :role "assistant"- :content "Hello from streaming!"}- {:_type :FINISH_MESSAGE- :finish_reason "stop"- :usage {:some-model {:prompt 12 :completion 3}}}]- (metabot.u/aisdk->messages "assistant" (str/split-lines response))))- (is (=? {:user_id (mt/user->id :rasta)}- conv))- (is (=? [{:total_tokens 0- :role :user- :data [{:role "user" :content (:content question)}]}- {:total_tokens 15- :role :assistant- :data [{:role "assistant" :content "Hello from streaming!"}]}]- messages)))))))))))-(deftest native-agent-streaming-test- (mt/with-premium-features #{:metabot-v3}- (mt/with-temporary-setting-values [metabot.settings/use-native-agent true]- (with-redefs [config/is-dev? true]- (let [conversation-id (str (random-uuid))- question {:role "user" :content "Test native streaming"}- historical-message {:role "user" :content "previous message"}]- (with-redefs [openrouter/openrouter (fn [_]- (mut/mock-llm-response- [{:type :start :id "msg-1"}- {:type :text :text "Hello from native agent!"}- {:type :usage :usage {:promptTokens 10 :completionTokens 5}- :model "test-model" :id "msg-1"}]))]- (testing "Native agent streaming request"- (mt/with-model-cleanup [:model/MetabotMessage- [:model/MetabotConversation :created_at]]- (let [response (mt/user-http-request :rasta :post 202 "metabot/agent-streaming"- {:message (:content question)- :context {}- :conversation_id conversation-id- :history [historical-message]- :state {}})- lines (str/split-lines response)- conv (t2/select-one :model/MetabotConversation :id conversation-id)- messages (t2/select :model/MetabotMessage :conversation_id conversation-id)]- ;; Native agent emits AI SDK v4 line protocol directly- (testing "response contains expected line types"- ;; f:{start}, 0:"text" chunks, 2:{state data}, d:{finish with usage}- (is (=? [#"f:.*"- #"0:.*"- #"2:.*"- #"d:.*"]- (m/distinct-by #(subs % 0 2) lines)))- ;; Text chunks reassemble to full message- (let [text-lines (filter #(str/starts-with? % "0:") lines)]- (is (= "Hello from native agent!"- (apply str (map #(json/decode (subs % 2)) text-lines)))))- ;; Finish line includes usage- (is (str/includes? (last lines) "promptTokens")))- (is (=? {:user_id (mt/user->id :rasta)}- conv))- ;; Native agent stores parts in raw format- (is (=? [{:total_tokens 0- :role :user- :data [{:role "user" :content (:content question)}]}- {:total_tokens pos-int?- :role :assistant- :data [{:type "text" :text "Hello from native agent!"}]}]- messages)))))))))))--(deftest closing-connection-test- (mt/with-temporary-setting-values [metabot.settings/use-native-agent false]- (let [messages (atom nil)- cnt (atom 30)- canceled (atom nil)- ai-handler (fn [req respond _raise]- (respond- (compojure.response/render- (sr/streaming-response {:content-type "text/event-stream; charset=utf-8"- ;; Transfer-Encoding: chunked is what makes normal .close on body fail- ;; See: `metabase.metabot.client/quick-closing-body`- :headers {"Transfer-Encoding" "chunked"}} [os canceled-chan]- (try- (loop []- (if (a/poll! canceled-chan)- (reset! canceled :nice)- (do- (.write os (.getBytes (str "2:" (json/encode {:msg @cnt}) "\n")))- (.flush os)- (swap! cnt dec)- (Thread/sleep 10)- (when (pos? @cnt)- (recur)))))- (catch Exception _e- (reset! canceled :not-nice))))- req)))- ai-server (doto (server.instance/create-server ai-handler {:port 0 :join? false})- .start)- ai-url (str "http://localhost:" (.. ai-server getURI getPort))]- (try- (mt/test-helpers-set-global-values!- (search.tu/with-index-disabled- (mt/with-premium-features #{:metabot-v3}- (with-redefs [client/ai-url (constantly ai-url)- api/store-aiservice-messages! (fn [_conv-id _prof-id msgs]- (reset! messages msgs))- sr/async-cancellation-poll-interval-ms 5]- (testing "Closing stream body will drop connection to LLM"- (let [body (mt/user-real-request :rasta :post 202 "metabot/agent-streaming"- {:request-options {:as :stream- :decompress-body false}}- {:message "Test closure"- :context {}- :conversation_id (str (random-uuid))- :history []- :state {}})]- (.read ^java.io.InputStream body) ;; start the handler- (.close ^java.io.Closeable body)- (u/poll {:thunk #(deref canceled)- :done? some?- :interval-ms 5})- (is (number? (:msg (first @messages)))- "store-messages! was called in the end on the lines streaming-request managed to process")- ;; if this flakes in CI, increase the number a bit; but it was 1 quite consistently for me- (is (> 10 (count @messages))- "But we shouldn't go through all 30 of them")- (testing "request to ai-service was canceled"- (is (< 20 @cnt) "Stopped writing when channel closed")- ;; see `metabase.server.streaming-response-test/canceling-chan-is-working-test` for explanation,- ;; reducing flakiness here- (is (some? @canceled)))))))))- (finally- (.stop ai-server))))))+ (with-redefs [config/is-dev? true]+ (let [conversation-id (str (random-uuid))+ question {:role "user" :content "Test native streaming"}+ historical-message {:role "user" :content "previous message"}]+ (with-redefs [openrouter/openrouter (fn [_]+ (mut/mock-llm-response+ [{:type :start :id "msg-1"}+ {:type :text :text "Hello from native agent!"}+ {:type :usage :usage {:promptTokens 10 :completionTokens 5}+ :model "test-model" :id "msg-1"}]))]+ (testing "Native agent streaming request"+ (mt/with-model-cleanup [:model/MetabotMessage+ [:model/MetabotConversation :created_at]]+ (let [response (mt/user-http-request :rasta :post 202 "metabot/agent-streaming"+ {:message (:content question)+ :context {}+ :conversation_id conversation-id+ :history [historical-message]+ :state {}})+ lines (str/split-lines response)+ conv (t2/select-one :model/MetabotConversation :id conversation-id)+ messages (t2/select :model/MetabotMessage :conversation_id conversation-id)]+ ;; Native agent emits AI SDK v4 line protocol directly+ (testing "response contains expected line types"+ ;; f:{start}, 0:"text" chunks, 2:{state data}, d:{finish with usage}+ (is (=? [#"f:.*"+ #"0:.*"+ #"2:.*"+ #"d:.*"]+ (m/distinct-by #(subs % 0 2) lines)))+ ;; Text chunks reassemble to full message+ (let [text-lines (filter #(str/starts-with? % "0:") lines)]+ (is (= "Hello from native agent!"+ (apply str (map #(json/decode (subs % 2)) text-lines)))))+ ;; Finish line includes usage+ (is (str/includes? (last lines) "promptTokens")))+ (is (=? {:user_id (mt/user->id :rasta)}+ conv))+ ;; Native agent stores parts in raw format+ (is (=? [{:total_tokens 0+ :role :user+ :data [{:role "user" :content (:content question)}]}+ {:total_tokens pos-int?+ :role :assistant+ :data [{:type "text" :text "Hello from native agent!"}]}]+ messages)))))))))(defn ^:private sse-event"Format an SSE event as a string for a mock LLM server."@@ -258,52 +138,50 @@(try(mt/test-helpers-set-global-values!(search.tu/with-index-disabled- (mt/with-premium-features #{:metabot-v3}- (mt/with-temporary-setting-values [metabot.settings/use-native-agent true]- (let [real-http-post http/post]- (with-redefs [llm.settings/llm-openrouter-api-key (constantly "fake-key")- llm.settings/llm-openrouter-api-base-url (constantly llm-url)- ;; The fake LLM server doesn't gzip, but clj-http wraps with- ;; GZIPInputStream by default. Closing mid-stream causes ZLIB errors.- http/post (fn [url opts]- (real-http-post url (assoc opts :decompress-body false)))- metabot.context/create-context identity- api/store-native-parts! (fn [_conv-id _prof-id parts]- (reset! stored-parts parts))- sr/async-cancellation-poll-interval-ms 5]- (testing "Closing stream body will drop connection to LLM"- (reset! cnt total-chunks)- (reset! stored-parts nil)- (let [body (mt/user-real-request :rasta :post 202 "metabot/agent-streaming"- {:request-options {:as :stream- :decompress-body false}}- {:message "Test closure"- :context {}- :conversation_id (str (random-uuid))- :history []- :state {}})]- (.read ^java.io.InputStream body) ;; start the handler- (.close ^java.io.Closeable body)- (u/poll {:thunk #(deref stored-parts)- :done? some?- :interval-ms 5- :timeout-ms 1000})- (is (some? @stored-parts) "store-parts! was called even though client disconnected")- (testing "LLM server stopped writing when connection was dropped"- (is (< 10 @cnt) "Server should not have written all chunks"))- ;; The stored parts should contain partial data — not all 30 chunks.- ;; Text chunks are combined by combine-text-parts-xf, so we check- ;; that the concatenated text is shorter than it would be if all- ;; 30 chunks were processed.- (let [stored-text (->> @stored-parts- (filter #(= :text (:type %)))- (map :text)- (str/join ""))]- (is (< (count stored-text)- ;; Each chunk is "chunk-NN " (~10 chars). If all 30 were- ;; processed, that's ~300 chars. We should have far fewer.- (* 10 total-chunks))- "Only a fraction of the text chunks were processed before disconnect"))))))))))+ (let [real-http-post http/post]+ (with-redefs [llm.settings/llm-openrouter-api-key (constantly "fake-key")+ llm.settings/llm-openrouter-api-base-url (constantly llm-url)+ ;; The fake LLM server doesn't gzip, but clj-http wraps with+ ;; GZIPInputStream by default. Closing mid-stream causes ZLIB errors.+ http/post (fn [url opts]+ (real-http-post url (assoc opts :decompress-body false)))+ metabot.context/create-context identity+ api/store-native-parts! (fn [_conv-id _prof-id parts]+ (reset! stored-parts parts))+ sr/async-cancellation-poll-interval-ms 5]+ (testing "Closing stream body will drop connection to LLM"+ (reset! cnt total-chunks)+ (reset! stored-parts nil)+ (let [body (mt/user-real-request :rasta :post 202 "metabot/agent-streaming"+ {:request-options {:as :stream+ :decompress-body false}}+ {:message "Test closure"+ :context {}+ :conversation_id (str (random-uuid))+ :history []+ :state {}})]+ (.read ^java.io.InputStream body) ;; start the handler+ (.close ^java.io.Closeable body)+ (u/poll {:thunk #(deref stored-parts)+ :done? some?+ :interval-ms 5+ :timeout-ms 1000})+ (is (some? @stored-parts) "store-parts! was called even though client disconnected")+ (testing "LLM server stopped writing when connection was dropped"+ (is (< 10 @cnt) "Server should not have written all chunks"))+ ;; The stored parts should contain partial data — not all 30 chunks.+ ;; Text chunks are combined by combine-text-parts-xf, so we check+ ;; that the concatenated text is shorter than it would be if all+ ;; 30 chunks were processed.+ (let [stored-text (->> @stored-parts+ (filter #(= :text (:type %)))+ (map :text)+ (str/join ""))]+ (is (< (count stored-text)+ ;; Each chunk is "chunk-NN " (~10 chars). If all 30 were+ ;; processed, that's ~300 chars. We should have far fewer.+ (* 10 total-chunks))+ "Only a fraction of the text chunks were processed before disconnect"))))))))(finally(.stop llm-server))))))@@ -325,16 +203,17 @@(deftest metabot-enabled-setting-test(mt/with-premium-features #{:metabot-v3}- (let [mock-response (client-test/make-mock-text-stream-response- ["Hello"] {"m" {:prompt 1 :completion 1}})- conversation-id (str (random-uuid))- base-request {:message "Test"- :context {}- :conversation_id conversation-id- :history []- :state {}}]- (mt/with-dynamic-fn-redefs [client/post! (fn [url opts]- ((client-test/mock-post! mock-response) url opts))]+ (let [base-request {:message "Test"+ :context {}+ :conversation_id (str (random-uuid))+ :history []+ :state {}}]+ (with-redefs [openrouter/openrouter (fn [_]+ (mut/mock-llm-response+ [{:type :start :id "msg-1"}+ {:type :text :text "Hello"}+ {:type :usage :usage {:promptTokens 1 :completionTokens 1}+ :model "test-model" :id "msg-1"}]))](testing "Regular metabot is blocked when metabot-enabled is false"(mt/with-temporary-setting-values [metabot-enabled? false](mt/with-model-cleanup [:model/MetabotMessagediff --git a/test/metabase/metabot/client_test.clj b/test/metabase/metabot/client_test.cljdeleted file mode 100644index 1f656e5cd78..00000000000--- a/test/metabase/metabot/client_test.clj+++ /dev/null@@ -1,231 +0,0 @@-(ns metabase.metabot.client-test- (:require- [clj-http.client :as http]- [clojure.core.async :as a]- [clojure.string :as str]- [clojure.test :refer :all]- [metabase.lib.core :as lib]- [metabase.lib.metadata :as lib.metadata]- [metabase.metabot.client :as metabot.client]- [metabase.metabot.client.schema :as metabot.client.schema]- [metabase.metabot.config :as metabot.config]- [metabase.metabot.suggested-prompts :as metabot.suggested-prompts]- [metabase.metabot.util :as metabot.util]- [metabase.test :as mt]- [metabase.util.json :as json]- [metabase.util.malli :as mu]- [toucan2.core :as t2])- (:import- (java.io ByteArrayOutputStream Closeable PipedInputStream PipedOutputStream)- (metabase.server.streaming_response StreamingResponse)))--(set! *warn-on-reflection* true)--(mu/defn- make-mock-stream-response* [part-prefix finish-reason chunks usage :- ::metabot.client.schema/usage]- (str (->> chunks- (map #(str part-prefix (json/encode %) "\n"))- (str/join))- "d:" (json/encode {:finishReason finish-reason :usage usage})))--(mu/defn make-mock-text-stream-response [chunks usage :- ::metabot.client.schema/usage]- (make-mock-stream-response* "0:" "stop" chunks usage))--(mu/defn make-mock-error-stream-response [chunks usage :- ::metabot.client.schema/usage]- (make-mock-stream-response* "3:" "error" chunks usage))--(defn mock-post! [^String body & [{:keys [delay-ms]- :or {delay-ms 0}}]]- (fn [_url _opts]- (let [ret (PipedInputStream.)- pipe (PipedOutputStream. ret)]- (future- (try- (doseq [^String line (str/split body #"\n")]- (.write pipe (.getBytes line "UTF-8"))- (.write pipe (.getBytes "\n" "UTF-8"))- (.flush pipe)- (Thread/sleep ^long delay-ms))- (finally- (.close pipe))))- {:status 200- :headers {"content-type" "text/event-stream"}- :body ret- :http-client (reify Closeable- (close [_this]- (.close ret)))})))--(defn consume-streaming-response- "Execute a StreamingResponse and capture its output"- [^StreamingResponse streaming-response]- (let [output-stream (ByteArrayOutputStream.)- canceled-chan (a/promise-chan)]- ;; Execute the streaming function- ((.f streaming-response) output-stream canceled-chan)- (.toString output-stream "UTF-8")))--(deftest client-test- (mt/with-premium-features #{:metabot-v3}- (let [input ["a1" "a2" "a3"]- mock-response (make-mock-text-stream-response input {"some-model" {:prompt 8 :completion 2}})- cid (str (random-uuid))- req {:context {:some "context"}- :message {:role :user :content "stuff"}- :history []- :profile-id "test-profile"- :conversation-id cid- :session-id "test-session"- :state {:some "state"}}]- (mt/with-dynamic-fn-redefs [http/post (mock-post! mock-response)]- (mt/with-current-user (mt/user->id :crowberto)- (let [res (metabot.client/streaming-request req)- body (consume-streaming-response res)]- (is (instance? StreamingResponse res))- (is (= "text/event-stream; charset=utf-8" (:content-type (.options ^StreamingResponse res))))- (is (string? body))- (is (=? [{:_type :TEXT :content "a1a2a3"}- {:_type :FINISH_MESSAGE :finish_reason "stop"}]- (metabot.util/aisdk->messages :assistant (str/split-lines body))))))))))--(deftest client-error-test- (mt/with-premium-features #{:metabot-v3}- (let [input ["oof " "bad " "error!"]- mock-response (make-mock-error-stream-response input {"some-model" {:prompt 8 :completion 2}})- cid (str (random-uuid))- req {:context {:some "context"}- :message {:role :user :content "stuff"}- :history []- :profile-id "test-profile"- :conversation-id cid- :session-id "test-session"- :state {:some "state"}}]- (mt/with-dynamic-fn-redefs [http/post (mock-post! mock-response)]- (mt/with-current-user (mt/user->id :crowberto)- (let [res (metabot.client/streaming-request req)- body (consume-streaming-response res)]- (is (instance? StreamingResponse res))- (is (= "text/event-stream; charset=utf-8" (:content-type (.options ^StreamingResponse res))))- (is (string? body))- (is (=? [{:_type :ERROR :content "oof bad error!"}- {:_type :FINISH_MESSAGE :finish_reason "error"}]- (metabot.util/aisdk->messages :assistant (str/split-lines body))))))))))--(deftest streaming-request-with-callback-test- (mt/with-premium-features #{:metabot-v3}- (let [input ["a1" "a2" "a3"]- mock-response (make-mock-text-stream-response input {"some-model" {:prompt 8 :completion 2}})- req {:context {:some "context"}- :message {:role :user :content "stuff"}- :history []- :profile-id "test-profile"- :conversation-id (str (random-uuid))- :session-id "test-session"- :state {:some "state"}}]- (testing "collects and returns all lines"- (mt/with-dynamic-fn-redefs [http/post (mock-post! mock-response)]- (mt/with-current-user (mt/user->id :crowberto)- (let [lines (metabot.client/streaming-request-with-callback req)]- (is (sequential? lines))- (is (pos? (count lines)))- (is (=? [{:_type :TEXT :content "a1a2a3"}- {:_type :FINISH_MESSAGE :finish_reason "stop"}]- (metabot.util/aisdk->messages :assistant lines)))))))- (testing "invokes on-line callback for each line"- (mt/with-dynamic-fn-redefs [http/post (mock-post! mock-response)]- (mt/with-current-user (mt/user->id :crowberto)- (let [callback-lines (atom [])- lines (metabot.client/streaming-request-with-callback- (assoc req :on-line #(swap! callback-lines conj %)))]- (is (= lines @callback-lines))))))- (testing "handles stream errors gracefully"- (mt/with-dynamic-fn-redefs [http/post (mock-post! mock-response {:delay-ms 10})]- (mt/with-current-user (mt/user->id :crowberto)- (let [error-lines (atom [])- lines (metabot.client/streaming-request-with-callback- (assoc req :on-line #(swap! error-lines conj %)))]- (is (sequential? lines))- (is (= lines @error-lines)))))))))--(deftest streaming-request-with-callback-on-complete-test- (mt/with-premium-features #{:metabot-v3}- (let [mock-response (make-mock-text-stream-response ["a" "b"] {"m" {:prompt 1 :completion 1}})- req {:context {} :message {:role :user :content "x"} :history []- :profile-id "p" :conversation-id (str (random-uuid))- :session-id "s" :state {}}]- (testing "on-complete receives collected lines"- (mt/with-dynamic-fn-redefs [http/post (mock-post! mock-response)]- (mt/with-current-user (mt/user->id :crowberto)- (let [result (atom nil)- lines (metabot.client/streaming-request-with-callback- (assoc req :on-complete #(reset! result %)))]- (is (= lines @result))))))- (testing "works without on-complete"- (mt/with-dynamic-fn-redefs [http/post (mock-post! mock-response)]- (mt/with-current-user (mt/user->id :crowberto)- (is (sequential? (metabot.client/streaming-request-with-callback req)))))))))--(deftest streaming-request-error-excludes-headers-test- (testing "When streaming-request gets an error response, the exception should not include headers"- (mt/with-premium-features #{:metabot-v3}- (let [req {:context {:some "context"}- :message {:role :user :content "stuff"}- :history []- :profile-id "test-profile"- :conversation-id (str (random-uuid))- :session-id "test-session"- :state {:some "state"}}]- (mt/with-dynamic-fn-redefs [http/post (fn [_url _opts]- {:status 500- :reason-phrase "Internal Server Error"- :headers {"x-secret-header" "sensitive-value"- "x-request-id" "abc123"}- :body "Error message"})]- (mt/with-current-user (mt/user->id :crowberto)- (let [ex (try- (metabot.client/streaming-request req)- nil- (catch Exception e- e))]- (is (some? ex) "Expected an exception to be thrown")- (when ex- (let [data (ex-data (ex-cause ex))]- (is (not (contains? (:request data) :headers))- "Exception data should not contain :headers in request")- (is (not (contains? (:response data) :headers))- "Exception data should not contain :headers in response"))))))))))--(deftest example-generation-payload-unknown-field-types-test- (let [mp (mt/metadata-provider)- metabot-eid (get-in metabot.config/metabot-config [metabot.config/internal-metabot-id- :entity-id])- original-collection-id (t2/select-one-fn :collection_id :model/Metabot :entity_id metabot-eid)]- ;; Ensure internal metabot is set to the root collection for generating prompts- (t2/update! :model/Metabot :entity_id metabot-eid {:collection_id nil})- (try- (mt/with-temp [:model/Card c {:type :metric- :dataset_query (-> (lib/query mp (lib.metadata/table mp (mt/id :orders)))- (lib/aggregate- (lib/count (lib.metadata/field mp (mt/id :orders :total)))))- ;; Set large view count to ensure metric is picked in `generate-sample-prompts`.- :view_count 1000}]- ;; Add column with type/* to metric result_metadata- (t2/update! :model/Card :id (:id c)- {:result_metadata (conj (:result_metadata (t2/select-one :model/Card :id (:id c)))- {:database_type "point"- :base_type :type/*- :effective_type :type/*- :name "dummy"})})- (testing "No exception is thrown when type/* column is present it result_metadata"- (is (= :not-thrown- (try- ;; Override calls to ai service as we are interested in no exception being thrown- ;; prior to those calls.- (with-redefs [metabot.client/post! (constantly {:status 200- :body {:table_questions []- :metric_questions []}})]- (let [metabot-id (t2/select-one-fn :id :model/Metabot :entity_id metabot-eid)]- (metabot.suggested-prompts/generate-sample-prompts metabot-id)- :not-thrown))- (catch Exception e- e))))))- (finally- (t2/update! :model/Metabot :entity_id metabot-eid {:collection_id original-collection-id})))))diff --git a/test/metabase/metabot/config_test.clj b/test/metabase/metabot/config_test.cljindex a766396b01d..8efc7073a73 100644--- a/test/metabase/metabot/config_test.clj+++ b/test/metabase/metabot/config_test.clj@@ -25,53 +25,44 @@(deftest resolve-dynamic-profile-id-test(testing "profile ID resolution precedence"(mt/with-premium-features #{:metabot-v3}- (mt/with-temporary-setting-values [metabot.settings/ai-service-profile-id nil]- (testing "explicit profile-id takes highest precedence"- (is (= "explicit-profile"- (metabot.config/resolve-dynamic-profile-id "explicit-profile" "any-metabot-id"))))+ (testing "explicit profile-id takes highest precedence"+ (is (= "explicit-profile"+ (metabot.config/resolve-dynamic-profile-id "explicit-profile" "any-metabot-id"))))- (testing "environment variable takes second precedence"- (mt/with-temporary-setting-values [metabot.settings/ai-service-profile-id "env-profile"]- (is (= "env-profile"- (metabot.config/resolve-dynamic-profile-id nil "any-metabot-id")))))+ (testing "metabot-id mapping takes second precedence"+ (is (= "internal"+ (metabot.config/resolve-dynamic-profile-id nil metabot.config/internal-metabot-id)))+ (is (= "embedding_next"+ (metabot.config/resolve-dynamic-profile-id nil metabot.config/embedded-metabot-id))))- (testing "metabot-id mapping takes third precedence"- (is (= "internal"- (metabot.config/resolve-dynamic-profile-id nil metabot.config/internal-metabot-id)))- (is (= "embedding_next"- (metabot.config/resolve-dynamic-profile-id nil metabot.config/embedded-metabot-id))))+ (testing "falls back to default when no matches"+ (is (= "embedding_next"+ (metabot.config/resolve-dynamic-profile-id nil "unknown-metabot-id"))))- (testing "falls back to default when no matches"+ (testing "single arity version uses dynamic metabot resolution"+ (mt/with-temporary-setting-values [metabot.settings/metabot-id metabot.config/embedded-metabot-id](is (= "embedding_next"- (metabot.config/resolve-dynamic-profile-id nil "unknown-metabot-id"))))-- (testing "single arity version uses dynamic metabot resolution"- (mt/with-temporary-setting-values [metabot.settings/metabot-id metabot.config/embedded-metabot-id]- (is (= "embedding_next"- (metabot.config/resolve-dynamic-profile-id nil)))))))))+ (metabot.config/resolve-dynamic-profile-id nil))))))))(deftest integrated-resolution-test(testing "combination of metabot-id and profile-id precedence resolution"(mt/with-premium-features #{:metabot-v3}(testing "explicit params override everything"- (mt/with-temporary-setting-values [metabot.settings/metabot-id nil- metabot.settings/ai-service-profile-id nil]+ (mt/with-temporary-setting-values [metabot.settings/metabot-id nil](let [metabot-id (metabot.config/resolve-dynamic-metabot-id "custom-metabot")profile-id (metabot.config/resolve-dynamic-profile-id "custom-profile" metabot-id)](is (= "custom-metabot" metabot-id))(is (= "custom-profile" profile-id)))))- (testing "environment variables work together"- (mt/with-temporary-setting-values [metabot.settings/metabot-id "env-metabot"- metabot.settings/ai-service-profile-id "env-profile"]+ (testing "env metabot-id resolves profile via metabot-id mapping"+ (mt/with-temporary-setting-values [metabot.settings/metabot-id metabot.config/embedded-metabot-id](let [metabot-id (metabot.config/resolve-dynamic-metabot-id nil)profile-id (metabot.config/resolve-dynamic-profile-id nil metabot-id)]- (is (= "env-metabot" metabot-id))- (is (= "env-profile" profile-id)))))+ (is (= metabot.config/embedded-metabot-id metabot-id))+ (is (= "embedding_next" profile-id)))))(testing "defaults work together"- (mt/with-temporary-setting-values [metabot.settings/metabot-id nil- metabot.settings/ai-service-profile-id nil]+ (mt/with-temporary-setting-values [metabot.settings/metabot-id nil](let [metabot-id (metabot.config/resolve-dynamic-metabot-id nil)profile-id (metabot.config/resolve-dynamic-profile-id nil metabot-id)](is (= metabot.config/internal-metabot-id metabot-id))diff --git a/test/metabase/metabot/native_generation_integration_test.clj b/test/metabase/metabot/native_generation_integration_test.cljindex 36a13302338..d2e33ae4712 100644--- a/test/metabase/metabot/native_generation_integration_test.clj+++ b/test/metabase/metabot/native_generation_integration_test.clj@@ -1,7 +1,5 @@(ns metabase.metabot.native-generation-integration-test- "Integration tests for native example question generation path.-- Tests the full regenerate endpoint flow with `use-native-agent=true`."+ "Integration tests for native example question generation path."(:require[clojure.set :as set][clojure.test :refer :all]@@ -9,7 +7,6 @@[metabase.lib.core :as lib][metabase.lib.metadata :as lib.metadata][metabase.metabot.example-question-generator :as native-generator]- [metabase.metabot.settings :as metabot.settings][metabase.test :as mt][toucan2.core :as t2]))@@ -51,9 +48,8 @@"NativeMetric1" ["native m1" "native m2" "native m3" "native m4" "native m5"]}native-mock (make-native-prompt-generator prompts-by-name)]- (testing "regenerate endpoint works with native path (use-native-agent=true)"- (with-redefs [metabot.settings/use-native-agent (constantly true)- native-generator/generate-example-questions native-mock]+ (testing "regenerate endpoint works with native path"+ (with-redefs [native-generator/generate-example-questions native-mock](mt/user-http-request :crowberto :post 204(format "metabot/metabot/%d/prompt-suggestions/regenerate" metabot-id)))@@ -69,8 +65,7 @@(testing "native path prompts are replaced on re-regenerate"(let [old-ids (t2/select-pks-set :model/MetabotPrompt :metabot_id metabot-id)]- (with-redefs [metabot.settings/use-native-agent (constantly true)- native-generator/generate-example-questions native-mock]+ (with-redefs [native-generator/generate-example-questions native-mock](mt/user-http-request :crowberto :post 204(format "metabot/metabot/%d/prompt-suggestions/regenerate" metabot-id)))(let [new-ids (t2/select-pks-set :model/MetabotPrompt :metabot_id metabot-id)]diff --git a/test/metabase/metabot/table_utils_test.clj b/test/metabase/metabot/table_utils_test.cljindex 2b1b5569681..1c6591c9646 100644--- a/test/metabase/metabot/table_utils_test.clj+++ b/test/metabase/metabot/table_utils_test.clj@@ -1,5 +1,6 @@(ns metabase.metabot.table-utils-test(:require+ [clojure.string :as str][clojure.test :refer :all][metabase.lib.core :as lib][metabase.metabot.query-analyzer :as query-analyzer]@@ -555,3 +556,68 @@;; "order" will match both "order" and "orders" due to fuzzy matching(is (re-find #"\border\b" ddl))(is (re-find #"\borders\b" ddl)))))))))++(deftest ^:parallel schema-sample-h2-ddl-test+ (mt/test-driver :h2+ (let [query (lib/native-query (mt/metadata-provider)+ (str "SELECT * FROM x.orders1"+ " INNER JOIN products ON orders1.product_id = products.id"+ " INNER JOIN ANALYTIC_EVENT ON true"))+ normalize #(into #{} (str/split % #"(?<=;)\n"))]+ (is (= (-> (str "CREATE TABLE PUBLIC.PRODUCTS (\n"+ " ID BIGINT,\n"+ " EAN CHARACTER VARYING,\n"+ " TITLE CHARACTER VARYING,\n"+ " CATEGORY CHARACTER VARYING,\n"+ " VENDOR CHARACTER VARYING,\n"+ " PRICE DOUBLE PRECISION,\n"+ " RATING DOUBLE PRECISION,\n"+ " CREATED_AT TIMESTAMP WITH TIME ZONE\n"+ ");\n"+ "CREATE TABLE PUBLIC.ORDERS (\n"+ " ID BIGINT,\n"+ " USER_ID INTEGER,\n"+ " PRODUCT_ID INTEGER,\n"+ " SUBTOTAL DOUBLE PRECISION,\n"+ " TAX DOUBLE PRECISION,\n"+ " TOTAL DOUBLE PRECISION,\n"+ " DISCOUNT DOUBLE PRECISION,\n"+ " CREATED_AT TIMESTAMP WITH TIME ZONE,\n"+ " QUANTITY INTEGER\n"+ ");\n"+ "CREATE TABLE PUBLIC.USERS (\n"+ " ID BIGINT,\n"+ " NAME CHARACTER VARYING,\n"+ " LAST_LOGIN TIMESTAMP,\n"+ " PASSWORD CHARACTER VARYING\n"+ ");\n")+ normalize)+ (-> (mt/with-current-user (mt/user->id :crowberto)+ (table-utils/schema-sample query {:all-tables-limit 5}))+ normalize))))))++(deftest ^:parallel schema-sample-postgres-ddl-test+ (mt/test-driver :postgres+ (let [query (lib/native-query (mt/metadata-provider) "SELECT * FROM x.orders1")+ normalize #(into #{} (str/split % #"(?<=;)\n"))]+ (is (= (-> (str "CREATE TABLE public.orders (\n"+ " id int4,\n"+ " user_id int4,\n"+ " product_id int4,\n"+ " subtotal float8,\n"+ " tax float8,\n"+ " total float8,\n"+ " discount float8,\n"+ " created_at timestamptz,\n"+ " quantity int4\n"+ ");\n"+ "CREATE TABLE public.users (\n"+ " id int4,\n"+ " name text,\n"+ " last_login timestamp,\n"+ " password text\n"+ ");\n")+ normalize)+ (-> (mt/with-current-user (mt/user->id :crowberto)+ (table-utils/schema-sample query {:all-tables-limit 5}))+ normalize))))))diff --git a/test/metabase/metabot/task/suggested_prompts_generator_test.clj b/test/metabase/metabot/task/suggested_prompts_generator_test.cljindex f8530138e30..770f44a366a 100644--- a/test/metabase/metabot/task/suggested_prompts_generator_test.clj+++ b/test/metabase/metabot/task/suggested_prompts_generator_test.clj@@ -4,10 +4,9 @@[metabase.lib.convert :as lib.convert][metabase.lib.core :as lib][metabase.lib.metadata :as lib.metadata]- [metabase.metabot.client :as metabot.client][metabase.metabot.config :as metabot.config]- [metabase.metabot.task.suggested-prompts-generator- :as metabot.task.suggested-prompts-generator]+ [metabase.metabot.example-question-generator :as metabot.example-question-generator]+ [metabase.metabot.task.suggested-prompts-generator :as metabot.task.suggested-prompts-generator][metabase.test :as mt][toucan2.core :as t2]))@@ -27,7 +26,7 @@{card-id :id}{:type :model:dataset_query query}]- (with-redefs [metabot.client/generate-example-questions+ (with-redefs [metabot.example-question-generator/generate-example-questions(fn [input];; Return fake prompts if we have cards, empty otherwise(if (or (seq (:metrics input)) (seq (:tables input)))diff --git a/test/metabase/metabot/tools/api_test.clj b/test/metabase/metabot/tools/api_test.cljdeleted file mode 100644index 993a593bbb3..00000000000--- a/test/metabase/metabot/tools/api_test.clj+++ /dev/null@@ -1,1253 +0,0 @@-(ns metabase.metabot.tools.api-test- (:require- [clojure.test :refer :all]- [malli.core :as mc]- [malli.transform :as mtx]- [medley.core :as m]- [metabase.lib-be.core :as lib-be]- [metabase.lib.core :as lib]- [metabase.lib.metadata :as lib.metadata]- [metabase.metabot.tools.api :as metabot.tools.api]- [metabase.metabot.tools.create-alert :as metabot.tools.create-alert]- [metabase.metabot.tools.create-dashboard-subscription :as metabot.tools.create-dashboard-subscription]- [metabase.metabot.tools.entity-details :as metabot.tools.entity-details]- [metabase.metabot.tools.filters :as metabot.tools.filters]- [metabase.metabot.tools.test-util :as tools.tu]- [metabase.metabot.tools.util :as metabot.tools.u]- [metabase.metabot.util :as metabot.u]- [metabase.test :as mt]- [metabase.util :as u]- [metabase.util.malli.registry :as mr]- [toucan2.core :as t2]))--(defn- db-engine-name []- (-> (mt/db) :engine name))--(def missing-value (symbol "nil #_\"key is not present.\""))--(deftest column-decode-test- (let [base-col {:field_id "fid", :name "fname"}]- (doseq [{:keys [test-case type-value]} [{:test-case "known type", :type-value :boolean}- {:test-case "unknown type", :type-value nil}]]- (testing test-case- (let [col (assoc base-col :type type-value)- decoded (mc/decode ::metabot.tools.api/column col (mtx/transformer {:name :tool-api-response}))]- (is (mr/validate ::metabot.tools.api/column decoded)))))))--(deftest create-alert-test- (mt/with-premium-features #{:metabot-v3}- (let [tool-requests (atom [])- conversation-id (str (random-uuid))- output (str (random-uuid))]- (with-redefs [metabot.tools.create-alert/create-alert- (fn [arguments]- (swap! tool-requests conj arguments)- {:output output})]- (let [response (mt/user-http-request :rasta :post 200 "metabot/tools/create-alert"- {:arguments {:card_id 42- :send_condition "has_result"- :slack_channel "data-team"- :schedule {:frequency "daily"- :hour 9}}- :conversation_id conversation-id})]- (is (=? [{:card-id 42- :send-condition :has_result- :slack-channel "data-team"- :schedule {:frequency :daily- :hour 9}}]- @tool-requests))- (is (=? {:output output- :conversation_id conversation-id}- response)))))))--(deftest create-dashboard-subscription-test- (mt/with-premium-features #{:metabot-v3}- (let [tool-requests (atom [])- conversation-id (str (random-uuid))- output (str (random-uuid))]- (with-redefs [metabot.tools.create-dashboard-subscription/create-dashboard-subscription- (fn [arguments]- (swap! tool-requests conj arguments)- {:output output})]- (let [response (mt/user-http-request :rasta :post 200 "metabot/tools/create-dashboard-subscription"- {:arguments {:dashboard_id 1- :slack_channel "data-team"- :schedule {:frequency "monthly"- :hour 15- :day_of_month "middle-of-month"}}- :conversation_id conversation-id})]- (is (=? [{:dashboard-id 1- :slack-channel "data-team"- :schedule {:frequency :monthly- :hour 15- :day-of-month :middle-of-month}}]- @tool-requests))- (is (=? {:output output- :conversation_id conversation-id}- response)))))))--(deftest field-values-test- (mt/with-premium-features #{:metabot-v3}- (let [conversation-id (str (random-uuid))- table-id (mt/id :people)- field-id (-> table-id- metabot.tools.u/table-field-id-prefix- (str 4))- response (mt/user-http-request :rasta :post 200 "metabot/tools/field-values"- {:arguments {:entity_type "table"- :entity_id table-id- :field_id field-id ; name- :limit 15}- :conversation_id conversation-id})]- (is (=? {:structured_output {:field_id field-id- :value_metadata- {:statistics- {:distinct_count 2499,- :percent_null 0.0,- :percent_json 0.0,- :percent_url 0.0,- :percent_email 0.0,- :percent_state 0.0,- :average_length 13.532}}}- :conversation_id conversation-id}- response)))))--(deftest filter-records-test- (mt/with-premium-features #{:metabot-v3}- (doseq [data-source [{:query {:database 1}, :query_id "query ID"}- {:query {:database 1}}- {:report_id 1}- {:table_id "1"}]]- (let [tool-requests (atom [])- conversation-id (str (random-uuid))- query-id (str (random-uuid))]- (with-redefs [metabot.tools.filters/filter-records- (fn [arguments]- (swap! tool-requests conj arguments)- {:structured-output {:type :query- :query-id query-id- :query {}- :result-columns []}})]- (let [filters [{:field_id "q2a-1", :operation "is-not-null"}- {:field_id "q2a-2", :operation "equals", :value "3"}- {:field_id "q2a-3", :operation "equals", :values ["3" "4"]}- {:field_id "q2a-5", :operation "not-equals", :values [3 4]}- {:field_id "q2a-6", :operation "month-equals", :values [4 5 9]}- {:field_id "c2a-6", :bucket "week-of-year" :operation "not-equals", :values [14 15 19]}- {:field_id "q2a-6", :operation "year-equals", :value 2008}]- response (mt/user-http-request :rasta :post 200 "metabot/tools/filter-records"- {:arguments {:data_source data-source- :filters filters}- :conversation_id conversation-id})]- (is (=? [{:data-source (metabot.u/recursive-update-keys data-source u/->kebab-case-en)}]- @tool-requests))- (is (=? {:structured_output {:type "query"- :query_id query-id- :query {}- :result_columns []}- :conversation_id conversation-id}- response))))))))--(deftest query-metric-test- (mt/with-premium-features #{:metabot-v3}- (let [tool-requests (atom [])- conversation-id (str (random-uuid))- output (str (random-uuid))]- (with-redefs [metabot.tools.filters/query-metric- (fn [arguments]- (swap! tool-requests conj arguments)- {:structured-output {:type :query- :query-id output- :query {}- :result-columns []}})]- (let [filters [{:field_id "c2-7", :operation "greater-than", :value 50}- {:field_id "c2-3", :operation "equals", :values ["3" "4"]}- {:field_id "c2-5", :operation "not-equals", :values [3 4]}- {:field_id "c2-6", :operation "month-equals", :values [4 5 9]}- {:field_id "c2-6", :bucket "day-of-month" :operation "not-equals", :values [14 15 19]}- {:field_id "c2-6", :bucket "day-of-week" :operation "equals", :values [1 7]}- {:field_id "c2-6", :operation "year-equals", :value 2008}]- breakouts [{:field_id "c2-4", :field_granularity "week"}- {:field_id "c2-6", :field_granularity "day"}]- response (mt/user-http-request :rasta :post 200 "metabot/tools/query-metric"- {:arguments {:metric_id 1- :filters filters- :group_by breakouts}- :conversation_id conversation-id})]- (is (= {:structured_output {:type "query"- :query_id output- :query {}- :result_columns []}- :conversation_id conversation-id}- response)))))))--(deftest query-metric-e2e-test- (mt/with-premium-features #{:metabot-v3}- (let [conversation-id (str (random-uuid))- mp (mt/metadata-provider)- source-query (-> (lib/query mp (lib.metadata/table mp (mt/id :products)))- (lib/aggregate (lib/avg (lib.metadata/field mp (mt/id :products :rating))))- (lib/breakout (lib/with-temporal-bucket- (lib.metadata/field mp (mt/id :products :created_at)) :week)))- metric-data {:name "Metrica"- :description "Metric description"- :dataset_query (lib/->legacy-MBQL source-query)- :type :metric}]- (mt/with-temp [:model/Card {metric-id :id} metric-data]- (let [fid #(format "c%d-%d" metric-id %)- filters [{:field_id (fid 0), :operation "greater-than", :value 50} ; ID- {:field_id (fid 2), :operation "equals", :values ["3" "4"]} ; Title- {:field_id (fid 6), :operation "not-equals", :values [3 4]} ; Rating- {:field_id (fid 7), :operation "month-equals", :values [4 5 9]} ; Created At- {:field_id (fid 7), :bucket "day-of-month" :operation "not-equals", :values [14 15 19]}- {:field_id (fid 7), :bucket "day-of-week" :operation "equals", :values [1 7]}- {:field_id (fid 7), :operation "year-equals", :value 2008}]- breakouts [{:field_id (fid 7), :field_granularity "week"}- {:field_id (fid 7), :field_granularity "day"}]- response (mt/user-http-request :rasta :post 200 "metabot/tools/query-metric"- {:arguments {:metric_id metric-id- :filters filters- :group_by breakouts}- :conversation_id conversation-id})- query-id (-> response :structured_output :query_id)- actual-query (-> response :structured_output :query lib-be/normalize-query)- id-col (lib.metadata/field mp (mt/id :products :id))- title-col (lib.metadata/field mp (mt/id :products :title))- rating-col (lib.metadata/field mp (mt/id :products :rating))- created-at-col (lib.metadata/field mp (mt/id :products :created_at))- expected-query (-> (lib/query mp (lib.metadata/table mp (mt/id :products)))- (lib/aggregate (lib/ensure-uuid [:metric {} metric-id]))- (lib/breakout (lib/with-temporal-bucket created-at-col :week))- (lib/breakout (lib/with-temporal-bucket created-at-col :day))- (lib/filter (lib/> id-col 50))- (lib/filter (lib/= title-col "3" "4"))- (lib/filter (lib/!= rating-col 3 4))- (lib/filter (lib/= (lib/get-month created-at-col) 4 5 9))- (lib/filter (lib/!= (lib/get-day created-at-col) 14 15 19))- (lib/filter (lib/= (lib/get-day-of-week created-at-col :iso) 1 7))- (lib/filter (lib/= (lib/get-year created-at-col) 2008)))]- (is (=? {:structured_output- {:type "query"- :query_id string?- :result_columns- [{:field_id (str "q" query-id "-0")- :name "CREATED_AT"- :display_name "Created At: Week"- :type "datetime"- :database_type string?- :semantic_type "creation_timestamp"}- {:field_id (str "q" query-id "-1")- :name "CREATED_AT_2"- :display_name "Created At: Day"- :type "datetime"- :database_type string?- :semantic_type "creation_timestamp"}- {:field_id (str "q" query-id "-2")- :name "avg"- :display_name "Metrica"- :type "number"- :database_type missing-value- :semantic_type "score"}]}- :conversation_id conversation-id}- response))- (is (tools.tu/query= expected-query actual-query)))))))--(deftest query-model-test- (mt/with-premium-features #{:metabot-v3}- (let [tool-requests (atom [])- conversation-id (str (random-uuid))- output (str (random-uuid))]- (with-redefs [metabot.tools.filters/query-model- (fn [arguments]- (swap! tool-requests conj arguments)- {:structured-output {:type :query- :query-id output- :query {}- :result-columns []}})]- (let [fields [{:field_id "c2-8", :bucket "year-of-era"}- {:field_id "c2-9"}]- filters [{:field_id "c2-7", :operation "greater-than", :value 50}- {:field_id "c2-3", :operation "equals", :values ["3" "4"]}- {:field_id "c2-5", :operation "not-equals", :values [3 4]}- {:field_id "c2-6", :operation "month-equals", :values [4 5 9]}- {:field_id "c2-6", :bucket "day-of-month" :operation "not-equals", :values [14 15 19]}- {:field_id "c2-6", :bucket "day-of-week" :operation "equals", :values [1 7]}- {:field_id "c2-6", :operation "year-equals", :value 2008}]- aggregations [{:field_id "c2-10", :bucket "week", :function "count-distinct"}- {:field_id "c2-11", :function "sum"}]- breakouts [{:field_id "c2-4", :field_granularity "week"}- {:field_id "c2-6", :field_granularity "day"}]- response (mt/user-http-request :rasta :post 200 "metabot/tools/query-model"- {:arguments {:model_id 1- :fields fields- :filters filters- :aggregations aggregations- :group_by breakouts}- :conversation_id conversation-id})]- (is (= {:structured_output {:type "query"- :query_id output- :query {}- :result_columns []}- :conversation_id conversation-id}- response)))))))--(deftest query-model-empty-fields-and-no-summary-test- (mt/with-premium-features #{:metabot-v3}- (let [tool-requests (atom [])- conversation-id (str (random-uuid))- output {:type :query- :query-id "query-id"- :query {:database 1- :type :query- :query {:source-table 1}}- :result-columns []}]- (with-redefs [metabot.tools.filters/query-model- (fn [arguments]- (swap! tool-requests conj arguments)- {:structured-output output})]- (let [fields []- filters [{:field_id "c2-7", :operation "greater-than", :value 50}]- response (mt/user-http-request :rasta :post 200 "metabot/tools/query-model"- {:arguments {:model_id 1- :fields fields- :filters filters}- :conversation_id conversation-id})]- (is (= {:structured_output {:type "query"- :query_id "query-id"- :query {:database 1- :type "query"- :query {:source-table 1}}- :result_columns []}- :conversation_id conversation-id}- response)))))))--(defn- int-sequence?- [coll]- (boolean (and (seqable? coll) (seq coll) (every? int? coll))))--(defn- string-sequence?- [coll]- (boolean (and (seqable? coll) (seq coll) (every? string? coll))))--(deftest answer-sources-test- (mt/with-premium-features #{:metabot-v3}- (let [mp (mt/metadata-provider)- model-source-query (lib/query mp (lib.metadata/table mp (mt/id :products)))- metric-source-query (-> model-source-query- (lib/aggregate (lib/avg (lib.metadata/field mp (mt/id :products :rating))))- (lib/breakout (lib/with-temporal-bucket- (lib.metadata/field mp (mt/id :products :created_at)) :week)))- metric-data {:name "Metrica"- :description "Metric description"- :dataset_query (lib/->legacy-MBQL metric-source-query)- :type :metric}- model-data {:name "Model Model"- :description "Model desc"- :dataset_query (lib/->legacy-MBQL model-source-query)- :type :model}]- (mt/with-temp [:model/Collection {collection-id :id} {:name "Test Metabot Collection"}- :model/Card {metric-id :id} (assoc metric-data :collection_id collection-id)- :model/Card _ignored (assoc metric-data :collection_id collection-id :archived true)- :model/Card _ignored (assoc model-data :collection_id collection-id :archived true)- :model/Card _ignored metric-data- :model/Card _ignored model-data- :model/Card {model-id :id} (assoc model-data :collection_id collection-id)- :model/Metabot {metabot-eid :entity_id} {:name "Test Metabot"- :collection_id collection-id}]- (with-redefs [metabot.tools.entity-details/verified-review? (constantly true)]- (let [model-metric-base-query (lib/query mp (lib.metadata/card mp model-id))- rating-column (m/find-first (comp #{"RATING"} :name) (lib/visible-columns model-metric-base-query))- created-at-column (m/find-first (comp #{"CREATED_AT"} :name) (lib/breakoutable-columns model-metric-base-query))- model-metric-source-query (-> model-metric-base-query- (lib/aggregate (lib/avg rating-column))- (lib/breakout (lib/with-temporal-bucket created-at-column :week)))- model-metric-data {:name "Model metric"- :description "Model metric desc"- :dataset_query (lib/->legacy-MBQL model-metric-source-query)- :type :metric}]- (mt/with-temp [:model/Card {model-metric-id :id} (assoc model-metric-data :collection_id collection-id)]- (testing "Calling with wrong metabot-id"- (let [conversation-id (str (random-uuid))]- (mt/user-http-request :rasta :post 400 "metabot/tools/answer-sources"- {:conversation_id conversation-id})))- (testing "Normal call"- (let [conversation-id (str (random-uuid))- response (mt/user-http-request :rasta :post 200 "metabot/tools/answer-sources"- {:metabot_id metabot-eid- :conversation_id conversation-id})- expected-fields- [{:name "ID", :display_name "ID", :type "number", :semantic_type "pk"}- {:name "EAN", :display_name "Ean", :type "string"}- {:name "TITLE", :display_name "Title", :type "string", :semantic_type "title"}- {:name "CATEGORY", :display_name "Category", :type "string", :semantic_type "category"}- {:name "VENDOR", :display_name "Vendor", :type "string", :semantic_type "company"}- {:name "PRICE", :display_name "Price", :type "number"}- {:name "RATING", :display_name "Rating", :type "number", :semantic_type "score"}- {:name "CREATED_AT", :display_name "Created At", :type "datetime", :semantic_type "creation_timestamp"}]]- (is (=? {:structured_output- {:metrics [(-> metric-data- (select-keys [:name :description])- (assoc :id metric-id- :type "metric"- :verified true- :default_time_dimension_field_id (format "c%d-%d" metric-id 7)- :queryable_dimensions- (map-indexed #(assoc %2 :field_id (format "c%d-%d" metric-id %1))- expected-fields)))- (-> model-metric-data- (select-keys [:name :description])- (assoc :id model-metric-id- :type "metric"- :default_time_dimension_field_id (format "c%d-%d" model-metric-id 7)- :queryable_dimensions- (map-indexed #(assoc %2 :field_id (format "c%d-%d" model-metric-id %1))- expected-fields)))]- :models [(-> model-data- (select-keys [:name :description :database_id])- (assoc :id model-id- :type "model"- :verified true- :database_engine (db-engine-name)- :display_name "Model Model"- :fields (map-indexed #(assoc %2 :field_id (format "c%d-%d" model-id %1))- expected-fields)- :metrics- [{:id model-metric-id- :name "Model metric"- :description "Model metric desc"- :default_time_dimension_field_id (format "c%d-%d" model-metric-id 7)}]))]}- :conversation_id conversation-id}- response))))- (testing "Minimal call"- (let [conversation-id (str (random-uuid))- response (mt/user-http-request :rasta :post 200 "metabot/tools/answer-sources"- {:metabot_id metabot-eid- :arguments {:with_model_fields false- :with_model_metrics false- :with_metric_default_temporal_breakout false- :with_metric_queryable_dimensions false}- :conversation_id conversation-id})]- (is (=? {:structured_output- {:metrics [(-> metric-data- (select-keys [:name :description])- (assoc :id metric-id- :type "metric"- :verified true- :default_time_dimension_field_id nil- :queryable_dimensions missing-value))- (-> model-metric-data- (select-keys [:name :description])- (assoc :id model-metric-id- :type "metric"- :verified true- :default_time_dimension_field_id nil- :queryable_dimensions missing-value))]- :models [(-> model-data- (select-keys [:name :description :database_id])- (assoc :id model-id- :database_engine (db-engine-name)- :display_name "Model Model"- :verified true- :type "model"- :fields []- :metrics (symbol "nil #_\"key is not present.\"")))]}- :conversation_id conversation-id}- response)))))))))))--(deftest ^:parallel get-current-user-test- (mt/with-premium-features #{:metabot-v3}- (mt/with-temp [:model/Glossary _ {:term "asdf" :definition "Sales Team Performance"}]- (let [conversation-id (str (random-uuid))- response (mt/user-http-request :rasta :post 200 "metabot/tools/get-current-user"- {:conversation_id conversation-id})]- (is (=? {:structured_output {:id (mt/user->id :rasta)- :type "user"- :name "Rasta Toucan"- :email_address "[email protected]"- :glossary {(keyword "asdf") "Sales Team Performance"}}- :conversation_id conversation-id}- response))))))--(deftest get-dashboard-details-test- (mt/with-premium-features #{:metabot-v3}- (let [dash-data {:name "dashing dash", :description "dash description"}]- (mt/with-temp [:model/Dashboard {dash-id :id} dash-data]- (with-redefs [metabot.tools.entity-details/verified-review? (constantly true)]- (let [conversation-id (str (random-uuid))- response (mt/user-http-request :rasta :post 200 "metabot/tools/get-dashboard-details"- {:arguments {:dashboard_id dash-id}- :conversation_id conversation-id})]- (is (=? {:structured_output (assoc dash-data :id dash-id, :type "dashboard" :verified true)- :conversation_id conversation-id}- response))))))))--(deftest get-metric-details-test- (mt/with-premium-features #{:metabot-v3}- (let [mp (mt/metadata-provider)- source-query (-> (lib/query mp (lib.metadata/table mp (mt/id :orders)))- (lib/aggregate (lib/avg (lib.metadata/field mp (mt/id :orders :subtotal))))- (lib/breakout (lib/with-temporal-bucket- (lib.metadata/field mp (mt/id :orders :created_at)) :week)))- metric-data {:name "Metrica"- :description "Metric description"- :dataset_query (lib/->legacy-MBQL source-query)- :type :metric}- expected-fields- [{:name "ID" :display_name "ID", :type "number", :semantic_type "pk"}- {:name "USER_ID" :display_name "User ID", :type "number", :semantic_type "fk"}- {:name "PRODUCT_ID" :display_name "Product ID", :type "number", :semantic_type "fk"}- {:name "SUBTOTAL" :display_name "Subtotal", :type "number"}- {:name "TAX" :display_name "Tax", :type "number"}- {:name "TOTAL" :display_name "Total", :type "number"}- {:name "DISCOUNT" :display_name "Discount", :type "number", :semantic_type "discount"}- {:name "CREATED_AT" :display_name "Created At", :type "datetime", :semantic_type "creation_timestamp"}- {:name "QUANTITY" :display_name "Quantity", :type "number", :semantic_type "quantity", :field_values int-sequence?}- {:name "ID" :display_name "ID", :type "number", :semantic_type "pk", :table_reference "User"}- {:name "ADDRESS" :display_name "Address", :type "string", :table_reference "User"}- {:name "EMAIL" :display_name "Email", :type "string", :semantic_type "email", :table_reference "User"}- {:name "PASSWORD" :display_name "Password", :type "string", :table_reference "User"}- {:name "NAME" :display_name "Name", :type "string", :semantic_type "name", :table_reference "User"}- {:name "CITY" :display_name "City", :type "string", :semantic_type "city", :table_reference "User"}- {:name "LONGITUDE" :display_name "Longitude", :type "number", :semantic_type "longitude", :table_reference "User"}- {:name "STATE" :display_name "State", :type "string", :semantic_type "state", :table_reference "User"}- {:name "SOURCE" :display_name "Source", :type "string", :semantic_type "source", :table_reference "User"}- {:name "BIRTH_DATE" :display_name "Birth Date", :type "date", :table_reference "User"}- {:name "ZIP" :display_name "Zip", :type "string", :table_reference "User"}- {:name "LATITUDE" :display_name "Latitude", :type "number", :semantic_type "latitude", :table_reference "User"}- {:name "CREATED_AT" :display_name "Created At", :type "datetime", :semantic_type "creation_timestamp", :table_reference "User"}- {:name "ID" :display_name "ID", :type "number", :semantic_type "pk", :table_reference "Product"}- {:name "EAN" :display_name "Ean", :type "string", :field_values string-sequence?, :table_reference "Product"}- {:name "TITLE" :display_name "Title", :type "string"- :semantic_type "title"- :field_values string-sequence?- :table_reference "Product"}- {:name "CATEGORY" :display_name "Category"- :type "string"- :semantic_type "category"- :field_values string-sequence?- :table_reference "Product"}- {:name "VENDOR" :display_name "Vendor" :type "string"- :semantic_type "company"- :field_values string-sequence?- :table_reference "Product"}- {:name "PRICE" :display_name "Price" :type "number" :table_reference "Product"}- {:name "RATING" :display_name "Rating" :type "number" :semantic_type "score" :table_reference "Product"}- {:name "CREATED_AT" :display_name "Created At" :type "datetime" :semantic_type "creation_timestamp" :table_reference "Product"}]- conversation-id (str (random-uuid))- request (fn [arguments]- (mt/user-http-request :rasta :post 200 "metabot/tools/get-metric-details"- {:arguments arguments- :conversation_id conversation-id}))]- (mt/with-temp [:model/Card {metric-id :id} metric-data]- (with-redefs [metabot.tools.entity-details/verified-review? (constantly true)]- (testing "Normal call"- (is (=? {:structured_output (-> metric-data- (select-keys [:name :display_name :description])- (assoc :id metric-id- :type "metric"- :verified true- :default_time_dimension_field_id (format "c%d-%d" metric-id 7)- :queryable_dimensions- (map-indexed #(assoc %2 :field_id (format "c%d-%d" metric-id %1))- expected-fields)))- :conversation_id conversation-id}- (request {:metric_id metric-id}))))- (testing "Without field values"- (is (=? {:structured_output (-> metric-data- (select-keys [:name :display_name :description])- (assoc :id metric-id- :type "metric"- :verified true- :default_time_dimension_field_id (format "c%d-%d" metric-id 7)- :queryable_dimensions- (map-indexed #(assoc %2- :field_id (format "c%d-%d" metric-id %1)- :field_values missing-value)- expected-fields)))- :conversation_id conversation-id}- (request {:metric_id metric-id- :with_field_values false}))))- (testing "Default time dimension only"- (is (=? {:structured_output (-> metric-data- (select-keys [:name :display_name :description])- (assoc :id metric-id- :type "metric"- :verified true- :default_time_dimension_field_id (format "c%d-%d" metric-id 7)- :queryable_dimensions missing-value))- :conversation_id conversation-id}- (request {:metric_id metric-id- :with_queryable_dimensions false}))))- (testing "Minimal call"- (is (=? {:structured_output (-> metric-data- (select-keys [:name :display_name :description])- (assoc :id metric-id- :type "metric"- :verified true- :default_time_dimension_field_id nil- :queryable_dimensions missing-value))- :conversation_id conversation-id}- (request {:metric_id metric-id- :with_default_temporal_breakout false- :with_queryable_dimensions false})))))))))--(deftest ^:parallel get-query-details-test- (mt/with-premium-features #{:metabot-v3}- (let [mp (mt/metadata-provider)- source-query (-> (lib/query mp (lib.metadata/table mp (mt/id :products)))- (lib/aggregate (lib/avg (lib.metadata/field mp (mt/id :products :rating))))- (lib/breakout (lib/with-temporal-bucket- (lib.metadata/field mp (mt/id :products :created_at)) :week)))- query (lib/->legacy-MBQL source-query)- conversation-id (str (random-uuid))- response (mt/user-http-request :rasta :post 200 "metabot/tools/get-query-details"- {:arguments {:query query}- :conversation_id conversation-id})- generated-id (-> response :structured_output :query_id)]- (is (=? {:structured_output {:type "query"- :query_id string?- :query map?- :result_columns- [{:field_id (str "q" generated-id "-0"),- :name "CREATED_AT",- :display_name "Created At: Week",- :type "datetime"- :database_type string?}- {:field_id (str "q" generated-id "-1"),- :name "avg",- :display_name "Average of Rating",- :type "number"- :database_type missing-value}]}- :conversation_id conversation-id}- response))- ;; Verify the query is normalized (supports both MBQL v4 and v5)- (is (= (mt/id) (get-in response [:structured_output :query :database]))))))--(deftest get-report-details-test- (mt/with-premium-features #{:metabot-v3}- (let [mp (mt/metadata-provider)- source-query (-> (lib/query mp (lib.metadata/table mp (mt/id :products)))- (lib/aggregate (lib/avg (lib.metadata/field mp (mt/id :products :rating))))- (lib/breakout (lib.metadata/field mp (mt/id :products :vendor)))- (lib/breakout (lib/with-temporal-bucket- (lib.metadata/field mp (mt/id :products :created_at)) :week)))- question-data {:name "Question?"- :description "Descriptive?"- :display :bar- :dataset_query (lib/->legacy-MBQL source-query)- :type :question}]- (mt/with-temp [:model/Card {question-id :id} question-data]- (with-redefs [metabot.tools.entity-details/verified-review? (constantly true)]- (let [conversation-id (str (random-uuid))- arguments {:report_id question-id}- request (fn [arguments]- (mt/user-http-request :rasta :post 200 "metabot/tools/get-report-details"- {:arguments arguments- :conversation_id conversation-id}))- expected-fields [{:name "VENDOR"- :display_name "Vendor"- :type "string"- :semantic_type "company"- :database_type string?- :field_values string-sequence?}- {:name "CREATED_AT"- :display_name "Created At: Week"- :type "datetime"- :semantic_type "creation_timestamp"- :database_type string?}- {:name "avg"- :display_name "Average of Rating"- :type "number"- :semantic_type "score"- :database_type missing-value}]]- (testing "Normal call"- (is (=? {:structured_output (-> question-data- (select-keys [:name :description :database_id])- (assoc :id question-id- :type "question"- :display "bar"- :verified true- :result_columns- (map-indexed #(assoc %2 :field_id (format "c%d-%d" question-id %1))- expected-fields)))- :conversation_id conversation-id}- (request arguments))))- (testing "Without field values"- (is (=? {:structured_output (-> question-data- (select-keys [:name :description])- (assoc :id question-id- :type "question"- :result_columns- (map-indexed #(assoc %2- :field_id (format "c%d-%d" question-id %1)- :field_values missing-value)- expected-fields)))- :conversation_id conversation-id}- (request (assoc arguments :with_field_values false)))))- (testing "Without fields"- (is (=? {:structured_output (-> question-data- (select-keys [:name :description])- (assoc :id question-id- :type "question"- :verified true- :result_columns []))- :conversation_id conversation-id}- (request (assoc arguments :with_fields false)))))))))))--;; Helper function to set up model test fixtures-(defn- model-test-fixtures []- (let [mp (lib-be/application-database-metadata-provider (mt/id))- source-query (lib/query mp (lib.metadata/table mp (mt/id :orders)))- model-data {:name "Model Model"- :description "Model desc"- :dataset_query (lib/->legacy-MBQL source-query)- :type :model- :database_id (mt/id)}- metric-data {:name "Metric"- :description "Model based metric"- :type :metric}- ;; Core fields returned by the model (lib/returned-columns)- expected-core-fields- [{:name "ID", :display_name "ID", :type "number", :semantic_type "pk"}- {:name "USER_ID", :display_name "User ID", :type "number", :semantic_type "fk"}- {:name "PRODUCT_ID", :display_name "Product ID", :type "number", :semantic_type "fk"}- {:name "SUBTOTAL", :display_name "Subtotal", :type "number"}- {:name "TAX", :display_name "Tax", :type "number"}- {:name "TOTAL", :display_name "Total", :type "number"}- {:name "DISCOUNT", :display_name "Discount", :type "number", :semantic_type "discount"}- {:name "CREATED_AT", :display_name "Created At", :type "datetime", :semantic_type "creation_timestamp"}- {:name "QUANTITY", :display_name "Quantity", :type "number", :semantic_type "quantity", :field_values int-sequence?}]- ;; Related tables via FK (order matches what related-tables function returns)- expected-related-tables- [{:type "table"- :id (mt/id :people)- :name "PEOPLE"- :display_name "People"- :database_id (mt/id)- :database_schema "PUBLIC"- :related_by "USER_ID"- :fields- [{:name "ID", :display_name "ID", :type "number", :semantic_type "pk"}- {:name "ADDRESS", :display_name "Address", :type "string"}- {:name "EMAIL", :display_name "Email", :type "string", :semantic_type "email"}- {:name "PASSWORD", :display_name "Password", :type "string"}- {:name "NAME", :display_name "Name", :type "string", :semantic_type "name"}- {:name "CITY", :display_name "City", :type "string", :semantic_type "city"}- {:name "LONGITUDE", :display_name "Longitude", :type "number", :semantic_type "longitude"}- {:name "STATE", :display_name "State", :type "string", :semantic_type "state"}- {:name "SOURCE", :display_name "Source", :type "string", :semantic_type "source"}- {:name "BIRTH_DATE", :display_name "Birth Date", :type "date"}- {:name "ZIP", :display_name "Zip", :type "string"}- {:name "LATITUDE", :display_name "Latitude", :type "number", :semantic_type "latitude"}- {:name "CREATED_AT", :display_name "Created At", :type "datetime", :semantic_type "creation_timestamp"}]}- {:type "table"- :id (mt/id :products)- :name "PRODUCTS"- :display_name "Products"- :database_id (mt/id)- :database_schema "PUBLIC"- :related_by "PRODUCT_ID"- :fields- [{:name "ID", :display_name "ID", :type "number", :semantic_type "pk"}- {:name "EAN", :display_name "Ean", :type "string", :field_values string-sequence?}- {:name "TITLE", :display_name "Title", :type "string", :semantic_type "title", :field_values string-sequence?}- {:name "CATEGORY", :display_name "Category", :type "string", :semantic_type "category", :field_values string-sequence?}- {:name "VENDOR", :display_name "Vendor", :type "string", :semantic_type "company", :field_values string-sequence?}- {:name "PRICE", :display_name "Price", :type "number"}- {:name "RATING", :display_name "Rating", :type "number", :semantic_type "score"}- {:name "CREATED_AT", :display_name "Created At", :type "datetime", :semantic_type "creation_timestamp"}]}]]- {:model-data model-data- :metric-data metric-data- :expected-core-fields expected-core-fields- :expected-related-tables expected-related-tables}))--(defn- add-field-ids- "Add field_id to fields using map-indexed. Optionally apply transform-fn to each field."- ([prefix-template fields]- (add-field-ids prefix-template fields identity))- ([prefix-template fields transform-fn]- (map-indexed #(transform-fn (assoc %2 :field_id (format prefix-template %1))) fields)))--(deftest get-model-details-basic-test- (mt/with-premium-features #{:metabot-v3}- (let [{:keys [model-data metric-data expected-core-fields expected-related-tables]} (model-test-fixtures)- conversation-id (str (random-uuid))]- (mt/with-temp [:model/Card {model-id :id} model-data- :model/Card {metric-id :id} (assoc metric-data :dataset_query- (mt/mbql-query orders- {:source-table (str "card__" model-id)- :aggregation [[:count]]- :breakout [!month.*created_at *quantity]}))]- (with-redefs [metabot.tools.entity-details/verified-review? (constantly true)]- (let [request (fn [arguments]- (mt/user-http-request :rasta :post 200 "metabot/tools/get-table-details"- {:arguments arguments- :conversation_id conversation-id}))]- (doseq [arguments [{:model_id model-id}- {:table_id (str "card__" model-id)}]]- (testing "Normal request"- (is (=? {:structured_output (-> model-data- (select-keys [:name :description :database_id])- (assoc :id model-id- :type "model"- :database_engine (db-engine-name)- :display_name "Model Model"- :verified true- :fields (add-field-ids (format "c%d-%%d" model-id) expected-core-fields)- :related_tables- [(-> (first expected-related-tables)- (update :fields (fn [fields]- (map-indexed #(assoc %2 :field_id (format "c%d-%d" model-id (+ 9 %1)))- fields))))- (-> (second expected-related-tables)- (update :fields (fn [fields]- (map-indexed #(assoc %2 :field_id (format "c%d-%d" model-id (+ 22 %1)))- fields))))]- :metrics [(assoc metric-data- :id metric-id- :type "metric"- :default_time_dimension_field_id (format "c%d-7" metric-id))]))- :conversation_id conversation-id}- (request arguments)))))))))))--(deftest get-model-details-without-field-values-test- (mt/with-premium-features #{:metabot-v3}- (let [{:keys [model-data metric-data expected-core-fields expected-related-tables]} (model-test-fixtures)- conversation-id (str (random-uuid))]- (mt/with-temp [:model/Card {model-id :id} model-data- :model/Card {metric-id :id} (assoc metric-data :dataset_query- (mt/mbql-query orders- {:source-table (str "card__" model-id)- :aggregation [[:count]]- :breakout [!month.*created_at *quantity]}))]- (with-redefs [metabot.tools.entity-details/verified-review? (constantly true)]- (let [request (fn [arguments]- (mt/user-http-request :rasta :post 200 "metabot/tools/get-table-details"- {:arguments arguments- :conversation_id conversation-id}))- arguments {:model_id model-id}]- (testing "Without field values"- (is (=? {:structured_output (-> model-data- (select-keys [:name :description :database_id])- (assoc :id model-id- :type "model"- :database_engine (db-engine-name)- :display_name "Model Model"- :verified true- :fields- (add-field-ids (format "c%d-%%d" model-id) expected-core-fields- #(assoc % :field_values missing-value))- :related_tables- [(-> (first expected-related-tables)- (update :fields (fn [fields]- (map-indexed #(assoc %2- :field_id (format "c%d-%d" model-id (+ 9 %1))- :field_values missing-value)- fields))))- (-> (second expected-related-tables)- (update :fields (fn [fields]- (map-indexed #(assoc %2- :field_id (format "c%d-%d" model-id (+ 22 %1))- :field_values missing-value)- fields))))]- :metrics [(assoc metric-data- :id metric-id- :type "metric"- :default_time_dimension_field_id (format "c%d-7" metric-id))]))- :conversation_id conversation-id}- (request (assoc arguments :with_field_values false)))))))))))--(deftest get-model-details-without-fields-test- (mt/with-premium-features #{:metabot-v3}- (let [{:keys [model-data metric-data expected-related-tables]} (model-test-fixtures)- conversation-id (str (random-uuid))]- (mt/with-temp [:model/Card {model-id :id} model-data- :model/Card {metric-id :id} (assoc metric-data :dataset_query- (mt/mbql-query orders- {:source-table (str "card__" model-id)- :aggregation [[:count]]- :breakout [!month.*created_at *quantity]}))]- (with-redefs [metabot.tools.entity-details/verified-review? (constantly true)]- (let [request (fn [arguments]- (mt/user-http-request :rasta :post 200 "metabot/tools/get-table-details"- {:arguments arguments- :conversation_id conversation-id}))- arguments {:model_id model-id}]- (testing "Without fields"- (is (=? {:structured_output (-> model-data- (select-keys [:name :description :database_id])- (assoc :id model-id- :type "model"- :database_engine (db-engine-name)- :display_name "Model Model"- :verified true- :fields []- :related_tables- (map #(assoc % :fields []) expected-related-tables)- :metrics [(assoc metric-data- :id metric-id- :type "metric"- :default_time_dimension_field_id (format "c%d-7" metric-id))]))- :conversation_id conversation-id}- (request (assoc arguments :with_fields false)))))))))))--(deftest get-model-details-without-metric-temporal-breakout-test- (mt/with-premium-features #{:metabot-v3}- (let [{:keys [model-data metric-data expected-related-tables]} (model-test-fixtures)- conversation-id (str (random-uuid))]- (mt/with-temp [:model/Card {model-id :id} model-data- :model/Card {metric-id :id} (assoc metric-data :dataset_query- (mt/mbql-query orders- {:source-table (str "card__" model-id)- :aggregation [[:count]]- :breakout [!month.*created_at *quantity]}))]- (with-redefs [metabot.tools.entity-details/verified-review? (constantly true)]- (let [request (fn [arguments]- (mt/user-http-request :rasta :post 200 "metabot/tools/get-table-details"- {:arguments arguments- :conversation_id conversation-id}))- arguments {:model_id model-id}]- (testing "Without fields and metric default time dimension"- (is (=? {:structured_output (-> model-data- (select-keys [:name :description :database_id])- (assoc :id model-id- :type "model"- :database_engine (db-engine-name)- :display_name "Model Model"- :verified true- :fields []- :related_tables- (map #(assoc % :fields []) expected-related-tables)- :metrics [(assoc metric-data- :id metric-id- :type "metric"- :default_time_dimension_field_id nil)]))- :conversation_id conversation-id}- (request (assoc arguments- :with_fields false- :with_metric_default_temporal_breakout false)))))))))))--(deftest get-model-details-without-metrics-test- (mt/with-premium-features #{:metabot-v3}- (let [{:keys [model-data expected-related-tables]} (model-test-fixtures)- conversation-id (str (random-uuid))]- (mt/with-temp [:model/Card {model-id :id} model-data- :model/Card {_metric-id :id} (assoc (:metric-data (model-test-fixtures)) :dataset_query- (mt/mbql-query orders- {:source-table (str "card__" model-id)- :aggregation [[:count]]- :breakout [!month.*created_at *quantity]}))]- (with-redefs [metabot.tools.entity-details/verified-review? (constantly true)]- (let [request (fn [arguments]- (mt/user-http-request :rasta :post 200 "metabot/tools/get-table-details"- {:arguments arguments- :conversation_id conversation-id}))- arguments {:model_id model-id}]- (testing "Without fields and metrics"- (is (=? {:structured_output (-> model-data- (select-keys [:name :description :database_id])- (assoc :id model-id- :type "model"- :database_engine (db-engine-name)- :display_name "Model Model"- :verified true- :fields []- :related_tables- (map #(assoc % :fields []) expected-related-tables)- :metrics missing-value))- :conversation_id conversation-id}- (request (assoc arguments- :with_fields false- :with_metrics false)))))))))))--(deftest get-model-details-without-related-tables-test- (mt/with-premium-features #{:metabot-v3}- (let [{:keys [model-data]} (model-test-fixtures)- conversation-id (str (random-uuid))]- (mt/with-temp [:model/Card {model-id :id} model-data- :model/Card {_metric-id :id} (assoc (:metric-data (model-test-fixtures)) :dataset_query- (mt/mbql-query orders- {:source-table (str "card__" model-id)- :aggregation [[:count]]- :breakout [!month.*created_at *quantity]}))]- (with-redefs [metabot.tools.entity-details/verified-review? (constantly true)]- (let [request (fn [arguments]- (mt/user-http-request :rasta :post 200 "metabot/tools/get-table-details"- {:arguments arguments- :conversation_id conversation-id}))]- (testing "Without related tables"- (is (=? {:structured_output (-> model-data- (select-keys [:name :description :database_id])- (assoc :id model-id- :type "model"- :database_engine (db-engine-name)- :display_name "Model Model"- :verified true- :fields []- :related_tables missing-value- :metrics missing-value))- :conversation_id conversation-id}- (request {:model_id model-id- :with_fields false- :with_related_tables false- :with_metrics false}))))))))))--(deftest field-values-auto-populate-test- (mt/with-premium-features #{:metabot-v3}- (t2/delete! :model/FieldValues :field_id [:in (t2/select-fn-vec :id :model/Field :table_id (mt/id :orders))])- (let [table-id (mt/id :orders)- conversation-id (str (random-uuid))- response (mt/user-http-request :rasta :post 200 "metabot/tools/field-values"- {:arguments- {:entity_type "table"- :entity_id table-id- :field_id (-> table-id- metabot.tools.u/table-field-id-prefix- (str 8)) ; quantity- :limit 15}- :conversation_id conversation-id})]- (is (=? {:structured_output {:value_metadata {:field_values int-sequence?}}- :conversation_id conversation-id}- response)))))--(deftest get-table-details-test- (mt/with-premium-features #{:metabot-v3}- (let [table-id (mt/id :orders)- metric-data {:name "Metric"- :description "Model based metric"- :type :metric}- conversation-id (str (random-uuid))- expected-fields- [{:name "ID", :display_name "ID", :type "number", :semantic_type "pk"}- {:name "USER_ID", :display_name "User ID", :type "number", :semantic_type "fk"}- {:name "PRODUCT_ID", :display_name "Product ID", :type "number", :semantic_type "fk"}- {:name "SUBTOTAL", :display_name "Subtotal", :type "number"}- {:name "TAX", :display_name "Tax", :type "number"}- {:name "TOTAL", :display_name "Total", :type "number"}- {:name "DISCOUNT", :display_name "Discount", :type "number", :semantic_type "discount"}- {:name "CREATED_AT", :display_name "Created At", :type "datetime", :semantic_type "creation_timestamp"}- {:name "QUANTITY", :display_name "Quantity", :type "number", :semantic_type "quantity", :field_values int-sequence?}]- request (fn [arguments]- (mt/user-http-request :rasta :post 200 "metabot/tools/get-table-details"- {:arguments arguments- :conversation_id conversation-id}))]- (mt/with-temp [:model/Card {metric-id :id} (assoc metric-data :dataset_query- (mt/mbql-query orders- {:source-table table-id- :aggregation [[:count]]- :breakout [!month.created_at $quantity]}))]- (testing "Normal call"- (doseq [arg-id [table-id (str table-id)]]- (is (=? {:structured_output {:name "ORDERS"- :display_name "Orders"- :database_id (mt/id)- :database_engine (db-engine-name)- :database_schema "PUBLIC"- :id table-id- :type "table"- :fields (map-indexed #(assoc %2 :field_id (format "t%d-%d" table-id %1))- expected-fields)- :metrics [(assoc metric-data- :id metric-id- :type "metric"- :default_time_dimension_field_id (format "c%d-7" metric-id))]}- :conversation_id conversation-id}- (request {:table_id arg-id})))))- (let [arguments {:table_id table-id}]- (testing "Without field values"- (is (=? {:structured_output {:name "ORDERS"- :display_name "Orders"- :database_id (mt/id)- :database_engine (db-engine-name)- :database_schema "PUBLIC"- :id table-id- :type "table"- :fields (map-indexed #(assoc %2- :field_id (format "t%d-%d" table-id %1)- :field_values missing-value)- expected-fields)- :metrics [(assoc metric-data- :id metric-id- :type "metric"- :default_time_dimension_field_id (format "c%d-7" metric-id))]}- :conversation_id conversation-id}- (request (assoc arguments :with_field_values false)))))- (testing "Without fields"- (is (=? {:structured_output {:name "ORDERS"- :display_name "Orders"- :database_id (mt/id)- :database_engine (db-engine-name)- :database_schema "PUBLIC"- :id table-id- :type "table"- :fields []- :metrics [(assoc metric-data- :id metric-id- :type "metric"- :default_time_dimension_field_id (format "c%d-7" metric-id))]}- :conversation_id conversation-id}- (request (assoc arguments :with_fields false)))))- (testing "Without fields and metric default time dimension"- (is (=? {:structured_output {:name "ORDERS"- :display_name "Orders"- :database_id (mt/id)- :database_engine (db-engine-name)- :database_schema "PUBLIC"- :id table-id- :type "table"- :fields []- :metrics [(assoc metric-data- :id metric-id- :type "metric"- :default_time_dimension_field_id nil)]}- :conversation_id conversation-id}- (request (assoc arguments- :with_fields false- :with_metric_default_temporal_breakout false)))))- (testing "Without fields and metrics"- (is (=? {:structured_output {:name "ORDERS"- :display_name "Orders"- :database_id (mt/id)- :database_engine (db-engine-name)- :database_schema "PUBLIC"- :id table-id- :type "table"- :fields []- :metrics missing-value}- :conversation_id conversation-id}- (request (assoc arguments- :with_fields false- :with_metrics false))))))))))--(deftest get-table-details-database-type-test- ;; get-table-details-test validates other metadata, this test focuses on :database_type.- (mt/with-premium-features #{:metabot-v3}- (let [table-id (mt/id :orders)- conversation-id (str (random-uuid))- expected-fields-with-h2-db-types- [{:name "ID", :type "number", :database_type "bigint"}- {:name "USER_ID", :type "number", :database_type "integer"}- {:name "PRODUCT_ID", :type "number", :database_type "integer"}- {:name "SUBTOTAL", :type "number", :database_type "double_precision"}- {:name "TAX", :type "number", :database_type "double_precision"}- {:name "TOTAL", :type "number", :database_type "double_precision"}- {:name "DISCOUNT", :type "number", :database_type "double_precision"}- {:name "CREATED_AT", :type "datetime", :database_type "timestamp_with_time_zone"}- {:name "QUANTITY", :type "number", :database_type "integer"}]- request (fn [arguments]- (mt/user-http-request :rasta :post 200 "metabot/tools/get-table-details"- {:arguments arguments- :conversation_id conversation-id}))- expected-fields (cond->> expected-fields-with-h2-db-types- ;; For non-h2 dbs, just verify we get some string?. We're sanity checking the result, not- ;; exhaustively testing :database_type column metadata.- (not= "h2" (db-engine-name)) (mapv #(assoc % :database_type string?)))]- (is (=? {:structured_output {:name "ORDERS"- :display_name "Orders"- :database_id (mt/id)- :database_engine (db-engine-name)- :database_schema "PUBLIC"- :id table-id- :type "table"- :fields (map-indexed #(assoc %2 :field_id (format "t%d-%d" table-id %1))- expected-fields)}- :conversation_id conversation-id}- (request {:table_id table-id}))))))--(deftest get-table-details-related-tables-test- (mt/with-premium-features #{:metabot-v3}- (let [conversation-id (str (random-uuid))- request (fn [arguments]- (mt/user-http-request :rasta :post 200 "metabot/tools/get-table-details"- {:arguments arguments- :conversation_id conversation-id}))]- (testing "Normal call includes related_tables by default"- (let [response (request {:table_id (mt/id :orders)})- related-tables (get-in response [:structured_output :related_tables])]- (is (= (sort [(mt/id :products) (mt/id :people)])- (sort (map :id related-tables)))- "Should include tables related to Orders by foreign keys")- (is (every? #(not (contains? % :related_tables)) related-tables)- "Related tables should not have nested related_tables")))- (testing "Without related tables"- (is (nil? (-> (request {:table_id (mt/id :orders)- :with_related_tables false})- (get-in [:structured_output :related_tables]))))))))--(deftest get-table-details-related-by-test- (mt/with-premium-features #{:metabot-v3}- (testing "Related tables include related_by field indicating the FK field name"- (let [conversation-id (str (random-uuid))- response (mt/user-http-request :rasta :post 200 "metabot/tools/get-table-details"- {:arguments {:table_id (mt/id :orders)}- :conversation_id conversation-id})- related-tables (get-in response [:structured_output :related_tables])- people-table (first (filter #(= (:id %) (mt/id :people)) related-tables))- products-table (first (filter #(= (:id %) (mt/id :products)) related-tables))]- (testing "People table is related by USER_ID FK"- (is (= "USER_ID" (:related_by people-table))))- (testing "Products table is related by PRODUCT_ID FK"- (is (= "PRODUCT_ID" (:related_by products-table))))))))--(deftest ^:sequential get-snippets-test- (mt/with-premium-features #{:metabot-v3}- (let [conversation-id (str (random-uuid))]- (mt/with-temp [:model/NativeQuerySnippet snippet-1 {:content "1"- :name "snippet_1"- :description "great snippet 1"}- :model/NativeQuerySnippet snippet-2 {:content "2"- :name "snippet_2"}]- (testing "No snippets visible without data perms"- (is (=? {:structured_output []- :conversation_id conversation-id}- (-> (mt/with-no-data-perms-for-all-users!- (mt/user-http-request :rasta :post 200 "metabot/tools/get-snippets"- {:conversation_id conversation-id}))- (update :structured_output (fn [output]- (filter #(#{(:id snippet-1) (:id snippet-2)} (:id %))- output)))))))- (testing "All snippets visible with full data perms"- (is (=? {:structured_output [(select-keys snippet-1 [:id :name :description])- (select-keys snippet-2 [:id :name :description])]- :conversation_id conversation-id}- (-> (mt/with-full-data-perms-for-all-users!- (mt/user-http-request :rasta :post 200 "metabot/tools/get-snippets"- {:conversation_id conversation-id}))- (update :structured_output (fn [output]- (filter #(#{(:id snippet-1) (:id snippet-2)} (:id %))- output)))))))))))--(deftest ^:sequential get-snippet-details-test- (mt/with-premium-features #{:metabot-v3}- (let [conversation-id (str (random-uuid))]- (mt/with-temp [:model/NativeQuerySnippet snippet-1 {:content "1"- :name "snippet_1"- :description "great snippet 1"}- :model/NativeQuerySnippet _ {:content "2"- :name "snippet_2"}]- (testing "400 for invalid args"- (is (=? {:errors- {:arguments {:snippet_id string?}},- :specific-errors {:arguments {:snippet_id ["should be an integer, received: nil"]}}}- (mt/user-http-request :rasta :post 400 "metabot/tools/get-snippet-details"- {:arguments {:snippet_id nil}- :conversation_id conversation-id}))))- (testing "404 returned for non-existent snippet"- (is (= "Not found."- (let [max-snippet-id (t2/select-one-fn :max-id [:model/NativeQuerySnippet [:%max.id :max-id]])]- (mt/user-http-request :rasta :post 404 "metabot/tools/get-snippet-details"- {:arguments {:snippet_id (inc max-snippet-id)}- :conversation_id conversation-id})))))- (testing "403 returned for missing data perms"- (is (= "You don't have permissions to do that."- (mt/with-no-data-perms-for-all-users!- (mt/user-http-request :rasta :post 403 "metabot/tools/get-snippet-details"- {:arguments {:snippet_id (:id snippet-1)}- :conversation_id conversation-id})))))- (testing "Snippet details returned with sufficient data perms"- (is (=? {:structured_output (select-keys snippet-1 [:id :name :description :content])- :conversation_id conversation-id}- (mt/with-full-data-perms-for-all-users!- (mt/user-http-request :rasta :post 200 "metabot/tools/get-snippet-details"- {:arguments {:snippet_id (:id snippet-1)}- :conversation_id conversation-id})))))))))diff --git a/test/metabase/metabot/tools/create_autogenerated_dashboard_test.clj b/test/metabase/metabot/tools/autogen_dashboard_test.cljsimilarity index 97%rename from test/metabase/metabot/tools/create_autogenerated_dashboard_test.cljrename to test/metabase/metabot/tools/autogen_dashboard_test.cljindex ed160ca74c5..4d345660217 100644--- a/test/metabase/metabot/tools/create_autogenerated_dashboard_test.clj+++ b/test/metabase/metabot/tools/autogen_dashboard_test.clj@@ -1,8 +1,8 @@-(ns metabase.metabot.tools.create-autogenerated-dashboard-test+(ns metabase.metabot.tools.autogen-dashboard-test(:require[clojure.string :as str][clojure.test :refer :all]- [metabase.metabot.tools.create-autogenerated-dashboard :as autogen-dashboard]+ [metabase.metabot.tools.autogen-dashboard :as autogen-dashboard][metabase.test :as mt]));;; Source Resolution Tests (without database)diff --git a/test/metabase/metabot/tools/create_chart_test.clj b/test/metabase/metabot/tools/charts/create_test.cljsimilarity index 95%rename from test/metabase/metabot/tools/create_chart_test.cljrename to test/metabase/metabot/tools/charts/create_test.cljindex 16d863eafe9..076d1f286a5 100644--- a/test/metabase/metabot/tools/create_chart_test.clj+++ b/test/metabase/metabot/tools/charts/create_test.clj@@ -1,8 +1,8 @@-(ns metabase.metabot.tools.create-chart-test+(ns metabase.metabot.tools.charts.create-test(:require[clojure.string :as str][clojure.test :refer :all]- [metabase.metabot.tools.create-chart :as create-chart]))+ [metabase.metabot.tools.charts.create :as create-chart]))(deftest create-chart-test(testing "creates a chart from a query"diff --git a/test/metabase/metabot/tools/edit_chart_test.clj b/test/metabase/metabot/tools/charts/edit_test.cljsimilarity index 96%rename from test/metabase/metabot/tools/edit_chart_test.cljrename to test/metabase/metabot/tools/charts/edit_test.cljindex ff41887e580..8d419f63e7c 100644--- a/test/metabase/metabot/tools/edit_chart_test.clj+++ b/test/metabase/metabot/tools/charts/edit_test.clj@@ -1,8 +1,8 @@-(ns metabase.metabot.tools.edit-chart-test+(ns metabase.metabot.tools.charts.edit-test(:require[clojure.string :as str][clojure.test :refer :all]- [metabase.metabot.tools.edit-chart :as edit-chart]))+ [metabase.metabot.tools.charts.edit :as edit-chart]))(deftest edit-chart-test(testing "edits a chart's visualization type"diff --git a/test/metabase/metabot/tools/ask_clarification_test.clj b/test/metabase/metabot/tools/clarification_test.cljsimilarity index 93%rename from test/metabase/metabot/tools/ask_clarification_test.cljrename to test/metabase/metabot/tools/clarification_test.cljindex 90d2453313f..def2f5cdb0b 100644--- a/test/metabase/metabot/tools/ask_clarification_test.clj+++ b/test/metabase/metabot/tools/clarification_test.clj@@ -1,8 +1,8 @@-(ns metabase.metabot.tools.ask-clarification-test+(ns metabase.metabot.tools.clarification-test(:require[clojure.string :as str][clojure.test :refer :all]- [metabase.metabot.tools.ask-clarification :as ask-clarification]))+ [metabase.metabot.tools.clarification :as ask-clarification]))(deftest ask-for-sql-clarification-test(testing "returns final-response? flag"diff --git a/test/metabase/metabot/agent/tools/document_test.clj b/test/metabase/metabot/tools/document_test.cljsimilarity index 55%rename from test/metabase/metabot/agent/tools/document_test.cljrename to test/metabase/metabot/tools/document_test.cljindex 88afaa2c0b2..4eac3eb6521 100644--- a/test/metabase/metabot/agent/tools/document_test.clj+++ b/test/metabase/metabot/tools/document_test.clj@@ -1,11 +1,12 @@-(ns metabase.metabot.agent.tools.document-test+(ns metabase.metabot.tools.document-test(:require[clojure.test :refer :all]- [metabase.metabot.agent.tools.construct :as construct-tools]- [metabase.metabot.agent.tools.document :as document-tools]- [metabase.metabot.agent.tools.shared :as shared][metabase.metabot.table-utils :as table-utils]- [metabase.metabot.tools.create-sql-query :as create-sql-query-tools]+ [metabase.metabot.tools.construct :as construct-tools]+ [metabase.metabot.tools.document :as document-tools]+ [metabase.metabot.tools.shared :as shared]+ [metabase.metabot.tools.sql.create :as create-sql-query-tools]+ [metabase.query-processor :as qp][metabase.warehouses.core :as warehouses]))(deftest document-schema-collect-tool-test@@ -40,11 +41,14 @@(testing "builds chart draft payload from SQL query"(with-redefs [create-sql-query-tools/create-sql-query(fn [_]- {:query-id "q-1"- :query {:database 1- :type "native"- :native {:query "SELECT * FROM test"- :template-tags {}}}})]+ {:validation-result {:valid? true+ :dialect "postgres"}+ :action-result {:query-id "q-1"+ :query {:database 1+ :type "native"+ :native {:query "SELECT * FROM test"+ :template-tags {}}}}})+ qp/process-query (fn [_] nil)](let [result (document-tools/document-construct-sql-chart-tool{:database_id 1:name "Test Name"@@ -65,7 +69,51 @@:type "native":native {:query "SELECT * FROM test":template-tags {}}}- (:dataset_query structured)))))))+ (:dataset_query structured))))))++ (testing "returns instructions when SQL validation fails"+ (with-redefs [create-sql-query-tools/create-sql-query+ (fn [_]+ {:validation-result {:valid? false+ :dialect "postgres"+ :error-message "syntax error near FROM"}})]+ (let [result (document-tools/document-construct-sql-chart-tool+ {:database_id 1+ :name "Test Name"+ :description "Test Desc"+ :analysis "Test Analysis"+ :approach "Test Approach"+ :sql "SELECT FROM test"+ :viz_settings {:chart_type "bar"}})]+ (is (nil? (:final-response? result)))+ (is (nil? (:structured-output result)))+ (is (re-find #"SQL chart draft generation failed" (:output result)))+ (is (re-find #"syntax error near FROM" (:output result))))))++ (testing "returns instructions when query processor rejects generated SQL"+ (with-redefs [create-sql-query-tools/create-sql-query+ (fn [_]+ {:validation-result {:valid? true+ :dialect "postgres"}+ :action-result {:query-id "q-1"+ :query {:database 1+ :type "native"+ :native {:query "SELECT * FROM missing_table"+ :template-tags {}}}}})+ qp/process-query (fn [_]+ (throw (ex-info "Table \"missing_table\" does not exist" {})))]+ (let [result (document-tools/document-construct-sql-chart-tool+ {:database_id 1+ :name "Test Name"+ :description "Test Desc"+ :analysis "Test Analysis"+ :approach "Test Approach"+ :sql "SELECT * FROM missing_table"+ :viz_settings {:chart_type "bar"}})]+ (is (nil? (:final-response? result)))+ (is (nil? (:structured-output result)))+ (is (re-find #"could not be processed by Metabase" (:output result)))+ (is (re-find #"missing_table" (:output result)))))))(deftest document-construct-model-chart-tool-test(testing "builds chart draft payload from model query"diff --git a/test/metabase/metabot/tools/navigate_test.clj b/test/metabase/metabot/tools/navigation_test.cljsimilarity index 98%rename from test/metabase/metabot/tools/navigate_test.cljrename to test/metabase/metabot/tools/navigation_test.cljindex 9473a9d8a66..d1ae9e42ea9 100644--- a/test/metabase/metabot/tools/navigate_test.clj+++ b/test/metabase/metabot/tools/navigation_test.clj@@ -1,8 +1,8 @@-(ns metabase.metabot.tools.navigate-test+(ns metabase.metabot.tools.navigation-test(:require[clojure.string :as str][clojure.test :refer :all]- [metabase.metabot.tools.navigate :as navigate]))+ [metabase.metabot.tools.navigation :as navigate]))(deftest page->path-test(testing "page navigation produces correct paths"diff --git a/test/metabase/metabot/tools/read_resource_test.clj b/test/metabase/metabot/tools/resources_test.cljsimilarity index 98%rename from test/metabase/metabot/tools/read_resource_test.cljrename to test/metabase/metabot/tools/resources_test.cljindex 0fb0a217b1d..a14b86a9374 100644--- a/test/metabase/metabot/tools/read_resource_test.clj+++ b/test/metabase/metabot/tools/resources_test.clj@@ -1,10 +1,10 @@-(ns metabase.metabot.tools.read-resource-test+(ns metabase.metabot.tools.resources-test"Tests for read_resource tool."(:require[clojure.string :as str][clojure.test :refer :all][metabase.lib.core :as lib]- [metabase.metabot.tools.read-resource :as read-resource]+ [metabase.metabot.tools.resources :as read-resource][metabase.test :as mt]))(deftest parse-uri-testdiff --git a/test/metabase/metabot/tools/llm_representations_test.clj b/test/metabase/metabot/tools/shared/llm_representations_test.cljsimilarity index 99%rename from test/metabase/metabot/tools/llm_representations_test.cljrename to test/metabase/metabot/tools/shared/llm_representations_test.cljindex 1f4fa8a2ecf..b852093b38d 100644--- a/test/metabase/metabot/tools/llm_representations_test.clj+++ b/test/metabase/metabot/tools/shared/llm_representations_test.clj@@ -1,8 +1,8 @@-(ns metabase.metabot.tools.llm-representations-test+(ns metabase.metabot.tools.shared.llm-representations-test(:require[clojure.string :as str][clojure.test :refer :all]- [metabase.metabot.tools.llm-representations :as llm-rep]))+ [metabase.metabot.tools.shared.llm-representations :as llm-rep]))(deftest escape-xml-test(testing "escape-xml handles special characters"diff --git a/test/metabase/metabot/agent/tools/slackbot_query_test.clj b/test/metabase/metabot/tools/slackbot_query_test.cljsimilarity index 87%rename from test/metabase/metabot/agent/tools/slackbot_query_test.cljrename to test/metabase/metabot/tools/slackbot_query_test.cljindex 06982363520..3fed1cc57f6 100644--- a/test/metabase/metabot/agent/tools/slackbot_query_test.clj+++ b/test/metabase/metabot/tools/slackbot_query_test.clj@@ -1,11 +1,11 @@-(ns metabase.metabot.agent.tools.slackbot-query-test+(ns metabase.metabot.tools.slackbot-query-test"Tests for slackbot query tool schema and prompt content."(:require[clojure.java.io :as io][clojure.string :as str][clojure.test :refer :all][malli.json-schema :as mjs]- [metabase.metabot.agent.tools.slackbot-query]))+ [metabase.metabot.tools.slackbot-query :as slackbot-query]));;; ---------------------------------------- prompt content tests ---------------------------------------------------@@ -25,7 +25,7 @@(deftest display-field-has-description-test(testing "display field in slackbot-query-schema has a description in JSON Schema"- (let [schema @#'metabase.metabot.agent.tools.slackbot-query/slackbot-query-schema+ (let [schema @#'slackbot-query/slackbot-query-schemajson-schema (mjs/transform schema)display-prop (get-in json-schema [:properties :display])](is (some? (:description display-prop))@@ -35,7 +35,7 @@(deftest display-field-is-optional-test(testing "display field is not in the required list"- (let [schema @#'metabase.metabot.agent.tools.slackbot-query/slackbot-query-schema+ (let [schema @#'slackbot-query/slackbot-query-schemajson-schema (mjs/transform schema)required (set (:required json-schema))](is (not (contains? required "display"))diff --git a/test/metabase/metabot/tools/create_sql_query_test.clj b/test/metabase/metabot/tools/sql/create_test.cljsimilarity index 93%rename from test/metabase/metabot/tools/create_sql_query_test.cljrename to test/metabase/metabot/tools/sql/create_test.cljindex 133b7317117..eba34ab7693 100644--- a/test/metabase/metabot/tools/create_sql_query_test.clj+++ b/test/metabase/metabot/tools/sql/create_test.clj@@ -1,9 +1,9 @@-(ns metabase.metabot.tools.create-sql-query-test+(ns metabase.metabot.tools.sql.create-test(:require[clojure.string :as str][clojure.test :refer :all][metabase.driver :as driver]- [metabase.metabot.tools.create-sql-query :as create-sql-query]+ [metabase.metabot.tools.sql.create :as create-sql-query][metabase.test :as mt]))(deftest create-sql-query-testdiff --git a/test/metabase/metabot/tools/sql_tools_test.clj b/test/metabase/metabot/tools/sql/tools_test.cljsimilarity index 95%rename from test/metabase/metabot/tools/sql_tools_test.cljrename to test/metabase/metabot/tools/sql/tools_test.cljindex 1266aefd15b..31f41c4707f 100644--- a/test/metabase/metabot/tools/sql_tools_test.clj+++ b/test/metabase/metabot/tools/sql/tools_test.clj@@ -1,12 +1,12 @@-(ns metabase.metabot.tools.sql-tools-test+(ns metabase.metabot.tools.sql.tools-test"Comprehensive tests for SQL query manipulation tools."(:require[clojure.string :as str][clojure.test :refer :all][metabase.lib.core :as lib]- [metabase.metabot.tools.create-sql-query :as create-sql-query]- [metabase.metabot.tools.edit-sql-query :as edit-sql-query]- [metabase.metabot.tools.replace-sql-query :as replace-sql-query]+ [metabase.metabot.tools.sql.create :as create-sql-query]+ [metabase.metabot.tools.sql.edit :as edit-sql-query]+ [metabase.metabot.tools.sql.replace :as replace-sql-query][metabase.test :as mt]))(deftest edit-sql-query-testdiff --git a/test/metabase/metabot/agent/tools/sql_test.clj b/test/metabase/metabot/tools/sql_test.cljsimilarity index 98%rename from test/metabase/metabot/agent/tools/sql_test.cljrename to test/metabase/metabot/tools/sql_test.cljindex db922029321..cc8a174e631 100644--- a/test/metabase/metabot/agent/tools/sql_test.clj+++ b/test/metabase/metabot/tools/sql_test.clj@@ -1,12 +1,12 @@-(ns metabase.metabot.agent.tools.sql-test+(ns metabase.metabot.tools.sql-test"Tests that agent-level SQL tools produce correctly formatted :output stringswith preambles, query IDs in links, and operation-specific instructions."(:require[clojure.string :as str][clojure.test :refer :all][metabase.lib.core :as lib]- [metabase.metabot.agent.tools.shared :as shared]- [metabase.metabot.agent.tools.sql :as agent-sql]+ [metabase.metabot.tools.shared :as shared]+ [metabase.metabot.tools.sql :as agent-sql][metabase.test :as mt]))(deftest create-sql-query-output-testdiff --git a/test/metabase/metabot/agent/tools/subscriptions_test.clj b/test/metabase/metabot/tools/subscriptions_test.cljsimilarity index 89%rename from test/metabase/metabot/agent/tools/subscriptions_test.cljrename to test/metabase/metabot/tools/subscriptions_test.cljindex d04540cc0fc..c4c05738b65 100644--- a/test/metabase/metabot/agent/tools/subscriptions_test.clj+++ b/test/metabase/metabot/tools/subscriptions_test.clj@@ -1,10 +1,9 @@-(ns metabase.metabot.agent.tools.subscriptions-test+(ns metabase.metabot.tools.subscriptions-test"Tests for the create_dashboard_subscription agent tool wrapper."(:require[clojure.test :refer :all][metabase.channel.settings :as channel.settings]- [metabase.metabot.agent.tools.subscriptions :as agent-subscriptions]- [metabase.metabot.tools.create-dashboard-subscription :as subscription-tools]+ [metabase.metabot.tools.subscriptions :as agent-subscriptions][metabase.test :as mt]));;; ------------------------------------------ schema / metadata tests -----------------------------------------------@@ -23,7 +22,7 @@(deftest create-dashboard-subscription-happy-path-test(testing "valid dashboard, valid user email, valid schedule → success"(let [captured-args (atom nil)]- (with-redefs [subscription-tools/create-dashboard-subscription+ (with-redefs [agent-subscriptions/create-dashboard-subscription(fn [args] (reset! captured-args args) {:output "success"})](mt/with-current-user (mt/user->id :crowberto)(mt/with-temp [:model/Dashboard {dash-id :id} {:name "Test Dashboard"}]@@ -37,23 +36,18 @@(is (= dash-id (:dashboard-id @captured-args))))))))))(deftest create-dashboard-subscription-invalid-dashboard-id-test- (testing "non-integer dashboard_id → 'invalid dashboard_id'"+ (testing "nonexistent dashboard_id → error about missing dashboard"(mt/with-current-user (mt/user->id :crowberto)- (with-redefs [subscription-tools/create-dashboard-subscription- (fn [{:keys [dashboard-id]}]- (if (int? dashboard-id)- {:output "success"}- {:output "invalid dashboard_id"}))]- (let [result (agent-subscriptions/create-dashboard-subscription-tool- {:dashboard_id 0- :email "[email protected]"- :schedule {:frequency "daily"}})]- ;; dashboard_id 0 is int but won't match any dashboard- (is (string? (:output result))))))))+ (let [result (agent-subscriptions/create-dashboard-subscription-tool+ {:dashboard_id 0+ :email "[email protected]"+ :schedule {:frequency "daily"}})]+ ;; dashboard_id 0 is int but won't match any dashboard+ (is (string? (:error result)))))))(deftest create-dashboard-subscription-unknown-email-test(testing "unknown email → 'no user with this email found'"- (with-redefs [subscription-tools/create-dashboard-subscription+ (with-redefs [agent-subscriptions/create-dashboard-subscription(fn [{:keys [email]}](if (= email "[email protected]"){:output "no user with this email found"}@@ -68,7 +62,7 @@(deftest create-dashboard-subscription-nonexistent-dashboard-test(testing "nonexistent dashboard → 404 or error message"- (with-redefs [subscription-tools/create-dashboard-subscription+ (with-redefs [agent-subscriptions/create-dashboard-subscription(fn [{:keys [dashboard-id]}](if (= dashboard-id 999999){:output "no dashboard with this dashboard_id found"}@@ -83,7 +77,7 @@(deftest create-dashboard-subscription-schedule-keywords-test(testing "schedule keywords are converted from snake_case to kebab-case"(let [captured-args (atom nil)]- (with-redefs [subscription-tools/create-dashboard-subscription+ (with-redefs [agent-subscriptions/create-dashboard-subscription(fn [args] (reset! captured-args args) {:output "success"})](mt/with-current-user (mt/user->id :crowberto)(agent-subscriptions/create-dashboard-subscription-tooldiff --git a/test/metabase/metabot/tools/transforms_write_test.clj b/test/metabase/metabot/tools/transforms/write_test.cljsimilarity index 98%rename from test/metabase/metabot/tools/transforms_write_test.cljrename to test/metabase/metabot/tools/transforms/write_test.cljindex 12c2816638f..965a5706efd 100644--- a/test/metabase/metabot/tools/transforms_write_test.clj+++ b/test/metabase/metabot/tools/transforms/write_test.clj@@ -1,7 +1,7 @@-(ns metabase.metabot.tools.transforms-write-test+(ns metabase.metabot.tools.transforms.write-test(:require[clojure.test :refer :all]- [metabase.metabot.tools.transforms-write :as transforms-write]))+ [metabase.metabot.tools.transforms.write :as transforms-write]));;; Edit Application Testsdiff --git a/test/metabase/metabot/tools/transforms_test.clj b/test/metabase/metabot/tools/transforms_test.cljindex 94b44b29501..6c35fdab941 100644--- a/test/metabase/metabot/tools/transforms_test.clj+++ b/test/metabase/metabot/tools/transforms_test.clj@@ -1,60 +1,123 @@(ns metabase.metabot.tools.transforms-test+ "Tests for agent-level transform tool wrappers, particularly the+ dependency checking integration in write-transform-sql-tool."(:require+ [clojure.string :as str][clojure.test :refer :all]- [metabase.lib-be.metadata.jvm :as lib-be]- [metabase.lib.core :as lib]- [metabase.metabot.tools.transforms :as metabot.tools.transforms]- [metabase.permissions.models.permissions-group :as perms-group]- [metabase.test :as mt]))+ [metabase.metabot.tools.dependencies :as deps]+ [metabase.metabot.tools.shared :as shared]+ [metabase.metabot.tools.transforms :as agent-transforms]+ [metabase.metabot.tools.transforms.write :as transforms-write]))-(deftest get-transforms-test- (testing "get-transforms correctly returns transform when the user has access to the source database"- (mt/with-premium-features #{:transforms-basic}- (mt/with-temp [:model/Database {db-id :id} {}]- (let [mp (lib-be/application-database-metadata-provider db-id)]- (mt/with-temp [:model/Transform transform- {:name "Test Transform"- :source {:type "query"- :query (lib/native-query mp "SELECT 1")}}]- (testing "returns transform when user can query the source database"- (mt/with-test-user :crowberto- (let [result (:structured_output (metabot.tools.transforms/get-transforms {}))- returned (first (filter #(= (:id transform) (:id %)) result))]- (is (some? returned)))))- (testing "filters out transform when user cannot query the source database"- (mt/with-data-analyst-role! (mt/user->id :rasta)- (mt/with-db-perm-for-group! (perms-group/all-users) db-id :perms/create-queries :no- (mt/with-test-user :rasta- (let [result (:structured_output (metabot.tools.transforms/get-transforms {}))- returned (first (filter #(= (:id transform) (:id %)) result))]- (is (nil? returned)))))))))))))+;;; ----------------------------------- dependency check integration tests --------------------------------------------(deftest get-transform-details-test- (testing "get-transform-details returns transform when user can query the source database"- (mt/with-premium-features #{:transforms-basic}- (mt/with-temp [:model/Transform transform- {:name "Test Transform"- :source {:type "query"- :query (lib/native-query (mt/metadata-provider) "SELECT 1")}}]- (mt/with-test-user :crowberto- (let [result (:structured_output (metabot.tools.transforms/get-transform-details- {:transform-id (:id transform)}))]- (is (= (:id transform) (:id result)))))))))+(deftest write-transform-sql-dependency-check-no-issues-test+ (testing "when check-dependencies returns nil (no issues) → result unchanged, no extra instructions"+ (let [memory-atom (atom {:state {}})+ base-result {:structured-output {:transform {:id 1+ :name "Test"+ :source {:type "query" :query "SELECT 1"}}+ :message "Transform updated successfully."}+ :data-parts [{:type :data :data-type "transform_suggestion" :version 1}]}]+ (with-redefs [transforms-write/write-transform-sql (fn [_] base-result)+ deps/check-transform-dependencies (fn [_] {:structured_output {:success true+ :bad_transforms []+ :bad_questions nil}})]+ (let [result (binding [shared/*memory-atom* memory-atom]+ (agent-transforms/write-transform-sql-tool+ {:transform_id 1+ :edit_action {:mode "replace" :new_content "SELECT 1"}}))]+ (is (nil? (:instructions result)))+ (is (some? (:output result))))))))-(deftest get-transform-details-blocked-test- (testing "get-transform-details throws when user cannot query the source database"- (mt/with-premium-features #{:transforms-basic}- (mt/with-temp [:model/Database {db-id :id} {}]- (let [mp (lib-be/application-database-metadata-provider db-id)]- (mt/with-temp [:model/Transform transform- {:name "Blocked Transform"- :source {:type "query"- :query (lib/native-query mp "SELECT 1")}}]- (mt/with-data-analyst-role! (mt/user->id :rasta)- (mt/with-db-perm-for-group! (perms-group/all-users) db-id :perms/create-queries :no- (mt/with-test-user :rasta- (is (thrown-with-msg?- clojure.lang.ExceptionInfo- #"You don't have permissions to do that"- (metabot.tools.transforms/get-transform-details- {:transform-id (:id transform)}))))))))))))+(deftest write-transform-sql-dependency-check-broken-transforms-test+ (testing "when check-dependencies returns bad_transforms → instructions appended with transform links"+ (let [memory-atom (atom {:state {}})+ base-result {:structured-output {:transform {:id 1+ :name "Test"+ :source {:type "query" :query "SELECT id FROM orders"}}+ :message "Transform updated successfully."}+ :data-parts [{:type :data :data-type "transform_suggestion" :version 1}]}]+ (with-redefs [transforms-write/write-transform-sql (fn [_] base-result)+ deps/check-transform-dependencies (fn [_]+ {:structured_output+ {:success false+ :bad_transform_count 1+ :bad_transforms [{:transform {:id 2 :name "Downstream Transform"}+ :errors ["Column 'total' not found"]}]+ :bad_questions nil}})]+ (let [result (binding [shared/*memory-atom* memory-atom]+ (agent-transforms/write-transform-sql-tool+ {:transform_id 1+ :edit_action {:mode "replace" :new_content "SELECT id FROM orders"}}))]+ (is (some? (:instructions result)))+ (is (str/includes? (:instructions result) "Dependency issues detected"))+ (is (str/includes? (:instructions result) "Broken transforms"))+ (is (str/includes? (:instructions result) "Downstream Transform"))+ (is (str/includes? (:instructions result) "metabase://transform/2")))))))++(deftest write-transform-sql-dependency-check-broken-questions-test+ (testing "when check-dependencies returns bad_questions → instructions appended with question links"+ (let [memory-atom (atom {:state {}})+ base-result {:structured-output {:transform {:id 1+ :name "Test"+ :source {:type "query" :query "SELECT id FROM orders"}}+ :message "Transform updated successfully."}+ :data-parts [{:type :data :data-type "transform_suggestion" :version 1}]}]+ (with-redefs [transforms-write/write-transform-sql (fn [_] base-result)+ deps/check-transform-dependencies (fn [_]+ {:structured_output+ {:success false+ :bad_transform_count 0+ :bad_transforms []+ :bad_question_count 2+ :bad_questions [{:question {:id 10 :name "Revenue Report"}+ :errors ["Column 'total' not found"]}+ {:question {:id 11 :name "Monthly Summary"}+ :errors ["Column 'total' not found"]}]}})]+ (let [result (binding [shared/*memory-atom* memory-atom]+ (agent-transforms/write-transform-sql-tool+ {:transform_id 1+ :edit_action {:mode "replace" :new_content "SELECT id FROM orders"}}))]+ (is (some? (:instructions result)))+ (is (str/includes? (:instructions result) "Broken questions"))+ (is (str/includes? (:instructions result) "Revenue Report"))+ (is (str/includes? (:instructions result) "metabase://question/10"))+ (is (str/includes? (:instructions result) "Monthly Summary"))+ (is (str/includes? (:instructions result) "metabase://question/11")))))))++(deftest write-transform-sql-dependency-check-error-test+ (testing "when check-dependencies throws → graceful degradation (no crash, result unchanged)"+ (let [memory-atom (atom {:state {}})+ base-result {:structured-output {:transform {:id 1+ :name "Test"+ :source {:type "query" :query "SELECT 1"}}+ :message "Transform updated successfully."}+ :data-parts [{:type :data :data-type "transform_suggestion" :version 1}]}]+ (with-redefs [transforms-write/write-transform-sql (fn [_] base-result)+ deps/check-transform-dependencies (fn [_] (throw (Exception. "DB connection failed")))]+ (let [result (binding [shared/*memory-atom* memory-atom]+ (agent-transforms/write-transform-sql-tool+ {:transform_id 1+ :edit_action {:mode "replace" :new_content "SELECT 1"}}))]+ ;; Should succeed without instructions — the dep check failure is logged but not propagated+ (is (nil? (:instructions result)))+ (is (some? (:output result))))))))++(deftest write-transform-sql-dependency-check-new-transform-test+ (testing "new transforms (no transform_id) → dependency check skipped"+ (let [memory-atom (atom {:state {}})+ dep-called? (atom false)+ base-result {:structured-output {:transform {:name "New Transform"+ :source {:type "query" :query "SELECT 1"}}+ :message "Transform created successfully."}+ :data-parts [{:type :data :data-type "transform_suggestion" :version 1}]}]+ (with-redefs [transforms-write/write-transform-sql (fn [_] base-result)+ deps/check-transform-dependencies (fn [_] (reset! dep-called? true) nil)]+ (let [result (binding [shared/*memory-atom* memory-atom]+ (agent-transforms/write-transform-sql-tool+ {:edit_action {:mode "replace" :new_content "SELECT 1"}+ :transform_name "New Transform"}))]+ (is (false? @dep-called?))+ (is (nil? (:instructions result)))+ (is (some? (:output result))))))))diff --git a/test/metabase/metabot/agent/tools_test.clj b/test/metabase/metabot/tools_test.cljsimilarity index 98%rename from test/metabase/metabot/agent/tools_test.cljrename to test/metabase/metabot/tools_test.cljindex 40ed4dc4674..005dcebfea8 100644--- a/test/metabase/metabot/agent/tools_test.clj+++ b/test/metabase/metabot/tools_test.clj@@ -1,9 +1,9 @@-(ns metabase.metabot.agent.tools-test+(ns metabase.metabot.tools-test(:require[clojure.test :refer :all][metabase.metabot.agent.profiles :as profiles]- [metabase.metabot.agent.tools :as agent-tools]- [metabase.metabot.tools.create-chart :as create-chart-tools]+ [metabase.metabot.tools :as agent-tools]+ [metabase.metabot.tools.charts.create :as create-chart-tools][metabase.metabot.tools.filters :as filter-tools]))(deftest all-tools-testdiff --git a/test_resources/serialization_baseline/settings.yaml b/test_resources/serialization_baseline/settings.yamlindex 55408373352..b8d4349370e 100644--- a/test_resources/serialization_baseline/settings.yaml+++ b/test_resources/serialization_baseline/settings.yaml@@ -40,7 +40,6 @@ landing-page-illustration-custom: nullloading-message: nulllogin-page-illustration: nulllogin-page-illustration-custom: null-metabot-ai-service-token-ttl: nullnative-query-autocomplete-match-style: nullno-data-illustration: nullno-data-illustration-custom: null