Skip to content

The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:

Report query, chart analysis and library search failures as errors (#82970)

Andrei Simionescu8c5c1e3e85ed
diff --git a/src/metabase/metabot/tools/analyze_chart.clj b/src/metabase/metabot/tools/analyze_chart.clj
index e547f89fcc3..fbcaa3f9451 100644
--- a/src/metabase/metabot/tools/analyze_chart.clj
+++ b/src/metabase/metabot/tools/analyze_chart.clj
@@ -8,7 +8,7 @@
[metabase.interestingness.core :as interestingness]
[metabase.metabot.scope :as scope]
[metabase.metabot.tools.shared :as shared]
- [metabase.util.log :as log]
+ [metabase.metabot.tools.util :as metabot.tools.u]
[metabase.util.malli :as mu]
[tech.v3.resource :as resource]))
@@ -60,17 +60,17 @@ Do not use headers (##). Do not list statistics. Do not analyze series separatel
[{:keys [series] :as _chart-config}]
(when (empty? series)
(throw (ex-info "This chart has no series data to analyze."
- {:type ::malformed-chart-config})))
+ {:agent-error? true, :type ::malformed-chart-config})))
(doseq [[series-name {:keys [y_values]}] series]
(when (empty? y_values)
(throw (ex-info (format "Series \"%s\" has no data points to analyze." series-name)
- {:type ::malformed-chart-config, :series series-name})))
+ {:agent-error? true, :type ::malformed-chart-config, :series series-name})))
(when (non-numeric-y-value? y_values)
;; compute-chart-stats assumes each series has numeric y-values.
(throw (ex-info (format (str "Series \"%s\" has non-numeric y-values. Chart analysis "
"requires a numeric y-axis metric.")
series-name)
- {:type ::malformed-chart-config, :series series-name})))))
+ {:agent-error? true, :type ::malformed-chart-config, :series series-name})))))
(mu/defn ^{:tool-name "analyze_chart"
:scope scope/agent-viz-read}
@@ -101,5 +101,4 @@ Do not use headers (##). Do not list statistics. Do not analyze series separatel
{:output (str "Chart config not found: " chart_config_id
". Available chart configs can be found in the viewing context.")})
(catch Exception e
- (log/errorf "Error analyzing chart: %s" (ex-message e))
- {:output (str "Failed to analyze chart: " (or (ex-message e) "Unknown error"))})))
+ (metabot.tools.u/handle-agent-error e))))
diff --git a/src/metabase/metabot/tools/construct.clj b/src/metabase/metabot/tools/construct.clj
index b7309d58005..8c399615f9a 100644
--- a/src/metabase/metabot/tools/construct.clj
+++ b/src/metabase/metabot/tools/construct.clj
@@ -27,7 +27,6 @@
[metabase.util :as u]
[metabase.util.i18n :refer [tru]]
[metabase.util.json :as json]
- [metabase.util.log :as log]
[metabase.util.malli :as mu]
[metabase.util.malli.registry :as mr]))
@@ -897,16 +896,4 @@
"<instructions>\n" instruction-text "\n</instructions>")))
query-result)))
(catch Exception e
- ;; A 403 counts as agent-facing even without the flag: `api/read-check` throws a bare one,
- ;; and it means the user can't have the card they named rather than that anything broke.
- (if (or (:agent-error? (ex-data e))
- (= 403 (:status-code (ex-data e))))
- ;; Expected agent-facing signal (bad LLM input: unknown table, unknown schema,
- ;; URI-in-source-table, …). Log at debug only — no stacktrace — since the message
- ;; is the tool's result and the LLM is expected to self-correct on the next turn.
- (do
- (log/debugf "construct_notebook_query returned agent-error to the LLM: %s" (ex-message e))
- {:output (ex-message e)})
- (do
- (log/errorf "Failed to construct notebook query: %s" (ex-message e))
- {:output (str "Failed to construct notebook query: " (or (ex-message e) "Unknown error"))})))))
+ (tools.u/handle-agent-or-api-error e))))
diff --git a/src/metabase/metabot/tools/entity_retrieval.clj b/src/metabase/metabot/tools/entity_retrieval.clj
index 5df6e838bb8..58704ee0d96 100644
--- a/src/metabase/metabot/tools/entity_retrieval.clj
+++ b/src/metabase/metabot/tools/entity_retrieval.clj
@@ -21,7 +21,6 @@
[metabase.metabot.tools.search :as tools.search]
[metabase.metabot.tools.shared.llm-shape :as llm-shape]
[metabase.util :as u]
- [metabase.util.log :as log]
[metabase.util.malli :as mu]))
(set! *warn-on-reflection* true)
@@ -187,19 +186,10 @@
top match is flagged low-confidence (a leading <note> / confidence=\"weak\"), nothing in the library
clearly matches — prefer asking the user to clarify or narrow the request."
[{:keys [user_search_prompt limit]} :- entity-retrieval-schema]
- (try
- (let [n (min max-limit (or limit default-limit))
- matches (build-matches user_search_prompt n)]
- {:output (format-output matches)
- :structured-output {:result-type :search
- :data (flatten-data matches)
- :total_count (count matches)
- :weak_match (boolean (:weak? (first matches)))}})
- (catch Exception e
- ;; A failure here is the search subsystem being down (typically the embedding service), not "the
- ;; library is empty" — say so in :output (the only channel the agent reads) so it doesn't confidently
- ;; tell the user nothing matches. No :structured-output: that feeds the FE a result payload, and there's
- ;; no successful search to render.
- (log/errorf "Error in retrieve_library_entities: %s" (ex-message e))
- {:output (str "The library search is temporarily unavailable (" (or (ex-message e) "unknown error")
- "). This does not mean the library is empty; the search could not be run.")})))
+ (let [n (min max-limit (or limit default-limit))
+ matches (build-matches user_search_prompt n)]
+ {:output (format-output matches)
+ :structured-output {:result-type :search
+ :data (flatten-data matches)
+ :total_count (count matches)
+ :weak_match (boolean (:weak? (first matches)))}}))
diff --git a/src/metabase/metabot/tools/slackbot_query.clj b/src/metabase/metabot/tools/slackbot_query.clj
index a24254cafc0..554a17e2deb 100644
--- a/src/metabase/metabot/tools/slackbot_query.clj
+++ b/src/metabase/metabot/tools/slackbot_query.clj
@@ -11,7 +11,7 @@
[metabase.metabot.scope :as scope]
[metabase.metabot.tools.construct :as construct]
[metabase.metabot.tools.recovery-hints :as recovery-hints]
- [metabase.util.log :as log]
+ [metabase.metabot.tools.util :as metabot.tools.u]
[metabase.util.malli :as mu]))
(set! *warn-on-reflection* true)
@@ -60,7 +60,4 @@
:data-parts [(streaming/adhoc-viz-part adhoc-viz-value)]})
query-result))
(catch Exception e
- (log/errorf "Failed to construct slackbot notebook query: %s" (ex-message e))
- (if (:agent-error? (ex-data e))
- {:output (ex-message e)}
- {:output (str "Failed to construct notebook query: " (or (ex-message e) "Unknown error"))}))))
+ (metabot.tools.u/handle-agent-or-api-error e))))
diff --git a/test/metabase/metabot/tools/analyze_chart_test.clj b/test/metabase/metabot/tools/analyze_chart_test.clj
index 325b3aa2fe8..1ceee57c775 100644
--- a/test/metabase/metabot/tools/analyze_chart_test.clj
+++ b/test/metabase/metabot/tools/analyze_chart_test.clj
@@ -2,8 +2,10 @@
(:require
[clojure.string :as str]
[clojure.test :refer :all]
+ [metabase.interestingness.core :as interestingness]
[metabase.metabot.tools.analyze-chart :as analyze-chart]
- [metabase.metabot.tools.shared :as shared]))
+ [metabase.metabot.tools.shared :as shared]
+ [metabase.test :as mt]))
(set! *warn-on-reflection* true)
@@ -38,12 +40,12 @@
(deftest ^:parallel analyze-chart-tool-empty-series-test
(testing "a chart config with no series is rejected"
- (is (= {:output "Failed to analyze chart: This chart has no series data to analyze."}
+ (is (= {:output "This chart has no series data to analyze."}
(analyze "c1" {"c1" {:display_type "row" :title "Empty" :series {}}})))))
(deftest ^:parallel analyze-chart-tool-empty-y-values-test
(testing "a series with no data points is rejected"
- (is (= {:output "Failed to analyze chart: Series \"Count\" has no data points to analyze."}
+ (is (= {:output "Series \"Count\" has no data points to analyze."}
(analyze "c1" {"c1" {:display_type "row"
:title "No points"
:series {"Count" {:x {:name "category" :type "string"}
@@ -54,7 +56,7 @@
(deftest ^:parallel analyze-chart-tool-non-numeric-y-values-test
(testing "a series with non-numeric y-values is rejected"
- (is (= {:output (str "Failed to analyze chart: Series \"Count\" has non-numeric y-values. "
+ (is (= {:output (str "Series \"Count\" has non-numeric y-values. "
"Chart analysis requires a numeric y-axis metric.")}
(analyze "c1" {"c1" {:display_type "row"
:title "Survey responses"
@@ -63,3 +65,9 @@
:x_values ["Never" "Rarely" "Often"]
:y_values ["One" "Two" "Three"]
:display_name "Count"}}}})))))
+
+(deftest ^:parallel analyze-chart-tool-unexpected-error-test
+ (testing "an unexpected error propagates to the agent loop"
+ (mt/with-dynamic-fn-redefs [interestingness/compute-chart-stats (fn [& _] (throw (ex-info "boom" {})))]
+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"boom"
+ (analyze "c1" (numeric-series-config)))))))
diff --git a/test/metabase/metabot/tools/entity_retrieval_test.clj b/test/metabase/metabot/tools/entity_retrieval_test.clj
index 1fd70c42004..73fa4304618 100644
--- a/test/metabase/metabot/tools/entity_retrieval_test.clj
+++ b/test/metabase/metabot/tools/entity_retrieval_test.clj
@@ -194,3 +194,10 @@
{:type "table" :id 1 :matched_doc_type "name" :matched_text "p2"
:usage_instructions "u2" :confidence "weak" :similarity 0.3}]
out)))))
+
+(deftest ^:parallel tool-search-failure-throws-test
+ (testing "a failing library search propagates to the agent loop, which reports the call as failed"
+ (with-unfiltered-search (fn [_ _] (throw (ex-info "Embedding service unavailable" {})))
+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"Embedding service unavailable"
+ (entity-retrieval/retrieve-library-entities-tool
+ {:user_search_prompt "revenue per region"}))))))
diff --git a/test/metabase/metabot/tools/slackbot_query_test.clj b/test/metabase/metabot/tools/slackbot_query_test.clj
index b9ee907efae..aa41a984713 100644
--- a/test/metabase/metabot/tools/slackbot_query_test.clj
+++ b/test/metabase/metabot/tools/slackbot_query_test.clj
@@ -187,20 +187,20 @@
(is (nil? (:structured-output result)))
(is (nil? (:data-parts result)))))))))
-(deftest slackbot-tool-unexpected-error-is-wrapped-test
- (testing (str "A non-agent exception (e.g. a programming bug) gets wrapped with a generic\n"
- "`Failed to construct notebook query: ...` prefix. Protects the LLM from\n"
- "leaking internal stack-trace-style messages.")
- (with-repr-stub!
- (fn [_external-query & _]
- (throw (RuntimeException. "something went sideways")))
- (fn []
- (let [result (slackbot-query/slackbot-construct-notebook-query-tool
- {:reasoning "test non-agent error path"
- :query {:lib/type "mbql/query" :stages []}})]
- (is (string? (:output result)))
- (is (str/starts-with? (:output result) "Failed to construct notebook query:"))
- (is (re-find #"something went sideways" (:output result))))))))
+(deftest slackbot-tool-non-agent-errors-test
+ (let [tool-result-for-thrown #(with-repr-stub!
+ (fn [_external-query & _] (throw %))
+ (fn []
+ (slackbot-query/slackbot-construct-notebook-query-tool
+ {:reasoning "test non-agent error path"
+ :query {:lib/type "mbql/query" :stages []}})))]
+ (testing "a permission error goes back to the agent as output"
+ (is (= "You don't have permissions to do that."
+ (:output (tool-result-for-thrown
+ (ex-info "You don't have permissions to do that." {:status-code 403}))))))
+ (testing "an unexpected error, e.g. a programming bug, propagates to the agent loop"
+ (is (thrown-with-msg? RuntimeException #"something went sideways"
+ (tool-result-for-thrown (RuntimeException. "something went sideways")))))))
;;; ---------------------------------------- end-to-end test --------------------------------------------------------
diff --git a/test/metabase/metabot/tools_test.clj b/test/metabase/metabot/tools_test.clj
index f51934f75da..ce83a6f0005 100644
--- a/test/metabase/metabot/tools_test.clj
+++ b/test/metabase/metabot/tools_test.clj
@@ -173,8 +173,8 @@
(get-in result [:data-parts 0 :data :description]))))))))
(defn- construct-tool-output-for-thrown
- "Run `construct_notebook_query` with `execute-representations-query` throwing `e`, and return
- the `:output` the LLM would see."
+ "Run `construct_notebook_query` with `execute-representations-query` throwing `e`.
+ Returns the `:output` the LLM would see when the tool handles `e`; otherwise `e` propagates."
[e]
(mt/with-dynamic-fn-redefs [construct/execute-representations-query (fn [_ _] (throw e))]
(:output (binding [shared/*profile-id* :nlq]
@@ -190,10 +190,10 @@
(is (= "You don't have permissions to do that."
(construct-tool-output-for-thrown
(ex-info "You don't have permissions to do that." {:status-code 403})))))
- (testing "anything else without `:agent-error?` still gets the generic wrapper"
- (is (= "Failed to construct notebook query: something went sideways"
- (construct-tool-output-for-thrown
- (ex-info "something went sideways" {:status-code 400}))))))
+ (testing "an unexpected error propagates to the agent loop"
+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"something went sideways"
+ (construct-tool-output-for-thrown
+ (ex-info "something went sideways" {}))))))
(deftest state-dependent-tools-test
(testing "state-dependent-tools set contains expected tools"