Skip to content

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

Let Metabot recover from bad Research tool calls (#84856)

Andrei Simionescu4a4102b3bf6d
diff --git a/src/metabase/explorations/impl.clj b/src/metabase/explorations/impl.clj
index fdaeb76d452..ccbb9929cd1 100644
--- a/src/metabase/explorations/impl.clj
+++ b/src/metabase/explorations/impl.clj
@@ -488,14 +488,39 @@
(seq missing)
(assoc :missing_metric_ids missing))))
+(defn- invalid-dimensions
+ "Return invalid dimension IDs from `groups`, grouped by metric.
+ `metric-by-id` must include each metric referenced by `groups`. Each result includes that
+ metric's candidate dimensions. Metrics appear in the order of their first invalid dimension in `groups`."
+ [groups metric-by-id]
+ (let [bad (for [{metric-id :metric_id dimension-ids :dimension_ids} groups
+ :let [valid (into #{} (map :id) (:dimensions (metric-by-id metric-id)))]
+ d dimension-ids
+ :when (not (contains? valid d))]
+ [metric-id d])
+ bad-by-metric (group-by first bad)]
+ (vec (for [metric-id (distinct (map first bad))
+ :let [{metric-name :name :keys [dimensions]} (metric-by-id metric-id)]]
+ {:metric-id metric-id
+ :metric-name metric-name
+ :dimension-ids (into [] (comp (map second) (distinct)) (bad-by-metric metric-id))
+ :candidates (mapv (fn [d] {:id (:id d) :name (or (block/dimension-label d) "")})
+ dimensions)}))))
+
(defn research-groups
"Validate Metabot's chosen research groups and return the FE picker payload for them.
`:groups` is a sequence of `{:metric_id <int> :dimension_ids [<str> ...]}` maps
(`:dimension_ids` optional).
- Hard-errors (throws) on any unknown/inaccessible metric id or a dimension id that isn't a
- candidate of its metric — one bad id fails the whole batch.
+ Throws when any group is invalid, so one bad ID fails the whole batch. The `ex-data` lists every
+ problem under the applicable keys:
+ - `:unknown-metric-ids`: the metric IDs that are unknown or inaccessible;
+ - `:replace-without-dimensions`: the metric IDs of groups that set
+ `:replace_default_dimensions` with no `:dimension_ids`;
+ - `:invalid-dimensions`: the invalid dimension IDs and candidate dimensions for each metric
+ (see [[invalid-dimensions]]).
+ A group whose metric is unknown gets no further checks.
On success returns `{:metrics [...] :dimension_groups [...] :groups [...]}`, where
`:metrics`/`:dimension_groups` are the [[exploration-data]] hydration restricted to the
@@ -503,35 +528,33 @@
blocks."
[{:keys [groups]}]
(lib-be/with-metadata-provider-cache
- (let [all (mapv with-candidate-dimensions (catalog-metrics {}))
- metric-by-id (u/index-by :id all)]
- ;; Metric-level checks run against the cheap catalog — they need no query build.
- (doseq [g groups]
- (let [metric-id (:metric_id g)]
- (when-not (contains? metric-by-id metric-id)
- (throw (ex-info (format "Unknown or inaccessible metric id %s" metric-id)
- {:metric_id metric-id})))
- (when (and (:replace_default_dimensions g) (empty? (:dimension_ids g)))
- (throw (ex-info "replace_default_dimensions requires at least one dimension_id"
- {:metric_id metric-id})))))
- (let [relevant (into #{} (map :metric_id) groups)
- ;; Only the referenced metrics pay [[resolve-metric-queries]]. `all` is already
- ;; candidate-filtered and resolution only drops dimensions further, so no second
- ;; [[with-candidate-dimensions]] pass is needed.
- relevant-metrics (->> all
- (filterv #(contains? relevant (:id %)))
- resolve-metric-queries)
- resolved-by-id (u/index-by :id relevant-metrics)]
- ;; Dimension ids are checked against the *resolved* metrics: a saved dimension whose
- ;; target no longer resolves is dropped by [[resolve-metric-queries]], and accepting it
- ;; would hand the FE a picker block for a dimension that isn't in the payload.
- (doseq [g groups
- :let [metric-id (:metric_id g)
- valid (set (map :id (:dimensions (get resolved-by-id metric-id))))]
- d (:dimension_ids g)]
- (when-not (contains? valid d)
- (throw (ex-info (format "Dimension %s is not a candidate of metric %s" d metric-id)
- {:metric_id metric-id :dimension_id d}))))
- {:metrics (mapv slim-metric relevant-metrics)
- :dimension_groups (group-dimensions relevant-metrics)
- :groups (vec groups)}))))
+ (let [all (mapv with-candidate-dimensions (catalog-metrics {}))
+ metric-by-id (u/index-by :id all)
+ known? #(contains? metric-by-id (:metric_id %))
+ known-groups (filterv known? groups)
+ ;; Metric checks use the catalog and do not build queries.
+ unknown (into [] (comp (remove known?) (map :metric_id) (distinct)) groups)
+ no-dims (into [] (comp (filter #(and (:replace_default_dimensions %)
+ (empty? (:dimension_ids %))))
+ (map :metric_id)
+ (distinct))
+ known-groups)
+ relevant (into #{} (map :metric_id) groups)
+ ;; Only resolve queries for referenced metrics. `all` already has its candidate
+ ;; dimensions filtered, and resolution can only remove dimensions.
+ relevant-metrics (->> all
+ (filterv #(contains? relevant (:id %)))
+ resolve-metric-queries)
+ resolved-by-id (u/index-by :id relevant-metrics)
+ ;; Dimension IDs must match the resolved metrics because query resolution removes
+ ;; dimensions whose targets no longer resolve.
+ invalid (invalid-dimensions known-groups resolved-by-id)
+ problems (cond-> {}
+ (seq unknown) (assoc :unknown-metric-ids unknown)
+ (seq no-dims) (assoc :replace-without-dimensions no-dims)
+ (seq invalid) (assoc :invalid-dimensions invalid))]
+ (when (seq problems)
+ (throw (ex-info "Invalid research groups" problems)))
+ {:metrics (mapv slim-metric relevant-metrics)
+ :dimension_groups (group-dimensions relevant-metrics)
+ :groups (vec groups)})))
diff --git a/src/metabase/metabot/tools/explorations.clj b/src/metabase/metabot/tools/explorations.clj
index 84804b845b8..7ba639baa7c 100644
--- a/src/metabase/metabot/tools/explorations.clj
+++ b/src/metabase/metabot/tools/explorations.clj
@@ -15,8 +15,9 @@
[metabase.metabot.agent.streaming :as streaming]
[metabase.metabot.scope :as scope]
[metabase.metabot.tmpl :as te]
- [metabase.util.json :as json]
- [metabase.util.malli :as mu]))
+ [metabase.metabot.tools.core :as tools]
+ [metabase.timeline.core :as timeline]
+ [metabase.util.json :as json]))
(set! *warn-on-reflection* true)
@@ -70,56 +71,73 @@
[:map {:closed true}
[:q {:optional true} [:maybe :string]]])
-(mu/defn ^{:tool-name "list_research_metrics"
- :scope scope/agent-explorations-read}
- list-research-metrics-tool
- "List the metrics available for research: one slim row per metric (id, name, description,
- in_library — a quality signal), best first. Dimensions are not included; pass metric ids from
- this index to `get_research_candidates` to see their candidate dimensions. Pass `q` to filter
- by a case-insensitive substring of a metric or dimension name — e.g. `q: \"region\"` returns
- the metrics that have a Region-like dimension. More than 500 matches are truncated to the top
- 500 with `truncated: true` — narrow with `q`."
- [{:keys [q]} :- list-research-metrics-schema]
- {:output (json/encode (explorations/research-metric-index {:q q}))})
+(defrecord ListResearchMetricsTool []
+ tools/Tool
+ (declaration [_]
+ {:name "list_research_metrics"
+ :description (str "List the metrics available for research, with the best matches first. Each row"
+ " includes `id`, `name`, `description` and `in_library` (a quality signal)."
+ " Pass metric IDs from this list to `get_research_candidates` to see"
+ " their candidate dimensions. Pass `q` to filter by a case-insensitive substring"
+ " of a metric or dimension name – e.g. `q: \"region\"` returns the metrics that"
+ " have a Region-like dimension. More than "
+ explorations/research-metric-index-max-metrics " matches are truncated to the top "
+ explorations/research-metric-index-max-metrics " with `truncated: true` – narrow"
+ " with `q`.")
+ :scope scope/agent-explorations-read
+ :args list-research-metrics-schema})
+
+ (handle [_ {:keys [q]} _ctx]
+ {:output (json/encode (explorations/research-metric-index {:q q}))}))
+
+(def list-research-metrics-tool
+ "The `list_research_metrics` tool."
+ (->ListResearchMetricsTool))
(def ^:private get-research-candidates-schema
[:map {:closed true}
[:q {:optional true} [:maybe :string]]
- [:metric_ids {:optional true} [:maybe [:sequential :int]]]])
-
-(mu/defn ^{:tool-name "get_research_candidates"
- :scope scope/agent-explorations-read}
- get-research-candidates-tool
- "Get the candidate dimensions for chosen research metrics. Pass `metric_ids` (up to 20, from
- `list_research_metrics`) and/or `q` (a case-insensitive substring of a metric or dimension
- name) — at least one is required. Each metric lists the `dimensions` it can be sliced by: the
- `id` to pass to `add_research_groups`, the `group` it belongs to, and a `name` only when this
- metric calls it something other than the group name. Each entry in `dimension_groups` states
- that group's types and interestingness once, plus the `metric_ids` it can slice. Every metric
- and dimension id you pass to `add_research_groups` must come from this tool. Requested ids you
- can't see come back as `missing_metric_ids`; a too-broad `q` returns the top matches with
- `truncated: true` — narrow the search or pass explicit `metric_ids`."
- [{:keys [q metric_ids]} :- get-research-candidates-schema]
- (cond
- (and (str/blank? q) (empty? metric_ids))
- {:output (str "Error: pass metric_ids (up to " explorations/research-candidates-max-metrics
- ", from list_research_metrics) and/or q (a search term). This tool reports"
- " dimensions for metrics you have already chosen; use list_research_metrics or"
- " search to choose them.")}
-
- (> (count metric_ids) explorations/research-candidates-max-metrics)
- {:output (str "Error: pass at most " explorations/research-candidates-max-metrics
- " metric_ids per call (got " (count metric_ids)
- "). Split the request into multiple calls.")}
-
- :else
+ [:metric_ids {:optional true}
+ [:maybe [:sequential {:max explorations/research-candidates-max-metrics} :int]]]])
+
+(tools/defrecoverable needs-metric-ids-or-q!
+ "`get_research_candidates` was called with neither `metric_ids` nor `q`."
+ {:payload [:map {:closed true}]}
+ [_]
+ {:message (str "Pass `metric_ids`, `q`, or both. This tool reports the candidate dimensions of"
+ " metrics that you have already chosen.")
+ :recovery [{:uses #{"list_research_metrics"}
+ :text "Call `list_research_metrics` to choose metric IDs."}
+ {:uses #{"search"}
+ :text "Call `search` with `entity_types` [\"metric\"] to find metrics by topic."}]})
+
+(defrecord GetResearchCandidatesTool []
+ tools/Tool
+ (declaration [_]
+ {:name "get_research_candidates"
+ :description (str "Get the candidate dimensions for chosen research metrics. Pass `metric_ids` (up to "
+ explorations/research-candidates-max-metrics ", from `list_research_metrics`)"
+ " or `q` (a case-insensitive substring of a metric or dimension name), or both; at"
+ " least one is required. Each metric lists the `dimensions` it can be sliced by:"
+ " the `id` to pass to `add_research_groups`, the `group` it belongs to, and a"
+ " `name` only when this metric calls it something other than the group name."
+ " Each entry in `dimension_groups` states that group's types and interestingness"
+ " once, plus the `metric_ids` it can slice. Every metric and dimension ID that you"
+ " pass to `add_research_groups` must come from this tool. Requested IDs that you"
+ " can't see come back as `missing_metric_ids`; a too-broad `q` returns the top"
+ " matches with `truncated: true` – narrow the search or pass explicit"
+ " `metric_ids`.")
+ :scope scope/agent-explorations-read
+ :args get-research-candidates-schema})
+
+ (handle [_ {:keys [q metric_ids]} _ctx]
+ (when (and (str/blank? q) (empty? metric_ids))
+ (needs-metric-ids-or-q! {}))
{:output (json/encode (explorations/research-candidates {:metric-ids metric_ids :q q}))}))
-(defn- research-groups-payload
- "Validate `groups` and hydrate the FE picker payload for them, in the snake_case shape the
- client consumes."
- [groups]
- (explorations/exploration-data->api (explorations/research-groups {:groups groups})))
+(def get-research-candidates-tool
+ "The `get_research_candidates` tool."
+ (->GetResearchCandidatesTool))
(def ^:private summary-max-names
"How many dimension names one summary line spells out before falling back to a count. A metric
@@ -127,11 +145,158 @@
LLM sees of the result."
15)
-(defn- summarize-names [names]
- (let [extra (- (count names) summary-max-names)]
- (if (pos? extra)
- (str (str/join ", " (take summary-max-names names)) " and " extra " more")
- (str/join ", " names))))
+(defn- summarize-names
+ ([names] (summarize-names names summary-max-names))
+ ([names max-names]
+ (let [extra (- (count names) max-names)]
+ (if (pos? extra)
+ (str (str/join ", " (take max-names names)) " and " extra " more")
+ (str/join ", " names)))))
+
+(defn- not-found-sentence
+ "Report that the entities named by `noun` and `ids` were not found, without disclosing whether they exist."
+ [noun ids]
+ (if (next ids)
+ (str noun "s " (summarize-names (map str ids)) " were not found. They may not exist, or you may"
+ " not have access to them.")
+ (str noun " " (first ids) " was not found. It may not exist, or you may not have access to it.")))
+
+(def ^:private error-text-budget
+ "Maximum length of the error text from [[invalid-research-groups!]], including recovery steps.
+ Space goes to recovery steps first, then invalid IDs and candidate dimensions. The runtime
+ truncates error text at 4,000 characters."
+ 3000)
+
+(defn- invalid-dimensions-line
+ "Render a line listing `ids` as invalid dimensions for the metric in `entry`."
+ [{:keys [metric-id metric-name]} ids]
+ (str "- " (if (next ids) "Dimensions " "Dimension ")
+ (str/join ", " (map pr-str ids))
+ (if (next ids) " are not candidates" " is not a candidate")
+ " of metric " metric-id " (" metric-name ")."))
+
+(defn- left-over-line
+ "Render a line counting the invalid IDs in `left-over` and naming their metrics."
+ [left-over listed?]
+ (let [n (count (mapcat :dimension-ids left-over))
+ metrics (map (comp str :metric-id) left-over)]
+ (str "- " (when listed? "…and ") n (when listed? " more") " invalid dimension "
+ (if (= 1 n) "ID" "IDs") " on "
+ (if (next metrics) "metrics " "metric ") (summarize-names metrics) ".")))
+
+(defn- invalid-dimensions-lines
+ "List the first `k` invalid dimension IDs and count the rest in a final line."
+ [invalid-dimensions k]
+ (let [[listed left-over] (reduce (fn [[listed left-over k] {ids :dimension-ids :as entry}]
+ (let [n (min k (count ids))]
+ [(cond-> listed
+ (pos? n) (conj (invalid-dimensions-line entry (take n ids))))
+ (cond-> left-over
+ (< n (count ids)) (conj (update entry :dimension-ids
+ #(drop n %))))
+ (- k n)]))
+ [[] [] k]
+ invalid-dimensions)]
+ (cond-> listed
+ (seq left-over) (conj (left-over-line left-over (seq listed))))))
+
+(defn- lookup-step
+ "Build a recovery step to look up candidates for the metrics in `invalid-dimensions`.
+ List at most two batches of IDs, using the batch size accepted by `get_research_candidates`."
+ [invalid-dimensions]
+ (let [per-call explorations/research-candidates-max-metrics
+ batches (partition-all per-call (map :metric-id invalid-dimensions))]
+ {:uses #{"get_research_candidates"}
+ :text (str "Call `get_research_candidates` with `metric_ids` "
+ (str/join ", then with " (map #(str "[" (str/join ", " %) "]") (take 2 batches)))
+ (when (nthnext batches 2)
+ (str ", and so on for the other metrics, " per-call " at a time,"))
+ " to see every candidate.")}))
+
+(defn- candidates-step
+ "Build a recovery step listing up to `per-metric` candidates for each metric in `invalid-dimensions`."
+ [invalid-dimensions per-metric]
+ {:uses #{}
+ :text (te/lines
+ "Candidate dimensions by metric:"
+ (for [{:keys [metric-id metric-name candidates]} invalid-dimensions]
+ (str "- Metric " metric-id " (" metric-name "): "
+ (if (seq candidates)
+ (summarize-names (map #(str (pr-str (:id %)) " (" (:name %) ")") candidates)
+ per-metric)
+ "none"))))})
+
+(tools/defrecoverable invalid-research-groups!
+ "Report groups in `add_research_groups` that can't be added.
+ Their metric wasn't found, they replace the automatic dimensions with none, or they name dimension
+ IDs that aren't candidates of their metric."
+ {:payload [:map {:closed true}
+ [:unknown-metric-ids {:optional true} [:sequential {:min 1} :int]]
+ [:replace-without-dimensions {:optional true} [:sequential {:min 1} :int]]
+ [:invalid-dimensions {:optional true}
+ [:sequential {:min 1}
+ [:map {:closed true}
+ [:metric-id :int]
+ [:metric-name :string]
+ [:dimension-ids [:sequential {:min 1} :string]]
+ [:candidates [:sequential [:map {:closed true}
+ [:id :string]
+ [:name :string]]]]]]]]}
+ [{:keys [unknown-metric-ids replace-without-dimensions invalid-dimensions]}]
+ (let [head (te/lines
+ "None of the groups were added:"
+ (when (seq unknown-metric-ids)
+ (str "- " (not-found-sentence "Metric" unknown-metric-ids)))
+ (when (seq replace-without-dimensions)
+ (str "- " (if (next replace-without-dimensions)
+ (str "The groups for metrics "
+ (summarize-names (map str replace-without-dimensions)) " set")
+ (str "The group for metric " (first replace-without-dimensions) " sets"))
+ " `replace_default_dimensions` with no `dimension_ids`.")))
+ steps (cond-> []
+ (seq unknown-metric-ids)
+ (conj {:uses #{"list_research_metrics" "get_research_candidates"}
+ :text (str "Call `list_research_metrics` to find metrics that are available"
+ " for research, and take their IDs from `get_research_candidates`.")})
+
+ (seq replace-without-dimensions)
+ (conj {:uses #{}
+ :text (str "Pass the IDs of the dimensions to use, or omit"
+ " `replace_default_dimensions` to keep the automatic selection.")})
+
+ (seq invalid-dimensions)
+ (conj {:uses #{}
+ :text (str "A dimension ID belongs to one metric, so the same dimension has a"
+ " different ID for each metric. Take each group's IDs from its"
+ " own metric's candidates.")}
+ (lookup-step invalid-dimensions)))
+ text-size (fn [message steps] (count (str/join "\n" (cons message (map :text steps)))))
+ room (- error-text-budget (text-size head steps) 1)
+ n-bad (count (mapcat :dimension-ids invalid-dimensions))
+ fits? #(<= (count (str/join "\n" (invalid-dimensions-lines invalid-dimensions %))) room)
+ listed (if (fits? n-bad) n-bad (or (last (take-while fits? (range n-bad))) 0))
+ message (te/lines head (invalid-dimensions-lines invalid-dimensions listed))]
+ {:message message
+ :recovery (cond-> steps
+ (seq invalid-dimensions)
+ (into (take 1 (filter #(<= (text-size message (conj steps %)) error-text-budget)
+ (map #(candidates-step invalid-dimensions %)
+ (range summary-max-names 0 -1))))))}))
+
+(defn- research-groups-payload
+ "Validate `groups` and hydrate the FE picker payload for them.
+ The payload has the snake_case keys that the client reads. Invalid groups raise
+ [[invalid-research-groups!]], which names their problems."
+ [groups]
+ (explorations/exploration-data->api
+ (try
+ (explorations/research-groups {:groups groups})
+ (catch clojure.lang.ExceptionInfo e
+ (let [problems (select-keys (ex-data e)
+ [:unknown-metric-ids :replace-without-dimensions :invalid-dimensions])]
+ (if (seq problems)
+ (invalid-research-groups! problems)
+ (throw e)))))))
(defn- format-added-groups
"Plain-text summary of the groups `add_research_groups` just applied — the whole of what the
@@ -145,10 +310,7 @@
d (:dimensions g)]
[(:id d) i]))
group-names (mapv :name dimension_groups)
- ;; Nil for a dimension the payload doesn't group: groups are validated against the
- ;; unresolved catalog, so a dimension can pass validation and still be dropped from the
- ;; hydrated metrics because their query can't actually break out on it. The summary skips
- ;; what it can't name rather than failing the whole tool call.
+ ;; Nil for an id that no group holds, which the summary skips rather than fail the call.
group-name (fn [dimension-id] (some-> (group-idx dimension-id) group-names))]
(te/lines
(str "Added " (count groups) " group(s) to the research plan:")
@@ -163,25 +325,34 @@
(def ^:private add-research-groups-schema
[:map {:closed true}
[:groups
- [:sequential
+ [:sequential {:min 1 :error/message "must list at least one group"}
[:map {:closed true}
[:metric_id :int]
[:dimension_ids {:optional true} [:sequential :string]]
[:replace_default_dimensions {:optional true} :boolean]]]]])
-(mu/defn ^{:tool-name "add_research_groups"
- :scope scope/agent-explorations-write}
- add-research-groups-tool
- "Add one or more groups to the research artifact. Each group is a metric sliced by chosen
- dimensions: `{\"metric_id\": <id>, \"dimension_ids\": [<id>, ...]}`. By default
- `dimension_ids` are added on top of the automatically-selected interesting dimensions; omit
- it to use only the automatic selection. To pin the metric to exactly the dimensions you
- list (no automatic ones), also pass `\"replace_default_dimensions\": true` - then
- `dimension_ids` must be non-empty."
- [{:keys [groups]} :- add-research-groups-schema]
- (let [payload (research-groups-payload groups)]
- {:output (format-added-groups payload)
- :data-parts [(streaming/research-plan-update-part payload)]}))
+(defrecord AddResearchGroupsTool []
+ tools/Tool
+ (declaration [_]
+ {:name "add_research_groups"
+ :description (str "Add one or more groups to the research artifact. Each group is a metric sliced"
+ " by chosen dimensions: `{\"metric_id\": <id>, \"dimension_ids\": [<id>, ...]}`."
+ " By default `dimension_ids` are added on top of the automatically-selected"
+ " interesting dimensions; omit it to use only the automatic selection. To pin the"
+ " metric to exactly the dimensions you list (no automatic ones), also pass"
+ " `\"replace_default_dimensions\": true` - then `dimension_ids` must be"
+ " non-empty.")
+ :scope scope/agent-explorations-write
+ :args add-research-groups-schema})
+
+ (handle [_ {:keys [groups]} _ctx]
+ (let [payload (research-groups-payload groups)]
+ {:output (format-added-groups payload)
+ :data-parts [(streaming/research-plan-update-part payload)]})))
+
+(def add-research-groups-tool
+ "The `add_research_groups` tool."
+ (->AddResearchGroupsTool))
(def ^:private remove-from-research-plan-schema
[:map {:closed true}
@@ -193,46 +364,88 @@
[:dimension_ids [:sequential :string]]]]]
[:timeline_ids {:optional true} [:sequential :int]]])
-(mu/defn ^{:tool-name "remove_from_research_plan"
- :scope scope/agent-explorations-write}
- remove-from-research-plan-tool
- "Remove groups, individual dimensions within a group, or timelines from the research plan.
- Address groups by the `block_id` shown in brackets for each group in the current research
- plan (e.g. `metric:42`).
-
- - To drop whole groups, pass `block_ids`: `{\"block_ids\": [\"metric:42\"]}`. Use this when the
- user no longer wants a metric at all (e.g. \"actually I don't care about revenue\").
- - To prune within a group, pass `members` with the `dimension_ids` to stop slicing that
- group's metric by: `{\"members\": [{\"block_id\": \"metric:42\", \"dimension_ids\": [\"d1\"]}]}`.
- - To drop timelines, pass `timeline_ids` (the ids shown in the current plan's selected
- timelines): `{\"timeline_ids\": [7]}`.
-
- If removing members would leave a group with nothing in it, the whole group is dropped — so to
- remove an entire group prefer `block_ids` directly. Removing a block, member, or id that isn't
- in the plan is a no-op."
- [{:keys [block_ids members timeline_ids]} :- remove-from-research-plan-schema]
- {:output (json/encode {:block_ids block_ids
- :members members
- :timeline_ids timeline_ids})})
+(defrecord RemoveFromResearchPlanTool []
+ tools/Tool
+ (declaration [_]
+ {:name "remove_from_research_plan"
+ :description (te/lines
+ (str "Remove groups, individual dimensions within a group, or timelines from the"
+ " research plan. Address groups by the `block_id` shown in brackets for each"
+ " group in the current research plan (e.g. `metric:42`).")
+ ""
+ (str "- To drop whole groups, pass `block_ids`: `{\"block_ids\": [\"metric:42\"]}`."
+ " Use this when the user no longer wants a metric at all (e.g. \"actually I"
+ " don't care about revenue\").")
+ (str "- To prune within a group, pass `members` with the `dimension_ids` to stop"
+ " slicing that group's metric by: `{\"members\": [{\"block_id\": \"metric:42\","
+ " \"dimension_ids\": [\"d1\"]}]}`.")
+ (str "- To drop timelines, pass `timeline_ids` (the ids shown in the current plan's"
+ " selected timelines): `{\"timeline_ids\": [7]}`.")
+ ""
+ (str "If removing members would leave a group with nothing in it, the whole group is"
+ " dropped – so to remove an entire group prefer `block_ids` directly. Removing"
+ " a block, member, or id that isn't in the plan is a no-op."))
+ :scope scope/agent-explorations-write
+ :args remove-from-research-plan-schema})
+
+ (handle [_ {:keys [block_ids members timeline_ids]} _ctx]
+ {:output (json/encode {:block_ids block_ids
+ :members members
+ :timeline_ids timeline_ids})}))
+
+(def remove-from-research-plan-tool
+ "The `remove_from_research_plan` tool."
+ (->RemoveFromResearchPlanTool))
(def ^:private set-exploration-name-schema
[:map {:closed true}
- [:name :string]])
+ [:name [:string {:min 1}]]])
+
+(defrecord SetResearchNameTool []
+ tools/Tool
+ (declaration [_]
+ {:name "set_research_name"
+ :description "Set the name of the research artifact."
+ :scope scope/agent-explorations-write
+ :args set-exploration-name-schema})
-(mu/defn ^{:tool-name "set_research_name"
- :scope scope/agent-explorations-write}
- set-exploration-name-tool
- "Set the name of the research artifact."
- [{:keys [name]} :- set-exploration-name-schema]
- {:output (json/encode {:name name})})
+ (handle [_ {:keys [name]} _ctx]
+ {:output (json/encode {:name name})}))
+
+(def set-exploration-name-tool
+ "The `set_research_name` tool."
+ (->SetResearchNameTool))
(def ^:private select-exploration-timelines-schema
[:map {:closed true}
- [:timeline_ids [:sequential :int]]])
-
-(mu/defn ^{:tool-name "select_research_timelines"
- :scope scope/agent-explorations-write}
- select-exploration-timelines-tool
- "Select the timelines to include in the research. Populates the research artifact with the chosen timelines."
- [{:keys [timeline_ids]} :- select-exploration-timelines-schema]
- {:output (json/encode {:timeline_ids timeline_ids})})
+ [:timeline_ids [:sequential {:min 1 :error/message "must list at least one timeline ID"} :int]]])
+
+(tools/defrecoverable unknown-timeline!
+ "Report timeline IDs in `select_research_timelines` that the user cannot list."
+ {:payload [:map {:closed true}
+ [:timeline-ids [:sequential {:min 1} :int]]]}
+ [{:keys [timeline-ids]}]
+ {:message (not-found-sentence "Timeline" timeline-ids)
+ :recovery [{:uses #{"list_timelines"}
+ :text "Call `list_timelines` and use IDs from its result."}]})
+
+(defrecord SelectResearchTimelinesTool []
+ tools/Tool
+ (declaration [_]
+ {:name "select_research_timelines"
+ :description (str "Add timelines to the research plan using the IDs returned by `list_timelines`."
+ " Timelines already in the plan stay; to drop one, use"
+ " `remove_from_research_plan`.")
+ :scope scope/agent-explorations-write
+ :args select-exploration-timelines-schema})
+
+ (handle [_ {:keys [timeline_ids]} _ctx]
+ ;; The client silently drops timelines that it cannot list, so it would report an unchecked ID as added.
+ (let [visible (into #{} (map :id) (timeline/list-timelines))]
+ (when-let [unknown (not-empty (into [] (comp (remove visible) (distinct)) timeline_ids))]
+ (unknown-timeline! {:timeline-ids unknown})))
+ {:output (json/encode {:timeline_ids timeline_ids})}))
+
+(def select-exploration-timelines-tool
+ "The `select_research_timelines` tool."
+ (->SelectResearchTimelinesTool))
diff --git a/test/metabase/explorations/impl_test.clj b/test/metabase/explorations/impl_test.clj
index 51228cee065..bdedef8b2f4 100644
--- a/test/metabase/explorations/impl_test.clj
+++ b/test/metabase/explorations/impl_test.clj
@@ -5,6 +5,7 @@
[metabase.explorations.impl :as explorations.impl]
[metabase.lib.core :as lib]
[metabase.lib.metadata :as lib.metadata]
+ [metabase.metrics.core :as metrics]
[metabase.test :as mt]
[metabase.test.fixtures :as fixtures]
[metabase.util :as u]
@@ -34,19 +35,20 @@
(thunk))))
(defn- insert-n-metrics!
- "Insert `n` metric Cards and return the set of their ids."
+ "Insert and sync `n` metric Cards, returning the set of their IDs."
[n]
(let [q (count-metric-query :orders)]
(set (for [_ (range n)]
- (t2/insert-returning-pk! :model/Card
- {:name (mt/random-name)
- :type :metric
- :creator_id (mt/user->id :crowberto)
- :database_id (mt/id)
- :table_id (mt/id :orders)
- :display :scalar
- :visualization_settings {}
- :dataset_query q})))))
+ (u/prog1 (t2/insert-returning-pk! :model/Card
+ {:name (mt/random-name)
+ :type :metric
+ :creator_id (mt/user->id :crowberto)
+ :database_id (mt/id)
+ :table_id (mt/id :orders)
+ :display :scalar
+ :visualization_settings {}
+ :dataset_query q})
+ (metrics/sync-dimensions! :metadata/metric <>))))))
(deftest target-resolvable?-test
(testing "target-resolvable? reuses a prebuilt query and breakoutable columns"
@@ -84,7 +86,7 @@
(is (= 2 @calls))))))
(deftest query-count-does-not-scale-with-metric-count-test
- (testing "exploration-data issues a ~constant number of DB queries regardless of metric count"
+ (testing "exploration-data issues a ~constant number of DB queries for synced metrics"
;; Before batching, each extra metric added ~2 permission queries (an N+1). After batching,
;; adding metrics must not add per-metric queries.
(mt/with-test-user :rasta
@@ -349,21 +351,51 @@
(is (= [1 2] (sort (mapv :id (:metrics (explorations.impl/research-groups
{:groups [{:metric_id 1} {:metric_id 2}]})))))))))
-(deftest research-groups-hard-errors-test
+(defn- research-groups-problems
+ "Return the `ex-data` from [[explorations.impl/research-groups]] for invalid `groups`."
+ [groups]
+ (try
+ (explorations.impl/research-groups {:groups groups})
+ (catch clojure.lang.ExceptionInfo e
+ (ex-data e))))
+
+(deftest research-groups-reports-every-bad-id-test
(with-synthetic-metrics
- (testing "unknown metric id"
- (is (thrown-with-msg? Exception #"Unknown or inaccessible metric id 999"
- (explorations.impl/research-groups
- {:groups [{:metric_id 999}]}))))
- (testing "dimension that isn't a candidate of its metric"
- (is (thrown-with-msg? Exception #"not a candidate of metric"
- (explorations.impl/research-groups
- {:groups [{:metric_id 1 :dimension_ids ["region-2"]}]}))))
- (testing "replace_default_dimensions with no dimension_ids"
- (is (thrown-with-msg? Exception #"replace_default_dimensions requires"
- (explorations.impl/research-groups
- {:groups [{:metric_id 1 :replace_default_dimensions true}]}))))
- (testing "dimension the catalog still lists but query resolution drops"
+ (testing "every unknown metric id, not just the first"
+ (is (= {:unknown-metric-ids [999 1000]}
+ (research-groups-problems [{:metric_id 999} {:metric_id 1}
+ {:metric_id 1000} {:metric_id 999}]))))
+ (testing "every group that replaces the automatic dimensions with none"
+ (is (= {:replace-without-dimensions [1 2]}
+ (research-groups-problems [{:metric_id 1 :replace_default_dimensions true}
+ {:metric_id 2 :replace_default_dimensions true
+ :dimension_ids []}]))))
+ (testing "every dimension that isn't a candidate of its metric, with that metric's candidates"
+ (is (= {:invalid-dimensions [{:metric-id 1
+ :metric-name "Revenue"
+ :dimension-ids ["region-2" "nope"]
+ :candidates [{:id "region-1" :name "Region"}
+ {:id "plan-1" :name "Plan"}]}
+ {:metric-id 2
+ :metric-name "Churn"
+ :dimension-ids ["plan-1"]
+ :candidates [{:id "region-2" :name "Region"}]}]}
+ (research-groups-problems [{:metric_id 1 :dimension_ids ["region-1" "region-2"]}
+ {:metric_id 2 :dimension_ids ["plan-1"]}
+ {:metric_id 1 :dimension_ids ["nope"]}]))))
+ (testing "every kind of problem at once, with no further checks on a metric that isn't there"
+ (is (= {:unknown-metric-ids [999 1000]
+ :replace-without-dimensions [2]
+ :invalid-dimensions [{:metric-id 1
+ :metric-name "Revenue"
+ :dimension-ids ["wrong"]
+ :candidates [{:id "region-1" :name "Region"}
+ {:id "plan-1" :name "Plan"}]}]}
+ (research-groups-problems [{:metric_id 999 :dimension_ids ["anything"]}
+ {:metric_id 1 :dimension_ids ["wrong"]}
+ {:metric_id 1000 :replace_default_dimensions true}
+ {:metric_id 2 :replace_default_dimensions true}]))))
+ (testing "a dimension that the catalog still lists is rejected if query resolution removes it"
;; `plan-1` survives the cheap catalog but its target no longer resolves against the
;; metric's query, so it must be rejected rather than silently dropped from the payload.
(mt/with-dynamic-fn-redefs [explorations.impl/resolve-metric-queries
@@ -371,9 +403,12 @@
(mapv #(update % :dimensions
(fn [ds] (filterv (comp #{"region-1"} :id) ds)))
metrics))]
- (is (thrown-with-msg? Exception #"not a candidate of metric"
- (explorations.impl/research-groups
- {:groups [{:metric_id 1 :dimension_ids ["plan-1"]}]})))))))
+ (is (= [{:metric-id 1
+ :metric-name "Revenue"
+ :dimension-ids ["plan-1"]
+ :candidates [{:id "region-1" :name "Region"}]}]
+ (:invalid-dimensions
+ (research-groups-problems [{:metric_id 1 :dimension_ids ["plan-1"]}]))))))))
;;; ------------------------------------------ exploration-data ------------------------------------------
diff --git a/test/metabase/metabot/tools/explorations_test.clj b/test/metabase/metabot/tools/explorations_test.clj
index 745b1b957f6..01c7b84929f 100644
--- a/test/metabase/metabot/tools/explorations_test.clj
+++ b/test/metabase/metabot/tools/explorations_test.clj
@@ -3,38 +3,50 @@
[clojure.string :as str]
[clojure.test :refer :all]
[metabase.api-scope.core :as api-scope]
+ [metabase.explorations.core :as explorations]
+ [metabase.lib.core :as lib]
+ [metabase.lib.metadata :as lib.metadata]
[metabase.metabot.agent.messages :as messages]
[metabase.metabot.agent.profiles :as profiles]
[metabase.metabot.agent.streaming :as streaming]
[metabase.metabot.scope :as scope]
[metabase.metabot.self.core :as metabot.self]
+ [metabase.metabot.tools :as metabot.tools]
+ [metabase.metabot.tools.core :as tools.core]
[metabase.metabot.tools.explorations :as tools.explorations]
[metabase.test :as mt]
[metabase.util.json :as json]))
-(def ^:private exploration-tool-vars
- [#'tools.explorations/list-research-metrics-tool
- #'tools.explorations/get-research-candidates-tool
- #'tools.explorations/add-research-groups-tool
- #'tools.explorations/remove-from-research-plan-tool
- #'tools.explorations/set-exploration-name-tool
- #'tools.explorations/select-exploration-timelines-tool])
+(def ^:private research-scopes
+ "Scopes for a user with Metabot and NLQ enabled, as required by the Research profile."
+ (scope/user-metabot-perms->scopes {:permission/metabot :yes
+ :permission/metabot-nlq :yes}))
(deftest tools-declare-registered-scopes-granted-to-nlq-users-test
- (testing "every exploration tool declares a registered :scope, so the per-tool scope check applies
- (a tool with no :scope skips wrap-with-scope-check entirely), AND an NLQ-yes user is
- granted that scope — so adding the gate does not filter the tools away from the
- NLQ-gated :explorations profile that offers them"
- (let [nlq-scopes (scope/user-metabot-perms->scopes {:permission/metabot :yes
- :permission/metabot-nlq :yes})]
- (doseq [tool-var exploration-tool-vars]
- (let [{tool-name :tool-name required-scope :scope} (meta tool-var)]
- (testing tool-name
- (is (some? required-scope) "declares a :scope")
- (when required-scope
- (is (api-scope/registered-scope? required-scope) "scope is registered")
- (is (api-scope/scope-matches? nlq-scopes required-scope)
- "scope is granted to an NLQ-yes user"))))))))
+ (testing "each Research tool declares a registered scope available to users with NLQ enabled"
+ (doseq [tool [tools.explorations/list-research-metrics-tool
+ tools.explorations/get-research-candidates-tool
+ tools.explorations/add-research-groups-tool
+ tools.explorations/remove-from-research-plan-tool
+ tools.explorations/set-exploration-name-tool
+ tools.explorations/select-exploration-timelines-tool]]
+ (let [{tool-name :name required-scope :scope} (tools.core/declaration tool)]
+ (testing tool-name
+ (is (some? required-scope) "declares a :scope")
+ (when required-scope
+ (is (api-scope/registered-scope? required-scope) "scope is registered")
+ (is (api-scope/scope-matches? research-scopes required-scope)
+ "scope is granted to an NLQ-yes user")))))))
+
+(defn- research-call
+ "Run a tool call through the Research profile and return its result.
+ The call runs as a user with `research-scopes`. The outcome is the `:output` that the model reads,
+ plus `:error` when the call failed."
+ [tool-name args]
+ (binding [scope/*current-user-scope* research-scopes]
+ (let [entries (metabot.tools/->entries (:tools (profiles/get-profile :explorations))
+ (atom {}) nil :explorations)]
+ ((:fn (get entries tool-name)) args))))
(defn- decoded-output
"The exploration tools return `{:output <json-string>}` (only `:output` survives onto the
@@ -43,21 +55,35 @@
(json/decode+kw (:output result)))
(deftest ^:parallel get-research-candidates-requires-a-filter-test
- (testing "an argument-less call is rejected with an instructive error (the unfiltered catalog is
- the unbounded payload this tool's contract exists to prevent)"
+ (testing "a call without `metric_ids` or `q` reports a recoverable error and explains how to choose metrics"
(doseq [args [{} {:q nil} {:q ""} {:metric_ids nil} {:metric_ids []} {:q " " :metric_ids []}]]
(testing (pr-str args)
- (let [{:keys [output]} (tools.explorations/get-research-candidates-tool args)]
- (is (str/starts-with? output "Error:"))
- (is (str/includes? output "list_research_metrics")))))))
+ (is (= {:output (str "Pass `metric_ids`, `q`, or both. This tool reports the candidate"
+ " dimensions of metrics that you have already chosen.\n"
+ "Call `list_research_metrics` to choose metric IDs.\n"
+ "Call `search` with `entity_types` [\"metric\"] to find metrics by topic.")
+ :error {:class :recoverable :code ::tools.explorations/needs-metric-ids-or-q}}
+ (research-call "get_research_candidates" args)))))))
(deftest ^:parallel get-research-candidates-caps-metric-ids-test
- (testing "more than the per-call cap of metric_ids is rejected, naming the cap and the count"
- (let [{:keys [output]} (tools.explorations/get-research-candidates-tool
- {:metric_ids (vec (range 21))})]
- (is (str/starts-with? output "Error:"))
- (is (str/includes? output "at most 20"))
- (is (str/includes? output "got 21")))))
+ (testing "a call rejects more than the supported number of metric IDs"
+ (is (= {:output (str "Invalid tool arguments: `metric_ids` should have at most 20 elements;"
+ " received an array.")
+ :error {:class :validation :code :invalid-arguments}}
+ (research-call "get_research_candidates" {:metric_ids (vec (range 1 22))})))))
+
+(deftest ^:parallel empty-plan-edits-are-argument-errors-test
+ (testing "empty group lists, timeline lists and names are rejected"
+ (doseq [[tool-name args expected] [["add_research_groups" {:groups []}
+ "`groups` must list at least one group; received an array."]
+ ["select_research_timelines" {:timeline_ids []}
+ "`timeline_ids` must list at least one timeline ID; received an array."]
+ ["set_research_name" {:name ""}
+ "`name` should be at least 1 character; received a string."]]]
+ (testing tool-name
+ (is (= {:output (str "Invalid tool arguments: " expected)
+ :error {:class :validation :code :invalid-arguments}}
+ (research-call tool-name args)))))))
;;; ------------------------------------ add_research_groups ------------------------------------
@@ -86,8 +112,8 @@
{:metric_id 1 :dimension_ids ["d1"] :replace_default_dimensions true}
{:metric_id 2}])]
(mt/with-dynamic-fn-redefs [tools.explorations/research-groups-payload (fn [_] payload)]
- (let [{:keys [output data-parts]} (tools.explorations/add-research-groups-tool
- {:groups (:groups payload)})]
+ (let [{:keys [output data-parts]} (research-call "add_research_groups"
+ {:groups (:groups payload)})]
(testing "the payload is on the data part, not in :output"
(is (= [{:type :data :data-type "research_plan_update" :data payload}] data-parts)))
(testing ":output is prose naming what the user got, not the payload"
@@ -98,17 +124,14 @@
output))))))))
(deftest add-research-groups-summary-tolerates-unnamed-dimensions-test
- (testing (str "groups are validated against the unresolved catalog, so a dimension can pass "
- "validation and still be absent from the hydrated payload (its metric's query "
- "can't break out on it) — the summary skips what it can't name rather than "
+ (testing (str "the summary skips a dimension ID that no group in the payload holds, rather than "
"throwing away the whole tool call")
(let [payload (assoc (picker-payload 1)
:groups [{:metric_id 0 :dimension_ids ["d0" "unresolved"]}])]
(mt/with-dynamic-fn-redefs [tools.explorations/research-groups-payload (fn [_] payload)]
(is (= (str "Added 1 group(s) to the research plan:\n"
"- Metric 0, by: Orders - Region, plus the automatic selection")
- (:output (tools.explorations/add-research-groups-tool
- {:groups (:groups payload)}))))))))
+ (:output (research-call "add_research_groups" {:groups (:groups payload)}))))))))
(deftest add-research-groups-summary-is-bounded-test
(testing "a metric can be sliced by a long dimension list, so the summary counts the tail
@@ -116,38 +139,226 @@
(let [summary-for (fn [n-dims]
(let [payload (wide-metric-payload n-dims)]
(mt/with-dynamic-fn-redefs [tools.explorations/research-groups-payload (fn [_] payload)]
- (:output (tools.explorations/add-research-groups-tool
- {:groups (:groups payload)})))))
+ (:output (research-call "add_research_groups"
+ {:groups (:groups payload)})))))
fifty (summary-for 50)]
(testing "the tail past the first `summary-max-names` members is counted, not listed"
(is (str/includes? fifty "and 35 more")))
(testing "so a 10x longer dimension list costs only the extra digits in that count"
(is (> 5 (- (count (summary-for 500)) (count fifty))))))))
+(defn- add-groups-rejected-with
+ "Return the model's result when `research-groups` rejects a call with `problems` as its ex-data."
+ [problems]
+ (mt/with-dynamic-fn-redefs [explorations/research-groups
+ (fn [_] (throw (ex-info "Invalid research groups" problems)))]
+ (research-call "add_research_groups" {:groups [{:metric_id 1}]})))
+
+(deftest add-research-groups-reports-every-problem-at-once-test
+ (testing "one error lists every problem so that the model can fix them in one retry"
+ (is (= {:output (str "None of the groups were added:\n"
+ "- Metrics 999, 1000 were not found. They may not exist, or you may not have"
+ " access to them.\n"
+ "- The group for metric 2 sets `replace_default_dimensions` with no"
+ " `dimension_ids`.\n"
+ "- Dimensions \"region-2\", \"nope\" are not candidates of metric 1"
+ " (Revenue).\n"
+ "- Dimension \"plan-1\" is not a candidate of metric 3 (Churn).\n"
+ "Call `list_research_metrics` to find metrics that are available for"
+ " research, and take their IDs from `get_research_candidates`.\n"
+ "Pass the IDs of the dimensions to use, or omit `replace_default_dimensions` to"
+ " keep the automatic selection.\n"
+ "A dimension ID belongs to one metric, so the same dimension has a different"
+ " ID for each metric. Take each group's IDs from its own metric's"
+ " candidates.\n"
+ "Call `get_research_candidates` with `metric_ids` [1, 3] to see every"
+ " candidate.\n"
+ "Candidate dimensions by metric:\n"
+ "- Metric 1 (Revenue): \"region-1\" (Region), \"plan-1\" (Plan)\n"
+ "- Metric 3 (Churn): none")
+ :error {:class :recoverable :code ::tools.explorations/invalid-research-groups}}
+ (add-groups-rejected-with
+ {:unknown-metric-ids [999 1000]
+ :replace-without-dimensions [2]
+ :invalid-dimensions [{:metric-id 1
+ :metric-name "Revenue"
+ :dimension-ids ["region-2" "nope"]
+ :candidates [{:id "region-1" :name "Region"}
+ {:id "plan-1" :name "Plan"}]}
+ {:metric-id 3
+ :metric-name "Churn"
+ :dimension-ids ["plan-1"]
+ :candidates []}]}))))
+ (testing "anything else that fails in validation still ends the turn"
+ (is (= {:class :unrecoverable :code :internal}
+ (:error (add-groups-rejected-with {:something "else"}))))))
+
+(deftest add-research-groups-cuts-candidates-to-fit-test
+ (testing "a long candidate list is counted rather than spelled out"
+ (is (str/includes? (:output (add-groups-rejected-with
+ {:invalid-dimensions
+ [{:metric-id 1
+ :metric-name "Revenue"
+ :dimension-ids ["nope"]
+ :candidates (vec (for [i (range 20)]
+ {:id (str "d" i) :name (str "D" i)}))}]}))
+ "\"d14\" (D14) and 5 more")))
+ (testing "candidates come last and are cut short, so the bad ids and the next steps fit"
+ (let [candidates (vec (for [i (range 15)]
+ {:id (format "00000000-0000-4000-8000-%012d" i)
+ :name (str "Customer acquisition channel " i)}))
+ {:keys [output]} (add-groups-rejected-with
+ {:invalid-dimensions (vec (for [m (range 1 6)]
+ {:metric-id m
+ :metric-name (str "Metric " m)
+ :dimension-ids [(str "wrong-" m)]
+ :candidates candidates}))})]
+ (is (> 4000 (count output)) "the runtime cuts a failure at 4,000 characters")
+ (doseq [m (range 1 6)]
+ (is (str/includes? output (str "Dimension \"wrong-" m "\" is not a candidate of metric " m))))
+ (is (str/includes? output "Call `get_research_candidates` with `metric_ids` [1, 2, 3, 4, 5]"))
+ (is (str/includes? output "Candidate dimensions by metric:\n- Metric 1 (Metric 1): ")))))
+
+(defn- uuids
+ "Dimension ids in UUID form, numbered from `from` (inclusive) to `to` (exclusive)."
+ [from to]
+ (mapv #(format "00000000-0000-4000-8000-%012d" %) (range from to)))
+
+(deftest add-research-groups-cuts-long-failure-lists-test
+ (testing "invalid IDs that do not fit are counted, leaving room for recovery steps"
+ (let [output (:output (add-groups-rejected-with
+ {:invalid-dimensions (vec (for [m (range 1 21)]
+ {:metric-id m
+ :metric-name (str "Metric " m)
+ :dimension-ids (uuids 1 6)
+ :candidates []}))}))
+ listed (count (re-seq #"\"00000000-0000-4000-8000-\d{12}\"" output))
+ [_ more] (re-find #"\n- …and (\d+) more invalid dimension IDs on metrics [\d, ]+20\.\n" output)]
+ (is (>= 3000 (count output)))
+ (is (= 100 (+ listed (parse-long more))))
+ (is (str/includes? output "\nA dimension ID belongs to one metric"))
+ (is (str/includes? output (str "\nCall `get_research_candidates` with `metric_ids` "
+ "[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19,"
+ " 20] to see every candidate.")))))
+ (testing "a metric whose bad ids don't all fit gets a line with the ones that do"
+ (let [output (:output (add-groups-rejected-with
+ {:invalid-dimensions [{:metric-id 1
+ :metric-name "Metric 1"
+ :dimension-ids (uuids 1 61)
+ :candidates []}
+ {:metric-id 2
+ :metric-name "Metric 2"
+ :dimension-ids (uuids 61 121)
+ :candidates []}]}))
+ listed (count (re-seq #"\"00000000-0000-4000-8000-\d{12}\"" output))
+ [_ more] (re-find #"\n- …and (\d+) more invalid dimension IDs on metric 2\.\n" output)]
+ (is (>= 3000 (count output)))
+ (is (= 120 (+ listed (parse-long more))))
+ (is (str/includes? output " are not candidates of metric 2 (Metric 2).\n- …and "))
+ (is (str/includes? output "\nCall `get_research_candidates` with `metric_ids` [1, 2] to see every candidate.")))))
+
+(deftest add-research-groups-counts-oversized-dimension-ids-test
+ (let [output (:output (add-groups-rejected-with
+ {:invalid-dimensions [{:metric-id 1
+ :metric-name "Revenue"
+ :dimension-ids [(apply str (repeat 3500 "x"))]
+ :candidates []}
+ {:metric-id 2
+ :metric-name "Orders"
+ :dimension-ids ["wrong"]
+ :candidates []}]}))]
+ (is (str/includes? output "- 2 invalid dimension IDs on metrics 1, 2.\n"))
+ (is (>= 3000 (count output)))
+ (is (str/includes? output "Call `get_research_candidates` with `metric_ids` [1, 2]"))))
+
+(deftest add-research-groups-suggests-lookups-within-the-limit-test
+ (testing "the suggested lookup respects the limit on metric IDs per call"
+ (let [output (:output (add-groups-rejected-with
+ {:invalid-dimensions (vec (for [m (range 1 22)]
+ {:metric-id m
+ :metric-name (str "Metric " m)
+ :dimension-ids ["wrong"]
+ :candidates []}))}))
+ lookup (re-find #"Call `get_research_candidates`[^\n]*" output)
+ batches (for [[_ ids] (re-seq #"\[([\d, ]+)\]" lookup)]
+ (mapv parse-long (str/split ids #", ")))]
+ (is (= [(range 1 21) [21]] batches))
+ (mt/with-test-user :crowberto
+ (doseq [batch batches]
+ (is (nil? (:error (research-call "get_research_candidates" {:metric_ids batch}))))))))
+ (testing "the recovery step lists at most two batches"
+ (let [output (:output (add-groups-rejected-with
+ {:invalid-dimensions (vec (for [m (range 1 61)]
+ {:metric-id m
+ :metric-name (str "Metric " m)
+ :dimension-ids ["wrong"]
+ :candidates []}))}))]
+ (is (>= 3000 (count output)))
+ (is (str/includes? output (str "\nCall `get_research_candidates` with `metric_ids` ["
+ (str/join ", " (range 1 21)) "], then with ["
+ (str/join ", " (range 21 41)) "], and so on for the other"
+ " metrics, 20 at a time, to see every candidate."))))))
+
+(defn- orders-count
+ "Return a metric query that counts orders."
+ []
+ (let [mp (mt/metadata-provider)]
+ (-> (lib/query mp (lib.metadata/table mp (mt/id :orders)))
+ (lib/aggregate (lib/count)))))
+
+(deftest research-workflow-against-the-real-catalog-test
+ (mt/with-test-user :crowberto
+ (mt/with-temp [:model/Card {metric-id :id} {:name "Order count"
+ :type :metric
+ :dataset_query (orders-count)}]
+ (let [listed (:metrics (decoded-output (research-call "list_research_metrics"
+ {:q "Order count"})))
+ candidates (-> (research-call "get_research_candidates" {:metric_ids [metric-id]})
+ decoded-output :metrics first :dimensions)]
+ (testing "the metric is listed, with candidate dimensions"
+ (is (some #(= metric-id (:id %)) listed))
+ (is (seq candidates)))
+ (testing "every dimension that get_research_candidates offers is accepted"
+ (let [outcome (research-call "add_research_groups"
+ {:groups [{:metric_id metric-id
+ :dimension_ids (mapv :id candidates)}]})]
+ (is (nil? (:error outcome)))
+ (is (str/starts-with? (:output outcome)
+ "Added 1 group(s) to the research plan:\n- Order count, by: "))))
+ (testing "a bad metric and a bad dimension are the model's to fix, both in one error"
+ (let [{:keys [output error]} (research-call "add_research_groups"
+ {:groups [{:metric_id Integer/MAX_VALUE}
+ {:metric_id metric-id
+ :dimension_ids ["not-a-dimension"]}]})]
+ (is (= {:class :recoverable :code ::tools.explorations/invalid-research-groups} error))
+ (is (str/includes? output (str "Metric " Integer/MAX_VALUE " was not found.")))
+ (is (str/includes? output (str "Dimension \"not-a-dimension\" is not a candidate of metric "
+ metric-id " (Order count).")))))))))
+
+;;; ------------------------------------ plan edits the client applies ------------------------------------
+
(deftest ^:parallel remove-from-research-plan-tool-test
(testing "echoes the block ids the agent asked to remove (pure-echo; the FE applies them)"
(is (= {:block_ids ["metric:42" "metric:43"] :members nil :timeline_ids nil}
(decoded-output
- (tools.explorations/remove-from-research-plan-tool
- {:block_ids ["metric:42" "metric:43"]})))))
+ (research-call "remove_from_research_plan" {:block_ids ["metric:42" "metric:43"]})))))
(testing "echoes member-level removals (deselect dimensions within a group)"
(is (= {:block_ids nil
:members [{:block_id "metric:42" :dimension_ids ["d1"]}
{:block_id "metric:43" :dimension_ids ["d2" "d3"]}]
:timeline_ids nil}
(decoded-output
- (tools.explorations/remove-from-research-plan-tool
- {:members [{:block_id "metric:42" :dimension_ids ["d1"]}
- {:block_id "metric:43" :dimension_ids ["d2" "d3"]}]})))))
+ (research-call "remove_from_research_plan"
+ {:members [{:block_id "metric:42" :dimension_ids ["d1"]}
+ {:block_id "metric:43" :dimension_ids ["d2" "d3"]}]})))))
(testing "echoes timeline removals"
(is (= {:block_ids nil :members nil :timeline_ids [7 9]}
(decoded-output
- (tools.explorations/remove-from-research-plan-tool
- {:timeline_ids [7 9]})))))
+ (research-call "remove_from_research_plan" {:timeline_ids [7 9]})))))
(testing "an empty list is valid (a no-op removal)"
(is (= {:block_ids [] :members nil :timeline_ids nil}
(decoded-output
- (tools.explorations/remove-from-research-plan-tool {:block_ids []}))))))
+ (research-call "remove_from_research_plan" {:block_ids []}))))))
(defn- streamed-tool-output
"Run a tool `result` through the SSE serializer and return the decoded payload the FE would
@@ -186,15 +397,31 @@
(testing "set_research_name"
(is (= {:name "Quarterly revenue"}
(streamed-tool-output
- (tools.explorations/set-exploration-name-tool {:name "Quarterly revenue"})))))
- (testing "select_research_timelines"
- (is (= {:timeline_ids [3 5]}
- (streamed-tool-output
- (tools.explorations/select-exploration-timelines-tool {:timeline_ids [3 5]})))))
+ (research-call "set_research_name" {:name "Quarterly revenue"})))))
(testing "remove_from_research_plan"
(is (= {:block_ids ["metric:42"] :members nil :timeline_ids nil}
(streamed-tool-output
- (tools.explorations/remove-from-research-plan-tool {:block_ids ["metric:42"]})))))))
+ (research-call "remove_from_research_plan" {:block_ids ["metric:42"]})))))))
+
+(deftest select-research-timelines-test
+ (mt/with-test-user :crowberto
+ (mt/with-temp [:model/Collection {coll-id :id} {:name "Research timelines"}
+ :model/Timeline {releases :id} {:name "Releases" :collection_id coll-id}
+ :model/Timeline {launches :id} {:name "Launches" :collection_id coll-id}
+ :model/Timeline {archived :id} {:name "Old launches"
+ :collection_id coll-id
+ :archived true}]
+ (testing "streams the ids for the FE to add, the same way as the other plan edits"
+ (is (= {:timeline_ids [releases launches]}
+ (streamed-tool-output
+ (research-call "select_research_timelines" {:timeline_ids [releases launches]})))))
+ (testing "reports every timeline ID that the client would skip because the user cannot list it"
+ (is (= {:output (str "Timelines " archived ", " Integer/MAX_VALUE " were not found. They may"
+ " not exist, or you may not have access to them.\n"
+ "Call `list_timelines` and use IDs from its result.")
+ :error {:class :recoverable :code ::tools.explorations/unknown-timeline}}
+ (research-call "select_research_timelines"
+ {:timeline_ids [releases archived Integer/MAX_VALUE archived]})))))))
;;; ----------------------------------------- Research plan → system prompt -----------------------------------------