The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:
TypeScript analyticsbibusiness-intelligencebusinessintelligenceclojuredashboarddatadata-analysisdata-visualizationdatabasemetabasemysqlpostgrespostgresqlreportingslacksql-editorvisualization
Add Mistral metabot provider (#78712)
appleby0a303f2dec0f
diff --git a/frontend/src/metabase-types/api/metabot.ts b/frontend/src/metabase-types/api/metabot.tsindex ecdca53d952..3ab3e52f3d3 100644--- a/frontend/src/metabase-types/api/metabot.ts+++ b/frontend/src/metabase-types/api/metabot.ts@@ -194,6 +194,7 @@ export type MetabotProvider =| "anthropic"| "azure"| "bedrock"+ | "mistral"| "openai"| "openrouter"| "zai";diff --git a/frontend/src/metabase-types/api/settings.ts b/frontend/src/metabase-types/api/settings.tsindex e36c6d40d7d..48e8b970301 100644--- a/frontend/src/metabase-types/api/settings.ts+++ b/frontend/src/metabase-types/api/settings.ts@@ -539,6 +539,7 @@ interface SettingsManagerSettings {"llm-anthropic-api-base-url"?: string | null;"llm-openrouter-api-key"?: string | null;"llm-zai-api-key"?: string | null;+ "llm-mistral-api-key"?: string | null;"llm-azure-api-key"?: string | null;"llm-azure-api-base-url"?: string | null;"llm-bedrock-access-key-id"?: string | null;@@ -773,6 +774,7 @@ export interface EnterpriseSettings extends Settings {"llm-metabot-supports-reasoning?"?: boolean | null;"llm-openrouter-api-key"?: string | null;"llm-zai-api-key"?: string | null;+ "llm-mistral-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.tsxindex 4db41e32b74..19786e3fa64 100644--- a/frontend/src/metabase/admin/ai/AIProviderSettingsSection.unit.spec.tsx+++ b/frontend/src/metabase/admin/ai/AIProviderSettingsSection.unit.spec.tsx@@ -3,6 +3,7 @@ import fetchMock from "fetch-mock";import { setupEnterpriseOnlyPlugin } from "__support__/enterprise";import {+ findRequests,setupBillingEndpoints,setupMetabaseManagedAiEndpoints,setupPropertiesEndpoints,@@ -88,6 +89,10 @@ const DEFAULT_RESPONSES: Record<MetabotProvider, MetabotSettingsResponse> = {},],},+ mistral: {+ value: "mistral/mistral-medium-3-5",+ models: [{ id: "mistral-medium-3-5", display_name: "Mistral Medium 3.5" }],+ },openai: {value: "openai/gpt-5.4",models: [@@ -127,6 +132,7 @@ type MetabotSettingKey =| "llm-anthropic-api-key"| "llm-azure-api-key"| "llm-azure-api-base-url"+ | "llm-mistral-api-key"| "llm-openai-api-key"| "llm-openrouter-api-key"| "llm-zai-api-key"@@ -135,6 +141,16 @@ type MetabotSettingKey =| "llm-bedrock-region"| "llm-bedrock-session-token";+const API_KEY_SETTING_BY_PROVIDER: Partial<+ Record<MetabotProvider, MetabotSettingKey>+> = {+ anthropic: "llm-anthropic-api-key",+ mistral: "llm-mistral-api-key",+ openai: "llm-openai-api-key",+ openrouter: "llm-openrouter-api-key",+ zai: "llm-zai-api-key",+};+type MetabotSettingDefinition = SettingDefinition<MetabotSettingKey>;type MetabotSettingsUpdateBody = {provider: MetabotProvider;@@ -221,6 +237,7 @@ async function setup({anthropic: "**********45",azure: null,bedrock: null,+ mistral: null,openai: null,openrouter: null,zai: null,@@ -278,6 +295,10 @@ async function setup({? "https://my-resource.services.ai.azure.com/anthropic": undefined,}),+ "llm-mistral-api-key": createMockSettingDefinition({+ key: "llm-mistral-api-key",+ value: mergedApiKeyValues.mistral ?? undefined,+ }),"llm-openai-api-key": createMockSettingDefinition({key: "llm-openai-api-key",value: mergedApiKeyValues.openai ?? undefined,@@ -386,15 +407,9 @@ async function setup({String(call.options?.body ?? "{}"),) as MetabotSettingsUpdateBody;- if ("api-key" in body) {- const apiKeySettingKey =- body.provider === "anthropic"- ? "llm-anthropic-api-key"- : body.provider === "openai"- ? "llm-openai-api-key"- : body.provider === "zai"- ? "llm-zai-api-key"- : "llm-openrouter-api-key";+ const apiKeySettingKey = API_KEY_SETTING_BY_PROVIDER[body.provider];++ if ("api-key" in body && apiKeySettingKey) {const maskedApiKey = body["api-key"]? `**********${String(body["api-key"]).slice(-2)}`: undefined;@@ -562,6 +577,27 @@ async function confirmDisconnectProvider() {);}+const METABOT_SETTINGS_PATH = "/api/metabot/settings";+const SETTING_PATH = "/api/setting";++async function findPutRequests() {+ const requests = await findRequests("PUT");+ return requests.map(({ url, body }) => ({+ path: new URL(url, location.origin).pathname,+ body,+ }));+}++async function findPutBodies(path: string) {+ return (await findPutRequests())+ .filter((request) => request.path === path)+ .map(({ body }) => body);+}++const findMetabotSettingsUpdates = () => findPutBodies(METABOT_SETTINGS_PATH);++const findSettingUpdates = () => findPutBodies(SETTING_PATH);+describe("AIProviderSettingsSection", () => {afterEach(() => {reinitialize();@@ -584,54 +620,25 @@ describe("AIProviderSettingsSection", () => {expect(screen.queryByLabelText("Model")).not.toBeInTheDocument();});- it("shows Anthropic as selectable in the provider dropdown", async () => {+ it("shows the providers as selectable in the provider dropdown", async () => {await setup({ savedProviderValue: null, isConfigured: false });await userEvent.click(screen.getByLabelText("Provider"));- const anthropicOption = await screen.findByRole("option", {- name: "Anthropic",- });- expect(anthropicOption).toBeInTheDocument();- expect(anthropicOption).not.toHaveAttribute("aria-disabled", "true");- });-- it("shows OpenAI as selectable in the provider dropdown", async () => {- await setup({ savedProviderValue: null, isConfigured: false });-- await userEvent.click(screen.getByLabelText("Provider"));-- const openaiOption = await screen.findByRole("option", {- name: /OpenAI/,- });- expect(openaiOption).toBeInTheDocument();- expect(openaiOption).not.toHaveAttribute("data-combobox-disabled");- });-- it("shows OpenRouter as selectable in the provider dropdown", async () => {- await setup({ savedProviderValue: null, isConfigured: false });-- await userEvent.click(screen.getByLabelText("Provider"));-- const openrouterOption = await screen.findByRole("option", {- name: /OpenRouter/,- });- expect(openrouterOption).toBeInTheDocument();- expect(openrouterOption).not.toHaveAttribute("data-combobox-disabled");-- 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");+ for (const name of [+ /Anthropic/,+ /OpenAI/,+ /OpenRouter/,+ /Mistral/,+ /Z\.AI/,+ /Microsoft Azure/,+ /Amazon Bedrock/,+ ]) {+ const option = await screen.findByRole("option", { name });+ expect(option).toBeInTheDocument();+ expect(option).not.toHaveAttribute("aria-disabled", "true");+ expect(option).not.toHaveAttribute("data-combobox-disabled");+ }expect(screen.queryByText("Coming soon")).not.toBeInTheDocument();});@@ -713,23 +720,12 @@ describe("AIProviderSettingsSection", () => {await userEvent.click(screen.getByRole("button", { name: "Connect" }));- await waitFor(() => {- expect(fetchMock.callHistory.called("path:/api/metabot/settings")).toBe(- true,- );+ await waitFor(async () => {+ expect(await findMetabotSettingsUpdates()).toEqual([+ { provider: "anthropic", "api-key": "sk-ant-rotated" },+ ]);});- const request = fetchMock.callHistory- .calls("path:/api/metabot/settings")- .find(- (call) =>- call.request?.method === "PUT" || call.options?.method === "PUT",- );-- expect(request?.options?.body).toBe(- JSON.stringify({ provider: "anthropic", "api-key": "sk-ant-rotated" }),- );-await waitFor(() => {expect(screen.getByRole("button", { name: "Disconnect" }),@@ -1540,23 +1536,12 @@ describe("AIProviderSettingsSection", () => {await openModelSelector();await userEvent.click(await screen.findByText("Claude Sonnet 4.5"));- await waitFor(() => {- expect(fetchMock.callHistory.called("path:/api/metabot/settings")).toBe(- true,- );+ await waitFor(async () => {+ expect(await findMetabotSettingsUpdates()).toEqual([+ { provider: "anthropic", model: "claude-sonnet-4-5" },+ ]);});- const [request] = fetchMock.callHistory.calls(- "path:/api/metabot/settings",- {- method: "PUT",- },- );-- expect(request?.options?.body).toBe(- JSON.stringify({ provider: "anthropic", model: "claude-sonnet-4-5" }),- );-await waitFor(() => {expect(store@@ -1587,40 +1572,23 @@ describe("AIProviderSettingsSection", () => {await userEvent.type(screen.getByLabelText("API key"), "sk-openai-test");await userEvent.click(screen.getByRole("button", { name: "Connect" }));- await waitFor(() => {- expect(- fetchMock.callHistory.calls("path:/api/metabot/settings", {- method: "PUT",- }),- ).toHaveLength(1);+ await waitFor(async () => {+ expect(await findMetabotSettingsUpdates()).toEqual([+ { provider: "openai", "api-key": "sk-openai-test" },+ ]);});- const connectRequest = fetchMock.callHistory- .calls("path:/api/metabot/settings", { method: "PUT" })- .at(-1);- expect(connectRequest?.options?.body).toBe(- JSON.stringify({ provider: "openai", "api-key": "sk-openai-test" }),- );-await screen.findByLabelText("Model");await openModelSelector();await userEvent.click(await screen.findByText("gpt-5.4"));- await waitFor(() => {- expect(- fetchMock.callHistory.calls("path:/api/metabot/settings", {- method: "PUT",- }),- ).toHaveLength(2);+ await waitFor(async () => {+ expect(await findMetabotSettingsUpdates()).toEqual([+ { provider: "openai", "api-key": "sk-openai-test" },+ { provider: "openai", model: "gpt-5.4" },+ ]);});- const modelRequest = fetchMock.callHistory- .calls("path:/api/metabot/settings", { method: "PUT" })- .at(-1);- expect(modelRequest?.options?.body).toBe(- JSON.stringify({ provider: "openai", model: "gpt-5.4" }),- );-expect(screen.queryByRole("button", { name: "Connect" }),).not.toBeInTheDocument();@@ -1637,16 +1605,11 @@ describe("AIProviderSettingsSection", () => {await screen.findByLabelText("API key");await confirmDisconnectProvider();- await waitFor(() => {- expect(- fetchMock.callHistory.called("path:/api/setting", {- method: "PUT",- body: {- "llm-metabot-provider": null,- "llm-openai-api-key": null,- },- }),- ).toBe(true);+ await waitFor(async () => {+ expect(await findSettingUpdates()).toContainEqual({+ "llm-metabot-provider": null,+ "llm-openai-api-key": null,+ });});expect(@@ -1673,46 +1636,23 @@ describe("AIProviderSettingsSection", () => {);await userEvent.click(screen.getByRole("button", { name: "Connect" }));- await waitFor(() => {- expect(- fetchMock.callHistory.calls("path:/api/metabot/settings", {- method: "PUT",- }),- ).toHaveLength(1);+ await waitFor(async () => {+ expect(await findMetabotSettingsUpdates()).toEqual([+ { provider: "openrouter", "api-key": "sk-or-v1-openrouter-test" },+ ]);});- expect(- fetchMock.callHistory.lastCall("path:/api/metabot/settings", {- method: "PUT",- body: {- provider: "openrouter",- "api-key": "sk-or-v1-openrouter-test",- },- }),- ).toBeDefined();-await screen.findByLabelText("Model");await openModelSelector();await userEvent.click(await screen.findByText("OpenAI: GPT-5.4 Mini"));- await waitFor(() => {- expect(- fetchMock.callHistory.calls("path:/api/metabot/settings", {- method: "PUT",- }),- ).toHaveLength(2);+ await waitFor(async () => {+ expect(await findMetabotSettingsUpdates()).toEqual([+ { provider: "openrouter", "api-key": "sk-or-v1-openrouter-test" },+ { provider: "openrouter", model: "openai/gpt-5.4-mini" },+ ]);});- expect(- fetchMock.callHistory.lastCall("path:/api/metabot/settings", {- method: "PUT",- body: {- provider: "openrouter",- model: "openai/gpt-5.4-mini",- },- }),- ).toBeDefined();-expect(screen.queryByRole("button", { name: "Connect" }),).not.toBeInTheDocument();@@ -1729,16 +1669,72 @@ describe("AIProviderSettingsSection", () => {await screen.findByLabelText("API key");await confirmDisconnectProvider();- await waitFor(() => {- expect(- fetchMock.callHistory.called("path:/api/setting", {- method: "PUT",- body: {- "llm-metabot-provider": null,- "llm-openrouter-api-key": null,- },- }),- ).toBe(true);+ await waitFor(async () => {+ expect(await findSettingUpdates()).toContainEqual({+ "llm-metabot-provider": null,+ "llm-openrouter-api-key": null,+ });+ });++ expect(+ await screen.findByText("Connect to an AI provider"),+ ).toBeInTheDocument();+ expect(screen.getByLabelText("Provider")).toHaveValue("");+ });++ it("connects to Mistral by saving the API key and selecting a model", async () => {+ await setup({+ savedProviderValue: null,+ isConfigured: false,+ apiKeyValues: { mistral: null },+ updateResponse: {+ value: "mistral/mistral-medium-3-5",+ models: DEFAULT_RESPONSES.mistral.models,+ },+ });++ await selectProvider("Mistral");+ await userEvent.type(screen.getByLabelText("API key"), "mistral-key.test");+ await userEvent.click(screen.getByRole("button", { name: "Connect" }));++ await waitFor(async () => {+ expect(await findMetabotSettingsUpdates()).toEqual([+ { provider: "mistral", "api-key": "mistral-key.test" },+ ]);+ });++ await screen.findByLabelText("Model");+ await openModelSelector();+ await userEvent.click(await screen.findByText("Mistral Medium 3.5"));++ await waitFor(async () => {+ expect(await findMetabotSettingsUpdates()).toEqual([+ { provider: "mistral", "api-key": "mistral-key.test" },+ { provider: "mistral", model: "mistral-medium-3-5" },+ ]);+ });++ expect(+ screen.queryByRole("button", { name: "Connect" }),+ ).not.toBeInTheDocument();+ });++ it("disconnects Mistral by clearing both the provider and API key settings", async () => {+ await setup({+ savedProviderValue: "mistral/mistral-medium-3-5",+ isConfigured: true,+ apiKeyValues: { mistral: "**********st" },+ });++ await screen.findByText("Connected to Mistral");+ await screen.findByLabelText("API key");+ await confirmDisconnectProvider();++ await waitFor(async () => {+ expect(await findSettingUpdates()).toContainEqual({+ "llm-metabot-provider": null,+ "llm-mistral-api-key": null,+ });});expect(@@ -1762,46 +1758,23 @@ describe("AIProviderSettingsSection", () => {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);+ await waitFor(async () => {+ expect(await findMetabotSettingsUpdates()).toEqual([+ { provider: "zai", "api-key": "zai-key.test" },+ ]);});- 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);+ await waitFor(async () => {+ expect(await findMetabotSettingsUpdates()).toEqual([+ { provider: "zai", "api-key": "zai-key.test" },+ { provider: "zai", model: "glm-5.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();@@ -1818,16 +1791,11 @@ describe("AIProviderSettingsSection", () => {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);+ await waitFor(async () => {+ expect(await findSettingUpdates()).toContainEqual({+ "llm-metabot-provider": null,+ "llm-zai-api-key": null,+ });});expect(@@ -1850,24 +1818,17 @@ describe("AIProviderSettingsSection", () => {"This will disconnect your AI provider and disable AI features across your instance until you connect a provider again.",),).toBeInTheDocument();- expect(- fetchMock.callHistory.calls("path:/api/setting", { method: "PUT" }),- ).toHaveLength(0);+ expect(await findSettingUpdates()).toEqual([]);await userEvent.click(screen.getByRole("button", { name: "Disconnect provider" }),);- await waitFor(() => {- expect(- fetchMock.callHistory.called("path:/api/setting", {- method: "PUT",- body: {- "llm-metabot-provider": null,- "llm-anthropic-api-key": null,- },- }),- ).toBe(true);+ await waitFor(async () => {+ expect(await findSettingUpdates()).toContainEqual({+ "llm-metabot-provider": null,+ "llm-anthropic-api-key": null,+ });});expect(@@ -1895,15 +1856,10 @@ describe("AIProviderSettingsSection", () => {await confirmDisconnectProvider();- await waitFor(() => {- expect(- fetchMock.callHistory.called("path:/api/setting", {- method: "PUT",- body: {- "llm-metabot-provider": null,- },- }),- ).toBe(true);+ await waitFor(async () => {+ expect(await findSettingUpdates()).toContainEqual({+ "llm-metabot-provider": null,+ });});expect(@@ -2097,18 +2053,6 @@ describe("AIProviderSettingsSection", () => {});describe("Microsoft Azure", () => {- it("shows Microsoft Azure as selectable in the provider dropdown", async () => {- await setup({ savedProviderValue: null, isConfigured: false });-- await userEvent.click(screen.getByLabelText("Provider"));-- const azureOption = await screen.findByRole("option", {- name: "Microsoft Azure",- });- expect(azureOption).toBeInTheDocument();- expect(azureOption).not.toHaveAttribute("data-combobox-disabled");- });-it("shows the Azure fields without a model dropdown when selected", async () => {await setup({ savedProviderValue: null, isConfigured: false });@@ -2155,29 +2099,18 @@ describe("AIProviderSettingsSection", () => {expect(connectButton).toBeEnabled();await userEvent.click(connectButton);- await waitFor(() => {- expect(- fetchMock.callHistory.called("path:/api/metabot/settings", {- method: "PUT",- }),- ).toBe(true);- });-- const [request] = fetchMock.callHistory.calls(- "path:/api/metabot/settings",- { method: "PUT" },- );-- expect(request?.options?.body).toBe(- JSON.stringify({- provider: "azure",- model: "openai/my-deployment",- credentials: {- "api-key": "azure-key",- "base-url": "https://my-resource.services.ai.azure.com/openai",+ await waitFor(async () => {+ expect(await findMetabotSettingsUpdates()).toEqual([+ {+ provider: "azure",+ model: "openai/my-deployment",+ credentials: {+ "api-key": "azure-key",+ "base-url": "https://my-resource.services.ai.azure.com/openai",+ },},- }),- );+ ]);+ });});it("shows the saved family, base URL, and deployment for a connected Azure provider", async () => {@@ -2228,31 +2161,20 @@ describe("AIProviderSettingsSection", () => {await userEvent.click(screen.getByRole("button", { name: "Connect" }));- await waitFor(() => {- expect(- fetchMock.callHistory.called("path:/api/metabot/settings", {- method: "PUT",- }),- ).toBe(true);- });-- const [request] = fetchMock.callHistory.calls(- "path:/api/metabot/settings",- { method: "PUT" },- );-// The untouched key and base URL round-trip as displayed values in the form, but must be// sent as null so the backend keeps the real saved values.- expect(request?.options?.body).toBe(- JSON.stringify({- provider: "azure",- model: "anthropic/renamed-deployment",- credentials: {- "api-key": null,- "base-url": null,+ await waitFor(async () => {+ expect(await findMetabotSettingsUpdates()).toEqual([+ {+ provider: "azure",+ model: "anthropic/renamed-deployment",+ credentials: {+ "api-key": null,+ "base-url": null,+ },},- }),- );+ ]);+ });});it("disconnects Azure by clearing the credentials before the provider setting", async () => {@@ -2264,42 +2186,20 @@ describe("AIProviderSettingsSection", () => {await screen.findByLabelText("Deployment name");await confirmDisconnectProvider();- await waitFor(() => {- expect(- fetchMock.callHistory.called("path:/api/metabot/settings", {- method: "PUT",+ // The credentials must be cleared before the provider setting.+ await waitFor(async () => {+ expect(await findPutRequests()).toEqual([+ {+ path: METABOT_SETTINGS_PATH,body: { provider: "azure", credentials: null },- }),- ).toBe(true);- });-- await waitFor(() => {- expect(- fetchMock.callHistory.called("path:/api/setting", {- method: "PUT",+ },+ {+ path: SETTING_PATH,body: { "llm-metabot-provider": null },- }),- ).toBe(true);+ },+ ]);});- const callHistory = fetchMock.callHistory.calls();- const [credentialsRequest] = fetchMock.callHistory.calls(- "path:/api/metabot/settings",- { method: "PUT" },- );- const [providerRequest] = fetchMock.callHistory.calls(- "path:/api/setting",- { method: "PUT" },- );-- if (!credentialsRequest || !providerRequest) {- throw new Error("Expected credentials and provider requests to exist");- }-- expect(callHistory.indexOf(credentialsRequest)).toBeLessThan(- callHistory.indexOf(providerRequest),- );-expect(await screen.findByText("Connect to an AI provider"),).toBeInTheDocument();@@ -2307,18 +2207,6 @@ describe("AIProviderSettingsSection", () => {});describe("Amazon Bedrock", () => {- it("shows Amazon Bedrock as selectable in the provider dropdown", async () => {- await setup({ savedProviderValue: null, isConfigured: false });-- await userEvent.click(screen.getByLabelText("Provider"));-- const bedrockOption = await screen.findByRole("option", {- name: "Amazon Bedrock",- });- expect(bedrockOption).toBeInTheDocument();- expect(bedrockOption).not.toHaveAttribute("data-combobox-disabled");- });-it("shows the AWS credential fields when Amazon Bedrock is selected", async () => {await setup({ savedProviderValue: null, isConfigured: false });@@ -2347,30 +2235,19 @@ describe("AIProviderSettingsSection", () => {await userEvent.type(screen.getByLabelText("Region"), "us-east-2");await userEvent.click(screen.getByRole("button", { name: "Connect" }));- await waitFor(() => {- expect(- fetchMock.callHistory.called("path:/api/metabot/settings", {- method: "PUT",- }),- ).toBe(true);- });-- const [request] = fetchMock.callHistory.calls(- "path:/api/metabot/settings",- { method: "PUT" },- );-// The untouched session token field is omitted entirely — only changed fields are sent.- expect(request?.options?.body).toBe(- JSON.stringify({- provider: "bedrock",- credentials: {- "access-key-id": "AKIDEXAMPLE",- "secret-access-key": "test-secret",- region: "us-east-2",+ await waitFor(async () => {+ expect(await findMetabotSettingsUpdates()).toEqual([+ {+ provider: "bedrock",+ credentials: {+ "access-key-id": "AKIDEXAMPLE",+ "secret-access-key": "test-secret",+ region: "us-east-2",+ },},- }),- );+ ]);+ });});it("does not echo obfuscated credentials when editing only the region of a connected Bedrock provider", async () => {@@ -2385,29 +2262,18 @@ describe("AIProviderSettingsSection", () => {await userEvent.click(screen.getByRole("button", { name: "Connect" }));- await waitFor(() => {- expect(- fetchMock.callHistory.called("path:/api/metabot/settings", {- method: "PUT",- }),- ).toBe(true);- });-- const [request] = fetchMock.callHistory.calls(- "path:/api/metabot/settings",- { method: "PUT" },- );-// The untouched access key, secret, and session token round-trip as obfuscated placeholders// in the form, and must be omitted so the backend leaves the real saved values intact.- expect(request?.options?.body).toBe(- JSON.stringify({- provider: "bedrock",- credentials: {- region: "us-west-2",+ await waitFor(async () => {+ expect(await findMetabotSettingsUpdates()).toEqual([+ {+ provider: "bedrock",+ credentials: {+ region: "us-west-2",+ },},- }),- );+ ]);+ });});it("clears the session token by sending an explicit null without touching the other fields", async () => {@@ -2421,28 +2287,17 @@ describe("AIProviderSettingsSection", () => {await userEvent.click(screen.getByRole("button", { name: "Connect" }));- await waitFor(() => {- expect(- fetchMock.callHistory.called("path:/api/metabot/settings", {- method: "PUT",- }),- ).toBe(true);- });-- const [request] = fetchMock.callHistory.calls(- "path:/api/metabot/settings",- { method: "PUT" },- );-// null means an explicit clear; the untouched fields are omitted so the saved keys survive.- expect(request?.options?.body).toBe(- JSON.stringify({- provider: "bedrock",- credentials: {- "session-token": null,+ await waitFor(async () => {+ expect(await findMetabotSettingsUpdates()).toEqual([+ {+ provider: "bedrock",+ credentials: {+ "session-token": null,+ },},- }),- );+ ]);+ });});it("shows the grouped model picker for a connected Bedrock provider", async () => {@@ -2469,42 +2324,20 @@ describe("AIProviderSettingsSection", () => {await screen.findByLabelText("Access key ID");await confirmDisconnectProvider();- await waitFor(() => {- expect(- fetchMock.callHistory.called("path:/api/metabot/settings", {- method: "PUT",+ // The credentials must be cleared before the provider setting.+ await waitFor(async () => {+ expect(await findPutRequests()).toEqual([+ {+ path: METABOT_SETTINGS_PATH,body: { provider: "bedrock", credentials: null },- }),- ).toBe(true);- });-- await waitFor(() => {- expect(- fetchMock.callHistory.called("path:/api/setting", {- method: "PUT",+ },+ {+ path: SETTING_PATH,body: { "llm-metabot-provider": null },- }),- ).toBe(true);+ },+ ]);});- const callHistory = fetchMock.callHistory.calls();- const [credentialsRequest] = fetchMock.callHistory.calls(- "path:/api/metabot/settings",- { method: "PUT" },- );- const [providerRequest] = fetchMock.callHistory.calls(- "path:/api/setting",- { method: "PUT" },- );-- if (!credentialsRequest || !providerRequest) {- throw new Error("Expected credentials and provider requests to exist");- }-- expect(callHistory.indexOf(credentialsRequest)).toBeLessThan(- callHistory.indexOf(providerRequest),- );-expect(await screen.findByText("Connect to an AI provider"),).toBeInTheDocument();@@ -2530,11 +2363,7 @@ describe("AIProviderSettingsSection", () => {).toBe(true);});- expect(- fetchMock.callHistory- .calls("path:/api/setting")- .some((call) => call.request?.method === "PUT"),- ).toBe(false);+ expect(await findSettingUpdates()).toEqual([]);expect(screen.getByRole("button", { name: "Disconnect" }),).toBeInTheDocument();diff --git a/frontend/src/metabase/admin/ai/AISettingsPage.unit.spec.tsx b/frontend/src/metabase/admin/ai/AISettingsPage.unit.spec.tsxindex a9d4a618c09..d7f17082d2e 100644--- a/frontend/src/metabase/admin/ai/AISettingsPage.unit.spec.tsx+++ b/frontend/src/metabase/admin/ai/AISettingsPage.unit.spec.tsx@@ -117,6 +117,10 @@ const setup = async ({key: "llm-zai-api-key",value: undefined,}),+ createMockSettingDefinition({+ key: "llm-mistral-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.tsxindex bb095739f1c..c09edf9eb21 100644--- a/frontend/src/metabase/metabot/components/AIProviderConfigurationForm/AIProviderConfigurationForm.tsx+++ b/frontend/src/metabase/metabot/components/AIProviderConfigurationForm/AIProviderConfigurationForm.tsx@@ -124,6 +124,7 @@ function AIProviderConfigurationFormBody({const { details: providerApiKeyDetails, isLoading: areDetailsLoading } =useAdminSettings(["llm-anthropic-api-key",+ "llm-mistral-api-key","llm-openai-api-key","llm-openrouter-api-key","llm-zai-api-key",@@ -324,6 +325,7 @@ function AIProviderConfigurationFormBody({)).with("anthropic",+ "mistral","openai","openrouter","zai",diff --git a/frontend/src/metabase/metabot/components/AIProviderConfigurationForm/ApiKeyProviderFields.tsx b/frontend/src/metabase/metabot/components/AIProviderConfigurationForm/ApiKeyProviderFields.tsxindex 73f4a96a2b6..e517bea90dc 100644--- a/frontend/src/metabase/metabot/components/AIProviderConfigurationForm/ApiKeyProviderFields.tsx+++ b/frontend/src/metabase/metabot/components/AIProviderConfigurationForm/ApiKeyProviderFields.tsx@@ -36,6 +36,7 @@ export const ApiKeyProviderFields = ({const { details } = useAdminSettings(["llm-anthropic-api-key",+ "llm-mistral-api-key","llm-openai-api-key","llm-openrouter-api-key","llm-zai-api-key",diff --git a/frontend/src/metabase/metabot/components/AIProviderConfigurationForm/utils.ts b/frontend/src/metabase/metabot/components/AIProviderConfigurationForm/utils.tsindex d9ba5341a28..01291a4668e 100644--- a/frontend/src/metabase/metabot/components/AIProviderConfigurationForm/utils.ts+++ b/frontend/src/metabase/metabot/components/AIProviderConfigurationForm/utils.ts@@ -61,6 +61,15 @@ export function getProviderOptions("https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_access-keys.html",},},+ mistral: {+ value: "mistral",+ label: "Mistral",+ apiKey: {+ // Mistral keys have no recognizable prefix+ placeholder: t`Enter your Mistral API key`,+ addKeyUrl: "https://console.mistral.ai/api-keys",+ },+ },openai: {value: "openai",label: "OpenAI",@@ -106,6 +115,7 @@ export function isAvailableProvider(provider: MetabotProvider): boolean {provider === "azure" ||provider === "bedrock" ||provider === "metabase" ||+ provider === "mistral" ||provider === "openai" ||provider === "openrouter" ||provider === "zai"@@ -115,11 +125,13 @@ export function isAvailableProvider(provider: MetabotProvider): boolean {export const API_KEY_SETTING_BY_PROVIDER: Record<MetabotApiKeyProvider,| "llm-anthropic-api-key"+ | "llm-mistral-api-key"| "llm-openai-api-key"| "llm-openrouter-api-key"| "llm-zai-api-key"> = {anthropic: "llm-anthropic-api-key",+ mistral: "llm-mistral-api-key",openai: "llm-openai-api-key",openrouter: "llm-openrouter-api-key",zai: "llm-zai-api-key",diff --git a/src/metabase/llm/settings.clj b/src/metabase/llm/settings.cljindex c863b941b1d..2078e429fe4 100644--- a/src/metabase/llm/settings.clj+++ b/src/metabase/llm/settings.clj@@ -145,6 +145,22 @@:export? false:setter (partial set-trimmed-string! :llm-zai-api-key))+;;; -------------------------------------------------- Mistral ---------------------------------------------------++(defsetting llm-mistral-api-base-url+ (deferred-tru "The Mistral API base URL used for Chat Completions.")+ :encryption :no+ :visibility :settings-manager+ :default "https://api.mistral.ai/v1"+ :export? false)++(defsetting llm-mistral-api-key+ (deferred-tru "The Mistral API Key.")+ :sensitive? true+ :visibility :settings-manager+ :export? false+ :setter (partial set-trimmed-string! :llm-mistral-api-key))+;;; ----------------------------------------------- Amazon Bedrock ----------------------------------------------(defsetting llm-bedrock-access-key-iddiff --git a/src/metabase/metabot/api.clj b/src/metabase/metabot/api.cljindex bc4d5edc4ac..3cb0df38172 100644--- a/src/metabase/metabot/api.clj+++ b/src/metabase/metabot/api.clj@@ -484,6 +484,7 @@[provider](case provider"anthropic" :llm-anthropic-api-key+ "mistral" :llm-mistral-api-key"openai" :llm-openai-api-key"openrouter" :llm-openrouter-api-key"zai" :llm-zai-api-key))diff --git a/src/metabase/metabot/self.clj b/src/metabase/metabot/self.cljindex 1b6b1f105d1..8f9b01c0a14 100644--- a/src/metabase/metabot/self.clj+++ b/src/metabase/metabot/self.clj@@ -18,6 +18,7 @@[metabase.metabot.self.bedrock :as bedrock][metabase.metabot.self.claude :as claude][metabase.metabot.self.core :as core]+ [metabase.metabot.self.mistral :as mistral][metabase.metabot.self.openai :as openai][metabase.metabot.self.openrouter :as openrouter][metabase.metabot.self.zai :as zai]@@ -34,6 +35,7 @@"anthropic" claude/claude"azure" azure/azure"bedrock" bedrock/bedrock+ "mistral" mistral/mistral"openai" openai/openai"openrouter" openrouter/openrouter"zai" zai/zai@@ -46,6 +48,7 @@"anthropic" claude/list-models"azure" azure/list-models"bedrock" bedrock/list-models+ "mistral" mistral/list-models"openai" openai/list-models"openrouter" openrouter/list-models"zai" zai/list-models@@ -313,9 +316,9 @@:tool-choice tool-choice :ai-proxy? ai-proxy?})(let [tracking-opts (assoc tracking-opts :model provider-and-model :ai-proxy? ai-proxy?)streaming-opts (cond-> {:model model :input parts :tools (vals tools) :ai-proxy? ai-proxy?}- system-msg (assoc :system system-msg)- (and (seq tools)- tool-choice) (assoc :tool_choice tool-choice))+ system-msg (assoc :system system-msg)+ (and (seq tools) tool-choice) (assoc :tool_choice tool-choice)+ (:session-id tracking-opts) (assoc :prompt-cache-key (:session-id tracking-opts)))make-source (fn [](eduction (comp (core/tool-executor-xf tools)(core/lite-aisdk-xf)@@ -379,7 +382,8 @@:temperature temperature:max-tokens max-tokens:ai-proxy? ai-proxy?}- system-msg (assoc :system system-msg))]+ system-msg (assoc :system system-msg)+ (:session-id tracking-opts) (assoc :prompt-cache-key (:session-id tracking-opts)))](with-span :info {:name :metabot.agent/call-llm-structured:model model:msg-count (count input)}diff --git a/src/metabase/metabot/self/core.clj b/src/metabase/metabot/self/core.cljindex 63e70c873fd..93b1cc2fe10 100644--- a/src/metabase/metabot/self/core.clj+++ b/src/metabase/metabot/self/core.clj@@ -38,31 +38,34 @@"Canonical schema for the opts map passed to every LLM provider adapter.Required:- :model - Model name string (e.g. \"claude-haiku-4-5\", \"gpt-5.4\")+ :model - Model name string (e.g. \"claude-haiku-4-5\", \"gpt-5.4\")Optional:- :system - System prompt string- :input - Sequence of AISDK parts and user messages- :tools - Sequence of tool definition maps- :tool_choice - \"auto\" or \"required\"- :temperature - Sampling temperature- :max-tokens - Maximum tokens in the response- :schema - JSON Schema map for structured output; each provider forces a- tool call (Claude, OpenRouter) or uses json_schema mode (OpenAI)- :ai-proxy? - When true, skip provider auth and use the Metabase AI proxy- :reasoning? - When false, don't request thinking/reasoning and strip- :reasoning parts from the replayed input (defaults true)"+ :system - System prompt string+ :input - Sequence of AISDK parts and user messages+ :tools - Sequence of tool definition maps+ :tool_choice - \"auto\" or \"required\"+ :temperature - Sampling temperature+ :max-tokens - Maximum tokens in the response+ :schema - JSON Schema map for structured output; each provider forces a+ tool call (Claude, OpenRouter) or uses json_schema mode (OpenAI)+ :ai-proxy? - When true, skip provider auth and use the Metabase AI proxy+ :reasoning? - When false, don't request thinking/reasoning and strip+ :reasoning parts from the replayed input (defaults true)+ :prompt-cache-key - prompt-cache affinity hint (the conversation id); adapters whose+ provider caches opt-in per key forward it (Mistral), others ignore it"[:map- [:model {:optional true} :string]- [:system {:optional true} [:maybe :string]]- [:input {:optional true} [:sequential :map]]- [:tools {:optional true} [:maybe [:sequential ToolEntry]]]- [:tool_choice {:optional true} [:maybe [:enum "auto" "required"]]]- [:temperature {:optional true} [:maybe number?]]- [:max-tokens {:optional true} [:maybe :int]]- [:schema {:optional true} :any]- [:ai-proxy? {:optional true} [:maybe :boolean]]- [:reasoning? {:optional true} [:maybe :boolean]]])+ [:model {:optional true} :string]+ [:system {:optional true} [:maybe :string]]+ [:input {:optional true} [:sequential :map]]+ [:tools {:optional true} [:maybe [:sequential ToolEntry]]]+ [:tool_choice {:optional true} [:maybe [:enum "auto" "required"]]]+ [:temperature {:optional true} [:maybe number?]]+ [:max-tokens {:optional true} [:maybe :int]]+ [:schema {:optional true} :any]+ [:ai-proxy? {:optional true} [:maybe :boolean]]+ [:reasoning? {:optional true} [:maybe :boolean]]+ [:prompt-cache-key {:optional true} [:maybe :string]]])(defn mkid"Generate a random id"diff --git a/src/metabase/metabot/self/mistral.clj b/src/metabase/metabot/self/mistral.cljnew file mode 100644index 00000000000..e138f72af0c--- /dev/null+++ b/src/metabase/metabot/self/mistral.clj@@ -0,0 +1,143 @@+(ns metabase.metabot.self.mistral+ "Mistral / Chat Completions adapter.++ Mistral exposes an OpenAI-compatible Chat Completions API.++ https://docs.mistral.ai/api/"+ (: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 "mistral-medium-3-5")++(defn- ai-proxy-unsupported-ex []+ (ex-info (tru "AI proxy is not supported for Mistral")+ {:api-error true+ :error-code :proxy-unsupported}))++(defn- mistral-error-msg+ "Canonical, status-specific Mistral error message."+ [res]+ (let [status (long (:status res 0))]+ (case status+ 401 (tru "Mistral API key expired or invalid")+ 404 (tru "Mistral API endpoint was not found — check the base URL")+ 429 (tru "Mistral has rate limited us")+ 500 (tru "Mistral returned an internal server error")+ (tru "Mistral API error (HTTP {0})" status))))++(def ^:private supported-models+ "Mistral 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."+ {"mistral-medium-3-5" "Mistral Medium 3.5"})++(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+ like `mistral-medium-3-5` or `mistral-medium-2604`, so a whitelisted id is matched against the entry's own id and+ its aliases."+ [{:keys [id aliases]}]+ (some #(when (contains? supported-models %) %)+ (cons id aliases)))++(defn- list-all-models+ "Fetch the full Mistral model catalog (`GET /models`).+ `:ai-proxy?` is not supported for Mistral and throws when true."+ [{:keys [credentials ai-proxy?]}]+ (when ai-proxy?+ (throw (ai-proxy-unsupported-ex)))+ (try+ (let [auth (core/resolve-auth "mistral" "Mistral"+ (when-let [k (or (not-empty (:api-key credentials))+ (not-empty (llm/llm-mistral-api-key)))]+ {:url (llm/llm-mistral-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! "mistral" mistral-error-msg e))))++(defn list-models+ "List the Mistral models supported by this adapter (see [[supported-models]]).+ `:ai-proxy?` is not supported for Mistral and throws when true."+ ([] (list-models {}))+ ([opts]+ {:models (->> (list-all-models opts)+ (keep whitelisted-id)+ distinct+ sort+ (mapv (fn [id]+ {:id id :display_name (supported-models id)})))}))++(mu/defn mistral-request-body+ "Build the Chat Completions request body for an LLM request.++ Mistral's Chat Completions dialect matches what [[chat-completions/request-body]] emits, except:++ - 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))))++(mu/defn mistral-raw+ "Perform a streaming request to the Mistral Chat Completions API.+ `:ai-proxy?` is not supported for Mistral 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 (mistral-request-body (assoc opts :model model))]+ (log/debug "Mistral request" {:model model :msg-count (count (:messages req)) :tools (count (or tools []))})+ (with-span :info {:name :metabot.mistral/request+ :model model+ :msg-count (count (:messages req))+ :tool-count (count (or tools []))}+ (try+ (let [api-key (not-empty (llm/llm-mistral-api-key))+ auth (core/resolve-auth "mistral" "Mistral"+ (when api-key+ {:url (llm/llm-mistral-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 "mistral"+ :model model+ :url "/chat/completions"+ :request req})))+ (catch Exception e+ (core/rethrow-api-error! "mistral" mistral-error-msg e))))))++(defn mistral->aisdk-chunks-xf+ "Translates Mistral Chat Completions streaming chunks into AI SDK v5 protocol chunks."+ []+ (chat-completions/chat-completions->aisdk-chunks-xf))++(defn mistral+ "Call the Mistral Chat Completions API, return AISDK stream."+ [& args]+ (let [raw (apply mistral-raw args)]+ (eduction (mistral->aisdk-chunks-xf) raw)))diff --git a/src/metabase/metabot/settings.clj b/src/metabase/metabot/settings.cljindex e6c17109de5..3fbddbaf2c9 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" "zai"})+ #{"anthropic" "azure" "bedrock" "mistral" "openai" "openrouter" "zai"})(def ^:private default-anthropic-llm-metabot-model"Default Anthropic model used for Metabot when no explicit model is selected."@@ -116,6 +116,10 @@"Default Bedrock model used for Metabot when no explicit model is selected.""anthropic.claude-opus-4-8")+(def ^:private default-mistral-llm-metabot-model+ "Default Mistral model used for Metabot when no explicit model is selected."+ "mistral-medium-3-5")+(def ^:private default-openai-llm-metabot-model"Default OpenAI model used for Metabot when no explicit model is selected.""gpt-5.4")@@ -141,6 +145,7 @@managed `metabase` provider uses the proxied `provider/model` form."{"anthropic" default-anthropic-llm-metabot-model"bedrock" default-bedrock-llm-metabot-model+ "mistral" default-mistral-llm-metabot-model"openai" default-openai-llm-metabot-model"openrouter" default-openrouter-llm-metabot-model"zai" default-zai-llm-metabot-model@@ -305,6 +310,7 @@:secret-access-key (non-blank (llm.settings/llm-bedrock-secret-access-key)):session-token (non-blank (llm.settings/llm-bedrock-session-token)):region (non-blank (llm.settings/llm-bedrock-region))})+ "mistral" (configured-api-key-credentials (llm.settings/llm-mistral-api-key))"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))diff --git a/test/metabase/metabot/api_test.clj b/test/metabase/metabot/api_test.cljindex 8fcc3fca63a..602462fa926 100644--- a/test/metabase/metabot/api_test.clj+++ b/test/metabase/metabot/api_test.clj@@ -571,6 +571,31 @@(is (= "zai-key.fresh"(llm.settings/llm-zai-api-key)))))))+(deftest settings-put-connect-mistral-defaults-model-test+ (testing "connecting mistral with only an api-key switches to the default mistral model"+ (mt/with-temporary-setting-values [metabot.settings/llm-metabot-provider "anthropic/claude-haiku-4-5"+ llm.settings/llm-mistral-api-key nil]+ (mt/with-dynamic-fn-redefs [metabot.self/list-models (fn+ ([provider]+ (is (= "mistral" provider))+ {:models [{:id "mistral-medium-3-5"+ :display_name "Mistral Medium 3.5"}]})+ ([provider {:keys [credentials]}]+ (is (= "mistral" provider))+ (is (= {:api-key "mistral-key-fresh"} credentials))+ {:models [{:id "mistral-medium-3-5"+ :display_name "Mistral Medium 3.5"}]}))]+ (is (= {:value "mistral/mistral-medium-3-5"+ :models [{:id "mistral-medium-3-5"+ :display_name "Mistral Medium 3.5"}]}+ (mt/user-http-request :crowberto :put 200 "metabot/settings"+ {:provider "mistral"+ :api-key "mistral-key-fresh"})))+ (is (= "mistral/mistral-medium-3-5"+ (metabot.settings/llm-metabot-provider)))+ (is (= "mistral-key-fresh"+ (llm.settings/llm-mistral-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 (fndiff --git a/test/metabase/metabot/self/mistral_test.clj b/test/metabase/metabot/self/mistral_test.cljnew file mode 100644index 00000000000..990de069e09--- /dev/null+++ b/test/metabase/metabot/self/mistral_test.clj@@ -0,0 +1,315 @@+(ns metabase.metabot.self.mistral-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.mistral :as mistral]+ [metabase.metabot.test-util :as metabot.tu]+ [metabase.premium-features.core :as premium-features]+ [metabase.test :as mt]))++(set! *warn-on-reflection* true)++;;; ──────────────────────────────────────────────────────────────────+;;; mistral-request-body tests+;;; ──────────────────────────────────────────────────────────────────++(deftest ^:parallel request-body-default-model-test+ (testing "the model defaults to mistral-medium-3-5"+ (is (= "mistral-medium-3-5"+ (:model (mistral/mistral-request-body {:input [{:role :user :content "hi"}]}))))))++(deftest ^:parallel request-body-system-plain-string-test+ (testing "the system prompt stays a plain string"+ (let [body (mistral/mistral-request-body+ {:model "mistral-medium-3-5"+ :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-stream-options-test+ (testing "requests stream but omit stream_options — Mistral 422s on it and reports usage on the final chunk anyway"+ (let [body (mistral/mistral-request-body {:model "mistral-medium-3-5"+ :input [{:role :user :content "hi"}]})]+ (is (true? (:stream body)))+ (is (not (contains? body :stream_options))))))++(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"+ (:prompt_cache_key (mistral/mistral-request-body+ {:model "mistral-medium-3-5"+ :input [{:role :user :content "hi"}]+ :prompt-cache-key "d34d4c93-a5cc-4d5e-b0a6-6b8f89525b48"}))))+ (is (not (contains? (mistral/mistral-request-body {:model "mistral-medium-3-5"+ :input [{:role :user :content "hi"}]})+ :prompt_cache_key)))))++(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"}+ (mistral/mistral-request-body {:model "mistral-medium-3-5"+ :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"}+ (mistral/mistral-request-body {:model "mistral-medium-3-5"+ :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}+ (mistral/mistral-request-body {:model "mistral-medium-3-5"+ :input [{:role :user :content "hi"}]+ :temperature 0.2+ :max-tokens 128})))))++;;; ──────────────────────────────────────────────────────────────────+;;; Streaming chunk conversion tests+;;;+;;; Mistral streams the same Chat Completions chunk dialect the adapter+;;; shares with OpenRouter and Z.AI; these chunks are synthetic but mirror+;;; the shapes Mistral sends: tool calls arriving whole in one delta, and+;;; usage on the final chunk alongside `finish_reason` (no stream_options+;;; needed).+;;; ──────────────────────────────────────────────────────────────────++(deftest ^:parallel mistral-text-conv-test+ (let [chunks [{:id "20260724-1"+ :model "mistral-medium-3-5"+ :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 (mistral/mistral->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 "mistral-medium-3-5"+ :usage {:promptTokens 12 :completionTokens 2}}]+ (into [] (comp (mistral/mistral->aisdk-chunks-xf)+ (self.core/aisdk-xf))+ chunks))))))++(deftest ^:parallel mistral-whole-tool-call-conv-test+ (testing "a tool call arriving whole in one delta 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 (mistral/mistral->aisdk-chunks-xf)+ (self.core/aisdk-xf))+ [{:id "20260724-2"+ :model "mistral-medium-3-5"+ :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 mistral-streamed-tool-call-conv-test+ (testing "tool-call argument deltas accumulate into one tool-input"+ (is (=? [{:type :start}+ {:type :tool-input+ :id "call_2"+ :function "get-time"+ :arguments {:tz "Europe/Kyiv"}}]+ (into [] (comp (mistral/mistral->aisdk-chunks-xf)+ (self.core/aisdk-xf))+ [{:id "20260724-3"+ :model "mistral-medium-3-5"+ :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 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+ ;; a :prompt-cache-key (the conversation id) is present.+ (let [usage (->> (into [] (mistral/mistral->aisdk-chunks-xf)+ [{:id "20260724-4"+ :model "mistral-medium-3-5"+ :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 0}}}])+ (filter #(= :usage (:type %)))+ first)]+ (is (=? {:type :usage+ :id "20260724-4"+ :model "mistral-medium-3-5"+ :usage {:promptTokens 5000+ :completionTokens 7+ :cacheCreationTokens 0+ :cacheReadTokens 0}}+ usage)))))++(deftest ^:parallel mistral-usage-cached-tokens-test+ (testing "prompt-cache reads are extracted from prompt_tokens_details; Mistral reports no cache writes"+ (let [usage (->> (into [] (mistral/mistral->aisdk-chunks-xf)+ [{:id "20260724-5"+ :model "mistral-medium-3-5"+ :choices [{:delta {:role "assistant" :content "OK"}}]}+ {:choices [{:delta {} :finish_reason "stop"}]+ :usage {:prompt_tokens 8060+ :completion_tokens 2+ :total_tokens 8062+ :prompt_tokens_details {:cached_tokens 8048}}}])+ (filter #(= :usage (:type %)))+ first)]+ (is (=? {:type :usage+ :id "20260724-5"+ :model "mistral-medium-3-5"+ :usage {:promptTokens 8060+ :completionTokens 2+ :cacheCreationTokens 0+ :cacheReadTokens 8048}}+ usage)))))++;;; ──────────────────────────────────────────────────────────────────+;;; Auth tests+;;; ──────────────────────────────────────────────────────────────────++(deftest mistral-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-mistral-api-key "mistral-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.mistral.ai/v1/chat/completions"+ :headers {"Authorization" "Bearer mistral-key-byok"}+ :body string?}+ (mistral/mistral-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-mistral-api-key nil]+ (is (thrown-with-msg?+ clojure.lang.ExceptionInfo+ #"No Mistral API key is set"+ (mistral/mistral-raw {:input [{:role :user :content "hi"}]})))))+ (testing "Throws an error if nothing is defined"+ (mt/with-temporary-setting-values [llm.settings/llm-mistral-api-key nil+ llm.settings/llm-proxy-base-url nil]+ (is (thrown-with-msg?+ clojure.lang.ExceptionInfo+ #"No Mistral API key is set"+ (mistral/mistral-raw {:input [{:role :user :content "hi"}]})))))))))++(deftest mistral-raw-ai-proxy-unsupported-test+ (testing "ai-proxy? throws before credentials are even consulted"+ (mt/with-temporary-setting-values [llm.settings/llm-mistral-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 Mistral"+ (mistral/mistral-raw {:model "mistral-medium-3-5"+ :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-mistral-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 Mistral"+ (mistral/list-models {:ai-proxy? true})))))))++;;; ──────────────────────────────────────────────────────────────────+;;; list-models tests+;;; ──────────────────────────────────────────────────────────────────++(deftest list-models-filters-catalog-to-whitelist-test+ (testing "list-models keeps only whitelisted models with the whitelist display name"+ (mt/with-temporary-setting-values [llm.settings/llm-mistral-api-key "mistral-key-test"]+ (mt/with-dynamic-fn-redefs [http/request (fn [req]+ (is (=? {:method :get+ :url "https://api.mistral.ai/v1/models"+ :headers {"Authorization" "Bearer mistral-key-test"}}+ req))+ {:status 200 :body {:data [{:id "mistral-large-2512"}+ {:id "mistral-medium-3-5"}+ {:id "codestral-2508"}]}})]+ (is (= {:models [{:id "mistral-medium-3-5" :display_name "Mistral Medium 3.5"}]}+ (mistral/list-models)))))))++(deftest list-models-matches-aliases-and-dedupes-test+ (testing "a catalog entry whose alias is whitelisted resolves to the whitelisted id, deduped across entries"+ (mt/with-temporary-setting-values [llm.settings/llm-mistral-api-key "mistral-key-test"]+ (mt/with-dynamic-fn-redefs [http/request (fn [_]+ {:status 200+ :body {:data [{:id "mistral-medium-latest"+ :aliases ["mistral-medium-3-5"]}+ {:id "mistral-medium-3-5"+ :aliases ["mistral-medium-latest"]}]}})]+ (is (= {:models [{:id "mistral-medium-3-5" :display_name "Mistral Medium 3.5"}]}+ (mistral/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-mistral-api-key "mistral-key-setting"]+ (mt/with-dynamic-fn-redefs [http/request (fn [req]+ (is (=? {:headers {"Authorization" "Bearer mistral-key-explicit"}}+ req))+ {:status 200 :body {:data []}})]+ (is (= {:models []}+ (mistral/list-models {:credentials {:api-key "mistral-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-mistral-api-key "mistral-key-setting"]+ (mt/with-dynamic-fn-redefs [http/request (fn [req]+ (is (=? {:headers {"Authorization" "Bearer mistral-key-setting"}}+ req))+ {:status 200 :body {:data []}})]+ (is (= {:models []}+ (mistral/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-mistral-api-key nil]+ (is (thrown-with-msg?+ clojure.lang.ExceptionInfo+ #"No Mistral API key is set"+ (mistral/list-models {:credentials {:api-key ""}}))))))++(deftest list-models-401-maps-to-invalid-key-message-test+ (testing "a 401 from Mistral surfaces as the canonical invalid-key message"+ (mt/with-temporary-setting-values [llm.settings/llm-mistral-api-key "mistral-key-expired"]+ (mt/with-dynamic-fn-redefs [http/request (fn [_]+ (throw (ex-info "clj-http: status 401"+ {:status 401+ :body "{\"message\":\"Unauthorized\"}"})))]+ (is (thrown-with-msg?+ clojure.lang.ExceptionInfo+ #"Mistral API key expired or invalid"+ (mistral/list-models)))))))diff --git a/test/metabase/metabot/self_test.clj b/test/metabase/metabot/self_test.cljindex a2b2e6f40f9..32403c810ec 100644--- a/test/metabase/metabot/self_test.clj+++ b/test/metabase/metabot/self_test.clj@@ -35,7 +35,9 @@(is (=? {:provider "openrouter" :model "google/gemini-2.5-flash" :ai-proxy? false}(#'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"))))+ (#'self/parse-provider-model "zai/glm-5.2")))+ (is (=? {:provider "mistral" :model "mistral-medium-3-5" :ai-proxy? false}+ (#'self/parse-provider-model "mistral/mistral-medium-3-5"))))(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")))@@ -53,7 +55,8 @@(is (fn? (#'self/resolve-adapter "anthropic")))(is (fn? (#'self/resolve-adapter "openai")))(is (fn? (#'self/resolve-adapter "openrouter")))- (is (fn? (#'self/resolve-adapter "zai"))))+ (is (fn? (#'self/resolve-adapter "zai")))+ (is (fn? (#'self/resolve-adapter "mistral"))))(testing "throws for unknown provider"(is (thrown-with-msg? clojure.lang.ExceptionInfo #"Unknown LLM provider"(#'self/resolve-adapter "unknown")))))@@ -87,6 +90,89 @@(throw e))))(is (= expected (:tool_choice @captured))))))))))+(deftest call-llm-prompt-cache-key-test+ (testing "the conversation id (:session-id) is forwarded as the Mistral prompt_cache_key"+ (let [captured (atom nil)]+ ;; `:api-error true` makes `rethrow-api-error!` rethrow as-is, so `::skip` survives on the outer ex-data.+ (mt/with-dynamic-fn-redefs [http/request (fn [opts]+ (when (:body opts)+ (reset! captured (json/decode+kw (:body opts))))+ (throw (ex-info "stop" {::skip true :api-error true})))]+ (mt/with-temporary-setting-values [llm-mistral-api-key "mistral-key-test"]+ (let [call! (fn [tracking-opts]+ (reset! captured nil)+ (try+ (run! identity (self/call-llm "mistral/mistral-medium-3-5" nil [] {} tracking-opts))+ (catch Exception e+ (when-not (::skip (ex-data e))+ (throw e)))))]+ (call! {:tag "agent" :session-id "d34d4c93-a5cc-4d5e-b0a6-6b8f89525b48"})+ (is (= "d34d4c93-a5cc-4d5e-b0a6-6b8f89525b48" (:prompt_cache_key @captured)))+ (testing "no prompt_cache_key without a :session-id"+ (call! {:tag "agent"})+ (is (not (contains? @captured :prompt_cache_key))))))))))++(deftest call-llm-structured-prompt-cache-key-test+ (testing "call-llm-structured forwards :session-id as the prompt_cache_key, same contract as call-llm"+ (let [captured (atom nil)]+ ;; `:api-error true` makes `rethrow-api-error!` rethrow as-is, so `::skip` survives on the outer ex-data.+ (mt/with-dynamic-fn-redefs [http/request (fn [opts]+ (when (:body opts)+ (reset! captured (json/decode+kw (:body opts))))+ (throw (ex-info "stop" {::skip true :api-error true})))]+ (mt/with-temporary-setting-values [llm-mistral-api-key "mistral-key-test"]+ (let [call! (fn [tracking-opts]+ (reset! captured nil)+ (try+ (self/call-llm-structured "mistral/mistral-medium-3-5"+ [{:role "user" :content "hi"}]+ {:type "object" :properties {:title {:type "string"}}}+ nil+ 128+ tracking-opts)+ (catch Exception e+ (when-not (::skip (ex-data e))+ (throw e)))))]+ (call! {:tag "conversation-title" :session-id "d34d4c93-a5cc-4d5e-b0a6-6b8f89525b48"})+ (is (= "d34d4c93-a5cc-4d5e-b0a6-6b8f89525b48" (:prompt_cache_key @captured)))+ (testing "no prompt_cache_key without a :session-id"+ (call! {:tag "example-question-generation"})+ (is (not (contains? @captured :prompt_cache_key))))))))))++(deftest call-llm-prompt-cache-key-not-leaked-to-other-providers-test+ (testing "call-llm hands :prompt-cache-key to every adapter, but only mistral forwards it to the wire"+ (let [captured (atom nil)]+ (mt/with-premium-features #{:metabase-ai-managed}+ ;; `:api-error true` makes `rethrow-api-error!` rethrow as-is, so `::skip` survives on the outer ex-data.+ (mt/with-dynamic-fn-redefs [http/request (fn [opts]+ (when (:body opts)+ (reset! captured (json/decode+kw (:body opts))))+ (throw (ex-info "stop" {::skip true :api-error true})))]+ (mt/with-temporary-setting-values [llm-anthropic-api-key "sk-ant-test-key"+ llm-proxy-base-url "http://proxy.example"+ llm-openrouter-api-key "sk-or-v1-test-key"+ llm-openai-api-key "sk-test-key"+ llm-zai-api-key "zai-key.test"]+ (doseq [model ["anthropic/test-model"+ "metabase/anthropic/claude-sonnet-4-6"+ "openrouter/test-model"+ "openai/test-model"+ "zai/glm-5.2"]]+ (testing model+ (reset! captured nil)+ (try+ (run! identity (self/call-llm model+ nil+ []+ {}+ {:tag "agent" :session-id "d34d4c93-a5cc-4d5e-b0a6-6b8f89525b48"}))+ (catch Exception e+ (when-not (::skip (ex-data e))+ (throw e))))+ (is (map? @captured))+ (is (not (contains? @captured :prompt_cache_key)))+ (is (not (contains? @captured :prompt-cache-key)))))))))))+;;; utils tests(deftest sse-reducible-testdiff --git a/test/metabase/metabot/settings_test.clj b/test/metabase/metabot/settings_test.cljindex 2d3e62c63c9..cfb16335980 100644--- a/test/metabase/metabot/settings_test.clj+++ b/test/metabase/metabot/settings_test.clj@@ -172,6 +172,13 @@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-direct-only-provider-as-managed-mistral-test+ (testing "rejects mistral 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 \"mistral\" for metabase managed AI"+ (metabot.settings/llm-metabot-provider! "metabase/mistral/mistral-medium-3-5"))))))+(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}@@ -207,6 +214,11 @@(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-valid-direct-mistral-test+ (testing "accepts valid direct mistral provider string"+ (mt/with-temporary-setting-values [llm-metabot-provider "mistral/mistral-medium-3-5"]+ (is (= "mistral/mistral-medium-3-5" (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}@@ -269,6 +281,14 @@(mt/with-temporary-setting-values [llm-zai-api-key nil](is (nil? (metabot.settings/configured-provider-credentials "zai"))))))+(deftest configured-provider-credentials-mistral-test+ (testing "returns the api-key map when a mistral key is configured, nil when blank or missing"+ (mt/with-temporary-setting-values [llm-mistral-api-key "mistral-key-test"]+ (is (= {:api-key "mistral-key-test"}+ (metabot.settings/configured-provider-credentials "mistral"))))+ (mt/with-temporary-setting-values [llm-mistral-api-key nil]+ (is (nil? (metabot.settings/configured-provider-credentials "mistral"))))))+(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"