Skip to content

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

Edit chart fix (#71424)

lbrdnk3bd3bf5b6ab0
diff --git a/resources/metabot/prompts/tools/edit_chart.md b/resources/metabot/prompts/tools/edit_chart.md
new file mode 100644
index 00000000000..07c84c22ec4
--- /dev/null
+++ b/resources/metabot/prompts/tools/edit_chart.md
@@ -0,0 +1,22 @@
+Edit the chart settings of an existing chart.
+This tool changes the chart type (e.g., bar chart to line chart, table to pie chart) but does not modify the underlying data or SQL query.
+It will return a new chart with the updated settings.
+
+**Usage:**
+- Use this tool when the user wants to change the chart settings of an existing visualization
+- Use when converting between basic chart types (bar, line, pie, table, etc.)
+- Only use when there is an existing chart that needs its settings changed
+
+**When NOT to use:**
+- Do not use for data analysis or querying - this tool only changes chart settings
+- Do not use for detailed formatting (titles, colors, axes labels, styling)
+- Do not use when the user needs to modify the underlying data or SQL query
+- Do not use for creating new charts - only for editing existing ones
+- Avoid when the user wants complex customizations beyond basic chart type changes
+- Do not use when you don't have any chart in the conversation context, instead, state that you seem not to have access to the chart the user is referring to.
+
+**Limitations:**
+- Only changes the chart type, not detailed display settings
+- Cannot modify chart titles, colors, axis formatting, or styling
+- Does not modify data or perform calculations
+- Limited to basic chart type conversions
\ No newline at end of file
diff --git a/src/metabase/metabot/agent/core.clj b/src/metabase/metabot/agent/core.clj
index 9a47839afb7..5f802cafe68 100644
--- a/src/metabase/metabot/agent/core.clj
+++ b/src/metabase/metabot/agent/core.clj
@@ -356,6 +356,37 @@
state
(:user_is_viewing context)))
+(defn chart-config->chart
+ "Create chart structure from chart-config"
+ [id {:keys [query timeline_events image_base_64] :as chart-config}]
+ {:chart_id id
+ :queries [query]
+ :image_base_64 image_base_64
+ :timeline_events (or timeline_events [])
+ ;; TODO (lbrdnk 2026-03-25): Viz settings seem to be redundant wrt fix this PR is implementing. Figure out
+ ;; what is the reason behind that if any and either add it or drop.
+ :visualization_settings nil
+ :chart_config chart-config})
+
+(defn seed-charts
+ "Reduce the chart-configs from context into charts."
+ [state context]
+ (reduce
+ ;; This logic is flawed for items with more than 1 chart config. It expects at most 1 chart config per viewing item.
+ ;; TODO (lbrdnk 2026-03-24): Figure out what is reasonable solution here. (ie no overwriting single config)
+ (fn [acc {:keys [id chart_configs] :as _item}]
+ ;; TODO (lbrdnk 2026-03-24): This is developed against adhoc queries. Ensure other cases work too!
+ (if-not (seq chart_configs)
+ acc
+ (update acc :charts merge
+ (into {}
+ (map (comp
+ (juxt :chart_id identity)
+ (partial chart-config->chart id)))
+ chart_configs))))
+ state
+ (:user_is_viewing context)))
+
;;; Main loop
(defn- init-agent
@@ -368,7 +399,8 @@
base-tools (profiles/get-tools-for-profile profile-id capabilities)
seeded (-> (or state {})
(seed-state context)
- (seed-chart-configs context))
+ (seed-chart-configs context)
+ (seed-charts context))
memory (-> (memory/initialize messages seeded context)
(memory/load-queries-from-state seeded)
(memory/load-charts-from-state seeded)
diff --git a/src/metabase/metabot/agent/links.clj b/src/metabase/metabot/agent/links.clj
index 2f8ec3546f0..9e00ef36c35 100644
--- a/src/metabase/metabot/agent/links.clj
+++ b/src/metabase/metabot/agent/links.clj
@@ -36,6 +36,15 @@
(.getBytes "UTF-8")
codecs/bytes->b64-str)))
+(defn pseudo-card->link
+ "Convert map with relevant card keys into a link. Relevant keys are e.g. dataset_query, display, displayIsLocked."
+ [pc]
+ (str "/question#"
+ (-> pc
+ json/encode
+ (.getBytes "UTF-8")
+ codecs/bytes->b64-str)))
+
(defn- resolve-query-link
"Resolve a metabase://query/{id} link to a /question# URL."
[query-id queries-state]
diff --git a/src/metabase/metabot/api.clj b/src/metabase/metabot/api.clj
index 6d93f55867d..98d7cfcc22e 100644
--- a/src/metabase/metabot/api.clj
+++ b/src/metabase/metabot/api.clj
@@ -226,7 +226,10 @@
[:context ::metabot.context/context]
[:conversation_id ms/UUIDString]
[:history [:maybe ::metabot.schema/messages]]
- [:state :map]
+ [:state [:map
+ [:queries {:optional true} [:map-of :string :any]]
+ [:charts {:optional true} [:map-of :string :any]]
+ [:chart-configs {:optional true} [:map-of :string :any]]]]
[:debug {:optional true} [:maybe :boolean]]]]
(metabot.context/log body :llm.log/fe->be)
(streaming-request body))
diff --git a/src/metabase/metabot/tools/charts.clj b/src/metabase/metabot/tools/charts.clj
index 982634528ce..8a1aa233ec5 100644
--- a/src/metabase/metabot/tools/charts.clj
+++ b/src/metabase/metabot/tools/charts.clj
@@ -2,6 +2,8 @@
"Chart tool wrappers."
(:require
[medley.core :as m]
+ [metabase.metabot.agent.links :as links]
+ [metabase.metabot.agent.streaming :as streaming]
[metabase.metabot.tools.charts.create :as create-chart-tools]
[metabase.metabot.tools.charts.edit :as edit-chart-tools]
[metabase.metabot.tools.shared :as shared]
@@ -65,13 +67,32 @@
Provide a new chart_type in new_viz_settings."
[{:keys [chart_id new_viz_settings]} :- edit-chart-schema]
(try
- (let [result (edit-chart-tools/edit-chart
- {:chart-id chart_id
- :new-chart-type (keyword (get new_viz_settings :chart_type))
- :charts-state (shared/current-charts-state)})
+ (let [new-viz (keyword (get new_viz_settings :chart_type))
+ chart (get (shared/current-charts-state) chart_id)
+ queries (:queries chart)
+ query (first queries)
+
+ {:keys [new-chart-data result]}
+ (edit-chart-tools/edit-chart
+ {:chart-id chart_id
+ :new-chart-type new-viz
+ :charts-state (shared/current-charts-state)})
+
structured (assoc result :result-type :chart)]
+
+ ;; Add the new chart to memory so it can be referenced in the conversation going forward.
+ (when (and (:chart_id new-chart-data) shared/*memory-atom*)
+ (swap! shared/*memory-atom* assoc-in [:state :charts (:chart_id new-chart-data)]
+ new-chart-data))
+
{:output (format-chart-output structured)
- :structured-output structured})
+ :structured-output structured
+ :data-parts [(streaming/navigate-to-part
+ (links/pseudo-card->link
+ {:dataset_query query
+ :display new-viz
+ :displayIsLocked true}))]})
+
(catch Exception e
(log/error e "Error editing chart")
(if (:agent-error? (ex-data e))
diff --git a/src/metabase/metabot/tools/charts/edit.clj b/src/metabase/metabot/tools/charts/edit.clj
index 03b84b271c0..004f77a06bc 100644
--- a/src/metabase/metabot/tools/charts/edit.clj
+++ b/src/metabase/metabot/tools/charts/edit.clj
@@ -9,22 +9,27 @@
:scatter :waterfall :sankey :scalar :smartscalar :gauge
:progress :funnel :object :map})
-(defn- format-chart-for-llm
- "Format chart data as XML for LLM consumption."
- [{:keys [chart-id query-id chart-type query-content]}]
- (str "<chart id=\"" chart-id "\">\n"
- "The chart is powered by the following query:\n"
- "<query id=\"" query-id "\">\n"
- query-content "\n"
- "</query>\n"
- "<visualization>{\"chart_type\": \"" (name chart-type) "\"}</visualization>\n"
- "</chart>"))
-
(defn- format-chart-link
"Format a metabase:// link to the chart."
[chart-id]
(str "metabase://chart/" chart-id))
+(defn- format-chart-for-llm
+ "Format chart data as XML for LLM consumption."
+ [{:keys [chart_id queries] :as chart-data}]
+ (apply str
+ (into ["<chart id=\"" chart_id "\">\n"
+ "The chart is powered by the following queries:\n"]
+ (comp cat
+ (remove nil?))
+ [(for [query queries]
+ (str "\n<query>\n"
+ query "\n"
+ "</query>\n"))
+ [(when-some [viz (get-in chart-data [:visualization_settings :chart_type])]
+ (str "<visualization>{\"chart_type\": \"" (name viz) "\"}</visualization>\n"))
+ "\n</chart>"]])))
+
(defn edit-chart
"Edit an existing chart's visualization settings.
@@ -33,12 +38,15 @@
- new-chart-type: New chart type to use
- charts-state: Map of chart-id to chart data from agent state
- Returns a map with:
+ Returns a map with result and new-chart-data.
+
+ `new-chart-data`: format that could be stored directly in memory or state's :charts key.
+
+ `result`:
- :chart-id - New unique ID for the edited chart
- :chart-content - XML representation of the chart
- :chart-link - Metabase link to the chart
- - :chart-type - Type of chart created
- - :query-id - ID of the source query"
+ - :chart-type - Type of chart created"
[{:keys [chart-id new-chart-type charts-state]}]
(log/info "Editing chart" {:chart-id chart-id :new-chart-type new-chart-type})
@@ -49,38 +57,25 @@
{:agent-error? true
:chart-type new-chart-type})))
- ;; Look up chart from state
(let [chart-data (get charts-state (str chart-id))]
(when-not chart-data
(throw (ex-info "Sorry, I have issues accessing the chart data. Is there anything else I can help you with?"
{:agent-error? true
:chart-id chart-id})))
- (when-not (:query-id chart-data)
- (throw (ex-info "Sorry, I have issues accessing the chart data. Is there anything else I can help you with?"
- {:agent-error? true
- :chart-id chart-id})))
-
- ;; Create the new chart with updated settings
- (let [new-chart-id (str (random-uuid))
- query-id (:query-id chart-data)
- query-content (or (:query-content chart-data) "")
- new-chart-data {:chart-id new-chart-id
- :query-id query-id
- :chart-type new-chart-type
- :query-content query-content}]
-
- (log/info "Edited chart" {:old-chart-id chart-id
- :new-chart-id new-chart-id
- :new-chart-type new-chart-type})
+ (let [new-chart-data (-> chart-data
+ (assoc :chart_id (str (random-uuid)))
+ (assoc :visualization_settings {:chart_type new-chart-type}))]
- {:chart-id new-chart-id
- :chart-content (format-chart-for-llm new-chart-data)
- :chart-link (format-chart-link new-chart-id)
- :chart-type new-chart-type
- :query-id query-id
- :instructions (str "Chart has been created successfully.\n\n"
- "Next steps to present the chart to the user:\n"
- "- Always provide a direct link using: `[Chart](" (format-chart-link new-chart-id) ")` "
- "where Chart is a meaningful link text\n"
- "- If creating multiple charts, present all chart links")})))
+ {:new-chart-data new-chart-data
+ :result {:chart-id (:chart_id new-chart-data)
+ :chart-content (format-chart-for-llm new-chart-data)
+ :chart-link (format-chart-link (:chart_id new-chart-data))
+ :chart-type new-chart-type
+ :instructions (str "Chart has been created successfully.\n\n"
+ "Next steps to present the chart to the user:\n"
+ "- Always provide a direct link using: `[Chart]("
+ (format-chart-link (:chart_id new-chart-data))
+ ")` "
+ "where Chart is a meaningful link text\n"
+ "- If creating multiple charts, present all chart links")}})))
diff --git a/test/metabase/metabot/agent/core_test.clj b/test/metabase/metabot/agent/core_test.clj
index 9fd820e2e95..cdcae717715 100644
--- a/test/metabase/metabot/agent/core_test.clj
+++ b/test/metabase/metabot/agent/core_test.clj
@@ -3,6 +3,7 @@
[clojure.test :refer :all]
[metabase.analytics.prometheus :as prometheus]
[metabase.analytics.snowplow-test :as snowplow-test]
+ [metabase.lib.core :as lib]
[metabase.metabot.agent.analytics :as agent-analytics]
[metabase.metabot.agent.core :as agent]
[metabase.metabot.agent.memory :as memory]
@@ -288,7 +289,7 @@
llm-call-count (atom 0)
;; Scripted LLM responses - uses real table ID from test DB
llm-responses
- [ ;; Iteration 1: Search for orders table
+ [;; Iteration 1: Search for orders table
[{:type :start :id "msg-1"}
{:type :tool-input
:id "call-search-1"
@@ -753,7 +754,7 @@
self/call-llm (fn [& _]
(reset! classify-called true)
(throw (ex-info "LLM error" {})))]
- ;; Should not throw — exception is caught inside the background future
+ ;; Should not throw — exception is caught inside the background future
(run-agent-loop! {:messages [{:role :user :content "test"}]
:state {}
:context {}
@@ -762,3 +763,32 @@
:track-user-intent? true}})
(tu/poll-until 5000 @classify-called)
(is (true? @classify-called)))))))
+
+(deftest chart-configs-loaded-into-charts-test
+ (let [query (lib/native-query (mt/metadata-provider) "select 1")
+ chart-config {:display_type "pie"
+ :query query
+ :image_base_64 "asdf"
+ :series {}
+ :timeline_events []}
+ memory (-> (#'agent/init-agent {:profile-id :internal
+ :context {:user_is_viewing
+ [{:chart_configs [chart-config]}]}})
+ :memory-atom
+ deref)
+
+ chart-configs (get-in memory [:state :chart-configs])
+ chart-configs-key (first (keys chart-configs))
+ charts (get-in memory [:state :charts])
+ chart-key (first (keys charts))]
+ (testing "Loaded charts from chart configs into memory"
+ (is (string? chart-key))
+ (is (=? {chart-key {:chart_id chart-key
+ :timeline_events []
+ :queries [query]
+ :chart_config chart-config}}
+ charts)))
+ (testing "Loaded chart configs into memory"
+ (is (every? string? (keys chart-configs)))
+ (is (=? {chart-configs-key chart-config}
+ chart-configs)))))
diff --git a/test/metabase/metabot/tools/charts/edit_test.clj b/test/metabase/metabot/tools/charts/edit_test.clj
index 8d419f63e7c..e265234a914 100644
--- a/test/metabase/metabot/tools/charts/edit_test.clj
+++ b/test/metabase/metabot/tools/charts/edit_test.clj
@@ -2,49 +2,44 @@
(:require
[clojure.string :as str]
[clojure.test :refer :all]
- [metabase.metabot.tools.charts.edit :as edit-chart]))
+ [metabase.lib.core :as lib]
+ [metabase.metabot.tools.charts.edit :as edit-chart]
+ [metabase.test :as mt]))
(deftest edit-chart-test
(testing "edits a chart's visualization type"
- (let [charts-state {"chart-abc" {:chart-id "chart-abc"
- :query-id "q-123"
- :chart-type :bar
- :query-content "SELECT * FROM orders"}}
- result (edit-chart/edit-chart
- {:chart-id "chart-abc"
- :new-chart-type :line
- :charts-state charts-state})]
+ (let [mp (mt/metadata-provider)
+ charts-state {"chart-abc" {:chart-id "chart-abc"
+ :queries [(lib/native-query mp "SELECT * FROM orders")]
+ :chart-type :bar}}
+ {:keys [result]} (edit-chart/edit-chart
+ {:chart-id "chart-abc"
+ :new-chart-type :line
+ :charts-state charts-state})]
(is (contains? result :chart-id))
(is (string? (:chart-id result)))
;; New chart should have a different ID
(is (not= "chart-abc" (:chart-id result)))
(is (= :line (:chart-type result)))
- (is (= "q-123" (:query-id result)))
(is (str/includes? (:chart-content result) "<chart"))
(is (str/includes? (:chart-content result) "line"))
(is (str/starts-with? (:chart-link result) "metabase://chart/"))
(is (contains? result :instructions))))
(testing "edits chart to various types"
- (let [charts-state {"chart-456" {:chart-id "chart-456"
- :query-id "q-original"
- :chart-type :bar
- :query-content "SELECT COUNT(*) FROM users"}}]
+ (let [mp (mt/metadata-provider)
+ charts-state {"chart-456" {:chart-id "chart-456"
+ :queries [(lib/native-query mp "SELECT * FROM orders")]}}]
(doseq [new-type [:pie :table :scatter :area :sunburst]]
- (let [result (edit-chart/edit-chart
- {:chart-id "chart-456"
- :new-chart-type new-type
- :charts-state charts-state})]
+ (let [{:keys [result]} (edit-chart/edit-chart
+ {:chart-id "chart-456"
+ :new-chart-type new-type
+ :charts-state charts-state})]
(is (= new-type (:chart-type result))
- (str "New chart type " new-type " should be set correctly"))
- ;; Query ID should be preserved
- (is (= "q-original" (:query-id result)))))))
+ (str "New chart type " new-type " should be set correctly"))))))
(testing "throws error for invalid chart type"
- (let [charts-state {"chart-789" {:chart-id "chart-789"
- :query-id "q-test"
- :chart-type :bar
- :query-content "SELECT 1"}}]
+ (let [charts-state {"chart-789" {:chart-id "chart-789"}}]
(is (thrown-with-msg?
clojure.lang.ExceptionInfo
#"Invalid chart type"
@@ -60,15 +55,4 @@
(edit-chart/edit-chart
{:chart-id "nonexistent"
:new-chart-type :bar
- :charts-state {}}))))
-
- (testing "throws error when chart has no query-id"
- (let [charts-state {"chart-bad" {:chart-id "chart-bad"
- :chart-type :bar}}]
- (is (thrown-with-msg?
- clojure.lang.ExceptionInfo
- #"issues accessing the chart data"
- (edit-chart/edit-chart
- {:chart-id "chart-bad"
- :new-chart-type :line
- :charts-state charts-state}))))))
+ :charts-state {}})))))