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
(ns metabase-enterprise.search.semantic.embedding
(:require
[buddy.core.codecs :as buddy-codecs]
[buddy.core.hash :as buddy-hash]
[clj-http.client :as http]
[clojure.string :as str]
[diehard.circuit-breaker :as dh.cb]
[flatland.ordered.set :refer [ordered-set]]
[metabase-enterprise.search.semantic.models.token-tracking :as semantic.models.token-tracking]
[metabase-enterprise.search.semantic.settings :as semantic-settings]
[metabase.analytics-interface.core :as analytics]
[metabase.analytics.core :as analytics.core]
[metabase.llm.provider :as llm.provider]
[metabase.llm.settings :as llm.settings]
[metabase.premium-features.core :as premium-features]
[metabase.search.embeddings.provider :as embeddings.provider]
[metabase.settings.core :as setting]
[metabase.tracing.core :as tracing]
[metabase.util :as u]
[metabase.util.json :as json]
[metabase.util.log :as log]
[metabase.util.malli :as mu])
(:import
[com.knuddels.jtokkit Encodings]
[com.knuddels.jtokkit.api Encoding EncodingType]
[dev.failsafe CircuitBreaker]
[java.net ConnectException]))
(set! *warn-on-reflection* true)
(defn ^:private clean-model-name
"Clean up a model name to make it friendly for use in index names."
[model-name]
(-> model-name
(str/split #"/")
last
(str/replace #"[-:.]" "_")))
(def ^:private model-abbreviations {"small" "sm" "medium" "md" "large" "lg" "tiny" "tn"})
(defn abbrev-model-name
"Abbreviate long model names for use in index names."
[model-name]
(-> model-name
clean-model-name
(str/replace #"embedding|embed" "")
((fn [s] (reduce-kv str/replace s model-abbreviations)))
(str/replace #"_{2,}" "_")
(str/replace #"^_+|_+$" "")))
(defn clean-provider-name
"Clean up a provider names for use in index names."
[provider-name]
(-> provider-name
(str/replace #"[^A-Za-z0-9_]" "_")
(str/replace #"_{2,}" "_")
(str/replace #"^_+|_+$" "")))
(defn abbrev-provider-name
"Abbreviate long provider names for use in index names."
[provider-name]
(case provider-name
"ai-service" "ais"
"ollama" "ollama"
"openai" "openai"
"in-process" "inproc"
;; Every plugin provider uses the same reserved form, including already-safe names. Otherwise an unsafe name's
;; encoded output could itself be registered as a safe provider name and collide with the same physical index.
(str "plugin_" (clean-provider-name provider-name) "_"
(subs (buddy-codecs/bytes->hex (buddy-hash/sha1 provider-name)) 0 16))))
;;; Token Counting for OpenAI Models
(def ^:private ^Encoding openai-encoding
"OpenAI tokenizer encoding for cl100k_base (used by text-embedding models)."
(delay (.getEncoding (Encodings/newDefaultEncodingRegistry) EncodingType/CL100K_BASE)))
(defn- count-tokens
"Count the number of tokens in a text string using OpenAI's cl100k_base encoding."
[^String text]
(when text
(let [^Encoding encoding @openai-encoding]
(.size (.encode encoding text)))))
(defn- count-tokens-batch
"Count the total number of tokens across multiple text strings."
[texts]
(reduce + 0 (map count-tokens texts)))
(defn- decode-embeddings
"Decode OpenAI base64 response"
[data]
(vec
(for [{:keys [embedding]} data]
(let [bytes (u/decode-base64-to-bytes ^String embedding)
buffer (doto (java.nio.ByteBuffer/wrap bytes)
(.order java.nio.ByteOrder/LITTLE_ENDIAN))
length (/ (alength bytes) 4)
_ (when-not (int? length)
(throw (ex-info "Invalid base64 length, not divisible by 4" {:length (alength bytes)})))
result (float-array length)]
(.get (.asFloatBuffer buffer) result)
result))))
;;; Batching Logic
(defn- create-batches
"Split texts into batches that don't exceed the threshold.
Returns a vector of batches, where each batch is a vector of texts.
- threshold: Maximum allowed measure per batch
- measure: Function to measure each text (e.g., count-tokens)
- texts: Collection of texts to batch"
[threshold measure texts]
(let [step (fn [{:keys [current-batch current-measure batches] :as acc} text]
(let [text-measure (measure text)]
(cond
;; Single text exceeds the limit - skip it with warning
;; TODO (Chris 2026-06-29) -- silently dropping an over-budget doc here is a poor default —
;; it vanishes from the index with only a warning. Make the over-budget policy a per-call
;; option (:truncate / :skip / :error, likely truncate-by-default eventually) and check what
;; the ai-service path does, which bypasses create-batches entirely.
;; https://linear.app/metabase/issue/BOT-1742
(> text-measure threshold)
(do
(log/warn
"Skipping text that exceeds maximum measure per batch"
{:measure text-measure :threshold threshold})
acc)
;; Adding this text would exceed the limit - start new batch
(> (+ current-measure text-measure) threshold)
(assoc acc
:current-batch [text]
:current-measure text-measure
:batches (conj batches current-batch))
;; Add to current batch
:else
(assoc acc
:current-batch (conj current-batch text)
:current-measure (+ current-measure text-measure)))))
{:keys [batches current-batch]}
(reduce step
{:current-batch [] :current-measure 0 :batches []}
texts)]
(if (seq current-batch)
(conj batches current-batch)
batches)))
;;;; Provider API
(defn- record-in-process-token-usage!
[{:keys [provider model-name]} texts {:keys [record-tokens? type]}]
(when (= "in-process" provider)
;; The bundled tokenizer is intentionally private to the plugin artifact. Use the existing cl100k
;; counter as an operational estimate so local inference participates in the same metrics/tracking.
(let [tokens (count-tokens-batch texts)]
(analytics/inc! :metabase-search/semantic-embedding-tokens
{:provider provider :model model-name}
tokens)
(when record-tokens?
(semantic.models.token-tracking/record-tokens model-name type tokens)))))
(defn resolve-model
"Resolve a requested embedding model to its immutable vector-space descriptor."
[embedding-model]
(embeddings.provider/resolve-model embedding-model))
(defn- in-process-token-model
[{:keys [provider model-name] :as embedding-model}]
(when (= "in-process" provider)
;; Configured and persisted descriptors already carry the canonical name. Only the optional plugin default
;; needs early resolution so token tracking has a stable label; the provider still owns embed-time resolution.
(if (nil? model-name)
(resolve-model embedding-model)
embedding-model)))
(defn get-embedding
"Return one embedding vector for `text`.
`opts` (honoured by the production providers; ollama ignores them):
- `:record-tokens?` — write a token-tracking row for the call
- `:type` — what the embedding is for (`:query`/`:index`), recorded with the tokens
- `:snowplow?` — ai-service only, default true; synthetic callers (e.g. the health probe) pass
false so the call emits no token_usage event
- `:connection-key` — openai only; the AI provider connection to embed through, for callers that are not
semantic search and so do not follow `ee-embedding-provider`"
[embedding-model text & {:as opts}]
(let [token-model (in-process-token-model embedding-model)]
(u/prog1 (embeddings.provider/embed-text (or token-model embedding-model) text opts)
(when token-model
(record-in-process-token-usage! token-model [text] opts)))))
(defn get-embeddings-batch
"Return one embedding vector per input text, in the same order.
Takes the same `opts` as [[get-embedding]], minus `:snowplow?` (batch callers are all organic)."
[embedding-model texts & {:as opts}]
(let [token-model (in-process-token-model embedding-model)]
(u/prog1 (embeddings.provider/embed-texts (or token-model embedding-model) texts opts)
(when token-model
(record-in-process-token-usage! token-model texts opts)))))
(defn- dispatch-provider [embedding-model & _] (:provider embedding-model))
(defmulti embedder-circuit-endpoint
"Return the remote endpoint that identifies `embedding-model`'s circuit, or nil when its provider does not
use the remote-service circuit breaker."
{:arglists '([embedding-model])} dispatch-provider)
(defmethod embedder-circuit-endpoint :default [_] nil)
(defn pull-model
"Prepare a provider model eagerly when the provider supports it."
[embedding-model]
(embeddings.provider/prepare! embedding-model))
;;;; Embedding-service circuit breaker
;;;
;;; The embedding service is a remote HTTP dependency; when it's down, every semantic-search / NLQ query
;;; would otherwise re-attempt (and re-time-out) against it. A circuit breaker fails fast after repeated
;;; failures, and its state doubles as a health signal: an open breaker means real traffic is currently
;;; failing. State transitions surface the affected health checks immediately (see the listeners) rather
;;; than waiting for the daily job. Thresholds are fixed (the breaker is built once); the setting is a
;;; runtime kill switch checked per call.
;;;
;;; The breaker wraps the HTTP providers defined below rather than sitting behind the provider SPI, since
;;; it keys circuits by remote endpoint and an in-process provider has none. If a second provider that
;;; needs it turns up, move it into `metabase.search.embeddings.provider` instead of adding a second copy.
(def ^:private embedder-circuit-breaker-failure-threshold
"Consecutive embedding-service failures that trip the breaker open." 5)
(def ^:private embedder-circuit-breaker-success-threshold
"Consecutive successes in half-open that close the breaker again." 2)
(def ^:private embedder-circuit-breaker-delay-ms
"How long the breaker stays open before it allows a half-open trial call." 30000)
(def ^:private embedding-http-timeouts
"clj-http timeout opts merged into every embedding-service request. Without an explicit :socket-timeout the
client waits forever, so a blackholed service (accepts connections, never responds) would hang callers
indefinitely -- and the breaker would never open, since only completed failures count toward it."
{:connection-timeout 10000
:socket-timeout 60000})
(defonce ^{:doc "Insertion-ordered set of `(fn [state])` hooks run on every breaker state change.
Health namespaces `conj` a hook here (inverting the dep -- they require this module) to re-persist their
embedder-dependent check on a transition, so an outage or recovery surfaces in minutes, not the next daily report.
Ordered-set: `conj` is reload-idempotent and load-ordered, so the semantic hook clears the probe cache
before the NLQ hook reads it. Register a var so a REPL redef takes effect live."}
embedder-circuit-state-change-hooks
(atom (ordered-set)))
(defonce ^:private embedder-circuit-hook-runner
;; One agent, so transitions run strictly in arrival order: concurrent futures would let a slow earlier
;; transition (e.g. its check blocked on a probe against a down service) persist a stale result AFTER a
;; later recovery transition's healthy one, leaving a pre-recovery "unreachable" row standing.
;; :continue so an unexpected action error can't wedge the agent for the process lifetime.
(agent nil
:error-mode :continue
:error-handler (fn [_agent e] (log/errorf "Embedder circuit hook runner errored: %s" (ex-message e)))))
(defn- on-embedder-circuit-state-change!
"Run the registered [[embedder-circuit-state-change-hooks]] off the failsafe callback thread -- one
transition at a time in arrival order, hooks in registration order, each isolated so one failing hook
doesn't starve the rest."
[state]
;; Log level tracks the resulting state's severity:
;; :open -> WARN (degradation)
;; :half-open -> INFO (probing)
;; :closed -> INFO (recovered)
;; Recovery is still captured level-independently -- the hooks below persist a health row per transition.
(if (= :open state)
(log/warn "Embedding service circuit breaker opened" {:state state})
(log/info "Embedding service circuit breaker changed state" {:state state}))
(send-off
embedder-circuit-hook-runner
(fn [_]
(doseq [hook @embedder-circuit-state-change-hooks]
(try
(hook state)
(catch InterruptedException e
(throw e))
(catch Exception e
(log/errorf "Embedder circuit state-change hook failed: %s" (ex-message e))))))))
(defn- new-embedder-circuit-breaker []
(dh.cb/circuit-breaker
{:failure-threshold embedder-circuit-breaker-failure-threshold
:success-threshold embedder-circuit-breaker-success-threshold
:delay-ms embedder-circuit-breaker-delay-ms
:on-open (fn [_] (on-embedder-circuit-state-change! :open))
:on-half-open (fn [_] (on-embedder-circuit-state-change! :half-open))
:on-close (fn [_] (on-embedder-circuit-state-change! :closed))}))
(defonce ^:private embedder-circuit-breakers
;; Provider settings can differ between semantic search and data complexity. Keying by endpoint prevents
;; one unavailable service from fast-failing calls to an unrelated, healthy service.
(atom {}))
(declare get-configured-model)
(defn- circuit-breaker-for
^CircuitBreaker [endpoint]
(or (get @embedder-circuit-breakers endpoint)
(get (swap! embedder-circuit-breakers
#(if (contains? % endpoint)
%
(assoc % endpoint (new-embedder-circuit-breaker))))
endpoint)))
#_{:clj-kondo/ignore [:metabase/discourage-dynamic-vars]}
(def ^:dynamic *bypass-circuit-breaker*
"Bind true to run an embedding call without consulting or tripping the breaker.
The health probe binds it so the probe stays an independent signal and can't flip the breaker from inside
a state-change listener (which would recurse)."
false)
(defn embedder-circuit-state
"Return the configured embedder circuit's state (`:closed`, `:open`, or `:half-open`), or nil when the
provider has no circuit endpoint. The optional `endpoint` arity inspects another endpoint's isolated circuit."
([]
(embedder-circuit-state (embedder-circuit-endpoint (get-configured-model))))
([endpoint]
(when endpoint
(dh.cb/state (circuit-breaker-for endpoint)))))
(defn embedder-circuit-untrusted?
"Whether the breaker is enabled and not closed -- i.e. open or half-open, so it doesn't yet trust the
embedding service (open short-circuits calls; half-open is on a single trial).
False when the breaker is disabled or the provider has no circuit endpoint.
True when resolving the endpoint throws, so a misconfigured embedder counts as untrusted, not as an error.
An `InterruptedException` still propagates."
[]
(boolean
(and (semantic-settings/semantic-search-embedder-circuit-breaker-enabled)
(try
(when-let [state (embedder-circuit-state)]
(not= :closed state))
(catch InterruptedException e
(throw e))
(catch Exception _ true)))))
(def ^:private request-specific-statuses
"HTTP statuses caused by a particular input, rather than the embedding service as a whole."
#{400 404 413 422})
(defn- service-failure?
[e]
(let [{:keys [status cause]} (u/all-ex-data e)]
(and (not (contains? request-specific-statuses status))
(not= :embedder/unexpected-dimensions cause)
;; A connection-time network-policy rejection is about the configured endpoint, not the service's health.
(not (llm.settings/llm-network-policy-error? e)))))
(defn- circuit-open-ex
[endpoint]
(ex-info "embedding service unavailable (circuit open)"
(cond-> {:status 502, :cause :embedder/circuit-open}
endpoint (assoc :endpoint endpoint))))
(defn- call-through-embedder-breaker
"Run `thunk` under the embedder circuit breaker, unless it is bypassed (probe) or disabled (kill switch).
Circuits are isolated by endpoint. Service-wide failures update the circuit; request- and model-specific
failures propagate without changing its history. An open circuit throws a 502 `ex-info` with
`:cause :embedder/circuit-open`."
[thunk & {:keys [endpoint]}]
(if (or (nil? endpoint)
*bypass-circuit-breaker*
(not (semantic-settings/semantic-search-embedder-circuit-breaker-enabled)))
(thunk)
(let [^CircuitBreaker breaker (circuit-breaker-for endpoint)]
(when-not (dh.cb/allow-execution? breaker)
(throw (circuit-open-ex endpoint)))
(let [execution-state (dh.cb/state breaker)]
(try
(let [result (thunk)]
(.recordSuccess breaker)
result)
(catch InterruptedException e
(when (= :half-open execution-state)
(.recordFailure breaker))
(throw e))
(catch Exception e
(cond
(service-failure? e) (.recordException breaker e)
(= :half-open execution-state) (.recordSuccess breaker))
(throw e))
(catch Throwable t
;; Every half-open permit must record an outcome, even when the JVM-level failure itself should
;; propagate unchanged rather than contribute to the service-failure history.
(when (= :half-open execution-state)
(.recordFailure breaker))
(throw t)))))))
(defn- validate-embeddings!
[embeddings expected-count expected-dimensions]
(when-not (= expected-count (count embeddings))
(throw (ex-info "Embedding response contained an unexpected number of vectors"
{:cause :embedder/invalid-response
:expected-count expected-count
:actual-count (count embeddings)})))
(doseq [embedding embeddings]
(when-not (= expected-dimensions (count embedding))
(throw (ex-info "Embedding response contained a vector with unexpected dimensions"
{:cause :embedder/unexpected-dimensions
:expected-dimensions expected-dimensions
:actual-dimensions (count embedding)})))
(when-not (every? #(Double/isFinite (double %)) embedding)
(throw (ex-info "Embedding response contained a non-finite value"
{:cause :embedder/invalid-response}))))
embeddings)
;;;; Ollama impl
(def ^:private ollama-embeddings-endpoint
"http://localhost:11434/api/embeddings") ;; TODO: we should make the host configurable
(defmethod embedder-circuit-endpoint "ollama" [_] ollama-embeddings-endpoint)
(defn- ollama-get-embedding [model-name vector-dimensions text]
(try
;; TODO count ollama tokens into :metabase-search/semantic-embedding-tokens?
(log/debug "Generating Ollama embedding for text of length:" (count text))
(let [embedding (-> (http/post ollama-embeddings-endpoint
(merge embedding-http-timeouts
{:headers {"Content-Type" "application/json"}
:body (json/encode {:model model-name
:prompt text})}))
:body
(json/decode true)
:embedding)]
(first (validate-embeddings! [embedding] 1 vector-dimensions)))
(catch Exception e
(log/error "Failed to generate Ollama embedding for text of length" (count text) ":" (ex-message e))
(throw e))))
(defn- ollama-pull-model [model-name]
(try
(log/debug "Pulling embedding model from Ollama...")
(http/post "http://localhost:11434/api/pull" ;; TODO: make the host configurable
(merge embedding-http-timeouts
{:headers {"Content-Type" "application/json"}
:body (json/encode {:model model-name})}))
(catch Exception e
(log/errorf "Failed to pull embedding model: %s" (ex-message e))
(throw e))))
;; Ollama is not used in production. Token tracking is not implemented.
(defn- ollama-get-embeddings-batch [model-name vector-dimensions texts]
;; Ollama doesn't have a native batch API, so we fall back to individual calls. Each call goes through the
;; breaker on its own, so an outage mid-batch fast-fails the remaining texts instead of timing out on each.
(log/debug "Generating" (count texts) "Ollama embeddings (using individual calls)")
(mapv (fn [text]
(call-through-embedder-breaker #(ollama-get-embedding model-name vector-dimensions text)
:endpoint ollama-embeddings-endpoint))
texts))
;;;; OpenAI-compatible embedding service impl (shared by "ai-service" and "openai" providers)
(defn- supports-dimensions?
"Check whether the model's API supports dimensions in request's body. At the time of writing supported on OpenAI's
text-embedding-3-small and text-embedding-3-large. Should be supported also on newer models when those are out."
[{:keys [model-name] :as _embedding-model}]
(boolean
(when (string? model-name)
(str/starts-with? model-name "text-embedding-3"))))
(mu/defn- openai-compatible-get-embeddings-batch
"Call an OpenAI-compatible /v1/embeddings endpoint. The breaker guards only the remote request and
response decoding; analytics and token persistence happen after it returns.
`:provider` - label for analytics (e.g. \"ai-service\", \"openai\")
`:endpoint` - full URL including /v1/embeddings
`:api-key` - Bearer token. Left empty, an `:instance-token?` endpoint uses `premium-embedding-token`.
`:model-name` - model identifier sent in the request body
`:vector-dimensions` - expected dimensions of each returned vector
`:texts` - collection of input strings
`:record-tokens?` - true writes a `semantic_search_token_tracking` row, false skips it.
`:snowplow?` - optional; when true fires a Snowplow `token_usage` event
`:extra-body` - optional; merged into the request body (e.g. `{:dimensions 1024}`)
`:type` - optional; forwarded to the token-tracking row
`:network-policy-floor` optionally sets the minimum network access for a deployment-controlled endpoint; see
[[metabase.llm.settings/network-policy]]. `:instance-token?` marks an endpoint the deployment chose, the only
kind the instance token may be sent to."
[{:keys [provider endpoint api-key model-name vector-dimensions texts record-tokens? extra-body snowplow?
network-policy-floor instance-token?]
:as opts}
:- [:map {:closed true}
[:provider :string]
[:endpoint :string]
[:api-key {:optional true} [:maybe :string]]
[:model-name :string]
[:vector-dimensions pos-int?]
[:texts [:sequential :string]]
[:record-tokens? :boolean]
[:snowplow? {:optional true} [:maybe :boolean]]
[:extra-body {:optional true} [:maybe [:map {:closed true}
[:dimensions {:optional true} pos-int?]]]]
[:network-policy-floor {:optional true} [:maybe [:enum :external-only :allow-private :allow-all]]]
[:instance-token? {:optional true} [:maybe :boolean]]
[:type {:optional true} [:maybe [:enum :query :index]]]]]
;; Outside the try: a malformed endpoint is neither a service failure nor something to log per batch.
(let [policy-opts (llm.settings/llm-request-opts network-policy-floor endpoint)]
(try
(log/debug (str "Calling " provider " embeddings API")
{:endpoint endpoint :documents (count texts) :tokens (count-tokens-batch texts)})
(let [headers (merge {"Content-Type" "application/json"}
(if (and (empty? api-key) instance-token?)
{"x-metabase-instance-token"
(u/prog1 (premium-features/premium-embedding-token)
(when (nil? <>)
(throw (ex-info "Premium embedding token not set"
{:provider provider}))))}
{"Authorization" (str "Bearer " api-key)}))
request (merge embedding-http-timeouts
{:headers headers
:body (json/encode
(merge {:model model-name
:input texts
:encoding_format "base64"}
extra-body))}
policy-opts)
start-ms (u/start-timer)
{:keys [usage embeddings]}
(call-through-embedder-breaker
#(let [{:keys [usage data]} (-> (http/post endpoint request)
:body
(json/decode true))]
{:usage usage
:embeddings (validate-embeddings! (decode-embeddings data)
(count texts)
vector-dimensions)})
:endpoint endpoint)
total-tokens (:total_tokens usage 0)
prompt-tokens (:prompt_tokens usage total-tokens)]
(analytics/inc! :metabase-search/semantic-embedding-tokens
{:provider provider :model model-name}
total-tokens)
(when snowplow?
(analytics.core/track-token-usage!
{:snowplow true
:prometheus false ; already tracked via inc! above
:request-id (analytics.core/uuid->ai-service-hex-uuid (random-uuid))
:model-id model-name
:provider provider
:model-name model-name
:total-tokens total-tokens
:prompt-tokens prompt-tokens
:completion-tokens 0 ; embedding models don't produce completion tokens
:estimated-costs-usd 0.0
:duration-ms (long (u/since-ms start-ms))
:tag "embedding_generation"}))
(when record-tokens?
(semantic.models.token-tracking/record-tokens model-name (:type opts) total-tokens))
embeddings)
(catch ConnectException e
(llm.settings/rethrow-if-llm-network-policy-error! e endpoint)
(log/error (str "Failed to connect to " provider ": " (ex-message e)) {:endpoint endpoint})
(throw (ex-info (str provider " unavailable (connection refused)")
{:status 502 :endpoint endpoint}
e)))
(catch Exception e
(llm.settings/rethrow-if-llm-network-policy-error! e endpoint)
;; The breaker transition already logs the outage once. Fast-failed calls while it remains open are
;; expected and can be frequent, so do not emit a redundant error for every guarded request.
(when-not (= :embedder/circuit-open (:cause (ex-data e)))
(log/error (str "Failed to generate " provider " embeddings: " (ex-message e))
{:documents (count texts) :tokens (count-tokens-batch texts)}))
(throw e)))))
;;;; Embedding-service provider
(defn- trim-trailing-slashes
[s]
(cond-> s
(string? s) (-> (str/trim)
(str/replace #"/+$" ""))))
(defn- embedding-service-resolve-config!
"Return the embedding endpoint config as `{:endpoint :api-key :instance-token? :network-policy-floor}`.
Throw an ex-info with an `:error-code` when the settings cannot be used together.
Its message names the settings to change and never their values.
The `:instance-token?` flag says the request authenticates with the instance token, not its own API key.
The instance token only goes to an endpoint the environment chose, never to a URL stored in the app DB.
A base URL from the environment also gets the `:allow-private` policy floor.
That floor admits private addresses but still blocks loopback and link-local."
[]
;; Trust follows where each value came from.
;; A settings manager can store ee-embedding-service-base-url through the generic settings API.
;; An environment value comes from the deployment and skips the vetting setter.
(let [base-url (not-empty (semantic-settings/ee-embedding-service-base-url))
;; A whitespace-only environment URL still overrides the stored one, and normalizes to nil.
;; Checking base-url first keeps it from counting as an environment URL.
env-url? (boolean (and base-url (setting/env-var-value :ee-embedding-service-base-url)))
env-key? (some? (setting/env-var-value :ee-embedding-service-api-key))]
;; A key from the deployment only goes to a URL from the deployment.
;; This holds even when the URL was saved through the API before the key was set.
(when (and env-key? (not env-url?))
(throw (ex-info (str "Set " (setting/env-var-name :ee-embedding-service-base-url)
" alongside " (setting/env-var-name :ee-embedding-service-api-key)
"; an environment API key is only sent to an embedding service URL"
" from the environment.")
{:error-code :embedding-environment-key-requires-environment-url
:settings ["ee-embedding-service-base-url"
"ee-embedding-service-api-key"]})))
(if base-url
(let [api-key (semantic-settings/ee-embedding-service-api-key)]
(when-not (or env-url? (not-empty api-key))
(throw (ex-info (str "The embedding service base URL is set in the application database"
" and has no API key. Set " (setting/env-var-name :ee-embedding-service-base-url)
" to use the instance token, or configure an API key"
" in the application database.")
{:error-code :embedding-database-url-requires-api-key
:settings ["ee-embedding-service-base-url"
"ee-embedding-service-api-key"]})))
(cond-> {:endpoint (str (trim-trailing-slashes base-url) "/v1/embeddings")
:api-key api-key
:instance-token? env-url?}
env-url? (assoc :network-policy-floor :allow-private)))
(if-let [ai-service-url (not-empty (llm.settings/ai-service-base-url))]
(cond-> {:endpoint (str (trim-trailing-slashes ai-service-url) "/v1/embeddings")
:instance-token? true}
(setting/env-var-value :ai-service-base-url) (assoc :network-policy-floor :allow-private))
(throw (ex-info "Embedding service and ai service base URLs are not configured"
{:error-code :embedding-service-url-not-configured
:settings ["ee-embedding-service-base-url"
"ai-service-base-url"]}))))))
(defmethod embedder-circuit-endpoint "ai-service" [_]
(:endpoint (embedding-service-resolve-config!)))
(defn- ai-service-readiness
"Return `{:ready? true}` when [[embedding-service-resolve-config!]] accepts the current settings.
Otherwise return `{:ready? false}` with the refusal's `:message`, and any `:error-code` as `:reason`."
[_]
(try
(embedding-service-resolve-config!)
{:ready? true}
(catch clojure.lang.ExceptionInfo e
(let [reason (:error-code (ex-data e))]
(cond-> {:ready? false
:message (ex-message e)}
reason (assoc :reason reason))))))
(defn- ai-service-get-embeddings-batch
[{:keys [model-name vector-dimensions]} texts {:keys [record-tokens? type snowplow?] :or {snowplow? true}}]
(let [{:keys [endpoint api-key network-policy-floor instance-token?]} (embedding-service-resolve-config!)]
(openai-compatible-get-embeddings-batch
{:provider "ai-service"
:endpoint endpoint
:api-key api-key
:model-name model-name
:vector-dimensions vector-dimensions
:texts texts
:snowplow? snowplow?
:record-tokens? record-tokens?
:type type
:network-policy-floor network-policy-floor
:instance-token? instance-token?})))
;;;; OpenAI provider
(defn- named-connection-key
[]
(let [provider (semantic-settings/ee-embedding-provider)]
(when-not (embeddings.provider/registered? provider)
provider)))
(defn- openai-connection-key
[]
(or (named-connection-key) "openai"))
(defn- openai-connection-config
[conn-key]
(let [{:keys [type config]} (llm.provider/connection conn-key)]
(when (= "openai" type)
(llm.provider/with-field-defaults type config))))
(defn- openai-resolve-config!
"Returns [endpoint api-key] or throws if not configured."
[conn-key]
(let [{:keys [api-key base-url]} (openai-connection-config conn-key)]
(when-not (not-empty api-key)
(throw (ex-info (str "The " (pr-str conn-key) " connection is not an OpenAI connection with an API key")
{:connection conn-key})))
[(str base-url "/v1/embeddings") api-key]))
(defmethod embedder-circuit-endpoint "openai" [_]
(first (openai-resolve-config! (openai-connection-key))))
(defn- openai-get-embeddings-batch
[embedding-model texts {:keys [record-tokens? type connection-key]}]
(let [[endpoint api-key] (openai-resolve-config! (or connection-key (openai-connection-key)))]
(openai-compatible-get-embeddings-batch
{:provider "openai"
:endpoint endpoint
:api-key api-key
:model-name (:model-name embedding-model)
:vector-dimensions (:vector-dimensions embedding-model)
:texts texts
:record-tokens? record-tokens?
:extra-body (when (supports-dimensions? embedding-model)
{:dimensions (:vector-dimensions embedding-model)})
:type type})))
(defn- register-built-in-providers!
[]
(let [spi-version embeddings.provider/embedding-spi-version
legacy embeddings.provider/legacy-resolved-model]
(embeddings.provider/register-provider!
"ollama"
{:embedding-spi-version spi-version
:readiness (constantly {:ready? true})
:resolve-model legacy
:embed-texts (fn [{:keys [model-name vector-dimensions]} texts _opts]
(ollama-get-embeddings-batch model-name vector-dimensions texts))
:prepare! (fn [{:keys [model-name]}]
(ollama-pull-model model-name))})
(embeddings.provider/register-provider!
"ai-service"
{:embedding-spi-version spi-version
:readiness ai-service-readiness
:resolve-model legacy
:embed-texts ai-service-get-embeddings-batch})
(embeddings.provider/register-provider!
"openai"
{:embedding-spi-version spi-version
:readiness (fn [_]
{:ready? (boolean (not-empty (:api-key (openai-connection-config
(openai-connection-key)))))})
:resolve-model legacy
:embed-texts openai-get-embeddings-batch})))
(register-built-in-providers!)
;;;; Query prefixes for asymmetric retrieval models
(def ^:private model-family-query-prefixes
"Query prefixes for embedding-model families trained for asymmetric retrieval.
These models expect search queries — but not the indexed documents — to carry a fixed prefix.
First match wins, so keep more specific patterns first."
;; Arctic Embed moved to the short "query: " prefix at v2.0. Everything earlier expects the original
;; longer instruction: v1 (xs, s, m, m-long, l) and v1.5 alike, including the bundled xs model.
;; Keep patterns narrow: a false positive is unfixable without a code change, since the
;; `ee-embedding-query-prefix` setting can only replace a matched prefix, never suppress it.
;; Hence the leading anchor, so an unrelated model that merely contains the family name is left alone.
[[#"(?i)(?:^|/)snowflake-arctic-embed-\w+-v[2-9]" "query: "]
[#"(?i)(?:^|/)snowflake-arctic-embed(?:-|$)" "Represent this sentence for searching relevant passages: "]])
(defn- default-query-prefix
[model-name]
(when model-name
(some (fn [[pattern prefix]]
(when (re-find pattern model-name)
prefix))
model-family-query-prefixes)))
(defn prefix-search-query
"Prepend the query prefix expected by `embedding-model` to `search-string`.
The `ee-embedding-query-prefix` setting overrides the per-model-family default and is prepended verbatim.
Returns `search-string` unchanged when neither applies."
[embedding-model search-string]
(str (or (not-empty (semantic-settings/ee-embedding-query-prefix))
(default-query-prefix (:model-name embedding-model)))
search-string))
;;;; Global embedding model
(defn get-configured-model
"Get the environments default embedding model according to the ee-embedding-provider / ee-embedding-model settings.
A registered embedder's name always means that embedder. Any other value that names an OpenAI connection embeds
through it as the `openai` provider."
[]
{:provider (or (some-> (named-connection-key) llm.provider/connection :type #{"openai"})
(semantic-settings/ee-embedding-provider))
:model-name (semantic-settings/ee-embedding-model)
:vector-dimensions (semantic-settings/ee-embedding-model-dimensions)})
(defn embedding-supported?
"Whether the selected provider is installed and configured. This is not a remote liveness probe."
[embedding-model]
(embeddings.provider/ready? embedding-model))
(defn- calc-token-metrics
[texts]
(let [counts (map count-tokens texts)
avg-raw (/ (reduce + counts) (count counts))]
{:n (count texts)
:min (apply min counts)
:max (apply max counts)
:sum (reduce + counts)
:avg (parse-double (format "%.2f" (double avg-raw)))}))
(defn process-embeddings-streaming
"Process texts in provider-appropriate batches, calling process-fn for each batch. process-fn will be called with
a map from text to embedding for each batch."
[embedding-model texts process-fn & {:as opts}]
(when (seq texts)
(let [{:keys [model-name provider vector-dimensions]} embedding-model]
(tracing/with-span :search "search.semantic.embeddings-batch"
{:search.semantic/provider provider
:search.semantic/model-name model-name
:search.semantic/text-count (count texts)}
(u/profile (str "Generating embeddings " {:model model-name
:dimensions vector-dimensions
:texts (calc-token-metrics texts)})
(if (= "openai" provider)
(let [max-tokens-per-batch (semantic-settings/openai-max-tokens-per-batch)
batches (create-batches max-tokens-per-batch count-tokens texts)
process-batch
(fn [batch-idx batch-texts]
(let [embeddings (u/profile (format "Embedding batch %d/%d %s"
(inc batch-idx) (count batches) (str (calc-token-metrics batch-texts)))
(get-embeddings-batch embedding-model batch-texts opts))
text-embedding-map (zipmap batch-texts embeddings)]
(process-fn text-embedding-map)))]
(transduce (map-indexed process-batch) (partial merge-with +) batches))
(let [embeddings (get-embeddings-batch embedding-model texts opts)
text-embedding-map (zipmap texts embeddings)]
(process-fn text-embedding-map))))))))
(comment
;; Configuration:
;; MB_EE_EMBEDDING_PROVIDER: "ai-service" (default), "ollama", "in-process", or the key of an AI provider connection
;; MB_EE_EMBEDDING_MODEL: optional override (leave empty for provider defaults)
;; - OpenAI default: "text-embedding-3-small"
;; - Ollama default: "mxbai-embed-large"
;; MB_EE_EMBEDDING_SERVICE_BASE_URL: URL of the embedding service (for ai-service provider)
;; MB_EE_EMBEDDING_SERVICE_API_KEY: API key for the embedding service
;; MB_EE_EMBEDDING_MODEL_DIMENSIONS: defaults to 1024.
(def embedding-model (get-configured-model))
embedding-model
(pull-model embedding-model)
(get-embedding embedding-model "hello"))