Skip to content

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

7.4 KB
Raw Blame
(ns metabase-enterprise.metabot-analytics.api
  "`/api/ee/metabot-analytics/` endpoints for AI/Metabot usage analytics.
  These only work if you have a premium token with the `:audit-app` feature.

  Handlers stay thin: auth + param coercion + delegation. The HoneySQL and
  response assembly live in `metabase-enterprise.metabot-analytics.conversations`."
  (:require
   [metabase-enterprise.metabot-analytics.conversations :as analytics.conversations]
   [metabase.api.common :as api]
   [metabase.api.macros :as api.macros]
   [metabase.api.routes.common :refer [+auth]]
   [metabase.metabot.schema :as metabot.schema]
   [metabase.metabot.tools :as metabot.tools]
   [metabase.request.core :as request]
   [metabase.util.malli.schema :as ms]))

(set! *warn-on-reflection* true)

;;; -------------------------------------------------- Schemas --------------------------------------------------

(def ^:private UserInfo
  "Trimmed user shape surfaced on analytics responses — no PII beyond what the
   admin UI already renders."
  [:map
   [:id         ms/PositiveInt]
   [:email      :string]
   [:first_name [:maybe :string]]
   [:last_name  [:maybe :string]]])

(def ^:private ConversationSummary
  "Schema for a conversation summary in list responses."
  [:map
   [:conversation_id             ms/UUIDString]
   [:created_at                  ms/TemporalInstant]
   [:title                       [:maybe :string]]
   [:message_count               ms/IntGreaterThanOrEqualToZero]
   [:user_message_count          ms/IntGreaterThanOrEqualToZero]
   [:assistant_message_count     ms/IntGreaterThanOrEqualToZero]
   [:total_tokens                ms/IntGreaterThanOrEqualToZero]
   [:cache_read_tokens           ms/IntGreaterThanOrEqualToZero]
   [:last_message_at             [:maybe ms/TemporalInstant]]
   [:profile_id                  [:maybe :string]]
   [:search_count                ms/IntGreaterThanOrEqualToZero]
   [:query_count                 ms/IntGreaterThanOrEqualToZero]
   [:ip_address                  [:maybe :string]]
   [:embedding_hostname          [:maybe :string]]
   [:embedding_path              [:maybe :string]]
   [:user_agent                  [:maybe :string]]
   [:sanitized_user_agent        [:maybe :string]]
   [:forked_from_conversation_id [:maybe ms/UUIDString]]
   [:user                        [:maybe UserInfo]]])

(def ^:private SortColumn
  "Allow-list of columns the list endpoint can sort by."
  [:enum "created_at" "title" "message_count" "total_tokens" "cache_read_tokens" "user" "profile_id" "ip_address"])

(def ^:private SortDirection
  [:enum "asc" "desc"])

(def ^:private ListConversationsQueryParams
  "Query-param schema for `GET /conversations`."
  [:map {:closed true}
   [:sort_by   {:optional true} [:maybe SortColumn]]
   [:sort_dir  {:optional true} [:maybe SortDirection]]
   [:user_id   {:optional true} [:maybe ms/PositiveInt]]
   [:group_id  {:optional true} [:maybe ms/PositiveInt]]
   [:tenant_id {:optional true} [:maybe ms/PositiveInt]]
   [:date      {:optional true} [:maybe :string]]])

(def ^:private GeneratedQuery
  "Schema for a single query generated by the bot during a conversation.
   One row per successful query-construction tool call. Errored calls are
   filtered out at the extractor."
  [:map
   [:tool        (into [:enum] (sort metabot.tools/query-generation-tool-names))]
   [:call_id     [:maybe :string]]
   [:message_id  ms/PositiveInt]
   [:query_id    [:maybe :string]]
   [:query_type  [:enum "sql" "notebook"]]
   [:sql         [:maybe :string]]
   [:mbql        [:maybe :map]]
   [:display     [:maybe :string]]
   [:database_id [:maybe ms/PositiveInt]]
   [:tables      [:sequential :string]]])

(def ^:private ConversationFeedback
  "Schema for one user-submitted feedback row attached to a conversation. Rows
   are keyed per-`(message_id, user_id)` — a shared Slack thread can yield
   multiple submissions on the same assistant message — so `:user_id` is
   carried explicitly and `:user` is hydrated for display."
  [:map
   [:id                ms/PositiveInt]
   [:message_id        ms/PositiveInt]
   [:user_id           ms/PositiveInt]
   [:user              {:optional true} [:maybe UserInfo]]
   [:external_id       [:maybe :string]]
   [:positive          :boolean]
   [:issue_type        [:maybe :string]]
   [:freeform_feedback [:maybe :string]]
   [:created_at        ms/TemporalInstant]
   [:updated_at        ms/TemporalInstant]])

(def ^:private ConversationMessage
  "A client message plus the parent pointer that threads the conversation — with
  regenerated replies as siblings — into the tree the detail page walks."
  [:merge
   ::metabot.schema/client-message
   [:map [:parent_message_id [:maybe :string]]]])

(def ^:private ConversationDetail
  "Schema for full conversation detail response."
  [:map
   [:conversation_id             ms/UUIDString]
   [:created_at                  ms/TemporalInstant]
   [:title                       [:maybe :string]]
   [:user                        [:maybe UserInfo]]
   [:message_count               ms/IntGreaterThanOrEqualToZero]
   [:total_tokens                ms/IntGreaterThanOrEqualToZero]
   [:profile_id                  [:maybe :string]]
   [:slack_permalink             [:maybe :string]]
   [:messages                    [:sequential ConversationMessage]]
   [:queries                     [:sequential GeneratedQuery]]
   [:search_count                ms/IntGreaterThanOrEqualToZero]
   [:query_count                 ms/IntGreaterThanOrEqualToZero]
   [:ip_address                  [:maybe :string]]
   [:embedding_hostname          [:maybe :string]]
   [:embedding_path              [:maybe :string]]
   [:user_agent                  [:maybe :string]]
   [:sanitized_user_agent        [:maybe :string]]
   [:forked_from_conversation_id [:maybe ms/UUIDString]]
   [:fork_boundary_message_id    [:maybe :string]]
   [:feedback                    [:sequential ConversationFeedback]]])

(def ^:private ListConversationsResponse
  "Response schema for `GET /conversations`."
  [:map
   [:data   [:sequential ConversationSummary]]
   [:total  ms/IntGreaterThanOrEqualToZero]
   [:limit  ms/IntGreaterThanOrEqualToZero]
   [:offset ms/IntGreaterThanOrEqualToZero]])

(def ^:private ConversationIdParams
  "Route-param schema for endpoints addressing a single conversation by id."
  [:map {:closed true} [:id ms/UUIDString]])

;;; -------------------------------------------------- Endpoints --------------------------------------------------

(api.macros/defendpoint :get "/conversations" :- ListConversationsResponse
  "Return paginated list of AI conversations with summary statistics."
  [_route-params
   {:keys [sort_by sort_dir user_id group_id tenant_id date]} :- ListConversationsQueryParams]
  (api/check-superuser)
  (analytics.conversations/list-conversations
   {:limit     (request/limit)
    :offset    (request/offset)
    :sort-by   sort_by
    :sort-dir  sort_dir
    :user-id   user_id
    :group-id  group_id
    :tenant-id tenant_id
    :date      date}))

(api.macros/defendpoint :get "/conversations/:id" :- ConversationDetail
  "Return full details for a specific conversation including all messages."
  [{:keys [id]} :- ConversationIdParams]
  (api/check-superuser)
  (analytics.conversations/fetch-conversation-detail id))

;;; -------------------------------------------------- Routes --------------------------------------------------

(def ^{:arglists '([request respond raise])} routes
  "Routes for `/api/ee/metabot-analytics/`."
  (+auth (api.macros/ns-handler *ns*)))