Skip to content

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

BOT-1895: Stream reasoning tokens for 7 more LLM providers (#81956)

Paolo Rascunà2e1a0c1a2c03
diff --git a/src/metabase/metabot/self/azure.clj b/src/metabase/metabot/self/azure.clj
index 9d0160bc71c..3459d3c47c2 100644
--- a/src/metabase/metabot/self/azure.clj
+++ b/src/metabase/metabot/self/azure.clj
@@ -21,7 +21,6 @@
[metabase.metabot.self.core :as core]
[metabase.metabot.self.debug :as debug]
[metabase.metabot.self.openai :as openai]
- [metabase.metabot.settings :as metabot.settings]
[metabase.util :as u]
[metabase.util.i18n :refer [tru]]
[metabase.util.json :as json]
@@ -34,25 +33,42 @@
;;; --------------------------------------------- API family dispatch -------------------------------------------
-(defn- model->family
- "Which wire-protocol family serves `model`, by its explicit first segment: `:anthropic` or `:openai`."
+(defn- model-family
+ "Which wire-protocol family serves `model`, by its explicit first segment: `:anthropic`, `:openai`, or nil."
[model]
(cond
(str/starts-with? (str model) "anthropic/") :anthropic
- (str/starts-with? (str model) "openai/") :openai
- :else
- (throw (ex-info (tru "Unsupported Azure model {0}. Only anthropic/* and openai/* models are supported." (pr-str model))
- {:api-error true
- :error-code :unsupported-model
- ;; a deployment the admin typed, so this is a bad request rather than an outage
- :status-code 400
- :model model}))))
+ (str/starts-with? (str model) "openai/") :openai))
+
+(defn- model->family
+ "Like [[model-family]], but throws for models outside the supported families."
+ [model]
+ (or (model-family model)
+ (throw (ex-info (tru "Unsupported Azure model {0}. Only anthropic/* and openai/* models are supported." (pr-str model))
+ {:api-error true
+ :error-code :unsupported-model
+ ;; a deployment the admin typed, so this is a bad request rather than an outage
+ :status-code 400
+ :model model}))))
(defn- model->deployment
"The Azure deployment name carried by a `{family}/{deployment-name}` model string."
[model]
(second (str/split (str model) #"/" 2)))
+(defn reasoning-model?
+ "Whether the deployment behind a `{family}/{deployment}` model string streams reasoning.
+
+ Deployment names are admin-chosen free text, so this is best-effort by name — and symmetric
+ with the request body, which derives its thinking config from the same string. A deployment
+ whose name resembles a reasoning model while serving a different one gets reasoning request
+ fields the served model may reject; name deployments after the model they serve."
+ [model]
+ (case (model-family model)
+ :anthropic (claude/reasoning-model? (model->deployment model))
+ :openai (openai/reasoning-model? (model->deployment model))
+ nil false))
+
(def ^:private model-context-windows
"Input context windows for the models Azure sells, keyed by model id.
GPT values are max input tokens (Microsoft's listed windows are input + output totals):
@@ -174,13 +190,6 @@
(when-not (= 400 (:status (ex-data e)))
(throw e)))))
-(defn- configured-azure-model
- "The saved `{family}/{deployment}` model string when the connection Metabot is pointed at is an Azure one."
- []
- (let [{:keys [type model]} (llm.provider/resolve-model-ref (metabot.settings/llm-metabot-provider))]
- (when (= type "azure")
- model)))
-
(defn list-models
"Validate Azure credentials with a model-free round trip and return an empty model list.
@@ -191,11 +200,11 @@
chat time with `DeploymentNotFound`.
Opts: `:credentials` (`{:api-key ... :base-url ...}`), `:model` (the `{family}/{deployment}`
- string selecting which surface family to validate; defaults to the saved Azure model), and
+ string selecting which surface family to validate; without it validation is skipped), and
`:ai-proxy?`, which is not supported for Azure and throws when true."
([] (list-models {}))
([{:keys [credentials model ai-proxy?]}]
- (when-let [model (or (not-empty model) (configured-azure-model))]
+ (when-let [model (not-empty model)]
(try
(case (model->family model)
:anthropic (validate-anthropic-surface! credentials ai-proxy?)
@@ -212,7 +221,7 @@
throws when they are missing. `:ai-proxy?` is not supported for Azure and throws when true."
[{:keys [model input tools credentials ai-proxy?] :as opts} :- core/LLMRequestOpts]
(let [family (model->family model)
- opts (assoc opts :model (model->deployment model) :reasoning? false :fast? false)
+ opts (assoc opts :model (model->deployment model) :fast? false)
{:keys [path headers req]}
(case family
:anthropic {:path "/v1/messages"
diff --git a/src/metabase/metabot/self/bedrock.clj b/src/metabase/metabot/self/bedrock.clj
index 511b264654f..6524faf1c08 100644
--- a/src/metabase/metabot/self/bedrock.clj
+++ b/src/metabase/metabot/self/bedrock.clj
@@ -298,17 +298,39 @@
(def ^:private anthropic-version "2023-06-01")
-(defn- model->family
- "Which mantle API family serves `model`, by vendor prefix: `:anthropic` or `:openai`."
+(defn- model-family
+ "Which mantle API family serves `model`, by vendor prefix: `:anthropic`, `:openai`, or nil."
[model]
(cond
- (str/starts-with? model "anthropic.") :anthropic
- (str/starts-with? model "openai.") :openai
- :else
- (throw (ex-info (tru "Unsupported Bedrock model {0}. Only anthropic.* and openai.* models are supported." model)
- {:api-error true
- :error-code :unsupported-model
- :model model}))))
+ (str/starts-with? (str model) "anthropic.") :anthropic
+ (str/starts-with? (str model) "openai.") :openai))
+
+(defn- model->family
+ "Like [[model-family]], but throws for models outside the supported families."
+ [model]
+ (or (model-family model)
+ (throw (ex-info (tru "Unsupported Bedrock model {0}. Only anthropic.* and openai.* models are supported." model)
+ {:api-error true
+ :error-code :unsupported-model
+ :model model}))))
+
+(defn reasoning-model?
+ "Whether `model` streams renderable reasoning back to us.
+
+ False (rather than [[model->family]]'s throw) outside the supported families:
+ the settings capability gate asks about whatever model is selected."
+ [model]
+ (case (model-family model)
+ :anthropic (claude/reasoning-model? model)
+ ;; The mantle's Responses surface accepts the reasoning request fields and
+ ;; the GPT models do reason (at a per-model default effort: gpt-5.4 "none",
+ ;; gpt-5.5 "medium"), but it never streams reasoning summaries — `summary`
+ ;; comes back empty at every effort/summary combination — so nothing will
+ ;; ever render. The request deliberately keeps its reasoning fields (see
+ ;; [[openai/openai-request-body]]): where the model reasons by default they
+ ;; buy encrypted-content replay across tool calls.
+ :openai false
+ nil false))
(defn ->mantle-anthropic-body
"Adapt a canonical Anthropic Messages request body for the mantle endpoint.
@@ -326,7 +348,7 @@
`:ai-proxy?` is not supported for Bedrock and throws when true."
[{:keys [model input tools credentials ai-proxy?] :as opts
:or {model default-model}} :- core/LLMRequestOpts]
- (let [opts (assoc opts :model model :reasoning? false :fast? false)
+ (let [opts (assoc opts :model model :fast? false)
family (model->family model)
{:keys [path headers req]}
(case family
diff --git a/src/metabase/metabot/self/catalog.clj b/src/metabase/metabot/self/catalog.clj
index 50176aedb3f..a49e140f5a9 100644
--- a/src/metabase/metabot/self/catalog.clj
+++ b/src/metabase/metabot/self/catalog.clj
@@ -3,28 +3,41 @@
and model behind it serve."
(:require
[metabase.llm.provider :as llm.provider]
+ [metabase.metabot.self.azure :as azure]
+ [metabase.metabot.self.bedrock :as bedrock]
[metabase.metabot.self.claude :as claude]
[metabase.metabot.self.deepseek :as deepseek]
[metabase.metabot.self.google :as google]
+ [metabase.metabot.self.mistral :as mistral]
+ [metabase.metabot.self.moonshot :as moonshot]
[metabase.metabot.self.openai :as openai]
- [metabase.metabot.self.vllm :as vllm]))
+ [metabase.metabot.self.openrouter :as openrouter]
+ [metabase.metabot.self.vllm :as vllm]
+ [metabase.metabot.self.zai :as zai]))
(set! *warn-on-reflection* true)
(defn streams-reasoning?
"Whether a model reference names a model that streams its reasoning back to us.
- Anthropic and OpenAI answer from the model name, because thinking is requested in the request body. vLLM answers
+ Anthropic, OpenAI, DeepSeek, Z.AI, OpenRouter, Google, Mistral, Moonshot, and — delegating per API family —
+ Bedrock and Azure answer from the model name, because thinking is requested in the request body. vLLM answers
from what its connect-time probe observed and recorded on the connection — the flag depends on the operator's
- `--reasoning-parser` as well as on the model, so the name cannot settle it."
+ `--reasoning-parser` as well as on the model, so the name cannot settle it. Unknown provider types answer false."
[model-ref]
(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)
- "google" (google/reasoning-model? model)
- "vllm" (vllm/reasoning-connection? credentials)
+ "anthropic" (claude/reasoning-model? model)
+ "azure" (azure/reasoning-model? model)
+ "bedrock" (bedrock/reasoning-model? model)
+ "deepseek" (deepseek/reasoning-model? model)
+ "google" (google/reasoning-model? model)
+ "mistral" (mistral/reasoning-model? model)
+ "moonshot" (moonshot/reasoning-model? model)
+ "openai" (openai/reasoning-model? model)
+ "openrouter" (openrouter/reasoning-model? model)
+ "vllm" (vllm/reasoning-connection? credentials)
+ "zai" (zai/reasoning-model? model)
false)))
(defn supports-fast-mode?
diff --git a/src/metabase/metabot/self/claude.clj b/src/metabase/metabot/self/claude.clj
index 85e4efbd4cf..53ec830e01f 100644
--- a/src/metabase/metabot/self/claude.clj
+++ b/src/metabase/metabot/self/claude.clj
@@ -209,20 +209,6 @@
:content (into [] (mapcat (comp ->content-blocks :content)) group)}])))
messages))
-(defn- merge-reasoning
- "Join consecutive same-id `:reasoning` parts (streamed as small parts plus a
- metadata carrier) into one block, keeping its provider metadata."
- [parts]
- (->> parts
- (partition-by (fn [p] (if (= :reasoning (:type p)) [:reasoning (:id p)] :other)))
- (mapcat (fn [group]
- (if (= :reasoning (:type (first group)))
- [{:type :reasoning
- :id (:id (first group))
- :text (->> group (map :text) (str/join ""))
- :provider-metadata (some :provider-metadata group)}]
- group)))))
-
(defn parts->claude-messages
"Convert a sequence of AISDK parts into Claude API messages.
@@ -238,7 +224,8 @@
reasoning (foreign parts, interrupted blocks) is dropped."
[parts]
(->> parts
- merge-reasoning
+ ;; a signed thinking block must be echoed back as ONE block or Claude 400s
+ core/merge-reasoning-parts
(into []
(keep (fn [part]
(case (:type part)
@@ -392,9 +379,11 @@
{:id id :display_name (or display_name (get-in supported-models [id :display-name]))})))}))
(defn- strip-vendor-prefix
- "`model` without an optional vendor prefix (e.g. Bedrock's `anthropic.`)."
+ "`model` lowercased and without an optional vendor prefix (e.g. Bedrock's `anthropic.`).
+
+ Lowercasing lets the model-derived predicates hold for Azure's admin-cased deployment names."
[model]
- (str/replace-first (str model) #"^anthropic\." ""))
+ (str/replace-first (u/lower-case-en (str model)) #"^anthropic\." ""))
(defn- model-max-tokens
"The `max_tokens` ceiling for `model`, or nil when it isn't one we know."
@@ -409,7 +398,10 @@
(defn- claude-model-version
"`[family major minor]` for a Claude opus/sonnet model id, or nil."
[model]
- (when-let [[_ family major minor] (re-find #"^claude-(opus|sonnet)-(\d+)(?:-(\d+))?"
+ ;; the minor version accepts both separators: canonical ids are hyphenated (claude-opus-4-8)
+ ;; but Azure admins name deployments freely, and the dotted display-name spelling
+ ;; (claude-opus-4.8) is the norm for the GPT family next to it
+ (when-let [[_ family major minor] (re-find #"^claude-(opus|sonnet)-(\d+)(?:[-.](\d+))?"
(strip-vendor-prefix model))]
[family (parse-long major) (or (some-> minor parse-long) 0)]))
diff --git a/src/metabase/metabot/self/core.clj b/src/metabase/metabot/self/core.clj
index 00818000b70..30371e49dfa 100644
--- a/src/metabase/metabot/self/core.clj
+++ b/src/metabase/metabot/self/core.clj
@@ -297,6 +297,27 @@
[]
(aisdk-xf {:stream-text? true}))
+(defn merge-reasoning-parts
+ "Joins consecutive same-id :reasoning parts into one, carrying the block's provider metadata.
+
+ A reasoning block streams as many small parts plus a possible empty-text metadata carrier;
+ every replay channel needs the block back as ONE part — replaying one fragment apiece costs
+ wrapper tokens (~3 prompt tokens each, measured on Mistral 2026-09-01) and would split a
+ signed Anthropic thinking block from its signature. Non-reasoning parts pass through
+ untouched, in order."
+ [parts]
+ (into []
+ (comp (partition-by (fn [p] (if (= :reasoning (:type p)) [:reasoning (:id p)] :other)))
+ (mapcat (fn [group]
+ (if (= :reasoning (:type (first group)))
+ (let [metadata (some :provider-metadata group)]
+ [(cond-> {:type :reasoning
+ :id (:id (first group))
+ :text (apply str (map :text group))}
+ metadata (assoc :provider-metadata metadata))])
+ group))))
+ parts))
+
(defn stamp-tool-titles-xf
"Stamp a client-facing `:title` onto `:tool-input` parts via each tool's
optional `:title-fn`. Stringified JSON is coerced and the tool's `:decode` is
diff --git a/src/metabase/metabot/self/google.clj b/src/metabase/metabot/self/google.clj
index 252a59ce0bc..89d8abb59a8 100644
--- a/src/metabase/metabot/self/google.clj
+++ b/src/metabase/metabot/self/google.clj
@@ -31,6 +31,7 @@
[metabase.llm.settings :as llm]
[metabase.metabot.self.core :as core]
[metabase.metabot.self.debug :as debug]
+ [metabase.metabot.self.google.models :as models]
[metabase.metabot.self.google.raw-predict :as raw-predict]
[metabase.metabot.self.google.stream-generate-content :as stream-generate-content]
[metabase.util :as u]
@@ -313,16 +314,6 @@
"The verb that serves Gemini models, asking for its stream as SSE rather than a JSON array."
":streamGenerateContent?alt=sse")
-(def ^:private gemini-context-windows
- "Input context windows for known Google Gemini models, keyed by publisher-qualified model id.
- Values:
- - https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/gemini/3-5-flash
- - https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/gemini/3-6-flash
- - https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/gemini/3-7-flash"
- {"google/gemini-3.5-flash" 1048576
- "google/gemini-3.6-flash" 1048576
- "google/gemini-3.7-flash" 1048576})
-
(defn reasoning-model?
"Whether a publisher-qualified `model` streams its reasoning back to us.
@@ -332,18 +323,19 @@
[model]
(case (model-families (model-publisher model))
:anthropic (raw-predict/reasoning-model? (model-id model))
- :google (stream-generate-content/reasoning-model? (model-id model))
+ :google (stream-generate-content/reasoning-model? model)
false))
(defn context-window-tokens
"The input context window for a publisher-qualified `model`, or nil when it isn't one we know.
+ Gemini windows come from the [[models/catalog]], the same rows that drive the reasoning gate.
Answers nil for a model this adapter cannot serve rather than throwing the way [[model->family]] does, for the
same reason [[reasoning-model?]] does."
[model]
(case (model-families (model-publisher model))
:anthropic (raw-predict/context-window-tokens (model-id model))
- :google (get gemini-context-windows model)
+ :google (get-in models/catalog [model :context-window])
nil))
(defn- model-resource-path
@@ -526,7 +518,8 @@
(let [family (model->family model)
req (case family
:anthropic (raw-predict/request-body (model-id model) opts)
- :google (stream-generate-content/request-body opts))
+ ;; pass the defaulted model down: the thinking directive keys off it
+ :google (stream-generate-content/request-body (assoc opts :model model)))
method (case family
:anthropic raw-predict-method
:google generate-content-method)
diff --git a/src/metabase/metabot/self/google/models.clj b/src/metabase/metabot/self/google/models.clj
new file mode 100644
index 00000000000..9e253582cd4
--- /dev/null
+++ b/src/metabase/metabot/self/google/models.clj
@@ -0,0 +1,30 @@
+(ns metabase.metabot.self.google.models
+ "The Gemini model catalog for the Google provider, and the predicates derived from it.
+
+ One catalog serves both halves of the adapter: [[metabase.metabot.self.google]] answers context
+ windows and the settings reasoning gate from it, and
+ [[metabase.metabot.self.google.stream-generate-content]] builds the thinking directive from it,
+ so the gate and the request body cannot disagree.")
+
+(def catalog
+ "The Gemini models Metabot supports, with what the adapter needs to know about each.
+
+ The same three models the connection form offers (the google entry in `metabase.llm.provider`);
+ a test pins the two lists together. All are Gemini 3 models: they think by default and thinking
+ cannot be turned off, so [[reasoning-model?]] is membership in this catalog.
+ https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/thinking
+ Context windows:
+ - https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/gemini/3-5-flash
+ - https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/gemini/3-6-flash
+ - https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/gemini/3-7-flash"
+ {"google/gemini-3.5-flash" {:context-window 1048576}
+ "google/gemini-3.6-flash" {:context-window 1048576}
+ "google/gemini-3.7-flash" {:context-window 1048576}})
+
+(defn reasoning-model?
+ "Whether `model` streams thought summaries that our chain-of-thought UI renders.
+
+ True exactly for the [[catalog]] models. Off-catalog models get no thinking directive and the
+ settings gate answers false for them, as with the other whitelisted providers."
+ [model]
+ (contains? catalog (str model)))
diff --git a/src/metabase/metabot/self/google/stream_generate_content.clj b/src/metabase/metabot/self/google/stream_generate_content.clj
index d8e73b4e243..335416d4049 100644
--- a/src/metabase/metabot/self/google/stream_generate_content.clj
+++ b/src/metabase/metabot/self/google/stream_generate_content.clj
@@ -8,6 +8,7 @@
(:require
[clojure.string :as str]
[metabase.metabot.self.core :as core]
+ [metabase.metabot.self.google.models :as models]
[metabase.metabot.self.schema :as schema]
[metabase.util :as u]
[metabase.util.json :as json]
@@ -83,7 +84,8 @@
sequence of parts keeps. `functionResponse.name` is necessary, but a :tool-output part that we rebuilt from
conversation history has no :function. For such a part, the name comes from the :tool-input part with the same id. A
`thoughtSignature` from stream time (see [[->aisdk-chunks-xf]]) goes back on the replayed functionCall part, because
- Gemini 3.x rejects a replay in the current turn that has no signature."
+ Gemini 3.x rejects a replay in the current turn that has no signature. :reasoning parts are display-only and
+ contribute no content here."
[parts]
(let [id->name (into {}
(comp (filter #(= :tool-input (:type %)))
@@ -111,6 +113,11 @@
(when-let [err (:error part)]
(str "Error: " (:message err)))
(pr-str (:result part)))}}}]}
+ ;; Reasoning is display-only: thought summaries never go back to Gemini. The
+ ;; model keeps its reasoning continuity through the functionCall
+ ;; thoughtSignatures replayed above. The empty :parts vector is dropped by
+ ;; [[merge-consecutive]] before role runs are computed.
+ :reasoning {:role "model" :parts []}
;; User messages pass through.
{:role (->gemini-role (or (:role part) "user"))
:parts (->text-parts (:content part))})))
@@ -132,13 +139,60 @@
;;; Request body
+(def ^:private forced-tool-call-token-floor
+ "Smallest `maxOutputTokens` a forced tool call on a catalog Gemini may be capped at.
+
+ Gemini 3 thinking cannot be turned off
+ (https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/thinking) and is billed against
+ `maxOutputTokens` alongside the answer, so a small caller cap risks a `MAX_TOKENS` finish before the forced tool
+ call is emitted. Probed 2026-09-09 on gemini-3.7-flash at `thinkingLevel LOW`: the spend is bimodal — 0 on most
+ runs, 200–490 when it fires — so the tail is the risk, not the median, and the ceiling across ~100 calls was 490
+ thinking tokens (554 total). [[metabase.metabot.example-question-generator]]'s own prompt, run at a 512 cap, spent
+ the whole budget thinking on one run in six and returned no functionCall; it escapes that in production only
+ because its call site already asks for 4096. The other two structured callers cap at 512
+ ([[metabase.metabot.conversation-title]]) and 1024 ([[metabase.contextual-interestingness.llm]]).
+
+ The Gemini numbers support any floor at or above roughly 768. 2048 is not derived from them: it is the value vLLM
+ proved and Moonshot, Z.AI and OpenRouter share. It carries ~4x margin over the worst spend measured, at no cost —
+ only the tokens actually generated are billed."
+ 2048)
+
(mu/defn request-body
"Builds the `streamGenerateContent` request body for an LLM request."
- [{:keys [system input tools schema tool_choice temperature max-tokens]} :- core/LLMRequestOpts]
+ [{:keys [system input tools schema tool_choice temperature max-tokens model reasoning?]
+ :or {reasoning? true}} :- core/LLMRequestOpts]
(let [fdecls (when (seq tools) (mapv tool->function-declaration tools))
+ forced? (or (some? schema) (= "required" (some-> tool_choice name)))
+ ;; Thinking is always on for the catalog's Gemini 3 models and has no off switch
+ ;; (https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/thinking).
+ ;; Off-catalog models get no thinkingConfig at all: non-thinking models reject the
+ ;; field outright, pre-Gemini-3 models reject thinkingLevel, and the reasoning gate
+ ;; answers false for them.
+ thinking (when (models/reasoning-model? model)
+ (cond
+ ;; Structured output — :schema, set by call-llm-structured-with-trace — is a
+ ;; one-shot internal call: nobody sees the thinking, and it eats the small
+ ;; maxOutputTokens budget the forced tool-call answer needs. z.ai disables
+ ;; thinking for the same reason ([[metabase.metabot.self.zai/zai-request-body]]);
+ ;; Gemini has no off switch, so pin the lowest level every catalog model
+ ;; supports — gemini-3.7-flash has no MINIMAL. LOW is a smaller spend, not no
+ ;; spend, so it is half the defence: the floor below raises the budget itself.
+ schema {:thinkingLevel "LOW"}
+ ;; The chat path streams to the browser: ask for the thought summaries the
+ ;; chain-of-thought UI renders, and leave the default thinking level alone.
+ reasoning? {:includeThoughts true}))
+ ;; Safety net: the forced tool call must survive the un-disableable thinking spend, which
+ ;; Gemini bills against maxOutputTokens (see [[forced-tool-call-token-floor]]). Only an
+ ;; existing cap is raised, and only where a tool call is actually forced — the chat path
+ ;; sends no cap at all. Independent of :reasoning?, because a catalog model thinks whether
+ ;; or not we asked it to.
+ max-tokens (cond-> max-tokens
+ (and max-tokens forced? (models/reasoning-model? model))
+ (max forced-tool-call-token-floor))
gen-config (cond-> {}
max-tokens (assoc :maxOutputTokens max-tokens)
- temperature (assoc :temperature temperature))]
+ temperature (assoc :temperature temperature)
+ thinking (assoc :thinkingConfig thinking))]
(cond-> {:contents (parts->contents input)}
(seq gen-config) (assoc :generationConfig gen-config)
system (assoc :systemInstruction {:parts [{:text system}]})
@@ -221,11 +275,12 @@
(str "Gemini stopped early (" reason ")")))
(defn reasoning-model?
- "Whether `model-id` streams its reasoning back to us.
- No Gemini model does today: thinking arrives as parts marked `:thought`, which [[->aisdk-chunks-xf]] drops. Should
- the adapter start forwarding them, this is where the models that send them get named."
- [_model-id]
- false)
+ "Whether a publisher-qualified Gemini `model` streams thought summaries that our chain-of-thought UI renders.
+
+ True exactly for the [[metabase.metabot.self.google.models]] catalog, the same whitelist the
+ [[request-body]] thinking directive keys off, so the gate and the request cannot disagree."
+ [model]
+ (models/reasoning-model? model))
(defn ->aisdk-chunks-xf
"Translates `streamGenerateContent` SSE events into AI SDK v5 protocol chunks.
@@ -239,72 +294,100 @@
Emits the same internal chunk types as the other adapters:
:start, :text-start, :text-delta, :text-end,
+ :reasoning-start, :reasoning-delta, :reasoning-end,
:tool-input-start, :tool-input-delta, :tool-input-available,
:usage, :error
Unlike Claude, there are no content-block start and stop events. Text streams as consecutive parts, and one open
text block holds them all. Each functionCall part arrives with complete args, thus its start, delta, and available
- chunks go out together. Parts with `:thought true` (thinking summaries) are ignored, as in the other adapters. A
- `finishReason` closes the open text block and is added to the :usage chunk as :finish-reason and :raw-finish-reason;
- the reasons that need one also emit an :error chunk (see [[finish-reason-error]]). Usage is buffered, the last value
- wins, and it goes out once at the end of the stream, because an event in the middle can have partial usageMetadata."
+ chunks go out together. Parts with `:thought true` are the thought summaries that [[request-body]] asks for; they
+ stream as reasoning blocks the same way text does, and a thought/text transition closes the one block kind and
+ opens the other. A `thoughtSignature` on a thought or text part is dropped: replaying one is optional, per the
+ \"Signatures in non-functionCall Parts\" section of
+ https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/thinking/thought-signatures, and reasoning
+ is display-only for us. A `finishReason` closes the open text and reasoning blocks and is added to the :usage
+ chunk as :finish-reason and :raw-finish-reason; the reasons that need one also emit an :error chunk (see
+ [[finish-reason-error]]). Usage is buffered, the last value wins, and it goes out once at the end of the stream,
+ because an event in the middle can have partial usageMetadata."
[]
(fn [rf]
- (let [message-id (volatile! nil)
- model-name (volatile! nil)
- text-id (volatile! nil) ; Non-nil while a text block is open.
- usage-acc (volatile! nil)
- stop-reason (volatile! nil)
- close-text! (fn [result]
- (if-let [id @text-id]
- (do (vreset! text-id nil)
- (rf result {:type :text-end :id id}))
- result))
- finish! (fn [result reason]
- (vreset! stop-reason reason)
- (when-not (= reason finish-reason-completed)
- (log/info "Gemini stopped early" {:finishReason reason}))
- (let [result (close-text! result)]
- (if-let [error-text (finish-reason-error reason)]
- (rf result {:type :error :errorText error-text})
- result)))
- emit-part (fn [result {:keys [text functionCall thought thoughtSignature]}]
- (cond
- thought
- result
-
- functionCall
- (let [tool-id (core/mkid)
- ids {:toolCallId tool-id :toolName (:name functionCall)}
- ;; Gemini 3.x adds a thoughtSignature to functionCall parts, which
- ;; must go back to Google on replay. Put it on the start chunk,
- ;; thus it stays in the :tool-input part as :provider-metadata.
- start (cond-> (merge {:type :tool-input-start} ids)
- thoughtSignature
- (assoc :providerMetadata {:google {:thoughtSignature thoughtSignature}}))]
- (-> (close-text! result)
- (rf start)
- (rf {:type :tool-input-delta
- :toolCallId tool-id
- :inputTextDelta (json/encode (or (:args functionCall) {}))})
- (rf (merge {:type :tool-input-available} ids))))
-
- ;; Open a text block only for text that is not empty, thus an empty part
- ;; between tool calls does not divide them. In an open block, blank
- ;; deltas pass through and keep the whitespace.
- (some? text)
- (if-let [id @text-id]
- (rf result {:type :text-delta :id id :delta text})
- (if (empty? text)
- result
- (let [id (core/mkid)]
- (vreset! text-id id)
- (-> result
- (rf {:type :text-start :id id})
- (rf {:type :text-delta :id id :delta text})))))
-
- :else
- result))]
+ (let [message-id (volatile! nil)
+ model-name (volatile! nil)
+ text-id (volatile! nil) ; Non-nil while a text block is open.
+ reasoning-id (volatile! nil) ; Non-nil while a reasoning block is open.
+ usage-acc (volatile! nil)
+ stop-reason (volatile! nil)
+ close-text! (fn [result]
+ (if-let [id @text-id]
+ (do (vreset! text-id nil)
+ (rf result {:type :text-end :id id}))
+ result))
+ close-reasoning! (fn [result]
+ (if-let [id @reasoning-id]
+ (do (vreset! reasoning-id nil)
+ (rf result {:type :reasoning-end :id id}))
+ result))
+ close-blocks! (fn [result]
+ (-> result close-text! close-reasoning!))
+ finish! (fn [result reason]
+ (vreset! stop-reason reason)
+ (when-not (= reason finish-reason-completed)
+ (log/info "Gemini stopped early" {:finishReason reason}))
+ (let [result (close-blocks! result)]
+ (if-let [error-text (finish-reason-error reason)]
+ (rf result {:type :error :errorText error-text})
+ result)))
+ emit-part (fn [result {:keys [text functionCall thought thoughtSignature]}]
+ (cond
+ functionCall
+ (let [tool-id (core/mkid)
+ ids {:toolCallId tool-id :toolName (:name functionCall)}
+ ;; Gemini 3.x adds a thoughtSignature to functionCall parts, which
+ ;; must go back to Google on replay. Put it on the start chunk,
+ ;; thus it stays in the :tool-input part as :provider-metadata.
+ start (cond-> (merge {:type :tool-input-start} ids)
+ thoughtSignature
+ (assoc :providerMetadata
+ {:google {:thoughtSignature thoughtSignature}}))]
+ (-> (close-blocks! result)
+ (rf start)
+ (rf {:type :tool-input-delta
+ :toolCallId tool-id
+ :inputTextDelta (json/encode (or (:args functionCall) {}))})
+ (rf (merge {:type :tool-input-available} ids))))
+
+ ;; Thought and text share one block discipline: open a block only for
+ ;; text that is not empty, thus an empty part between tool calls does
+ ;; not divide them, and close the other block kind only when actually
+ ;; opening — a part that emits nothing must close nothing, because a
+ ;; signature can ride a part with empty text mid-stream. In an open
+ ;; block, blank deltas pass through and keep the whitespace.
+ thought
+ (if-let [id @reasoning-id]
+ (if (some? text)
+ (rf result {:type :reasoning-delta :id id :delta text})
+ result)
+ (if (empty? text)
+ result
+ (let [id (core/mkid)]
+ (vreset! reasoning-id id)
+ (-> (close-text! result)
+ (rf {:type :reasoning-start :id id})
+ (rf {:type :reasoning-delta :id id :delta text})))))
+
+ (some? text)
+ (if-let [id @text-id]
+ (rf result {:type :text-delta :id id :delta text})
+ (if (empty? text)
+ result
+ (let [id (core/mkid)]
+ (vreset! text-id id)
+ (-> (close-reasoning! result)
+ (rf {:type :text-start :id id})
+ (rf {:type :text-delta :id id :delta text})))))
+
+ :else
+ result))]
(fn
([result]
;; An early stop that emits no :error chunk still needs a :usage chunk when the stream carried no
@@ -315,7 +398,7 @@
(when (early-stops-without-error reason)
(usage->aisdk-usage nil)))]
(-> result
- (close-text!)
+ (close-blocks!)
(cond-> usage
(rf (cond-> {:type :usage
:usage usage
@@ -340,10 +423,10 @@
(seq (:parts content)) (as-> res (u/reduce-preserving-reduced emit-part res (:parts content)))
(some? finishReason) (finish! finishReason)
;; A blocked prompt ends the stream with no candidates, only promptFeedback.
- (some? block-reason) (-> (close-text!)
+ (some? block-reason) (-> (close-blocks!)
(rf {:type :error
:errorText (str "Prompt blocked by Google: " block-reason)}))
;; An error envelope in the stream, e.g. a failure in the middle of the stream.
- (some? error) (-> (close-text!)
+ (some? error) (-> (close-blocks!)
(rf {:type :error
:errorText (or (:message error) (pr-str error))})))))))))
diff --git a/src/metabase/metabot/self/mistral.clj b/src/metabase/metabot/self/mistral.clj
index cc0d283a10e..c89aac4f4f8 100644
--- a/src/metabase/metabot/self/mistral.clj
+++ b/src/metabase/metabot/self/mistral.clj
@@ -45,6 +45,16 @@
[model]
(get-in supported-models [model :context-window]))
+(defn reasoning-model?
+ "Whether `model` streams thinking that our chain-of-thought UI renders.
+
+ True exactly for the [[supported-models]] whitelist. Off-catalog models — including
+ catalog aliases like `mistral-medium-latest`, which are not resolved, as with
+ [[context-window-tokens]] — get no reasoning directive and the settings gate answers
+ false for them; the server default sends no thinking either way."
+ [model]
+ (contains? supported-models (str model)))
+
(defn- whitelisted-id
"The [[supported-models]] id a `/models` catalog entry resolves to, or nil when unsupported.
Mistral models have a generic `:id` like `mistral-medium-latest` but `:aliases` contains version specific aliases
@@ -88,6 +98,22 @@
(mapv (fn [id]
{:id id :display_name (get-in supported-models [id :display-name])})))}))
+(defn- think-message
+ "The replayed assistant message for a coalesced in-turn :reasoning part.
+
+ Mistral's reasoning docs instruct replaying think chunks with the assistant message —
+ the \"Multi-turn conversations\" section of
+ https://docs.mistral.ai/studio/conversations/reasoning: \"always replay the full assistant
+ message (including ThinkChunk)\"; stripping them \"significantly degrades output quality\".
+ The reconstructed chunk deliberately carries neither :closed — `closed false` is rejected
+ on replay (error 3240; omission means closed) — nor the captured :signature: the model
+ rejects any signature today (\"Signature is not supported for this model\", error 3051,
+ probed 2026-09-01), so emission waits for Mistral to accept one; the capture side already
+ delivers it in :provider-metadata when that day comes."
+ [part]
+ {:role "assistant"
+ :content [{:type "thinking" :thinking [{:type "text" :text (:text part)}]}]})
+
(mu/defn mistral-request-body
"Build the Chat Completions request body for an LLM request.
@@ -96,12 +122,29 @@
- Mistral's strict request validation 422s (`Extra inputs are not permitted`) on `stream_options`; it is dropped
here, and Mistral reports usage on the final streamed chunk without it.
- Prompt caching is opt-in per request via `prompt_cache_key` (cache reads bill at 10% of the input price), so a
- `:prompt-cache-key` — the conversation id — is forwarded when present."
- [{:keys [model prompt-cache-key] :as opts
- :or {model default-model}} :- core/LLMRequestOpts]
- (-> (chat-completions/request-body (assoc opts :model model))
- (dissoc :stream_options)
- (cond-> prompt-cache-key (assoc :prompt_cache_key prompt-cache-key))))
+ `:prompt-cache-key` — the conversation id — is forwarded when present.
+ - Whitelisted models get a `reasoning_effort` directive and replay their in-turn reasoning as think chunks
+ (see [[think-message]])."
+ [{:keys [model prompt-cache-key reasoning? schema] :as opts
+ :or {model default-model reasoning? true}} :- core/LLMRequestOpts]
+ ;; mistral-medium-3-5 accepts exactly "high" and "none" — the server 400s the other four
+ ;; enum values, enumerating these two (probed 2026-09-01) — and its server default sends NO
+ ;; thinking, so "high" is what makes reasoning exist at all: net-new completion tokens on
+ ;; every chat turn (a trivial prompt went from 4 to 247). "none" on the structured path is
+ ;; forward-protection should the server default ever change, not a change to today's
+ ;; behavior. https://docs.mistral.ai/studio/conversations/reasoning
+ (let [whitelisted? (reasoning-model? model)
+ ;; One binding gates both the "high" directive and the replay hook, so
+ ;; they cannot desynchronize: with :reasoning? false or on the
+ ;; structured path the hook is nil, which also strips :reasoning parts
+ ;; from the replayed input, honoring the LLMRequestOpts contract.
+ thinking? (and whitelisted? reasoning? (not schema))]
+ (-> (chat-completions/request-body
+ (assoc opts :model model)
+ (when thinking? {:reasoning-part->message think-message}))
+ (dissoc :stream_options)
+ (cond-> prompt-cache-key (assoc :prompt_cache_key prompt-cache-key)
+ whitelisted? (assoc :reasoning_effort (if thinking? "high" "none"))))))
(mu/defn mistral-raw
"Perform a streaming request to the Mistral Chat Completions API.
@@ -146,10 +189,51 @@
"model_length" "length"
"error" "error"))
+(defn- flatten-content-chunks
+ "Splits a chunked-content SSE event into the flat events the shared translation understands.
+
+ With reasoning on, Mistral streams `delta.content` as a vector of typed chunks — thinking
+ deltas, then one transition event carrying both the closing think chunk and the first text
+ chunk, then plain strings (probed 2026-09-01; `:closed` rides most mid-stream think deltas
+ too, so chunk STRUCTURE, not flags, decides). The shared xf reads only flat
+ `:reasoning`/`:content` strings and classifies content first, so the transition event must
+ become two events, reasoning first. The synthetic reasoning event keeps the top-level
+ :id/:model — :start is emitted from them — and carries nothing else; usage, finish_reason,
+ and tool_calls stay on the content event.
+
+ A think chunk's `signature` — defined for replay (ThinkChunk.signature in
+ https://docs.mistral.ai/openapi.yaml) but never emitted by mistral-medium-3-5 today (probed
+ 2026-09-01) — is lifted out as ready-namespaced :reasoning_metadata for the shared xf to ride
+ into provider metadata, ready for the day it appears; a signature-only think chunk still gets
+ its synthetic event, since the closing chunk of a block is where a signature would ride.
+
+ Chunk `:type` is optional in Mistral's OpenAPI spec, so dispatch is structural on the
+ :thinking/:text keys; chunk kinds carrying neither (references, files, audio — at either
+ nesting level) are dropped deliberately, like the parts the other adapters do not translate."
+ [event]
+ (let [content (get-in event [:choices 0 :delta :content])]
+ (if-not (vector? content)
+ [event]
+ (let [thinking (apply str (mapcat #(keep :text (:thinking %)) content))
+ text (apply str (keep :text content))
+ signature (some :signature (filter :thinking content))]
+ (cond-> []
+ (or (seq thinking) signature)
+ (conj (cond-> {:choices [{:delta (cond-> {}
+ (seq thinking) (assoc :reasoning thinking)
+ signature (assoc :reasoning_metadata
+ {:mistral {:signature signature}}))}]}
+ (:id event) (assoc :id (:id event))
+ (:model event) (assoc :model (:model event))))
+
+ true
+ (conj (assoc-in event [:choices 0 :delta :content] text)))))))
+
(defn mistral->aisdk-chunks-xf
"Translates Mistral Chat Completions streaming chunks into AI SDK v5 protocol chunks."
[]
- (chat-completions/chat-completions->aisdk-chunks-xf stop-reasons))
+ (comp (mapcat flatten-content-chunks)
+ (chat-completions/chat-completions->aisdk-chunks-xf stop-reasons {:forward-reasoning? true})))
(defn mistral
"Call the Mistral Chat Completions API, return AISDK stream."
diff --git a/src/metabase/metabot/self/moonshot.clj b/src/metabase/metabot/self/moonshot.clj
index ec79ab7b899..e229f0d59e1 100644
--- a/src/metabase/metabot/self/moonshot.clj
+++ b/src/metabase/metabot/self/moonshot.clj
@@ -59,6 +59,22 @@
thinking on, unlike k2.6."
#{"kimi-k3"})
+(def ^:private reasoning-models
+ "Models whose streamed thinking our chain-of-thought UI renders.
+
+ The [[thinking-only-models]] plus the thinking-optional kimi-k2.6. Today this equals the [[supported-models]]
+ key set, but deliberately so, not derived: rendering reasoning is a per-model product decision, and a newly
+ supported model must opt in here."
+ (conj thinking-only-models "kimi-k2.6"))
+
+(defn reasoning-model?
+ "Whether `model` streams thinking that our chain-of-thought UI renders.
+
+ True exactly for the [[reasoning-models]] whitelist; off-whitelist models get thinking disabled in the request,
+ so the settings gate and the stream agree by construction."
+ [model]
+ (contains? reasoning-models (str model)))
+
(defn- supported-model?
"Whether a `/models` catalog entry is one of the [[supported-models]]."
[{:keys [id]}]
@@ -102,6 +118,30 @@
(mapv (fn [{:keys [id]}]
{:id id :display_name (get-in supported-models [id :display-name])})))}))
+(def ^:private forced-tool-call-token-floor
+ "Smallest `max_tokens` a forced tool call on a thinking-only model may be capped at.
+
+ kimi-k3 cannot stop thinking and Chat Completions bills thinking and the tool call against one budget, so a small
+ caller cap (the conversation-title path sends 512) risks a `length` finish before the tool call is emitted.
+ Matches vLLM's probe-proven floor."
+ 2048)
+
+(defn- floor-max-tokens
+ "Raises an existing `max_tokens` cap to [[forced-tool-call-token-floor]]; an uncapped body stays uncapped."
+ [body]
+ (cond-> body (:max_tokens body) (update :max_tokens max forced-tool-call-token-floor)))
+
+(defn- reasoning-message
+ "The replayed assistant message for a coalesced in-turn :reasoning part.
+
+ Kimi thinking models require replaying reasoning with the assistant message it came with — \"pass the complete
+ assistant message returned by the API back to messages as-is (including reasoning_content)\"
+ (https://platform.kimi.ai/docs/guide/use-thinking-models). It rides as a top-level sibling of
+ `content`/`tool_calls`, so this message relies on [[chat-completions/parts->cc-messages]] merging it into the
+ round's assistant message; `:content \"\"` matches Moonshot's own emission shape and joins invisibly."
+ [part]
+ {:role "assistant" :content "" :reasoning_content (:text part)})
+
(mu/defn moonshot-request-body
"Build the Chat Completions request body for an LLM request.
@@ -110,19 +150,60 @@
- **No `temperature`.** Moonshot 400s on any value but the one its thinking mode allows (0.6 off, 1.0 on), so
there is no safe value to pass and it is dropped unconditionally.
- - **`thinking {:type \"disabled\"}`.** Thinking is on by default on every Kimi model, and `tool_choice
- \"required\"` — which the structured-output path and the `:sql` and `:document-generate-content` profiles all
- depend on — is rejected while it is on. We drop `reasoning_content` anyway, so thinking is pure cost
- (~12x the completion tokens for the same conversation title). [[thinking-only-models]] cannot disable it and
- does not need to, so they are sent no `thinking` at all and the model default applies.
+ - **`thinking`** on models that can switch it (today kimi-k2.6): `{:type \"enabled\"}` when the chat path
+ renders reasoning; `{:type \"disabled\"}` on the structured path, under a forced tool choice — k2.6 rejects
+ `tool_choice \"required\"` while thinking is on, which the structured-output path and the `:sql` and
+ `:document-generate-content` profiles all depend on — and for off-whitelist models. `thinking.keep` stays at
+ its default null, so k2.6 does not replay reasoning (see the hook note in the body).
+ [[thinking-only-models]] cannot disable thinking and are sent no `thinking` at all.
+ - **`reasoning_effort`** for [[thinking-only-models]] (kimi-k3, which explicitly does not support `thinking`
+ and is the only model accepting `reasoning_effort`): \"max\" when the chat path renders reasoning, \"low\"
+ otherwise; their in-turn reasoning is replayed (see [[reasoning-message]]) and forced tool calls get a
+ `max_tokens` floor (see [[forced-tool-call-token-floor]]).
- **`prompt_cache_key`.** Moonshot caching is automatic and hits without it, but a `:prompt-cache-key` — the
conversation id — is forwarded when present."
- [{:keys [model prompt-cache-key] :as opts
- :or {model default-model}} :- core/LLMRequestOpts]
- (-> (chat-completions/request-body (assoc opts :model model))
- (dissoc :temperature)
- (cond-> (not (thinking-only-models model)) (assoc :thinking {:type "disabled"})
- prompt-cache-key (assoc :prompt_cache_key prompt-cache-key))))
+ [{:keys [model prompt-cache-key reasoning? schema tool_choice] :as opts
+ :or {model default-model reasoning? true}} :- core/LLMRequestOpts]
+ ;; kimi-k3 always thinks — there is no off switch, so `reasoning_effort` ("low" | "high" | "max", server default
+ ;; "max") is the only knob (https://platform.kimi.ai/docs/guide/kimi-k3-quickstart). "max" on the chat path pins
+ ;; the documented default explicitly; "low" is the floor on the structured path and under :reasoning? false — a
+ ;; best-effort floor, not an off switch: the model thinks, bills, and streams regardless.
+ (let [whitelisted? (reasoning-model? model)
+ thinking-only? (contains? thinking-only-models (str model))
+ ;; k2.6 rejects `tool_choice "required"` while thinking is on (probe-derived, BOT-1929; no doc
+ ;; statement — unre-verified), so a forced tool choice turns k2.6's thinking off. k3 accepts the
+ ;; combination, so on thinking-only models only the schema call — a forced structured_output tool
+ ;; call whose stream no user ever sees (conversation titles and the like) — drops to the cheapest
+ ;; effort.
+ forced? (or (some? schema) (= "required" (some-> tool_choice name)))
+ ;; thinking? = "we want renderable thinking", not "the model will think" — k3 thinks regardless,
+ ;; which is why the floor arm below is keyed on the model class instead. One binding gates the
+ ;; effort level, the thinking switch, and the replay hook, so they cannot desynchronize; when it
+ ;; is false the nil hook also strips :reasoning parts from the replayed input, honoring the
+ ;; LLMRequestOpts contract.
+ thinking? (and whitelisted? reasoning?
+ (if thinking-only? (not schema) (not forced?)))]
+ (-> (chat-completions/request-body
+ (assoc opts :model model)
+ ;; Replay only where the dialect mandates it: k3's Preserved Thinking. k2.6 cannot use
+ ;; `thinking.keep "all"` — that mode obliges the caller to send back EVERY historical assistant
+ ;; message's reasoning_content, but reasoning parts are never persisted across turns, so we could
+ ;; honor it only within the current turn and would breach it on every turn after the first. k2.6
+ ;; therefore runs with keep at its default null, under which the server ignores replayed
+ ;; reasoning_content — a replay hook there would only burn prompt tokens.
+ ;; https://platform.kimi.ai/docs/guide/use-kimi-k2-thinking-model
+ (when (and thinking? thinking-only?) {:reasoning-part->message reasoning-message}))
+ (dissoc :temperature)
+ (cond-> thinking-only? (assoc :reasoning_effort (if thinking? "max" "low"))
+ ;; Every forced tool call — schema or tool_choice "required" — must survive the
+ ;; thinking spend: reasoning and the tool call share one max_tokens budget ("the
+ ;; sum of tokens in reasoning_content and content must be <= max_tokens", and the
+ ;; guide recommends >= 16000 for tool calls —
+ ;; https://platform.kimi.ai/docs/guide/use-thinking-models). A tool call cut off
+ ;; at `length` fails the whole turn.
+ (and thinking-only? forced?) floor-max-tokens
+ (not thinking-only?) (assoc :thinking {:type (if thinking? "enabled" "disabled")})
+ prompt-cache-key (assoc :prompt_cache_key prompt-cache-key)))))
(mu/defn moonshot-raw
"Perform a streaming request to the Moonshot Chat Completions API.
@@ -161,9 +242,15 @@
(core/rethrow-api-error! "moonshot" moonshot-error-msg e))))))
(defn moonshot->aisdk-chunks-xf
- "Translates Moonshot Chat Completions streaming chunks into AI SDK v5 protocol chunks."
+ "Translates Moonshot Chat Completions streaming chunks into AI SDK v5 protocol chunks.
+
+ Reasoning arrives as flat `delta.reasoning_content` strings, documented to always precede content deltas
+ (https://platform.kimi.ai/docs/guide/use-thinking-models). A delta carrying both `reasoning_content` and
+ non-empty `content` would drop its reasoning — the shared xf classifies content first. Accepted, unprobed risk:
+ no such chunk is documented or has been observed."
[]
- (chat-completions/chat-completions->aisdk-chunks-xf))
+ (chat-completions/chat-completions->aisdk-chunks-xf chat-completions/stop-reasons
+ {:forward-reasoning? true}))
(defn moonshot
"Call the Moonshot Chat Completions API, return AISDK stream."
diff --git a/src/metabase/metabot/self/openai.clj b/src/metabase/metabot/self/openai.clj
index e2f7a31312f..e04739d6042 100644
--- a/src/metabase/metabot/self/openai.clj
+++ b/src/metabase/metabot/self/openai.clj
@@ -305,12 +305,19 @@
(mapv (fn [{:keys [id]}]
{:id id :display_name (get-in supported-models [id :display-name])})))}))
+(defn- strip-vendor-prefix
+ "`model` lowercased and without an optional vendor prefix (e.g. Bedrock's `openai.`).
+
+ Lowercasing lets the model-derived predicates hold for Azure's admin-cased deployment names."
+ [model]
+ (str/replace-first (u/lower-case-en (str model)) #"^openai\." ""))
+
(defn- model-supports-temperature?
"Whether `model` accepts an explicit `temperature` parameter.
The GPT-5 family and the o-series reasoning models only support the default temperature."
[model]
- (let [model (str/replace-first (str model) #"^openai\." "")]
+ (let [model (strip-vendor-prefix model)]
(not (or (str/starts-with? model "gpt-5")
(re-find #"^o\d" model)))))
diff --git a/src/metabase/metabot/self/openai/chat_completions.clj b/src/metabase/metabot/self/openai/chat_completions.clj
index 30af804eb42..db682d54017 100644
--- a/src/metabase/metabot/self/openai/chat_completions.clj
+++ b/src/metabase/metabot/self/openai/chat_completions.clj
@@ -48,11 +48,30 @@
(mapcat (fn [group]
(if (and (< 1 (count group))
(= "assistant" (:role (first group))))
- (let [text (->> group (keep :content) (str/join ""))
- tool-calls (into [] (mapcat :tool_calls) group)]
+ (let [tool-calls (into [] (mapcat :tool_calls) group)
+ ;; :reasoning_content exists on a member only when the replay
+ ;; hook of [[parts->cc-messages]] minted it — today only
+ ;; Moonshot, whose dialect replays reasoning as a top-level
+ ;; sibling of :content (see
+ ;; [[metabase.metabot.self.moonshot/reasoning-message]]).
+ ;; Joined in part order: the wire has a single field per
+ ;; message, so order is the only fidelity available.
+ reasoning (apply str (keep :reasoning_content group))
+ ;; Vector (chunk-array) content exists only when the reasoning
+ ;; replay hook of [[parts->cc-messages]] produced it — today
+ ;; only Mistral's think chunks. Every other provider's members
+ ;; are strings or nil, so they always take the original string
+ ;; join below.
+ content (if (some (comp vector? :content) group)
+ (into [] (mapcat (fn [{c :content}]
+ (cond (vector? c) c
+ (not-empty c) [{:type "text" :text c}])))
+ group)
+ (->> group (keep :content) (str/join "")))]
;; :content should be always there, even if empty/nil
- [(cond-> {:role "assistant" :content text}
- (seq tool-calls) (assoc :tool_calls tool-calls))])
+ [(cond-> {:role "assistant" :content content}
+ (seq tool-calls) (assoc :tool_calls tool-calls)
+ (not-empty reasoning) (assoc :reasoning_content reasoning))])
group))))
messages))
@@ -66,30 +85,47 @@
{:type :tool-output, :id ..., :result ...}
Output: Chat Completions messages (user, assistant with tool_calls, tool)."
- [parts]
- (->> parts
- (keep (fn [part]
- (case (:type part)
- ;; reasoning is not replayable over Chat Completions
- :reasoning nil
- :text {:role "assistant" :content (:text part)}
- :tool-input {:role "assistant"
- :content nil
- :tool_calls [{:id (:id part)
- :type "function"
- :function {:name (:function part)
- :arguments (let [args (:arguments part)]
- (if (string? args) args (json/encode (or args {}))))}}]}
- :tool-output {:role "tool"
- :tool_call_id (:id part)
- :content (or (get-in part [:result :output])
- (when-let [err (:error part)]
- (str "Error: " (:message err)))
- (pr-str (:result part)))}
- ;; User messages pass through
- {:role (name (or (:role part) "user"))
- :content (or (:content part) "")})))
- merge-consecutive-assistant-messages))
+ ([parts] (parts->cc-messages parts nil))
+ ([parts {:keys [reasoning-part->message]}]
+ ;; coalescing runs only when a dialect passes a replay hook — today Mistral (think chunks)
+ ;; and Moonshot (top-level reasoning_content), the two Chat Completions dialects that define
+ ;; a reasoning replay channel
+ (->> (cond-> parts reasoning-part->message core/merge-reasoning-parts)
+ (keep (fn [part]
+ (case (:type part)
+ ;; The generic Chat Completions dialect has no replay channel for
+ ;; reasoning, so by default it drops here — this arm returns nil for
+ ;; every provider that doesn't pass a hook. A dialect that defines a
+ ;; channel passes :reasoning-part->message, a fn from a coalesced
+ ;; :reasoning part to a replayed assistant message (or nil); today
+ ;; Mistral (think chunks — see
+ ;; [[metabase.metabot.self.mistral/think-message]]) and Moonshot
+ ;; (top-level reasoning_content — see
+ ;; [[metabase.metabot.self.moonshot/reasoning-message]]) do. Z.AI and
+ ;; vLLM define no such channel yet; when they grow one, each gets its
+ ;; own hook fn here rather than more shared code.
+ :reasoning (when reasoning-part->message
+ (reasoning-part->message part))
+ :text {:role "assistant" :content (:text part)}
+ :tool-input {:role "assistant"
+ :content nil
+ :tool_calls [{:id (:id part)
+ :type "function"
+ :function {:name (:function part)
+ :arguments (let [args (:arguments part)]
+ (if (string? args)
+ args
+ (json/encode (or args {}))))}}]}
+ :tool-output {:role "tool"
+ :tool_call_id (:id part)
+ :content (or (get-in part [:result :output])
+ (when-let [err (:error part)]
+ (str "Error: " (:message err)))
+ (pr-str (:result part)))}
+ ;; User messages pass through
+ {:role (name (or (:role part) "user"))
+ :content (or (:content part) "")})))
+ merge-consecutive-assistant-messages)))
;;; Tool definition format
@@ -186,14 +222,22 @@
delta (:delta choice)
finish-reason (:finish_reason choice)
tool-call (first (:tool_calls delta))
+ reasoning-md (:reasoning_metadata delta)
;; Determine what kind of content this chunk carries.
;; Empty-string content (common between tool calls) is ignored
;; to avoid spurious text blocks that would close open tools.
chunk-type (cond
(not-empty (:content delta)) :text
+ ;; tool_calls outrank reasoning: a delta carrying both would
+ ;; otherwise classify as :reasoning, and the tool call's opening
+ ;; chunk — the only one carrying its id and name — would be
+ ;; lost, breaking the tool loop. Ranked this way, such a delta
+ ;; loses its reasoning fragment instead: display text,
+ ;; recoverable. No probed provider combines the two in one
+ ;; delta today.
+ (some? tool-call) :function_call
(and forward-reasoning?
(delta-reasoning delta)) :reasoning
- (some? tool-call) :function_call
:else nil)
;; For new tool calls, the id comes from the chunk; for deltas
;; on the same tool, we keep current-id.
@@ -236,6 +280,18 @@
(= chunk-type :reasoning) (rf {:type :reasoning-delta
:id @current-id
:delta (delta-reasoning delta)})
+ ;; A delta may carry ready-namespaced provider metadata for the
+ ;; open reasoning block, ridden out on its end chunk the way
+ ;; openai.clj rides out encrypted_content. :reasoning_metadata is
+ ;; not a wire key — no Chat Completions server emits it; only a
+ ;; dialect's own pre-transform mints it (today Mistral's
+ ;; flatten-content-chunks, carrying a think-chunk signature) — so
+ ;; this clause never fires for any other dialect. It is carried
+ ;; opaquely: the minting side owns the namespace inside it.
+ (and reasoning-md
+ (= @current-type :reasoning)) (u/prog1
+ (vswap! payload assoc
+ :providerMetadata reasoning-md))
;; Start a new tool call block
(and (= chunk-type :function_call)
(:id tool-call)
@@ -273,28 +329,34 @@
;;; Request body
(mu/defn request-body
- "Build the Chat Completions request body for an LLM request."
- [{:keys [model system input tools temperature max-tokens tool_choice schema]} :- core/LLMRequestOpts]
- (let [messages (cond-> (parts->cc-messages input)
- system (as-> msgs (into [{:role "system" :content system}] msgs)))
- all-tools (or (when schema
- ;; Structured output: force a tool call with the given JSON schema
- [{:type "function"
- :function {:name "structured_output"
- :description "Output structured data"
- :parameters schema}}])
- (seq (mapv tool->cc-tool tools)))]
- (cond-> {:model model
- :stream true
- :stream_options {:include_usage true}
- :messages messages}
- all-tools (assoc :tools (vec all-tools)
- :tool_choice (cond
- schema "required"
- tool_choice tool_choice
- :else "auto"))
- temperature (assoc :temperature temperature)
- max-tokens (assoc :max_tokens max-tokens))))
+ "Build the Chat Completions request body for an LLM request.
+
+ The optional `cc-opts` map holds dialect hooks that are not request options —
+ today only `:reasoning-part->message`, threaded to [[parts->cc-messages]]. A
+ fn-valued hook stays out of the traced and logged `LLMRequestOpts` on purpose."
+ ([opts] (request-body opts nil))
+ ([{:keys [model system input tools temperature max-tokens tool_choice schema]} :- core/LLMRequestOpts
+ cc-opts]
+ (let [messages (cond-> (parts->cc-messages input cc-opts)
+ system (as-> msgs (into [{:role "system" :content system}] msgs)))
+ all-tools (or (when schema
+ ;; Structured output: force a tool call with the given JSON schema
+ [{:type "function"
+ :function {:name "structured_output"
+ :description "Output structured data"
+ :parameters schema}}])
+ (seq (mapv tool->cc-tool tools)))]
+ (cond-> {:model model
+ :stream true
+ :stream_options {:include_usage true}
+ :messages messages}
+ all-tools (assoc :tools (vec all-tools)
+ :tool_choice (cond
+ schema "required"
+ tool_choice tool_choice
+ :else "auto"))
+ temperature (assoc :temperature temperature)
+ max-tokens (assoc :max_tokens max-tokens)))))
;;; Model catalog
diff --git a/src/metabase/metabot/self/openrouter.clj b/src/metabase/metabot/self/openrouter.clj
index 04cfe50416f..fff88b142bd 100644
--- a/src/metabase/metabot/self/openrouter.clj
+++ b/src/metabase/metabot/self/openrouter.clj
@@ -51,40 +51,83 @@
https://openrouter.ai/api/v1/models, taking the lower of `context_length` and
`top_provider.context_length` since a request can be routed to any backing provider.
OpenAI rows subtract the 128k max output from that total, recording max input like
- the direct openai adapter."
- {"anthropic/claude-fable-5" {:display-name "Claude Fable 5" :context-window 1000000}
- "anthropic/claude-opus-5" {:display-name "Claude Opus 5" :context-window 1000000}
- "anthropic/claude-opus-4.8" {:display-name "Claude Opus 4.8" :context-window 1000000}
- "anthropic/claude-opus-4.7" {:display-name "Claude Opus 4.7" :context-window 1000000}
- "anthropic/claude-opus-4.6" {:display-name "Claude Opus 4.6" :context-window 1000000}
- "anthropic/claude-opus-4.5" {:display-name "Claude Opus 4.5" :context-window 200000}
- "anthropic/claude-opus-4.1" {:display-name "Claude Opus 4.1" :context-window 200000}
- "anthropic/claude-sonnet-5" {:display-name "Claude Sonnet 5" :context-window 1000000}
- "anthropic/claude-sonnet-4.6" {:display-name "Claude Sonnet 4.6" :context-window 1000000}
- "anthropic/claude-sonnet-4.5" {:display-name "Claude Sonnet 4.5" :context-window 1000000}
- "anthropic/claude-haiku-4.5" {:display-name "Claude Haiku 4.5" :context-window 200000}
- "deepseek/deepseek-v4-pro" {:display-name "DeepSeek V4 Pro 0423" :context-window 1048576}
- "deepseek/deepseek-v4-pro-0813" {:display-name "DeepSeek V4 Pro 0813" :context-window 1048575}
- "deepseek/deepseek-v4-flash-0731" {:display-name "DeepSeek V4 Flash 0731" :context-window 1048576}
- "mistralai/mistral-medium-3-5" {:display-name "Mistral Medium 3.5" :context-window 262144}
- "moonshotai/kimi-k3" {:display-name "Kimi K3" :context-window 1048576}
- "openai/gpt-5.6-sol" {:display-name "GPT-5.6 Sol" :context-window 922000}
- "openai/gpt-5.6-terra" {:display-name "GPT-5.6 Terra" :context-window 922000}
- "openai/gpt-5.6-luna" {:display-name "GPT-5.6 Luna" :context-window 922000}
- "openai/gpt-5.5" {:display-name "GPT-5.5" :context-window 922000}
- "openai/gpt-5.5-pro" {:display-name "GPT-5.5 Pro" :context-window 922000}
- "openai/gpt-5.4" {:display-name "GPT-5.4" :context-window 922000}
- "openai/gpt-5.4-pro" {:display-name "GPT-5.4 Pro" :context-window 922000}
- "openai/gpt-5.4-mini" {:display-name "GPT-5.4 Mini" :context-window 272000}
- "qwen/qwen3.8-max" {:display-name "Qwen3.8 Max" :context-window 1000000}
- "z-ai/glm-5.3" {:display-name "GLM-5.3" :context-window 1048576}
- "z-ai/glm-5.2" {:display-name "GLM-5.2" :context-window 1048576}})
+ the direct openai adapter.
+
+ `:reasoning` classifies what each model streams back, probed live against OpenRouter on
+ 2026-08-31 (all 26 models) and cross-checked with the `reasoning` metadata in
+ `GET /v1/models` (https://openrouter.ai/docs/use-cases/reasoning-tokens):
+ `:renderable` streams reasoning text under an explicit `reasoning {:enabled true}`;
+ `:renderable-default` streams reasoning summaries under the server default but must receive
+ NO directive — an explicit enable verifiably suppresses gpt-5.6's reasoning entirely;
+ `:budget-only` (`supported_efforts` nil in the catalog) silently ignores the unified enable
+ and would need an explicit token budget.
+ `:reasoning-mandatory?` marks models where `reasoning {:enabled false}` is rejected with a 400."
+ {"anthropic/claude-fable-5" {:display-name "Claude Fable 5" :context-window 1000000 :reasoning :renderable :reasoning-mandatory? true}
+ "anthropic/claude-opus-5" {:display-name "Claude Opus 5" :context-window 1000000 :reasoning :renderable}
+ "anthropic/claude-opus-4.8" {:display-name "Claude Opus 4.8" :context-window 1000000 :reasoning :renderable}
+ "anthropic/claude-opus-4.7" {:display-name "Claude Opus 4.7" :context-window 1000000 :reasoning :renderable}
+ "anthropic/claude-opus-4.6" {:display-name "Claude Opus 4.6" :context-window 1000000 :reasoning :renderable}
+ "anthropic/claude-opus-4.5" {:display-name "Claude Opus 4.5" :context-window 200000 :reasoning :budget-only}
+ "anthropic/claude-opus-4.1" {:display-name "Claude Opus 4.1" :context-window 200000 :reasoning :budget-only}
+ "anthropic/claude-sonnet-5" {:display-name "Claude Sonnet 5" :context-window 1000000 :reasoning :renderable}
+ "anthropic/claude-sonnet-4.6" {:display-name "Claude Sonnet 4.6" :context-window 1000000 :reasoning :renderable}
+ "anthropic/claude-sonnet-4.5" {:display-name "Claude Sonnet 4.5" :context-window 1000000 :reasoning :budget-only}
+ "anthropic/claude-haiku-4.5" {:display-name "Claude Haiku 4.5" :context-window 200000 :reasoning :budget-only}
+ "deepseek/deepseek-v4-pro" {:display-name "DeepSeek V4 Pro 0423" :context-window 1048576 :reasoning :renderable}
+ "deepseek/deepseek-v4-pro-0813" {:display-name "DeepSeek V4 Pro 0813" :context-window 1048575 :reasoning :renderable}
+ "deepseek/deepseek-v4-flash-0731" {:display-name "DeepSeek V4 Flash 0731" :context-window 1048576 :reasoning :renderable}
+ "mistralai/mistral-medium-3-5" {:display-name "Mistral Medium 3.5" :context-window 262144 :reasoning :renderable}
+ ;; probed 2026-09-08: OpenRouter honors `reasoning {:enabled false}` for kimi-k3 even though the
+ ;; native Moonshot API cannot turn k3's thinking off — a title-shaped forced tool call under the
+ ;; disable reports 0 reasoning_tokens in usage and completes within 48 completion tokens, so the
+ ;; structured path needs neither a low effort nor the mandatory max_tokens floor
+ "moonshotai/kimi-k3" {:display-name "Kimi K3" :context-window 1048576 :reasoning :renderable}
+ "openai/gpt-5.6-sol" {:display-name "GPT-5.6 Sol" :context-window 922000 :reasoning :renderable-default}
+ "openai/gpt-5.6-terra" {:display-name "GPT-5.6 Terra" :context-window 922000 :reasoning :renderable-default}
+ "openai/gpt-5.6-luna" {:display-name "GPT-5.6 Luna" :context-window 922000 :reasoning :renderable-default}
+ "openai/gpt-5.5" {:display-name "GPT-5.5" :context-window 922000 :reasoning :renderable-default}
+ "openai/gpt-5.5-pro" {:display-name "GPT-5.5 Pro" :context-window 922000 :reasoning :renderable-default :reasoning-mandatory? true}
+ ;; re-probed 2026-09-04 (classed :encrypted-only on 2026-08-31): under the explicit enable
+ ;; both stream `reasoning.summary` text through the shared xf (~100 deltas on a hard prompt)
+ ;; and accept the disable; without a directive OpenAI's default is no reasoning at all —
+ ;; 0 reasoning tokens, and the mini answered the probe wrong
+ "openai/gpt-5.4" {:display-name "GPT-5.4" :context-window 922000 :reasoning :renderable}
+ "openai/gpt-5.4-mini" {:display-name "GPT-5.4 Mini" :context-window 272000 :reasoning :renderable}
+ "openai/gpt-5.4-pro" {:display-name "GPT-5.4 Pro" :context-window 922000 :reasoning :renderable-default :reasoning-mandatory? true}
+ "qwen/qwen3.8-max" {:display-name "Qwen3.8 Max" :context-window 1000000 :reasoning :renderable :reasoning-mandatory? true}
+ ;; probed 2026-09-04 (post-dating the 2026-08-31 run): the enable streams reasoning, the
+ ;; disable is rejected with a 400 (thinking-only upstream, as on native z.ai), and a forced
+ ;; tool call at the floored budget completes
+ "z-ai/glm-5.3" {:display-name "GLM-5.3" :context-window 1048576 :reasoning :renderable :reasoning-mandatory? true}
+ "z-ai/glm-5.2" {:display-name "GLM-5.2" :context-window 1048576 :reasoning :renderable}})
(defn context-window-tokens
"The input context window for `model`, or nil when it isn't one we know."
[model]
(get-in supported-models [model :context-window]))
+(defn- reasoning-class
+ "The `:reasoning` class [[supported-models]] records for `model`, or nil."
+ [model]
+ (get-in supported-models [(str model) :reasoning]))
+
+(defn reasoning-model?
+ "Whether `model` streams renderable reasoning back to us through OpenRouter.
+
+ True for the `:renderable` and `:renderable-default` classes (see [[supported-models]]).
+ Excluded: the budget-only Claudes, which silently ignore the unified enable
+ (https://openrouter.ai/docs/use-cases/reasoning-tokens)."
+ [model]
+ (contains? #{:renderable :renderable-default} (reasoning-class model)))
+
+(defn- reasoning-mandatory?
+ "Whether OpenRouter rejects `reasoning {:enabled false}` for `model` with a 400.
+
+ Probed live; the catalog's `mandatory` flag documents the same restriction:
+ https://openrouter.ai/docs/use-cases/reasoning-tokens."
+ [model]
+ (boolean (get-in supported-models [(str model) :reasoning-mandatory?])))
+
(defn- supported-model?
"Whether a `/v1/models` catalog entry is one of the [[supported-models]]."
[{:keys [id]}]
@@ -134,10 +177,19 @@
(defn openrouter->aisdk-chunks-xf
"Translates Chat Completions streaming chunks into AI SDK v5 protocol chunks.
+
OpenRouter streams the generic Chat Completions dialect; see
- [[chat-completions/chat-completions->aisdk-chunks-xf]]."
+ [[chat-completions/chat-completions->aisdk-chunks-xf]]. Reasoning arrives as a flat
+ `delta.reasoning` string (verified identical to the concatenation of the structured
+ `reasoning_details` text blocks) and is forwarded as reasoning chunks. A delta carrying both
+ `reasoning` and non-empty `content` would drop its reasoning — the shared xf classifies
+ content first; accepted, unprobed risk, no such chunk observed. Display-only: the
+ structured `reasoning_details` (signatures included) are not captured, so tool rounds
+ re-derive their reasoning rather than continuing it — extending that would touch both this
+ xf and the dialect-level replay; see the \"Preserving Reasoning\" section of
+ https://openrouter.ai/docs/use-cases/reasoning-tokens."
[]
- (chat-completions/chat-completions->aisdk-chunks-xf stop-reasons))
+ (chat-completions/chat-completions->aisdk-chunks-xf stop-reasons {:forward-reasoning? true}))
;;; HTTP request
@@ -183,6 +235,57 @@
(cond-> req
(= "required" (:tool_choice req)) (assoc :tool_choice "auto")))
+(def ^:private forced-tool-call-token-floor
+ "Smallest `max_tokens` a forced tool call on a mandatory-reasoning model may be capped at.
+
+ A safety net: in theory the un-disableable reasoning bills against the same `max_tokens` budget as the tool call
+ (\"max_tokens must be strictly higher than the reasoning budget\" —
+ https://openrouter.ai/docs/use-cases/reasoning-tokens), so a small caller cap (the conversation-title path sends
+ 512) could hit `length` before the mandatory tool call is emitted. In practice this has not been observed: probed
+ 2026-09-03, qwen3.8-max reasons only ~150 tokens on title-shaped structured calls and fits the 512 cap, and
+ claude-fable-5 emits zero reasoning under a forced tool choice; probed 2026-09-08, gpt-5.4-pro and gpt-5.5-pro
+ finish the same calls at the 512 cap with the tool call (242–375 and 22 completion tokens across runs). The floor
+ guards against a model update or a longer-thinking mandatory model changing that. Matches vLLM's probe-proven
+ floor."
+ 2048)
+
+(defn- with-reasoning-directive
+ "Add OpenRouter's unified `reasoning` directive to a built request `body`.
+
+ `:renderable`-class models get an explicit enable, or an explicit disable for structured
+ output and forced tool calls — probed live: forced tool choice yields zero reasoning tokens on
+ Anthropic upstreams even when enabled, so the disable mirrors what actually happens
+ (https://openrouter.ai/docs/use-cases/reasoning-tokens). Mandatory-reasoning models reject the
+ disable with a 400 and get no directive instead. `:renderable-default` models (the gpt-5.5/5.6
+ family) never get one either way — they stream summaries under the server default, and an
+ explicit enable verifiably suppresses gpt-5.6's reasoning entirely. Other models never get
+ one: the server default rules, and the gate answers false. Independently of the class, a
+ mandatory-reasoning model's forced tool calls get a `max_tokens` floor (see
+ [[forced-tool-call-token-floor]]) — gpt-5.5-pro and gpt-5.4-pro are mandatory but
+ `:renderable-default`, so the floor cannot live inside the `:renderable` branch. Reads the
+ body's own `:tool_choice` so it sees the [[required-tool-choice->auto]] downgrade, not the
+ incoming opts."
+ [body {:keys [model reasoning? schema] :or {reasoning? true}}]
+ (let [forced? (or (some? schema) (= "required" (:tool_choice body)))
+ ;; Safety net: the mandatory tool call must survive the un-disableable thinking spend
+ ;; (theory vs practice in [[forced-tool-call-token-floor]]); only an existing cap is
+ ;; raised, and only where a tool call is actually forced.
+ body (cond-> body
+ (and (reasoning-mandatory? model) forced? (:max_tokens body))
+ (update :max_tokens max forced-tool-call-token-floor))]
+ (if-not (= :renderable (reasoning-class model))
+ body
+ (let [thinking? (and reasoning? (not forced?))]
+ (cond
+ thinking? (cond-> (assoc body :reasoning {:enabled true})
+ ;; Anthropic rejects an explicit temperature while
+ ;; thinking (same interlock as claude.clj); sonnet-4.6
+ ;; and opus-4.6 keep :temperature past
+ ;; [[model-supports-temperature?]], so drop it here
+ (anthropic-model? model) (dissoc :temperature))
+ (reasoning-mandatory? model) body
+ :else (assoc body :reasoning {:enabled false}))))))
+
(mu/defn openrouter-request-body
"Build the Chat Completions request body for an LLM request.
@@ -198,15 +301,16 @@
whose model names are customer-chosen free text."
[{:keys [model system] :as opts
:or {model "anthropic/claude-haiku-4.5"}} :- core/LLMRequestOpts]
- (cond-> (chat-completions/request-body (assoc opts :model model))
- (and system (anthropic-model? model))
- (update-in [:messages 0 :content] claude/system->cached-content-blocks)
+ (-> (cond-> (chat-completions/request-body (assoc opts :model model))
+ (and system (anthropic-model? model))
+ (update-in [:messages 0 :content] claude/system->cached-content-blocks)
- (not (model-supports-temperature? model))
- (dissoc :temperature)
+ (not (model-supports-temperature? model))
+ (dissoc :temperature)
- (not (supports-required-tool-choice? model))
- required-tool-choice->auto))
+ (not (supports-required-tool-choice? model))
+ required-tool-choice->auto)
+ (with-reasoning-directive (assoc opts :model model))))
(mu/defn openrouter-raw
"Perform a streaming request to the Chat Completions API.
diff --git a/src/metabase/metabot/self/zai.clj b/src/metabase/metabot/self/zai.clj
index 265c99e0806..dee411df0db 100644
--- a/src/metabase/metabot/self/zai.clj
+++ b/src/metabase/metabot/self/zai.clj
@@ -36,8 +36,11 @@
(def supported-models
"Z.AI models offered in the Metabot model picker, keyed by model id.
- `list-models` returns the intersection of this map with the `/models` catalog."
- {"glm-5.3" {:display-name "GLM-5.3" :context-window 1048576}
+ `list-models` returns the intersection of this map with the `/models` catalog.
+
+ `:thinking-only?` marks a model that rejects `thinking {:type \"disabled\"}` — see
+ [[thinking-only-model?]]."
+ {"glm-5.3" {:display-name "GLM-5.3" :context-window 1048576 :thinking-only? true}
"glm-5.2" {:display-name "GLM-5.2" :context-window 1048576}})
(defn context-window-tokens
@@ -50,6 +53,24 @@
[{:keys [id]}]
(contains? supported-models id))
+(defn reasoning-model?
+ "Whether `model` streams reasoning back to us.
+
+ True only for the whitelisted GLM models, which think by default — thinking defaults to enabled
+ server-side (https://docs.z.ai/api-reference/llm/chat-completion)."
+ [model]
+ (contains? supported-models (str model)))
+
+(defn- thinking-only-model?
+ "Whether `model` rejects `thinking {:type \"disabled\"}` outright.
+
+ Z.AI answers error 1210 \"always engages in thinking\" for these and takes `reasoning_effort`
+ low|high|max instead (https://docs.z.ai/api-reference/llm/chat-completion, probed on glm-5.3
+ 2026-09-03). Reading the flag off a [[supported-models]] row keeps it from ever disagreeing with
+ [[reasoning-model?]]: a model can only be thinking-only if we serve it."
+ [model]
+ (boolean (get-in supported-models [(str model) :thinking-only?])))
+
(defn- list-all-models
"Fetch the full Z.AI model catalog (`GET /models`).
@@ -87,15 +108,52 @@
(mapv (fn [{:keys [id] :as model}]
{:id id :display_name (or (:name model) (get-in supported-models [id :display-name]))})))}))
+(def ^:private forced-tool-call-token-floor
+ "Smallest `max_tokens` a forced tool call on a thinking-only model may be capped at.
+
+ glm-5.3 cannot stop thinking, and its thinking and tool call draw on one `max_tokens` budget — undocumented by
+ Z.AI, but probed 2026-09-08: a title-shaped structured call capped at 16 finished `length` on reasoning alone, with
+ no tool call. A small caller cap (the conversation-title path sends 512) therefore risks a `length` finish before
+ the tool call is emitted. At effort max the same calls spent 102–173 completion tokens, so 512 holds today but
+ leaves no margin for longer session content. Same floor as Moonshot (which documents the shared budget for
+ kimi-k3, https://platform.kimi.ai/docs/guide/use-thinking-models), vLLM and Google."
+ 2048)
+
(mu/defn zai-request-body
"Build the Chat Completions request body for an LLM request.
- Z.AI's Chat Completions dialect matches what [[chat-completions/request-body]] emits, so this delegates to it. Z.AI
- documents only `tool_choice \"auto\"`, but `\"required\"` — which the structured-output path relies on — is accepted
- and honored in practice."
- [{:keys [model] :as opts
- :or {model default-model}} :- core/LLMRequestOpts]
- (chat-completions/request-body (assoc opts :model model)))
+ Z.AI's Chat Completions dialect matches what [[chat-completions/request-body]] emits, so this delegates to it,
+ adding Z.AI's `thinking` directive: enabled only where a whitelisted model's reasoning renders, disabled
+ otherwise. A [[thinking-only-model?]] rejects the directive and gets `reasoning_effort` instead — \"max\"
+ where reasoning renders, \"low\" otherwise — plus a `max_tokens` floor on forced tool calls (see
+ [[forced-tool-call-token-floor]]). Z.AI documents only `tool_choice \"auto\"`, but `\"required\"` — which the
+ structured-output path relies on — is accepted and honored in practice, with thinking on."
+ [{:keys [model reasoning? schema tool_choice] :as opts
+ :or {model default-model reasoning? true}} :- core/LLMRequestOpts]
+ ;; Thinking is on by default server-side, at reasoning_effort "max"
+ ;; (https://docs.z.ai/api-reference/llm/chat-completion), so "enabled" only makes the default
+ ;; explicit; "disabled" is the real change — it protects structured output's small budget (see
+ ;; [[metabase.metabot.conversation-title]]'s title-max-tokens) and, off the whitelist, keeps the
+ ;; stream matching the settings gate answering false: glm-4.7 "will think compulsorily" by
+ ;; default and the xf forwards reasoning unconditionally. Probed 2026-09-03: the disable is
+ ;; accepted and honored on glm-4.7, tolerated by pre-4.5 models (which do not think), and
+ ;; rejected only by a [[thinking-only-model?]]. Those take `reasoning_effort` low|high|max only
+ ;; (same docs page), so "low" is a best-effort floor on their spend, not an off switch — the
+ ;; docs say thinking cannot be turned off, though probed 2026-09-08 a title-shaped call at "low"
+ ;; streamed no reasoning at all (16 completion tokens, the tool call only) against 102–173 at "max".
+ (let [thinking-only? (thinking-only-model? model)
+ forced? (or (some? schema) (= "required" (some-> tool_choice name)))
+ thinking? (and (reasoning-model? model) reasoning? (not schema))
+ body (chat-completions/request-body (assoc opts :model model))]
+ (cond-> body
+ thinking-only?
+ (assoc :reasoning_effort (if thinking? "max" "low"))
+
+ (and thinking-only? forced? (:max_tokens body))
+ (update :max_tokens max forced-tool-call-token-floor)
+
+ (not thinking-only?)
+ (assoc :thinking {:type (if thinking? "enabled" "disabled")}))))
(mu/defn zai-raw
"Perform a streaming request to the Z.AI Chat Completions API.
@@ -141,9 +199,13 @@
"network_error" "error"))
(defn zai->aisdk-chunks-xf
- "Translates Z.AI Chat Completions streaming chunks into AI SDK v5 protocol chunks."
+ "Translates Z.AI Chat Completions streaming chunks into AI SDK v5 protocol chunks.
+
+ Thinking arrives as `delta.reasoning_content` and is forwarded as reasoning chunks. A delta
+ carrying both `reasoning_content` and non-empty `content` would drop its reasoning — the
+ shared xf classifies content first. Accepted, unprobed risk: no such chunk has been observed."
[]
- (chat-completions/chat-completions->aisdk-chunks-xf stop-reasons))
+ (chat-completions/chat-completions->aisdk-chunks-xf stop-reasons {:forward-reasoning? true}))
(defn zai
"Call the Z.AI Chat Completions API, return AISDK stream."
diff --git a/test/metabase/metabot/self/azure_test.clj b/test/metabase/metabot/self/azure_test.clj
index 36027bdb1d6..77236fedeab 100644
--- a/test/metabase/metabot/self/azure_test.clj
+++ b/test/metabase/metabot/self/azure_test.clj
@@ -4,11 +4,9 @@
[clojure.string :as str]
[clojure.test :refer :all]
[metabase.llm.settings :as llm.settings]
- [metabase.llm.test-util :as llm.tu]
[metabase.metabot.self.azure :as azure]
[metabase.metabot.self.core :as self.core]
[metabase.metabot.self.debug :as debug]
- [metabase.metabot.settings :as metabot.settings]
[metabase.test :as mt]
[metabase.util.json :as json]))
@@ -88,24 +86,10 @@
:base-url "https://my-resource.services.ai.azure.com/anthropic"}
:model "anthropic/claude-sonnet-4-5"}))))))
-(deftest list-models-falls-back-to-the-configured-azure-model-test
- (testing "without a candidate model, validation uses the saved Azure model's family"
- (llm.tu/with-connections [(llm.tu/connection "azure" {:api-key "saved-key" :base-url test-base-url})]
- (mt/with-temporary-setting-values [metabot.settings/llm-metabot-provider "azure/openai/gpt-4.1-mini"]
- (let [captured (atom nil)]
- (with-redefs [http/request (fn [req] (reset! captured req) {:status 200 :body {:data []}})]
- (is (= {:models []}
- (azure/list-models {:credentials {:api-key "saved-key" :base-url test-base-url}})))
- (is (=? {:method :get
- :url (str test-base-url "/v1/models")}
- @captured))))))))
-
(deftest list-models-skips-validation-without-any-model-test
- (testing "with no candidate model and a non-Azure provider configured, there is no surface to probe"
- (llm.tu/with-default-connections
- (mt/with-temporary-setting-values [metabot.settings/llm-metabot-provider "anthropic/claude-sonnet-4-6"]
- (with-redefs [http/request (fn [_] (throw (ex-info "should never be called" {})))]
- (is (= {:models []} (azure/list-models))))))))
+ (testing "without a candidate model there is no surface to probe"
+ (with-redefs [http/request (fn [_] (throw (ex-info "should never be called" {})))]
+ (is (= {:models []} (azure/list-models))))))
;;; ──────────────────────────────────────────────────────────────────
;;; API family dispatch and request construction
@@ -161,23 +145,85 @@
(testing "temperature is omitted when the deployment is named after a reasoning model"
(is (not (contains? body :temperature))))))
-(deftest reasoning-is-disabled-test
- (testing "anthropic deployments get no thinking config and reasoning parts are stripped"
+(defn- captured-body!
+ "The decoded request body `azure-raw` would send for `opts`, with a stock user message."
+ [opts]
+ (json/decode+kw (:body (captured-raw-request! (merge {:input [{:role :user :content "hi"}]} opts)))))
+
+(deftest reasoning-request-config-test
+ (testing "anthropic deployments named after reasoning models request adaptive summarized thinking, and only that"
+ (let [body (captured-body! {:model "anthropic/claude-opus-4-8"})]
+ (is (=? {:thinking {:type "adaptive" :display "summarized"}} body))
+ (is (not (contains? body :reasoning)))
+ (is (not (contains? body :include)))))
+ (testing "openai deployments named after reasoning models request reasoning summaries with encrypted-content replay, and only that"
+ (let [body (captured-body! {:model "openai/gpt-5.4"})]
+ (is (=? {:reasoning {:summary "auto"}
+ :include ["reasoning.encrypted_content"]}
+ body))
+ (is (not (contains? body :thinking)))))
+ (testing "deployments that do not stream reasoning get no thinking config"
+ (is (not (contains? (captured-body! {:model "anthropic/claude-haiku-4-5"}) :thinking)))
+ (is (not (contains? (captured-body! {:model "anthropic/my-claude-deployment"}) :thinking))))
+ (testing ":reasoning? false suppresses both families"
+ (is (not (contains? (captured-body! {:model "anthropic/claude-opus-4-8" :reasoning? false}) :thinking)))
+ (let [body (captured-body! {:model "openai/gpt-5.4" :reasoning? false})]
+ (is (not (contains? body :reasoning)))
+ (is (not (contains? body :include)))))
+ (testing "structured output suppresses thinking for the anthropic family only"
+ (is (not (contains? (captured-body! {:model "anthropic/claude-opus-4-8"
+ :schema {:type "object"}})
+ :thinking)))
+ (is (=? {:reasoning {:summary "auto"}
+ :include ["reasoning.encrypted_content"]}
+ (captured-body! {:model "openai/gpt-5.4" :schema {:type "object"}})))))
+
+(deftest reasoning-replay-test
+ (testing "signed reasoning parts replay as a thinking block merged into the assistant turn"
(let [body (json/decode+kw
(:body (captured-raw-request!
{:model "anthropic/claude-opus-4-8"
- :input [{:type :reasoning :id "r1" :text ""
+ :input [{:type :reasoning :id "r1" :text "first "}
+ {:type :reasoning :id "r1" :text "second"}
+ {:type :reasoning :id "r1" :text ""
:provider-metadata {:anthropic {:signature "abc"}}}
{:type :tool-input :id "call-1" :function "search" :arguments {}}]})))]
- (is (not (contains? body :thinking)))
- (is (=? [{:role "assistant" :content [{:type "tool_use" :id "call-1"}]}]
- (:messages body)))))
- (testing "openai deployments get no reasoning summary or encrypted-content include"
- (let [body (json/decode+kw
- (:body (captured-raw-request! {:model "openai/gpt-5.4"
- :input [{:role :user :content "hi"}]})))]
- (is (not (contains? body :reasoning)))
- (is (not (contains? body :include))))))
+ (is (=? [{:role "assistant"
+ :content [{:type "thinking" :thinking "first second" :signature "abc"}
+ {:type "tool_use" :id "call-1"}]}]
+ (:messages body))))))
+
+(deftest reasoning-gate-matches-request-config-test
+ (testing "the string the gate reads is the string the body is built from"
+ (doseq [model ["anthropic/claude-opus-4-8" "anthropic/Claude-Opus-5" "openai/GPT-5.4"]]
+ (testing model
+ (is (= (#'azure/model->deployment model)
+ (:model (captured-body! {:model model}))))))))
+
+(deftest ^:parallel reasoning-model?-test
+ (are [model expected] (= expected (azure/reasoning-model? model))
+ "anthropic/claude-opus-5" true
+ "anthropic/claude-opus-4-8" true
+ ;; dotted display-name spelling parses the same — deployment names are admin free text
+ "anthropic/claude-opus-4.8" true
+ "anthropic/claude-sonnet-4.6" true
+ "anthropic/claude-opus-4-6" true
+ "anthropic/claude-sonnet-4-6" true
+ "anthropic/claude-fable-5" true
+ "anthropic/claude-opus-4-5" false
+ "anthropic/claude-opus-4.5" false
+ "anthropic/claude-haiku-4-5" false
+ "anthropic/claude-sonnet-4-5" false
+ "anthropic/Claude-Opus-5" true
+ "anthropic/my-claude" false
+ "anthropic/" false
+ "anthropic" false
+ "openai/gpt-5.4" true
+ "openai/GPT-5.4" true
+ "openai/o3-mini" true
+ "openai/gpt-4.1-mini" false
+ "evilai/some-deployment" false
+ nil false))
(deftest fast-mode-is-disabled-test
(testing "a fast-mode request is stripped before the anthropic body is built"
@@ -275,6 +321,43 @@
{:type "response.completed"
:response {:id "resp_1" :usage {:input_tokens 3 :output_tokens 2}}}]))))
+(deftest anthropic-family-streams-reasoning-test
+ (is (=? [{:type :start :id "msg_1"}
+ {:type :reasoning :text "let me think" :provider-metadata {:anthropic {:signature "sig-1"}}}
+ {:type :text :text "pong"}
+ {:type :usage :usage {:promptTokens 3 :completionTokens 2}}]
+ (aisdk-parts-for!
+ "anthropic/claude-opus-4-8"
+ [{:type "message_start" :message {:id "msg_1" :model "claude-opus-4-8" :usage {:input_tokens 3}}}
+ {:type "content_block_start" :index 0 :content_block {:type "thinking"}}
+ {:type "content_block_delta" :index 0 :delta {:type "thinking_delta" :thinking "let me think"}}
+ {:type "content_block_delta" :index 0 :delta {:type "signature_delta" :signature "sig-1"}}
+ {:type "content_block_stop" :index 0}
+ {:type "content_block_start" :index 1 :content_block {:type "text"}}
+ {:type "content_block_delta" :index 1 :delta {:type "text_delta" :text "pong"}}
+ {:type "content_block_stop" :index 1}
+ {:type "message_delta" :delta {:stop_reason "end_turn"} :usage {:input_tokens 3 :output_tokens 2}}
+ {:type "message_stop"}]))))
+
+(deftest openai-family-streams-reasoning-test
+ (is (=? [{:type :start :id "resp_1"}
+ {:type :reasoning :text "keeping it short"}
+ {:type :text :text "pong"}
+ {:type :usage :usage {:promptTokens 3 :completionTokens 2}}]
+ (aisdk-parts-for!
+ "openai/gpt-5.4"
+ [{:type "response.created" :response {:id "resp_1" :model "gpt-5.4"}}
+ {:type "response.output_item.added" :item {:type "reasoning" :id "rs_1"}}
+ {:type "response.reasoning_summary_part.added" :item_id "rs_1"}
+ {:type "response.reasoning_summary_text.delta" :item_id "rs_1" :delta "keeping it short"}
+ {:type "response.reasoning_summary_text.done" :item_id "rs_1"}
+ {:type "response.output_item.done" :item {:type "reasoning" :id "rs_1"}}
+ {:type "response.output_item.added" :item {:type "message" :id "item_1"} :id "item_1"}
+ {:type "response.output_text.delta" :delta "pong" :id "item_1"}
+ {:type "response.output_item.done" :item {:type "message" :id "item_1"} :id "item_1"}
+ {:type "response.completed"
+ :response {:id "resp_1" :usage {:input_tokens 3 :output_tokens 2}}}]))))
+
;;; ──────────────────────────────────────────────────────────────────
;;; Error translation
;;; ──────────────────────────────────────────────────────────────────
diff --git a/test/metabase/metabot/self/bedrock_test.clj b/test/metabase/metabot/self/bedrock_test.clj
index ce864dd5322..85b77ae005f 100644
--- a/test/metabase/metabot/self/bedrock_test.clj
+++ b/test/metabase/metabot/self/bedrock_test.clj
@@ -309,23 +309,75 @@
(testing "openai.* models omit the field entirely"
(is (not (contains? (captured-body! {:model "openai.gpt-5.5"}) :max_output_tokens)))))
-(deftest reasoning-is-disabled-test
- (testing "anthropic models get no thinking config and reasoning parts are stripped"
+(deftest reasoning-request-config-test
+ (testing "anthropic models request adaptive summarized thinking, and only that"
+ (let [body (captured-body! {:model "anthropic.claude-opus-4-8"})]
+ (is (=? {:thinking {:type "adaptive" :display "summarized"}} body))
+ (is (not (contains? body :reasoning)))
+ (is (not (contains? body :include)))))
+ (testing "openai models request reasoning summaries with encrypted-content replay, and only that"
+ (let [body (captured-body! {:model "openai.gpt-5.5"})]
+ (is (=? {:reasoning {:summary "auto"}
+ :include ["reasoning.encrypted_content"]}
+ body))
+ (is (not (contains? body :thinking)))))
+ (testing "models that do not stream reasoning get no thinking config"
+ (is (not (contains? (captured-body! {:model "anthropic.claude-haiku-4-5"}) :thinking))))
+ (testing ":reasoning? false suppresses both families"
+ (is (not (contains? (captured-body! {:model "anthropic.claude-opus-4-8" :reasoning? false}) :thinking)))
+ (let [body (captured-body! {:model "openai.gpt-5.5" :reasoning? false})]
+ (is (not (contains? body :reasoning)))
+ (is (not (contains? body :include)))))
+ (testing "structured output suppresses thinking for the anthropic family only"
+ (is (not (contains? (captured-body! {:model "anthropic.claude-opus-4-8"
+ :schema {:type "object"}})
+ :thinking)))
+ (is (=? {:reasoning {:summary "auto"}
+ :include ["reasoning.encrypted_content"]}
+ (captured-body! {:model "openai.gpt-5.5" :schema {:type "object"}})))))
+
+(deftest reasoning-replay-test
+ (testing "signed reasoning parts replay as a thinking block merged into the assistant turn"
(let [body (json/decode+kw
(:body (captured-raw-request!
{:model "anthropic.claude-opus-4-8"
- :input [{:type :reasoning :id "r1" :text ""
+ :input [{:type :reasoning :id "r1" :text "first "}
+ {:type :reasoning :id "r1" :text "second"}
+ {:type :reasoning :id "r1" :text ""
:provider-metadata {:anthropic {:signature "abc"}}}
{:type :tool-input :id "call-1" :function "search" :arguments {}}]})))]
- (is (not (contains? body :thinking)))
- (is (=? [{:role "assistant" :content [{:type "tool_use" :id "call-1"}]}]
- (:messages body)))))
- (testing "openai models get no reasoning summary or encrypted-content include"
- (let [body (json/decode+kw
- (:body (captured-raw-request! {:model "openai.gpt-5.5"
- :input [{:role :user :content "hi"}]})))]
- (is (not (contains? body :reasoning)))
- (is (not (contains? body :include))))))
+ (is (=? [{:role "assistant"
+ :content [{:type "thinking" :thinking "first second" :signature "abc"}
+ {:type "tool_use" :id "call-1"}]}]
+ (:messages body))))))
+
+(deftest reasoning-gate-matches-request-config-test
+ (doseq [model (keys @#'bedrock/supported-models)]
+ (testing model
+ (let [body (captured-body! {:model model})]
+ ;; `case` so a model of an unknown family fails loudly here
+ (case (#'bedrock/model-family model)
+ :anthropic
+ (testing "the gate and the thinking request agree"
+ (is (= (bedrock/reasoning-model? model) (contains? body :thinking))))
+ ;; deliberately asymmetric: the request keeps its reasoning fields
+ ;; (encrypted-content replay works) while the gate answers false,
+ ;; because the mantle never streams summaries — nothing will render.
+ ;; See [[bedrock/reasoning-model?]].
+ :openai
+ (testing "reasoning is requested but the gate answers false"
+ (is (contains? body :reasoning))
+ (is (false? (bedrock/reasoning-model? model)))))))))
+
+(deftest ^:parallel reasoning-model?-test
+ (are [model expected] (= expected (bedrock/reasoning-model? model))
+ "anthropic.claude-opus-4-8" true
+ "anthropic.claude-fable-5" true
+ "anthropic.claude-haiku-4-5" false
+ "openai.gpt-5.5" false
+ "openai.gpt-5.4-2026-03-05" false
+ "deepseek.v3.2" false
+ nil false))
(deftest fast-mode-is-disabled-test
(testing "a fast-mode request is stripped before the anthropic body is built"
@@ -396,6 +448,46 @@
{:type "response.completed"
:response {:id "resp_1" :usage {:input_tokens 3 :output_tokens 2}}}]))))
+(deftest anthropic-model-streams-reasoning-test
+ (is (=? [{:type :start :id "msg_1"}
+ {:type :reasoning :text "let me think" :provider-metadata {:anthropic {:signature "sig-1"}}}
+ {:type :text :text "pong"}
+ {:type :usage :usage {:promptTokens 3 :completionTokens 2}}]
+ (aisdk-parts-for!
+ "anthropic.claude-opus-4-8"
+ [{:type "message_start" :message {:id "msg_1" :model "claude-opus-4-8" :usage {:input_tokens 3}}}
+ {:type "content_block_start" :index 0 :content_block {:type "thinking"}}
+ {:type "content_block_delta" :index 0 :delta {:type "thinking_delta" :thinking "let me think"}}
+ {:type "content_block_delta" :index 0 :delta {:type "signature_delta" :signature "sig-1"}}
+ {:type "content_block_stop" :index 0}
+ {:type "content_block_start" :index 1 :content_block {:type "text"}}
+ {:type "content_block_delta" :index 1 :delta {:type "text_delta" :text "pong"}}
+ {:type "content_block_stop" :index 1}
+ {:type "message_delta" :delta {:stop_reason "end_turn"} :usage {:input_tokens 3 :output_tokens 2}}
+ {:type "message_stop"}]))))
+
+;; The mantle has never been observed to emit reasoning_summary_* events (see
+;; [[bedrock/reasoning-model?]]) — this pins the translation wiring so only the
+;; gate needs flipping if it ever starts.
+(deftest openai-model-streams-reasoning-test
+ (is (=? [{:type :start :id "resp_1"}
+ {:type :reasoning :text "keeping it short"}
+ {:type :text :text "pong"}
+ {:type :usage :usage {:promptTokens 3 :completionTokens 2}}]
+ (aisdk-parts-for!
+ "openai.gpt-5.5"
+ [{:type "response.created" :response {:id "resp_1" :model "openai.gpt-5.5"}}
+ {:type "response.output_item.added" :item {:type "reasoning" :id "rs_1"}}
+ {:type "response.reasoning_summary_part.added" :item_id "rs_1"}
+ {:type "response.reasoning_summary_text.delta" :item_id "rs_1" :delta "keeping it short"}
+ {:type "response.reasoning_summary_text.done" :item_id "rs_1"}
+ {:type "response.output_item.done" :item {:type "reasoning" :id "rs_1"}}
+ {:type "response.output_item.added" :item {:type "message" :id "item_1"} :id "item_1"}
+ {:type "response.output_text.delta" :delta "pong" :id "item_1"}
+ {:type "response.output_item.done" :item {:type "message" :id "item_1"} :id "item_1"}
+ {:type "response.completed"
+ :response {:id "resp_1" :usage {:input_tokens 3 :output_tokens 2}}}]))))
+
;;; ──────────────────────────────────────────────────────────────────
;;; Region validation (host-injection backstop)
;;; ──────────────────────────────────────────────────────────────────
diff --git a/test/metabase/metabot/self/claude_test.clj b/test/metabase/metabot/self/claude_test.clj
index 45081aa0b4c..85f2a5d09ad 100644
--- a/test/metabase/metabot/self/claude_test.clj
+++ b/test/metabase/metabot/self/claude_test.clj
@@ -628,7 +628,10 @@
(is (= {:type "adaptive" :display "summarized"} (thinking {:model "claude-opus-4-8"})))
(is (= {:type "adaptive" :display "summarized"} (thinking {:model "claude-sonnet-5"})))
(testing "bedrock vendor prefix is stripped"
- (is (= {:type "adaptive" :display "summarized"} (thinking {:model "anthropic.claude-opus-4-8"})))))
+ (is (= {:type "adaptive" :display "summarized"} (thinking {:model "anthropic.claude-opus-4-8"}))))
+ (testing "the dotted display-name spelling of the minor version parses the same
+ (Azure admins name deployments freely)"
+ (is (= {:type "adaptive" :display "summarized"} (thinking {:model "claude-opus-4.8"})))))
(testing "4.6 models also get an explicit display param, not just the (currently matching) default"
(is (= {:type "adaptive" :display "summarized"} (thinking {:model "claude-opus-4-6"})))
(is (= {:type "adaptive" :display "summarized"} (thinking {:model "claude-sonnet-4-6"}))))
diff --git a/test/metabase/metabot/self/google/models_test.clj b/test/metabase/metabot/self/google/models_test.clj
new file mode 100644
index 00000000000..75d4e143a4b
--- /dev/null
+++ b/test/metabase/metabot/self/google/models_test.clj
@@ -0,0 +1,31 @@
+(ns metabase.metabot.self.google.models-test
+ (:require
+ [clojure.string :as str]
+ [clojure.test :refer :all]
+ [metabase.llm.provider :as llm.provider]
+ [metabase.metabot.self.google.models :as models]))
+
+(deftest ^:parallel reasoning-model?-test
+ (testing "exactly the catalog models stream renderable thought summaries"
+ (is (true? (models/reasoning-model? "google/gemini-3.5-flash")))
+ (is (true? (models/reasoning-model? "google/gemini-3.6-flash")))
+ (is (true? (models/reasoning-model? "google/gemini-3.7-flash")))
+ (is (false? (models/reasoning-model? "google/gemini-2.5-flash")))
+ (is (false? (models/reasoning-model? "gemini-3.5-flash")))
+ (is (false? (models/reasoning-model? nil)))))
+
+(deftest ^:parallel catalog-matches-connection-form-test
+ (testing "the adapter catalog offers the same Gemini models as the connection form, so neither can drift alone"
+ ;; the form also offers Anthropic partner models, which raw-predict serves; this catalog
+ ;; deliberately owns only the google/-publisher half
+ (is (= (->> (:models (llm.provider/provider-type "google"))
+ (map :id)
+ (filter #(str/starts-with? % "google/"))
+ set)
+ (set (keys models/catalog))))))
+
+(deftest ^:parallel catalog-rows-carry-context-windows-test
+ (testing "every catalog row records the model's input context window: google/context-window-tokens reads it here"
+ (doseq [[model {:keys [context-window]}] models/catalog]
+ (testing model
+ (is (pos-int? context-window))))))
diff --git a/test/metabase/metabot/self/google/stream_generate_content_test.clj b/test/metabase/metabot/self/google/stream_generate_content_test.clj
index dc6de9aae83..649e9f49930 100644
--- a/test/metabase/metabot/self/google/stream_generate_content_test.clj
+++ b/test/metabase/metabot/self/google/stream_generate_content_test.clj
@@ -177,6 +177,21 @@
(sgc/parts->contents
[{:type :tool-output :id "call-9" :result {:output "orphan"}}])))))
+(deftest ^:parallel parts->contents-reasoning-part-dropped-test
+ (testing "a :reasoning part is display-only and contributes no content"
+ (is (= [{:role "user" :parts [{:text "question"}]}
+ {:role "model" :parts [{:text "answer"}]}]
+ (sgc/parts->contents
+ [{:role :user :content "question"}
+ {:type :reasoning :text "thinking..." :id "r1"}
+ {:type :text :text "answer"}]))))
+ (testing "and dropping it does not split the model contents that surrounded it"
+ (is (= [{:role "model" :parts [{:text "first"} {:text "second"}]}]
+ (sgc/parts->contents
+ [{:type :text :text "first"}
+ {:type :reasoning :text "thinking..." :id "r1"}
+ {:type :text :text "second"}])))))
+
(deftest ^:parallel parts->contents-thought-signature-replay-test
(testing "a thoughtSignature carried in :provider-metadata is echoed on the replayed functionCall part"
(is (= [{:role "model"
@@ -330,6 +345,77 @@
:tool_choice "auto"
:schema {:type "object"}})))))
+(deftest ^:parallel request-body-thinking-config-test
+ (testing "a catalog model asks for thought summaries by default"
+ (is (=? {:generationConfig {:thinkingConfig {:includeThoughts true}}}
+ (sgc/request-body {:model "google/gemini-3.5-flash"
+ :input [{:role :user :content "hi"}]}))))
+ (testing "structured output pins thinking to LOW instead, with or without :reasoning?"
+ (is (=? {:generationConfig {:thinkingConfig {:thinkingLevel "LOW"}}}
+ (sgc/request-body {:model "google/gemini-3.7-flash"
+ :input [{:role :user :content "hi"}]
+ :schema {:type "object"}})))
+ (is (=? {:generationConfig {:thinkingConfig {:thinkingLevel "LOW"}}}
+ (sgc/request-body {:model "google/gemini-3.5-flash"
+ :input [{:role :user :content "hi"}]
+ :reasoning? false
+ :schema {:type "object"}}))))
+ (testing ":reasoning? false sends no thinkingConfig, leaving the server default"
+ (is (= {:contents [{:role "user" :parts [{:text "hi"}]}]}
+ (sgc/request-body {:model "google/gemini-3.6-flash"
+ :input [{:role :user :content "hi"}]
+ :reasoning? false}))))
+ (testing "an off-catalog or absent model gets no thinkingConfig at all"
+ (is (= {:contents [{:role "user" :parts [{:text "hi"}]}]}
+ (sgc/request-body {:model "google/gemini-2.5-flash"
+ :input [{:role :user :content "hi"}]})))
+ (is (= {:contents [{:role "user" :parts [{:text "hi"}]}]}
+ (sgc/request-body {:input [{:role :user :content "hi"}]})))))
+
+(deftest ^:parallel request-body-forced-tool-call-token-floor-test
+ (testing "a catalog model's structured call has its caller cap raised to the floor"
+ (is (=? {:generationConfig {:maxOutputTokens 2048}}
+ (sgc/request-body {:model "google/gemini-3.7-flash"
+ :input [{:role :user :content "hi"}]
+ :schema {:type "object"}
+ :max-tokens 512}))))
+ (testing "a cap already above the floor is left alone"
+ (is (=? {:generationConfig {:maxOutputTokens 8000}}
+ (sgc/request-body {:model "google/gemini-3.7-flash"
+ :input [{:role :user :content "hi"}]
+ :schema {:type "object"}
+ :max-tokens 8000}))))
+ (testing "an uncapped structured call stays uncapped — the floor raises, it never introduces a cap"
+ (is (nil? (get-in (sgc/request-body {:model "google/gemini-3.7-flash"
+ :input [{:role :user :content "hi"}]
+ :schema {:type "object"}})
+ [:generationConfig :maxOutputTokens]))))
+ (testing "an unforced call keeps the caller's cap"
+ (is (=? {:generationConfig {:maxOutputTokens 512}}
+ (sgc/request-body {:model "google/gemini-3.7-flash"
+ :input [{:role :user :content "hi"}]
+ :max-tokens 512}))))
+ (testing "an off-catalog model gets no floor, as it gets no thinkingConfig"
+ (is (=? {:generationConfig {:maxOutputTokens 512}}
+ (sgc/request-body {:model "google/gemini-2.5-flash"
+ :input [{:role :user :content "hi"}]
+ :schema {:type "object"}
+ :max-tokens 512}))))
+ (testing "a schema is not the only way to force a call: tool_choice \"required\" gets the floor, \"auto\" does not"
+ (let [body-for (fn [tool-choice]
+ (sgc/request-body
+ {:model "google/gemini-3.7-flash"
+ :input [{:role :user :content "hi"}]
+ :tools [{:tool-name "t" :doc "d"
+ :schema [:=> [:cat [:map [:x :string]]] :any]
+ :fn identity}]
+ :tool_choice tool-choice
+ :max-tokens 512}))]
+ (is (=? {:generationConfig {:maxOutputTokens 2048}}
+ (body-for "required")))
+ (is (=? {:generationConfig {:maxOutputTokens 512}}
+ (body-for "auto"))))))
+
;;; ──────────────────────────────────────────────────────────────────
;;; Streaming event conversion tests.
;;; ──────────────────────────────────────────────────────────────────
@@ -438,17 +524,78 @@
{:type :text :text "Hello world"}]
(into [] (comp (sgc/->aisdk-chunks-xf) (self.core/aisdk-xf)) events))))))
-(deftest ^:parallel thought-parts-ignored-test
- (testing "thinking summaries are dropped"
+(deftest ^:parallel thought-parts-stream-as-reasoning-test
+ (testing "thinking summaries stream as a reasoning part ahead of the answer text"
(let [events [{:responseId "r5"
:candidates [{:content {:role "model"
:parts [{:thought true :text "reasoning..."}
{:text "Answer"}]}
:finishReason "STOP"}]}]]
(is (=? [{:type :start}
+ {:type :reasoning :text "reasoning..."}
{:type :text :text "Answer"}]
(into [] (comp (sgc/->aisdk-chunks-xf) (self.core/aisdk-xf)) events))))))
+(deftest ^:parallel thought-text-transitions-close-and-reopen-blocks-test
+ (testing "a thought/text transition closes the one block kind and opens the other"
+ (let [events [{:responseId "r5b"
+ :candidates [{:content {:role "model"
+ :parts [{:thought true :text "t1"}
+ {:text "a1"}
+ {:thought true :text "t2"}]}
+ :finishReason "STOP"}]}]]
+ (is (=? [{:type :start}
+ {:type :reasoning-start}
+ {:type :reasoning-delta :delta "t1"}
+ {:type :reasoning-end}
+ {:type :text-start}
+ {:type :text-delta :delta "a1"}
+ {:type :text-end}
+ {:type :reasoning-start}
+ {:type :reasoning-delta :delta "t2"}
+ {:type :reasoning-end}]
+ (into [] (sgc/->aisdk-chunks-xf) events))))))
+
+(deftest ^:parallel thought-before-tool-call-closes-reasoning-test
+ (testing "a functionCall closes the open reasoning block before the tool chunks"
+ (let [events [{:responseId "r5c"
+ :candidates [{:content {:role "model"
+ :parts [{:thought true :text "planning..."}
+ {:functionCall {:name "search" :args {}}
+ :thoughtSignature "sig-1"}]}
+ :finishReason "STOP"}]}]]
+ (is (=? [{:type :start}
+ {:type :reasoning-start}
+ {:type :reasoning-delta}
+ {:type :reasoning-end}
+ {:type :tool-input-start :providerMetadata {:google {:thoughtSignature "sig-1"}}}
+ {:type :tool-input-delta}
+ {:type :tool-input-available}]
+ (into [] (sgc/->aisdk-chunks-xf) events))))))
+
+(deftest ^:parallel empty-parts-do-not-split-a-reasoning-block-test
+ (testing "an empty thought and a signature-only empty text part emit nothing and close nothing"
+ (let [events [{:responseId "r5d"
+ :candidates [{:content {:role "model"
+ :parts [{:thought true :text "before"}
+ {:thought true :text ""}
+ {:text "" :thoughtSignature "sig-tail"}
+ {:thought true :text " after"}]}
+ :finishReason "STOP"}]}]]
+ (is (=? [{:type :start}
+ {:type :reasoning :text "before after"}]
+ (into [] (comp (sgc/->aisdk-chunks-xf) (self.core/aisdk-xf)) events))))))
+
+(deftest ^:parallel stream-end-closes-open-reasoning-block-test
+ (testing "a stream that ends mid-thought still closes the reasoning block"
+ (let [events [{:responseId "r5e"
+ :candidates [{:content {:role "model" :parts [{:thought true :text "unfinished"}]}}]}]]
+ (is (=? [{:type :start}
+ {:type :reasoning-start}
+ {:type :reasoning-delta}
+ {:type :reasoning-end}]
+ (into [] (sgc/->aisdk-chunks-xf) events))))))
+
(deftest ^:parallel usage-buffered-and-emitted-once-test
(testing "usageMetadata is buffered last-wins and emitted once at stream end, after content"
(let [events [{:responseId "r6" :modelVersion "gemini-3.5-flash"
diff --git a/test/metabase/metabot/self/google_test.clj b/test/metabase/metabot/self/google_test.clj
index c4388778f8d..3f66df883c3 100644
--- a/test/metabase/metabot/self/google_test.clj
+++ b/test/metabase/metabot/self/google_test.clj
@@ -135,9 +135,13 @@
self.core/reducible-with-api-errors (fn [r _ _] r)
debug/capture-stream (fn [r _] r)
http/request (fn [req] {:body req})]
- (is (=? {:url (str "https://aiplatform.googleapis.com/v1/projects/my-project/locations/global"
- "/publishers/google/models/gemini-3.5-flash:streamGenerateContent?alt=sse")}
- (google-raw {:input [{:role :user :content "hi"}]})))))))
+ (let [req (google-raw {:input [{:role :user :content "hi"}]})]
+ (is (=? {:url (str "https://aiplatform.googleapis.com/v1/projects/my-project/locations/global"
+ "/publishers/google/models/gemini-3.5-flash:streamGenerateContent?alt=sse")}
+ req))
+ (testing "and the thinking directive keys off the defaulted model"
+ (is (=? {:generationConfig {:thinkingConfig {:includeThoughts true}}}
+ (json/decode+kw (:body req))))))))))
(deftest google-raw-request-body-test
(testing "the request streams its response and carries the streamGenerateContent body as JSON"
@@ -154,7 +158,8 @@
(is (=? {:as :stream
:headers {"Content-Type" "application/json"}}
req))
- (is (= {:contents [{:role "user" :parts [{:text "hi"}]}]}
+ (is (= {:contents [{:role "user" :parts [{:text "hi"}]}]
+ :generationConfig {:thinkingConfig {:includeThoughts true}}}
(json/decode+kw (:body req)))))))))
(deftest google-raw-regional-location-host-test
@@ -777,8 +782,8 @@
(is (false? (google/reasoning-model? "anthropic/claude-haiku-4-5@20251001")))))
(deftest reasoning-model?-gemini-test
- (testing "Gemini sends thinking only as :thought parts, which the adapter drops"
- (is (false? (google/reasoning-model? "google/gemini-3.5-flash")))
+ (testing "catalog Geminis stream thought summaries; off-catalog Geminis stay dark"
+ (is (true? (google/reasoning-model? "google/gemini-3.5-flash")))
(is (false? (google/reasoning-model? "google/gemini-3.6-pro")))))
(deftest reasoning-model?-unqualified-test
diff --git a/test/metabase/metabot/self/mistral_test.clj b/test/metabase/metabot/self/mistral_test.clj
index a83fd5027e9..cc7d6e9b2ef 100644
--- a/test/metabase/metabot/self/mistral_test.clj
+++ b/test/metabase/metabot/self/mistral_test.clj
@@ -82,6 +82,67 @@
:temperature 0.2
:max-tokens 128})))))
+(deftest ^:parallel reasoning-model?-test
+ (testing "exactly the whitelist streams renderable thinking; aliases are not resolved"
+ (is (true? (mistral/reasoning-model? "mistral-medium-3-5")))
+ (is (false? (mistral/reasoning-model? "mistral-medium-latest")))
+ (is (false? (mistral/reasoning-model? "mistral-large-2")))
+ (is (false? (mistral/reasoning-model? nil)))))
+
+(deftest ^:parallel request-body-reasoning-effort-test
+ (let [body-for (fn [opts]
+ (:reasoning_effort
+ (mistral/mistral-request-body
+ (merge {:model "mistral-medium-3-5" :input [{:role :user :content "hi"}]} opts))))]
+ (testing "a whitelisted model asks for thinking by default — the server default sends none"
+ (is (= "high" (body-for {}))))
+ (testing "tool_choice \"required\" keeps thinking on — Mistral accepts the combination"
+ (is (= "high" (body-for {:tool_choice "required"
+ :tools [{:tool-name "t" :doc "d"
+ :schema [:=> [:cat [:map [:x :string]]] :any]
+ :fn identity}]}))))
+ (testing "structured output and :reasoning? false pin thinking off"
+ (is (= "none" (body-for {:schema {:type "object"}})))
+ (is (= "none" (body-for {:reasoning? false})))
+ (is (= "none" (body-for {:reasoning? false :schema {:type "object"}}))))
+ (testing "an off-whitelist model gets no directive at all"
+ (is (nil? (:reasoning_effort
+ (mistral/mistral-request-body {:model "mistral-large-2"
+ :input [{:role :user :content "hi"}]})))))))
+
+(deftest ^:parallel request-body-replays-think-chunks-test
+ (let [input [{:role :user :content "check the weather"}
+ ;; a block streams as several small parts plus an empty-text metadata carrier
+ {:type :reasoning :id "r1" :text "I should "}
+ {:type :reasoning :id "r1" :text "use the tool."}
+ {:type :reasoning :id "r1" :text "" :provider-metadata {:mistral {:signature "sig-abc"}}}
+ {:type :text :text "Checking now."}
+ {:type :tool-input :id "call-1" :function "get_weather" :arguments {:city "Paris"}}
+ {:type :tool-output :id "call-1" :result {:output "18C"}}]]
+ (testing "in-turn reasoning replays as ONE think chunk folded into the step's assistant message"
+ (is (= {:role "assistant"
+ :content [{:type "thinking" :thinking [{:type "text" :text "I should use the tool."}]}
+ {:type "text" :text "Checking now."}]
+ :tool_calls [{:id "call-1"
+ :type "function"
+ :function {:name "get_weather" :arguments "{\"city\":\"Paris\"}"}}]}
+ (nth (:messages (mistral/mistral-request-body {:model "mistral-medium-3-5" :input input})) 1))))
+ (testing "the replayed chunk carries neither :closed (400 on replay, error 3240) nor the captured
+ :signature (rejected today, error 3051) — the equality assertion above pins both absences"
+ (let [chunk (-> (mistral/mistral-request-body {:model "mistral-medium-3-5" :input input})
+ :messages (nth 1) :content first)]
+ (is (not (contains? chunk :closed)))
+ (is (not (contains? chunk :signature)))))
+ (testing "the structured path, :reasoning? false, and off-whitelist models replay nothing"
+ (doseq [opts [{:schema {:type "object"}}
+ {:reasoning? false}
+ {:model "mistral-large-2"}]]
+ (testing (pr-str opts)
+ (is (= "Checking now."
+ (-> (mistral/mistral-request-body
+ (merge {:model "mistral-medium-3-5" :input input} opts))
+ :messages (nth 1) :content))))))))
+
;;; ──────────────────────────────────────────────────────────────────
;;; Streaming chunk conversion tests
;;;
@@ -150,6 +211,124 @@
{:choices [{:delta {:tool_calls [{:function {:arguments "\"Europe/Kyiv\"}"}}]}}]}
{:choices [{:delta {} :finish_reason "tool_calls"}]}])))))
+(deftest ^:parallel flatten-content-chunks-test
+ (let [flatten* @#'mistral/flatten-content-chunks]
+ (testing "string and absent content pass through untouched, including usage-only events"
+ (are [event] (= [event] (flatten* event))
+ {:id "m" :choices [{:delta {:role "assistant" :content ""}}]}
+ {:choices [{:delta {:content "plain"}}]}
+ {:choices [{:delta {} :finish_reason "stop"}] :usage {:prompt_tokens 1}}
+ {:usage {:prompt_tokens 1}}))
+ (testing "a thinking-only vector becomes a reasoning event plus an empty-content original"
+ (is (= [{:id "m" :model "mistral-medium-3-5"
+ :choices [{:delta {:reasoning "step one"}}]}
+ {:id "m" :model "mistral-medium-3-5"
+ :choices [{:delta {:content ""}}]}]
+ (flatten* {:id "m" :model "mistral-medium-3-5"
+ :choices [{:delta {:content [{:type "thinking" :closed true
+ :thinking [{:type "text" :text "step one"}]}]}}]}))))
+ (testing "the transition event splits reasoning-first, keeping finish/tool keys on the content event"
+ (is (= [{:choices [{:delta {:reasoning "1."}}]}
+ {:choices [{:delta {:content "3"} :finish_reason "stop"}]}]
+ (flatten* {:choices [{:delta {:content [{:type "thinking" :closed true
+ :thinking [{:type "text" :text "1."}]}
+ {:type "text" :text "3"}]}
+ :finish_reason "stop"}]}))))
+ (testing "dispatch is structural — spec-legal chunks without :type still translate"
+ (is (= [{:choices [{:delta {:reasoning "quiet"}}]}
+ {:choices [{:delta {:content "answer"}}]}]
+ (flatten* {:choices [{:delta {:content [{:thinking [{:text "quiet"}]}
+ {:text "answer"}]}}]}))))
+ (testing "chunk kinds carrying neither :thinking nor :text are dropped, at both nesting levels"
+ (is (= [{:choices [{:delta {:reasoning "kept"}}]}
+ {:choices [{:delta {:content "ans"}}]}]
+ (flatten* {:choices [{:delta {:content [{:type "reference" :reference_ids [1 2]}
+ {:type "thinking"
+ :thinking [{:type "text" :text "kept"}
+ {:type "reference" :reference_ids [3]}]}
+ {:type "text" :text "ans"}]}}]}))))
+ (testing "a think-chunk signature is lifted out, ready-namespaced, for the shared xf to carry"
+ (is (=? [{:choices [{:delta {:reasoning "hmm"
+ :reasoning_metadata {:mistral {:signature "sig-abc"}}}}]}
+ {:choices [{:delta {:content ""}}]}]
+ (flatten* {:choices [{:delta {:content [{:type "thinking" :signature "sig-abc"
+ :thinking [{:type "text" :text "hmm"}]}]}}]}))))
+ (testing "a signature-only think chunk — the likely closing shape — still gets its synthetic event"
+ (is (=? [{:choices [{:delta {:reasoning_metadata {:mistral {:signature "sig-tail"}}}}]}
+ {:choices [{:delta {:content ""}}]}]
+ (flatten* {:choices [{:delta {:content [{:type "thinking" :signature "sig-tail"
+ :thinking []}]}}]}))))))
+
+(deftest ^:parallel mistral-reasoning-conv-test
+ ;; Transcribed from a live mistral-medium-3-5 stream with reasoning_effort "high"
+ ;; (2026-09-01): prelude string deltas, think-chunk deltas, ONE transition delta
+ ;; carrying the closing think chunk and the first text chunk, then plain strings.
+ (let [chunks [{:id "20260901-1"
+ :model "mistral-medium-3-5"
+ :choices [{:delta {:role "assistant" :content ""}}]}
+ {:choices [{:delta {:content ""}}]}
+ {:choices [{:delta {:content [{:type "thinking"
+ :thinking [{:type "text" :text "Let me calculate "}]}]}}]}
+ {:choices [{:delta {:content [{:type "thinking" :closed true
+ :thinking [{:type "text" :text "17 times 23."}]}]}}]}
+ {:choices [{:delta {:content [{:type "thinking" :closed true
+ :thinking [{:type "text" :text "1."}]}
+ {:type "text" :text "3"}]}}]}
+ {:choices [{:delta {:content "91"}}]}
+ {:choices [{:delta {} :finish_reason "stop"}]
+ :usage {:prompt_tokens 30 :completion_tokens 262 :total_tokens 292}}]]
+ (testing ":start precedes every reasoning chunk, and one reasoning block precedes the text"
+ (is (=? [{:type :start}
+ {:type :reasoning-start}
+ {:type :reasoning-delta :delta "Let me calculate "}
+ {:type :reasoning-delta :delta "17 times 23."}
+ {:type :reasoning-delta :delta "1."}
+ {:type :reasoning-end}
+ {:type :text-start}
+ {:type :text-delta :delta "3"}
+ {:type :text-delta :delta "91"}
+ {:type :text-end}
+ {:type :usage}]
+ (into [] (mistral/mistral->aisdk-chunks-xf) chunks))))
+ (testing "through the full pipeline: coalesced reasoning, then the answer, then usage"
+ (is (=? [{:type :start}
+ {:type :reasoning :text "Let me calculate 17 times 23.1."}
+ {:type :text :text "391"}
+ {:type :usage :model "mistral-medium-3-5"
+ :usage {:promptTokens 30 :completionTokens 262}}]
+ (into [] (comp (mistral/mistral->aisdk-chunks-xf)
+ (self.core/aisdk-xf))
+ chunks))))))
+
+(deftest ^:parallel mistral-signature-capture-conv-test
+ (testing "a streamed think-chunk signature lands in the reasoning part's provider metadata,
+ including when it arrives on a signature-only closing chunk"
+ (is (=? [{:type :start}
+ {:type :reasoning :text "hmm"}
+ {:type :reasoning :text "" :provider-metadata {:mistral {:signature "sig-abc"}}}
+ {:type :text :text "done"}]
+ (into [] (comp (mistral/mistral->aisdk-chunks-xf)
+ (self.core/lite-aisdk-xf))
+ [{:id "20260901-2"
+ :model "mistral-medium-3-5"
+ :choices [{:delta {:role "assistant" :content ""}}]}
+ {:choices [{:delta {:content [{:type "thinking"
+ :thinking [{:type "text" :text "hmm"}]}]}}]}
+ ;; the signature alone on the block's closing chunk
+ {:choices [{:delta {:content [{:type "thinking" :signature "sig-abc"
+ :thinking []}]}}]}
+ {:choices [{:delta {:content "done"}}]}
+ {:choices [{:delta {} :finish_reason "stop"}]}]))))
+ (testing "and the coalescing replay fold reunites the carrier with its block's text"
+ (is (= [{:type "thinking" :thinking [{:type "text" :text "hmm"}]}]
+ (-> (mistral/mistral-request-body
+ {:model "mistral-medium-3-5"
+ :input [{:role :user :content "q"}
+ {:type :reasoning :id "r1" :text "hmm"}
+ {:type :reasoning :id "r1" :text ""
+ :provider-metadata {:mistral {:signature "sig-abc"}}}]})
+ :messages (nth 1) :content)))))
+
(deftest ^:parallel mistral-usage-final-chunk-test
(testing "usage is extracted from the final chunk; without a cache hit Mistral reports cached_tokens 0"
;; Caching is opt-in via the `prompt_cache_key` request param, which the adapter sends only when
diff --git a/test/metabase/metabot/self/moonshot_test.clj b/test/metabase/metabot/self/moonshot_test.clj
index 876eef663bc..8eb4332fe21 100644
--- a/test/metabase/metabot/self/moonshot_test.clj
+++ b/test/metabase/metabot/self/moonshot_test.clj
@@ -51,16 +51,31 @@
(deftest ^:parallel request-body-max-tokens-test
(testing "max-tokens passes through"
+ ;; a capped k2.6 chat call would share this budget with thinking (reasoning_content counts
+ ;; toward max_tokens); unreachable today — the only :max-tokens producer also sets :schema,
+ ;; which disables k2.6's thinking
(is (= 128 (:max_tokens (moonshot/moonshot-request-body {:model "kimi-k2.6"
:input [{:role :user :content "hi"}]
:max-tokens 128}))))))
-(deftest ^:parallel request-body-disables-thinking-test
- (testing "thinking is disabled on models that can disable it"
- ;; `tool_choice "required"` is rejected while thinking is on, and reasoning tokens are billed and then
- ;; discarded — we drop `reasoning_content`.
+(deftest ^:parallel request-body-thinking-switch-test
+ (testing "kimi-k2.6's thinking switch follows the path"
+ ;; enabled only where reasoning renders; disabled on the structured path, under a forced tool
+ ;; choice (k2.6 rejects `tool_choice "required"` while thinking is on — probe-derived,
+ ;; BOT-1929), and with :reasoning? false. thinking.keep stays at its default null — see the
+ ;; hook note in moonshot-request-body.
+ (are [expected opts] (= expected (:thinking (moonshot/moonshot-request-body
+ (assoc opts
+ :model "kimi-k2.6"
+ :input [{:role :user :content "hi"}]))))
+ {:type "enabled"} {}
+ {:type "enabled"} {:tools [(metabot.tu/get-time-tool)]}
+ {:type "disabled"} {:tools [(metabot.tu/get-time-tool)] :tool_choice "required"}
+ {:type "disabled"} {:schema {:type "object" :properties {:title {:type "string"}}}}
+ {:type "disabled"} {:reasoning? false}))
+ (testing "an off-whitelist model keeps the safe disable"
(is (= {:type "disabled"}
- (:thinking (moonshot/moonshot-request-body {:model "kimi-k2.6"
+ (:thinking (moonshot/moonshot-request-body {:model "kimi-k9"
:input [{:role :user :content "hi"}]})))))
(testing "no thinking parameter is sent for a thinking-only model"
;; kimi-k3 reports `supports_thinking_type: "only"` and would reject `{:type "disabled"}`. It accepts
@@ -72,6 +87,84 @@
(is (not (contains? (moonshot/moonshot-request-body {:input [{:role :user :content "hi"}]})
:thinking))))))
+(deftest ^:parallel request-body-reasoning-effort-test
+ (testing "reasoning_effort is sent exactly for whitelisted reasoning models, per path"
+ ;; kimi-k3 always thinks — "max" pins the documented server default on the chat path; "low" is the
+ ;; best-effort floor everywhere reasoning is never rendered. k2.6 gets `thinking` instead; the two
+ ;; keys must never ride together (k3 rejects `thinking`; reasoning_effort is explicitly not
+ ;; supported on k2.6). A forced tool_choice keeps k3 at "max" — k3 accepts required+thinking, and
+ ;; the guard row pins that the k2.6 forced-tool-choice disable stayed k2.6-scoped.
+ (are [expected opts] (let [body (moonshot/moonshot-request-body opts)]
+ (and (= expected (:reasoning_effort body))
+ (not (and (contains? body :reasoning_effort)
+ (contains? body :thinking)))))
+ "max" {:model "kimi-k3" :input [{:role :user :content "hi"}]}
+ "max" {:model "kimi-k3" :input [{:role :user :content "hi"}]
+ :tools [(metabot.tu/get-time-tool)]}
+ "max" {:model "kimi-k3" :input [{:role :user :content "hi"}]
+ :tools [(metabot.tu/get-time-tool)] :tool_choice "required"}
+ "low" {:model "kimi-k3" :input [{:role :user :content "hi"}] :reasoning? false}
+ "low" {:model "kimi-k3" :input [{:role :user :content "hi"}]
+ :schema {:type "object" :properties {:title {:type "string"}}}}
+ nil {:model "kimi-k2.6" :input [{:role :user :content "hi"}]}
+ nil {:model "kimi-k2.6" :input [{:role :user :content "hi"}]
+ :tools [(metabot.tu/get-time-tool)] :tool_choice "required"}
+ nil {:model "kimi-k2.6" :input [{:role :user :content "hi"}]
+ :schema {:type "object" :properties {:title {:type "string"}}}})))
+
+(deftest ^:parallel request-body-forced-tool-call-floors-max-tokens-test
+ (testing "a forced tool call on a thinking-only model gets its max_tokens cap floored"
+ ;; k3 bills thinking and the forced tool call against one budget — a small cap risks a `length`
+ ;; finish before the tool call is emitted (the conversation-title path sends 512). Both forcing
+ ;; shapes count: a schema and a plain tool_choice "required".
+ (let [schema {:type "object" :properties {:title {:type "string"}}}]
+ (are [expected opts] (= expected (:max_tokens (moonshot/moonshot-request-body opts)))
+ 2048 {:model "kimi-k3" :input [{:role :user :content "hi"}] :schema schema :max-tokens 512}
+ 2048 {:model "kimi-k3" :input [{:role :user :content "hi"}] :max-tokens 512
+ :tools [(metabot.tu/get-time-tool)] :tool_choice "required"}
+ 4096 {:model "kimi-k3" :input [{:role :user :content "hi"}] :schema schema :max-tokens 4096}
+ nil {:model "kimi-k3" :input [{:role :user :content "hi"}] :schema schema}
+ 512 {:model "kimi-k3" :input [{:role :user :content "hi"}] :max-tokens 512}
+ 512 {:model "kimi-k2.6" :input [{:role :user :content "hi"}] :schema schema :max-tokens 512}
+ 512 {:model "kimi-k2.6" :input [{:role :user :content "hi"}] :max-tokens 512
+ :tools [(metabot.tu/get-time-tool)] :tool_choice "required"}))))
+
+(deftest ^:parallel request-body-replays-reasoning-test
+ (let [reasoning-round [{:role :user :content "q"}
+ {:type :reasoning :id "r1" :text "think "}
+ {:type :reasoning :id "r1" :text "hard"}
+ {:type :tool-input :id "c1" :function "f" :arguments {:x 1}}
+ {:type :tool-output :id "c1" :result {:output "ok"}}
+ {:type :reasoning :id "r2" :text "more"}
+ {:type :text :text "answer"}]]
+ (testing "in-turn reasoning replays as reasoning_content on each round's assistant message"
+ ;; Moonshot requires the complete assistant message back as-is, including reasoning_content —
+ ;; https://platform.kimi.ai/docs/guide/use-thinking-models
+ (is (=? [{:role "user" :content "q"}
+ {:role "assistant"
+ :content ""
+ :tool_calls [{:id "c1"}]
+ :reasoning_content "think hard"}
+ {:role "tool" :tool_call_id "c1" :content "ok"}
+ {:role "assistant" :content "answer" :reasoning_content "more"}]
+ (:messages (moonshot/moonshot-request-body {:model "kimi-k3" :input reasoning-round})))))
+ (testing "the replay strips with the gate: structured path and :reasoning? false"
+ (are [opts] (not-any? :reasoning_content
+ (:messages (moonshot/moonshot-request-body
+ (assoc opts :model "kimi-k3" :input reasoning-round))))
+ {:schema {:type "object" :properties {:title {:type "string"}}}}
+ {:reasoning? false}))
+ (testing "k2.6 never replays, even though it is whitelisted"
+ ;; its thinking.keep stays at the default null, under which the server ignores replayed
+ ;; reasoning_content — see the hook note in moonshot-request-body
+ (is (not-any? :reasoning_content
+ (:messages (moonshot/moonshot-request-body {:model "kimi-k2.6"
+ :input reasoning-round})))))
+ (testing "an off-whitelist model never replays"
+ (is (not-any? :reasoning_content
+ (:messages (moonshot/moonshot-request-body {:model "kimi-k9"
+ :input reasoning-round})))))))
+
(deftest ^:parallel request-body-prompt-cache-key-test
(testing "a :prompt-cache-key is forwarded as prompt_cache_key, absent otherwise"
(is (= "d34d4c93-a5cc-4d5e-b0a6-6b8f89525b48"
@@ -135,6 +228,39 @@
(self.core/aisdk-xf))
chunks))))))
+(deftest ^:parallel moonshot-reasoning-conv-test
+ (testing "reasoning_content deltas stream as a reasoning block ahead of the text"
+ ;; Condensed from a live kimi-k3 stream captured 2026-09-04 (32 events, reasoning_effort
+ ;; "low"): an empty-content opener, one empty reasoning_content delta — neither may open a
+ ;; block — then flat reasoning deltas, one content delta, and a finish whose usage rides both
+ ;; the finishing choice and a final top-level chunk (one :usage part must come out).
+ (let [usage {:prompt_tokens 103
+ :completion_tokens 44
+ :total_tokens 147
+ :completion_tokens_details {:reasoning_tokens 28}}
+ chunks [{:id "chatcmpl-6a9ab5d84cc66eeecb5c4827"
+ :model "kimi-k3"
+ :choices [{:index 0 :delta {:role "assistant" :content ""} :finish_reason nil}]}
+ {:choices [{:index 0 :delta {:reasoning_content ""} :finish_reason nil}]}
+ {:choices [{:index 0 :delta {:reasoning_content "17*23 = 391."} :finish_reason nil}]}
+ {:choices [{:index 0 :delta {:reasoning_content " 391 < 400."} :finish_reason nil}]}
+ {:choices [{:index 0 :delta {:reasoning_content " So 400 is bigger."} :finish_reason nil}]}
+ {:choices [{:index 0 :delta {:content "400"} :finish_reason nil}]}
+ {:choices [{:index 0 :delta {} :finish_reason "stop" :usage usage}]}
+ {:choices [] :usage usage}]]
+ (testing "chunk stream: :start first, then one reasoning block, then text"
+ (is (= [:start :reasoning-start :reasoning-delta :reasoning-delta :reasoning-delta
+ :reasoning-end :text-start :text-delta :text-end :usage]
+ (into [] (comp (moonshot/moonshot->aisdk-chunks-xf) (map :type)) chunks))))
+ (testing "through the full pipeline: one reasoning part ahead of the text"
+ (is (=? [{:type :start}
+ {:type :reasoning :text "17*23 = 391. 391 < 400. So 400 is bigger."}
+ {:type :text :text "400"}
+ {:type :usage
+ :usage {:promptTokens 103 :completionTokens 44}
+ :finish-reason "stop"}]
+ (into [] (comp (moonshot/moonshot->aisdk-chunks-xf) (self.core/aisdk-xf)) chunks)))))))
+
(deftest ^:parallel moonshot-tool-call-conv-test
(testing "a streamed tool call preceded by reasoning deltas produces one tool-input and no text block"
;; Moonshot opens every stream with an empty-string `content` delta and then streams `reasoning_content`
diff --git a/test/metabase/metabot/self/openai/chat_completions_test.clj b/test/metabase/metabot/self/openai/chat_completions_test.clj
index ae5d6cc0721..a5afe573cd3 100644
--- a/test/metabase/metabot/self/openai/chat_completions_test.clj
+++ b/test/metabase/metabot/self/openai/chat_completions_test.clj
@@ -20,7 +20,8 @@
{:type :text :text "Hi there!"}])))))
(deftest ^:parallel parts->cc-messages-drops-reasoning-test
- (testing "reasoning parts are dropped, not turned into empty user messages"
+ (testing "without a replay hook — every dialect but Mistral and Moonshot — reasoning parts are dropped,
+ not turned into empty user messages"
(is (=? [{:role "user" :content "Hello"}
{:role "assistant" :content "Hi there!"}]
(chat-completions/parts->cc-messages
@@ -29,6 +30,86 @@
{:type :reasoning :id "r1" :text "" :provider-metadata {:anthropic {:signature "abc"}}}
{:type :text :text "Hi there!"}])))))
+(deftest ^:parallel parts->cc-messages-reasoning-replay-hook-test
+ (let [think-hook (fn [part]
+ {:role "assistant"
+ :content [{:type "thinking" :thinking [(:text part)]}]})]
+ (testing "a dialect's replay hook turns each coalesced reasoning block into its message,
+ merged with the step's text and tool calls as chunk-array content"
+ (is (= [{:role "user" :content "Hello"}
+ {:role "assistant"
+ :content [{:type "thinking" :thinking ["thinking"]}
+ {:type "text" :text "Hi there!"}]
+ :tool_calls [{:id "call-1"
+ :type "function"
+ :function {:name "f" :arguments "{}"}}]}]
+ (chat-completions/parts->cc-messages
+ [{:role :user :content "Hello"}
+ ;; a block streams as small parts plus an empty-text metadata carrier;
+ ;; the hook must see ONE coalesced part
+ {:type :reasoning :id "r1" :text "think"}
+ {:type :reasoning :id "r1" :text "ing"}
+ {:type :reasoning :id "r1" :text "" :provider-metadata {:mistral {:signature "abc"}}}
+ {:type :text :text "Hi there!"}
+ {:type :tool-input :id "call-1" :function "f" :arguments {}}]
+ {:reasoning-part->message think-hook}))))
+ (testing "the coalesced part carries the block's metadata for the hook to use"
+ (let [seen (atom nil)]
+ (chat-completions/parts->cc-messages
+ [{:type :reasoning :id "r1" :text "a"}
+ {:type :reasoning :id "r1" :text "" :provider-metadata {:mistral {:signature "abc"}}}]
+ {:reasoning-part->message (fn [part] (reset! seen part) nil)})
+ (is (= {:type :reasoning
+ :id "r1"
+ :text "a"
+ :provider-metadata {:mistral {:signature "abc"}}}
+ @seen))))
+ (testing "string-only assistant groups fold exactly as they do without a hook"
+ (is (= (chat-completions/parts->cc-messages
+ [{:type :text :text "Hi"}
+ {:type :tool-input :id "c1" :function "f" :arguments {}}])
+ (chat-completions/parts->cc-messages
+ [{:type :text :text "Hi"}
+ {:type :tool-input :id "c1" :function "f" :arguments {}}]
+ {:reasoning-part->message think-hook}))))))
+
+(deftest ^:parallel parts->cc-messages-top-level-reasoning-hook-test
+ ;; the Moonshot-shaped replay channel: reasoning rides as a top-level :reasoning_content
+ ;; sibling of :content/:tool_calls rather than as a content chunk
+ (let [top-level-hook (fn [part] {:role "assistant" :content "" :reasoning_content (:text part)})]
+ (testing "a hook message's :reasoning_content lands on the round's merged assistant message"
+ (is (= [{:role "user" :content "q"}
+ {:role "assistant"
+ :content ""
+ :tool_calls [{:id "c1" :type "function" :function {:name "f" :arguments "{}"}}]
+ :reasoning_content "thinking"}]
+ (chat-completions/parts->cc-messages
+ [{:role :user :content "q"}
+ {:type :reasoning :id "r1" :text "think"}
+ {:type :reasoning :id "r1" :text "ing"}
+ {:type :tool-input :id "c1" :function "f" :arguments {}}]
+ {:reasoning-part->message top-level-hook}))))
+ (testing "multiple reasoning blocks in one assistant group join in part order"
+ ;; the wire has a single :reasoning_content field per message, so order is the only
+ ;; fidelity available — reasoning emitted after a tool call joins after, not before
+ (is (= [{:role "assistant"
+ :content "answer"
+ :tool_calls [{:id "c1" :type "function" :function {:name "f" :arguments "{}"}}]
+ :reasoning_content "firstsecond"}]
+ (chat-completions/parts->cc-messages
+ [{:type :reasoning :id "r1" :text "first"}
+ {:type :tool-input :id "c1" :function "f" :arguments {}}
+ {:type :reasoning :id "r2" :text "second"}
+ {:type :text :text "answer"}]
+ {:reasoning-part->message top-level-hook}))))
+ (testing "a lone reasoning part passes through as the hook's own message"
+ ;; a reasoning-only assistant message is a shape Moonshot itself never emits; unprobed
+ ;; whether the API accepts it — pinned so a change here is deliberate
+ (is (= [{:role "assistant" :content "" :reasoning_content "alone"}]
+ (chat-completions/parts->cc-messages
+ [{:type :reasoning :id "r1" :text "alone"}]
+ {:reasoning-part->message top-level-hook}))))))
+
(deftest ^:parallel parts->cc-messages-tool-call-test
(testing "text + tool call merges into single assistant message"
(is (=? [{:role "assistant"
@@ -266,9 +347,35 @@
{:choices [{:index 0 :delta {} :finish_reason "tool_calls"}]}
{:choices [] :usage {:prompt_tokens 138 :completion_tokens 36}}])))))
+(deftest ^:parallel chunks-xf-combined-reasoning-and-tool-call-delta-test
+ (testing "a delta carrying both reasoning and a tool call keeps the tool call"
+ ;; The tool call's opening chunk is the only one carrying its id and name — classifying the
+ ;; delta as :reasoning would lose the call entirely and break the tool loop. The delta's
+ ;; reasoning fragment is dropped instead: display text, recoverable.
+ (is (= [{:type :start :messageId "chatcmpl-9"}
+ {:type :tool-input-start :toolCallId "call-1" :toolName "get_weather"}
+ {:type :tool-input-delta :toolCallId "call-1" :inputTextDelta "{\"city\""}
+ {:type :tool-input-delta :toolCallId "call-1" :inputTextDelta ": \"Berlin\"}"}
+ {:type :tool-input-available :toolCallId "call-1" :toolName "get_weather"}]
+ (into [] (chat-completions/chat-completions->aisdk-chunks-xf
+ chat-completions/stop-reasons
+ {:forward-reasoning? true})
+ [{:id "chatcmpl-9"
+ :model "m"
+ :choices [{:index 0
+ :delta {:reasoning_content "planning"
+ :tool_calls [{:index 0
+ :id "call-1"
+ :type "function"
+ :function {:name "get_weather"
+ :arguments "{\"city\""}}]}}]}
+ {:choices [{:index 0 :delta {:tool_calls [{:index 0
+ :function {:arguments ": \"Berlin\"}"}}]}}]}
+ {:choices [{:index 0 :delta {} :finish_reason "tool_calls"}]}])))))
+
(deftest ^:parallel chunks-xf-reasoning-deltas-open-no-text-block-test
(testing "reasoning_content deltas and empty-string content produce no chunks"
- ;; Reasoning is not replayable over Chat Completions, so it is dropped rather than surfaced as text.
+ ;; Without `:forward-reasoning?` reasoning deltas are dropped rather than surfaced as text.
;; An empty-string `content` between blocks must not open a text block either — that would close
;; the tool call that follows it.
(is (= [:start :tool-input-start :tool-input-delta :tool-input-available :usage]
diff --git a/test/metabase/metabot/self/openrouter_test.clj b/test/metabase/metabot/self/openrouter_test.clj
index bce118884fe..d429aa081ae 100644
--- a/test/metabase/metabot/self/openrouter_test.clj
+++ b/test/metabase/metabot/self/openrouter_test.clj
@@ -96,11 +96,20 @@
(deftest ^:parallel request-body-keeps-temperature-for-models-that-accept-it-test
(testing "every other whitelisted model still gets the profile's temperature"
- (doseq [model ["anthropic/claude-opus-4.6" "anthropic/claude-opus-4.5" "anthropic/claude-opus-4.1"
- "anthropic/claude-sonnet-4.6" "anthropic/claude-sonnet-4.5" "anthropic/claude-haiku-4.5"
+ (doseq [model ["anthropic/claude-opus-4.5" "anthropic/claude-opus-4.1"
+ "anthropic/claude-sonnet-4.5" "anthropic/claude-haiku-4.5"
"deepseek/deepseek-v4-pro" "mistralai/mistral-medium-3-5" "z-ai/glm-5.2"]]
(testing model
- (is (= 0.3 (request-body-temperature model)))))))
+ (is (= 0.3 (request-body-temperature model))))))
+ (testing "the 4.6 Claudes accept temperature only while reasoning is off — enabled thinking rejects it"
+ (doseq [model ["anthropic/claude-opus-4.6" "anthropic/claude-sonnet-4.6"]]
+ (testing model
+ (is (nil? (request-body-temperature model)))
+ (is (= 0.3 (:temperature (openrouter/openrouter-request-body
+ {:model model
+ :input [{:role :user :content "hi"}]
+ :temperature 0.3
+ :reasoning? false}))))))))
(deftest ^:parallel request-body-omits-temperature-when-none-is-supplied-test
(testing "a request with no temperature is unchanged either way"
@@ -158,6 +167,141 @@
:schema {:type "object" :properties {:answer {:type "string"}}}})]
(is (= "required" (:tool_choice body))))))))
+;;; ──────────────────────────────────────────────────────────────────
+;;; Reasoning directive tests
+;;; ──────────────────────────────────────────────────────────────────
+
+(defn- body-for
+ "The request body for `opts`, with a stock user message."
+ [opts]
+ (openrouter/openrouter-request-body (merge {:input [{:role :user :content "hi"}]} opts)))
+
+(deftest ^:parallel reasoning-model?-test
+ (are [model expected] (= expected (openrouter/reasoning-model? model))
+ "anthropic/claude-sonnet-4.6" true
+ "anthropic/claude-fable-5" true
+ "moonshotai/kimi-k3" true
+ "z-ai/glm-5.2" true
+ "openai/gpt-5.5" true
+ "openai/gpt-5.6-sol" true
+ "openai/gpt-5.4" true
+ "openai/gpt-5.4-mini" true
+ "anthropic/claude-haiku-4.5" false
+ "anthropic/claude-opus-4.5" false
+ "not/a-model" false
+ nil false))
+
+(deftest ^:parallel request-body-reasoning-directive-test
+ (testing "renderable models get an explicit enable by default"
+ (is (= {:enabled true} (:reasoning (body-for {:model "anthropic/claude-sonnet-4.6"})))))
+ (testing ":reasoning? false gets an explicit disable"
+ (is (= {:enabled false} (:reasoning (body-for {:model "anthropic/claude-sonnet-4.6" :reasoning? false})))))
+ (testing "structured output gets an explicit disable"
+ (is (= {:enabled false} (:reasoning (body-for {:model "z-ai/glm-5.2" :schema {:type "object"}})))))
+ (testing "a forced tool call gets an explicit disable: probed live, Anthropic upstreams do no reasoning under it"
+ (is (= {:enabled false}
+ (:reasoning (body-for {:model "anthropic/claude-sonnet-4.6"
+ :tools [{:tool-name "get_thing"
+ :doc "Get a thing."
+ :schema [:=> [:cat [:map [:id :int]]] :any]
+ :fn identity}]
+ :tool_choice "required"})))))
+ (testing "qwen's required->auto downgrade lands first, so its directive stays enabled"
+ (is (= {:enabled true}
+ (:reasoning (body-for {:model "qwen/qwen3.8-max"
+ :tools [{:tool-name "get_thing"
+ :doc "Get a thing."
+ :schema [:=> [:cat [:map [:id :int]]] :any]
+ :fn identity}]
+ :tool_choice "required"})))))
+ (testing "mandatory-reasoning models get no directive instead of a rejected disable"
+ (is (not (contains? (body-for {:model "anthropic/claude-fable-5" :reasoning? false}) :reasoning)))
+ (is (not (contains? (body-for {:model "qwen/qwen3.8-max" :schema {:type "object"}}) :reasoning))))
+ (testing "renderable-default models never get a directive, even under structured output:
+ they stream summaries server-side by default and an explicit enable suppresses
+ gpt-5.6's reasoning entirely"
+ (is (not (contains? (body-for {:model "openai/gpt-5.5"}) :reasoning)))
+ (is (not (contains? (body-for {:model "openai/gpt-5.6-sol"}) :reasoning)))
+ (is (not (contains? (body-for {:model "openai/gpt-5.5" :schema {:type "object"}}) :reasoning)))
+ (is (not (contains? (body-for {:model "openai/gpt-5.5" :reasoning? false}) :reasoning))))
+ (testing "budget-only models never get a directive"
+ (is (not (contains? (body-for {:model "anthropic/claude-haiku-4.5"}) :reasoning))))
+ (testing "enabling reasoning drops :temperature for anthropic models (rejected while thinking)"
+ (let [body (body-for {:model "anthropic/claude-sonnet-4.6" :temperature 0.3})]
+ (is (= {:enabled true} (:reasoning body)))
+ (is (not (contains? body :temperature)))))
+ (testing "other renderable models keep their temperature alongside the enable"
+ (is (=? {:reasoning {:enabled true}
+ :temperature 0.3}
+ (body-for {:model "z-ai/glm-5.2" :temperature 0.3})))))
+
+(deftest ^:parallel mandatory-reasoning-forced-tool-call-floor-test
+ (testing "a forced tool call on a mandatory-reasoning model gets its max_tokens cap floored"
+ ;; safety net — its reasoning cannot be disabled and bills against the same budget as the
+ ;; tool call; theory vs practice in openrouter/forced-tool-call-token-floor
+ (are [expected opts] (= expected (:max_tokens (body-for (assoc opts :model "qwen/qwen3.8-max"))))
+ 2048 {:schema {:type "object"} :max-tokens 512}
+ 4096 {:schema {:type "object"} :max-tokens 4096}
+ nil {:schema {:type "object"}}
+ 512 {:max-tokens 512}))
+ (testing "a non-mandatory model keeps its cap — it got the disable instead"
+ (let [body (body-for {:model "anthropic/claude-sonnet-4.6" :schema {:type "object"} :max-tokens 512})]
+ (is (= 512 (:max_tokens body)))
+ (is (= {:enabled false} (:reasoning body)))))
+ (testing "the floor is keyed on the mandatory flag, not the class: the renderable-default pros get it too"
+ (doseq [model ["openai/gpt-5.5-pro" "openai/gpt-5.4-pro"]]
+ (testing model
+ (let [body (body-for {:model model :schema {:type "object"} :max-tokens 512})]
+ (is (= 2048 (:max_tokens body)))
+ (is (not (contains? body :reasoning))))
+ (is (= 512 (:max_tokens (body-for {:model model :max-tokens 512})))))))
+ (testing "a non-mandatory renderable-default model keeps its cap and still gets no directive"
+ (let [body (body-for {:model "openai/gpt-5.5" :schema {:type "object"} :max-tokens 512})]
+ (is (= 512 (:max_tokens body)))
+ (is (not (contains? body :reasoning))))))
+
+(deftest ^:parallel reasoning-class-partition-test
+ (testing "every whitelisted model is deliberately classified, and the class drives the body"
+ (let [renderable #{"anthropic/claude-fable-5" "anthropic/claude-opus-5" "anthropic/claude-opus-4.8"
+ "anthropic/claude-opus-4.7" "anthropic/claude-opus-4.6" "anthropic/claude-sonnet-5"
+ "anthropic/claude-sonnet-4.6" "deepseek/deepseek-v4-pro" "deepseek/deepseek-v4-pro-0813"
+ "deepseek/deepseek-v4-flash-0731" "mistralai/mistral-medium-3-5" "moonshotai/kimi-k3"
+ "openai/gpt-5.4" "openai/gpt-5.4-mini" "qwen/qwen3.8-max" "z-ai/glm-5.3" "z-ai/glm-5.2"}
+ renderable-default #{"openai/gpt-5.6-sol" "openai/gpt-5.6-terra" "openai/gpt-5.6-luna" "openai/gpt-5.5"
+ "openai/gpt-5.5-pro" "openai/gpt-5.4-pro"}
+ budget #{"anthropic/claude-opus-4.5" "anthropic/claude-opus-4.1" "anthropic/claude-sonnet-4.5"
+ "anthropic/claude-haiku-4.5"}]
+ (is (= (set (keys @#'openrouter/supported-models))
+ (into renderable (concat renderable-default budget))))
+ (doseq [model renderable]
+ (testing model
+ (is (true? (openrouter/reasoning-model? model)))
+ (is (= {:enabled true} (:reasoning (body-for {:model model}))))))
+ (doseq [model renderable-default]
+ (testing model
+ (is (true? (openrouter/reasoning-model? model)))
+ (is (not (contains? (body-for {:model model}) :reasoning)))))
+ (doseq [model budget]
+ (testing model
+ (is (false? (openrouter/reasoning-model? model)))
+ (is (not (contains? (body-for {:model model}) :reasoning))))))))
+
+(deftest ^:parallel openrouter-reasoning-deltas-become-reasoning-parts-test
+ (testing "flat delta.reasoning strings stream as a reasoning part ahead of the text"
+ (is (=? [{:type :start}
+ {:type :reasoning :text "Let me think about 2+2."}
+ {:type :text :text "4"}
+ {:type :usage}]
+ (into [] (comp (openrouter/openrouter->aisdk-chunks-xf)
+ (self.core/aisdk-xf))
+ [{:id "gen-1"
+ :model "anthropic/claude-sonnet-4.6"
+ :choices [{:delta {:role "assistant" :reasoning "Let me think"}}]}
+ {:choices [{:delta {:reasoning " about 2+2."}}]}
+ {:choices [{:delta {:content "4"}}]}
+ {:choices [{:delta {} :finish_reason "stop"}]
+ :usage {:prompt_tokens 8 :completion_tokens 1 :total_tokens 9}}])))))
+
;;; ──────────────────────────────────────────────────────────────────
;;; Streaming chunk conversion tests
;;; ──────────────────────────────────────────────────────────────────
diff --git a/test/metabase/metabot/self/zai_test.clj b/test/metabase/metabot/self/zai_test.clj
index 00837dfe3a9..d5c1294f52d 100644
--- a/test/metabase/metabot/self/zai_test.clj
+++ b/test/metabase/metabot/self/zai_test.clj
@@ -71,6 +71,105 @@
:temperature 0.2
:max-tokens 128})))))
+(deftest ^:parallel request-body-thinking-directive-test
+ (testing "whitelisted models get thinking enabled by default (making the server default explicit)"
+ (is (= {:type "enabled"}
+ (:thinking (zai/zai-request-body {:input [{:role :user :content "hi"}]})))))
+ (testing ":reasoning? false disables thinking explicitly — omitting the key would leave it on"
+ (is (= {:type "disabled"}
+ (:thinking (zai/zai-request-body {:input [{:role :user :content "hi"}]
+ :reasoning? false})))))
+ (testing "structured output disables thinking: it would spend the output budget invisibly"
+ (is (= {:type "disabled"}
+ (:thinking (zai/zai-request-body {:input [{:role :user :content "hi"}]
+ :schema {:type "object"}})))))
+ (testing "tool_choice \"required\" keeps thinking on — Z.AI accepts the combination"
+ (is (= {:type "enabled"}
+ (:thinking (zai/zai-request-body {:input [{:role :user :content "hi"}]
+ :tools [(metabot.tu/get-time-tool)]
+ :tool_choice "required"})))))
+ (testing "non-whitelisted models get an explicit disable — glm-4.7 thinks compulsorily by default,
+ and the xf forwards reasoning unconditionally (disable accepted, probed 2026-09-03)"
+ (are [opts] (= {:type "disabled"}
+ (:thinking (zai/zai-request-body
+ (assoc opts :model "glm-4.7" :input [{:role :user :content "hi"}]))))
+ {}
+ {:schema {:type "object"}}))
+ (testing "pre-4.5 models tolerate the disable (probed 2026-09-03) and do not think anyway"
+ (is (= {:type "disabled"}
+ (:thinking (zai/zai-request-body {:model "glm-4-32b-0414-128k"
+ :input [{:role :user :content "hi"}]}))))))
+
+(deftest ^:parallel request-body-thinking-only-model-test
+ (let [input [{:role :user :content "hi"}]]
+ (testing "thinking-only models reject the disable (error 1210): no directive, reasoning_effort instead"
+ (let [body (zai/zai-request-body {:model "glm-5.3" :input input})]
+ (is (not (contains? body :thinking)))
+ (is (= "max" (:reasoning_effort body)))
+ (is (not (contains? body :max_tokens)))))
+ (testing "a schema drops the effort to low and raises a title-sized cap to the floor"
+ (is (=? {:reasoning_effort "low"
+ :max_tokens 2048}
+ (zai/zai-request-body {:model "glm-5.3"
+ :input input
+ :schema {:type "object"}
+ :max-tokens 512}))))
+ (testing ":reasoning? false also drops the effort to low — a floor, not an off switch"
+ (is (= "low" (:reasoning_effort (zai/zai-request-body {:model "glm-5.3"
+ :input input
+ :reasoning? false})))))
+ (testing "tool_choice \"required\" keeps max effort but still gets the floor"
+ (is (=? {:reasoning_effort "max"
+ :max_tokens 2048}
+ (zai/zai-request-body {:model "glm-5.3"
+ :input input
+ :tools [(metabot.tu/get-time-tool)]
+ :tool_choice "required"
+ :max-tokens 512}))))
+ (testing "the floor only raises: a larger cap and an unforced cap are left alone"
+ (are [opts expected] (= expected
+ (:max_tokens (zai/zai-request-body (assoc opts :model "glm-5.3" :input input))))
+ {:schema {:type "object"} :max-tokens 4096} 4096
+ {:max-tokens 512} 512))
+ (testing "models that can switch thinking off get neither effort nor floor"
+ (let [body (zai/zai-request-body {:model "glm-5.2"
+ :input input
+ :schema {:type "object"}
+ :max-tokens 512})]
+ (is (= {:type "disabled"} (:thinking body)))
+ (is (not (contains? body :reasoning_effort)))
+ (is (= 512 (:max_tokens body)))))))
+
+(deftest ^:parallel reasoning-model?-test
+ (are [model expected] (= expected (zai/reasoning-model? model))
+ "glm-5.2" true
+ "glm-4.7" false
+ nil false))
+
+(deftest ^:parallel reasoning-gate-matches-request-config-test
+ (testing "every whitelisted model gates true and requests thinking under default opts"
+ (doseq [model (keys @#'zai/supported-models)]
+ (testing model
+ (is (true? (zai/reasoning-model? model)))
+ ;; thinking-only models reject the directive and get none — their thinking is on
+ ;; server-side regardless, so the gate still holds
+ (is (= (if (@#'zai/thinking-only-model? model) nil {:type "enabled"})
+ (:thinking (zai/zai-request-body {:model model
+ :input [{:role :user :content "hi"}]})))))))
+ (testing "a non-whitelisted model gates false and its thinking is explicitly disabled"
+ (is (false? (zai/reasoning-model? "glm-4.7")))
+ (is (= {:type "disabled"}
+ (:thinking (zai/zai-request-body {:model "glm-4.7"
+ :input [{:role :user :content "hi"}]}))))))
+
+(deftest ^:parallel thinking-only-implies-supported-test
+ (testing "thinking-only is read off a supported-models row, so it cannot name a model the gate disavows"
+ (doseq [[model {:keys [thinking-only?]}] @#'zai/supported-models
+ :when thinking-only?]
+ (testing model
+ (is (true? (zai/reasoning-model? model)))))
+ (is (false? (@#'zai/thinking-only-model? "a-model-we-do-not-serve")))))
+
;;; ──────────────────────────────────────────────────────────────────
;;; Streaming chunk conversion tests
;;;
@@ -100,9 +199,10 @@
(self.core/aisdk-xf))
chunks))))))
-(deftest ^:parallel zai-reasoning-deltas-ignored-test
- (testing "thinking-mode reasoning_content deltas produce no text blocks"
+(deftest ^:parallel zai-reasoning-deltas-become-reasoning-parts-test
+ (testing "thinking-mode reasoning_content deltas stream as a reasoning part ahead of the text"
(is (=? [{:type :start}
+ {:type :reasoning :text "Let me think about 2+2."}
{:type :text :text "4"}
{:type :usage}]
(into [] (comp (zai/zai->aisdk-chunks-xf)
diff --git a/test/metabase/metabot/settings_test.clj b/test/metabase/metabot/settings_test.clj
index dc4183d8cbd..d9070e2fe0b 100644
--- a/test/metabase/metabot/settings_test.clj
+++ b/test/metabase/metabot/settings_test.clj
@@ -191,21 +191,55 @@
(is (false? (metabot.settings/llm-metabot-configured?)))))))
(deftest metabot-supports-reasoning-test
- (testing "only anthropic and openai models that stream reasoning report support"
+ (testing "models that stream reasoning report support; others answer false"
(with-connections [(connection "anthropic" "anthropic")
(connection "openai" "openai")
(connection "bedrock" "bedrock")
- (connection "google" "google")]
+ (connection "google" "google")
+ (connection "azure" "azure")
+ (connection "zai" "zai")
+ (connection "openrouter" "openrouter")
+ (connection "mistral" "mistral")
+ (connection "moonshot" "moonshot")]
(doseq [[model-ref expected]
{"anthropic/claude-sonnet-4-6" true
"anthropic/claude-haiku-4-5" false
"openai/gpt-5.4" true
"openai/gpt-4o" false
- "bedrock/anthropic.claude-opus-4-8" false
- ;; google serves both wire families; only its Claude models stream reasoning back
+ "bedrock/anthropic.claude-opus-4-8" true
+ "bedrock/anthropic.claude-haiku-4-5" false
+ ;; requests reasoning (encrypted replay), but the mantle never
+ ;; streams summaries, so nothing renders — see bedrock/reasoning-model?
+ "bedrock/openai.gpt-5.5" false
+ "azure/anthropic/claude-opus-5" true
+ "azure/anthropic/claude-haiku-4-5" false
+ "azure/openai/gpt-5.4" true
+ "azure/openai/my-deployment" false
+ ;; a family with no deployment segment names no model
+ "azure/anthropic" false
+ "zai/glm-5.2" true
+ "zai/glm-4.7" false
+ "openrouter/anthropic/claude-sonnet-4.6" true
+ "openrouter/z-ai/glm-5.2" true
+ ;; streams reasoning summaries under the server default
+ "openrouter/openai/gpt-5.5" true
+ ;; re-probed 2026-09-04: streams summaries under the explicit enable
+ "openrouter/openai/gpt-5.4" true
+ "openrouter/anthropic/claude-haiku-4.5" false
+ ;; google serves both wire families; Claude partner models and catalog Geminis both stream
"google/anthropic/claude-sonnet-4-6" true
"google/anthropic/claude-haiku-4-5@20251001" false
- "google/google/gemini-3.5-flash" false}]
+ "google/google/gemini-3.5-flash" true
+ "google/google/gemini-3.7-flash" true
+ ;; off-catalog: no thinking directive — see google/models.clj
+ "google/google/gemini-2.5-flash" false
+ "mistral/mistral-medium-3-5" true
+ ;; catalog aliases are not resolved — see mistral/reasoning-model?
+ "mistral/mistral-medium-latest" false
+ "moonshot/kimi-k3" true
+ "moonshot/kimi-k2.6" true
+ ;; thinking-capable but excluded from supported-models — see moonshot/reasoning-model?
+ "moonshot/kimi-k2.7-code" false}]
(testing model-ref
(with-selected-model model-ref
(is (= expected (metabot.settings/llm-metabot-supports-reasoning?)))))))))
@@ -231,6 +265,12 @@
(with-selected-model "metabase/anthropic/claude-opus-5"
(is (false? (metabot.settings/llm-metabot-supports-fast-mode?))))))))
+(deftest metabot-supports-reasoning-model-less-ref-test
+ (testing "a ref with no model segment answers false rather than throwing"
+ (with-connections [(connection "bedrock" "bedrock")]
+ (with-selected-model "bedrock"
+ (is (false? (metabot.settings/llm-metabot-supports-reasoning?)))))))
+
(deftest metabot-supports-reasoning-vllm-test
(testing "vLLM answers from what the connect-time probe recorded on the connection, since neither its catalog
nor its model names carry a reasoning field"
@@ -245,6 +285,18 @@
(with-selected-model "vllm/vllm-test"
(is (false? (metabot.settings/llm-metabot-supports-reasoning?)))))))
+(deftest metabot-supports-reasoning-managed-proxy-test
+ (testing "the managed connection answers from the model's own provider segment"
+ (with-connections [(connection "metabase" "metabase")]
+ ;; only anthropic models are servable over the proxy (openai-raw rejects
+ ;; :ai-proxy?), so only anthropic refs are exercised here
+ (doseq [[model-ref expected]
+ {"metabase/anthropic/claude-sonnet-4-6" true
+ "metabase/anthropic/claude-haiku-4-5" false}]
+ (testing model-ref
+ (with-selected-model model-ref
+ (is (= expected (metabot.settings/llm-metabot-supports-reasoning?)))))))))
+
(deftest metabot-configured-with-a-keyless-vllm-connection-test
(testing "a vLLM server started without --api-key is a complete configuration: the base URL is the credential"
(with-connections [(connection "vllm" "vllm" {:base-url "http://vllm.internal:8000/v1"})]