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
Store Metabot conversation history with token usage and report it to HM (#63073)
Oleksandr Solovyov065d6ce5aa7a
diff --git a/enterprise/backend/src/metabase_enterprise/metabot_v3/api.clj b/enterprise/backend/src/metabase_enterprise/metabot_v3/api.cljindex 1bc78f04d0d..1a7c8de75e2 100644--- a/enterprise/backend/src/metabase_enterprise/metabot_v3/api.clj+++ b/enterprise/backend/src/metabase_enterprise/metabot_v3/api.clj@@ -1,81 +1,69 @@(ns metabase-enterprise.metabot-v3.api"`/api/ee/metabot-v3/` routes"(:require- [malli.core :as mc]- [malli.transform :as mtx][metabase-enterprise.metabot-v3.api.document][metabase-enterprise.metabot-v3.api.metabot]+ [metabase-enterprise.metabot-v3.client :as metabot-v3.client][metabase-enterprise.metabot-v3.client.schema :as metabot-v3.client.schema][metabase-enterprise.metabot-v3.config :as metabot-v3.config][metabase-enterprise.metabot-v3.context :as metabot-v3.context][metabase-enterprise.metabot-v3.envelope :as metabot-v3.envelope]- [metabase-enterprise.metabot-v3.reactions :as metabot-v3.reactions]- [metabase-enterprise.metabot-v3.tools.api :as metabot-v3.tools.api]+ [metabase-enterprise.metabot-v3.util :as metabot-v3.u]+ [metabase.api.common :as api][metabase.api.macros :as api.macros][metabase.api.routes.common :refer [+auth]][metabase.api.util.handlers :as handlers]+ [metabase.app-db.core :as app-db][metabase.util :as u]- [metabase.util.malli :as mu]- [metabase.util.malli.schema :as ms]))+ [metabase.util.malli.schema :as ms]+ [toucan2.core :as t2]))-(mu/defn ^:private encode-reactions [reactions :- [:sequential ::metabot-v3.reactions/reaction]]- (mc/encode [:sequential ::metabot-v3.reactions/reaction]- reactions- (mtx/transformer- {:name :api-response}- (mtx/key-transformer {:encode u/->snake_case_en}))))--(defn request- "Handles an incoming request, making all required tool invocation, LLM call loops, etc."- [{:keys [metabot_id profile_id message context history conversation_id state]}]- (let [initial-message (metabot-v3.envelope/user-message message)- history (conj (vec history) initial-message)- metabot-id (metabot-v3.config/resolve-dynamic-metabot-id metabot_id)- profile-id (metabot-v3.config/resolve-dynamic-profile-id profile_id metabot-id)- env (metabot-v3.tools.api/handle-envelope- {:context (metabot-v3.context/create-context context)- :metabot-id metabot-id- :profile-id profile-id- :conversation-id conversation_id- :messages history- :state state})- messages (:messages env)]- {:reactions (-> messages metabot-v3.envelope/reactions encode-reactions)- :history (into history messages)- :state (metabot-v3.envelope/state env)}))--(api.macros/defendpoint :post "/v2/agent"- "Send a chat message to the LLM via the AI Service."- [_route-params- _query-params- {:keys [conversation_id] :as body} :- [:map- [:metabot_id {:optional true} :string]- [:profile_id {:optional true} :string]- [:message ms/NonBlankString]- [:context ::metabot-v3.context/context]- [:conversation_id ms/UUIDString]- [:history [:maybe ::metabot-v3.client.schema/messages]]- [:state :map]]]- (metabot-v3.context/log body :llm.log/fe->be)- (doto (assoc- (request body)- :conversation_id conversation_id)- (metabot-v3.context/log :llm.log/be->fe)))+(defn- store-message! [conversation-id profile-id messages]+ (let [finish (let [m (u/last messages)]+ (when (= (:_type m) :FINISH_MESSAGE)+ m))+ state (u/seek #(and (= (:_type %) :DATA)+ (= (:type %) "state"))+ messages)+ messages (-> (remove #(or (= % state) (= % finish)) messages)+ vec)]+ (app-db/update-or-insert! :model/MetabotConversation {:id conversation-id}+ (constantly (cond-> {:user_id api/*current-user-id*}+ state (assoc :state state))))+ ;; NOTE: this will need to be constrained at some point, see BOT-386+ (t2/insert! :model/MetabotMessage+ {:conversation_id conversation-id+ :data messages+ :usage (:usage finish)+ :role (:role (first messages))+ :profile_id profile-id+ :total_tokens (->> (vals (:usage finish))+ ;; NOTE: this filter is supporting backward-compatible usage format, can be+ ;; removed when ai-service does not give us `completionTokens` in `usage`+ (filter map?)+ (map #(+ (:prompt %) (:completion %)))+ (apply +))})))(defn streaming-request"Handles an incoming request, making all required tool invocation, LLM call loops, etc."[{:keys [metabot_id profile_id message context history conversation_id state]}]- (let [initial-message (metabot-v3.envelope/user-message message)- history (conj (vec history) initial-message)- metabot-id (metabot-v3.config/resolve-dynamic-metabot-id metabot_id)- profile-id (metabot-v3.config/resolve-dynamic-profile-id profile_id metabot-id)]- (metabot-v3.tools.api/streaming-handle-envelope+ (let [message (metabot-v3.envelope/user-message message)+ metabot-id (metabot-v3.config/resolve-dynamic-metabot-id metabot_id)+ profile-id (metabot-v3.config/resolve-dynamic-profile-id profile_id metabot-id)+ session-id (metabot-v3.client/get-ai-service-token api/*current-user-id* metabot-id)]+ (store-message! conversation_id profile-id [message])+ (metabot-v3.client/streaming-request{:context (metabot-v3.context/create-context context):metabot-id metabot-id:profile-id profile-id+ :session-id session-id:conversation-id conversation_id- :messages history- :state state})))+ :message message+ :history history+ :state state+ :on-complete (fn [lines]+ (store-message! conversation_id profile-id (metabot-v3.u/aisdk->messages "assistant" lines))+ :store-in-db)})))(api.macros/defendpoint :post "/v2/agent-streaming""Send a chat message to the LLM via the AI Proxy."diff --git a/enterprise/backend/src/metabase_enterprise/metabot_v3/client.clj b/enterprise/backend/src/metabase_enterprise/metabot_v3/client.cljindex 1d2fa41f967..09003d44e84 100644--- a/enterprise/backend/src/metabase_enterprise/metabot_v3/client.clj+++ b/enterprise/backend/src/metabase_enterprise/metabot_v3/client.clj@@ -22,8 +22,7 @@[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)))+ [metabase.util.o11y :refer [with-span]]))(set! *warn-on-reflection* true)@@ -47,15 +46,11 @@(json/encode-to x w nil)(.toByteArray os)))-(defn- request-headers- []- {"Accept" "application/json"- "Content-Type" "application/json;charset=UTF-8"- "x-metabase-instance-token" (premium-features/premium-embedding-token)})-(defn- build-request-options [body](merge- {:headers (request-headers)+ {: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}@@ -79,11 +74,8 @@(deliver response-metadata (some-> <> :body :metadata))(deliver response-status (some-> <> :status))))))-(defn- agent-v2-endpoint-url []- (str (metabot-v3.settings/ai-service-base-url) "/v2/agent"))--(defn- agent-v2-streaming-endpoint-url []- (str (metabot-v3.settings/ai-service-base-url) "/v2/agent/stream"))+(defn- ai-url [path]+ (str (metabot-v3.settings/ai-service-base-url) path))(defn- metric-selection-endpoint-url [](str (metabot-v3.settings/ai-service-base-url) "/v1/select-metric"))@@ -112,50 +104,6 @@(defn- generate-embeddings-endpoint [](str (metabot-v3.settings/ai-service-base-url) "/v1/embeddings"))-(mu/defn request :- ::metabot-v3.client.schema/ai-service.response- "Make a V2 request to the AI Service."- [{:keys [context messages profile-id conversation-id session-id state]}- :- [:map- [:context :map]- [:messages ::metabot-v3.client.schema/messages]- [:profile-id :string]- [:conversation-id :string]- [:session-id :string]- [:state :map]]]- (premium-features/assert-has-feature :metabot-v3 "MetaBot")- (try- (let [url (agent-v2-endpoint-url)- body (-> {:messages messages- :context context- :conversation_id conversation-id- :profile_id profile-id- :user_id api/*current-user-id*- :state state}- (u/deep-kebab->snake-keys))- _ (metabot-v3.context/log body :llm.log/be->llm)- _ (log/debugf "V2 request to AI Service:\n%s" (u/pprint-to-str body))- options (cond-> {:headers {"Accept" "application/json"- "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)}- :body (->json-bytes body)- :throw-exceptions false}- *debug* (assoc :debug true))- response (post! url options)]- (metabot-v3.context/log (:body response) :llm.log/llm->be)- (log/debugf "Response from AI Service:\n%s" (u/pprint-to-str (select-keys response #{:body :status :headers})))- (if (= (:status response) 200)- (u/prog1 (mc/decode ::metabot-v3.client.schema/ai-service.response- (:body response)- (mtx/transformer {:name :api-response}))- (log/debugf "Response (decoded):\n%s" (u/pprint-to-str <>)))- (throw (ex-info (format "Error: unexpected status code: %d %s" (:status response) (:reason-phrase response))- {:request (assoc options :body body)- :response response}))))- (catch Throwable e- (throw (ex-info (format "Error in request to AI Service: %s" (ex-message e)) {} e)))))-(mu/defn streaming-request :- :any"Make a streaming V2 request to the AI Service@@ -172,24 +120,25 @@Response chunks are encoded in the format understood by the frontend and AI Service, Clojure backend doesn'tknow anything about it and just shuttles them over."- [{:keys [context messages profile-id conversation-id session-id state]}+ [{:keys [context message history profile-id conversation-id session-id state on-complete]}:- [:map[:context :map]- [:messages ::metabot-v3.client.schema/messages]+ [:message ::metabot-v3.client.schema/message]+ [:history ::metabot-v3.client.schema/messages][:profile-id :string][:conversation-id :string][:session-id :string]- [:state :map]]]+ [:state :map]+ [:on-complete {:optional true} [:function [:=> [:cat :any] :any]]]]](premium-features/assert-has-feature :metabot-v3 "MetaBot")(try- (let [url (agent-v2-streaming-endpoint-url)- body (-> {:messages messages- :context context- :conversation_id conversation-id- :profile_id profile-id- :user_id api/*current-user-id*- :state state}- (u/deep-kebab->snake-keys))+ (let [url (ai-url "/v2/agent/stream")+ body {:messages (conj (vec history) message)+ :context context+ :conversation_id conversation-id+ :profile_id profile-id+ :user_id api/*current-user-id*+ :state state}_ (metabot-v3.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"@@ -201,22 +150,30 @@:throw-exceptions false:as :stream}*debug* (assoc :debug true))- response (post! url options)]+ response (post! url options)+ lines (when on-complete+ (atom []))](metabot-v3.context/log (:body response) :llm.log/llm->be)(log/debugf "Response from AI Proxy:\n%s" (u/pprint-to-str (select-keys response #{:body :status :headers})))(if (= (:status response) 200)+ ;; TODO: handle canceled-chan here?(sr/streaming-response {:content-type "text/event-stream; charset=utf-8"} [os canceled-chan];; Response from the AI Service will send response parts separated by newline- (with-open [response-lines ^BufferedReader (io/reader (:body response))]- (loop []- ;; Grab the next line and write it to the output stream with appended newline (frontend depends on it)- ;; Immediately flush so it get's sent to the frontend as soon as possible- (when-let [line (.readLine response-lines)]- (.write os (.getBytes (str line "\n") "UTF-8"))- (.flush os)- (recur)))))+ (with-open [response-reader (io/reader (:body response))]+ (doseq [^String line (line-seq response-reader)]+ (when on-complete+ (swap! lines conj line))+ (doto os+ ;; Line we read from response will lack newline at the end, but FE will be confused without that, so+ ;; we need to append it.+ (.write (.getBytes line "UTF-8"))+ (.write (.getBytes "\n"))+ ;; Immediately flush so it feels fluid on the frontend+ (.flush))))+ (when on-complete+ (on-complete @lines)))(throw (ex-info (format "Error: unexpected status code: %d %s" (:status response) (:reason-phrase response))- {:request (assoc options :body body)+ {:request (assoc options :body body):response response}))))(catch Throwable e(throw (ex-info (format "Error in request to AI Proxy: %s" (ex-message e)) {} e)))))diff --git a/enterprise/backend/src/metabase_enterprise/metabot_v3/client/schema.clj b/enterprise/backend/src/metabase_enterprise/metabot_v3/client/schema.cljindex 1bde5c7dd01..030bf154770 100644--- a/enterprise/backend/src/metabase_enterprise/metabot_v3/client/schema.clj+++ b/enterprise/backend/src/metabase_enterprise/metabot_v3/client/schema.clj@@ -1,6 +1,5 @@(ns metabase-enterprise.metabot-v3.client.schema(:require- [metabase-enterprise.metabot-v3.util :as metabot-v3.u][metabase.util :as u][metabase.util.malli.registry :as mr]))@@ -11,13 +10,14 @@:system :user :assistant :tool])(mr/def ::message- [:and- [:map- {:decode/api-response #(update-keys % metabot-v3.u/safe->kebab-case-en)}- [:role ::role]- [:content {:optional true} [:maybe :string]]- [:navigate-to {:optional true} [:maybe :string]]]- [:map {:encode/api-request #(update-keys % metabot-v3.u/safe->snake_case_en)}]])+ [:map+ [:role ::role]+ [:content {:optional true} [:maybe :string]]+ [:tool_calls {:optional true} [:maybe [:map+ [:id :string]+ [:name :string]+ [:arguments :string]]]]+ [:tool_call_id {:optional true} [:maybe :string]]])(mr/def ::messages[:sequential ::message])@@ -29,8 +29,15 @@[: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]])+ [:state :map]+ [:usage ::usage]])diff --git a/enterprise/backend/src/metabase_enterprise/metabot_v3/core.clj b/enterprise/backend/src/metabase_enterprise/metabot_v3/core.cljindex 84226e47973..4afd8c16441 100644--- a/enterprise/backend/src/metabase_enterprise/metabot_v3/core.clj+++ b/enterprise/backend/src/metabase_enterprise/metabot_v3/core.clj@@ -1,10 +1,13 @@(ns metabase-enterprise.metabot-v3.core"API namespace for the `metabase-enterprise.metabot-v3` module."(:require+ [java-time.api :as t][metabase-enterprise.metabot-v3.api][metabase-enterprise.metabot-v3.client][metabase-enterprise.metabot-v3.table-utils]- [potemkin :as p]))+ [metabase-enterprise.metabot-v3.util]+ [potemkin :as p]+ [toucan2.core :as t2]))(p/import-vars[metabase-enterprise.metabot-v3.api@@ -18,3 +21,21 @@database-tablesused-tablesschema-sample])++(defn metabot-stats+ "Calculate total Metabot token usage over a window of the the previous UTC day 00:00-23:59"+ []+ (let [yesterday-utc (t/minus (t/offset-date-time (t/zone-offset "+00")) (t/days 1))]+ {:metabot-tokens (t2/select-one-fn :sum+ [:model/MetabotMessage [:%sum.total :sum]]+ {:where [:= [:cast :created_at :date] [:cast yesterday-utc :date]]})+ :metabot-queries (t2/select-one-fn :cnt+ [:model/MetabotMessage [:%count.id :cnt]]+ ;; there are requests from users and responses from ai-service, in theory+ ;; counting requests from users should be good enough+ :role "user"+ {:where [:= [:cast :created_at :date] [:cast yesterday-utc :date]]})+ :metabot-users (:cnt (t2/query-one {:select [[[:count [:distinct :c.user_id]] :cnt]]+ :from [[:metabot_message :m]]+ :join [[:metabot_conversation :c] [:= :c.id :m.conversation_id]]+ :where [:= [:cast :m.created_at :date] [:cast yesterday-utc :date]]}))}))diff --git a/enterprise/backend/src/metabase_enterprise/metabot_v3/dummy_tools.clj b/enterprise/backend/src/metabase_enterprise/metabot_v3/dummy_tools.cljindex 744b103dec3..7fb7ee37137 100644--- a/enterprise/backend/src/metabase_enterprise/metabot_v3/dummy_tools.clj+++ b/enterprise/backend/src/metabase_enterprise/metabot_v3/dummy_tools.clj@@ -249,7 +249,9 @@(let [options (cond-> arguments(= (:with-field-values? arguments) false) (assoc :field-values-fn identity))details (cond- (int? model-id) (card-details model-id options)+ (int? model-id) (u/prog1 (card-details model-id (assoc options :only-model true))+ (api/check (= :model (:type <>)) 404+ (format "ID %s is not a valid model id, it's a question" model-id)))(int? table-id) (table-details table-id options)(string? table-id) (if-let [[_ card-id] (re-matches #"card__(\d+)" table-id)](card-details (parse-long card-id) options)diff --git a/enterprise/backend/src/metabase_enterprise/metabot_v3/models/metabot.clj b/enterprise/backend/src/metabase_enterprise/metabot_v3/models/metabot.cljindex 42ecf933eeb..f43ca4cbbef 100644--- a/enterprise/backend/src/metabase_enterprise/metabot_v3/models/metabot.clj+++ b/enterprise/backend/src/metabase_enterprise/metabot_v3/models/metabot.clj@@ -27,14 +27,13 @@(t2/select :model/MetabotEntity {:where [:in :metabot_id (map :id metabots)]})):id{:default []}))-;;; ------------------------------------------------ Serdes Hashing -------------------------------------------------++;;; ------------------------------------------------- Serialization -------------------------------------------------(defmethod serdes/hash-fields :model/Metabot[_table][:name])-;;; ------------------------------------------------- Serialization --------------------------------------------------(defmethod serdes/dependencies "Metabot"[{:keys [entities]}](into #{} (mapcat serdes/dependencies) entities))diff --git a/enterprise/backend/src/metabase_enterprise/metabot_v3/models/metabot_conversation.clj b/enterprise/backend/src/metabase_enterprise/metabot_v3/models/metabot_conversation.cljnew file mode 100644index 00000000000..6778a0554b5--- /dev/null+++ b/enterprise/backend/src/metabase_enterprise/metabot_v3/models/metabot_conversation.clj@@ -0,0 +1,15 @@+(ns metabase-enterprise.metabot-v3.models.metabot-conversation+ (:require+ [metabase.models.interface :as mi]+ [methodical.core :as methodical]+ [toucan2.core :as t2]))++;;; --------------------------------------------------- Lifecycle ----------------------------------------------------++(methodical/defmethod t2/table-name :model/MetabotConversation [_model] :metabot_conversation)++(doto :model/MetabotConversation+ (derive :metabase/model))++(t2/deftransforms :model/MetabotConversation+ {:state mi/transform-json})diff --git a/enterprise/backend/src/metabase_enterprise/metabot_v3/models/metabot_entity.clj b/enterprise/backend/src/metabase_enterprise/metabot_v3/models/metabot_entity.cljindex 5ffe331c1c7..0e1ae603f7c 100644--- a/enterprise/backend/src/metabase_enterprise/metabot_v3/models/metabot_entity.clj+++ b/enterprise/backend/src/metabase_enterprise/metabot_v3/models/metabot_entity.clj@@ -19,14 +19,12 @@(t2/deftransforms :model/MetabotEntity{:model mi/transform-keyword})-;;; ------------------------------------------------ Serdes Hashing -------------------------------------------------+;;; ------------------------------------------------- Serialization -------------------------------------------------(defmethod serdes/hash-fields :model/MetabotEntity[_table][:metabot_id :model :model_id])-;;; ------------------------------------------------- Serialization --------------------------------------------------(defmethod serdes/dependencies "MetabotEntity"[{:keys [model model_id prompts]}](into #{[{:model (case modeldiff --git a/enterprise/backend/src/metabase_enterprise/metabot_v3/models/metabot_message.clj b/enterprise/backend/src/metabase_enterprise/metabot_v3/models/metabot_message.cljnew file mode 100644index 00000000000..73adfa244c4--- /dev/null+++ b/enterprise/backend/src/metabase_enterprise/metabot_v3/models/metabot_message.clj@@ -0,0 +1,17 @@+(ns metabase-enterprise.metabot-v3.models.metabot-message+ (:require+ [metabase.models.interface :as mi]+ [methodical.core :as methodical]+ [toucan2.core :as t2]))++;;; --------------------------------------------------- Lifecycle ----------------------------------------------------++(methodical/defmethod t2/table-name :model/MetabotMessage [_model] :metabot_message)++(doto :model/MetabotMessage+ (derive :metabase/model))++(t2/deftransforms :model/MetabotMessage+ {:usage mi/transform-json+ :data mi/transform-json+ :role mi/transform-keyword})diff --git a/enterprise/backend/src/metabase_enterprise/metabot_v3/models/metabot_prompt.clj b/enterprise/backend/src/metabase_enterprise/metabot_v3/models/metabot_prompt.cljindex bbca537c3ab..de35b1a9b92 100644--- a/enterprise/backend/src/metabase_enterprise/metabot_v3/models/metabot_prompt.clj+++ b/enterprise/backend/src/metabase_enterprise/metabot_v3/models/metabot_prompt.clj@@ -18,14 +18,12 @@(t2/deftransforms :model/MetabotPrompt{:model mi/transform-keyword})-;;; ------------------------------------------------ Serdes Hashing -------------------------------------------------+;;; ------------------------------------------------- Serialization -------------------------------------------------(defmethod serdes/hash-fields :model/MetabotPrompt[_table][:metabot_entity_id :model :card_id :prompt])-;;; ------------------------------------------------- Serialization --------------------------------------------------(defmethod serdes/generate-path "MetabotPrompt" [_ entity](conj (serdes/generate-path "MetabotEntity" (t2/select-one :model/MetabotEntity (:metabot_entity_id entity)))(serdes/infer-self-path "MetabotPrompt" entity)))diff --git a/enterprise/backend/src/metabase_enterprise/metabot_v3/repl.clj b/enterprise/backend/src/metabase_enterprise/metabot_v3/repl.cljindex abee44e2a3f..77d7709dcf9 100644--- a/enterprise/backend/src/metabase_enterprise/metabot_v3/repl.clj+++ b/enterprise/backend/src/metabase_enterprise/metabot_v3/repl.clj@@ -4,12 +4,16 @@clj -X:ee:metabot-v3/repl"(:require+ [clojure.core.async :as a][clojure.string :as str][metabase-enterprise.metabot-v3.api :as api]- [metabase-enterprise.metabot-v3.reactions :as metabot-v3.reactions]+ [metabase-enterprise.metabot-v3.context :as metabot-v3.context]+ [metabase-enterprise.metabot-v3.util :as metabot-v3.u][metabase.app-db.core :as mdb]- [metabase.util :as u]- [metabase.util.malli :as mu]))+ [metabase.util :as u])+ (:import+ (java.io ByteArrayOutputStream)+ (metabase.server.streaming_response StreamingResponse)))(set! *warn-on-reflection* true)@@ -30,10 +34,14 @@#_{:clj-kondo/ignore [:discouraged-var]}(println (u/format-color :magenta "<REACTION>\n%s" (u/pprint-to-str reaction))))-(mu/defn- handle-reactions- [reactions :- [:sequential ::metabot-v3.reactions/reaction]]- (doseq [reaction reactions]- (handle-reaction reaction)))+(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")))(defn user-repl"REPL for interacting with MetaBot."@@ -50,12 +58,16 @@(println "🗨 " (u/colorize :blue input))(when (and (not (#{"quit" "exit" "bye" "goodbye" "\\q"} input))(not (str/blank? input)))- (let [result (api/request {:message input- :context context- :history history- :conversation_id conversation-id- :state state})]- (handle-reactions (:reactions result))+ (let [result (->> (api/streaming-request+ {:message input+ :context context+ :history history+ :conversation_id conversation-id+ :state state})+ consume-streaming-response+ str/split-lines+ (metabot-v3.u/aisdk->messages "assistant"))]+ (run! handle-reaction result)result)))(catch Throwable e#_{:clj-kondo/ignore [:discouraged-var]}@@ -87,20 +99,21 @@:display "table",:visualization_settings {},:type "question"}]- {:user_is_viewing [{:type :dashboard- :id 5- :parameters []- :is-embedded false}- {:type :table- :id 27}- {:type :model- :id 18}- {:type :metric- :id 135}- {:type :report- :id 43}- {:type :adhoc- :query test-query}]}))+ (-> {:user_is_viewing [{:type :dashboard+ :id 5+ :parameters []+ :is-embedded false}+ {:type :table+ :id 27}+ {:type :model+ :id 18}+ {:type :metric+ :id 135}+ {:type :report+ :id 43}+ {:type :adhoc+ :query test-query}]}+ metabot-v3.context/create-context)))(defn- user-repl-with-context [context](user-repl [] context (str (random-uuid))))diff --git a/enterprise/backend/src/metabase_enterprise/metabot_v3/tools/api.clj b/enterprise/backend/src/metabase_enterprise/metabot_v3/tools/api.cljindex 969af3d6edc..f4903d091fa 100644--- a/enterprise/backend/src/metabase_enterprise/metabot_v3/tools/api.clj+++ b/enterprise/backend/src/metabase_enterprise/metabot_v3/tools/api.clj@@ -6,11 +6,9 @@[clojure.set :as set][malli.core :as mc][malli.transform :as mtx]- [metabase-enterprise.metabot-v3.client :as metabot-v3.client][metabase-enterprise.metabot-v3.config :as metabot-v3.config][metabase-enterprise.metabot-v3.context :as metabot-v3.context][metabase-enterprise.metabot-v3.dummy-tools :as metabot-v3.dummy-tools]- [metabase-enterprise.metabot-v3.envelope :as envelope][metabase-enterprise.metabot-v3.reactions][metabase-enterprise.metabot-v3.settings :as metabot-v3.settings][metabase-enterprise.metabot-v3.table-utils :as table-utils]@@ -22,7 +20,6 @@[metabase-enterprise.metabot-v3.tools.find-outliers :as metabot-v3.tools.find-outliers][metabase-enterprise.metabot-v3.tools.generate-insights :as metabot-v3.tools.generate-insights][metabase-enterprise.metabot-v3.util :as metabot-v3.u]- [metabase.api.common :as api][metabase.api.macros :as api.macros][metabase.api.response :as api.response][metabase.api.routes.common :as api.routes.common]@@ -45,26 +42,6 @@(log/error e "Bad AI service token")nil)))-(defn handle-envelope- "Executes the AI loop in the context of a new session. Returns the response of the AI service."- [{:keys [metabot-id] :as e}]- (let [session-id (metabot-v3.client/get-ai-service-token api/*current-user-id* metabot-id)]- (try- (metabot-v3.client/request (assoc e :session-id session-id))- (catch Exception ex- (let [d (ex-data ex)]- (if-let [assistant-message (:assistant-message d)]- (envelope/add-message (or (:envelope d) e)- {:role :assistant- :content assistant-message})- (throw ex)))))))--(defn streaming-handle-envelope- "Executes the AI loop in the context of a new session. Returns the response of the AI service."- [{:keys [metabot-id] :as e}]- (let [session-id (metabot-v3.client/get-ai-service-token api/*current-user-id* metabot-id)]- (metabot-v3.client/streaming-request (assoc e :session-id session-id))))-(mr/def ::bucket(into [:enum {:error/message "Valid bucket":encode/tool-api-request keyword}]diff --git a/enterprise/backend/src/metabase_enterprise/metabot_v3/util.clj b/enterprise/backend/src/metabase_enterprise/metabot_v3/util.cljindex cc137a09b1e..ce712edbaa6 100644--- a/enterprise/backend/src/metabase_enterprise/metabot_v3/util.clj+++ b/enterprise/backend/src/metabase_enterprise/metabot_v3/util.clj@@ -1,7 +1,9 @@(ns metabase-enterprise.metabot-v3.util(:require+ [clojure.set :as set][clojure.walk :as walk]- [metabase.util :as u]))+ [metabase.util :as u]+ [metabase.util.json :as json]))(defn- safe-case-updater[f]@@ -21,3 +23,55 @@(walk/walk #(cond-> % (coll? %) (recursive-update-keys f))#(cond-> % (map? %) (update-keys f))form))++;;; AI SDK support++(def TYPE-PREFIX+ "AI SDK type to prefix, same names as in FE or ai-service"+ ;; NOTE: if we ever get prefix longer than 2 chars, you need to fix parsing to be more generic+ {:TEXT "0:"+ :DATA "2:"+ :ERROR "3:"+ :FINISH_MESSAGE "d:"+ :FINISH_STEP "e:"+ :START_STEP "f:"+ :TOOL_CALL "9:"+ :TOOL_RESULT "a:"})++(def PREFIX-TYPE "AI SDK prefix to type" (set/map-invert TYPE-PREFIX))++(defn aisdk->messages+ "Convert AI SDK line format into an array of parsed messages."+ [role lines]+ (into [] (comp+ (map (fn [line] [(get PREFIX-TYPE (subs line 0 2)) (json/decode+kw (subs line 2))]))+ (partition-by first)+ (mapcat (fn [block]+ (let [type (ffirst block)]+ (case type+ :TEXT [{:role role+ :_type type+ :content (transduce (map second) str block)}]+ (:DATA+ :ERROR) (map #(-> (second %) (assoc :_type type)) block)+ :TOOL_CALL [{:role role+ :_type type+ :tool_calls (map (fn [[_ v]]+ {:id (:toolCallId v)+ :name (:toolName v)+ :arguments (:args v)})+ block)}]+ :TOOL_RESULT (map (fn [[_ v]]+ {:role "tool"+ :_type type+ :tool_call_id (:toolCallId v)+ :content (:result v)})+ block)+ :FINISH_MESSAGE (map (fn [[_ v]]+ {:role role+ :_type type+ :finish_reason (:finishReason v)+ :usage (-> (:usage v)+ (dissoc :promptTokens :completionTokens))})+ block))))))+ lines))diff --git a/enterprise/backend/src/metabase_enterprise/serialization/v2/models.clj b/enterprise/backend/src/metabase_enterprise/serialization/v2/models.cljindex 4c1d4a411fe..0be2d0c7cb0 100644--- a/enterprise/backend/src/metabase_enterprise/serialization/v2/models.clj+++ b/enterprise/backend/src/metabase_enterprise/serialization/v2/models.clj@@ -64,6 +64,8 @@"HTTPAction""ImplicitAction""LoginHistory"+ "MetabotConversation"+ "MetabotMessage""ModelIndex""ModelIndexValue""ModerationReview"diff --git a/enterprise/backend/test/metabase_enterprise/metabot_v3/aisdkstream1.txt b/enterprise/backend/test/metabase_enterprise/metabot_v3/aisdkstream1.txtnew file mode 100644index 00000000000..112357c2bd6--- /dev/null+++ b/enterprise/backend/test/metabase_enterprise/metabot_v3/aisdkstream1.txt@@ -0,0 +1,58 @@+9:{"toolCallId":"call_hZ6Q9AwsxqXaL0lbtpoAEdBi","toolName":"construct_notebook_query","args":"{\"query_plan\":{\"analysis\":\"The user wants to know the number of orders each user has made. The best source for this data is the 'Orders + People' model, which contains the 'User ID' field and the unique 'ID' for each order. We can count the number of orders grouped by 'User ID'.\",\"approach\":\"Use the 'Orders + People' model. Group by 'User ID' and count the distinct 'ID' (order ID) to get the number of orders per user.\"},\"source\":{\"model_id\":1},\"instructions\":\"Show the count of orders (using the unique order ID) grouped by each user ID from the 'Orders + People' model.\"}"}+a:{"toolCallId":"call_hZ6Q9AwsxqXaL0lbtpoAEdBi","result":"\n<result>\nThe query has been successfully constructed.\n\n<query type=\"notebook\" id=\"ajjvXmzxvwACMrT7t9pHK\" database_id=\"1\">\n{\"aggregation\": [[\"count\"]], \"breakout\": [[\"field\", \"USER_ID\", {\"base-type\": \"type/Integer\"}]], \"source-table\": \"card__1\"}\n\n\n<query_results>\n\n### Result Columns\n| Field Name | Type | Description |\n| ---------- | ---- | ----------- |\n| User ID | number | The id of the user who made this order. Note that in some cases where an order was created on behalf of a customer who phoned the order in, this might be the employee who handled the request. |\n| Count | number | None |\n\n\n</query_results>\n\n</query>\n</result>\n<instructions>\n\nNote that you cannot view the results directly yourself.\nConsider how best to present the query results to the user:\n- If they want to see raw tabular data, navigate them to the query results using query ID: ajjvXmzxvwACMrT7t9pHK\n- If they want a visualization, create a chart or graph using the query data\n- You can reference the query naturally in your response using this markdown format: `[Link text](metabase://query/ajjvXmzxvwACMrT7t9pHK)`\n\nPresent the results in a way that matches the user's intent and context.\n</instructions>"}+0:"I"+0:" created"+0:" a"+0:" query"+0:" that"+0:" shows"+0:" how"+0:" many"+0:" orders"+0:" each"+0:" user"+0:" has"+0:" made"+0:","+0:" grouped"+0:" by"+0:" their"+0:" User"+0:" ID"+0:"."+0:" You"+0:" can"+0:" check"+0:" the"+0:" detailed"+0:" results"+0:" here"+0:":"+0:" "+0:"[Orders Count by User](/question#eyJkYXRhc2V0X3F1ZXJ5IjogeyJkYXRhYmFzZSI6IDEsICJ0eXBlIjogInF1ZXJ5IiwgInF1ZXJ5IjogeyJhZ2dyZWdhdGlvbiI6IFtbImNvdW50Il1dLCAiYnJlYWtvdXQiOiBbWyJmaWVsZCIsICJVU0VSX0lEIiwgeyJiYXNlLXR5cGUiOiAidHlwZS9JbnRlZ2VyIn1dXSwgInNvdXJjZS10YWJsZSI6ICJjYXJkX18xIn19LCAiZGlzcGxheSI6ICJ0YWJsZSIsICJkaXNwbGF5SXNMb2NrZWQiOiB0cnVlLCAidmlzdWFsaXphdGlvbl9zZXR0aW5ncyI6IHt9fQ==).\n\n"+0:"If"+0:" you'd"+0:" like"+0:","+0:" I"+0:" can"+0:" also"+0:" help"+0:" you"+0:" visualize"+0:" this"+0:" data"+0:" or"+0:" provide"+0:" it"+0:" in"+0:" another"+0:" format"+0:"."+0:" Just"+0:" let"+0:" me"+0:" know"+0:"!"+2:{"type":"state","version":1,"value":{"queries":{"e897317e-4da0-46cb-827b-59ca52ee2ef2":{"database":1,"type":"query","query":{"source_table":"card__1"}},"ajjvXmzxvwACMrT7t9pHK":{"database":1,"type":"query","query":{"aggregation":[["count"]],"breakout":[["field","USER_ID",{"base-type":"type/Integer"}]],"source-table":"card__1"}}},"charts":{"99994d2e-e38f-4ec3-a582-1068b796e807":{"chart_id":"99994d2e-e38f-4ec3-a582-1068b796e807","queries":[{"query_id":"e897317e-4da0-46cb-827b-59ca52ee2ef2","query":{"database":1,"type":"query","query":{"source_table":"card__1"}},"result":null}],"visualization_settings":{"chart_type":"table"},"image_base_64":null,"timeline_events":[]}}}}+d:{"finishReason":"stop","usage":{"openai/gpt-4.1-mini-2025-04-14":{"prompt":22829,"completion":231},"openai/gpt-4o-mini-2024-07-18":{"prompt":7975,"completion":142},"promptTokens":30804,"completionTokens":373}}diff --git a/enterprise/backend/test/metabase_enterprise/metabot_v3/aisdkstream2.txt b/enterprise/backend/test/metabase_enterprise/metabot_v3/aisdkstream2.txtnew file mode 100644index 00000000000..b63ace8828e--- /dev/null+++ b/enterprise/backend/test/metabase_enterprise/metabot_v3/aisdkstream2.txt@@ -0,0 +1,49 @@+9:{"toolCallId":"call_sJpEjRXSqi5vSjAOJXFdJhjt","toolName":"create_chart","args":"{\"data_source\":{\"query_id\":\"ajjvXmzxvwACMrT7t9pHK\"},\"viz_settings\":{\"chart_type\":\"bar\"}}"}+a:{"toolCallId":"call_sJpEjRXSqi5vSjAOJXFdJhjt","result":"\n<result>\nA new chart has been created with the ID 64e67fbd-7858-4765-b58f-8d8378732600\n</result>\n<instructions>\nThe chart is not visible to you or the user yet.\nTo show the chart to the user, use your navigation tool (chart ID: 64e67fbd-7858-4765-b58f-8d8378732600).\nReference it in your response using: `[Link text](metabase://chart/64e67fbd-7858-4765-b58f-8d8378732600)`\n</instructions>"}+9:{"toolCallId":"call_oPCH01Dt3jlFAwRuemtq9fTt","toolName":"navigate_user","args":"{\"destination\":{\"chart_id\":\"64e67fbd-7858-4765-b58f-8d8378732600\"}}"}+2:{"type":"navigate_to","version":1,"value":"/question#eyJkYXRhc2V0X3F1ZXJ5IjogeyJkYXRhYmFzZSI6IDEsICJ0eXBlIjogInF1ZXJ5IiwgInF1ZXJ5IjogeyJhZ2dyZWdhdGlvbiI6IFtbImNvdW50Il1dLCAiYnJlYWtvdXQiOiBbWyJmaWVsZCIsICJVU0VSX0lEIiwgeyJiYXNlX3R5cGUiOiAidHlwZS9JbnRlZ2VyIn1dXSwgInNvdXJjZV90YWJsZSI6ICJjYXJkX18xIn19LCAiZGlzcGxheSI6ICJiYXIiLCAiZGlzcGxheUlzTG9ja2VkIjogdHJ1ZSwgInZpc3VhbGl6YXRpb25fc2V0dGluZ3MiOiB7fX0="}+a:{"toolCallId":"call_oPCH01Dt3jlFAwRuemtq9fTt","result":"The user now can see the result of the chart with ID 64e67fbd-7858-4765-b58f-8d8378732600"}+0:"I"+0:" created"+0:" a"+0:" bar"+0:" chart"+0:" that"+0:" shows"+0:" how"+0:" many"+0:" orders"+0:" each"+0:" user"+0:" has"+0:" made"+0:"."+0:" You"+0:" can"+0:" view"+0:" it"+0:" here"+0:":"+0:" "+0:"[Orders per User Bar Chart](/question#eyJkYXRhc2V0X3F1ZXJ5IjogeyJkYXRhYmFzZSI6IDEsICJ0eXBlIjogInF1ZXJ5IiwgInF1ZXJ5IjogeyJhZ2dyZWdhdGlvbiI6IFtbImNvdW50Il1dLCAiYnJlYWtvdXQiOiBbWyJmaWVsZCIsICJVU0VSX0lEIiwgeyJiYXNlX3R5cGUiOiAidHlwZS9JbnRlZ2VyIn1dXSwgInNvdXJjZV90YWJsZSI6ICJjYXJkX18xIn19LCAiZGlzcGxheSI6ICJiYXIiLCAiZGlzcGxheUlzTG9ja2VkIjogdHJ1ZSwgInZpc3VhbGl6YXRpb25fc2V0dGluZ3MiOiB7fX0=)."+0:" Let"+0:" me"+0:" know"+0:" if"+0:" you'd"+0:" like"+0:" it"+0:" in"+0:" another"+0:" format"+0:" or"+0:" if"+0:" you"+0:" want"+0:" to"+0:" explore"+0:" more"+0:" details"+0:"!"+2:{"type":"state","version":1,"value":{"queries":{"e897317e_4da0_46cb_827b_59ca52ee2ef2":{"database":1,"type":"query","query":{"source_table":"card__1"}},"ajjvXmzxvwACMrT7t9pHK":{"database":1,"type":"query","query":{"aggregation":[["count"]],"breakout":[["field","USER_ID",{"base_type":"type/Integer"}]],"source_table":"card__1"}},"e897317e-4da0-46cb-827b-59ca52ee2ef2":{"database":1,"type":"query","query":{"source_table":"card__1"}},"16098fb6-3a51-4ac6-bf72-062b386d871b":{"database":1,"type":"query","query":{"source_table":"card__1"}}},"charts":{"99994d2e-e38f-4ec3-a582-1068b796e807":{"chart_id":"99994d2e-e38f-4ec3-a582-1068b796e807","queries":[{"query_id":"e897317e-4da0-46cb-827b-59ca52ee2ef2","query":{"database":1,"type":"query","query":{"source_table":"card__1"}},"result":null}],"visualization_settings":{"chart_type":"table"},"image_base_64":null,"timeline_events":[]},"24172f7e-c5f8-433d-850b-f6be68c0c3ac":{"chart_id":"24172f7e-c5f8-433d-850b-f6be68c0c3ac","queries":[{"query_id":"16098fb6-3a51-4ac6-bf72-062b386d871b","query":{"database":1,"type":"query","query":{"source_table":"card__1"}},"result":null}],"visualization_settings":{"chart_type":"table"},"image_base_64":null,"timeline_events":[]},"64e67fbd-7858-4765-b58f-8d8378732600":{"chart_id":"64e67fbd-7858-4765-b58f-8d8378732600","queries":[{"query_id":"ajjvXmzxvwACMrT7t9pHK","query":{"database":1,"type":"query","query":{"aggregation":[["count"]],"breakout":[["field","USER_ID",{"base_type":"type/Integer"}]],"source_table":"card__1"}},"result":null}],"visualization_settings":{"chart_type":"bar"},"image_base_64":null,"timeline_events":null}}}}+d:{"finishReason":"stop","usage":{"openai/gpt-4.1-mini-2025-04-14":{"prompt":36300,"completion":151},"promptTokens":36300,"completionTokens":151}}diff --git a/enterprise/backend/test/metabase_enterprise/metabot_v3/api_test.clj b/enterprise/backend/test/metabase_enterprise/metabot_v3/api_test.cljindex c1bd1bb253f..367c34ab7a7 100644--- a/enterprise/backend/test/metabase_enterprise/metabot_v3/api_test.clj+++ b/enterprise/backend/test/metabase_enterprise/metabot_v3/api_test.clj@@ -1,50 +1,60 @@(ns metabase-enterprise.metabot-v3.api-test(:require+ [clj-http.client :as http]+ [clojure.string :as str][clojure.test :refer :all][medley.core :as m]- [metabase-enterprise.metabot-v3.client :as metabot-v3.client]- [metabase-enterprise.metabot-v3.config :as metabot-v3.config]- [metabase-enterprise.metabot-v3.tools.api :as metabot-v3.tools.api]- [metabase.test :as mt]))+ [metabase-enterprise.metabot-v3.client-test :as client-test]+ [metabase-enterprise.metabot-v3.util :as metabot.u]+ [metabase.test :as mt]+ [metabase.util.json :as json]+ [toucan2.core :as t2]))-(deftest agent-test- (let [ai-requests (atom [])- conversation-id (str (random-uuid))- question "what can you do?"- navigation-target "url"- historical-message {:role "user", :content "hello?"}- agent-message {:role :assistant, :navigate-to navigation-target}- agent-state {:key "value"}]- (mt/with-premium-features #{:metabot-v3}- (with-redefs [metabot-v3.client/request (fn [e]- (swap! ai-requests conj e)- {:messages [agent-message]- :state agent-state})]- (testing "Trivial request"+(set! *warn-on-reflection* true)++(deftest agent-streaming-test+ (mt/with-premium-features #{:metabot-v3}+ (let [mock-response (client-test/make-mock-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 [http/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))]]- (reset! ai-requests [])- (let [response (mt/user-http-request :rasta :post 200 "ee/metabot-v3/v2/agent"- (-> {:message question- :context {}- :conversation_id conversation-id- :history [historical-message]- :state {}}- (m/assoc-some :metabot_id metabot-id)))]- (is (=? [{:context {:current_user_time (every-pred string? java.time.Instant/parse)}- :messages [(update historical-message :role keyword) {:role :user, :content question}]- :state {}- :conversation-id conversation-id- :profile-id (metabot-v3.config/resolve-dynamic-profile-id nil (metabot-v3.config/resolve-dynamic-metabot-id metabot-id))- :session-id (fn [session-id]- (when-let [token (#'metabot-v3.tools.api/decode-ai-service-token session-id)]- (and (= (:metabot-id token) (or metabot-id- metabot-v3.config/internal-metabot-id))- (= (:user token) (mt/user->id :rasta)))))}]- @ai-requests))- (is (=? {:reactions [{:type "metabot.reaction/redirect", :url navigation-target}]- :history [historical-message- {:role "user", :content question}- (update agent-message :role name)]- :state agent-state- :conversation_id conversation-id}- response)))))))))+ (mt/with-model-cleanup [:model/MetabotMessage+ [:model/MetabotConversation :created_at]]+ (reset! ai-requests [])+ (let [response (mt/user-http-request :rasta :post 202 "ee/metabot-v3/v2/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))))))))))diff --git a/enterprise/backend/test/metabase_enterprise/metabot_v3/client_test.clj b/enterprise/backend/test/metabase_enterprise/metabot_v3/client_test.cljnew file mode 100644index 00000000000..03788cb7416--- /dev/null+++ b/enterprise/backend/test/metabase_enterprise/metabot_v3/client_test.clj@@ -0,0 +1,61 @@+(ns metabase-enterprise.metabot-v3.client-test+ (:require+ [clj-http.client :as http]+ [clojure.core.async :as a]+ [clojure.string :as str]+ [clojure.test :refer :all]+ [metabase-enterprise.metabot-v3.client :as metabot-v3.client]+ [metabase-enterprise.metabot-v3.client.schema :as metabot-v3.client.schema]+ [metabase-enterprise.metabot-v3.util :as metabot-v3.util]+ [metabase.test :as mt]+ [metabase.util.json :as json]+ [metabase.util.malli :as mu])+ (:import+ (java.io ByteArrayInputStream ByteArrayOutputStream)+ (metabase.server.streaming_response StreamingResponse)))++(set! *warn-on-reflection* true)++(mu/defn make-mock-stream-response [chunks usage :- ::metabot-v3.client.schema/usage]+ (str (->> chunks+ (map #(str "0:" (json/encode %) "\n"))+ (str/join))+ "d:" (json/encode {:finishReason "stop" :usage usage})))++(defn mock-post! [^String body]+ (fn [_url _opts]+ {:status 200+ :headers {"content-type" "text/event-stream"}+ :body (ByteArrayInputStream. (.getBytes body "UTF-8"))}))++(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-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-v3.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-v3.util/aisdk->messages "assistant" (str/split-lines body))))))))))diff --git a/enterprise/backend/test/metabase_enterprise/metabot_v3/util_test.clj b/enterprise/backend/test/metabase_enterprise/metabot_v3/util_test.cljnew file mode 100644index 00000000000..ced32b65509--- /dev/null+++ b/enterprise/backend/test/metabase_enterprise/metabot_v3/util_test.clj@@ -0,0 +1,68 @@+(ns metabase-enterprise.metabot-v3.util-test+ (:require+ [clojure.java.io :as io]+ [clojure.test :refer :all]+ [metabase-enterprise.metabot-v3.util :as metabot.u]))++(deftest aisdk-line-parse-test+ (testing "We should be able to parse AI SDK streaming format to ai-service format 1"+ (is (=? [{:role "assistant"+ :_type :TOOL_CALL+ :tool_calls [{:id "call_hZ6Q9AwsxqXaL0lbtpoAEdBi"+ :name "construct_notebook_query"+ :arguments #"\{\"query_plan\":.*\}"}]}+ {:role "tool"+ :_type :TOOL_RESULT+ :tool_call_id "call_hZ6Q9AwsxqXaL0lbtpoAEdBi"+ :content #"(?s)\n<result>.*</instructions>"}+ {:role "assistant"+ :_type :TEXT+ :content #"(?s)I created.*let me know!"}+ {:type "state"+ :_type :DATA+ :version 1+ :value {}}+ {:finish_reason "stop"+ :_type :FINISH_MESSAGE+ :usage {}}]+ (metabot.u/aisdk->messages "assistant"+ (-> (io/resource "metabase_enterprise/metabot_v3/aisdkstream1.txt")+ io/reader+ line-seq)))))+ (testing "We should be able to parse AI SDK streaming format to ai-service format 2"+ (is (=? [{:role "assistant"+ :_type :TOOL_CALL+ :tool_calls [{:id "call_sJpEjRXSqi5vSjAOJXFdJhjt"+ :name "create_chart"+ :arguments #"\{\"data_source\":.*\}"}]}+ {:role "tool"+ :_type :TOOL_RESULT+ :tool_call_id "call_sJpEjRXSqi5vSjAOJXFdJhjt"+ :content #"(?s)\n<result>.*</instructions>"}+ {:role "assistant"+ :_type :TOOL_CALL+ :tool_calls [{:id "call_oPCH01Dt3jlFAwRuemtq9fTt"+ :name "navigate_user"+ :arguments #"\{\"destination\":.*\}"}]}+ {:type "navigate_to"+ :_type :DATA+ :version 1+ :value #"/question#eyJ.*"}+ {:role "tool"+ :_type :TOOL_RESULT+ :tool_call_id "call_oPCH01Dt3jlFAwRuemtq9fTt"+ :content #"(?s)The user now can see the result of the chart.*"}+ {:role "assistant"+ :_type :TEXT+ :content #"(?s)I created.*more details!"}+ {:type "state"+ :_type :DATA+ :version 1+ :value {}}+ {:finish_reason "stop"+ :_type :FINISH_MESSAGE+ :usage {}}]+ (metabot.u/aisdk->messages "assistant"+ (-> (io/resource "metabase_enterprise/metabot_v3/aisdkstream2.txt")+ io/reader+ line-seq))))))diff --git a/enterprise/backend/test/metabase_enterprise/models/entity_id_test.clj b/enterprise/backend/test/metabase_enterprise/models/entity_id_test.cljindex a082414bcde..c616b349a3a 100644--- a/enterprise/backend/test/metabase_enterprise/models/entity_id_test.clj+++ b/enterprise/backend/test/metabase_enterprise/models/entity_id_test.clj@@ -50,6 +50,8 @@:model/DashboardCardSeries:model/LoginHistory:model/FieldValues+ :model/MetabotConversation+ :model/MetabotMessage:model/ModelIndex:model/ModelIndexValue:model/ModerationReviewdiff --git a/enterprise/frontend/src/metabase-enterprise/api/ai-streaming/__snapshots__/process-stream.unit.spec.ts.snap b/enterprise/frontend/src/metabase-enterprise/api/ai-streaming/__snapshots__/process-stream.unit.spec.ts.snapindex 14f98699a32..98650e77661 100644--- a/enterprise/frontend/src/metabase-enterprise/api/ai-streaming/__snapshots__/process-stream.unit.spec.ts.snap+++ b/enterprise/frontend/src/metabase-enterprise/api/ai-streaming/__snapshots__/process-stream.unit.spec.ts.snap@@ -18,7 +18,7 @@ exports[`processChatResponse should be able to process a valid stream 1`] = `},{"role": "assistant",- "tool-calls": [+ "tool_calls": [{"arguments": "","id": "x",@@ -29,7 +29,7 @@ exports[`processChatResponse should be able to process a valid stream 1`] = `{"content": "","role": "tool",- "tool-call-id": "x",+ "tool_call_id": "x",},],"parts": [diff --git a/enterprise/frontend/src/metabase-enterprise/api/ai-streaming/process-stream.ts b/enterprise/frontend/src/metabase-enterprise/api/ai-streaming/process-stream.tsindex aeeb2137a1e..b8f1c11650d 100644--- a/enterprise/frontend/src/metabase-enterprise/api/ai-streaming/process-stream.ts+++ b/enterprise/frontend/src/metabase-enterprise/api/ai-streaming/process-stream.ts@@ -148,7 +148,7 @@ function accumulateStreamParts(streamParts: ParsedStreamPart[]) {acc.toolCalls.push({ ...streamPart.value, state: "call" });acc.history.push({role: "assistant",- "tool-calls": [+ tool_calls: [{id: streamPart.value.toolCallId,name: streamPart.value.toolName,@@ -175,7 +175,7 @@ function accumulateStreamParts(streamParts: ParsedStreamPart[]) {acc.history.push({role: "tool",content: streamPart.value.result,- "tool-call-id": streamPart.value.toolCallId,+ tool_call_id: streamPart.value.toolCallId,});}diff --git a/enterprise/frontend/src/metabase-enterprise/api/ai-streaming/schemas.ts b/enterprise/frontend/src/metabase-enterprise/api/ai-streaming/schemas.tsindex 584dece25f8..1b28712c695 100644--- a/enterprise/frontend/src/metabase-enterprise/api/ai-streaming/schemas.ts+++ b/enterprise/frontend/src/metabase-enterprise/api/ai-streaming/schemas.ts@@ -28,15 +28,11 @@ export const finishPartSchema = Yup.object({.oneOf(["stop","length",- "content-filter",- "tool-calls",+ "content_filter",+ "tool_calls","error","other","unknown",]).required(),- usage: Yup.object({- promptTokens: Yup.number().required(),- completionTokens: Yup.number().required(),- }),});diff --git a/resources/migrations/056_update_migrations.yaml b/resources/migrations/056_update_migrations.yamlindex 948a9ff90cd..17447e091ce 100644--- a/resources/migrations/056_update_migrations.yaml+++ b/resources/migrations/056_update_migrations.yaml@@ -373,6 +373,137 @@ databaseChangeLog:AND mt2.name = SUBSTRING(metabase_table.name, 1, POSITION('__mbarchiv__' IN metabase_table.name) - 1)AND mt2.id != metabase_table.id);+ - changeSet:+ id: v56.2025-09-03T17:15:00+ author: piranha+ comment: metabot_conversation table+ changes:+ - createTable:+ tableName: metabot_conversation+ remarks: Table to store metabot conversation messages+ columns:+ - column:+ name: id+ type: varchar(36)+ constraints:+ primaryKey: true+ nullable: false+ remarks: 'Conversation UUID'+ - column:+ name: created_at+ type: ${timestamp_type}+ defaultValueComputed: current_timestamp+ constraints:+ nullable: false+ remarks: 'created_at'+ - column:+ name: user_id+ type: int+ constraints:+ nullable: false+ referencedTableName: core_user+ referencedColumnNames: id+ foreignKeyName: fk_metabot_conversation_user_id+ remarks: 'Reference to user having the conversation'+ - column:+ name: summary+ type: ${text.type}+ remarks: 'Auto-generated summary for the conversation'+ - column:+ name: state+ type: ${text.type}+ remarks: 'Metabot conversation state'++ - changeSet:+ id: v56.2025-09-03T17:15:01+ author: piranha+ comment: Index on metabot_conversation.user_id+ changes:+ - createIndex:+ indexName: idx_metabot_conversation_user_id+ tableName: metabot_conversation+ columns:+ - column:+ name: user_id+ rollback: # will be dropped with table++ - changeSet:+ id: v56.2025-09-03T17:16:00+ author: piranha+ comment: metabot_message table+ changes:+ - createTable:+ tableName: metabot_message+ remarks: Table to store metabot conversation messages+ columns:+ - column:+ name: id+ type: int+ autoIncrement: true+ constraints:+ primaryKey: true+ nullable: false+ remarks: 'Autoincrement PK'+ - column:+ name: created_at+ type: ${timestamp_type}+ defaultValueComputed: current_timestamp+ constraints:+ nullable: false+ remarks: 'created_at'+ - column:+ name: profile_id+ type: ${text.type}+ constraints:+ nullable: false+ remarks: 'ai-service profile used to perform the conversation'+ - column:+ name: role+ type: varchar(20)+ constraints:+ nullable: false+ remarks: 'Role of the sender'+ - column:+ name: data+ type: ${text.type}+ constraints:+ nullable: false+ remarks: 'Full message content'+ - column:+ name: usage+ type: ${text.type}+ constraints:+ nullable: true+ remarks: 'Can be null for user messages; {"<model-name>": {"prompt": 1, "completion": 2}}'+ - column:+ name: total_tokens+ type: int+ constraints:+ nullable: false+ remarks: 'A sum of all prompt+completion from `usage`'+ - column:+ name: conversation_id+ type: varchar(36)+ constraints:+ nullable: false+ referencedTableName: metabot_conversation+ referencedColumnNames: id+ foreignKeyName: fk_metabot_message_conversation_id+ remarks: 'Reference to a conversation'++ - changeSet:+ id: v56.2025-09-03T17:16:01+ author: piranha+ comment: Index on metabot_message.conversation_id+ changes:+ - createIndex:+ indexName: idx_metabot_message_conversation_id+ tableName: metabot_message+ columns:+ - column:+ name: conversation_id+ rollback: # will be dropped with table+# >>>>>>>>>> DO NOT ADD NEW MIGRATIONS BELOW THIS LINE! ADD THEM ABOVE <<<<<<<<<<########################################################################################################################diff --git a/src/metabase/cmd/copy.clj b/src/metabase/cmd/copy.cljindex f0851bfeffa..b1de67f24b4 100644--- a/src/metabase/cmd/copy.clj+++ b/src/metabase/cmd/copy.clj@@ -50,8 +50,9 @@`(do-step ~msg (fn [] ~@body)))(def entities- "Entities in the order they should be serialized/deserialized. This is done so we make sure that we load- instances of entities before others that might depend on them, e.g. `Databases` before `Tables` before `Fields`."+ "Entities in the order they should be serialized/deserialized in `load-from-h2`. This is done so we make sure that+ we load instances of entities before others that might depend on them, e.g. `Databases` before `Tables` before+ `Fields`."(concat[:model/Channel:model/ChannelTemplate@@ -116,7 +117,9 @@[:model/Sandbox:model/ConnectionImpersonation:model/Metabot+ :model/MetabotConversation:model/MetabotEntity+ :model/MetabotMessage:model/MetabotPrompt:model/Document:model/DocumentBookmark@@ -353,6 +356,7 @@:model/HTTPAction:model/FieldUserSettings:model/QueryAction+ :model/MetabotConversation:model/ModelIndexValue})(defmulti ^:private postgres-id-sequence-namediff --git a/src/metabase/models/resolution.clj b/src/metabase/models/resolution.cljindex da779839b21..b0195e771e9 100644--- a/src/metabase/models/resolution.clj+++ b/src/metabase/models/resolution.clj@@ -49,7 +49,9 @@:model/ImplicitAction metabase.actions.models:model/LoginHistory metabase.login-history.models.login-history:model/Metabot metabase-enterprise.metabot-v3.models.metabot+ :model/MetabotConversation metabase-enterprise.metabot-v3.models.metabot-conversation:model/MetabotEntity metabase-enterprise.metabot-v3.models.metabot-entity+ :model/MetabotMessage metabase-enterprise.metabot-v3.models.metabot-message:model/MetabotPrompt metabase-enterprise.metabot-v3.models.metabot-prompt:model/ModelIndex metabase.indexed-entities.models.model-index:model/ModelIndexValue metabase.indexed-entities.models.model-indexdiff --git a/src/metabase/premium_features/token_check.clj b/src/metabase/premium_features/token_check.cljindex 29a76440d33..87461fe961b 100644--- a/src/metabase/premium_features/token_check.clj+++ b/src/metabase/premium_features/token_check.clj@@ -97,21 +97,28 @@:enabled-embedding-sdk false:enabled-embedding-simple false})+(defenterprise metabot-stats+ "Stats for Metabot"+ metabase-enterprise.metabot-v3.core+ []+ {:metabot-tokens 0})+(defn- stats-for-token-request[]- (let [users (premium-features.settings/active-users-count)- ext-users (internal-stats/external-users-count)+ (let [users (premium-features.settings/active-users-count)+ ext-users (internal-stats/external-users-count)embedding-dashboard-count (internal-stats/embedding-dashboard-count)- embedding-question-count (internal-stats/embedding-question-count)- stats (merge (internal-stats/query-execution-last-utc-day)- (embedding-settings embedding-dashboard-count embedding-question-count)- {:users users- :embedding-dashboard-count embedding-dashboard-count- :embedding-question-count embedding-question-count- :external-users ext-users- :internal-users (- users ext-users)- :domains (internal-stats/email-domain-count)})]- (log/info "Reporting embedding stats:" stats)+ embedding-question-count (internal-stats/embedding-question-count)+ stats (merge (internal-stats/query-execution-last-utc-day)+ (embedding-settings embedding-dashboard-count embedding-question-count)+ (metabot-stats)+ {:users users+ :embedding-dashboard-count embedding-dashboard-count+ :embedding-question-count embedding-question-count+ :external-users ext-users+ :internal-users (- users ext-users)+ :domains (internal-stats/email-domain-count)})]+ (log/info "Reporting Metabase stats:" stats)stats))(defn- token-status-url [token base-url]diff --git a/src/metabase/util.cljc b/src/metabase/util.cljcindex 279b0934758..c4c96c01871 100644--- a/src/metabase/util.cljc+++ b/src/metabase/util.cljc@@ -1,7 +1,7 @@#_{:clj-kondo/ignore [:metabase/namespace-name]}(ns metabase.util"Common utility functions useful throughout the codebase."- (:refer-clojure :exclude [group-by])+ (:refer-clojure :exclude [group-by last])(:require#?@(:clj ([clojure.core.protocols][clojure.math.numeric-tower :as math]@@ -122,6 +122,14 @@(str " " (pr-str data)))))(str/join "\n"))))+(defn last+ "Like `clojure.core/last`, but tries to be O(1)."+ [v]+ (cond+ (or (list? v) (map? v)) (clojure.core/last v)+ (zero? (count v)) nil+ :else (nth v (dec (count v)))))+(defmacro prog1"Execute `first-form`, then any other expressions in `body`, presumably for side-effects; return the result of`first-form`.diff --git a/test/metabase/premium_features/token_check_test.clj b/test/metabase/premium_features/token_check_test.cljindex 0ded30b5b85..37a96f3c45f 100644--- a/test/metabase/premium_features/token_check_test.clj+++ b/test/metabase/premium_features/token_check_test.clj@@ -69,7 +69,7 @@(deftest ^:parallel fetch-token-status-test-2(testing "With the backend unavailable"- (let [result (#'token-status-response (random-token) {:status 500})]+ (let [result (token-status-response (random-token) {:status 500})](is (false? (:valid result))))))(deftest ^:parallel fetch-token-status-test-3@@ -138,8 +138,8 @@(deftest ^:parallel fetch-token-status-test-4(testing "With a valid token"- (let [result (#'token-status-response (random-token) {:status 200- :body token-response-fixture})]+ (let [result (token-status-response (random-token) {:status 200+ :body token-response-fixture})](is (:valid result))(is (contains? (set (:features result)) "test")))))diff --git a/test/metabase/util_test.cljc b/test/metabase/util_test.cljcindex c19415ad229..677892a8a8d 100644--- a/test/metabase/util_test.cljc+++ b/test/metabase/util_test.cljc@@ -694,3 +694,14 @@(is (nil? (u/find-first-map test-maps [:a :b] 5)))(is (= {:a {:b 2}}(u/find-first-map test-maps [:a :b] 2))))))++(deftest ^:parallel last-test+ (testing "u/last works"+ (are [res src] (= res (u/last src))+ 9 (range 10)+ 3 '(1 2 3)+ nil '()+ 3 [1 2 3]+ nil []+ \c "abc"+ [:b 2] {:a 1 :b 2})))