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
[BOT-1899] Metabot DeepSeek direct provider support (#80054)
Tyler Plude3cd5fc8e1ecc
diff --git a/frontend/src/metabase-types/api/llm.ts b/frontend/src/metabase-types/api/llm.tsindex 3fea04e89e8..95e1f2f7e99 100644--- a/frontend/src/metabase-types/api/llm.ts+++ b/frontend/src/metabase-types/api/llm.ts@@ -40,6 +40,7 @@ export type LlmProviderTypeName =| "mistral"| "zai"| "moonshot"+ | "deepseek"| "google"| "azure"| "bedrock"diff --git a/frontend/src/metabase-types/api/settings.ts b/frontend/src/metabase-types/api/settings.tsindex 5af7fbc9a17..e85885b9340 100644--- a/frontend/src/metabase-types/api/settings.ts+++ b/frontend/src/metabase-types/api/settings.ts@@ -532,6 +532,7 @@ interface SettingsManagerSettings {"llm-zai-api-key"?: string | null;"llm-mistral-api-key"?: string | null;"llm-moonshot-api-key"?: string | null;+ "llm-deepseek-api-key"?: string | null;"llm-azure-api-key"?: string | null;"llm-azure-api-base-url"?: string | null;"llm-google-service-account-key"?: string | null;@@ -777,6 +778,7 @@ export interface EnterpriseSettings extends Settings {"llm-zai-api-key"?: string | null;"llm-mistral-api-key"?: string | null;"llm-moonshot-api-key"?: string | null;+ "llm-deepseek-api-key"?: string | null;"session-timeout": TimeoutValue | null;"search-engine": SearchEngineSettingValue | null;"scim-enabled"?: boolean | null;diff --git a/frontend/src/metabase/metabot/components/AIProviderConfigurationForm/ProviderTypeIcon.tsx b/frontend/src/metabase/metabot/components/AIProviderConfigurationForm/ProviderTypeIcon.tsxindex ad9ad48cec7..9850d1a44ca 100644--- a/frontend/src/metabase/metabot/components/AIProviderConfigurationForm/ProviderTypeIcon.tsx+++ b/frontend/src/metabase/metabot/components/AIProviderConfigurationForm/ProviderTypeIcon.tsx@@ -8,6 +8,7 @@ import S from "./ProviderTypeIcon.module.css";import AnthropicMark from "./logos/anthropic.svg?component";import AzureMark from "./logos/azure.svg?component";import BedrockMark from "./logos/bedrock.svg?component";+import DeepSeekMark from "./logos/deepseek.svg?component";import GoogleMark from "./logos/google.svg?component";import MistralMark from "./logos/mistral.svg?component";import MoonshotMark from "./logos/moonshot.svg?component";@@ -32,6 +33,7 @@ const PROVIDER_LOGOS: Record<mistral: MistralMark,zai: ZaiMark,moonshot: MoonshotMark,+ deepseek: DeepSeekMark,google: GoogleMark,azure: AzureMark,vllm: null,diff --git a/frontend/src/metabase/metabot/components/AIProviderConfigurationForm/ProviderTypeIcon.unit.spec.tsx b/frontend/src/metabase/metabot/components/AIProviderConfigurationForm/ProviderTypeIcon.unit.spec.tsxindex a05399ea6b0..f4559f93417 100644--- a/frontend/src/metabase/metabot/components/AIProviderConfigurationForm/ProviderTypeIcon.unit.spec.tsx+++ b/frontend/src/metabase/metabot/components/AIProviderConfigurationForm/ProviderTypeIcon.unit.spec.tsx@@ -29,6 +29,7 @@ describe("ProviderTypeIcon", () => {"mistral","zai","moonshot",+ "deepseek","google","azure","bedrock",diff --git a/frontend/src/metabase/metabot/components/AIProviderConfigurationForm/logos/deepseek.svg b/frontend/src/metabase/metabot/components/AIProviderConfigurationForm/logos/deepseek.svgnew file mode 100644index 00000000000..d54330553d0--- /dev/null+++ b/frontend/src/metabase/metabot/components/AIProviderConfigurationForm/logos/deepseek.svg@@ -0,0 +1 @@+<svg width="24" height="24" xmlns="http://www.w3.org/2000/svg" fill="currentColor" viewBox="0 0 24 24"><path d="M23.748 4.651c-.254-.124-.364.113-.512.233-.051.04-.094.09-.137.137-.372.397-.806.657-1.373.626-.829-.046-1.537.214-2.163.848-.133-.782-.575-1.248-1.247-1.548-.352-.155-.708-.311-.955-.65-.172-.24-.219-.509-.305-.774-.055-.16-.11-.323-.293-.35-.2-.031-.278.136-.356.276-.313.572-.434 1.202-.422 1.84.027 1.436.633 2.58 1.838 3.393.137.094.172.187.129.323-.082.28-.18.553-.266.833-.055.179-.137.218-.328.14a5.5 5.5 0 0 1-1.737-1.179c-.857-.828-1.631-1.743-2.597-2.46a12 12 0 0 0-.689-.47c-.985-.957.13-1.743.387-1.836.27-.098.094-.433-.778-.428-.872.003-1.67.295-2.687.685a3 3 0 0 1-.465.136 9.6 9.6 0 0 0-2.883-.101c-1.885.21-3.39 1.1-4.497 2.622C.082 8.776-.231 10.854.152 13.02c.403 2.284 1.568 4.175 3.36 5.653 1.857 1.533 3.997 2.284 6.438 2.14 1.482-.085 3.132-.284 4.994-1.86.47.234.962.328 1.78.398.629.058 1.235-.031 1.705-.129.735-.155.684-.836.418-.961-2.155-1.004-1.682-.595-2.112-.926 1.095-1.295 2.768-3.598 3.284-6.733.05-.346.115-.834.108-1.114-.004-.171.035-.238.23-.257a4.2 4.2 0 0 0 1.545-.475c1.397-.763 1.96-2.016 2.093-3.517.02-.23-.004-.467-.247-.588M11.58 18.168c-2.088-1.642-3.101-2.183-3.52-2.16-.39.024-.32.472-.234.763.09.288.207.487.371.74.114.167.192.416-.113.603-.673.416-1.842-.14-1.897-.168-1.361-.801-2.5-1.86-3.301-3.306-.775-1.393-1.225-2.888-1.299-4.482-.02-.385.094-.522.477-.592a4.7 4.7 0 0 1 1.53-.038c2.131.311 3.946 1.264 5.467 2.774.868.86 1.525 1.887 2.202 2.89.72 1.066 1.494 2.082 2.48 2.915.348.291.626.513.892.677-.802.09-2.14.109-3.055-.615zm1.001-6.44a.306.306 0 0 1 .415-.287.3.3 0 0 1 .113.074.3.3 0 0 1 .086.214c0 .17-.136.307-.308.307a.303.303 0 0 1-.306-.307m3.11 1.596c-.2.081-.4.151-.591.16a1.25 1.25 0 0 1-.798-.254c-.274-.23-.47-.358-.551-.758a1.7 1.7 0 0 1 .015-.588c.07-.327-.007-.537-.238-.727-.188-.156-.426-.199-.689-.199a.6.6 0 0 1-.254-.078.253.253 0 0 1-.114-.358 1 1 0 0 1 .192-.21c.356-.202.767-.136 1.146.016.352.144.618.408 1.001.782.392.451.462.576.685.915.176.264.336.536.446.848.066.194-.02.353-.25.45"/></svg>diff --git a/src/metabase/llm/provider.clj b/src/metabase/llm/provider.cljindex fc24ebc53f4..5a6a81ac05b 100644--- a/src/metabase/llm/provider.clj+++ b/src/metabase/llm/provider.clj@@ -144,6 +144,25 @@:advanced? true:default "https://api.moonshot.ai/v1":help (deferred-tru "Point this at the .cn platform to use it instead; keys are not interchangeable between the two.")}]}+ {:type "deepseek"+ :label (deferred-tru "DeepSeek")+ :default-model "deepseek-v4-pro"+ :mini-model "deepseek-v4-flash"+ :fields [{:key :api-key+ :label (deferred-tru "API key")+ :type :password+ ;; No `:prefix`: DeepSeek keys carry the same `sk-` an OpenAI key does, so matching on it+ ;; would claim OpenAI keys while rejecting nothing.+ :required? true+ :placeholder "sk-..."+ :docs-url "https://platform.deepseek.com/api_keys"}+ {:key :base-url+ :normalize strip-trailing-slashes+ :label (deferred-tru "API base URL")+ :type :text+ :advanced? true+ :default "https://api.deepseek.com"+ :help (deferred-tru "The root both surfaces hang off; leave off any /anthropic or /v1 path.")}]}{:type "google";; "Google Gemini Enterprise" (nearly the official "Gemini Enterprise Agent Platform" name), not "Google;; Gemini": the Gemini API is a separate surface with its own credentials, and may become a provider type of@@ -489,6 +508,9 @@"moonshot" {:type "moonshot":settings {:api-key {:setting :llm-moonshot-api-key :credential? true}:base-url {:setting :llm-moonshot-api-base-url}}}+ "deepseek" {:type "deepseek"+ :settings {:api-key {:setting :llm-deepseek-api-key :credential? true}+ :base-url {:setting :llm-deepseek-api-base-url}}}"google" {:type "google":settings {:service-account-key {:setting :llm-google-service-account-key :credential? true}:oauth-access-token {:setting :llm-google-oauth-access-token :credential? true}diff --git a/src/metabase/llm/settings.clj b/src/metabase/llm/settings.cljindex 3ec6f6e5a7e..bc152fba21c 100644--- a/src/metabase/llm/settings.clj+++ b/src/metabase/llm/settings.clj@@ -223,6 +223,27 @@:setter (connection-field-setter :llm-moonshot-api-key):doc "Backed by the moonshot connection in the admin AI settings provider list: reads and writes go through the llm-providers connection list, and a value set by this environment variable shadows this one field of that connection.")+;;; ------------------------------------------------- DeepSeek --------------------------------------------------++(defsetting llm-deepseek-api-base-url+ (deferred-tru "The DeepSeek API base URL. Both the Anthropic-compatible Messages surface (`/anthropic/v1/messages`) and the model catalog (`/models`) are served off this root, so do not include `/anthropic` or `/v1`.")+ :encryption :no+ :visibility :settings-manager+ :default "https://api.deepseek.com"+ :export? false+ :getter (connection-field-getter :llm-deepseek-api-base-url)+ :setter (connection-field-setter :llm-deepseek-api-base-url)+ :doc "Backed by the deepseek connection in the admin AI settings provider list: reads and writes go through the llm-providers connection list, and a value set by this environment variable shadows this one field of that connection.")++(defsetting llm-deepseek-api-key+ (deferred-tru "The DeepSeek API Key.")+ :sensitive? true+ :visibility :settings-manager+ :export? false+ :getter (connection-field-getter :llm-deepseek-api-key)+ :setter (connection-field-setter :llm-deepseek-api-key)+ :doc "Backed by the deepseek connection in the admin AI settings provider list: reads and writes go through the llm-providers connection list, and a value set by this environment variable shadows this one field of that connection.")+;;; ------------------------------------ Google Gemini Enterprise Agent Platform --------------------------------;;; The Gemini Enterprise Agent Platform (formerly Vertex AI). Every request applies to one Google Cloud project. The;;; project ID is necessary. The location is optional and defaults to `global`.diff --git a/src/metabase/metabot/self.clj b/src/metabase/metabot/self.cljindex 126ac15220b..13ad71696a3 100644--- a/src/metabase/metabot/self.clj+++ b/src/metabase/metabot/self.clj@@ -19,6 +19,7 @@[metabase.metabot.self.bedrock :as bedrock][metabase.metabot.self.claude :as claude][metabase.metabot.self.core :as core]+ [metabase.metabot.self.deepseek :as deepseek][metabase.metabot.self.google :as google][metabase.metabot.self.mistral :as mistral][metabase.metabot.self.moonshot :as moonshot]@@ -41,6 +42,7 @@"anthropic" claude/claude"azure" azure/azure"bedrock" bedrock/bedrock+ "deepseek" deepseek/deepseek"google" google/google"mistral" mistral/mistral"moonshot" moonshot/moonshot@@ -57,6 +59,7 @@"anthropic" claude/list-models"azure" azure/list-models"bedrock" bedrock/list-models+ "deepseek" deepseek/list-models"google" google/list-models"mistral" mistral/list-models"moonshot" moonshot/list-modelsdiff --git a/src/metabase/metabot/self/claude.clj b/src/metabase/metabot/self/claude.cljindex 2c8c4c1a21a..136e763f896 100644--- a/src/metabase/metabot/self/claude.clj+++ b/src/metabase/metabot/self/claude.clj@@ -443,13 +443,18 @@(some? (model-thinking-config model)))(mu/defn claude-request-body- "Build the Anthropic Messages API request body for an LLM request."- [{:keys [model system input tools schema tool_choice temperature max-tokens reasoning?]+ "Build the Anthropic Messages API request body for an LLM request.++ A caller-supplied `:reasoning-config` is this dialect's `thinking` block and wins outright: an+ adapter re-hosting a non-Claude model here knows its own provider's thinking shape and+ restrictions, which the model-id-derived config and the suppression rules below cannot describe."+ [{:keys [model system input tools schema tool_choice temperature max-tokens reasoning? reasoning-config]:or {model "claude-haiku-4-5" reasoning? true}} :- core/LLMRequestOpts](let [;; forced tool choice (structured output, or "required") is incompatible;; with thinking — suppress it there.- thinking (when-not (or (not reasoning?) schema (= "required" (some-> tool_choice name)))- (model-thinking-config model))+ thinking (or reasoning-config+ (when-not (or (not reasoning?) schema (= "required" (some-> tool_choice name)))+ (model-thinking-config model)))input (cond->> input(nil? thinking) (remove #(= :reasoning (:type %))))messages (parts->claude-messages input)diff --git a/src/metabase/metabot/self/core.clj b/src/metabase/metabot/self/core.cljindex 5013e1fa2aa..ef10900e093 100644--- a/src/metabase/metabot/self/core.clj+++ b/src/metabase/metabot/self/core.clj@@ -55,6 +55,12 @@:ai-proxy? - When true, skip provider auth and use the Metabase AI proxy:reasoning? - When false, don't request thinking/reasoning and strip:reasoning parts from the replayed input (defaults true)+ :reasoning-config - Explicit reasoning directive for an adapter re-hosting a non-native+ model on another provider's dialect, where the model-derived config+ does not apply. Dialect-shaped, not portable: on the Anthropic dialect+ it is the `thinking` block, sent verbatim. When set it wins over both+ the derived config and the suppression rules, and :reasoning parts+ survive into the replayed input.:prompt-cache-key - prompt-cache affinity hint (the conversation id); adapters whoseprovider caches opt-in per key forward it (Mistral), others ignore it"[:map@@ -69,6 +75,7 @@[:credentials {:optional true} [:maybe :map]][:ai-proxy? {:optional true} [:maybe :boolean]][:reasoning? {:optional true} [:maybe :boolean]]+ [:reasoning-config {:optional true} [:maybe :map]][:prompt-cache-key {:optional true} [:maybe :string]]])(defn mkiddiff --git a/src/metabase/metabot/self/deepseek.clj b/src/metabase/metabot/self/deepseek.cljnew file mode 100644index 00000000000..8650036d157--- /dev/null+++ b/src/metabase/metabot/self/deepseek.clj@@ -0,0 +1,261 @@+(ns metabase.metabot.self.deepseek+ "DeepSeek adapter, speaking DeepSeek's Anthropic-compatible Messages surface.++ Both surfaces DeepSeek serves hang off one host, so a single base URL covers them:++ - `POST {base-url}/anthropic/v1/messages` — Anthropic Messages API, the chat surface+ - `GET {base-url}/models` — OpenAI-style catalog, also the admin Connect round trip++ The Anthropic dialect is used rather than DeepSeek's Chat Completions surface because it is the+ only one that can carry reasoning back to us: [[metabase.metabot.self.claude]] already captures+ thinking blocks with their signatures and replays them, while the shared Chat Completions+ translation drops `reasoning_content` on the floor. Request bodies and stream translation are+ therefore delegated to `claude.clj`; this namespace owns auth, the catalog, errors, and the+ thinking directive.++ https://api-docs.deepseek.com/guides/anthropic_api"+ (:require+ [metabase.metabot.self.claude :as claude]+ [metabase.metabot.self.core :as core]+ [metabase.metabot.self.debug :as debug]+ [metabase.metabot.self.openai.chat-completions :as chat-completions]+ [metabase.util.i18n :refer [tru]]+ [metabase.util.json :as json]+ [metabase.util.log :as log]+ [metabase.util.malli :as mu]+ [metabase.util.o11y :refer [with-span]]))++(set! *warn-on-reflection* true)++(def ^:private default-model "deepseek-v4-pro")++(def ^:private anthropic-version "2023-06-01")++(def ^:private messages-path "/anthropic/v1/messages")++(def ^:private supported-models+ "DeepSeek models offered in the Metabot model picker, as a map of model id -> display name.+ `list-models` returns the intersection of this map with the `/models` catalog."+ {"deepseek-v4-flash" "DeepSeek V4 Flash"+ "deepseek-v4-pro" "DeepSeek V4 Pro"})++(def ^:private thinking-enabled-payload+ "Sent whenever thinking is allowed. Explicit rather than omitted: DeepSeek ignores an+ unrecognized `thinking.type` and leaves thinking on, so only the exact disable payload turns+ it off and an omitted directive is indistinguishable from a typo."+ {:type "enabled"})++(def ^:private thinking-disabled-payload+ {:type "disabled"})++(defn reasoning-model?+ "Whether `model` streams reasoning back to us. Every DeepSeek model we offer does, subject to the+ per-request suppression in [[thinking-enabled?]]."+ [model]+ (contains? supported-models model))++(defn- ai-proxy-unsupported-ex []+ (ex-info (tru "AI proxy is not supported for DeepSeek")+ {:api-error true+ :error-code :proxy-unsupported}))++(defn- deepseek-error-msg+ "Canonical, status-specific DeepSeek error message.++ `metabase.metabot.api`'s `provider-client-error?` renders any 4xx `:api-error` under the admin+ API-key field, so the request-rejected statuses (400, 422) need messages that do not send admins+ hunting a key problem that does not exist. 402 is an exhausted account balance, which DeepSeek+ reports separately from rate limiting."+ [res]+ (let [status (long (:status res 0))]+ (case status+ 400 (tru "DeepSeek rejected the request — check the model and request parameters")+ 401 (tru "DeepSeek API key expired or invalid")+ 402 (tru "DeepSeek account balance is exhausted")+ 403 (tru "DeepSeek denied access — check the API key permissions")+ 404 (tru "DeepSeek API endpoint or model was not found — check the base URL and model")+ 422 (tru "DeepSeek rejected the request parameters")+ 429 (tru "DeepSeek has rate limited us")+ 500 (tru "DeepSeek returned an internal server error")+ 503 (tru "DeepSeek is overloaded and is asking us to wait")+ (tru "DeepSeek API error (HTTP {0})" status))))++(defn- supported-model?+ "Whether a `/models` catalog entry is one of the [[supported-models]]."+ [{:keys [id]}]+ (contains? supported-models id))++(defn- list-all-models+ "Fetch the full DeepSeek model catalog (`GET /models`).++ The catalog is OpenAI-style even though the chat surface is not, so the fail-closed extraction in+ [[chat-completions/models-catalog]] applies. It doubles as the credential round-trip behind the+ admin Connect button — it 401s on a bad key.+ `:ai-proxy?` is not supported for DeepSeek and throws when true."+ [{:keys [credentials ai-proxy?]}]+ (when ai-proxy?+ (throw (ai-proxy-unsupported-ex)))+ (try+ (let [auth (core/resolve-auth "deepseek" "DeepSeek"+ (when-let [k (not-empty (:api-key credentials))]+ {:url (:base-url credentials)+ :headers {"Authorization" (str "Bearer " k)}})+ ai-proxy?)+ res (core/request auth {:method :get+ :url "/models"+ :as :json+ :headers {"Content-Type" "application/json"}})]+ (chat-completions/models-catalog "DeepSeek" res))+ (catch Exception e+ (core/rethrow-api-error! "deepseek" deepseek-error-msg e))))++(defn list-models+ "List the DeepSeek models supported by this adapter (see [[supported-models]]).++ Display names come from [[supported-models]]: DeepSeek catalog entries carry no `:name`.+ `:ai-proxy?` is not supported for DeepSeek and throws when true."+ ([] (list-models {}))+ ([opts]+ {:models (->> (list-all-models opts)+ (filter supported-model?)+ (sort-by :id)+ (mapv (fn [{:keys [id]}]+ {:id id :display_name (supported-models id)})))}))++;;; --------------------------------------------- The thinking contract ------------------------------------------+;;;+;;; DeepSeek validates thinking provenance over the *currently open turn* — everything after the+;;; last plain user message. Every assistant message there carrying a `tool_use` must also carry a+;;; thinking block, or hold a tool-call id minted by a thinking-enabled generation; one offending+;;; message 400s the whole request. `thinking {:type "disabled"}` bypasses the check entirely.++(defn- plain-user-message?+ "Whether `part` is a plain user message — the only thing that closes a turn. Tool results are+ user-role on the wire but do not close it."+ [part]+ (and (nil? (:type part))+ (contains? #{nil :user "user"} (:role part))))++(defn- open-turn-parts+ "The parts after the last plain user message."+ [input]+ (if-let [i (->> input+ (keep-indexed (fn [i part] (when (plain-user-message? part) i)))+ last)]+ (drop (inc i) input)+ input))++(def ^:private assistant-part-type?+ "Part types [[claude/parts->claude-messages]] renders as assistant-role content, and so merges+ into one message."+ #{:reasoning :text :tool-input})++(defn- signed-reasoning?+ "Whether `part` is a thinking block DeepSeek will accept back. A signature is the only+ provenance it recognizes: [[claude/parts->claude-messages]] also vouches for a part carrying+ `:redactedData`, but `redacted_thinking` is one of the block types DeepSeek does not support, and+ DeepSeek never emits one for us to replay."+ [part]+ (and (= :reasoning (:type part))+ (some? (get-in part [:provider-metadata :anthropic :signature]))))++(defn- unsigned-tool-call-in-open-turn?+ "Whether the open turn holds a tool call we cannot vouch for. Parts are grouped the way they merge+ onto the wire: a run of assistant-role parts becomes one message, and a run holding a `:tool-input`+ with no signed `:reasoning` is a message DeepSeek rejects. Metabot's synthetic dialect preload+ (`skill_preload_*`, injected for SQL-editor sessions) is exactly that shape."+ [input]+ (->> (open-turn-parts input)+ (partition-by (comp boolean assistant-part-type? :type))+ (some (fn [run]+ (and (some #(= :tool-input (:type %)) run)+ (not-any? signed-reasoning? run))))+ boolean))++(defn- thinking-enabled?+ "Thinking is on unless the caller opted out, we are forcing a single structured-output tool call+ (`tool_choice {:type \"tool\"}` is rejected in thinking mode, unlike `{:type \"any\"}`), or the+ open turn carries a tool call with no signed reasoning to vouch for it."+ [{:keys [schema reasoning? input] :or {reasoning? true}}]+ (cond+ (not reasoning?) false+ (some? schema) false+ (unsigned-tool-call-in-open-turn? input) (do (log/debug "DeepSeek thinking disabled: unsigned tool call in the open turn")+ false)+ :else true))++(mu/defn deepseek-request-body+ "Build the Anthropic Messages request body for an LLM request.++ DeepSeek's Anthropic surface accepts what [[claude/claude-request-body]] emits as-is, so the only+ DeepSeek-specific work is the thinking directive, which must always be present: an omitted+ directive leaves thinking on.++ The three `cache_control` markers are inert here: DeepSeek lists the field among those it ignores+ and caches input prefixes on its own, with no request parameter to set. Hits are still reported,+ on the Anthropic-shaped `cache_read_input_tokens`.++ Where thinking is allowed this diverges from `claude-request-body` deliberately: DeepSeek accepts+ `tool_choice {:type \"any\"}` with thinking on, so the profiles that force a tool call keep their+ reasoning."+ [{:keys [model] :as opts+ :or {model default-model}} :- core/LLMRequestOpts]+ (let [thinking? (thinking-enabled? opts)]+ (cond-> (claude/claude-request-body+ (assoc opts+ :model model+ :reasoning? thinking?+ :reasoning-config (when thinking? thinking-enabled-payload)))+ (not thinking?) (assoc :thinking thinking-disabled-payload))))++(mu/defn deepseek-raw+ "Perform a streaming request to the DeepSeek Anthropic Messages API.+ Opts map takes `:credentials` (`{:api-key ... :base-url ...}`) from the connection serving this request, and+ throws when they are missing.+ `:ai-proxy?` is not supported for DeepSeek and throws when true."+ [{:keys [model tools credentials ai-proxy?] :as opts+ :or {model default-model}} :- core/LLMRequestOpts]+ (when ai-proxy?+ (throw (ai-proxy-unsupported-ex)))+ (let [req (deepseek-request-body (assoc opts :model model))]+ (log/debug "DeepSeek request" {:model model :msg-count (count (:messages req)) :tools (count (or tools []))})+ (with-span :info {:name :metabot.deepseek/request+ :model model+ :msg-count (count (:messages req))+ :tool-count (count (or tools []))}+ (try+ (let [api-key (not-empty (:api-key credentials))+ auth (core/resolve-auth "deepseek" "DeepSeek"+ (when api-key+ {:url (:base-url credentials)+ :headers {"Authorization" (str "Bearer " api-key)}})+ ai-proxy?)+ response (core/request auth+ {:method :post+ :url messages-path+ :as :stream+ :headers {"anthropic-version" anthropic-version+ "Content-Type" "application/json"}+ :body (json/encode req)})]+ ;; The SSE body is consumed lazily, after this `try` has exited — wrap+ ;; the reducible so mid-stream IO/timeout failures get the same+ ;; provider-friendly translation as request-time errors.+ (-> (core/sse-reducible (:body response))+ (debug/capture-stream {:provider "deepseek"+ :model model+ :url messages-path+ :request req})+ (core/reducible-with-api-errors "deepseek" deepseek-error-msg)))+ (catch Exception e+ (core/rethrow-api-error! "deepseek" deepseek-error-msg e))))))++(defn deepseek->aisdk-chunks-xf+ "Translates DeepSeek Anthropic Messages streaming events into AI SDK v5 protocol chunks."+ []+ (claude/claude->aisdk-chunks-xf))++(defn deepseek+ "Call the DeepSeek Anthropic Messages API, return AISDK stream."+ [& args]+ (let [raw (apply deepseek-raw args)]+ (eduction (deepseek->aisdk-chunks-xf) raw)))diff --git a/src/metabase/metabot/settings.clj b/src/metabase/metabot/settings.cljindex d81cf99c861..2f9baf3dd7e 100644--- a/src/metabase/metabot/settings.clj+++ b/src/metabase/metabot/settings.clj@@ -4,6 +4,7 @@[metabase.llm.provider :as llm.provider][metabase.llm.settings :as llm.settings][metabase.metabot.self.claude :as claude]+ [metabase.metabot.self.deepseek :as deepseek][metabase.metabot.self.openai :as openai][metabase.metabot.self.vllm :as vllm][metabase.settings.core :as setting :refer [defsetting]]@@ -231,6 +232,7 @@(let [{:keys [type model credentials]} (llm.provider/resolve-model-ref model-ref)](case type"anthropic" (claude/reasoning-model? model)+ "deepseek" (deepseek/reasoning-model? model)"openai" (openai/reasoning-model? model)"vllm" (vllm/reasoning-connection? credentials)false)))diff --git a/test/metabase/app_db/custom_migrations/llm_providers_test.clj b/test/metabase/app_db/custom_migrations/llm_providers_test.cljindex 1633512214c..f5f551e9a93 100644--- a/test/metabase/app_db/custom_migrations/llm_providers_test.clj+++ b/test/metabase/app_db/custom_migrations/llm_providers_test.clj@@ -146,6 +146,26 @@(is (= {"llm-metabot-provider" "anthropic/claude-opus-4-1"}(llm-setting-values ["llm-metabot-provider"])))))))+(deftest rollback-llm-provider-settings-drops-a-post-migration-type-test+ (testing "v64.7qmx3p : a provider type added after this migration is not in its frozen table, so a rollback has+ nowhere to put it — the versions this rolls back to cannot serve that provider either"+ (impl/test-migrations ["v64.7qmx3p"] [migrate!]+ (insert-llm-settings! {"llm-anthropic-api-key" "sk-ant-stored"})+ (migrate!)+ (t2/query {:update :setting+ :set {:value (encryption/maybe-encrypt+ (json/encode [{:key "deepseek"+ :type "deepseek"+ :name "DeepSeek"+ :config {:api-key "sk-deepseek"}}]))}+ :where [:= :key "llm-providers"]})+ (insert-llm-settings! {"llm-metabot-provider" "deepseek/deepseek-v4-flash"})+ (migrate! :down 63)+ (testing "the credential is dropped rather than written to a setting nothing reads"+ (is (= {} (llm-setting-values ["llm-deepseek-api-key"]))))+ (testing "and the reference naming it falls back to the default rather than pointing at a provider that is gone"+ (is (= {} (llm-setting-values ["llm-metabot-provider"])))))))+(deftest rollback-llm-provider-settings-encrypts-only-secrets-test(testing "v64.7qmx3p : the downgrade encrypts what the pre-migration code stored encrypted, and nothing else"(encryption-test/with-secret-key "dont-tell-anyone-about-this"diff --git a/test/metabase/llm/api/provider_test.clj b/test/metabase/llm/api/provider_test.cljindex 4ef2509c90b..e53a4edc94c 100644--- a/test/metabase/llm/api/provider_test.clj+++ b/test/metabase/llm/api/provider_test.clj@@ -31,10 +31,11 @@(deftest provider-types-test(testing "every provider type is listed with the credential fields a connection needs"(let [types (mt/user-http-request :crowberto :get 200 "llm/provider-types")]- (is (= #{"anthropic" "openai" "openrouter" "mistral" "zai" "moonshot" "google" "azure" "bedrock" "vllm"- "metabase"}+ (is (= #{"anthropic" "openai" "openrouter" "mistral" "zai" "moonshot" "deepseek" "google" "azure" "bedrock"+ "vllm" "metabase"}(set (map :type types))))- (is (= ["anthropic" "openai" "openrouter" "mistral" "zai" "moonshot" "google" "azure" "bedrock" "vllm"]+ (is (= ["anthropic" "openai" "openrouter" "mistral" "zai" "moonshot" "deepseek" "google" "azure" "bedrock"+ "vllm"](remove #{"metabase"} (map :type types)))"the bring-your-own-key providers keep their registry order")(is (=? {:type "anthropic"diff --git a/test/metabase/llm/provider_test.clj b/test/metabase/llm/provider_test.cljindex 0aaf60f8221..5484060b63b 100644--- a/test/metabase/llm/provider_test.clj+++ b/test/metabase/llm/provider_test.clj@@ -458,8 +458,8 @@"so a type without a decided logo fails to compile. Nothing links the two, so adding a type here ""without updating them ships a provider that silently falls back to the generic icon. Update ""both, then this list.")- (is (= #{"anthropic" "openai" "openrouter" "mistral" "zai" "moonshot" "google" "azure" "bedrock" "vllm"- "metabase"}+ (is (= #{"anthropic" "openai" "openrouter" "mistral" "zai" "moonshot" "deepseek" "google" "azure" "bedrock"+ "vllm" "metabase"}(into #{} (map :type) (llm.provider/provider-types))))))(deftest ^:parallel provider-types-test@@ -487,6 +487,7 @@"mistral" "mistral-medium-3-5""zai" "glm-5.2""moonshot" "kimi-k3"+ "deepseek" "deepseek-v4-pro""google" "google/gemini-3.5-flash";; azure's models are deployment names the admin chooses, so there is nothing to default to"azure" nil@@ -506,6 +507,7 @@"mistral" "mistral-medium-3-5""zai" "glm-5.2""moonshot" "kimi-k3"+ "deepseek" "deepseek-v4-flash""google" nil"azure" nil"bedrock" "anthropic.claude-haiku-4-5"diff --git a/test/metabase/llm/test_util.clj b/test/metabase/llm/test_util.cljindex 6f07e268447..f93798598bd 100644--- a/test/metabase/llm/test_util.clj+++ b/test/metabase/llm/test_util.clj@@ -14,6 +14,7 @@"mistral" {:api-key "mistral-test-key"}"zai" {:api-key "zai-test-key"}"moonshot" {:api-key "sk-moonshot-test-key"}+ "deepseek" {:api-key "sk-deepseek-test-key"}"google" {:oauth-access-token "ya29.test-token":project-id "my-project"}"azure" {:api-key "azure-test-key"@@ -36,8 +37,8 @@:config (merge (get dummy-configs type-name) config-overrides)}))(def default-connections- (mapv connection ["anthropic" "openai" "openrouter" "mistral" "zai" "moonshot" "google" "azure" "bedrock"- "metabase"]))+ (mapv connection ["anthropic" "openai" "openrouter" "mistral" "zai" "moonshot" "deepseek" "google" "azure"+ "bedrock" "metabase"]))(defn do-with-connections![connections thunk]diff --git a/test/metabase/metabot/self/deepseek_test.clj b/test/metabase/metabot/self/deepseek_test.cljnew file mode 100644index 00000000000..bfeff72f8d3--- /dev/null+++ b/test/metabase/metabot/self/deepseek_test.clj@@ -0,0 +1,394 @@+(ns metabase.metabot.self.deepseek-test+ (:require+ [clj-http.client :as http]+ [clojure.string :as str]+ [clojure.test :refer :all]+ [metabase.llm.settings :as llm.settings]+ [metabase.metabot.self.claude :as claude]+ [metabase.metabot.self.core :as self.core]+ [metabase.metabot.self.debug :as debug]+ [metabase.metabot.self.deepseek :as deepseek]+ [metabase.metabot.skills :as skills]+ [metabase.metabot.test-util :as metabot.tu]+ [metabase.premium-features.core :as premium-features]+ [metabase.test :as mt]+ [metabase.util.json :as json]))++(set! *warn-on-reflection* true)++(def ^:private user-message {:role :user :content "hi"})++(def ^:private byok-credentials+ "What a resolved DeepSeek connection hands the adapter: adapters read credentials only, never settings."+ {:api-key "sk-deepseek-byok" :base-url "https://api.deepseek.com"})++(defn- signed-reasoning+ [signature]+ {:type :reasoning+ :id "r1"+ :text "Let me look that up."+ :provider-metadata {:anthropic {:signature signature}}})++(def ^:private tool-call+ {:type :tool-input :id "call_00_abc" :function "get-time" :arguments {:tz "Asia/Tokyo"}})++(def ^:private tool-result+ {:type :tool-output :id "call_00_abc" :result {:output "13:00"}})++;;; ──────────────────────────────────────────────────────────────────+;;; The thinking directive+;;; ──────────────────────────────────────────────────────────────────++(deftest ^:parallel request-body-enables-thinking-by-default-test+ (is (= {:type "enabled"}+ (:thinking (deepseek/deepseek-request-body {:input [user-message]})))))++(deftest ^:parallel request-body-replays-reasoning-onto-the-tool-call-message-test+ (testing "a signed reasoning part rides the same assistant message as the tool_use it preceded"+ (is (=? [{:role "user"}+ {:role "assistant"+ :content [{:type "thinking" :thinking "Let me look that up." :signature "sig-1"}+ {:type "tool_use" :id "call_00_abc" :name "get-time"}]}+ {:role "user" :content [{:type "tool_result" :tool_use_id "call_00_abc"}]}]+ (:messages (deepseek/deepseek-request-body+ {:input [user-message (signed-reasoning "sig-1") tool-call tool-result]}))))))++(deftest ^:parallel request-body-disables-thinking-for-structured-output-test+ (testing "a schema forces tool_choice {:type \"tool\"}, which DeepSeek rejects in thinking mode"+ (let [body (deepseek/deepseek-request-body+ {:input [user-message (signed-reasoning "sig-1") tool-call tool-result]+ :schema {:type "object" :properties {:title {:type "string"}}}})]+ (is (= {:type "disabled"} (:thinking body)))+ (is (= {:type "tool" :name "structured_output"} (:tool_choice body)))+ (is (not-any? #(some (comp #{"thinking"} :type) (:content %)) (:messages body))))))++(deftest ^:parallel request-body-keeps-thinking-under-required-tool-choice-test+ (testing "tool_choice \"required\" maps to {:type \"any\"}, which DeepSeek accepts with thinking on"+ (let [body (deepseek/deepseek-request-body+ {:input [user-message]+ :tools [(metabot.tu/get-time-tool)]+ :tool_choice "required"})]+ (is (= {:type "any"} (:tool_choice body)))+ (is (= {:type "enabled"} (:thinking body))))))++(deftest ^:parallel request-body-disables-thinking-for-the-dialect-preload-test+ (testing "the synthetic load_skill pair carries no signed reasoning, so thinking is turned off"+ (let [preload (skills/dialect-preload-parts "postgres")]+ (is (seq preload))+ (is (= {:type "disabled"}+ (:thinking (deepseek/deepseek-request-body+ {:input (vec (concat [user-message] preload))})))))))++(deftest ^:parallel request-body-keeps-thinking-for-a-signed-tool-call-test+ (testing "the agent-loop shape — signed reasoning ahead of the tool call — keeps thinking on"+ (is (= {:type "enabled"}+ (:thinking (deepseek/deepseek-request-body+ {:input [user-message (signed-reasoning "sig-1") tool-call tool-result]}))))))++(deftest ^:parallel request-body-ignores-tool-calls-in-closed-turns-test+ (testing "provenance is only checked over the open turn, so a later user message clears an unsigned call"+ (let [preload (skills/dialect-preload-parts "postgres")]+ (is (= {:type "enabled"}+ (:thinking (deepseek/deepseek-request-body+ {:input (vec (concat [user-message] preload [user-message]))})))))))++(deftest ^:parallel request-body-disables-thinking-when-reasoning-is-off-test+ (let [body (deepseek/deepseek-request-body+ {:input [user-message (signed-reasoning "sig-1") tool-call tool-result]+ :reasoning? false})]+ (is (= {:type "disabled"} (:thinking body)))+ (is (not-any? #(some (comp #{"thinking"} :type) (:content %)) (:messages body)))))++(deftest ^:parallel request-body-always-carries-a-thinking-directive-test+ (testing "an omitted directive leaves thinking on, so every request states it explicitly"+ (doseq [schema [nil {:type "object"}]+ tool_choice [nil "auto" "required"]+ reasoning? [true false]]+ (let [opts (cond-> {:input [user-message]+ :tools [(metabot.tu/get-time-tool)]+ :reasoning? reasoning?}+ schema (assoc :schema schema)+ tool_choice (assoc :tool_choice tool_choice))]+ (is (contains? #{{:type "enabled"} {:type "disabled"}}+ (:thinking (deepseek/deepseek-request-body opts)))+ (pr-str opts))))))++;;; ──────────────────────────────────────────────────────────────────+;;; Body shape inherited from the Anthropic dialect+;;; ──────────────────────────────────────────────────────────────────++(deftest ^:parallel request-body-anthropic-shape-test+ (let [body (deepseek/deepseek-request-body+ {:system "You are Metabot."+ :input [user-message]+ :tools [(metabot.tu/get-time-tool)]})]+ (testing "the model defaults to deepseek-v4-pro"+ (is (= "deepseek-v4-pro" (:model body))))+ (testing "an unknown model id falls back to the shared max_tokens ceiling"+ (is (= 64000 (:max_tokens body))))+ (is (true? (:stream body)))+ (testing "the system prompt is sent as cache-marked content blocks"+ (is (=? [{:type "text" :text "You are Metabot." :cache_control {:type "ephemeral"}}]+ (:system body))))+ (testing "tools use the Anthropic envelope"+ (is (=? [{:name "get-time" :input_schema {:type "object"}}] (:tools body))))))++;;; ──────────────────────────────────────────────────────────────────+;;; Stream translation+;;;+;;; Events transcribed from a live `deepseek-v4-flash` capture: a thinking block+;;; (whose content_block_start carries no id) followed by two parallel tool_use+;;; blocks with distinct ids.+;;; ──────────────────────────────────────────────────────────────────++(def ^:private stream-events+ [{:type "message_start"+ :message {:id "dd71c602-baab-442c-88ec-3d57b85447b3"+ :role "assistant"+ :model "deepseek-v4-flash"+ :usage {:input_tokens 47 :cache_creation_input_tokens 0 :cache_read_input_tokens 384 :output_tokens 0}}}+ {:type "content_block_start" :index 0 :content_block {:type "thinking" :thinking "" :signature ""}}+ {:type "ping"}+ {:type "content_block_delta" :index 0 :delta {:type "thinking_delta" :thinking "The user wants two cities."}}+ {:type "content_block_delta" :index 0 :delta {:type "signature_delta" :signature "dd71c602-baab-442c-88ec-3d57b85447b3"}}+ {:type "content_block_stop" :index 0}+ {:type "content_block_start" :index 1 :content_block {:type "tool_use" :id "call_00_cB0D45Xgu" :name "get-time" :input {}}}+ {:type "content_block_delta" :index 1 :delta {:type "input_json_delta" :partial_json "{\"tz\":\"Asia/Tokyo\"}"}}+ {:type "content_block_stop" :index 1}+ {:type "content_block_start" :index 2 :content_block {:type "tool_use" :id "call_01_nOr1amlw2" :name "get-time" :input {}}}+ {:type "content_block_delta" :index 2 :delta {:type "input_json_delta" :partial_json "{\"tz\":\"Europe/Paris\"}"}}+ {:type "content_block_stop" :index 2}+ {:type "message_delta"+ :delta {:stop_reason "tool_use"}+ :usage {:input_tokens 47 :cache_creation_input_tokens 0 :cache_read_input_tokens 384 :output_tokens 137}}+ {:type "message_stop"}])++(defn- sse-response+ [events]+ {:status 200+ :body (java.io.ByteArrayInputStream.+ (.getBytes (str/join (map #(str "data: " (json/encode %) "\n\n") events)) "UTF-8"))})++(defn- aisdk-parts!+ [events]+ (with-redefs [debug/capture-stream (fn [r _] r)+ http/request (fn [_] (sse-response events))]+ (into [] (self.core/aisdk-xf) (deepseek/deepseek {:input [user-message]+ :credentials byok-credentials}))))++(deftest deepseek-uses-claude-stream-translation-test+ (let [parts (aisdk-parts! stream-events)]+ (testing "thinking, parallel tool calls, and usage all translate"+ (is (=? [{:type :start :id "dd71c602-baab-442c-88ec-3d57b85447b3"}+ {:type :reasoning+ :text "The user wants two cities."+ :provider-metadata {:anthropic {:signature "dd71c602-baab-442c-88ec-3d57b85447b3"}}}+ {:type :tool-input :id "call_00_cB0D45Xgu" :function "get-time" :arguments {:tz "Asia/Tokyo"}}+ {:type :tool-input :id "call_01_nOr1amlw2" :function "get-time" :arguments {:tz "Europe/Paris"}}+ {:type :usage}]+ parts)))+ (testing "the disjoint input buckets are summed into promptTokens"+ (is (=? {:type :usage+ :model "deepseek-v4-flash"+ :usage {:promptTokens 431+ :completionTokens 137+ :cacheCreationTokens 0+ :cacheReadTokens 384}}+ (last parts))))))++(deftest reasoning-round-trips-within-a-turn-test+ (testing "reasoning captured off the stream replays as a thinking block on the tool-call message"+ (let [parts (filterv #(#{:text :reasoning :tool-input} (:type %)) (aisdk-parts! stream-events))]+ (is (=? [{:role "user"}+ {:role "assistant"+ :content [{:type "thinking"+ :thinking "The user wants two cities."+ :signature "dd71c602-baab-442c-88ec-3d57b85447b3"}+ {:type "tool_use" :id "call_00_cB0D45Xgu"}+ {:type "tool_use" :id "call_01_nOr1amlw2"}]}]+ (:messages (deepseek/deepseek-request-body+ {:input (into [user-message] parts)})))))))++;;; ──────────────────────────────────────────────────────────────────+;;; Auth and request routing+;;; ──────────────────────────────────────────────────────────────────++(defn- captured-request!+ [f]+ (let [captured (atom nil)]+ (with-redefs [self.core/sse-reducible identity+ debug/capture-stream (fn [r _] r)+ http/request (fn [req] (reset! captured req) {:body req})]+ (f))+ @captured))++(deftest deepseek-auth-preferences-test+ (mt/with-premium-features #{:metabase-ai-managed}+ (mt/with-dynamic-fn-redefs [premium-features/premium-embedding-token (constantly "proxy-token")]+ (mt/with-temporary-setting-values [llm.settings/llm-proxy-base-url "https://proxy.example"]+ (testing "uses the connection's own credentials rather than the ai proxy"+ (is (=? {:method :post+ :url "https://api.deepseek.com/anthropic/v1/messages"+ :headers {"Authorization" "Bearer sk-deepseek-byok"+ "anthropic-version" "2023-06-01"}}+ (captured-request! #(deepseek/deepseek-raw {:input [user-message]+ :credentials byok-credentials})))))+ (testing "does not fall back to the ai proxy when the connection carries no key"+ (is (thrown-with-msg?+ clojure.lang.ExceptionInfo+ #"No DeepSeek API key is set"+ (deepseek/deepseek-raw {:input [user-message]}))))+ (testing "does not borrow the single-provider setting when the connection carries no key"+ (mt/with-temporary-setting-values [llm.settings/llm-deepseek-api-key "sk-deepseek-elsewhere"]+ (is (thrown-with-msg?+ clojure.lang.ExceptionInfo+ #"No DeepSeek API key is set"+ (deepseek/deepseek-raw {:input [user-message]+ :credentials {:api-key ""}})))))))))++(deftest deepseek-raw-explicit-credentials-test+ (testing "the connection's base URL is used over the configured one"+ (mt/with-temporary-setting-values [llm.settings/llm-deepseek-api-base-url "https://configured.example"]+ (is (=? {:url "https://explicit.example/anthropic/v1/messages"+ :headers {"Authorization" "Bearer sk-deepseek-explicit"}}+ (captured-request! #(deepseek/deepseek-raw+ {:input [user-message]+ :credentials {:api-key "sk-deepseek-explicit"+ :base-url "https://explicit.example"}})))))))++(deftest deepseek-raw-ai-proxy-unsupported-test+ (testing "ai-proxy? throws before credentials are even consulted"+ (with-redefs [http/request (fn [_] (throw (ex-info "should never be called" {})))]+ (is (thrown-with-msg?+ clojure.lang.ExceptionInfo+ #"AI proxy is not supported for DeepSeek"+ (deepseek/deepseek-raw {:input [user-message] :ai-proxy? true}))))))++(deftest list-models-ai-proxy-unsupported-test+ (testing "ai-proxy? throws before credentials are even consulted"+ (with-redefs [http/request (fn [_] (throw (ex-info "should never be called" {})))]+ (is (thrown-with-msg?+ clojure.lang.ExceptionInfo+ #"AI proxy is not supported for DeepSeek"+ (deepseek/list-models {:ai-proxy? true}))))))++(deftest chat-and-catalog-share-one-base-url-test+ (testing "the base URL carries neither /anthropic nor /v1 — both paths hang off the same root"+ (is (= "https://api.deepseek.com/anthropic/v1/messages"+ (:url (captured-request! #(deepseek/deepseek-raw {:input [user-message]+ :credentials byok-credentials})))))+ (mt/with-dynamic-fn-redefs [http/request (fn [req]+ (is (= "https://api.deepseek.com/models" (:url req)))+ {:status 200 :body {:data []}})]+ (is (= {:models []} (deepseek/list-models {:credentials byok-credentials}))))))++;;; ──────────────────────────────────────────────────────────────────+;;; list-models+;;; ──────────────────────────────────────────────────────────────────++(deftest list-models-filters-catalog-to-whitelist-test+ (testing "display names come from the whitelist — DeepSeek catalog entries carry none"+ (mt/with-dynamic-fn-redefs [http/request (fn [req]+ (is (=? {:method :get+ :headers {"Authorization" "Bearer sk-deepseek-byok"}}+ req))+ {:status 200+ :body {:data [{:id "deepseek-v4-flash"}+ {:id "deepseek-v4-pro"}+ {:id "deepseek-chat"}]}})]+ (is (= {:models [{:id "deepseek-v4-flash" :display_name "DeepSeek V4 Flash"}+ {:id "deepseek-v4-pro" :display_name "DeepSeek V4 Pro"}]}+ (deepseek/list-models {:credentials byok-credentials}))))))++(deftest list-models-explicit-credentials-test+ (testing "a passed-in api-key is used over the configured key"+ (mt/with-temporary-setting-values [llm.settings/llm-deepseek-api-key "sk-deepseek-setting"]+ (mt/with-dynamic-fn-redefs [http/request (fn [req]+ (is (=? {:headers {"Authorization" "Bearer sk-deepseek-explicit"}}+ req))+ {:status 200 :body {:data []}})]+ (is (= {:models []} (deepseek/list-models {:credentials {:api-key "sk-deepseek-explicit"}})))))))++(deftest list-models-blank-credentials-do-not-borrow-the-setting-test+ (testing "a blank api-key does not fall back to the single-provider setting"+ (mt/with-temporary-setting-values [llm.settings/llm-deepseek-api-key "sk-deepseek-elsewhere"]+ (is (thrown-with-msg?+ clojure.lang.ExceptionInfo+ #"No DeepSeek API key is set"+ (deepseek/list-models {:credentials {:api-key ""}}))))))++(deftest list-models-blank-credentials-without-configured-key-test+ (testing "throws when the passed-in api-key is blank and no key is configured"+ (mt/with-temporary-setting-values [llm.settings/llm-deepseek-api-key nil]+ (is (thrown-with-msg?+ clojure.lang.ExceptionInfo+ #"No DeepSeek API key is set"+ (deepseek/list-models {:credentials {:api-key ""}}))))))++(deftest list-models-malformed-catalog-throws-test+ (testing "a 2xx whose body carries no model list throws instead of reporting an empty catalog"+ (mt/with-dynamic-fn-redefs [http/request (fn [_] {:status 200 :body "<html>Not Found</html>"})]+ (is (thrown-with-msg?+ clojure.lang.ExceptionInfo+ #"DeepSeek returned an unexpected model list response"+ (deepseek/list-models {:credentials byok-credentials}))))))++;;; ──────────────────────────────────────────────────────────────────+;;; Error translation+;;; ──────────────────────────────────────────────────────────────────++(defn- list-models-error-message!+ [status]+ (with-redefs [http/request (fn [_] (throw (ex-info "HTTP error"+ {:status status+ :headers {"content-type" "application/json"}+ :body "{\"error\":{\"message\":\"nope\"}}"})))]+ (try+ (deepseek/list-models {:credentials byok-credentials})+ (catch Exception e+ (ex-message e)))))++(deftest error-status-messages-test+ (testing "4xx statuses that mean a rejected request say so — the admin UI renders any 4xx under the API-key field"+ (is (str/starts-with? (list-models-error-message! 400) "DeepSeek rejected the request"))+ (is (str/starts-with? (list-models-error-message! 422) "DeepSeek rejected the request parameters")))+ (testing "an exhausted balance is not a key problem"+ (is (str/starts-with? (list-models-error-message! 402) "DeepSeek account balance is exhausted")))+ (testing "auth failures keep the canonical message and withhold the upstream body"+ (is (= "DeepSeek API key expired or invalid" (list-models-error-message! 401))))+ (is (str/starts-with? (list-models-error-message! 429) "DeepSeek has rate limited us"))+ (is (str/starts-with? (list-models-error-message! 503) "DeepSeek is overloaded"))+ (is (str/starts-with? (list-models-error-message! 418) "DeepSeek API error (HTTP 418)")))++;;; ──────────────────────────────────────────────────────────────────+;;; Reasoning capability reporting+;;; ──────────────────────────────────────────────────────────────────++(deftest ^:parallel reasoning-model-test+ (is (true? (deepseek/reasoning-model? "deepseek-v4-flash")))+ (is (true? (deepseek/reasoning-model? "deepseek-v4-pro")))+ (is (false? (deepseek/reasoning-model? "deepseek-chat"))))++;;; ──────────────────────────────────────────────────────────────────+;;; The shared claude.clj hook+;;; ──────────────────────────────────────────────────────────────────++(deftest ^:parallel claude-request-body-unchanged-without-reasoning-config-test+ (doseq [opts [{:model "claude-sonnet-4-6" :input [user-message]}+ {:model "claude-sonnet-4-6" :input [user-message] :schema {:type "object"}}+ {:model "claude-sonnet-4-6" :input [user-message] :tool_choice "required"+ :tools [(metabot.tu/get-time-tool)]}+ {:model "claude-haiku-4-5-20251001" :input [user-message]}]]+ (is (= (dissoc (claude/claude-request-body opts) :thinking)+ (dissoc (claude/claude-request-body (assoc opts :reasoning-config nil)) :thinking))+ (pr-str opts))))++(deftest ^:parallel claude-request-body-reasoning-config-overrides-suppression-test+ (testing "an explicit config survives the rules that would otherwise suppress thinking"+ (doseq [opts [{:model "claude-sonnet-4-6" :input [user-message] :schema {:type "object"}}+ {:model "claude-sonnet-4-6" :input [user-message] :tool_choice "required"+ :tools [(metabot.tu/get-time-tool)]}+ {:model "not-a-claude-model" :input [user-message]}]]+ (is (= {:type "enabled"}+ (:thinking (claude/claude-request-body (assoc opts :reasoning-config {:type "enabled"}))))+ (pr-str opts)))))diff --git a/test/metabase/metabot/self_test.clj b/test/metabase/metabot/self_test.cljindex bd021e6a546..406268d59b7 100644--- a/test/metabase/metabot/self_test.clj+++ b/test/metabase/metabot/self_test.clj@@ -72,6 +72,8 @@(#'self/parse-provider-model "mistral/mistral-medium-3-5")))(is (=? {:provider "moonshot" :model "kimi-k3" :ai-proxy? false}(#'self/parse-provider-model "moonshot/kimi-k3")))+ (is (=? {:provider "deepseek" :model "deepseek-v4-flash" :ai-proxy? false}+ (#'self/parse-provider-model "deepseek/deepseek-v4-flash")))(is (=? {:provider "google" :model "google/gemini-3.5-flash" :ai-proxy? false}(#'self/parse-provider-model "google/google/gemini-3.5-flash"))))(testing "a vLLM served model is often a Hugging Face repo id, so the model segment keeps its slashes"@@ -98,6 +100,7 @@(is (fn? (#'self/resolve-adapter "zai")))(is (fn? (#'self/resolve-adapter "mistral")))(is (fn? (#'self/resolve-adapter "moonshot")))+ (is (fn? (#'self/resolve-adapter "deepseek")))(is (fn? (#'self/resolve-adapter "google")))(is (fn? (#'self/resolve-adapter "vllm"))))(testing "throws for unknown provider"