Skip to content

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

Support Model Garden endpoints on the Google provider (#82276)

Andrei Simionescu912b2ba3b9bc
diff --git a/docs/ai/providers.md b/docs/ai/providers.md
index 66f30afb843..479b2dd3742 100644
--- a/docs/ai/providers.md
+++ b/docs/ai/providers.md
@@ -209,10 +209,23 @@ Credentials:
- **Authentication method** (required). Authenticate with a service account key or an OAuth access token. One of: `Service account key`, `OAuth token`. Defaults to `Service account key`.
- **Service account key file**. Only when **Authentication method** is **Service account key**. Upload a service account key file to authenticate with. [Where do I find this?](https://docs.cloud.google.com/iam/docs/keys-create-delete) You can also set it with the environment variable `MB_LLM_GOOGLE_SERVICE_ACCOUNT_KEY`.
- **OAuth access token**. Only when **Authentication method** is **OAuth token**. A short-lived token, e.g. the output of gcloud auth print-access-token. Useful for testing. You can also set it with the environment variable `MB_LLM_GOOGLE_OAUTH_ACCESS_TOKEN`.
+- **Model Garden endpoint ID**. Optional. Use an open model you deployed from Model Garden instead of one Google hosts. Set the location to the region you deployed it to.
- **API base URL** (advanced). Derived from the location when left at the global host. Defaults to `https://aiplatform.googleapis.com`. You can also set it with the environment variable `MB_LLM_GOOGLE_API_BASE_URL`.
Google Gemini Enterprise needs either **Service account key file**, or **OAuth access token** and **Project ID**.
+### Connect an open model from Model Garden
+
+You can also run Metabot on an open model, like GLM or Llama, that you deployed from [Model Garden](https://cloud.google.com/model-garden). Metabase talks to the endpoint the deployment created through its OpenAI-compatible Chat Completions API, with the credentials above, and finds a dedicated endpoint's own DNS name for you.
+
+To connect it, add a Google Gemini Enterprise provider in **Admin > AI**, enter the endpoint's ID in **Model Garden endpoint ID**, and set **Location** to the region you deployed to. That connection serves the endpoint instead of the models above: connecting checks the endpoint, and the model picker offers the endpoint as the connection's only model. To use the models above too, add a second Google Gemini Enterprise provider without an endpoint ID, and pick between them in the model picker.
+
+If you configure the Google connection with environment variables, it has no endpoint ID. Set `MB_LLM_METABOT_PROVIDER` to `google/endpoints/` followed by the endpoint's ID instead.
+
+The credentials need `aiplatform.endpoints.get` to look up the endpoint and `aiplatform.endpoints.predict` to run it.
+
+Metabot calls tools and sends long prompts, so deploy the model with tool calling turned on (for vLLM, `--enable-auto-tool-choice` and a `--tool-call-parser` that matches the model) and a context length of at least 16,384 tokens, the minimum Metabase also requires of a vLLM connection. Metabase doesn't check either one when you connect.
+
## Microsoft Azure
- Provider key: `azure`
diff --git a/frontend/src/metabase-types/api/llm.ts b/frontend/src/metabase-types/api/llm.ts
index a4b8174f1e0..eaa695ed002 100644
--- a/frontend/src/metabase-types/api/llm.ts
+++ b/frontend/src/metabase-types/api/llm.ts
@@ -77,6 +77,7 @@ export interface LlmProviderType {
available: boolean;
default_model: string | null;
models: LlmModel[];
+ model_fields: string[];
required_any: string[][];
requires: Record<string, string[]>;
fields: LlmProviderField[];
diff --git a/frontend/src/metabase-types/api/mocks/llm.ts b/frontend/src/metabase-types/api/mocks/llm.ts
index a0ae6657983..c86b4cd1948 100644
--- a/frontend/src/metabase-types/api/mocks/llm.ts
+++ b/frontend/src/metabase-types/api/mocks/llm.ts
@@ -27,6 +27,7 @@ export const createMockLlmProviderType = (
available: true,
default_model: null,
models: [],
+ model_fields: [],
required_any: [],
requires: {},
fields: [createMockLlmProviderField()],
diff --git a/frontend/src/metabase/metabot/components/AIProviderConfigurationForm/ProviderConnectionForm.tsx b/frontend/src/metabase/metabot/components/AIProviderConfigurationForm/ProviderConnectionForm.tsx
index 54f45fea50e..abab58e242f 100644
--- a/frontend/src/metabase/metabot/components/AIProviderConfigurationForm/ProviderConnectionForm.tsx
+++ b/frontend/src/metabase/metabot/components/AIProviderConfigurationForm/ProviderConnectionForm.tsx
@@ -169,6 +169,10 @@ export function ProviderConnectionForm({
Object.entries(providerType.requires).every(
([key, deps]) => !hasValue(key) || deps.every(hasValue),
);
+ const hasConfiguredModel =
+ providerType != null &&
+ providerType.model_fields.length > 0 &&
+ providerType.model_fields.every(hasValue);
const handleSave = async () => {
if (!providerType) {
@@ -184,19 +188,20 @@ export function ProviderConnectionForm({
...config,
...Object.fromEntries(cleared.map((key) => [key, ""])),
};
+ const savedModel = hasConfiguredModel ? undefined : model;
try {
const saved = isEditing
? await updateProvider({
key: connection.key,
name,
config: savedConfig,
- model,
+ model: savedModel,
}).unwrap()
: await createProvider({
type: providerType.type,
name,
config: savedConfig,
- model,
+ model: savedModel,
}).unwrap();
onSaved(saved);
} catch (caught) {
@@ -247,7 +252,7 @@ export function ProviderConnectionForm({
disabledFields={connection?.env_fields}
autoFocusFirstField
/>
- {selected.models.length > 0 && (
+ {selected.models.length > 0 && !hasConfiguredModel && (
<Select
label={t`Model`}
description={t`Connecting checks your credentials against this model, and Metabot starts on it.`}
diff --git a/frontend/src/metabase/metabot/components/AIProviderConfigurationForm/ProviderConnectionForm.unit.spec.tsx b/frontend/src/metabase/metabot/components/AIProviderConfigurationForm/ProviderConnectionForm.unit.spec.tsx
index c268ac96da9..d0f06beb10e 100644
--- a/frontend/src/metabase/metabot/components/AIProviderConfigurationForm/ProviderConnectionForm.unit.spec.tsx
+++ b/frontend/src/metabase/metabot/components/AIProviderConfigurationForm/ProviderConnectionForm.unit.spec.tsx
@@ -131,6 +131,7 @@ const GOOGLE_TYPE = createMockLlmProviderType({
display_name: "Claude Sonnet 4.6",
},
],
+ model_fields: ["endpoint-id"],
required_any: [["service-account-key"], ["oauth-access-token", "project-id"]],
fields: [
createMockLlmProviderField({
@@ -165,6 +166,12 @@ const GOOGLE_TYPE = createMockLlmProviderType({
required: false,
show_when: { field: "auth-method", value: "oauth-token" },
}),
+ createMockLlmProviderField({
+ key: "endpoint-id",
+ label: "Model Garden endpoint ID",
+ type: "text",
+ required: false,
+ }),
],
});
@@ -338,6 +345,43 @@ describe("ProviderConnectionForm with fields behind a choice", () => {
model: "google/gemini-3.6-flash",
});
});
+
+ it("connects to a Model Garden endpoint in place of a catalog model", async () => {
+ const { onSaved } = setupGoogle();
+ const key = '{"type":"service_account"}';
+
+ await pickGoogle();
+ await userEvent.upload(
+ screen.getByLabelText("Service account key file file input"),
+ new File([key], "key.json", { type: "application/json" }),
+ );
+ expect(screen.getByLabelText("Model")).toBeInTheDocument();
+
+ await userEvent.type(
+ screen.getByLabelText("Model Garden endpoint ID"),
+ "1234567890123456789",
+ );
+
+ expect(screen.queryByLabelText("Model")).not.toBeInTheDocument();
+
+ await userEvent.click(screen.getByRole("button", { name: "Connect" }));
+
+ await waitFor(() => {
+ expect(onSaved).toHaveBeenCalled();
+ });
+ expect(
+ await fetchMock.callHistory
+ .lastCall("path:/api/llm/providers", { method: "POST" })
+ ?.request?.json(),
+ ).toEqual({
+ type: "google",
+ name: "Google Gemini Enterprise",
+ config: {
+ "service-account-key": key,
+ "endpoint-id": "1234567890123456789",
+ },
+ });
+ });
});
describe("ProviderConnectionForm editing a fixed-catalog connection", () => {
@@ -421,6 +465,39 @@ describe("ProviderConnectionForm editing a fixed-catalog connection", () => {
);
});
+ it("saves a connection that names an endpoint without picking a catalog model", async () => {
+ const { onSaved } = setupGoogle(
+ createMockLlmProviderConnection({
+ key: "google",
+ type: "google",
+ name: "Google Gemini Enterprise",
+ config: {
+ "auth-method": "oauth-token",
+ "oauth-access-token": "**********en",
+ "project-id": "my-project",
+ "endpoint-id": "1234567890123456789",
+ },
+ }),
+ { modelRef: "google/endpoints/1234567890123456789" },
+ );
+
+ expect(
+ await screen.findByLabelText("Model Garden endpoint ID"),
+ ).toHaveValue("1234567890123456789");
+ expect(screen.queryByLabelText("Model")).not.toBeInTheDocument();
+
+ await userEvent.click(screen.getByRole("button", { name: "Save" }));
+
+ await waitFor(() => {
+ expect(onSaved).toHaveBeenCalled();
+ });
+ expect(
+ await fetchMock.callHistory
+ .lastCall("express:/api/llm/providers/:key", { method: "PUT" })
+ ?.request?.json(),
+ ).not.toHaveProperty("model");
+ });
+
it("disables the fields the environment owns and leaves the rest editable", async () => {
setupGoogle(
createMockLlmProviderConnection({
diff --git a/src/metabase/cmd/ai_provider_dox.clj b/src/metabase/cmd/ai_provider_dox.clj
index 9a520bc7c92..04b8b45a3db 100644
--- a/src/metabase/cmd/ai_provider_dox.clj
+++ b/src/metabase/cmd/ai_provider_dox.clj
@@ -20,9 +20,11 @@
(def ^:private provider-notes-resources
"Hand-written prose appended to a provider type's section, keyed by type, for what an admin needs to know that the
registry doesn't hold. The managed provider's covers that it's a Metabase Cloud offering, how it's billed, and how it
- authenticates. Bedrock's covers the IAM actions the mantle endpoint needs and why the model picker is region-scoped."
+ authenticates. Bedrock's covers the IAM actions the mantle endpoint needs and why the model picker is region-scoped.
+ Google's covers connecting a Model Garden endpoint, which its fixed catalog cannot list."
{"metabase" "metabase/cmd/resources/ai-provider-metabase.md"
- "bedrock" "metabase/cmd/resources/ai-provider-bedrock.md"})
+ "bedrock" "metabase/cmd/resources/ai-provider-bedrock.md"
+ "google" "metabase/cmd/resources/ai-provider-google.md"})
(def ^:private dynamic-catalog-types
"Provider types that serve whatever models the operator loaded, so there is no list to publish."
diff --git a/src/metabase/cmd/resources/ai-provider-google.md b/src/metabase/cmd/resources/ai-provider-google.md
new file mode 100644
index 00000000000..7401a0d8ab4
--- /dev/null
+++ b/src/metabase/cmd/resources/ai-provider-google.md
@@ -0,0 +1,11 @@
+### Connect an open model from Model Garden
+
+You can also run Metabot on an open model, like GLM or Llama, that you deployed from [Model Garden](https://cloud.google.com/model-garden). Metabase talks to the endpoint the deployment created through its OpenAI-compatible Chat Completions API, with the credentials above, and finds a dedicated endpoint's own DNS name for you.
+
+To connect it, add a Google Gemini Enterprise provider in **Admin > AI**, enter the endpoint's ID in **Model Garden endpoint ID**, and set **Location** to the region you deployed to. That connection serves the endpoint instead of the models above: connecting checks the endpoint, and the model picker offers the endpoint as the connection's only model. To use the models above too, add a second Google Gemini Enterprise provider without an endpoint ID, and pick between them in the model picker.
+
+If you configure the Google connection with environment variables, it has no endpoint ID. Set `MB_LLM_METABOT_PROVIDER` to `google/endpoints/` followed by the endpoint's ID instead.
+
+The credentials need `aiplatform.endpoints.get` to look up the endpoint and `aiplatform.endpoints.predict` to run it.
+
+Metabot calls tools and sends long prompts, so deploy the model with tool calling turned on (for vLLM, `--enable-auto-tool-choice` and a `--tool-call-parser` that matches the model) and a context length of at least 16,384 tokens, the minimum Metabase also requires of a vLLM connection. Metabase doesn't check either one when you connect.
diff --git a/src/metabase/llm/api/provider.clj b/src/metabase/llm/api/provider.clj
index fb6d35914da..ce4d29840f5 100644
--- a/src/metabase/llm/api/provider.clj
+++ b/src/metabase/llm/api/provider.clj
@@ -51,6 +51,8 @@
;; the fixed catalog, for types whose models cannot be listed from the provider; the connection form offers
;; these so the connect-time credential probe runs against the model the admin actually wants
[:models [:sequential [:map [:id :string] [:display_name :string]]]]
+ ;; the config fields that name a connection's model once all are filled, in place of a pick from `models`
+ [:model_fields [:sequential :string]]
;; alternative credential groups: the connection is complete when one group is filled in full
[:required_any [:sequential [:sequential :string]]]
;; paired credential groups: each must be filled in full or left empty in full
@@ -108,7 +110,7 @@
show-when (assoc :show_when {:field (name (:field show-when)) :value (:value show-when)})))
(defn- provider-type-response
- [{:keys [type label managed? singleton? default-model required-any requires fields]}]
+ [{:keys [type label managed? singleton? default-model model-fields required-any requires fields]}]
{:type type
:label (str label)
:managed (boolean managed?)
@@ -116,6 +118,7 @@
:available (llm.provider/type-available? type)
:default_model default-model
:models (mapv #(select-keys % [:id :display_name]) (llm.provider/fixed-models type))
+ :model_fields (into [] (comp (filter keyword?) (map name)) model-fields)
:required_any (mapv #(mapv name %) required-any)
:requires (into {} (map (fn [[k deps]] [(name k) (mapv name deps)])) requires)
:fields (mapv field-response fields)})
@@ -168,9 +171,9 @@
serves — the `:probed-model` an earlier probe recorded, or the catalog's first entry — which a type is free to
ignore.
- A type that names its model in `:config` (Azure, whose deployments its listing endpoint does not return) makes
- the call for the same reason, but the model it serves comes from the connection rather than from the empty list
- that comes back.
+ A connection that names its model in `:config` (an Azure deployment or a Google Model Garden endpoint, which no
+ listing returns) makes the call for the same reason. That model is the one verified, whichever model the caller or
+ the Metabot selection names, and the only one listed, in place of the type's catalog.
`probe?` asks a type that can check more than its credentials to do so — vLLM exercises the tool calling and
structured output the agent loop depends on against the model it will run on. Only [[verify-credentials!]] sets
@@ -184,7 +187,7 @@
configured-model (llm.provider/connection-model type config)
;; Our best guess at the model to try if caller did not specify a model.
proposed-model (or (:probed-model config) (:id (first fixed)))
- model (or model configured-model (selected-model conn-key))
+ model (or configured-model model (selected-model conn-key))
config-models (cond
configured-model [{:id configured-model
:display_name (last (str/split configured-model #"/"))}]
@@ -290,14 +293,19 @@
(when listed
(swap! models-cache cache/miss (models-cache-key conn) (select-keys listed [:models]))))
+(defn- composed-model-ref
+ "The `connection-key/model` reference to the model `conn`'s own config names, like Azure's deployment or a Google
+ connection's Model Garden endpoint, or nil when the config names none."
+ [{conn-key :key :keys [type config]}]
+ (some->> (llm.provider/connection-model type (llm.provider/with-field-defaults type config))
+ (str conn-key "/")))
+
(defn- connection-model-ref
"The `connection-key/model` reference that points Metabot at `conn`: the model the connection's own config names
- (Azure's deployment) when it has one, and the type's default model otherwise. Nil when the type neither names nor
- defaults to a model."
- [{conn-key :key :keys [type config]}]
- (when-let [model (or (llm.provider/connection-model type (llm.provider/with-field-defaults type config))
- (llm.provider/default-model type))]
- (str conn-key "/" model)))
+ when it has one, and the type's default model otherwise. Nil when the type neither names nor defaults to a model."
+ [{conn-key :key :keys [type] :as conn}]
+ (or (composed-model-ref conn)
+ (some->> (llm.provider/default-model type) (str conn-key "/"))))
(defn- fallback-model-ref
"A model reference to fall back to once the connection Metabot was pointed at is gone: the first remaining
@@ -337,11 +345,13 @@
(defn- select-model-for-new-connection!
"Point Metabot at a freshly created connection when it had nothing usable to run on, so connecting the first
provider leaves the instance working rather than connected-but-with-no-model-selected. An existing selection that
- still resolves is left alone — adding a second provider must not silently switch Metabot over to it."
+ still resolves is left alone: adding a second provider must not silently switch Metabot over to it.
+
+ A model the connection's own config names wins over `requested-model`."
[{conn-key :key :as conn} requested-model]
- (when-let [model-ref (if (not-empty requested-model)
- (str conn-key "/" requested-model)
- (connection-model-ref conn))]
+ (when-let [model-ref (or (composed-model-ref conn)
+ (some->> (not-empty requested-model) (str conn-key "/"))
+ (connection-model-ref conn))]
(repoint-metabot! model-ref)))
(defn- follow-edited-connection-model!
@@ -356,9 +366,8 @@
An explicitly pinned mini model moves with a composed model the same way — its reference goes just as stale —
but not with a pick, which changes what the admin prefers rather than what the connection can serve. A derived
mini model needs no help, since it follows the Metabot selection on its own."
- [{conn-key :key :keys [type config] :as conn} requested-model]
- (let [composed-ref (when (llm.provider/connection-model type (llm.provider/with-field-defaults type config))
- (connection-model-ref conn))
+ [{conn-key :key :keys [type] :as conn} requested-model]
+ (let [composed-ref (composed-model-ref conn)
picked-ref (when (and (not-empty requested-model) (seq (llm.provider/fixed-models type)))
(str conn-key "/" requested-model))
metabot-ref (metabot.settings/llm-metabot-provider)
diff --git a/src/metabase/llm/provider.clj b/src/metabase/llm/provider.clj
index 20b73e79491..88575a36805 100644
--- a/src/metabase/llm/provider.clj
+++ b/src/metabase/llm/provider.clj
@@ -192,6 +192,8 @@
{:id "anthropic/claude-sonnet-5" :display_name "Claude Sonnet 5"}
{:id "anthropic/claude-sonnet-4-6" :display_name "Claude Sonnet 4.6"}
{:id "anthropic/claude-haiku-4-5@20251001" :display_name "Claude Haiku 4.5"}]
+ ;; A connection with an endpoint ID serves that Model Garden endpoint instead of the catalog.
+ :model-fields ["endpoints" :endpoint-id]
;; A service account key authenticates on its own (it can carry the project); an OAuth token needs the project
;; named beside it.
:required-any [[:service-account-key] [:oauth-access-token :project-id]]
@@ -236,6 +238,11 @@
:show-when {:field :auth-method :value "oauth-token"}
:placeholder "ya29..."
:help (deferred-tru "A short-lived token, e.g. the output of gcloud auth print-access-token. Useful for testing.")}
+ {:key :endpoint-id
+ :label (deferred-tru "Model Garden endpoint ID")
+ :type :text
+ :placeholder "1234567890123456789"
+ :help (deferred-tru "Optional. Use an open model you deployed from Model Garden instead of one Google hosts. Set the location to the region you deployed it to.")}
{:key :base-url
:normalize strip-trailing-slashes
:validate llm.provider.settings/llm-url-problem
@@ -422,8 +429,9 @@
(:models (provider-type type-name)))
(defn model-fields
- "The `:config` keys whose values compose the model a connection of `type-name` serves, for types whose models
- cannot be listed from the provider. Returns nil for types whose catalog is fetched or fixed."
+ "The parts that compose the model a connection names in its own `:config`, for models the provider cannot list.
+ Each part is a `:config` key, or a string that stands for itself like the `endpoints` in Google's `endpoints/{id}`.
+ Returns nil for types whose connections only serve a fetched or fixed catalog."
[type-name]
(:model-fields (provider-type type-name)))
@@ -444,12 +452,12 @@
;;; -------------------------------------------------- Validation --------------------------------------------------
(defn connection-model
- "The model `config` names, composed from its type's [[model-fields]] — Azure's `{family}/{deployment}` comes from
- two inputs so the admin picks the family rather than typing it as a prefix. Returns nil for types that list their
- models, and for a connection that has not filled every part in yet."
+ "The model `config` names, composed from its type's [[model-fields]], or nil when it names none.
+ Azure's `{family}/{deployment}` comes from two inputs so the admin picks the family rather than typing it as a
+ prefix. A connection that leaves a part blank names no model, which for Google means it serves the catalog."
[type-name config]
(when-let [field-keys (seq (model-fields type-name))]
- (let [parts (map #(u/trimmed-string (get config %)) field-keys)]
+ (let [parts (map #(if (string? %) % (u/trimmed-string (get config %))) field-keys)]
(when (every? some? parts)
(str/join "/" parts)))))
diff --git a/src/metabase/metabot/self/core.clj b/src/metabase/metabot/self/core.clj
index f68f049b418..37189252fd4 100644
--- a/src/metabase/metabot/self/core.clj
+++ b/src/metabase/metabot/self/core.clj
@@ -173,6 +173,7 @@
[:location {:optional true} [:maybe :string]]
[:auth-method {:optional true} [:maybe :string]]
[:base-url {:optional true} [:maybe :string]]
+ [:endpoint-id {:optional true} [:maybe :string]]
;; recorded by the connect-time probe, not entered by the admin
[:probed-model {:optional true} [:maybe :string]]])
diff --git a/src/metabase/metabot/self/google.clj b/src/metabase/metabot/self/google.clj
index 1cd20865fdd..ae0c3a6600a 100644
--- a/src/metabase/metabot/self/google.clj
+++ b/src/metabase/metabot/self/google.clj
@@ -2,13 +2,16 @@
"Google Gemini Enterprise Agent Platform (formerly Vertex AI) provider.
This namespace handles credentials, endpoint URLs, HTTP calls, error translation, and connect-time model validation.
- Wire-format translation is in [[metabase.metabot.self.google.stream-generate-content]]
- and [[metabase.metabot.self.google.raw-predict]].
+ Wire-format translation is in [[metabase.metabot.self.google.stream-generate-content]],
+ [[metabase.metabot.self.google.raw-predict]] and, for Model Garden endpoints, [[metabase.metabot.self.vllm]].
Like openrouter and azure, models for this provider must specify the sub-provider in the `llm-metabot-provider`
setting. For example `MB_LLM_METABOT_PROVIDER=google/google/gemini-3.6-flash`. Gemini models are served by
`streamGenerateContent`; Anthropic partner models (e.g. `google/anthropic/claude-sonnet-4-6`) are served by
- `streamRawPredict`, whose payload is Anthropic's Messages API.
+ `streamRawPredict`, whose payload is Anthropic's Messages API. An open model deployed from Model Garden is named by
+ the endpoint the deployment created (e.g. `google/endpoints/1234567890123456789`) and served by that endpoint's
+ `chat/completions` route, whose payload is the OpenAI-compatible Chat Completions API of the vLLM or SGLang server
+ behind it.
Credentials can be supplied via either a service account key JSON or an OAuth access token.
@@ -34,6 +37,7 @@
[metabase.metabot.self.google.models :as models]
[metabase.metabot.self.google.raw-predict :as raw-predict]
[metabase.metabot.self.google.stream-generate-content :as stream-generate-content]
+ [metabase.metabot.self.vllm :as vllm]
[metabase.util :as u]
[metabase.util.i18n :refer [tru]]
[metabase.util.json :as json]
@@ -259,10 +263,11 @@
:error-code :invalid-project-id}))))
(defn- location-path
- "Returns the URL path to the project's location resource.
+ "Returns the URL path to the project's location resource in API version `api-version`.
This is the parent of every resource that we call."
- [credentials]
- (format "/v1/projects/%s/locations/%s" (effective-project-id credentials) (effective-location credentials)))
+ [credentials api-version]
+ (format "/%s/projects/%s/locations/%s"
+ api-version (effective-project-id credentials) (effective-location credentials)))
(def ^:private max-model-segment-length
"The longest publisher or model ID that belongs in a request path.
@@ -295,9 +300,12 @@
(llm.provider/model-ref->model model))
(def ^:private model-families
- "Map from supported model publishers to their API format."
+ "Map from supported model publishers to their API format.
+ `endpoints` is not a publisher but the resource collection a Model Garden deployment lands in, so a model reads as
+ the tail of its endpoint's resource name."
{"google" :google
- "anthropic" :anthropic})
+ "anthropic" :anthropic
+ "endpoints" :chat-completions})
(def model-publishers
"The publishers whose models this adapter serves."
@@ -319,7 +327,7 @@
(or (model-families (model-publisher model))
(throw (if (str/blank? (model-id model))
(unqualified-model-ex model)
- (ex-info (tru "Unsupported Google model {0}. Only google/* and anthropic/* models are supported."
+ (ex-info (tru "Unsupported Google model {0}. Only google/*, anthropic/* and endpoints/* models are supported."
(pr-str model))
{:api-error true
:status-code 400
@@ -337,13 +345,15 @@
(defn reasoning-model?
"Whether a publisher-qualified `model` streams its reasoning back to us.
+ A Model Garden endpoint serves whatever the admin deployed on it, which its name does not say, so it answers false.
Answers false for a model this adapter cannot serve rather than throwing the way [[model->family]] does: the
`llm-metabot-supports-reasoning?` setting reads this, and a provider setting Metabot cannot use must not take the
public settings endpoint down with it. The request path rejects the same model soon enough."
[model]
(case (model-families (model-publisher model))
- :anthropic (raw-predict/reasoning-model? (model-id model))
- :google (stream-generate-content/reasoning-model? model)
+ :anthropic (raw-predict/reasoning-model? (model-id model))
+ :google (stream-generate-content/reasoning-model? model)
+ :chat-completions false
false))
(mu/defn streams-reasoning? :- :boolean
@@ -354,22 +364,25 @@
(mu/defn context-window-tokens :- [:maybe :int]
"The input context window for a publisher-qualified `model`, or nil when it isn't one we know.
- Gemini windows come from the [[models/catalog]], the same rows that drive the reasoning gate.
+ Gemini windows come from the [[models/catalog]], the same rows that drive the reasoning gate. A Model Garden
+ endpoint's window is whatever the admin deployed with, so it is not known here.
Answers nil for a model this adapter cannot serve rather than throwing the way [[model->family]] does, for the
same reason [[reasoning-model?]] does."
[model :- [:maybe :string]]
(case (model-families (model-publisher model))
- :anthropic (raw-predict/context-window-tokens (model-id model))
- :google (get-in models/catalog [model :context-window])
+ :anthropic (raw-predict/context-window-tokens (model-id model))
+ :google (get-in models/catalog [model :context-window])
+ :chat-completions nil
nil))
(defn- model-resource-path
- "Returns the URL path to a publisher model resource, without the `:method` verb at the end.
- The `model` must include its `{publisher}/{model}` qualifier, e.g. `google/gemini-3.5-flash`.
+ "Returns the URL path to a publisher model or endpoint resource, without the `:method` verb at the end.
+ The `model` must include its `{publisher}/{model}` qualifier, e.g. `google/gemini-3.5-flash` or
+ `endpoints/1234567890123456789`. The path is in API version `v1` unless `api-version` names another.
Both segments become path segments of the request URL, so a character that does not belong in one is rejected here.
[[model->family]] has already settled the publisher by this point; the model ID is still free text."
- [credentials model]
+ [credentials model & {:keys [api-version] :or {api-version "v1"}}]
(let [publisher (model-publisher model)
model-id (model-id model)]
(when (str/blank? model-id)
@@ -382,7 +395,15 @@
{:api-error true
:status-code 400
:error-code :invalid-model})))
- (format "%s/publishers/%s/models/%s" (location-path credentials) publisher model-id)))
+ (if (= :chat-completions (model-families publisher))
+ (format "%s/endpoints/%s" (location-path credentials api-version) model-id)
+ (format "%s/publishers/%s/models/%s" (location-path credentials api-version) publisher model-id))))
+
+(defn- chat-completions-path
+ "Returns the URL path of the `chat/completions` route of the endpoint `model` names.
+ Google defines the route in `v1beta1` only, while the endpoint resource itself is read from `v1`."
+ [credentials model]
+ (str (model-resource-path credentials model :api-version "v1beta1") "/chat/completions"))
(def ^:private provider
"Google is the only adapter whose request path is derived from its credentials rather than fixed, so the path it
@@ -402,6 +423,56 @@
501 #(tru "Google API is not available in this location")
503 #(tru "Google API is temporarily unavailable")}}))
+(defn- fetch-endpoint
+ "Returns the Endpoint resource at `endpoint-path`.
+ https://docs.cloud.google.com/gemini-enterprise-agent-platform/reference/rest/v1/projects.locations.endpoints/get"
+ [credentials endpoint-path]
+ (:body (adapter/request! provider {:method :get
+ :path endpoint-path
+ :as :json
+ :credentials credentials})))
+
+(defn- admin-base-url
+ "Returns the base URL the admin set outright, say a proxy, or nil when the connection uses Google's own hosts."
+ [{:keys [base-url] :as credentials}]
+ (when-let [configured (not-empty base-url)]
+ (when-not (#{llm/google-global-api-base-url (location-host (effective-location credentials))} configured)
+ configured)))
+
+(defn- endpoint-host
+ "Returns the host that serves requests to the endpoint whose resource is `endpoint`.
+
+ A dedicated endpoint answers only on the DNS name its resource reports; the shared regional host refuses it.
+ Google's reference spells that name with a scheme and its samples without one, so either is accepted. A base URL
+ the admin set outright is kept, as it is for every other route: only Google's own hosts are looked past. A shared
+ endpoint is served by the location's host."
+ [credentials endpoint]
+ (let [dns (not-empty (:dedicatedEndpointDns endpoint))]
+ (or (admin-base-url credentials)
+ (when dns (str "https://" (str/replace-first dns #"^https://" "")))
+ (api-base-url credentials))))
+
+(defn- lookup-endpoint-host
+ "Reads the endpoint at `endpoint-path` with `credentials` and returns its [[endpoint-host]]."
+ [credentials endpoint-path]
+ (endpoint-host credentials (fetch-endpoint credentials endpoint-path)))
+
+(def ^:private cached-endpoint-host
+ "Bounded memoization of [[lookup-endpoint-host]].
+ Cached so that the endpoint resource is read once per connection and endpoint, and not once per request. The
+ connection's credentials are the key, which a refreshed access token does not change."
+ (u.memoize/bounded #'lookup-endpoint-host :bounded/threshold 8))
+
+(defn- endpoint-auth
+ "Google's `:auth` for a request to the Model Garden endpoint `model` names: [[google-auth]], sent to the host that
+ serves the endpoint. The host is looked up here, inside the request span like the credentials, and recorded in the
+ volatile `host` for errors to name."
+ [model host]
+ (fn [p {:keys [credentials] :as req}]
+ (let [credentials (resolve-credentials credentials)]
+ (assoc (google-auth p req)
+ :url (vreset! host (cached-endpoint-host credentials (model-resource-path credentials model)))))))
+
(defn- json-content?
"Returns true if an HTTP response has a JSON content type."
[{:keys [headers]}]
@@ -420,9 +491,10 @@
Wraps the descriptor's own message rather than restating it: a status whose message should name the host it was
sent to (see [[include-endpoint-in-msg?]]) gets the endpoint appended, and the endpoint is known only per
- connection, which is why this cannot live on the descriptor."
- [credentials]
- (let [endpoint (delay (try (api-base-url credentials) (catch Exception _ nil)))]
+ connection, which is why this cannot live on the descriptor. The message names `host` when given, and
+ [[api-base-url]] otherwise."
+ [credentials host]
+ (let [endpoint (delay (or host (try (api-base-url credentials) (catch Exception _ nil))))]
(fn [res]
(cond-> ((:error-msg provider) res)
(and (include-endpoint-in-msg? (:status res)) @endpoint)
@@ -432,15 +504,20 @@
"Rethrows a Google HTTP exception like [[core/rethrow-api-error!]], with two changes:
- For a status that satisfies [[include-endpoint-in-msg?]], the message includes the endpoint URL.
- - For 404s include a hint to check that the provided location is correct."
- [credentials e]
+ - For 404s include a hint to check that the provided location is correct.
+
+ `host` is the host an endpoint's resource named, for a request that failed there. The message names it, and there is
+ no hint, since the resource resolved in that location. An exception that is already translated is left as it is."
+ [credentials host e]
(let [data (ex-data e)
location (:location credentials)
known? (conj multi-region-locations global-location)]
(core/rethrow-api-error!
(:slug provider)
- (google-res->msg credentials)
+ (google-res->msg credentials host)
(if (and location
+ (not host)
+ (not (:api-error data))
(= 404 (:status data))
(not (known? location))
(not (json-content? data)))
@@ -508,12 +585,46 @@
(when-not (and (= 400 status) (anthropic-error-body? body))
(throw e))))))
+(def ^:private endpoint-probe-body
+ "The smallest Chat Completions request for the connect-time check of an endpoint: one token, no stream."
+ {:model ""
+ :messages [{:role "user" :content "hi"}]
+ :max_tokens 1})
+
+(defn- validate-endpoint-surface!
+ "Validate `credentials` and `model` for a Model Garden endpoint.
+
+ Read the endpoint resource, which is free and names the endpoint in the URL, so a 2xx proves the credential, the
+ project, the location and the endpoint all resolve. An endpoint still resolves after its model is undeployed, which
+ is how its compute is stopped, so that is checked as well.
+
+ Reading the resource takes only `aiplatform.endpoints.get`, which a viewer role carries without
+ `aiplatform.endpoints.predict`, so with `probe?` a one-token completion on the route conversations use, on the host
+ they use, is what proves the credential can run one. Without `probe?` nothing is generated."
+ [credentials model probe?]
+ (let [endpoint (fetch-endpoint credentials (model-resource-path credentials model))]
+ (when (empty? (:deployedModels endpoint))
+ (throw (ex-info (tru "Nothing is deployed on Google endpoint {0}" (pr-str (model-id model)))
+ {:api-error true
+ :status-code 400
+ :error-code :endpoint-has-no-model})))
+ (when probe?
+ (let [host (endpoint-host credentials endpoint)]
+ (try
+ (adapter/request! provider {:method :post
+ :path (chat-completions-path credentials model)
+ :body (json/encode endpoint-probe-body)
+ :credentials (assoc credentials :base-url host)})
+ (catch Exception e
+ (rethrow-google-api-error! credentials host e)))))))
+
(defn- validate-model!
"Validates `model` against the surface that serves it, and discards the response."
- [credentials model]
+ [credentials model probe?]
(case (model->family model)
- :anthropic (validate-anthropic-surface! credentials model)
- :google (validate-google-surface! credentials model))
+ :anthropic (validate-anthropic-surface! credentials model)
+ :google (validate-google-surface! credentials model)
+ :chat-completions (validate-endpoint-surface! credentials model probe?))
nil)
(mu/defn list-models :- adapter/ModelListing
@@ -525,46 +636,57 @@
https://github.com/googleapis/python-genai/issues/679
`:probe?` reports the model the probe verified as `:connection-info` `:probed-model`, for the connect and edit paths
- to record on the connection and re-verify against later passing it in as the `proposed-model` on future attempts."
+ to record on the connection and re-verify against later passing it in as the `proposed-model` on future attempts.
+ For an endpoint it also runs a one-token completion, where a plain listing only reads the endpoint's resource."
([] (list-models {}))
([{:keys [credentials model proposed-model ai-proxy? probe?]} :- adapter/ListOpts]
(adapter/reject-ai-proxy! provider ai-proxy?)
(if-let [model (or (not-empty model) (not-empty proposed-model))]
(do
(try
- (validate-model! (resolve-credentials credentials) model)
+ (validate-model! (resolve-credentials credentials) model probe?)
(catch Exception e
- (rethrow-google-api-error! credentials e)))
+ (rethrow-google-api-error! credentials nil e)))
(cond-> {:models []}
probe? (assoc :connection-info {:probed-model model})))
{:models []})))
(mu/defn google-raw
"Makes a streaming request to the Gemini Enterprise Agent Platform.
- Gemini models stream through `streamGenerateContent`; Anthropic partner models through `streamRawPredict`.
+ Gemini models stream through `streamGenerateContent`; Anthropic partner models through `streamRawPredict`; Model
+ Garden endpoints through their `chat/completions` route.
`:ai-proxy?` is not supported and throws when it is true."
[{:keys [model credentials] :as opts
:or {model default-model}} :- core/LLMRequestOpts]
(let [family (model->family model)
- opts (assoc opts :model model)]
- (adapter/stream! provider opts
+ opts (assoc opts :model model)
+ host (volatile! nil)]
+ (adapter/stream! (cond-> provider
+ (= :chat-completions family) (assoc :auth (endpoint-auth model host)))
+ opts
{;; a thunk, not a string: the project and the location are URL segments, so the path cannot be
;; built until the credentials resolve, and that resolution is the only one in the fleet that
;; can fail. [[adapter/stream!]] calls it inside the span and behind the proxy refusal, so a
;; bad project ID lands on the trace and a proxied request still hears about the proxy first.
- :path #(str (model-resource-path (resolve-credentials credentials) model)
- (case family
- :anthropic raw-predict-method
- :google generate-content-method))
+ :path #(let [credentials (resolve-credentials credentials)]
+ (if (= :chat-completions family)
+ (chat-completions-path credentials model)
+ (str (model-resource-path credentials model)
+ (case family
+ :anthropic raw-predict-method
+ :google generate-content-method))))
:body (case family
- :anthropic (raw-predict/request-body (model-id model) opts)
+ :anthropic (raw-predict/request-body (model-id model) opts)
;; `opts` carries the defaulted model: the thinking directive keys off it
- :google (stream-generate-content/request-body opts))
+ :google (stream-generate-content/request-body opts)
+ ;; the endpoint serves one model, and Model Garden's OpenAI client samples
+ ;; send an empty `model`
+ :chat-completions (assoc (vllm/vllm-request-body opts) :model ""))
:span-attrs {:family (name family)}
;; both read only `:location`, which resolution does not touch, so the raw map serves and
;; neither can mask a resolution failure with one of its own
- :error-msg (google-res->msg credentials)
- :on-request-error #(rethrow-google-api-error! credentials %)})))
+ :error-msg #((google-res->msg credentials @host) %)
+ :on-request-error #(rethrow-google-api-error! credentials @host %)})))
(defn google
"Call the Gemini Enterprise Agent Platform, return AISDK stream."
@@ -574,6 +696,7 @@
;; Keep this dispatch in sync with `google-raw`, which independently uses
;; `model->family` to select the request protocol.
(eduction (case (model->family model)
- :anthropic (raw-predict/->aisdk-chunks-xf)
- :google (stream-generate-content/->aisdk-chunks-xf))
+ :anthropic (raw-predict/->aisdk-chunks-xf)
+ :google (stream-generate-content/->aisdk-chunks-xf)
+ :chat-completions (vllm/vllm->aisdk-chunks-xf))
raw)))
diff --git a/src/metabase/metabot/self/openai/chat_completions.clj b/src/metabase/metabot/self/openai/chat_completions.clj
index ee5ef704d4e..08c299cfcb7 100644
--- a/src/metabase/metabot/self/openai/chat_completions.clj
+++ b/src/metabase/metabot/self/openai/chat_completions.clj
@@ -171,7 +171,7 @@
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
+ :usage, :error
Chat Completions has no explicit start/stop events per content block like
Claude or OpenAI Responses do — we infer transitions from the delta shape.
@@ -183,7 +183,8 @@
would lose their arguments, since neither the start branch (needs `:name`) nor
the argument-delta branch (needs no `:id`) would fire.
- Takes the dialect's `finish_reason` table, defaulting to OpenAI's [[stop-reasons]].
+ Takes the dialect's `finish_reason` table, defaulting to OpenAI's [[stop-reasons]]. A reason the table maps to
+ \"error\" (Mistral's `error`, Z.AI's `network_error`) fails the response the same way an error object does.
`opts` may carry `:forward-reasoning?`, which additionally translates reasoning
deltas (see [[delta-reasoning]]) into :reasoning-start / :reasoning-delta /
@@ -202,25 +203,32 @@
model-name (volatile! nil)
payload (volatile! {}) ;; carried across start/delta/end, same as openai.clj
stop-reason (volatile! nil)
+ clear! (fn []
+ (vreset! current-type nil)
+ (vreset! current-id nil)
+ (vreset! payload {}))
close! (fn [result]
(u/prog1 (rf result (merge {:type (case @current-type
:text :text-end
:reasoning :reasoning-end
:function_call :tool-input-available)}
@payload))
- (vreset! current-type nil)
- (vreset! current-id nil)
- (vreset! payload {})))]
+ (clear!)))]
(fn
([result]
(cond-> result
@current-type (close!)
true (rf)))
- ([result {:keys [id model choices usage] :as _chunk}]
+ ([result {:keys [id model choices usage error] :as _chunk}]
(let [choice (first choices)
delta (:delta choice)
finish-reason (:finish_reason choice)
+ error-text (when (or (some? error)
+ (= "error" (core/stop-reason->finish-reason stop-reasons finish-reason)))
+ (or (:message error)
+ (some-> error pr-str)
+ (tru "The model provider failed to complete the response")))
tool-call (first (:tool_calls delta))
reasoning-md (:reasoning_metadata delta)
;; Determine what kind of content this chunk carries.
@@ -312,6 +320,9 @@
(some? (:arguments (:function tool-call)))) (rf {:type :tool-input-delta
:toolCallId (:toolCallId @payload)
:inputTextDelta (:arguments (:function tool-call))})
+ ;; Closing a tool call runs it, so drop one that an error cuts off
+ (and error-text
+ (= @current-type :function_call)) (u/prog1 (clear!))
;; Finish reason — close whatever is open
(some? finish-reason) (-> (u/prog1
(vreset! stop-reason finish-reason))
@@ -324,7 +335,10 @@
:model @model-name}
@stop-reason
(assoc :finish-reason (core/stop-reason->finish-reason stop-reasons @stop-reason)
- :raw-finish-reason @stop-reason)))))))))))
+ :raw-finish-reason @stop-reason)))
+ ;; An error in the stream, e.g. a failure partway through generation
+ error-text (-> (cond-> @current-type (close!))
+ (rf {:type :error :errorText error-text}))))))))))
;;; Request body
diff --git a/test/metabase/llm/api/provider_test.clj b/test/metabase/llm/api/provider_test.clj
index d3f2b3290f7..c8849d8aa34 100644
--- a/test/metabase/llm/api/provider_test.clj
+++ b/test/metabase/llm/api/provider_test.clj
@@ -125,7 +125,8 @@
(filter #(= "google" (:type %)))
first)
fields (into {} (map (juxt :key identity)) (:fields google))]
- (is (= ["project-id" "location" "auth-method" "service-account-key" "oauth-access-token" "base-url"]
+ (is (= ["project-id" "location" "auth-method" "service-account-key" "oauth-access-token" "endpoint-id"
+ "base-url"]
(map :key (:fields google))))
(is (=? {:type "segmented"
:default "service-account-key"
@@ -151,7 +152,9 @@
{:id "anthropic/claude-sonnet-5" :display_name "Claude Sonnet 5"}
{:id "anthropic/claude-sonnet-4-6" :display_name "Claude Sonnet 4.6"}
{:id "anthropic/claude-haiku-4-5@20251001" :display_name "Claude Haiku 4.5"}]
- (:models google)))))
+ (:models google))))
+ (testing "and the endpoint ID is the field that names a model in place of the catalog"
+ (is (= ["endpoint-id"] (:model_fields google)))))
(testing "the alternative credential groups ride along so the form knows when the config is complete"
(is (= [["service-account-key"] ["oauth-access-token" "project-id"]]
(:required_any google)))))))
@@ -450,6 +453,25 @@
:deployment-name "gpt-4.1-mini"}})
(is (= "azure/openai/gpt-4.1-mini" (metabot.settings/llm-metabot-provider))))))))
+(deftest create-google-connection-with-an-endpoint-verifies-and-selects-the-endpoint-test
+ (doseq [[sent model] [["no model" nil]
+ ["a catalog model beside it" "google/gemini-3.5-flash"]]]
+ (testing (str "with " sent)
+ (let [opts (atom nil)]
+ (mt/with-dynamic-fn-redefs [metabot.self/list-models (fn [_provider {:keys [model] :as o}]
+ (reset! opts o)
+ {:models [] :connection-info {:probed-model model}})]
+ (mt/with-temporary-setting-values [llm-providers []]
+ (mt/with-temporary-raw-setting-values [llm-metabot-provider nil]
+ (mt/user-http-request :crowberto :post 200 "llm/providers"
+ (cond-> {:type "google"
+ :config {:oauth-access-token "ya29.token"
+ :project-id "my-project"
+ :endpoint-id "1234567890123456789"}}
+ model (assoc :model model)))
+ (is (=? {:model "endpoints/1234567890123456789" :probe? true} @opts))
+ (is (= "google/endpoints/1234567890123456789" (metabot.settings/llm-metabot-provider))))))))))
+
(deftest writes-keep-a-stored-connection-the-environment-shadows-test
(testing (str "The environment wins on read, but it must not take the stored credentials with it: they are what "
"the instance falls back to once the variable comes back off.")
@@ -832,16 +854,21 @@
(testing (str "Azure's model reference bakes in the deployment name, so renaming the deployment of the connection "
"Metabot is pointed at has to move the selection with it — otherwise the next request resolves a "
"deployment that no longer exists.")
- (mt/with-dynamic-fn-redefs [metabot.self/list-models (fn [& _] {:models []})]
- (mt/with-temporary-setting-values [llm-providers [(connection "azure" "azure"
- {:api-key "azure-key"
- :base-url "https://r.services.ai.azure.com/openai"
- :model-family "openai"
- :deployment-name "gpt-4.1-mini"})]]
- (mt/with-temporary-raw-setting-values [llm-metabot-provider "azure/openai/gpt-4.1-mini"]
- (mt/user-http-request :crowberto :put 200 "llm/providers/azure"
- {:config {:deployment-name "gpt-4.1"}})
- (is (= "azure/openai/gpt-4.1" (metabot.settings/llm-metabot-provider))))))))
+ (let [checked (atom nil)]
+ (mt/with-dynamic-fn-redefs [metabot.self/list-models (fn [_provider {:keys [model]}]
+ (reset! checked model)
+ {:models []})]
+ (mt/with-temporary-setting-values [llm-providers [(connection "azure" "azure"
+ {:api-key "azure-key"
+ :base-url "https://r.services.ai.azure.com/openai"
+ :model-family "openai"
+ :deployment-name "gpt-4.1-mini"})]]
+ (mt/with-temporary-raw-setting-values [llm-metabot-provider "azure/openai/gpt-4.1-mini"]
+ (mt/user-http-request :crowberto :put 200 "llm/providers/azure"
+ {:config {:deployment-name "gpt-4.1"}})
+ (is (= "azure/openai/gpt-4.1" (metabot.settings/llm-metabot-provider)))
+ (testing "and the edit checks the deployment the connection now names, not the one Metabot was on"
+ (is (= "openai/gpt-4.1" @checked)))))))))
(deftest update-follows-the-model-picked-for-a-fixed-catalog-connection-test
(testing (str "Google's edit form carries a model pick rather than a probe input, so saving with a different "
@@ -862,6 +889,27 @@
:model "google/gemini-3.6-flash"})
(is (= "anthropic/claude-sonnet-4-6" (metabot.settings/llm-metabot-provider)))))))))
+(deftest update-verifies-and-follows-the-endpoint-a-google-connection-names-test
+ (testing "adding an endpoint to the Google connection Metabot runs on checks the endpoint and moves Metabot onto it"
+ (let [opts (atom nil)]
+ (mt/with-dynamic-fn-redefs [metabot.self/list-models (fn [_provider {:keys [model] :as o}]
+ (reset! opts o)
+ {:models [] :connection-info {:probed-model model}})]
+ (mt/with-temporary-setting-values [llm-providers [(connection "google" "google"
+ {:oauth-access-token "ya29.token"
+ :project-id "my-project"
+ :probed-model "google/gemini-3.5-flash"})]]
+ (mt/with-temporary-raw-setting-values [llm-metabot-provider "google/google/gemini-3.5-flash"]
+ (mt/user-http-request :crowberto :put 200 "llm/providers/google"
+ {:config {:endpoint-id "1234567890123456789"}})
+ (is (=? {:model "endpoints/1234567890123456789" :probe? true} @opts))
+ (is (= "endpoints/1234567890123456789" (:probed-model (stored-config "google"))))
+ (is (= "google/endpoints/1234567890123456789" (metabot.settings/llm-metabot-provider)))
+ (testing "and saving it again leaves Metabot there"
+ (mt/user-http-request :crowberto :put 200 "llm/providers/google"
+ {:config {:oauth-access-token "ya29.rotated"}})
+ (is (= "google/endpoints/1234567890123456789" (metabot.settings/llm-metabot-provider))))))))))
+
(deftest ref-writes-leave-an-env-pinned-selection-alone-test
(testing (str "MB_LLM_METABOT_PROVIDER pins the selection, so the automatic follow-ups — pointing Metabot at a "
"first connection, following an edit, falling back after a delete — must not write a value that "
@@ -1313,6 +1361,23 @@
(testing "and the call still happens, because it is what verifies the credentials"
(is (= "openai/gpt-4.1-mini" (:model @listed-with)))))))))
+(deftest models-for-a-google-connection-that-names-an-endpoint-test
+ (testing "a Google connection with a Model Garden endpoint offers that endpoint in place of the catalog"
+ (mt/with-temporary-setting-values [llm-providers [(connection "glm" "google"
+ {:oauth-access-token "ya29.token"
+ :project-id "my-project"
+ :endpoint-id "1234567890123456789"})]]
+ (let [listed-with (atom nil)]
+ (mt/with-dynamic-fn-redefs [metabot.self/list-models (fn [_provider opts]
+ (reset! listed-with opts)
+ {:models []})]
+ (is (= [{:key "glm"
+ :name "glm"
+ :type "google"
+ :models [{:id "endpoints/1234567890123456789" :display_name "1234567890123456789"}]}]
+ (mt/user-http-request :crowberto :get 200 "llm/models")))
+ (is (= "endpoints/1234567890123456789" (:model @listed-with))))))))
+
(deftest models-isolate-per-connection-failures-test
(mt/with-temporary-setting-values [llm-providers [(connection "failing-anthropic" "anthropic" {:api-key "sk-ant-bad"})
(connection "working-openai" "openai" {:api-key "sk-good"})]]
diff --git a/test/metabase/llm/provider_test.clj b/test/metabase/llm/provider_test.clj
index ef0bceddd7c..9c129085eea 100644
--- a/test/metabase/llm/provider_test.clj
+++ b/test/metabase/llm/provider_test.clj
@@ -318,6 +318,10 @@
(is (= "anthropic/claude-sonnet-4-5"
(llm.provider/connection-model "azure" {:model-family "anthropic"
:deployment-name "claude-sonnet-4-5"}))))
+ (testing "Google names a Model Garden endpoint by the collection its ID belongs to, and nothing without an ID"
+ (is (= "endpoints/1234567890123456789"
+ (llm.provider/connection-model "google" {:endpoint-id " 1234567890123456789 "})))
+ (is (nil? (llm.provider/connection-model "google" {:oauth-access-token "ya29.token"}))))
(testing "a half-filled connection names no model rather than a malformed one"
(is (nil? (llm.provider/connection-model "azure" {:model-family "openai"})))
(is (nil? (llm.provider/connection-model "azure" {:model-family "openai"
diff --git a/test/metabase/metabot/self/google_test.clj b/test/metabase/metabot/self/google_test.clj
index a62cd084119..95263afa039 100644
--- a/test/metabase/metabot/self/google_test.clj
+++ b/test/metabase/metabot/self/google_test.clj
@@ -336,7 +336,7 @@
nil
(catch Exception e e))]
(is (= (str "Unsupported Google model " (pr-str model)
- ". Only google/* and anthropic/* models are supported.")
+ ". Only google/*, anthropic/* and endpoints/* models are supported.")
(ex-message e)))
(is (=? {:api-error true
:status-code 400
@@ -353,7 +353,7 @@
(mt/with-dynamic-fn-redefs [http/request (fn [_] (throw (ex-info "should never be called" {})))]
(is (thrown-with-msg?
clojure.lang.ExceptionInfo
- #"Unsupported Google model \"mistralai/mistral-large\"\. Only google/\* and anthropic/\* models are supported\."
+ #"Unsupported Google model \"mistralai/mistral-large\"\. Only google/\*, anthropic/\* and endpoints/\* models are supported\."
(list-models {:model "mistralai/mistral-large"})))))))
(deftest google-raw-anthropic-model-stream-raw-predict-test
@@ -1255,3 +1255,266 @@
clojure.lang.ExceptionInfo
pattern
(list-models {:model "google/gemini-3.5-flash"})))))))))
+
+;;; ──────────────────────────────────────────────────────────────────
+;;; Model Garden endpoint tests
+;;; ──────────────────────────────────────────────────────────────────
+
+(defn- endpoint-resource
+ "A stubbed Endpoint resource for `endpoint-id`, dedicated when `dns` is given."
+ ([endpoint-id] (endpoint-resource endpoint-id nil))
+ ([endpoint-id dns]
+ (cond-> {:name (str "projects/my-project/locations/us-central1/endpoints/" endpoint-id)
+ :displayName "glm-5.2"
+ :deployedModels [{:id "42" :displayName "glm-5.2"}]}
+ dns (assoc :dedicatedEndpointEnabled true :dedicatedEndpointDns dns))))
+
+(defn- stub-endpoint
+ "An `http/request` stub answering the endpoint resource GET with `endpoint` and the chat completions POST with an
+ SSE stream of `events`, recording every request into `calls`."
+ [calls endpoint events]
+ (fn [req]
+ (swap! calls conj req)
+ (if (= :get (:method req))
+ {:status 200 :body endpoint}
+ (sse-response-for events))))
+
+(defn- unique-token
+ "An access token no earlier test has used, so the endpoint host cache it keys starts empty."
+ []
+ (str "ya29." (random-uuid)))
+
+(defn- endpoint-requests!
+ "Run `google-raw` `n` times against a stubbed endpoint in us-central1 and return the requests it issued."
+ [token model endpoint n & {:keys [base-url]}]
+ (let [calls (atom [])]
+ (mt/with-temporary-setting-values [llm.settings/llm-google-oauth-access-token token
+ llm.settings/llm-google-service-account-key nil
+ llm.settings/llm-google-project-id "my-project"
+ llm.settings/llm-google-location "us-central1"
+ llm.settings/llm-google-api-base-url base-url]
+ (mt/with-dynamic-fn-redefs [self.core/sse-reducible identity
+ self.core/reducible-with-api-errors (fn [r _ _] r)
+ debug/capture-stream (fn [r _] r)
+ http/request (stub-endpoint calls endpoint [])]
+ (dotimes [_ n]
+ (google-raw {:model model :input [{:role :user :content "hi"}]}))))
+ @calls))
+
+(deftest google-raw-endpoint-chat-completions-test
+ (testing "an endpoint's resource is read first, then it is served through its chat/completions route on the location's host"
+ (let [token (unique-token)
+ endpoint "1234567890123456789"
+ [get-req post-req :as calls] (endpoint-requests! token (str "endpoints/" endpoint) (endpoint-resource endpoint) 1)]
+ (is (= 2 (count calls)))
+ (is (=? {:method :get
+ :url (str "https://us-central1-aiplatform.googleapis.com/v1/projects/my-project/locations/us-central1"
+ "/endpoints/" endpoint)
+ :headers {"Authorization" (str "Bearer " token)}}
+ get-req))
+ (is (=? {:method :post
+ :url (str "https://us-central1-aiplatform.googleapis.com/v1beta1/projects/my-project"
+ "/locations/us-central1/endpoints/" endpoint "/chat/completions")
+ :headers {"Authorization" (str "Bearer " token)
+ "Content-Type" "application/json"}
+ :as :stream}
+ post-req))
+ (testing "the body is a Chat Completions request with an empty model, since the endpoint serves one"
+ (is (=? {:model ""
+ :stream true
+ :stream_options {:include_usage true}
+ :messages [{:role "user" :content "hi"}]
+ :max_tokens pos-int?}
+ (json/decode+kw (:body post-req))))))))
+
+(deftest google-raw-dedicated-endpoint-host-test
+ (testing "a dedicated endpoint is served on the DNS name its resource reports, in either spelling Google uses, also when the base URL names Google's host for the location"
+ (let [endpoint "2345678901234567890"
+ host (str endpoint ".us-central1-123456789.prediction.vertexai.goog")]
+ (doseq [dns [host (str "https://" host)]
+ base-url [nil "https://us-central1-aiplatform.googleapis.com"]]
+ (testing (pr-str dns base-url)
+ (let [[get-req post-req] (endpoint-requests! (unique-token) (str "endpoints/" endpoint)
+ (endpoint-resource endpoint dns) 1 :base-url base-url)]
+ (is (str/starts-with? (:url get-req) "https://us-central1-aiplatform.googleapis.com/")
+ "the resource itself is read from the shared host")
+ (is (= (str "https://" host "/v1beta1/projects/my-project/locations/us-central1/endpoints/" endpoint
+ "/chat/completions")
+ (:url post-req)))))))))
+
+(deftest google-raw-endpoint-host-cached-test
+ (testing "repeated requests to an endpoint read its resource once, across the access tokens a service account key mints"
+ (let [endpoint "3456789012345678901"
+ sa-key (test-service-account-json (str "cache-" (subs (str (random-uuid)) 0 8)))
+ tokens (atom 0)
+ calls (atom [])]
+ (mt/with-temporary-setting-values [llm.settings/llm-google-oauth-access-token nil
+ llm.settings/llm-google-service-account-key sa-key
+ llm.settings/llm-google-project-id nil
+ llm.settings/llm-google-location "us-central1"]
+ (mt/with-dynamic-fn-redefs [self.core/sse-reducible identity
+ self.core/reducible-with-api-errors (fn [r _ _] r)
+ debug/capture-stream (fn [r _] r)
+ google/fresh-bearer-headers (fn [_]
+ {"Authorization" (str "Bearer t" (swap! tokens inc))})
+ http/request (stub-endpoint calls (endpoint-resource endpoint) [])]
+ (dotimes [_ 2]
+ (google-raw {:model (str "endpoints/" endpoint) :input [{:role :user :content "hi"}]}))))
+ (is (= [:get :post :post] (map :method @calls)))
+ (is (< 1 (count (into #{} (map #(get-in % [:headers "Authorization"])) @calls)))
+ "the token did rotate between the requests"))))
+
+(deftest google-raw-endpoint-keeps-an-explicit-base-url-test
+ (testing "a base URL the admin set is kept for a dedicated endpoint too, the way it is for every other route"
+ (let [endpoint "7890123456789012345"
+ proxy "https://gemini.proxy.example.com"
+ [get-req post-req] (endpoint-requests! (unique-token) (str "endpoints/" endpoint)
+ (endpoint-resource endpoint (str endpoint ".us-central1-123456789.prediction.vertexai.goog"))
+ 1 :base-url proxy)]
+ (is (str/starts-with? (:url get-req) (str proxy "/")))
+ (is (= (str proxy "/v1beta1/projects/my-project/locations/us-central1/endpoints/" endpoint "/chat/completions")
+ (:url post-req))))))
+
+(defn- endpoint-parts-for!
+ "The AISDK parts [[metabase.metabot.self.google/google]] yields for `endpoint` streaming `events`, on the credentials
+ a connection saved by connecting to it resolves to, its endpoint ID and probed model among them."
+ [endpoint events]
+ (mt/with-dynamic-fn-redefs [debug/capture-stream (fn [r _] r)
+ http/request (stub-endpoint (atom []) (endpoint-resource endpoint) events)]
+ (into []
+ (self.core/aisdk-xf)
+ (google {:model (str "endpoints/" endpoint)
+ :input [{:role :user :content "hi"}]
+ :credentials {:auth-method "oauth-token"
+ :oauth-access-token (unique-token)
+ :project-id "my-project"
+ :location "us-central1"
+ :base-url "https://aiplatform.googleapis.com"
+ :endpoint-id endpoint
+ :probed-model (str "endpoints/" endpoint)}}))))
+
+(deftest google-endpoint-stream-test
+ (testing "an endpoint's Chat Completions events off the wire are translated by the vLLM chunk translation"
+ (is (=? [{:type :start :id "chatcmpl-1"}
+ {:type :text :text "Hello"}
+ {:type :usage
+ :model "glm-5.2"
+ :usage {:promptTokens 5 :completionTokens 2}}]
+ (endpoint-parts-for! "4567890123456789012"
+ [{:id "chatcmpl-1" :model "glm-5.2"
+ :choices [{:index 0 :delta {:role "assistant" :content "Hel"} :finish_reason nil}]}
+ {:id "chatcmpl-1" :model "glm-5.2"
+ :choices [{:index 0 :delta {:content "lo"} :finish_reason nil}]}
+ {:id "chatcmpl-1" :model "glm-5.2"
+ :choices [{:index 0 :delta {} :finish_reason "stop"}]}
+ {:id "chatcmpl-1" :model "glm-5.2" :choices []
+ :usage {:prompt_tokens 5 :completion_tokens 2}}])))))
+
+(deftest google-endpoint-stream-error-test
+ (testing "the error vLLM sends when generation fails partway through a stream arrives after the text so far"
+ (is (=? [{:type :start :id "chatcmpl-2"}
+ {:type :text :text "Hello"}
+ {:type :error :error {:message "Internal server error"}}]
+ (endpoint-parts-for! "4567890123456789012"
+ [{:id "chatcmpl-2" :model "glm-5.2"
+ :choices [{:index 0 :delta {:role "assistant" :content "Hel"} :finish_reason nil}]}
+ {:id "chatcmpl-2" :model "glm-5.2"
+ :choices [{:index 0 :delta {:content "lo"} :finish_reason nil}]}
+ {:error {:message "Internal server error" :type "InternalServerError" :param nil :code 500}}])))))
+
+(deftest endpoint-model-knowledge-test
+ (testing "what an endpoint serves is not knowable from its name"
+ (is (false? (google/reasoning-model? "endpoints/1234567890123456789")))
+ (is (nil? (google/context-window-tokens "endpoints/1234567890123456789")))))
+
+(deftest list-models-endpoint-probe-test
+ (testing "list-models reads the endpoint's resource, then runs a one-token completion on the host it names, and reports the endpoint as the probed model"
+ (let [token (unique-token)
+ endpoint "5678901234567890123"
+ host (str endpoint ".us-central1-123456789.prediction.vertexai.goog")
+ calls (atom [])]
+ (mt/with-temporary-setting-values [llm.settings/llm-google-oauth-access-token token
+ llm.settings/llm-google-service-account-key nil
+ llm.settings/llm-google-project-id "my-project"
+ llm.settings/llm-google-location "us-central1"]
+ (mt/with-dynamic-fn-redefs [http/request (stub-endpoint calls (endpoint-resource endpoint host) [])]
+ (is (= {:models []
+ :connection-info {:probed-model (str "endpoints/" endpoint)}}
+ (list-models {:model (str "endpoints/" endpoint) :probe? true})))
+ (is (=? [{:method :get
+ :url (str "https://us-central1-aiplatform.googleapis.com/v1/projects/my-project"
+ "/locations/us-central1/endpoints/" endpoint)
+ :headers {"Authorization" (str "Bearer " token)}}
+ {:method :post
+ :url (str "https://" host "/v1beta1/projects/my-project/locations/us-central1/endpoints/"
+ endpoint "/chat/completions")
+ :headers {"Authorization" (str "Bearer " token)}
+ :body (json/encode {:model "" :messages [{:role "user" :content "hi"}] :max_tokens 1})}]
+ @calls))
+ (testing "a plain model listing reads only the resource"
+ (reset! calls [])
+ (is (= {:models []} (list-models {:model (str "endpoints/" endpoint)})))
+ (is (= [:get] (mapv :method @calls)))))))))
+
+(deftest list-models-endpoint-without-predict-permission-rejected-test
+ (testing "a credential that can read the endpoint but not run it is refused at connect as lacking permissions"
+ (let [endpoint "8901234567890123456"]
+ (mt/with-temporary-setting-values [llm.settings/llm-google-oauth-access-token (unique-token)
+ llm.settings/llm-google-service-account-key nil
+ llm.settings/llm-google-project-id "my-project"
+ llm.settings/llm-google-location "us-central1"]
+ (mt/with-dynamic-fn-redefs [http/request (fn [{:keys [method]}]
+ (if (= :get method)
+ {:status 200 :body (endpoint-resource endpoint)}
+ (throw (ex-info "clj-http: status 403"
+ {:status 403
+ :headers {"content-type" "application/json"}
+ :body (json/encode {:error {:code 403
+ :message "Permission 'aiplatform.endpoints.predict' denied on resource"
+ :status "PERMISSION_DENIED"}})}))))]
+ (let [e (try (list-models {:model (str "endpoints/" endpoint) :probe? true}) nil (catch Exception e e))]
+ (is (= "Google API credentials have insufficient permissions or the API is not enabled for this project"
+ (ex-message e)))
+ (is (=? {:api-error true :status 403} (ex-data e)))))))))
+
+(deftest list-models-endpoint-without-a-deployed-model-rejected-test
+ (testing "an endpoint whose model has been undeployed is refused with a 400 the connection form can show"
+ (let [endpoint "6789012345678901234"]
+ (mt/with-temporary-setting-values [llm.settings/llm-google-oauth-access-token (unique-token)
+ llm.settings/llm-google-service-account-key nil
+ llm.settings/llm-google-project-id "my-project"
+ llm.settings/llm-google-location "us-central1"]
+ (mt/with-dynamic-fn-redefs [http/request (stub-endpoint (atom [])
+ (assoc (endpoint-resource endpoint) :deployedModels [])
+ [])]
+ (let [e (try (list-models {:model (str "endpoints/" endpoint)}) nil (catch Exception e e))]
+ (is (= (str "Nothing is deployed on Google endpoint \"" endpoint "\"") (ex-message e)))
+ (is (=? {:api-error true
+ :status-code 400
+ :error-code :endpoint-has-no-model}
+ (ex-data e)))))))))
+
+(deftest endpoint-host-failure-names-that-host-test
+ (testing "a failure on an endpoint's own host names that host and shows its body, with no location hint"
+ (let [endpoint "9012345678901234567"
+ host (str endpoint ".us-central1-123456789.prediction.vertexai.goog")]
+ (mt/with-temporary-setting-values [llm.settings/llm-google-oauth-access-token (unique-token)
+ llm.settings/llm-google-service-account-key nil
+ llm.settings/llm-google-project-id "my-project"
+ llm.settings/llm-google-location "us-central1"]
+ (mt/with-dynamic-fn-redefs [http/request (fn [{:keys [method]}]
+ (if (= :get method)
+ {:status 200 :body (endpoint-resource endpoint host)}
+ (throw (ex-info "clj-http: status 404"
+ {:status 404
+ :headers {"content-type" "text/html"}
+ :body (java.io.ByteArrayInputStream.
+ (.getBytes html-404-body))}))))]
+ (doseq [[entry-point call] {"connect" #(list-models {:model (str "endpoints/" endpoint) :probe? true})
+ "request" #(google-raw {:model (str "endpoints/" endpoint)
+ :input [{:role :user :content "hi"}]})}]
+ (testing entry-point
+ (let [message (ex-message (try (call) nil (catch Exception e e)))]
+ (is (str/starts-with? message (str "Google API endpoint is unavailable or the model was not found "
+ "(endpoint: https://" host ")")))
+ (is (str/ends-with? message html-404-body))))))))))
diff --git a/test/metabase/metabot/self/openai/chat_completions_test.clj b/test/metabase/metabot/self/openai/chat_completions_test.clj
index 20309c6fac6..f3829a74e4c 100644
--- a/test/metabase/metabot/self/openai/chat_completions_test.clj
+++ b/test/metabase/metabot/self/openai/chat_completions_test.clj
@@ -2,6 +2,7 @@
(:require
[clojure.test :refer :all]
[metabase.metabot.self.core :as self.core]
+ [metabase.metabot.self.mistral :as mistral]
[metabase.metabot.self.openai.chat-completions :as chat-completions]
[metabase.metabot.test-util :as metabot.tu]))
@@ -394,6 +395,58 @@
{:choices [{:index 0 :delta {} :finish_reason "tool_calls"}]}
{:choices [] :usage {:prompt_tokens 127 :completion_tokens 288}}])))))
+(deftest ^:parallel chunks-xf-streamed-error-becomes-an-error-chunk-test
+ (testing "an error sent partway through a stream becomes an error chunk"
+ (doseq [[shape xf error-chunk message]
+ [["vLLM's error envelope"
+ (chat-completions/chat-completions->aisdk-chunks-xf)
+ {:error {:message "Internal server error" :type "InternalServerError" :param nil :code 500}}
+ "Internal server error"]
+ ["OpenRouter's error on a chunk that finishes the choice"
+ (chat-completions/chat-completions->aisdk-chunks-xf)
+ {:id "cmpl-abc123"
+ :object "chat.completion.chunk"
+ :created 1234567890
+ :model "openai/gpt-4o"
+ :provider "openai"
+ :error {:code "server_error" :message "Provider disconnected unexpectedly"}
+ :choices [{:index 0 :delta {:content ""} :finish_reason "error"}]}
+ "Provider disconnected unexpectedly"]
+ ["Mistral's error finish reason, which carries no message"
+ (mistral/mistral->aisdk-chunks-xf)
+ {:id "cmpl-e5cc70bb28c444948073e77776eb30ef"
+ :object "chat.completion.chunk"
+ :created 1702256327
+ :model "mistral-medium-3-5"
+ :choices [{:index 0 :delta {:content ""} :finish_reason "error"}]}
+ "The model provider failed to complete the response"]]]
+ (testing shape
+ (testing "after closing the open text block"
+ (is (=? [{:type :start :messageId "chatcmpl-5"}
+ {:type :text-start}
+ {:type :text-delta :delta "Hel"}
+ {:type :text-end}
+ {:type :error :errorText message}]
+ (into [] xf
+ [{:id "chatcmpl-5"
+ :model "kimi-k2.6"
+ :choices [{:index 0 :delta {:role "assistant" :content "Hel"} :finish_reason nil}]}
+ error-chunk]))))
+ (testing "without making a half-streamed tool call available to run"
+ (is (= [{:type :start :messageId "chatcmpl-5"}
+ {:type :tool-input-start :toolCallId "call-1" :toolName "search"}
+ {:type :tool-input-delta :toolCallId "call-1" :inputTextDelta "{\"query\": \"rev"}
+ {:type :error :errorText message}]
+ (into [] xf
+ [{:id "chatcmpl-5"
+ :model "kimi-k2.6"
+ :choices [{:index 0
+ :delta {:tool_calls [{:index 0
+ :id "call-1"
+ :type "function"
+ :function {:name "search" :arguments "{\"query\": \"rev"}}]}}]}
+ error-chunk]))))))))
+
;;; ──────────────────────────────────────────────────────────────────
;;; models-catalog tests
;;; ──────────────────────────────────────────────────────────────────
diff --git a/test/metabase/metabot/settings_test.clj b/test/metabase/metabot/settings_test.clj
index d9070e2fe0b..63c9c241da9 100644
--- a/test/metabase/metabot/settings_test.clj
+++ b/test/metabase/metabot/settings_test.clj
@@ -402,11 +402,13 @@
(deftest validate-metabot-provider-google-model-format-test
(with-connections [configured-anthropic configured-google]
- (testing "accepts a publisher-qualified model"
+ (testing "accepts a publisher-qualified model, or a Model Garden endpoint"
(mt/with-temporary-setting-values [llm-metabot-provider "google/google/gemini-3.5-flash"]
(is (= "google/google/gemini-3.5-flash" (metabot.settings/llm-metabot-provider))))
(mt/with-temporary-setting-values [llm-metabot-provider "google/anthropic/claude-haiku-4-5@20251001"]
- (is (= "google/anthropic/claude-haiku-4-5@20251001" (metabot.settings/llm-metabot-provider)))))))
+ (is (= "google/anthropic/claude-haiku-4-5@20251001" (metabot.settings/llm-metabot-provider))))
+ (mt/with-temporary-setting-values [llm-metabot-provider "google/endpoints/1234567890123456789"]
+ (is (= "google/endpoints/1234567890123456789" (metabot.settings/llm-metabot-provider)))))))
(deftest validate-metabot-provider-google-rejects-an-unqualified-model-test
(with-connections [configured-anthropic configured-google]
@@ -470,6 +472,12 @@
:base-url "https://my-resource.services.ai.azure.com/openai"})]
(with-selected-model "azure/openai/my-gpt-deployment"
(is (= "azure/openai/my-gpt-deployment" (metabot.settings/llm-mini-model))))))
+ (testing "so does a Google connection that serves a Model Garden endpoint"
+ (with-connections [(connection "google" "google" {:oauth-access-token "ya29.test"
+ :project-id "my-project"
+ :endpoint-id "1234567890123456789"})]
+ (with-selected-model "google/endpoints/1234567890123456789"
+ (is (= "google/endpoints/1234567890123456789" (metabot.settings/llm-mini-model))))))
(testing "so does a model reference naming a connection that does not exist"
(with-connections []
(with-selected-model "gone/some-model"