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
Support Bedrock inference profiles and unlisted Claude models (#83433)
Andrei Simionescud7c6ddb54bea
diff --git a/docs/ai/providers.md b/docs/ai/providers.mdindex b52d478b707..e33e4633c88 100644--- a/docs/ai/providers.md+++ b/docs/ai/providers.md@@ -286,11 +286,12 @@ Credentials:- **Access key ID**. Only together with **Secret access key**. Leave the keys blank to authenticate with the AWS default credentials chain (IRSA, EKS Pod Identity, or instance profile). On Metabase Cloud, Bedrock always authenticates with your own AWS keys. [Where do I find this?](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_access-keys.html) You can also set it with the environment variable `MB_LLM_BEDROCK_ACCESS_KEY_ID`.- **Secret access key**. Only together with **Access key ID**. Required on Metabase Cloud. You can also set it with the environment variable `MB_LLM_BEDROCK_SECRET_ACCESS_KEY`.- **Region**. Pick one from the dropdown in **Admin > AI**. Defaults to `us-east-1`. You can also set it with the environment variable `MB_LLM_BEDROCK_REGION`.+- **Model ID**. Optional. Use an inference profile, or a model that isn't listed for this region, by its ID or ARN.- **Session token** (advanced). Only together with **Access key ID** and **Secret access key**. Only needed for temporary credentials. You can also set it with the environment variable `MB_LLM_BEDROCK_SESSION_TOKEN`.### IAM permissions for Bedrock-Metabase talks to Bedrock through the mantle endpoint, `https://bedrock-mantle.{region}.api.aws`, not through `bedrock-runtime`. Mantle is a separate IAM namespace with its own actions, so a policy written against the `bedrock` prefix won't grant access. Metabase lists models and runs conversations, so it needs `bedrock-mantle:ListModels` and `bedrock-mantle:CreateInference`.+Metabase talks to Bedrock through the mantle endpoint, `https://bedrock-mantle.{region}.api.aws`, unless the connection's **Model ID** sends it to `bedrock-runtime` (see [Use an inference profile](#use-an-inference-profile)). Mantle is a separate IAM namespace with its own actions, so a policy written against the `bedrock` prefix won't grant access. Metabase lists models and runs conversations, so it needs `bedrock-mantle:ListModels` and `bedrock-mantle:CreateInference`.Here's a least-privilege policy that grants both:@@ -313,13 +314,38 @@ If Metabase reports "AWS Bedrock credentials lack permission for this model or a### The Bedrock models you can pick depend on the region-The table above lists the models Metabase can use. The **Models** card only offers the ones Bedrock serves in the connection's region, so what you can pick depends on the region. The mantle catalog has no cross-region inference profiles, so a model that isn't served in your region can't be reached from that region at all.+The table above lists the models Metabase can use. The **Models** card only offers the ones Bedrock serves in the connection's region, so what you can pick depends on the region. The mantle catalog has no cross-region inference profiles, so to reach a model that isn't served in your region, [use an inference profile](#use-an-inference-profile).If the model list is empty or shorter than you expect after connecting:- **Check the region**: the **Region** dropdown lists every AWS region, including regions where Bedrock serves none of these models. The [AWS model cards](https://docs.aws.amazon.com/bedrock/latest/userguide/model-cards.html) show where each model is available. For example, the GPT models are only served in US regions.- **Check your account's data retention setting**: Bedrock marks a model unavailable when your account's data retention mode doesn't meet what that model requires. For example, [Claude Fable 5](https://docs.aws.amazon.com/bedrock/latest/userguide/model-card-anthropic-claude-fable-5.html) requires the `aws_review` data retention mode.+### Use an inference profile++To use an [inference profile](https://docs.aws.amazon.com/bedrock/latest/userguide/inference-profiles.html), or a Claude model that isn't listed for your region, enter its ID or ARN in **Model ID**, like `eu.anthropic.claude-sonnet-4-6` or `us.anthropic.claude-haiku-4-5-20251001-v1:0`. That connection serves this model instead of the models above: connecting checks it by generating a single token, and the model picker offers it as the connection's only model. To use the models above too, add a second Amazon Bedrock provider without a model ID.++Metabase sends inference profile IDs, ARNs, and model IDs with a version suffix like `-v1:0` to `bedrock-runtime`, `https://bedrock-runtime.{region}.amazonaws.com`, instead of mantle. Through `bedrock-runtime`, Metabase only talks to Claude models, and it needs `bedrock:InvokeModelWithResponseStream` on the inference profile and on the foundation model in every region the profile routes to:++```json+{+ "Version": "2012-10-17",+ "Statement": [+ {+ "Effect": "Allow",+ "Action": "bedrock:InvokeModelWithResponseStream",+ "Resource": [+ "arn:aws:bedrock:*:*:inference-profile/*",+ "arn:aws:bedrock:*:*:application-inference-profile/*",+ "arn:aws:bedrock:*::foundation-model/*"+ ]+ }+ ]+}+```++If you configure the Bedrock connection with environment variables, it has no model ID. Set `MB_LLM_METABOT_PROVIDER` to `bedrock/` followed by the ID instead, and set `MB_LLM_MINI_MODEL` the same way, since short tasks otherwise run on `anthropic.claude-haiku-4-5` through mantle.+## vLLM- Provider key: `vllm`diff --git a/src/metabase/cmd/resources/ai-provider-bedrock.md b/src/metabase/cmd/resources/ai-provider-bedrock.mdindex c9ffafee9d1..8fb987306b5 100644--- a/src/metabase/cmd/resources/ai-provider-bedrock.md+++ b/src/metabase/cmd/resources/ai-provider-bedrock.md@@ -1,6 +1,6 @@### IAM permissions for Bedrock-Metabase talks to Bedrock through the mantle endpoint, `https://bedrock-mantle.{region}.api.aws`, not through `bedrock-runtime`. Mantle is a separate IAM namespace with its own actions, so a policy written against the `bedrock` prefix won't grant access. Metabase lists models and runs conversations, so it needs `bedrock-mantle:ListModels` and `bedrock-mantle:CreateInference`.+Metabase talks to Bedrock through the mantle endpoint, `https://bedrock-mantle.{region}.api.aws`, unless the connection's **Model ID** sends it to `bedrock-runtime` (see [Use an inference profile](#use-an-inference-profile)). Mantle is a separate IAM namespace with its own actions, so a policy written against the `bedrock` prefix won't grant access. Metabase lists models and runs conversations, so it needs `bedrock-mantle:ListModels` and `bedrock-mantle:CreateInference`.Here's a least-privilege policy that grants both:@@ -23,9 +23,34 @@ If Metabase reports "AWS Bedrock credentials lack permission for this model or a### The Bedrock models you can pick depend on the region-The table above lists the models Metabase can use. The **Models** card only offers the ones Bedrock serves in the connection's region, so what you can pick depends on the region. The mantle catalog has no cross-region inference profiles, so a model that isn't served in your region can't be reached from that region at all.+The table above lists the models Metabase can use. The **Models** card only offers the ones Bedrock serves in the connection's region, so what you can pick depends on the region. The mantle catalog has no cross-region inference profiles, so to reach a model that isn't served in your region, [use an inference profile](#use-an-inference-profile).If the model list is empty or shorter than you expect after connecting:- **Check the region**: the **Region** dropdown lists every AWS region, including regions where Bedrock serves none of these models. The [AWS model cards](https://docs.aws.amazon.com/bedrock/latest/userguide/model-cards.html) show where each model is available. For example, the GPT models are only served in US regions.- **Check your account's data retention setting**: Bedrock marks a model unavailable when your account's data retention mode doesn't meet what that model requires. For example, [Claude Fable 5](https://docs.aws.amazon.com/bedrock/latest/userguide/model-card-anthropic-claude-fable-5.html) requires the `aws_review` data retention mode.++### Use an inference profile++To use an [inference profile](https://docs.aws.amazon.com/bedrock/latest/userguide/inference-profiles.html), or a Claude model that isn't listed for your region, enter its ID or ARN in **Model ID**, like `eu.anthropic.claude-sonnet-4-6` or `us.anthropic.claude-haiku-4-5-20251001-v1:0`. That connection serves this model instead of the models above: connecting checks it by generating a single token, and the model picker offers it as the connection's only model. To use the models above too, add a second Amazon Bedrock provider without a model ID.++Metabase sends inference profile IDs, ARNs, and model IDs with a version suffix like `-v1:0` to `bedrock-runtime`, `https://bedrock-runtime.{region}.amazonaws.com`, instead of mantle. Through `bedrock-runtime`, Metabase only talks to Claude models, and it needs `bedrock:InvokeModelWithResponseStream` on the inference profile and on the foundation model in every region the profile routes to:++```json+{+ "Version": "2012-10-17",+ "Statement": [+ {+ "Effect": "Allow",+ "Action": "bedrock:InvokeModelWithResponseStream",+ "Resource": [+ "arn:aws:bedrock:*:*:inference-profile/*",+ "arn:aws:bedrock:*:*:application-inference-profile/*",+ "arn:aws:bedrock:*::foundation-model/*"+ ]+ }+ ]+}+```++If you configure the Bedrock connection with environment variables, it has no model ID. Set `MB_LLM_METABOT_PROVIDER` to `bedrock/` followed by the ID instead, and set `MB_LLM_MINI_MODEL` the same way, since short tasks otherwise run on `anthropic.claude-haiku-4-5` through mantle.diff --git a/src/metabase/llm/provider.clj b/src/metabase/llm/provider.cljindex 0de8422cd8c..af114c6a49a 100644--- a/src/metabase/llm/provider.clj+++ b/src/metabase/llm/provider.clj@@ -312,6 +312,8 @@:label (deferred-tru "Amazon Bedrock"):default-model "anthropic.claude-opus-4-8":mini-model "anthropic.claude-haiku-4-5"+ ;; A connection with a model ID serves that model instead of the catalog.+ :model-fields [:model-id];; Both keys together select explicit credentials, neither selects the AWS default credentials chain, and one;; without the other authenticates nothing. A session token only extends the pair.:requires {:access-key-id [:secret-access-key]@@ -336,6 +338,11 @@:type :select:options aws-region-options:default "us-east-1"}+ {:key :model-id+ :label (deferred-tru "Model ID")+ :type :text+ :placeholder "global.anthropic.claude-sonnet-4-6"+ :help (deferred-tru "Optional. Use an inference profile, or a model that isn''t listed for this region, by its ID or ARN.")}{:key :session-token:label (deferred-tru "Session token"):type :passworddiff --git a/src/metabase/metabot/self/adapter.clj b/src/metabase/metabot/self/adapter.cljindex 9f92d1e0b68..a87f02bac84 100644--- a/src/metabase/metabot/self/adapter.clj+++ b/src/metabase/metabot/self/adapter.clj@@ -126,6 +126,7 @@[:span-attrs {:optional true} [:maybe [:map {::mr/deliberately-open true:description "extra span attributes"}]]][:error-msg {:optional true} [:maybe fn?]]+ [:read-stream {:optional true} [:maybe fn?]][:wrap-stream {:optional true} [:maybe fn?]][:on-request-error {:optional true} [:maybe fn?]]])@@ -327,6 +328,8 @@:error-msg - replaces the descriptor's own `res->message`, for a provider whose messagedepends on the connection rather than only on the response. Applies to bothphases below.+ :read-stream - turns the response body into a reducible of the provider's events, for a stream+ that is not SSE. Defaults to [[core/sse-reducible]].:wrap-stream - applied to the reducible before error translation, for an adapter with its owntranslation to do first.:on-request-error - replaces the default [[rethrow!]] catch, for an adapter that retries. Only@@ -335,11 +338,12 @@instead, which no adapter overrides."[{:keys [slug display-name span] :as p} :- Provider{:keys [model input tools credentials ai-proxy?]} :- core/LLMRequestOpts- {:keys [path body headers request-options span-attrs wrap-stream on-request-error error-msg]+ {:keys [path body headers request-options span-attrs read-stream wrap-stream on-request-error error-msg]:or {wrap-stream identity}} :- StreamOpts]- (let [msg-count (count input)- tool-count (count tools)- res->msg (or error-msg (:error-msg p))]+ (let [msg-count (count input)+ tool-count (count tools)+ res->msg (or error-msg (:error-msg p))+ read-stream (or read-stream core/sse-reducible)](log/debug (str display-name " request") {:model model :msg-count msg-count :tools tool-count});; flat keys, which is what `u.o11y/with-span` renders into its log line. clj-otel reads span;; attributes only from `:attributes` and drops every other key, so these reach the log and not the@@ -365,7 +369,7 @@:body (json/encode body)}request-options):body- core/sse-reducible+ read-stream(debug/capture-stream {:provider slug:model model:url pathdiff --git a/src/metabase/metabot/self/bedrock.clj b/src/metabase/metabot/self/bedrock.cljindex 73f23046c46..256a137f031 100644--- a/src/metabase/metabot/self/bedrock.clj+++ b/src/metabase/metabot/self/bedrock.clj@@ -13,6 +13,10 @@[[openai/openai-request-body]] + [[openai/openai->aisdk-chunks-xf]]; the vendor prefix on themodel id (e.g. `anthropic.claude-haiku-4-5`, `openai.gpt-5.5`) selects the API family.+ Claude inference profiles, ARNs and versioned model IDs, none of which mantle serves, go to+ `bedrock-runtime`'s `InvokeModelWithResponseStream` with the same Anthropic Messages body instead (see+ [[runtime-model?]]).+Requests are authenticated with AWS Signature Version 4 computed from the connection's access key pair, or, on aself-hosted Metabase with no pair configured, from the AWS SDK default credentials chain (IRSA, EKS Pod Identity,instance profile). Metabase Cloud always requires the pair:@@ -27,9 +31,12 @@[metabase.metabot.self.openai :as openai][metabase.util :as u][metabase.util.i18n :refer [tru]]+ [metabase.util.json :as json][metabase.util.log :as log]- [metabase.util.malli :as mu])+ [metabase.util.malli :as mu]+ [ring.util.codec :as codec])(:import+ (java.io InputStream)(java.net URI)(java.util.function Consumer)(software.amazon.awssdk.auth.credentials DefaultCredentialsProvider)@@ -37,7 +44,8 @@(software.amazon.awssdk.http ContentStreamProvider SdkHttpMethod SdkHttpRequest SdkHttpRequest$Builder)(software.amazon.awssdk.http.auth.aws.signer AwsV4HttpSigner)(software.amazon.awssdk.http.auth.spi.signer SignRequest$Builder SignedRequest)- (software.amazon.awssdk.identity.spi AwsCredentialsIdentity AwsSessionCredentialsIdentity)))+ (software.amazon.awssdk.identity.spi AwsCredentialsIdentity AwsSessionCredentialsIdentity)+ (software.amazon.eventstream HeaderValue Message MessageDecoder)))(set! *warn-on-reflection* true)@@ -104,7 +112,7 @@(.build b)))(defn- signed-headers- "AWS SigV4 request headers for a Bedrock mantle request, computed by the AWS SDK's [[AwsV4HttpSigner]].+ "AWS SigV4 request headers for a Bedrock request, computed by the AWS SDK's [[AwsV4HttpSigner]].Returns a `{header-name header-value}` map carrying `Host`, `X-Amz-Date`, `Authorization`,`x-amz-content-sha256`, plus `Content-Type` and `X-Amz-Security-Token` when applicable. Additional@@ -192,10 +200,11 @@being fixed by the descriptor. The signed headers travel as the request's auth headers; extra unsignedheaders (e.g. `anthropic-version`) can still be added freely alongside them.- `ai-proxy?` is accepted for parity with the other adapters but is not supported."- [{:keys [slug display-name]} {:keys [credentials ai-proxy? method path body]}]+ `base-url-format` puts the region into the endpoint's base URL. `ai-proxy?` is accepted for parity with the+ other adapters but is not supported."+ [base-url-format {:keys [slug display-name]} {:keys [credentials ai-proxy? method path body]}](let [{:keys [region] :as creds} (ensure-credentials credentials)- base-url (str "https://bedrock-mantle." region ".api.aws")+ base-url (format base-url-format region)content-type (when body "application/json")sig-headers (signed-headers (merge creds {:method method:url (str base-url path)@@ -208,7 +217,7 @@(def ^:private provider(adapter/provider{:slug "bedrock"- :auth bedrock-auth+ :auth (partial bedrock-auth "https://bedrock-mantle.%s.api.aws"):display-name "AWS Bedrock":error-fallback #(tru "AWS Bedrock API error (HTTP {0})" %):errors {401 #(tru "AWS Bedrock rejected our credentials or request signature")@@ -217,6 +226,93 @@429 #(tru "AWS Bedrock has rate limited us")500 #(tru "AWS Bedrock is not working but not saying why")}}))+(def ^:private runtime-provider+ (assoc provider :auth (partial bedrock-auth "https://bedrock-runtime.%s.amazonaws.com")))++;;; ------------------------------------------------ bedrock-runtime ---------------------------------------------++(defn- runtime-model?+ "Whether `model` names a Claude model the way only `bedrock-runtime` serves it: an inference profile ID like+ `eu.anthropic.claude-sonnet-4-6`, an ARN, or a versioned model ID like `anthropic.claude-haiku-4-5-20251001-v1:0`.+ A bare `anthropic.*` or `openai.*` ID is a mantle catalog ID."+ [model]+ (boolean (re-find #"^arn:|^[a-z-]+\.anthropic\.|^anthropic\..*-v\d+(:\d+)?$" (str model))))++(defn- runtime-base-model+ "The `anthropic.claude-*` ID of the model a runtime `model` invokes, which is what the Claude adapter reads a model's+ capabilities from: `anthropic.claude-haiku-4-5-20251001` for `global.anthropic.claude-haiku-4-5-20251001-v1:0`.+ An ARN that doesn't name its model, like an application inference profile's, gives its own resource ID."+ [model]+ (-> model+ (str/replace #"^arn:.*/" "")+ (str/replace #"^[a-z-]+\.(?=anthropic\.)" "")+ (str/replace #"-v\d+(:\d+)?$" "")))++(def ^:private runtime-anthropic-version "bedrock-2023-05-31")++(defn- runtime-path+ [model]+ (str "/model/" (codec/url-encode model) "/invoke-with-response-stream"))++(defn- ->runtime-anthropic-body+ "Adapt a canonical Anthropic Messages request body for `InvokeModelWithResponseStream`: the model goes in the URL+ and the API version in the body, and there is no `stream` flag or top-level `cache_control`."+ [body]+ (-> body+ (dissoc :model :stream :cache_control)+ (assoc :anthropic_version runtime-anthropic-version)))++(defn- header-string+ [^Message message header]+ (when-let [^HeaderValue value (.get (.getHeaders message) header)]+ (.getString value)))++(defn- runtime-event+ "The Anthropic streaming event one `InvokeModelWithResponseStream` message carries. A chunk carries it as base64+ JSON; an exception becomes Anthropic's `error` event, which the Claude translation reports like any other."+ [^Message message]+ (let [payload (json/decode+kw (u/bytes-to-string (.getPayload message)))]+ (if (= "chunk" (header-string message ":event-type"))+ (json/decode+kw (u/decode-base64 (:bytes payload)))+ {:type "error"+ :error {:type (header-string message ":exception-type")+ :message (:message payload)}})))++(defn- runtime-events+ "A reducible over the Anthropic streaming events in an `InvokeModelWithResponseStream` response `body`, which+ comes framed as an AWS event stream rather than SSE."+ [^InputStream body]+ (reify clojure.lang.IReduceInit+ (reduce [_ rf init]+ (with-open [in body]+ (let [decoder (MessageDecoder.)+ buf (byte-array 8192)]+ (loop [acc init, messages ()]+ (cond+ (reduced? acc) @acc+ (seq messages) (recur (rf acc (runtime-event (first messages))) (rest messages))+ :else (let [n (.read in buf)]+ (if (neg? n)+ acc+ (do (.feed decoder buf 0 n)+ (recur acc (.getDecodedMessages decoder))))))))))))++(defn- check-runtime-model!+ "Generate one token with `model` on `bedrock-runtime`, which has no catalog to check a model against.+ Throws unless the model finishes its response."+ [{:keys [model] :as opts}]+ (let [chunks (into [] (claude/claude->aisdk-chunks-xf)+ (adapter/stream! runtime-provider (select-keys opts [:model :credentials :ai-proxy?])+ {:path (runtime-path model)+ :body {:anthropic_version runtime-anthropic-version+ :max_tokens 1+ :messages [{:role "user" :content "Hi"}]}+ :read-stream runtime-events}))]+ (when-let [error (or (some :errorText chunks)+ (when-not (some :finish-reason chunks)+ (tru "AWS Bedrock returned an incomplete response from {0}" (pr-str model))))]+ (throw (ex-info error {:api-error true :status-code 400})))))+;;; ------------------------------------------------ Model listing ----------------------------------------------(def supported-models@@ -240,7 +336,9 @@(mu/defn context-window-tokens :- [:maybe :int]"The input context window for `model`, or nil when it isn't one we know."[model :- [:maybe :string]]- (get-in supported-models [model :context-window]))+ (if (runtime-model? model)+ (claude/context-window-tokens (runtime-base-model model))+ (get-in supported-models [model :context-window])))(defn- available-model?"Whether a `/v1/models` catalog entry is available.@@ -254,11 +352,19 @@The opts map supports `:credentials`, a map of `:access-key-id`, `:secret-access-key`, `:region`, and (fortemporary credentials) `:session-token`, plus `:ai-proxy?`, which is not supported for Bedrock and throws whentrue. On a self-hosted Metabase with no access key pair, requests are signed with whatever the AWS default- credentials chain resolves; Metabase Cloud requires the pair."+ credentials chain resolves; Metabase Cloud requires the pair.++ A `:model` only `bedrock-runtime` serves is not in that catalog, so nothing is listed for it, and with `:probe?`+ it is checked by generating a token with it."([] (list-models {}))- ([opts :- adapter/ListOpts]- (adapter/model-listing supported-models- (filter available-model? (adapter/fetch-catalog provider opts "/v1/models")))))+ ([{:keys [model probe? ai-proxy?] :as opts} :- adapter/ListOpts]+ (if (runtime-model? model)+ (do (adapter/reject-ai-proxy! provider ai-proxy?)+ (when probe?+ (check-runtime-model! opts))+ {:models []})+ (adapter/model-listing supported-models+ (filter available-model? (adapter/fetch-catalog provider opts "/v1/models"))))));;; --------------------------------------------- API family dispatch -------------------------------------------@@ -267,9 +373,11 @@(def ^:private anthropic-version "2023-06-01")(defn- model-family- "Which mantle API family serves `model`, by vendor prefix: `:anthropic`, `:openai`, or nil."+ "Which API serves `model`: mantle's `:anthropic` or `:openai` family by vendor prefix, `:runtime` for a Claude+ model only `bedrock-runtime` serves, or nil."[model](cond+ (runtime-model? model) :runtime(str/starts-with? (str model) "anthropic.") :anthropic(str/starts-with? (str model) "openai.") :openai))@@ -290,6 +398,7 @@[model](case (model-family model):anthropic (claude/reasoning-model? model)+ :runtime (claude/reasoning-model? (runtime-base-model model));; The mantle's Responses surface accepts the reasoning request fields and;; the GPT models do reason (at a per-model default effort: gpt-5.4 "none",;; gpt-5.5 "medium"), but it never streams reasoning summaries — `summary`@@ -314,7 +423,8 @@(dissoc body :cache_control))(mu/defn bedrock-raw- "Perform a streaming request to the Bedrock mantle endpoint.+ "Perform a streaming request to Bedrock: the mantle endpoint for a mantle catalog ID, `bedrock-runtime` for a+ Claude model only it serves (see [[runtime-model?]]).Opts map takes `:credentials` from the connection serving this request: `:access-key-id`, `:secret-access-key`,`:region`, and (for temporary credentials) `:session-token`. On a self-hosted Metabase with no access key pair,requests are signed with whatever the AWS default credentials chain resolves; Metabase Cloud requires the pair.@@ -323,29 +433,34 @@:or {model default-model}} :- core/LLMRequestOpts](let [opts (assoc opts :model model :fast? false)family (model->family model)- {:keys [path headers req]}+ {:keys [path headers req read-stream]}(case family:anthropic {:path "/anthropic/v1/messages":headers {"anthropic-version" anthropic-version}:req (->mantle-anthropic-body (claude/claude-request-body opts))}+ :runtime {:path (runtime-path model)+ :req (->runtime-anthropic-body+ (claude/claude-request-body (assoc opts :model (runtime-base-model model))))+ :read-stream runtime-events}:openai {:path "/openai/v1/responses":req (openai/openai-request-body opts)})]- (adapter/stream! provider opts- {:path path- :body req- :headers headers- :span-attrs {:family (name family)}})))+ (adapter/stream! (if (= :runtime family) runtime-provider provider) opts+ {:path path+ :body req+ :headers headers+ :read-stream read-stream+ :span-attrs {:family (name family)}})))(defn- model->aisdk-chunks-xf"The SSE->AISDK translating transducer for a Bedrock model id.- Claude's for `anthropic.*` models, OpenAI's for `openai.*` models."+ Claude's for Claude models, OpenAI's for `openai.*` models."[model](case (model->family model)- :anthropic (claude/claude->aisdk-chunks-xf)- :openai (openai/openai->aisdk-chunks-xf)))+ (:anthropic :runtime) (claude/claude->aisdk-chunks-xf)+ :openai (openai/openai->aisdk-chunks-xf)))(defn bedrock- "Call AWS Bedrock (mantle endpoint), return AISDK stream."+ "Call AWS Bedrock, return AISDK stream."[& [{:keys [model] :or {model default-model}} :as args]](let [raw (apply bedrock-raw args)](eduction (model->aisdk-chunks-xf model) raw)))diff --git a/src/metabase/metabot/self/claude.clj b/src/metabase/metabot/self/claude.cljindex 7509b746545..e455e2ab65f 100644--- a/src/metabase/metabot/self/claude.clj+++ b/src/metabase/metabot/self/claude.clj@@ -183,11 +183,11 @@(= t "content_block_stop") (close!);; Claude reports usage at both message_start and message_delta,;; but message_delta values are cumulative and include the earlier- ;; counts.+ ;; counts. Bedrock's InvokeModel stream can leave the input counts out.;; https://platform.claude.com/docs/en/build-with-claude/streaming#event-types;; https://platform.claude.com/docs/en/api/cli/messages#message_delta_usage(= t "message_delta") (u/prog1- (vreset! last-usage (:usage chunk))+ (vswap! last-usage merge (:usage chunk))(vreset! stop-reason (:stop_reason delta)));; end of message(= t "message_stop") identitydiff --git a/src/metabase/metabot/self/core.clj b/src/metabase/metabot/self/core.cljindex 4efb30c52f7..79cef25b584 100644--- a/src/metabase/metabot/self/core.clj+++ b/src/metabase/metabot/self/core.clj@@ -174,7 +174,8 @@[:access-key-id {:optional true} [:maybe :string]][:secret-access-key {:optional true} [:maybe :string]][:session-token {:optional true} [:maybe :string]]- [:region {:optional true} [:maybe :string]]])+ [:region {:optional true} [:maybe :string]]+ [:model-id {:optional true} [:maybe :string]]])(def ^:private GoogleCredentials[:map {:closed true}diff --git a/src/metabase/metabot/settings.clj b/src/metabase/metabot/settings.cljindex ac52e119f44..42b17bbf1c2 100644--- a/src/metabase/metabot/settings.clj+++ b/src/metabase/metabot/settings.clj@@ -195,10 +195,12 @@(defn- mini-model-ref"The model reference for the fastest model of the connection `model-ref` names, or nil when that connection's- provider type has no such model."+ provider type has no such model or the connection names the one model it serves."[model-ref]- (let [conn-key (llm.provider/model-ref->connection-key model-ref)]- (when-let [model (llm.provider/mini-model (:type (llm.provider/connection conn-key)))]+ (let [conn-key (llm.provider/model-ref->connection-key model-ref)+ {:keys [type config]} (llm.provider/connection conn-key)]+ (when-let [model (and (not (llm.provider/connection-model type config))+ (llm.provider/mini-model type))](str conn-key "/" model))))(defn explicit-mini-model@@ -213,8 +215,8 @@(defn- -llm-mini-model"Quick background tasks — naming a conversation, and whatever short, high-volume calls come next — do not need themodel Metabot chats on, so with nothing stored this resolves to the fastest model of the- connection [[llm-metabot-provider]] names. Connections whose provider type has no such model — the ones that name- the single model they serve, and the managed provider — fall through to the Metabot model itself, so this always+ connection [[llm-metabot-provider]] names. Connections that name the single model they serve, and those whose+ provider type has no such model like the managed provider, fall through to the Metabot model itself, so this alwaysnames a model as long as Metabot does."[](or (explicit-mini-model)diff --git a/test/metabase/llm/api/provider_test.clj b/test/metabase/llm/api/provider_test.cljindex f91df997288..d8ff9b0a493 100644--- a/test/metabase/llm/api/provider_test.clj+++ b/test/metabase/llm/api/provider_test.clj@@ -1,11 +1,12 @@(ns metabase.llm.api.provider-test(:require[clj-http.client :as http]- [clojure.test :refer [deftest is testing use-fixtures]]+ [clojure.test :refer [are deftest is testing use-fixtures]][medley.core :as m][metabase.llm.api.provider :as llm.api.provider][metabase.llm.provider :as llm.provider][metabase.metabot.self :as metabot.self]+ [metabase.metabot.self.bedrock-test :as bedrock-test][metabase.metabot.settings :as metabot.settings][metabase.permissions.core :as perms][metabase.settings.core :as setting]@@ -108,6 +109,7 @@(is (= {"access-key-id" false"secret-access-key" false"region" false+ "model-id" false"session-token" true}(->> types(filter #(= "bedrock" (:type %)))@@ -165,7 +167,7 @@(mt/with-premium-features #{:hosting}(let [bedrock (m/find-first #(= "bedrock" (:type %))(mt/user-http-request :crowberto :get 200 "llm/provider-types"))]- (is (= {"access-key-id" true "secret-access-key" true "region" false "session-token" false}+ (is (= {"access-key-id" true "secret-access-key" true "region" false "model-id" false "session-token" false}(->> bedrock :fields (into {} (map (juxt :key :required))))))(is (= "On Metabase Cloud, Bedrock always authenticates with your own AWS keys."(:help (m/find-first #(= "access-key-id" (:key %)) (:fields bedrock)))))))))@@ -473,6 +475,41 @@(is (=? {:model "endpoints/1234567890123456789" :probe? true} @opts))(is (= "google/endpoints/1234567890123456789" (metabot.settings/llm-metabot-provider))))))))))+(def ^:private bedrock-inference-profile-connection+ {:type "bedrock"+ :config {:access-key-id "AKIAIOSFODNN7EXAMPLE"+ :secret-access-key "wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY"+ :region "eu-central-1"+ :model-id "eu.anthropic.claude-sonnet-4-6"}})++(deftest create-bedrock-connection-with-an-inference-profile-test+ (testing "a Bedrock connection that names an inference profile is checked on bedrock-runtime and Metabot runs on it"+ (let [requested (atom [])]+ (mt/with-dynamic-fn-redefs [http/request (fn [req]+ (swap! requested conj (:url req))+ (bedrock-test/runtime-response-for bedrock-test/one-token-completion))]+ (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" bedrock-inference-profile-connection)+ (is (= [(str "https://bedrock-runtime.eu-central-1.amazonaws.com/model/eu.anthropic.claude-sonnet-4-6"+ "/invoke-with-response-stream")]+ @requested))+ (is (= "bedrock/eu.anthropic.claude-sonnet-4-6" (metabot.settings/llm-metabot-provider)))))))))++(deftest create-bedrock-connection-is-rejected-when-the-model-does-not-finish-test+ (testing "the connection is not saved when the model errors partway through or never finishes its response"+ (mt/with-temporary-setting-values [llm-providers []]+ (let [connect! (fn [messages]+ (mt/with-dynamic-fn-redefs [http/request (fn [_] (bedrock-test/runtime-response-for messages))]+ (:message (mt/user-http-request :crowberto :post 400 "llm/providers"+ bedrock-inference-profile-connection))))+ incomplete "AWS Bedrock returned an incomplete response from \"eu.anthropic.claude-sonnet-4-6\""]+ (are [messages error] (= error (connect! messages))+ [bedrock-test/message-start bedrock-test/stream-error] "Model stream error"+ [] incomplete+ [bedrock-test/message-start] incomplete))+ (is (= [] (llm.provider/connections))))))+(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.")diff --git a/test/metabase/llm/provider_test.clj b/test/metabase/llm/provider_test.cljindex c00498824b4..f86c95cf33f 100644--- a/test/metabase/llm/provider_test.clj+++ b/test/metabase/llm/provider_test.clj@@ -226,7 +226,7 @@clojure.lang.ExceptionInfo #"Access key ID is required for bedrock"(llm.provider/validate-config! "bedrock" {})))(testing "the pair is a mandatory set, so the form marks each of its fields required"- (is (= {:access-key-id true :secret-access-key true :region false :session-token false}+ (is (= {:access-key-id true :secret-access-key true :region false :model-id false :session-token false}(->> (llm.provider/provider-type "bedrock"):fields(into {} (map (juxt :key (comp boolean :required?))))))))diff --git a/test/metabase/metabot/self/bedrock_test.clj b/test/metabase/metabot/self/bedrock_test.cljindex 382ce491f0d..fc3257af7fe 100644--- a/test/metabase/metabot/self/bedrock_test.clj+++ b/test/metabase/metabot/self/bedrock_test.clj@@ -1,5 +1,8 @@(ns metabase.metabot.self.bedrock-test(:require+ [buddy.core.codecs :as codecs]+ [buddy.core.hash :as buddy-hash]+ [buddy.core.mac :as mac][clj-http.client :as http][clojure.string :as str][clojure.test :refer :all]@@ -9,10 +12,14 @@[metabase.metabot.self.debug :as debug][metabase.premium-features.core :as premium-features][metabase.test :as mt]+ [metabase.util :as u][metabase.util.json :as json])(:import+ (java.io ByteArrayInputStream ByteArrayOutputStream SequenceInputStream)+ (java.util Collections)(software.amazon.awssdk.core.exception SdkClientException SdkException)- (software.amazon.awssdk.identity.spi AwsSessionCredentialsIdentity)))+ (software.amazon.awssdk.identity.spi AwsSessionCredentialsIdentity)+ (software.amazon.eventstream HeaderValue Message)))(set! *warn-on-reflection* true)@@ -264,6 +271,7 @@"Run `bedrock-raw` with HTTP stubbed out and return the clj-http request map it would send."[opts](with-redefs [self.core/sse-reducible identity+ bedrock/runtime-events identityself.core/reducible-with-api-errors (fn [r _ _] r)debug/capture-stream (fn [r _] r)http/request (fn [req] {:body req})]@@ -534,3 +542,190 @@(deftest not-found-error-is-translated-with-body-preview-test(is (= "AWS Bedrock model or endpoint is unavailable in the configured region — no such model"(list-models-error-message! 404 "{\"message\":\"no such model\"}"))))++;;; ──────────────────────────────────────────────────────────────────+;;; bedrock-runtime+;;; ──────────────────────────────────────────────────────────────────++(def ^:private profile-arn+ "arn:aws:bedrock:eu-central-1:123456789012:inference-profile/eu.anthropic.claude-sonnet-4-6")++(deftest runtime-endpoint-by-model-id-test+ (testing "a Claude inference profile ID or ARN, or a versioned model ID, goes to bedrock-runtime, a bare catalog ID to mantle"+ (are [model url] (= url (:url (captured-raw-request! {:model model :input [{:role :user :content "hi"}]})))+ "anthropic.claude-haiku-4-5"+ "https://bedrock-mantle.us-east-1.api.aws/anthropic/v1/messages"++ "eu.anthropic.claude-sonnet-4-6"+ "https://bedrock-runtime.us-east-1.amazonaws.com/model/eu.anthropic.claude-sonnet-4-6/invoke-with-response-stream"++ "global.anthropic.claude-haiku-4-5-20251001-v1:0"+ "https://bedrock-runtime.us-east-1.amazonaws.com/model/global.anthropic.claude-haiku-4-5-20251001-v1%3A0/invoke-with-response-stream"++ "anthropic.claude-haiku-4-5-20251001-v1:0"+ "https://bedrock-runtime.us-east-1.amazonaws.com/model/anthropic.claude-haiku-4-5-20251001-v1%3A0/invoke-with-response-stream"++ "anthropic.claude-opus-4-6-v1"+ "https://bedrock-runtime.us-east-1.amazonaws.com/model/anthropic.claude-opus-4-6-v1/invoke-with-response-stream"++ profile-arn+ (str "https://bedrock-runtime.us-east-1.amazonaws.com/model/"+ "arn%3Aaws%3Abedrock%3Aeu-central-1%3A123456789012%3Ainference-profile%2Feu.anthropic.claude-sonnet-4-6"+ "/invoke-with-response-stream"))))++(deftest runtime-request-body-test+ (let [body (captured-body! {:model "eu.anthropic.claude-opus-4-8" :system "be brief"})]+ (testing "the Claude body is built for the model the profile invokes"+ (is (=? {:anthropic_version "bedrock-2023-05-31"+ :system [{:type "text" :text "be brief" :cache_control {:type "ephemeral"}}]+ :messages [{:role "user" :content [{:type "text" :text "hi"}]}]+ :thinking {:type "adaptive" :display "summarized"}}+ body)))+ (testing "the model goes in the URL, and there is no stream flag or top-level cache_control"+ (is (not-any? #(contains? body %) [:model :stream :cache_control]))))+ (testing "a model that doesn't stream reasoning gets no thinking config"+ (is (not (contains? (captured-body! {:model "global.anthropic.claude-haiku-4-5-20251001-v1:0"}) :thinking)))))++(deftest ^:parallel runtime-model-capabilities-test+ (are [model reasoning? context-window] (= [reasoning? context-window]+ [(bedrock/reasoning-model? model) (bedrock/context-window-tokens model)])+ "eu.anthropic.claude-sonnet-4-6" true 1000000+ "global.anthropic.claude-haiku-4-5-20251001-v1:0" false 200000+ profile-arn true 1000000+ "arn:aws:bedrock:us-east-1:123456789012:application-inference-profile/abcdef123456" false nil))++(defn- sigv4-signature+ "The SigV4 signature of `canonical-request`, worked out by hand:+ https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_sigv-create-signed-request.html"+ [date region canonical-request]+ (let [hmac (fn [k s] (mac/hash s {:key k :alg :hmac+sha256}))+ scope [(subs date 0 8) region "bedrock" "aws4_request"]+ k (reduce hmac (codecs/str->bytes (str "AWS4" (:secret-access-key credentials))) scope)]+ (codecs/bytes->hex (hmac k (str/join "\n" ["AWS4-HMAC-SHA256"+ date+ (str/join "/" scope)+ (codecs/bytes->hex (buddy-hash/sha256 canonical-request))])))))++(deftest runtime-request-signature-test+ (testing "an ARN is percent-encoded once in the URL and twice in the signed path, the way botocore signs it"+ (let [{:keys [body headers]} (captured-raw-request! {:model profile-arn+ :input [{:role :user :content "hi"}]+ :credentials (assoc credentials :region "eu-central-1")})+ date (get headers "X-Amz-Date")+ payload-hash (codecs/bytes->hex (buddy-hash/sha256 body))+ signature (sigv4-signature+ date "eu-central-1"+ (str/join "\n" ["POST"+ (str "/model/arn%253Aaws%253Abedrock%253Aeu-central-1%253A123456789012%253A"+ "inference-profile%252Feu.anthropic.claude-sonnet-4-6/invoke-with-response-stream")+ ""+ "content-type:application/json"+ "host:bedrock-runtime.eu-central-1.amazonaws.com"+ (str "x-amz-content-sha256:" payload-hash)+ (str "x-amz-date:" date)+ ""+ "content-type;host;x-amz-content-sha256;x-amz-date"+ payload-hash]))]+ (is (= {"Host" "bedrock-runtime.eu-central-1.amazonaws.com"+ "x-amz-content-sha256" payload-hash+ "Authorization" (str "AWS4-HMAC-SHA256 Credential=AKIAIOSFODNN7EXAMPLE/" (subs date 0 8)+ "/eu-central-1/bedrock/aws4_request, "+ "SignedHeaders=content-type;host;x-amz-content-sha256;x-amz-date, "+ "Signature=" signature)}+ (select-keys headers ["Host" "x-amz-content-sha256" "Authorization"]))))))++(defn- event-stream-message+ "One message of an AWS event stream, the framing bedrock-runtime streams in."+ ^bytes [headers ^String payload]+ (let [out (ByteArrayOutputStream.)]+ (.encode (Message. (update-vals headers #(HeaderValue/fromString %)) (.getBytes payload "UTF-8")) out)+ (.toByteArray out)))++(defn- chunk-message+ "An `InvokeModelWithResponseStream` chunk carrying one Anthropic streaming `event`."+ [event]+ (event-stream-message {":message-type" "event" ":event-type" "chunk" ":content-type" "application/json"}+ (json/encode {:bytes (u/encode-base64 (json/encode event)) :p "abcdefgh"})))++(defn runtime-response-for+ "A stubbed clj-http response streaming `messages` in reads of a few bytes, so messages straddle them."+ [messages]+ {:status 200+ :body (SequenceInputStream.+ (Collections/enumeration+ (map #(ByteArrayInputStream. (byte-array %)) (partition-all 7 (mapcat seq messages)))))})++(defn- runtime-chunks-for!+ [messages]+ (with-redefs [debug/capture-stream (fn [r _] r)+ http/request (fn [_] (runtime-response-for messages))]+ (into [] (bedrock/bedrock {:model "eu.anthropic.claude-sonnet-4-6"+ :input [{:role :user :content "hi"}]+ :credentials credentials}))))++(def message-start+ (chunk-message {:type "message_start"+ :message {:id "msg_bdrk_1"+ :model "claude-sonnet-4-6"+ :usage {:input_tokens 10 :cache_read_input_tokens 5 :output_tokens 1}}}))++(def one-token-completion+ [message-start+ (chunk-message {:type "content_block_start" :index 0 :content_block {:type "text" :text ""}})+ (chunk-message {:type "content_block_delta" :index 0 :delta {:type "text_delta" :text "Hello"}})+ (chunk-message {:type "content_block_stop" :index 0})+ (chunk-message {:type "message_delta" :delta {:stop_reason "max_tokens"} :usage {:output_tokens 1}})+ (chunk-message {:type "message_stop"})])++(def stream-error+ (event-stream-message {":message-type" "exception"+ ":exception-type" "modelStreamErrorException"+ ":content-type" "application/json"}+ (json/encode {:message "Model stream error"})))++(deftest runtime-model-streams-claude-events-test+ (testing "chunks carry Claude's events, and message_start's input counts survive a message_delta with output only"+ (is (=? [{:type :start :id "msg_bdrk_1"}+ {:type :text :text "pong"}+ {:type :usage :usage {:promptTokens 15 :completionTokens 2 :cacheReadTokens 5}}]+ (into [] (self.core/aisdk-xf)+ (runtime-chunks-for!+ [message-start+ (chunk-message {:type "content_block_start" :index 0 :content_block {:type "text" :text ""}})+ (chunk-message {:type "content_block_delta" :index 0 :delta {:type "text_delta" :text "pong"}})+ (chunk-message {:type "content_block_stop" :index 0})+ (chunk-message {:type "message_delta" :delta {:stop_reason "end_turn"} :usage {:output_tokens 2}})+ (chunk-message {:type "message_stop"+ :amazon-bedrock-invocationMetrics {:inputTokenCount 10 :outputTokenCount 2}})])))))+ (testing "an exception partway through becomes Claude's error chunk"+ (is (= [{:type :error :errorText "Model stream error"}]+ (filter (comp #{:error} :type)+ (runtime-chunks-for! [message-start stream-error]))))))++(deftest list-models-runtime-model-test+ (let [opts {:credentials credentials :model "eu.anthropic.claude-sonnet-4-6"}]+ (testing "a model only bedrock-runtime serves is not in the mantle catalog, so nothing is listed or requested"+ (with-redefs [http/request (fn [_] (throw (ex-info "should never be called" {})))]+ (is (= {:models []} (bedrock/list-models opts)))))+ (testing "with :probe? it generates one token on bedrock-runtime"+ (let [captured (atom nil)]+ (with-redefs [http/request (fn [req] (reset! captured req) (runtime-response-for one-token-completion))]+ (is (= {:models []} (bedrock/list-models (assoc opts :probe? true))))+ (is (= (str "https://bedrock-runtime.us-east-1.amazonaws.com/model/eu.anthropic.claude-sonnet-4-6"+ "/invoke-with-response-stream")+ (:url @captured)))+ (is (=? {:max_tokens 1} (json/decode+kw (:body @captured)))))))+ (testing "a model bedrock-runtime refuses fails with its reason"+ (with-redefs [http/request (fn [_] (throw (ex-info "HTTP error"+ {:status 400+ :headers {"content-type" "application/json"}+ :body "{\"message\":\"The provided model identifier is invalid.\"}"})))]+ (is (thrown-with-msg?+ clojure.lang.ExceptionInfo+ #"The provided model identifier is invalid\."+ (bedrock/list-models (assoc opts :probe? true))))))+ (testing "the AI proxy is refused even though nothing is requested"+ (is (thrown-with-msg?+ clojure.lang.ExceptionInfo+ #"AI proxy is not supported for AWS Bedrock"+ (bedrock/list-models (assoc opts :ai-proxy? true)))))))diff --git a/test/metabase/metabot/settings_test.clj b/test/metabase/metabot/settings_test.cljindex 026520fdd25..e9ac10c855a 100644--- a/test/metabase/metabot/settings_test.clj+++ b/test/metabase/metabot/settings_test.clj@@ -481,6 +481,13 @@:endpoint-id "1234567890123456789"})](with-selected-model "google/endpoints/1234567890123456789"(is (= "google/endpoints/1234567890123456789" (metabot.settings/llm-mini-model))))))+ (testing "so does a Bedrock connection that names its model, while one without a model ID keeps its mini model"+ (with-connections [(connection "bedrock" "bedrock" {:model-id "eu.anthropic.claude-sonnet-4-6"})]+ (with-selected-model "bedrock/eu.anthropic.claude-sonnet-4-6"+ (is (= "bedrock/eu.anthropic.claude-sonnet-4-6" (metabot.settings/llm-mini-model)))))+ (with-connections [(connection "bedrock" "bedrock")]+ (with-selected-model "bedrock/anthropic.claude-opus-4-8"+ (is (= "bedrock/anthropic.claude-haiku-4-5" (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"