Skip to content

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

Add Z.AI metabot provider (#78521)

appleby75fb5a66ee4a
diff --git a/frontend/src/metabase-types/api/metabot.ts b/frontend/src/metabase-types/api/metabot.ts
index ae5ef141ba8..ecdca53d952 100644
--- a/frontend/src/metabase-types/api/metabot.ts
+++ b/frontend/src/metabase-types/api/metabot.ts
@@ -195,7 +195,8 @@ export type MetabotProvider =
| "azure"
| "bedrock"
| "openai"
- | "openrouter";
+ | "openrouter"
+ | "zai";
export interface BedrockCredentials {
"access-key-id"?: string | null;
diff --git a/frontend/src/metabase-types/api/settings.ts b/frontend/src/metabase-types/api/settings.ts
index f4f33afdd23..e36c6d40d7d 100644
--- a/frontend/src/metabase-types/api/settings.ts
+++ b/frontend/src/metabase-types/api/settings.ts
@@ -538,6 +538,7 @@ interface SettingsManagerSettings {
"llm-anthropic-api-key"?: string | null;
"llm-anthropic-api-base-url"?: string | null;
"llm-openrouter-api-key"?: string | null;
+ "llm-zai-api-key"?: string | null;
"llm-azure-api-key"?: string | null;
"llm-azure-api-base-url"?: string | null;
"llm-bedrock-access-key-id"?: string | null;
@@ -771,6 +772,7 @@ export interface EnterpriseSettings extends Settings {
"llm-metabot-configured?"?: boolean | null;
"llm-metabot-supports-reasoning?"?: boolean | null;
"llm-openrouter-api-key"?: string | null;
+ "llm-zai-api-key"?: string | null;
"session-timeout": TimeoutValue | null;
"search-engine": SearchEngineSettingValue | null;
"scim-enabled"?: boolean | null;
diff --git a/frontend/src/metabase/admin/ai/AIProviderSettingsSection.unit.spec.tsx b/frontend/src/metabase/admin/ai/AIProviderSettingsSection.unit.spec.tsx
index add469808bc..4db41e32b74 100644
--- a/frontend/src/metabase/admin/ai/AIProviderSettingsSection.unit.spec.tsx
+++ b/frontend/src/metabase/admin/ai/AIProviderSettingsSection.unit.spec.tsx
@@ -105,6 +105,10 @@ const DEFAULT_RESPONSES: Record<MetabotProvider, MetabotSettingsResponse> = {
},
],
},
+ zai: {
+ value: "zai/glm-5.2",
+ models: [{ id: "glm-5.2", display_name: "GLM-5.2" }],
+ },
};
type MetabotUsageQuota = {
@@ -125,6 +129,7 @@ type MetabotSettingKey =
| "llm-azure-api-base-url"
| "llm-openai-api-key"
| "llm-openrouter-api-key"
+ | "llm-zai-api-key"
| "llm-bedrock-access-key-id"
| "llm-bedrock-secret-access-key"
| "llm-bedrock-region"
@@ -218,6 +223,7 @@ async function setup({
bedrock: null,
openai: null,
openrouter: null,
+ zai: null,
...apiKeyValues,
};
@@ -280,6 +286,10 @@ async function setup({
key: "llm-openrouter-api-key",
value: mergedApiKeyValues.openrouter ?? undefined,
}),
+ "llm-zai-api-key": createMockSettingDefinition({
+ key: "llm-zai-api-key",
+ value: mergedApiKeyValues.zai ?? undefined,
+ }),
"llm-bedrock-access-key-id": createMockSettingDefinition({
key: "llm-bedrock-access-key-id",
value: mergedApiKeyValues.bedrock ?? undefined,
@@ -382,7 +392,9 @@ async function setup({
? "llm-anthropic-api-key"
: body.provider === "openai"
? "llm-openai-api-key"
- : "llm-openrouter-api-key";
+ : body.provider === "zai"
+ ? "llm-zai-api-key"
+ : "llm-openrouter-api-key";
const maskedApiKey = body["api-key"]
? `**********${String(body["api-key"]).slice(-2)}`
: undefined;
@@ -610,6 +622,20 @@ describe("AIProviderSettingsSection", () => {
expect(screen.queryByText("Coming soon")).not.toBeInTheDocument();
});
+ it("shows Z.AI as selectable in the provider dropdown", async () => {
+ await setup({ savedProviderValue: null, isConfigured: false });
+
+ await userEvent.click(screen.getByLabelText("Provider"));
+
+ const zaiOption = await screen.findByRole("option", {
+ name: /Z\.AI/,
+ });
+ expect(zaiOption).toBeInTheDocument();
+ expect(zaiOption).not.toHaveAttribute("data-combobox-disabled");
+
+ expect(screen.queryByText("Coming soon")).not.toBeInTheDocument();
+ });
+
it("BOT-1429: keeps the form interactive while session-properties refetches in the background", async () => {
const { store } = await setup();
const apiKey = await screen.findByLabelText("API key");
@@ -1721,6 +1747,95 @@ describe("AIProviderSettingsSection", () => {
expect(screen.getByLabelText("Provider")).toHaveValue("");
});
+ it("connects to Z.AI by saving the API key and selecting a model", async () => {
+ await setup({
+ savedProviderValue: null,
+ isConfigured: false,
+ apiKeyValues: { zai: null },
+ updateResponse: {
+ value: "zai/glm-5.2",
+ models: DEFAULT_RESPONSES.zai.models,
+ },
+ });
+
+ await selectProvider("Z.AI");
+ await userEvent.type(screen.getByLabelText("API key"), "zai-key.test");
+ await userEvent.click(screen.getByRole("button", { name: "Connect" }));
+
+ await waitFor(() => {
+ expect(
+ fetchMock.callHistory.calls("path:/api/metabot/settings", {
+ method: "PUT",
+ }),
+ ).toHaveLength(1);
+ });
+
+ expect(
+ fetchMock.callHistory.lastCall("path:/api/metabot/settings", {
+ method: "PUT",
+ body: {
+ provider: "zai",
+ "api-key": "zai-key.test",
+ },
+ }),
+ ).toBeDefined();
+
+ await screen.findByLabelText("Model");
+ await openModelSelector();
+ await userEvent.click(await screen.findByText("GLM-5.2"));
+
+ await waitFor(() => {
+ expect(
+ fetchMock.callHistory.calls("path:/api/metabot/settings", {
+ method: "PUT",
+ }),
+ ).toHaveLength(2);
+ });
+
+ expect(
+ fetchMock.callHistory.lastCall("path:/api/metabot/settings", {
+ method: "PUT",
+ body: {
+ provider: "zai",
+ model: "glm-5.2",
+ },
+ }),
+ ).toBeDefined();
+
+ expect(
+ screen.queryByRole("button", { name: "Connect" }),
+ ).not.toBeInTheDocument();
+ });
+
+ it("disconnects Z.AI by clearing both the provider and API key settings", async () => {
+ await setup({
+ savedProviderValue: "zai/glm-5.2",
+ isConfigured: true,
+ apiKeyValues: { zai: "**********st" },
+ });
+
+ await screen.findByText("Connected to Z.AI");
+ await screen.findByLabelText("API key");
+ await confirmDisconnectProvider();
+
+ await waitFor(() => {
+ expect(
+ fetchMock.callHistory.called("path:/api/setting", {
+ method: "PUT",
+ body: {
+ "llm-metabot-provider": null,
+ "llm-zai-api-key": null,
+ },
+ }),
+ ).toBe(true);
+ });
+
+ expect(
+ await screen.findByText("Connect to an AI provider"),
+ ).toBeInTheDocument();
+ expect(screen.getByLabelText("Provider")).toHaveValue("");
+ });
+
it("disconnects an API-key provider by clearing both the provider and API key settings", async () => {
await setup();
diff --git a/frontend/src/metabase/admin/ai/AISettingsPage.unit.spec.tsx b/frontend/src/metabase/admin/ai/AISettingsPage.unit.spec.tsx
index d9ce3637423..a9d4a618c09 100644
--- a/frontend/src/metabase/admin/ai/AISettingsPage.unit.spec.tsx
+++ b/frontend/src/metabase/admin/ai/AISettingsPage.unit.spec.tsx
@@ -113,6 +113,10 @@ const setup = async ({
key: "llm-openrouter-api-key",
value: undefined,
}),
+ createMockSettingDefinition({
+ key: "llm-zai-api-key",
+ value: undefined,
+ }),
]);
setupUpdateSettingEndpoint();
setupCollectionByIdEndpoint({ collections });
diff --git a/frontend/src/metabase/metabot/components/AIProviderConfigurationForm/AIProviderConfigurationForm.tsx b/frontend/src/metabase/metabot/components/AIProviderConfigurationForm/AIProviderConfigurationForm.tsx
index b4f8bbc8671..bb095739f1c 100644
--- a/frontend/src/metabase/metabot/components/AIProviderConfigurationForm/AIProviderConfigurationForm.tsx
+++ b/frontend/src/metabase/metabot/components/AIProviderConfigurationForm/AIProviderConfigurationForm.tsx
@@ -126,6 +126,7 @@ function AIProviderConfigurationFormBody({
"llm-anthropic-api-key",
"llm-openai-api-key",
"llm-openrouter-api-key",
+ "llm-zai-api-key",
] as const);
const disconnectProvider = useCallback(async () => {
@@ -321,15 +322,21 @@ function AIProviderConfigurationFormBody({
isEnvSetting={isEnvSetting}
/>
))
- .with("anthropic", "openai", "openrouter", (selectedProvider) => (
- <ApiKeyProviderFields
- key={selectedProvider}
- selectedProvider={selectedProvider}
- connectedModel={connectedModel}
- isCurrentConfigured={isCurrentConfigured}
- isEnvSetting={isEnvSetting}
- />
- ))
+ .with(
+ "anthropic",
+ "openai",
+ "openrouter",
+ "zai",
+ (selectedProvider) => (
+ <ApiKeyProviderFields
+ key={selectedProvider}
+ selectedProvider={selectedProvider}
+ connectedModel={connectedModel}
+ isCurrentConfigured={isCurrentConfigured}
+ isEnvSetting={isEnvSetting}
+ />
+ ),
+ )
.with(P.nullish, () => null)
.exhaustive()}
diff --git a/frontend/src/metabase/metabot/components/AIProviderConfigurationForm/ApiKeyProviderFields.tsx b/frontend/src/metabase/metabot/components/AIProviderConfigurationForm/ApiKeyProviderFields.tsx
index 7084348329d..73f4a96a2b6 100644
--- a/frontend/src/metabase/metabot/components/AIProviderConfigurationForm/ApiKeyProviderFields.tsx
+++ b/frontend/src/metabase/metabot/components/AIProviderConfigurationForm/ApiKeyProviderFields.tsx
@@ -38,6 +38,7 @@ export const ApiKeyProviderFields = ({
"llm-anthropic-api-key",
"llm-openai-api-key",
"llm-openrouter-api-key",
+ "llm-zai-api-key",
] as const);
const apiKeySetting = details[API_KEY_SETTING_BY_PROVIDER[selectedProvider]];
const apiKeyEnvSettingName = apiKeySetting?.is_env_setting
diff --git a/frontend/src/metabase/metabot/components/AIProviderConfigurationForm/utils.ts b/frontend/src/metabase/metabot/components/AIProviderConfigurationForm/utils.ts
index 8ef786cd56d..d9ba5341a28 100644
--- a/frontend/src/metabase/metabot/components/AIProviderConfigurationForm/utils.ts
+++ b/frontend/src/metabase/metabot/components/AIProviderConfigurationForm/utils.ts
@@ -77,6 +77,15 @@ export function getProviderOptions(
addKeyUrl: "https://openrouter.ai/keys",
},
},
+ zai: {
+ value: "zai",
+ label: "Z.AI",
+ apiKey: {
+ // Z.AI keys have no recognizable prefix
+ placeholder: t`Enter your Z.AI API key`,
+ addKeyUrl: "https://z.ai/manage-apikey/apikey-list",
+ },
+ },
};
}
@@ -98,17 +107,22 @@ export function isAvailableProvider(provider: MetabotProvider): boolean {
provider === "bedrock" ||
provider === "metabase" ||
provider === "openai" ||
- provider === "openrouter"
+ provider === "openrouter" ||
+ provider === "zai"
);
}
export const API_KEY_SETTING_BY_PROVIDER: Record<
MetabotApiKeyProvider,
- "llm-anthropic-api-key" | "llm-openai-api-key" | "llm-openrouter-api-key"
+ | "llm-anthropic-api-key"
+ | "llm-openai-api-key"
+ | "llm-openrouter-api-key"
+ | "llm-zai-api-key"
> = {
anthropic: "llm-anthropic-api-key",
openai: "llm-openai-api-key",
openrouter: "llm-openrouter-api-key",
+ zai: "llm-zai-api-key",
};
export const AZURE_MODEL_FAMILIES = [
diff --git a/src/metabase/llm/settings.clj b/src/metabase/llm/settings.clj
index d50a53a17d7..c863b941b1d 100644
--- a/src/metabase/llm/settings.clj
+++ b/src/metabase/llm/settings.clj
@@ -127,6 +127,24 @@
"sk-or-v1-"
(deferred-tru "Invalid OpenRouter API key format. Key must start with ''sk-or-v1-''.")))
+;;; --------------------------------------------------- Z.AI ----------------------------------------------------
+
+(defsetting llm-zai-api-base-url
+ (deferred-tru "The Z.AI API base URL used for Chat Completions.")
+ :encryption :no
+ :visibility :settings-manager
+ :default "https://api.z.ai/api/paas/v4"
+ :export? false)
+
+(defsetting llm-zai-api-key
+ (deferred-tru "The Z.AI API Key.")
+ ;; Z.AI keys are `{id}.{secret}` pairs with no documented prefix, so unlike the other
+ ;; direct-provider keys there is no format validation.
+ :sensitive? true
+ :visibility :settings-manager
+ :export? false
+ :setter (partial set-trimmed-string! :llm-zai-api-key))
+
;;; ----------------------------------------------- Amazon Bedrock ----------------------------------------------
(defsetting llm-bedrock-access-key-id
diff --git a/src/metabase/metabot/api.clj b/src/metabase/metabot/api.clj
index 7be566bad4c..bc4d5edc4ac 100644
--- a/src/metabase/metabot/api.clj
+++ b/src/metabase/metabot/api.clj
@@ -485,7 +485,8 @@
(case provider
"anthropic" :llm-anthropic-api-key
"openai" :llm-openai-api-key
- "openrouter" :llm-openrouter-api-key))
+ "openrouter" :llm-openrouter-api-key
+ "zai" :llm-zai-api-key))
(defn- non-blank-string
[value]
diff --git a/src/metabase/metabot/self.clj b/src/metabase/metabot/self.clj
index 0568e44e9c4..1b6b1f105d1 100644
--- a/src/metabase/metabot/self.clj
+++ b/src/metabase/metabot/self.clj
@@ -20,6 +20,7 @@
[metabase.metabot.self.core :as core]
[metabase.metabot.self.openai :as openai]
[metabase.metabot.self.openrouter :as openrouter]
+ [metabase.metabot.self.zai :as zai]
[metabase.metabot.usage :as usage]
[metabase.util :as u]
[metabase.util.log :as log]
@@ -35,6 +36,7 @@
"bedrock" bedrock/bedrock
"openai" openai/openai
"openrouter" openrouter/openrouter
+ "zai" zai/zai
(throw (ex-info (str "Unknown LLM provider: " provider)
{:provider provider}))))
@@ -46,6 +48,7 @@
"bedrock" bedrock/list-models
"openai" openai/list-models
"openrouter" openrouter/list-models
+ "zai" zai/list-models
(throw (ex-info (str "Unknown LLM provider: " provider)
{:provider provider}))))
diff --git a/src/metabase/metabot/self/openai/chat_completions.clj b/src/metabase/metabot/self/openai/chat_completions.clj
new file mode 100644
index 00000000000..d1f4de03801
--- /dev/null
+++ b/src/metabase/metabot/self/openai/chat_completions.clj
@@ -0,0 +1,248 @@
+(ns metabase.metabot.self.openai.chat-completions
+ "Shared support for OpenAI-compatible Chat Completions (`/chat/completions`) adapters.
+
+ Many providers expose an OpenAI-compatible Chat Completions API, so we include common functions here. The agent loop
+ produces AISDK parts as its canonical message format; this namespace converts those to Chat Completions messages,
+ builds the request body, and translates Chat Completions streaming chunks back into AI SDK v5 protocol chunks.
+
+ Only the generic Chat Completions dialect lives here. Provider-specific concerns belong in the provider adapters,
+ which can post-process the body [[request-body]] returns."
+ (:require
+ [clojure.string :as str]
+ [malli.json-schema :as mjs]
+ [metabase.metabot.self.core :as core]
+ [metabase.metabot.self.schema :as schema]
+ [metabase.util :as u]
+ [metabase.util.json :as json]
+ [metabase.util.malli :as mu]))
+
+(set! *warn-on-reflection* true)
+
+(defn- usage->aisdk-usage
+ "Convert a Chat Completions `usage` block into the AISDK `:usage` shape.
+
+ `prompt_tokens` is the total input count, and the cache buckets are a subset
+ breakdown of it under `prompt_tokens_details`:
+
+ cached_tokens — input tokens read from the provider cache
+ cache_write_tokens — input tokens written to the provider cache;
+ undocumented but reported by both OpenRouter
+ (Anthropic models) and newer OpenAI models.
+ Providers without it (e.g. Z.AI) omit it."
+ [u]
+ (let [details (:prompt_tokens_details u)]
+ {:promptTokens (:prompt_tokens u 0)
+ :completionTokens (:completion_tokens u 0)
+ :cacheCreationTokens (or (:cache_write_tokens details) 0)
+ :cacheReadTokens (or (:cached_tokens details) 0)}))
+
+;;; AISDK parts → Chat Completions messages
+
+(defn- merge-consecutive-assistant-messages
+ "Merge consecutive assistant messages.
+
+ Chat Completions allows text + tool_calls on a single assistant message, so
+ when we see a :text part followed by :tool-input parts we fold them together."
+ [messages]
+ (into [] (comp (partition-by :role)
+ (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)]
+ ;; :content should be always there, even if empty/nil
+ [(cond-> {:role "assistant" :content text}
+ (seq tool-calls) (assoc :tool_calls tool-calls))])
+ group))))
+ messages))
+
+(defn parts->cc-messages
+ "Convert a sequence of AISDK parts into Chat Completions messages.
+
+ Input: flat sequence of AISDK parts and user messages:
+ {:role :user, :content \"...\"}
+ {:type :text, :text \"...\"}
+ {:type :tool-input, :id ..., :function ..., :arguments ...}
+ {: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))
+
+;;; Tool definition format
+
+(defn- tool->cc-tool
+ "Convert a tool definition map to Chat Completions tool format.
+ Accepts a ToolEntry map with :tool-name, :doc, :schema, :fn."
+ [{:keys [tool-name doc schema]}]
+ (let [[_:=> [_:cat params] _out] schema
+ params (schema/filter-schema-by-features params)
+ doc (if (str/starts-with? (or doc "") "Inputs: ")
+ (second (str/split doc #"\n\n " 2))
+ doc)]
+ {:type "function"
+ :function {:name tool-name
+ :description doc
+ :parameters (mjs/transform params {:additionalProperties false})}}))
+
+;;; Streaming response → AISDK v5 chunks
+
+(defn chat-completions->aisdk-chunks-xf
+ "Translates Chat Completions streaming chunks into AI SDK v5 protocol chunks.
+
+ Chat Completions streaming format:
+ {\"id\":\"chatcmpl-xxx\",
+ \"object\":\"chat.completion.chunk\",
+ \"model\":\"...\",
+ \"choices\":[{\"index\":0,
+ \"delta\":{\"role\":\"assistant\",\"content\":\"Hello\"},
+ \"finish_reason\":null}],
+ \"usage\":{...}}
+
+ Emits the same internal chunk types as claude.clj and openai.clj:
+ :start, :text-start, :text-delta, :text-end,
+ :tool-input-start, :tool-input-delta, :tool-input-available,
+ :usage
+
+ Chat Completions has no explicit start/stop events per content block like
+ Claude or OpenAI Responses do — we infer transitions from the delta shape.
+ Parallel tool calls arrive with different `index` values; when a new index
+ appears the previous tool is complete."
+ []
+ (fn [rf]
+ (let [current-type (volatile! nil) ;; :text | :function_call | nil
+ current-id (volatile! nil) ;; active chunk id (text-id or tool call_id)
+ message-id (volatile! nil)
+ model-name (volatile! nil)
+ payload (volatile! {}) ;; carried across start/delta/end, same as openai.clj
+ close! (fn [result]
+ (u/prog1 (rf result (merge {:type (case @current-type
+ :text :text-end
+ :function_call :tool-input-available)}
+ @payload))
+ (vreset! current-type nil)
+ (vreset! current-id nil)
+ (vreset! payload {})))]
+ (fn
+ ([result]
+ (cond-> result
+ @current-type (close!)
+ true (rf)))
+
+ ([result {:keys [id model choices usage] :as _chunk}]
+ (let [choice (first choices)
+ delta (:delta choice)
+ finish-reason (:finish_reason choice)
+ tool-call (first (:tool_calls 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
+ (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.
+ chunk-id (or (:id tool-call) @current-id (core/mkid))]
+ (cond-> result
+ ;; Emit :start on first chunk
+ (and id (not @message-id)) (-> (rf {:type :start :messageId id})
+ (u/prog1
+ (vreset! message-id id)
+ (vreset! model-name model)))
+ ;; Close previous block when type changes, or when a new tool
+ ;; call arrives (different id = different tool in parallel)
+ (and @current-type
+ (or (and chunk-type
+ (not= chunk-type @current-type))
+ (and (= chunk-type :function_call)
+ (not= chunk-id @current-id)))) (close!)
+ ;; Start a new text block
+ (and (= chunk-type :text)
+ (not= @current-type :text)) (-> (u/prog1
+ (let [tid (core/mkid)]
+ (vreset! current-type :text)
+ (vreset! current-id tid)
+ (vreset! payload {:id tid})))
+ (rf (merge {:type :text-start} @payload)))
+ ;; Text delta
+ (and (= chunk-type :text)
+ (some? (:content delta))) (rf {:type :text-delta
+ :id @current-id
+ :delta (:content delta)})
+ ;; Start a new tool call block
+ (and (= chunk-type :function_call)
+ (:id tool-call)
+ (:name (:function tool-call))) (-> (u/prog1
+ (vreset! current-type :function_call)
+ (vreset! current-id (:id tool-call))
+ (vreset! payload {:toolCallId (:id tool-call)
+ :toolName (:name (:function tool-call))}))
+ (rf (merge {:type :tool-input-start} @payload))
+ ;; Emit initial arguments if present
+ (cond-> (not (str/blank? (:arguments (:function tool-call))))
+ (rf {:type :tool-input-delta
+ :toolCallId (:id tool-call)
+ :inputTextDelta (:arguments (:function tool-call))})))
+ ;; Tool argument delta (continuation of existing tool call)
+ (and (= chunk-type :function_call)
+ (not (:id tool-call))
+ (some? (:arguments (:function tool-call)))) (rf {:type :tool-input-delta
+ :toolCallId (:toolCallId @payload)
+ :inputTextDelta (:arguments (:function tool-call))})
+ ;; Finish reason — close whatever is open
+ (some? finish-reason) (cond->
+ @current-type (close!))
+ ;; Usage (often on a separate final chunk with empty choices)
+ (some? usage) (rf {:type :usage
+ :usage (usage->aisdk-usage usage)
+ :id @message-id
+ :model @model-name}))))))))
+
+;;; 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))))
diff --git a/src/metabase/metabot/self/openrouter.clj b/src/metabase/metabot/self/openrouter.clj
index a186d93ae49..44f6304bc13 100644
--- a/src/metabase/metabot/self/openrouter.clj
+++ b/src/metabase/metabot/self/openrouter.clj
@@ -9,13 +9,11 @@
adapter converts those directly to Chat Completions messages."
(:require
[clojure.string :as str]
- [malli.json-schema :as mjs]
[metabase.llm.settings :as llm]
[metabase.metabot.self.claude :as claude]
[metabase.metabot.self.core :as core]
[metabase.metabot.self.debug :as debug]
- [metabase.metabot.self.schema :as schema]
- [metabase.util :as u]
+ [metabase.metabot.self.openai.chat-completions :as chat-completions]
[metabase.util.i18n :refer [tru]]
[metabase.util.json :as json]
[metabase.util.log :as log]
@@ -24,96 +22,6 @@
(set! *warn-on-reflection* true)
-(defn- openrouter-usage->aisdk-usage
- "Convert an OpenRouter Chat Completions `usage` block into the AISDK `:usage` shape.
-
- OpenRouter normalizes usage to the OpenAI shape regardless of the upstream
- provider: `prompt_tokens` is the total input count, and the cache buckets are
- a subset breakdown of it under `prompt_tokens_details`:
-
- cached_tokens — input tokens read from the provider cache
- cache_write_tokens — input tokens written to the provider cache;
- Anthropic models only. OpenAI caching is
- automatic, its writes are free and reported
- as 0 (or omitted entirely)."
- [u]
- (let [details (:prompt_tokens_details u)]
- {:promptTokens (:prompt_tokens u 0)
- :completionTokens (:completion_tokens u 0)
- :cacheCreationTokens (or (:cache_write_tokens details) 0)
- :cacheReadTokens (or (:cached_tokens details) 0)}))
-
-;;; AISDK parts → Chat Completions messages
-
-(defn- merge-consecutive-assistant-messages
- "Merge consecutive assistant messages.
-
- Chat Completions allows text + tool_calls on a single assistant message, so
- when we see a :text part followed by :tool-input parts we fold them together."
- [messages]
- (into [] (comp (partition-by :role)
- (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)]
- ;; :content should be always there, even if empty/nil
- [(cond-> {:role "assistant" :content text}
- (seq tool-calls) (assoc :tool_calls tool-calls))])
- group))))
- messages))
-
-(defn parts->cc-messages
- "Convert a sequence of AISDK parts into Chat Completions messages.
-
- Input: flat sequence of AISDK parts and user messages:
- {:role :user, :content \"...\"}
- {:type :text, :text \"...\"}
- {:type :tool-input, :id ..., :function ..., :arguments ...}
- {: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))
-
-;;; Tool definition format
-
-(defn- tool->openai-chat
- "Convert a tool definition map to Chat Completions tool format.
- Accepts a ToolEntry map with :tool-name, :doc, :schema, :fn."
- [{:keys [tool-name doc schema]}]
- (let [[_:=> [_:cat params] _out] schema
- params (schema/filter-schema-by-features params)
- doc (if (str/starts-with? (or doc "") "Inputs: ")
- (second (str/split doc #"\n\n " 2))
- doc)]
- {:type "function"
- :function {:name tool-name
- :description doc
- :parameters (mjs/transform params {:additionalProperties false})}}))
-
(defn- ai-proxy-unsupported-ex []
(ex-info (tru "AI proxy is not supported for OpenRouter")
{:api-error true
@@ -207,115 +115,10 @@
(defn openrouter->aisdk-chunks-xf
"Translates Chat Completions streaming chunks into AI SDK v5 protocol chunks.
-
- Chat Completions streaming format:
- {\"id\":\"chatcmpl-xxx\",
- \"object\":\"chat.completion.chunk\",
- \"model\":\"...\",
- \"choices\":[{\"index\":0,
- \"delta\":{\"role\":\"assistant\",\"content\":\"Hello\"},
- \"finish_reason\":null}],
- \"usage\":{...}}
-
- Emits the same internal chunk types as claude.clj and openai.clj:
- :start, :text-start, :text-delta, :text-end,
- :tool-input-start, :tool-input-delta, :tool-input-available,
- :usage
-
- Chat Completions has no explicit start/stop events per content block like
- Claude or OpenAI Responses do — we infer transitions from the delta shape.
- Parallel tool calls arrive with different `index` values; when a new index
- appears the previous tool is complete."
+ OpenRouter streams the generic Chat Completions dialect; see
+ [[chat-completions/chat-completions->aisdk-chunks-xf]]."
[]
- (fn [rf]
- (let [current-type (volatile! nil) ;; :text | :function_call | nil
- current-id (volatile! nil) ;; active chunk id (text-id or tool call_id)
- message-id (volatile! nil)
- model-name (volatile! nil)
- payload (volatile! {}) ;; carried across start/delta/end, same as openai.clj
- close! (fn [result]
- (u/prog1 (rf result (merge {:type (case @current-type
- :text :text-end
- :function_call :tool-input-available)}
- @payload))
- (vreset! current-type nil)
- (vreset! current-id nil)
- (vreset! payload {})))]
- (fn
- ([result]
- (cond-> result
- @current-type (close!)
- true (rf)))
-
- ([result {:keys [id model choices usage] :as _chunk}]
- (let [choice (first choices)
- delta (:delta choice)
- finish-reason (:finish_reason choice)
- tool-call (first (:tool_calls 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
- (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.
- chunk-id (or (:id tool-call) @current-id (core/mkid))]
- (cond-> result
- ;; Emit :start on first chunk
- (and id (not @message-id)) (-> (rf {:type :start :messageId id})
- (u/prog1
- (vreset! message-id id)
- (vreset! model-name model)))
- ;; Close previous block when type changes, or when a new tool
- ;; call arrives (different id = different tool in parallel)
- (and @current-type
- (or (and chunk-type
- (not= chunk-type @current-type))
- (and (= chunk-type :function_call)
- (not= chunk-id @current-id)))) (close!)
- ;; Start a new text block
- (and (= chunk-type :text)
- (not= @current-type :text)) (-> (u/prog1
- (let [tid (core/mkid)]
- (vreset! current-type :text)
- (vreset! current-id tid)
- (vreset! payload {:id tid})))
- (rf (merge {:type :text-start} @payload)))
- ;; Text delta
- (and (= chunk-type :text)
- (some? (:content delta))) (rf {:type :text-delta
- :id @current-id
- :delta (:content delta)})
- ;; Start a new tool call block
- (and (= chunk-type :function_call)
- (:id tool-call)
- (:name (:function tool-call))) (-> (u/prog1
- (vreset! current-type :function_call)
- (vreset! current-id (:id tool-call))
- (vreset! payload {:toolCallId (:id tool-call)
- :toolName (:name (:function tool-call))}))
- (rf (merge {:type :tool-input-start} @payload))
- ;; Emit initial arguments if present
- (cond-> (not (str/blank? (:arguments (:function tool-call))))
- (rf {:type :tool-input-delta
- :toolCallId (:id tool-call)
- :inputTextDelta (:arguments (:function tool-call))})))
- ;; Tool argument delta (continuation of existing tool call)
- (and (= chunk-type :function_call)
- (not (:id tool-call))
- (some? (:arguments (:function tool-call)))) (rf {:type :tool-input-delta
- :toolCallId (:toolCallId @payload)
- :inputTextDelta (:arguments (:function tool-call))})
- ;; Finish reason — close whatever is open
- (some? finish-reason) (cond->
- @current-type (close!))
- ;; Usage (often on a separate final chunk with empty choices)
- (some? usage) (rf {:type :usage
- :usage (openrouter-usage->aisdk-usage usage)
- :id @message-id
- :model @model-name}))))))))
+ (chat-completions/chat-completions->aisdk-chunks-xf))
;;; HTTP request
@@ -324,48 +127,20 @@
[model]
(str/starts-with? (str model) "anthropic/"))
-(defn- system->cc-message
- "Build the Chat Completions system message for `system`.
-
- Anthropic models get explicit prompt-cache breakpoints: the content becomes
- Anthropic-style text blocks with `cache_control` markers (see
- [[claude/system->cached-content-blocks]]), which OpenRouter passes through to
- Anthropic unchanged. Anthropic's cache prefix orders tools before system, so a
- breakpoint on the system blocks caches the tool definitions too; OpenRouter
- doesn't document `cache_control` on tool definitions, so unlike claude.clj we
- don't put a separate breakpoint there.
+(mu/defn openrouter-request-body
+ "Build the Chat Completions request body for an LLM request.
- Other models (OpenAI) get a plain string system message: OpenAI prompt caching
- is automatic server-side and takes no request markup."
- [system model]
- {:role "system"
- :content (cond-> system
- (anthropic-model? model) claude/system->cached-content-blocks)})
+ Delegates to the shared [[chat-completions/request-body]]. Anthropic models get explicit prompt-cache breakpoints
+ [[claude/system->cached-content-blocks]]. OpenRouter doesn't document `cache_control` on tool definitions, so
+ unlike claude.clj we don't put a separate breakpoint there.
-(mu/defn openrouter-request-body
- "Build the Chat Completions request body for an LLM request."
- [{:keys [model system input tools temperature max-tokens tool_choice schema]
+ Other models (OpenAI) keep the generic plain string system message: OpenAI prompt caching is automatic server-side
+ and takes no request markup."
+ [{:keys [model system] :as opts
:or {model "anthropic/claude-haiku-4.5"}} :- core/LLMRequestOpts]
- (let [messages (cond-> (parts->cc-messages input)
- system (as-> msgs (into [(system->cc-message system model)] 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->openai-chat 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))))
+ (cond-> (chat-completions/request-body (assoc opts :model model))
+ (and system (anthropic-model? model))
+ (update-in [:messages 0 :content] claude/system->cached-content-blocks)))
(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
new file mode 100644
index 00000000000..cafcfdbc7bf
--- /dev/null
+++ b/src/metabase/metabot/self/zai.clj
@@ -0,0 +1,137 @@
+(ns metabase.metabot.self.zai
+ "Z.AI (GLM) / Chat Completions adapter.
+
+ Z.AI exposes an OpenAI-compatible Chat Completions API.
+
+ https://docs.z.ai/api-reference/llm/chat-completion"
+ (:require
+ [metabase.llm.settings :as llm]
+ [metabase.metabot.self.core :as core]
+ [metabase.metabot.self.debug :as debug]
+ [metabase.metabot.self.openai.chat-completions :as chat-completions]
+ [metabase.util.i18n :refer [tru]]
+ [metabase.util.json :as json]
+ [metabase.util.log :as log]
+ [metabase.util.malli :as mu]
+ [metabase.util.o11y :refer [with-span]]))
+
+(set! *warn-on-reflection* true)
+
+(def ^:private default-model "glm-5.2")
+
+(defn- ai-proxy-unsupported-ex []
+ (ex-info (tru "AI proxy is not supported for Z.AI")
+ {:api-error true
+ :error-code :proxy-unsupported}))
+
+(defn- zai-error-msg
+ "Canonical, status-specific Z.AI error message."
+ [res]
+ (let [status (long (:status res 0))]
+ (case status
+ 401 (tru "Z.AI API key expired or invalid")
+ 404 (tru "Z.AI API endpoint was not found — check the base URL")
+ 429 (tru "Z.AI has rate limited us")
+ 500 (tru "Z.AI returned an internal server error")
+ (tru "Z.AI API error (HTTP {0})" status))))
+
+(def ^:private supported-models
+ "Z.AI models offered in the Metabot model picker, as a map of model id -> display name.
+ `list-models` returns the intersection of this map with the `/models` catalog."
+ {"glm-5.2" "GLM-5.2"})
+
+(defn- supported-model?
+ "Whether a `/models` catalog entry is one of the [[supported-models]]."
+ [{:keys [id]}]
+ (contains? supported-models id))
+
+(defn- list-all-models
+ "Fetch the full Z.AI model catalog (`GET /models`).
+
+ The endpoint is OpenAI-compatible but undocumented; it doubles as the credential
+ round-trip behind the admin Connect button (auth is checked before routing, so a 2xx
+ proves the key and base URL reach an authenticated surface).
+ `:ai-proxy?` is not supported for Z.AI and throws when true."
+ [{:keys [credentials ai-proxy?]}]
+ (when ai-proxy?
+ (throw (ai-proxy-unsupported-ex)))
+ (try
+ (let [auth (core/resolve-auth "zai" "Z.AI"
+ (when-let [k (or (not-empty (:api-key credentials))
+ (not-empty (llm/llm-zai-api-key)))]
+ {:url (llm/llm-zai-api-base-url)
+ :headers {"Authorization" (str "Bearer " k)}})
+ ai-proxy?)
+ res (core/request auth {:method :get
+ :url "/models"
+ :as :json
+ :headers {"Content-Type" "application/json"}})]
+ (get-in res [:body :data]))
+ (catch Exception e
+ (core/rethrow-api-error! "zai" zai-error-msg e))))
+
+(defn list-models
+ "List the Z.AI models supported by this adapter (see [[supported-models]]).
+ `:ai-proxy?` is not supported for Z.AI and throws when true."
+ ([] (list-models {}))
+ ([opts]
+ {:models (->> (list-all-models opts)
+ (filter supported-model?)
+ (sort-by :id)
+ (mapv (fn [{:keys [id] :as model}]
+ {:id id :display_name (or (:name model) (supported-models id))})))}))
+
+(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)))
+
+(mu/defn zai-raw
+ "Perform a streaming request to the Z.AI Chat Completions API.
+ `:ai-proxy?` is not supported for Z.AI and throws when true."
+ [{:keys [model tools ai-proxy?] :as opts
+ :or {model default-model}} :- core/LLMRequestOpts]
+ (when ai-proxy?
+ (throw (ai-proxy-unsupported-ex)))
+ (let [req (zai-request-body (assoc opts :model model))]
+ (log/debug "Z.AI request" {:model model :msg-count (count (:messages req)) :tools (count (or tools []))})
+ (with-span :info {:name :metabot.zai/request
+ :model model
+ :msg-count (count (:messages req))
+ :tool-count (count (or tools []))}
+ (try
+ (let [api-key (not-empty (llm/llm-zai-api-key))
+ auth (core/resolve-auth "zai" "Z.AI"
+ (when api-key
+ {:url (llm/llm-zai-api-base-url)
+ :headers {"Authorization" (str "Bearer " api-key)}})
+ ai-proxy?)
+ response (core/request auth
+ {:method :post
+ :url "/chat/completions"
+ :as :stream
+ :headers {"Content-Type" "application/json"}
+ :body (json/encode req)})]
+ (-> (core/sse-reducible (:body response))
+ (debug/capture-stream {:provider "zai"
+ :model model
+ :url "/chat/completions"
+ :request req})))
+ (catch Exception e
+ (core/rethrow-api-error! "zai" zai-error-msg e))))))
+
+(defn zai->aisdk-chunks-xf
+ "Translates Z.AI Chat Completions streaming chunks into AI SDK v5 protocol chunks."
+ []
+ (chat-completions/chat-completions->aisdk-chunks-xf))
+
+(defn zai
+ "Call the Z.AI Chat Completions API, return AISDK stream."
+ [& args]
+ (let [raw (apply zai-raw args)]
+ (eduction (zai->aisdk-chunks-xf) raw)))
diff --git a/src/metabase/metabot/settings.clj b/src/metabase/metabot/settings.clj
index 268f8d0a3ae..e6c17109de5 100644
--- a/src/metabase/metabot/settings.clj
+++ b/src/metabase/metabot/settings.clj
@@ -106,7 +106,7 @@
(def ^:private direct-providers
"Providers that can be used directly (not via the metabase/ proxy prefix)."
- #{"anthropic" "azure" "bedrock" "openai" "openrouter"})
+ #{"anthropic" "azure" "bedrock" "openai" "openrouter" "zai"})
(def ^:private default-anthropic-llm-metabot-model
"Default Anthropic model used for Metabot when no explicit model is selected."
@@ -126,6 +126,10 @@
unlike the Anthropic API's hyphenated IDs (`claude-sonnet-4-6`)."
"anthropic/claude-sonnet-4.6")
+(def ^:private default-zai-llm-metabot-model
+ "Default Z.AI model used for Metabot when no explicit model is selected."
+ "glm-5.2")
+
(def default-llm-metabot-provider
"Default provider/model used for Metabot when no explicit model is selected."
(str "anthropic/" default-anthropic-llm-metabot-model))
@@ -139,6 +143,7 @@
"bedrock" default-bedrock-llm-metabot-model
"openai" default-openai-llm-metabot-model
"openrouter" default-openrouter-llm-metabot-model
+ "zai" default-zai-llm-metabot-model
provider-util/metabase-provider-prefix default-llm-metabot-provider})
(def default-metabase-llm-metabot-provider
@@ -302,6 +307,7 @@
:region (non-blank (llm.settings/llm-bedrock-region))})
"openai" (configured-api-key-credentials (llm.settings/llm-openai-api-key))
"openrouter" (configured-api-key-credentials (llm.settings/llm-openrouter-api-key))
+ "zai" (configured-api-key-credentials (llm.settings/llm-zai-api-key))
nil))
(defn provider-credentials-complete?
diff --git a/test/metabase/metabot/api_test.clj b/test/metabase/metabot/api_test.clj
index 638b99e3908..8fcc3fca63a 100644
--- a/test/metabase/metabot/api_test.clj
+++ b/test/metabase/metabot/api_test.clj
@@ -546,6 +546,31 @@
(is (= "sk-or-v1-fresh"
(llm.settings/llm-openrouter-api-key)))))))
+(deftest settings-put-connect-zai-defaults-model-test
+ (testing "connecting zai with only an api-key switches to the default zai model"
+ (mt/with-temporary-setting-values [metabot.settings/llm-metabot-provider "anthropic/claude-haiku-4-5"
+ llm.settings/llm-zai-api-key nil]
+ (mt/with-dynamic-fn-redefs [metabot.self/list-models (fn
+ ([provider]
+ (is (= "zai" provider))
+ {:models [{:id "glm-5.2"
+ :display_name "GLM-5.2"}]})
+ ([provider {:keys [credentials]}]
+ (is (= "zai" provider))
+ (is (= {:api-key "zai-key.fresh"} credentials))
+ {:models [{:id "glm-5.2"
+ :display_name "GLM-5.2"}]}))]
+ (is (= {:value "zai/glm-5.2"
+ :models [{:id "glm-5.2"
+ :display_name "GLM-5.2"}]}
+ (mt/user-http-request :crowberto :put 200 "metabot/settings"
+ {:provider "zai"
+ :api-key "zai-key.fresh"})))
+ (is (= "zai/glm-5.2"
+ (metabot.settings/llm-metabot-provider)))
+ (is (= "zai-key.fresh"
+ (llm.settings/llm-zai-api-key)))))))
+
(deftest settings-put-updates-metabase-provider-without-api-key-test
(mt/with-temporary-setting-values [metabot.settings/llm-metabot-provider "anthropic/claude-haiku-4-5"]
(mt/with-dynamic-fn-redefs [metabot.self/list-models (fn
diff --git a/test/metabase/metabot/self/openai/chat_completions_test.clj b/test/metabase/metabot/self/openai/chat_completions_test.clj
new file mode 100644
index 00000000000..0802644b144
--- /dev/null
+++ b/test/metabase/metabot/self/openai/chat_completions_test.clj
@@ -0,0 +1,151 @@
+(ns metabase.metabot.self.openai.chat-completions-test
+ (:require
+ [clojure.test :refer :all]
+ [metabase.metabot.self.openai.chat-completions :as chat-completions]
+ [metabase.metabot.test-util :as metabot.tu]))
+
+(set! *warn-on-reflection* true)
+
+;;; ──────────────────────────────────────────────────────────────────
+;;; parts->cc-messages tests
+;;; ──────────────────────────────────────────────────────────────────
+
+(deftest ^:parallel parts->cc-messages-plain-text-test
+ (testing "plain user and assistant text"
+ (is (=? [{:role "user" :content "Hello"}
+ {:role "assistant" :content "Hi there!"}]
+ (chat-completions/parts->cc-messages
+ [{:role :user :content "Hello"}
+ {:type :text :text "Hi there!"}])))))
+
+(deftest ^:parallel parts->cc-messages-drops-reasoning-test
+ (testing "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
+ [{:role :user :content "Hello"}
+ {:type :reasoning :id "r1" :text "thinking"}
+ {:type :reasoning :id "r1" :text "" :provider-metadata {:anthropic {:signature "abc"}}}
+ {:type :text :text "Hi there!"}])))))
+
+(deftest ^:parallel parts->cc-messages-tool-call-test
+ (testing "text + tool call merges into single assistant message"
+ (is (=? [{:role "assistant"
+ :content "Let me check..."
+ :tool_calls [{:id "call-1"
+ :type "function"
+ :function {:name "search"}}]}]
+ (chat-completions/parts->cc-messages
+ [{:type :text :text "Let me check..."}
+ {:type :tool-input :id "call-1" :function "search" :arguments {:query "revenue"}}])))))
+
+(deftest ^:parallel parts->cc-messages-tool-call-only-test
+ (testing "tool call without preceding text"
+ (is (=? [{:role "assistant"
+ :content nil
+ :tool_calls [{:id "call-1"}]}]
+ (chat-completions/parts->cc-messages
+ [{:type :tool-input :id "call-1" :function "search" :arguments {:query "revenue"}}])))))
+
+(deftest ^:parallel parts->cc-messages-tool-result-test
+ (testing "tool output becomes tool role message"
+ (is (=? [{:role "tool"
+ :tool_call_id "call-1"
+ :content "Found 42 results"}]
+ (chat-completions/parts->cc-messages
+ [{:type :tool-output :id "call-1" :result {:output "Found 42 results"}}])))))
+
+(deftest ^:parallel parts->cc-messages-multiple-tool-results-test
+ (testing "multiple tool outputs become separate tool messages"
+ (is (=? [{:role "tool" :tool_call_id "call-1" :content "Result 1"}
+ {:role "tool" :tool_call_id "call-2" :content "Result 2"}]
+ (chat-completions/parts->cc-messages
+ [{:type :tool-output :id "call-1" :result {:output "Result 1"}}
+ {:type :tool-output :id "call-2" :result {:output "Result 2"}}])))))
+
+(deftest ^:parallel parts->cc-messages-nil-arguments-test
+ (testing "tool call with nil arguments defaults to empty object JSON string"
+ (is (=? [{:role "assistant"
+ :content nil
+ :tool_calls [{:id "call-1"
+ :type "function"
+ :function {:name "todo_read"
+ :arguments "{}"}}]}]
+ (chat-completions/parts->cc-messages
+ [{:type :tool-input :id "call-1" :function "todo_read" :arguments nil}])))))
+
+(deftest ^:parallel parts->cc-messages-full-conversation-test
+ (testing "full conversation with tool round-trip"
+ (is (=? [{:role "user" :content "What time is it in Kyiv?"}
+ {:role "assistant" :tool_calls [{:id "call-1" :function {:name "get-time"}}]}
+ {:role "tool" :tool_call_id "call-1" :content "2025-02-13T14:00:00+02:00"}
+ {:role "assistant" :content "It's 2:00 PM in Kyiv."}]
+ (chat-completions/parts->cc-messages
+ [{:role :user :content "What time is it in Kyiv?"}
+ {:type :tool-input :id "call-1" :function "get-time" :arguments {:tz "Europe/Kyiv"}}
+ {:type :tool-output :id "call-1" :result {:output "2025-02-13T14:00:00+02:00"}}
+ {:type :text :text "It's 2:00 PM in Kyiv."}])))))
+
+;;; ──────────────────────────────────────────────────────────────────
+;;; request-body tests
+;;; ──────────────────────────────────────────────────────────────────
+
+(deftest ^:parallel request-body-system-plain-string-test
+ (testing "the generic dialect keeps the system prompt a plain string"
+ (let [body (chat-completions/request-body
+ {:model "some/model"
+ :system "You are a helpful assistant."
+ :input [{:role :user :content "hi"}]})]
+ (is (= {:role "system" :content "You are a helpful assistant."}
+ (-> body :messages first))))))
+
+(deftest ^:parallel request-body-no-system-message-test
+ (testing "no system message is added when system is not provided"
+ (let [body (chat-completions/request-body
+ {:model "some/model"
+ :input [{:role :user :content "hi"}]})]
+ (is (= ["user"] (map :role (:messages body)))))))
+
+(deftest ^:parallel request-body-streaming-usage-test
+ (testing "requests stream and ask for usage in the final chunk"
+ (is (=? {:stream true
+ :stream_options {:include_usage true}}
+ (chat-completions/request-body {:model "some/model"
+ :input [{:role :user :content "hi"}]})))))
+
+(deftest ^:parallel request-body-tools-test
+ (testing "tools are sent in OpenAI function format with tool_choice auto"
+ (is (=? {:tools [{:type "function"
+ :function {:name "get-time"}}]
+ :tool_choice "auto"}
+ (chat-completions/request-body {:model "some/model"
+ :input [{:role :user :content "hi"}]
+ :tools [(metabot.tu/get-time-tool)]})))))
+
+(deftest ^:parallel request-body-tool-choice-passthrough-test
+ (testing "an explicit tool_choice passes through when tools are present"
+ (is (=? {:tool_choice "required"}
+ (chat-completions/request-body {:model "some/model"
+ :input [{:role :user :content "hi"}]
+ :tools [(metabot.tu/get-time-tool)]
+ :tool_choice "required"})))))
+
+(deftest ^:parallel request-body-schema-forces-structured-output-test
+ (testing "a schema forces a structured_output tool call"
+ (is (=? {:tools [{:type "function"
+ :function {:name "structured_output"
+ :parameters {:type "object"}}}]
+ :tool_choice "required"}
+ (chat-completions/request-body {:model "some/model"
+ :input [{:role :user :content "hi"}]
+ :schema {:type "object"
+ :properties {:title {:type "string"}}}})))))
+
+(deftest ^:parallel request-body-temperature-and-max-tokens-test
+ (testing "temperature and max-tokens pass through"
+ (is (=? {:temperature 0.2
+ :max_tokens 128}
+ (chat-completions/request-body {:model "some/model"
+ :input [{:role :user :content "hi"}]
+ :temperature 0.2
+ :max-tokens 128})))))
diff --git a/test/metabase/metabot/self/openrouter_test.clj b/test/metabase/metabot/self/openrouter_test.clj
index cb0b8857722..2d9baae6ced 100644
--- a/test/metabase/metabot/self/openrouter_test.clj
+++ b/test/metabase/metabot/self/openrouter_test.clj
@@ -18,86 +18,6 @@
[fixture-name opts]
(metabot.tu/raw-fixture fixture-name #(openrouter/openrouter-raw (merge {:model "anthropic/claude-haiku-4-5"} opts))))
-;;; ──────────────────────────────────────────────────────────────────
-;;; parts->cc-messages tests
-;;; ──────────────────────────────────────────────────────────────────
-
-(deftest ^:parallel parts->cc-messages-plain-text-test
- (testing "plain user and assistant text"
- (is (=? [{:role "user" :content "Hello"}
- {:role "assistant" :content "Hi there!"}]
- (openrouter/parts->cc-messages
- [{:role :user :content "Hello"}
- {:type :text :text "Hi there!"}])))))
-
-(deftest ^:parallel parts->cc-messages-drops-reasoning-test
- (testing "reasoning parts are dropped, not turned into empty user messages"
- (is (=? [{:role "user" :content "Hello"}
- {:role "assistant" :content "Hi there!"}]
- (openrouter/parts->cc-messages
- [{:role :user :content "Hello"}
- {:type :reasoning :id "r1" :text "thinking"}
- {:type :reasoning :id "r1" :text "" :provider-metadata {:anthropic {:signature "abc"}}}
- {:type :text :text "Hi there!"}])))))
-
-(deftest ^:parallel parts->cc-messages-tool-call-test
- (testing "text + tool call merges into single assistant message"
- (is (=? [{:role "assistant"
- :content "Let me check..."
- :tool_calls [{:id "call-1"
- :type "function"
- :function {:name "search"}}]}]
- (openrouter/parts->cc-messages
- [{:type :text :text "Let me check..."}
- {:type :tool-input :id "call-1" :function "search" :arguments {:query "revenue"}}])))))
-
-(deftest ^:parallel parts->cc-messages-tool-call-only-test
- (testing "tool call without preceding text"
- (is (=? [{:role "assistant"
- :content nil
- :tool_calls [{:id "call-1"}]}]
- (openrouter/parts->cc-messages
- [{:type :tool-input :id "call-1" :function "search" :arguments {:query "revenue"}}])))))
-
-(deftest ^:parallel parts->cc-messages-tool-result-test
- (testing "tool output becomes tool role message"
- (is (=? [{:role "tool"
- :tool_call_id "call-1"
- :content "Found 42 results"}]
- (openrouter/parts->cc-messages
- [{:type :tool-output :id "call-1" :result {:output "Found 42 results"}}])))))
-
-(deftest ^:parallel parts->cc-messages-multiple-tool-results-test
- (testing "multiple tool outputs become separate tool messages"
- (is (=? [{:role "tool" :tool_call_id "call-1" :content "Result 1"}
- {:role "tool" :tool_call_id "call-2" :content "Result 2"}]
- (openrouter/parts->cc-messages
- [{:type :tool-output :id "call-1" :result {:output "Result 1"}}
- {:type :tool-output :id "call-2" :result {:output "Result 2"}}])))))
-
-(deftest ^:parallel parts->cc-messages-nil-arguments-test
- (testing "tool call with nil arguments defaults to empty object JSON string"
- (is (=? [{:role "assistant"
- :content nil
- :tool_calls [{:id "call-1"
- :type "function"
- :function {:name "todo_read"
- :arguments "{}"}}]}]
- (openrouter/parts->cc-messages
- [{:type :tool-input :id "call-1" :function "todo_read" :arguments nil}])))))
-
-(deftest ^:parallel parts->cc-messages-full-conversation-test
- (testing "full conversation with tool round-trip"
- (is (=? [{:role "user" :content "What time is it in Kyiv?"}
- {:role "assistant" :tool_calls [{:id "call-1" :function {:name "get-time"}}]}
- {:role "tool" :tool_call_id "call-1" :content "2025-02-13T14:00:00+02:00"}
- {:role "assistant" :content "It's 2:00 PM in Kyiv."}]
- (openrouter/parts->cc-messages
- [{:role :user :content "What time is it in Kyiv?"}
- {:type :tool-input :id "call-1" :function "get-time" :arguments {:tz "Europe/Kyiv"}}
- {:type :tool-output :id "call-1" :result {:output "2025-02-13T14:00:00+02:00"}}
- {:type :text :text "It's 2:00 PM in Kyiv."}])))))
-
;;; ──────────────────────────────────────────────────────────────────
;;; openrouter-request-body prompt-caching tests
;;; ──────────────────────────────────────────────────────────────────
diff --git a/test/metabase/metabot/self/zai_test.clj b/test/metabase/metabot/self/zai_test.clj
new file mode 100644
index 00000000000..31bc0fb11e9
--- /dev/null
+++ b/test/metabase/metabot/self/zai_test.clj
@@ -0,0 +1,291 @@
+(ns metabase.metabot.self.zai-test
+ (:require
+ [clj-http.client :as http]
+ [clojure.test :refer :all]
+ [medley.core :as m]
+ [metabase.llm.settings :as llm.settings]
+ [metabase.metabot.self.core :as self.core]
+ [metabase.metabot.self.debug :as debug]
+ [metabase.metabot.self.zai :as zai]
+ [metabase.metabot.test-util :as metabot.tu]
+ [metabase.premium-features.core :as premium-features]
+ [metabase.test :as mt]))
+
+(set! *warn-on-reflection* true)
+
+;;; ──────────────────────────────────────────────────────────────────
+;;; zai-request-body tests
+;;; ──────────────────────────────────────────────────────────────────
+
+(deftest ^:parallel request-body-default-model-test
+ (testing "the model defaults to glm-5.2"
+ (is (= "glm-5.2"
+ (:model (zai/zai-request-body {:input [{:role :user :content "hi"}]}))))))
+
+(deftest ^:parallel request-body-system-plain-string-test
+ (testing "the system prompt stays a plain string (Z.AI prompt caching is automatic server-side)"
+ (let [body (zai/zai-request-body
+ {:model "glm-5.2"
+ :system "You are a helpful assistant."
+ :input [{:role :user :content "hi"}]})]
+ (is (= {:role "system" :content "You are a helpful assistant."}
+ (-> body :messages first))))))
+
+(deftest ^:parallel request-body-streaming-usage-test
+ (testing "requests stream and ask for usage in the final chunk"
+ (is (=? {:stream true
+ :stream_options {:include_usage true}}
+ (zai/zai-request-body {:model "glm-5.2"
+ :input [{:role :user :content "hi"}]})))))
+
+(deftest ^:parallel request-body-tools-test
+ (testing "tools are sent in OpenAI function format with tool_choice auto"
+ (is (=? {:tools [{:type "function"
+ :function {:name "get-time"}}]
+ :tool_choice "auto"}
+ (zai/zai-request-body {:model "glm-5.2"
+ :input [{:role :user :content "hi"}]
+ :tools [(metabot.tu/get-time-tool)]})))))
+
+(deftest ^:parallel request-body-schema-forces-structured-output-test
+ (testing "a schema forces a structured_output tool call"
+ (is (=? {:tools [{:type "function"
+ :function {:name "structured_output"
+ :parameters {:type "object"}}}]
+ :tool_choice "required"}
+ (zai/zai-request-body {:model "glm-5.2"
+ :input [{:role :user :content "hi"}]
+ :schema {:type "object"
+ :properties {:title {:type "string"}}}})))))
+
+(deftest ^:parallel request-body-temperature-and-max-tokens-test
+ (testing "temperature and max-tokens pass through"
+ (is (=? {:temperature 0.2
+ :max_tokens 128}
+ (zai/zai-request-body {:model "glm-5.2"
+ :input [{:role :user :content "hi"}]
+ :temperature 0.2
+ :max-tokens 128})))))
+
+;;; ──────────────────────────────────────────────────────────────────
+;;; Streaming chunk conversion tests
+;;;
+;;; Z.AI streams the same Chat Completions chunk dialect the adapter shares
+;;; with OpenRouter; these chunks are synthetic but mirror the shapes Z.AI
+;;; sends: reasoning deltas (`delta.reasoning_content`) when thinking mode is
+;;; on, tool calls arriving whole in one delta (`tool_stream` defaults to
+;;; false), and usage on the final chunk alongside `finish_reason`.
+;;; ──────────────────────────────────────────────────────────────────
+
+(deftest ^:parallel zai-text-conv-test
+ (let [chunks [{:id "20260723-1"
+ :model "glm-5.2"
+ :choices [{:delta {:role "assistant" :content "Hello"}}]}
+ {:choices [{:delta {:content " there"}}]}
+ {:choices [{:delta {} :finish_reason "stop"}]
+ :usage {:prompt_tokens 12 :completion_tokens 2 :total_tokens 14}}]]
+ (testing "text streaming chunks are mapped correctly"
+ (is (=? [{:type :start} {:type :text-start} {:type :text-delta} {:type :text-end} {:type :usage}]
+ (into [] (comp (zai/zai->aisdk-chunks-xf) (m/distinct-by :type)) chunks))))
+ (testing "through full pipeline produces text + usage"
+ (is (=? [{:type :start}
+ {:type :text :text "Hello there"}
+ {:type :usage :model "glm-5.2"
+ :usage {:promptTokens 12 :completionTokens 2}}]
+ (into [] (comp (zai/zai->aisdk-chunks-xf)
+ (self.core/aisdk-xf))
+ chunks))))))
+
+(deftest ^:parallel zai-reasoning-deltas-ignored-test
+ (testing "thinking-mode reasoning_content deltas produce no text blocks"
+ (is (=? [{:type :start}
+ {:type :text :text "4"}
+ {:type :usage}]
+ (into [] (comp (zai/zai->aisdk-chunks-xf)
+ (self.core/aisdk-xf))
+ [{:id "20260723-2"
+ :model "glm-5.2"
+ :choices [{:delta {:role "assistant" :reasoning_content "Let me think"}}]}
+ {:choices [{:delta {:reasoning_content " about 2+2."}}]}
+ {:choices [{:delta {:content "4"}}]}
+ {:choices [{:delta {} :finish_reason "stop"}]
+ :usage {:prompt_tokens 8 :completion_tokens 1 :total_tokens 9}}])))))
+
+(deftest ^:parallel zai-whole-tool-call-conv-test
+ (testing "a tool call arriving whole in one delta (tool_stream false) is mapped correctly"
+ (is (=? [{:type :start}
+ {:type :tool-input
+ :id "call_1"
+ :function "get-time"
+ :arguments {:tz "Europe/Kyiv"}}
+ {:type :usage :usage {:promptTokens 20 :completionTokens 5}}]
+ (into [] (comp (zai/zai->aisdk-chunks-xf)
+ (self.core/aisdk-xf))
+ [{:id "20260723-3"
+ :model "glm-5.2"
+ :choices [{:delta {:role "assistant"
+ :tool_calls [{:id "call_1"
+ :type "function"
+ :function {:name "get-time"
+ :arguments "{\"tz\":\"Europe/Kyiv\"}"}}]}}]}
+ {:choices [{:delta {} :finish_reason "tool_calls"}]
+ :usage {:prompt_tokens 20 :completion_tokens 5 :total_tokens 25}}])))))
+
+(deftest ^:parallel zai-streamed-tool-call-conv-test
+ (testing "tool-call argument deltas (tool_stream true) accumulate into one tool-input"
+ (is (=? [{:type :start}
+ {:type :tool-input
+ :id "call_2"
+ :function "get-time"
+ :arguments {:tz "Europe/Kyiv"}}]
+ (into [] (comp (zai/zai->aisdk-chunks-xf)
+ (self.core/aisdk-xf))
+ [{:id "20260723-4"
+ :model "glm-5.2"
+ :choices [{:delta {:role "assistant"
+ :tool_calls [{:id "call_2"
+ :type "function"
+ :function {:name "get-time"
+ :arguments "{\"tz\":"}}]}}]}
+ {:choices [{:delta {:tool_calls [{:function {:arguments "\"Europe/Kyiv\"}"}}]}}]}
+ {:choices [{:delta {} :finish_reason "tool_calls"}]}])))))
+
+(deftest ^:parallel zai-usage-cached-tokens-test
+ (testing "automatic context-cache reads are extracted from prompt_tokens_details; Z.AI reports no cache writes"
+ (let [usage (->> (into [] (zai/zai->aisdk-chunks-xf)
+ [{:id "20260723-5"
+ :model "glm-5.2"
+ :choices [{:delta {:role "assistant" :content "Hi"}}]}
+ {:choices [{:delta {} :finish_reason "stop"}]
+ :usage {:prompt_tokens 5000
+ :completion_tokens 7
+ :total_tokens 5007
+ :prompt_tokens_details {:cached_tokens 4200}}}])
+ (filter #(= :usage (:type %)))
+ first)]
+ (is (=? {:type :usage
+ :id "20260723-5"
+ :model "glm-5.2"
+ :usage {:promptTokens 5000
+ :completionTokens 7
+ :cacheCreationTokens 0
+ :cacheReadTokens 4200}}
+ usage)))))
+
+;;; ──────────────────────────────────────────────────────────────────
+;;; Auth tests
+;;; ──────────────────────────────────────────────────────────────────
+
+(deftest zai-auth-preferences-test
+ (mt/with-premium-features #{:metabase-ai-managed}
+ (mt/with-dynamic-fn-redefs [premium-features/premium-embedding-token (constantly "proxy-token")]
+ (mt/with-temporary-setting-values [llm.settings/llm-zai-api-key "zai-key.byok"
+ llm.settings/llm-proxy-base-url "https://proxy.example"]
+ (testing "Prefers BYOK over ai proxy"
+ (with-redefs [self.core/sse-reducible identity
+ debug/capture-stream (fn [r _] r)
+ http/request (fn [req] {:body req})]
+ (is (=? {:method :post
+ :url "https://api.z.ai/api/paas/v4/chat/completions"
+ :headers {"Authorization" "Bearer zai-key.byok"}
+ :body string?}
+ (zai/zai-raw {:input [{:role :user :content "hi"}]})))))
+ (testing "Does not fall back to ai proxy when BYOK is missing"
+ (mt/with-temporary-setting-values [llm.settings/llm-zai-api-key nil]
+ (is (thrown-with-msg?
+ clojure.lang.ExceptionInfo
+ #"No Z\.AI API key is set"
+ (zai/zai-raw {:input [{:role :user :content "hi"}]})))))
+ (testing "Throws an error if nothing is defined"
+ (mt/with-temporary-setting-values [llm.settings/llm-zai-api-key nil
+ llm.settings/llm-proxy-base-url nil]
+ (is (thrown-with-msg?
+ clojure.lang.ExceptionInfo
+ #"No Z\.AI API key is set"
+ (zai/zai-raw {:input [{:role :user :content "hi"}]})))))))))
+
+(deftest zai-raw-ai-proxy-unsupported-test
+ (testing "ai-proxy? throws before credentials are even consulted"
+ (mt/with-temporary-setting-values [llm.settings/llm-zai-api-key nil]
+ (with-redefs [http/request (fn [_] (throw (ex-info "should never be called" {})))]
+ (is (thrown-with-msg?
+ clojure.lang.ExceptionInfo
+ #"AI proxy is not supported for Z\.AI"
+ (zai/zai-raw {:model "glm-5.2"
+ :input [{:role :user :content "hi"}]
+ :ai-proxy? true})))))))
+
+(deftest list-models-ai-proxy-unsupported-test
+ (testing "ai-proxy? throws before credentials are even consulted"
+ (mt/with-temporary-setting-values [llm.settings/llm-zai-api-key nil]
+ (with-redefs [http/request (fn [_] (throw (ex-info "should never be called" {})))]
+ (is (thrown-with-msg?
+ clojure.lang.ExceptionInfo
+ #"AI proxy is not supported for Z\.AI"
+ (zai/list-models {:ai-proxy? true})))))))
+
+;;; ──────────────────────────────────────────────────────────────────
+;;; list-models tests
+;;; ──────────────────────────────────────────────────────────────────
+
+(deftest list-models-filters-catalog-to-whitelist-test
+ (testing "list-models keeps only whitelisted models, falling back to the whitelist display name"
+ (mt/with-temporary-setting-values [llm.settings/llm-zai-api-key "zai-key.test"]
+ (mt/with-dynamic-fn-redefs [http/request (fn [req]
+ (is (=? {:method :get
+ :url "https://api.z.ai/api/paas/v4/models"
+ :headers {"Authorization" "Bearer zai-key.test"}}
+ req))
+ {:status 200 :body {:data [{:id "glm-4.7"}
+ {:id "glm-5.2"}
+ {:id "some-other-model"}]}})]
+ (is (= {:models [{:id "glm-5.2" :display_name "GLM-5.2"}]}
+ (zai/list-models)))))))
+
+(deftest list-models-prefers-catalog-display-name-test
+ (testing "a display name carried by the catalog entry wins over the whitelist fallback"
+ (mt/with-temporary-setting-values [llm.settings/llm-zai-api-key "zai-key.test"]
+ (mt/with-dynamic-fn-redefs [http/request (fn [_]
+ {:status 200 :body {:data [{:id "glm-5.2" :name "GLM-5.2 (catalog)"}]}})]
+ (is (= {:models [{:id "glm-5.2" :display_name "GLM-5.2 (catalog)"}]}
+ (zai/list-models)))))))
+
+(deftest list-models-explicit-credentials-test
+ (testing "a passed-in api-key is used over the configured key"
+ (mt/with-temporary-setting-values [llm.settings/llm-zai-api-key "zai-key.setting"]
+ (mt/with-dynamic-fn-redefs [http/request (fn [req]
+ (is (=? {:headers {"Authorization" "Bearer zai-key.explicit"}}
+ req))
+ {:status 200 :body {:data []}})]
+ (is (= {:models []}
+ (zai/list-models {:credentials {:api-key "zai-key.explicit"}})))))))
+
+(deftest list-models-blank-credentials-fall-back-to-configured-key-test
+ (testing "a blank passed-in api-key falls back to the configured key"
+ (mt/with-temporary-setting-values [llm.settings/llm-zai-api-key "zai-key.setting"]
+ (mt/with-dynamic-fn-redefs [http/request (fn [req]
+ (is (=? {:headers {"Authorization" "Bearer zai-key.setting"}}
+ req))
+ {:status 200 :body {:data []}})]
+ (is (= {:models []}
+ (zai/list-models {:credentials {:api-key ""}})))))))
+
+(deftest list-models-blank-credentials-without-configured-key-test
+ (testing "throws when the passed-in api-key is blank and no key is configured"
+ (mt/with-temporary-setting-values [llm.settings/llm-zai-api-key nil]
+ (is (thrown-with-msg?
+ clojure.lang.ExceptionInfo
+ #"No Z\.AI API key is set"
+ (zai/list-models {:credentials {:api-key ""}}))))))
+
+(deftest list-models-401-maps-to-invalid-key-message-test
+ (testing "a 401 from Z.AI surfaces as the canonical invalid-key message"
+ (mt/with-temporary-setting-values [llm.settings/llm-zai-api-key "zai-key.expired"]
+ (mt/with-dynamic-fn-redefs [http/request (fn [_]
+ (throw (ex-info "clj-http: status 401"
+ {:status 401
+ :body "{\"error\":{\"code\":\"401\",\"message\":\"token expired or incorrect\"}}"})))]
+ (is (thrown-with-msg?
+ clojure.lang.ExceptionInfo
+ #"Z\.AI API key expired or invalid"
+ (zai/list-models)))))))
diff --git a/test/metabase/metabot/self_test.clj b/test/metabase/metabot/self_test.clj
index b426811c66f..a2b2e6f40f9 100644
--- a/test/metabase/metabot/self_test.clj
+++ b/test/metabase/metabot/self_test.clj
@@ -33,7 +33,9 @@
(is (=? {:provider "openrouter" :model "anthropic/claude-haiku-4-5" :ai-proxy? false}
(#'self/parse-provider-model "openrouter/anthropic/claude-haiku-4-5")))
(is (=? {:provider "openrouter" :model "google/gemini-2.5-flash" :ai-proxy? false}
- (#'self/parse-provider-model "openrouter/google/gemini-2.5-flash"))))
+ (#'self/parse-provider-model "openrouter/google/gemini-2.5-flash")))
+ (is (=? {:provider "zai" :model "glm-5.2" :ai-proxy? false}
+ (#'self/parse-provider-model "zai/glm-5.2"))))
(testing "parses metabase/ prefix (AI proxy)"
(is (=? {:provider "anthropic" :model "claude-haiku-4-5" :ai-proxy? true}
(#'self/parse-provider-model "metabase/anthropic/claude-haiku-4-5")))
@@ -50,7 +52,8 @@
(testing "resolves known providers to adapter functions"
(is (fn? (#'self/resolve-adapter "anthropic")))
(is (fn? (#'self/resolve-adapter "openai")))
- (is (fn? (#'self/resolve-adapter "openrouter"))))
+ (is (fn? (#'self/resolve-adapter "openrouter")))
+ (is (fn? (#'self/resolve-adapter "zai"))))
(testing "throws for unknown provider"
(is (thrown-with-msg? clojure.lang.ExceptionInfo #"Unknown LLM provider"
(#'self/resolve-adapter "unknown")))))
diff --git a/test/metabase/metabot/settings_test.clj b/test/metabase/metabot/settings_test.clj
index 6085a0a18ea..2d3e62c63c9 100644
--- a/test/metabase/metabot/settings_test.clj
+++ b/test/metabase/metabot/settings_test.clj
@@ -165,6 +165,13 @@
clojure.lang.ExceptionInfo #"Unsupported provider \"openrouter\" for metabase managed AI"
(metabot.settings/llm-metabot-provider! "metabase/openrouter/anthropic/claude-haiku-4-5"))))))
+(deftest validate-metabot-provider-rejects-direct-only-provider-as-managed-zai-test
+ (testing "rejects zai under metabase/ prefix (not in the managed allow-list)"
+ (mt/with-premium-features #{:metabase-ai-managed}
+ (is (thrown-with-msg?
+ clojure.lang.ExceptionInfo #"Unsupported provider \"zai\" for metabase managed AI"
+ (metabot.settings/llm-metabot-provider! "metabase/zai/glm-5.2"))))))
+
(deftest validate-metabot-provider-rejects-unsupported-metabase-managed-model-test
(testing "rejects unsupported model for an allowed metabase managed provider"
(mt/with-premium-features #{:metabase-ai-managed}
@@ -195,6 +202,11 @@
(mt/with-temporary-setting-values [llm-metabot-provider "openrouter/anthropic/claude-haiku-4-5"]
(is (= "openrouter/anthropic/claude-haiku-4-5" (metabot.settings/llm-metabot-provider))))))
+(deftest validate-metabot-provider-accepts-valid-direct-zai-test
+ (testing "accepts valid direct zai provider string"
+ (mt/with-temporary-setting-values [llm-metabot-provider "zai/glm-5.2"]
+ (is (= "zai/glm-5.2" (metabot.settings/llm-metabot-provider))))))
+
(deftest validate-metabot-provider-accepts-allowed-metabase-managed-provider-and-model-test
(testing "accepts allow-listed metabase managed provider/model"
(mt/with-premium-features #{:metabase-ai-managed}
@@ -249,6 +261,14 @@
llm-bedrock-secret-access-key nil]
(is (false? (metabot.settings/llm-metabot-configured?))))))
+(deftest configured-provider-credentials-zai-test
+ (testing "returns the api-key map when a zai key is configured, nil when blank or missing"
+ (mt/with-temporary-setting-values [llm-zai-api-key "zai-key.test"]
+ (is (= {:api-key "zai-key.test"}
+ (metabot.settings/configured-provider-credentials "zai"))))
+ (mt/with-temporary-setting-values [llm-zai-api-key nil]
+ (is (nil? (metabot.settings/configured-provider-credentials "zai"))))))
+
(deftest configured-provider-credentials-bedrock-fully-configured-test
(testing "returns the AWS credentials map when bedrock is fully configured"
(mt/with-temporary-setting-values [llm-bedrock-access-key-id "AKIAIOSFODNN7EXAMPLE"