The personal finance app for everyone (by everyone)
Ruby
Keep the saved OpenAI key off custom embedding endpoints (#5659)
David Gila369353865b8
diff --git a/app/models/ai/legacy_env_config.rb b/app/models/ai/legacy_env_config.rbindex d20a06a08c..462a67cbd4 100644--- a/app/models/ai/legacy_env_config.rb+++ b/app/models/ai/legacy_env_config.rb@@ -6,7 +6,8 @@# (Provider::Registry and the providers it builds, Assistant::External.config), this calls it, so# the router and the calls not yet on the router can't disagree. test/architecture/ai_config_test# checks that over every documented setup. The one deliberate difference: embeddings fall back-# to the OpenAI values saved in Settings, as every other AI setting does.+# to the OpenAI values saved in Settings, as every other AI setting does (the saved key only for the+# OpenAI URL).## It's built in every process. The release that stops reading the old variables deletes this file.class Ai::LegacyEnvConfig@@ -146,10 +147,14 @@ class Ai::LegacyEnvConfigend# The URL and key fall back to the OpenAI values saved in Settings too. The URL is used as- # written, as VectorStore::Embeddable uses EMBEDDING_URI_BASE.+ # written, as VectorStore::Embeddable uses EMBEDDING_URI_BASE. The key saved in Settings goes+ # only to the OpenAI URL it was saved with, never to a separate embedding server;+ # OPENAI_ACCESS_TOKEN falls back as it always has.def embedding_model- base_url = env("EMBEDDING_URI_BASE") || openai_uri_base || VectorStore::DEFAULT_EMBEDDING_URI_BASE- api_key = env("EMBEDDING_ACCESS_TOKEN") || env("OPENAI_ACCESS_TOKEN") || Setting.openai_access_token.presence+ own_url = env("EMBEDDING_URI_BASE")+ base_url = own_url || openai_uri_base || VectorStore::DEFAULT_EMBEDDING_URI_BASE+ saved_key = Setting.openai_access_token.presence if own_url.nil? || same_server?(own_url, openai_uri_base)+ api_key = env("EMBEDDING_ACCESS_TOKEN") || env("OPENAI_ACCESS_TOKEN") || saved_keyendpoint = Ai::Config::Endpoint.new(name: "embed", protocol: :compatible, base_url:, api_key:, location: location_for(base_url),timeout_seconds: EMBEDDING_TIMEOUT, exact_base_url: true@@ -160,6 +165,22 @@ class Ai::LegacyEnvConfig)end+ # Whether two OpenAI-compatible base URLs name one server: scheme and host ignore case, the path+ # keeps it, a default port is no port. A blank one is OpenAI's.+ def same_server?(url, other)+ return true if [ url, other ].all? { _1.blank? || Provider::Openai.hosted_endpoint?(_1) }++ server, other_server = [ url, other ].map { server_of(_1) }+ server.present? && server == other_server+ end++ def server_of(url)+ uri = URI.parse(Ai::Transport::Http.compatible_base(url))+ [ uri.scheme.downcase, uri.host.downcase, uri.port, uri.path ] if uri.scheme && uri.host+ rescue URI::InvalidURIError+ nil+ end+def route_list(feature, models, conditions: {})models.map { |model| Ai::Route.new(feature:, model:, condition: conditions[model]) }enddiff --git a/docs/hosting/ai.md b/docs/hosting/ai.mdindex c76291c3d4..79dda111c6 100644--- a/docs/hosting/ai.md+++ b/docs/hosting/ai.md@@ -1676,12 +1676,16 @@ VECTOR_STORE_PROVIDER=pgvectorEMBEDDING_MODEL=mxbai-embed-large # Default: mxbai-embed-largeEMBEDDING_DIMENSIONS=1024 # Default: 1024 (must match your model)EMBEDDING_URI_BASE=http://ollama:11434/v1 # Falls back to the OpenAI API Base URL (ENV or Settings) if not set-EMBEDDING_ACCESS_TOKEN= # Falls back to the OpenAI Access Token (ENV or Settings) if not set+EMBEDDING_ACCESS_TOKEN= # Falls back to OPENAI_ACCESS_TOKEN, or to the token saved in Settings for the OpenAI URL```The fallbacks include values saved in **Settings** → **Self-Hosting**. Before this release theyread only `OPENAI_URI_BASE` and `OPENAI_ACCESS_TOKEN` from the environment, so an install that set-its OpenAI endpoint in Settings sent embeddings to `https://api.openai.com/v1/` without a key.+its OpenAI endpoint in Settings sent embeddings to `https://api.openai.com/v1/` without a key. The+access token saved in Settings is sent only to the OpenAI URL it was saved with: a separate+`EMBEDDING_URI_BASE` that needs a key needs `EMBEDDING_ACCESS_TOKEN`. `OPENAI_ACCESS_TOKEN` set in+the environment still goes to a separate `EMBEDDING_URI_BASE` when `EMBEDDING_ACCESS_TOKEN` is+empty, as it did before this release.Sure enables the `vector` extension when it first provisions the chunks table,provided the database user has permission. If the AI status page reports thatdiff --git a/test/models/ai/legacy_env_config_test.rb b/test/models/ai/legacy_env_config_test.rbindex ddd2dace50..fd664365d7 100644--- a/test/models/ai/legacy_env_config_test.rb+++ b/test/models/ai/legacy_env_config_test.rb@@ -125,6 +125,40 @@ class Ai::LegacyEnvConfigTest < ActiveSupport::TestCaseassert_equal "sk-setting", endpoint.api_keyend+ test "the OpenAI key saved in Settings goes only to the OpenAI URL, not to a separate embedding server" do+ VectorStore::Pgvector.stubs(:available?).returns(true)+ Setting.openai_access_token = "sk-saved"++ separate = build("VECTOR_STORE_PROVIDER" => "pgvector", "EMBEDDING_URI_BASE" => "http://embeddings.example.test:11434/v1")+ inherited = build("VECTOR_STORE_PROVIDER" => "pgvector")+ same = build("VECTOR_STORE_PROVIDER" => "pgvector", "EMBEDDING_URI_BASE" => "https://api.openai.com/v1/")++ assert_nil first_model(separate, :embed).endpoint.api_key+ assert_equal "sk-saved", first_model(inherited, :embed).endpoint.api_key+ assert_equal "sk-saved", first_model(same, :embed).endpoint.api_key, "OpenAI's own URL written out is the same server"+ end++ test "the saved key goes to EMBEDDING_URI_BASE when it is the OpenAI URL saved with it, and nowhere else on that host" do+ VectorStore::Pgvector.stubs(:available?).returns(true)+ Setting.openai_access_token = "sk-saved"+ Setting.openai_uri_base = "https://gateway.example.test/TenantA/v1"++ same = build("VECTOR_STORE_PROVIDER" => "pgvector", "EMBEDDING_URI_BASE" => "https://GATEWAY.example.test:443/TenantA/v1/")+ other_tenant = build("VECTOR_STORE_PROVIDER" => "pgvector", "EMBEDDING_URI_BASE" => "https://gateway.example.test/tenanta/v1")++ assert_equal "sk-saved", first_model(same, :embed).endpoint.api_key+ assert_nil first_model(other_tenant, :embed).endpoint.api_key+ end++ test "EMBEDDING_ACCESS_TOKEN and OPENAI_ACCESS_TOKEN still reach a separate embedding server, as before the router" do+ VectorStore::Pgvector.stubs(:available?).returns(true)+ Setting.openai_access_token = "sk-saved"+ separate = { "VECTOR_STORE_PROVIDER" => "pgvector", "EMBEDDING_URI_BASE" => "http://embeddings.example.test:11434/v1" }++ assert_equal "emb-env", first_model(build(separate.merge("EMBEDDING_ACCESS_TOKEN" => "emb-env")), :embed).endpoint.api_key+ assert_equal "sk-env", first_model(build(separate.merge("OPENAI_ACCESS_TOKEN" => "sk-env")), :embed).endpoint.api_key+ end+test "Jev is listed first for categorization, for families that chose it, when it can be built" doconfig = build("OPENAI_ACCESS_TOKEN" => "sk-test", "JEV_API_KEY" => "jev-test")jev = config.routes_for(:categorize).firstdiff --git a/test/models/vector_store/embeddable_test.rb b/test/models/vector_store/embeddable_test.rbindex d6eac0a04e..429da79188 100644--- a/test/models/vector_store/embeddable_test.rb+++ b/test/models/vector_store/embeddable_test.rb@@ -152,6 +152,31 @@ class VectorStore::EmbeddableTest < ActiveSupport::TestCaseassert_equal "token", @host.embedding_access_tokenend+ test "embed sends the OpenAI key saved in Settings to OpenAI only, and a separate server its own token" do+ VectorStore::Pgvector.stubs(:available?).returns(true)+ Setting.openai_access_token = "sk-saved"+ body = { "data" => [ { "embedding" => [ 0.1 ], "index" => 0 } ] }.to_json+ json = { "Content-Type" => "application/json" }+ separate = stub_request(:post, "http://embeddings.example.test:11434/v1/embeddings")+ .with { |request| request.headers["Authorization"].nil? }.to_return(body:, headers: json)+ separate_with_token = stub_request(:post, "http://embeddings.example.test:11434/v1/embeddings")+ .with(headers: { "Authorization" => "Bearer emb-token" }).to_return(body:, headers: json)+ openai = stub_request(:post, "https://api.openai.com/v1/embeddings")+ .with(headers: { "Authorization" => "Bearer sk-saved" }).to_return(body:, headers: json)++ embed_with = ->(env) do+ ai_env = %w[OPENAI_ACCESS_TOKEN OPENAI_URI_BASE EMBEDDING_ACCESS_TOKEN EMBEDDING_URI_BASE].index_with { nil }+ with_env_overrides(ai_env.merge("VECTOR_STORE_PROVIDER" => "pgvector").merge(env)) { EmbeddableHost.new.embed("text") }+ end+ embed_with.call("EMBEDDING_URI_BASE" => "http://embeddings.example.test:11434/v1")+ embed_with.call("EMBEDDING_URI_BASE" => "http://embeddings.example.test:11434/v1", "EMBEDDING_ACCESS_TOKEN" => "emb-token")+ embed_with.call({})++ assert_requested separate, times: 1+ assert_requested separate_with_token, times: 1+ assert_requested openai, times: 1+ end+# --- embed_batch ---test "embed_batch processes texts and returns ordered vectors" do