The personal finance app for everyone (by everyone)
Ruby
feat(ai): support OPENAI_EXTRA_HEADERS on the OpenAI-compatible provider (#3362)
Joe Maplescc826df909ec
diff --git a/.env.example b/.env.exampleindex fcc16316fb..1380e90537 100644--- a/.env.example+++ b/.env.example@@ -60,6 +60,7 @@ OPENAI_URI_BASE=# Optional: OpenAI-compatible capability flags# OPENAI_REQUEST_TIMEOUT=60 # HTTP timeout in seconds; raise for slow local models+# OPENAI_EXTRA_HEADERS='{"x-opencode-session":"{session_id}"}' # Extra JSON headers for chat requests; value containing {session_id} becomes the chat UUID# OPENAI_SUPPORTS_PDF_PROCESSING=true # Set to false for endpoints without vision support# OPENAI_SUPPORTS_RESPONSES_ENDPOINT= # Override Responses-API vs chat.completions routing# LLM_JSON_MODE= # auto | strict | json_object | nonediff --git a/.env.local.example b/.env.local.exampleindex dd2dca0763..21c29120c2 100644--- a/.env.local.example+++ b/.env.local.example@@ -50,6 +50,7 @@ OPENAI_MODEL =# OpenAI-compatible capability flags (custom/self-hosted providers)# OPENAI_REQUEST_TIMEOUT = 60 # HTTP timeout in seconds; raise for slow local models+# OPENAI_EXTRA_HEADERS = '{"x-opencode-session":"{session_id}"}' # Extra JSON headers for chat requests; value containing {session_id} becomes the chat UUID# AI_RESPONSE_TIMEOUT = 90 # Whole-turn budget: (1 + iterations) * OPENAI_REQUEST_TIMEOUT + tool time + queue wait# ASSISTANT_MAX_TOOL_CALL_ITERATIONS = 5 # Chained tool calls per turn; a turn costs up to (1 + this) model calls# OPENAI_SUPPORTS_PDF_PROCESSING = true # Set to false for endpoints without vision supportdiff --git a/app/models/provider/openai.rb b/app/models/provider/openai.rbindex 29c095ce99..44a59455f7 100644--- a/app/models/provider/openai.rb+++ b/app/models/provider/openai.rb@@ -22,6 +22,8 @@ class Provider::Openai < Provider# Effective per-request HTTP timeout for OpenAI-compatible calls.# Precedence matches other self-hosting settings: ENV > Setting > default.+ #+ # @return [Integer] timeout in seconds, at least MIN_REQUEST_TIMEOUTdef self.request_timeoutconfigured = ENV["OPENAI_REQUEST_TIMEOUT"].to_s.strip.to_iconfigured = Setting.openai_request_timeout.to_i unless configured.positive?@@ -30,13 +32,47 @@ class Provider::Openai < Provider[ configured, MIN_REQUEST_TIMEOUT ].maxend+ # Extra HTTP headers for OpenAI-compatible requests, parsed from the+ # OPENAI_EXTRA_HEADERS env var (a JSON object). ENV-only: no Setting+ # fallback. Keys and values are stringified for Faraday; blank values are+ # dropped. Nested JSON values are Ruby-inspect-stringified, not+ # JSON-serialized. Fail-closed: any parse problem yields {} plus an error+ # log (raw value never logged) so chat never breaks from bad config.+ #+ # @return [Hash<String, String>] parsed headers, {} when unset or invalid+ def self.extra_headers+ raw = ENV["OPENAI_EXTRA_HEADERS"].presence+ return {} unless raw++ parsed = JSON.parse(raw)+ unless parsed.is_a?(Hash)+ Rails.logger.error("OPENAI_EXTRA_HEADERS must be a JSON object; ignoring")+ return {}+ end+ parsed.transform_keys(&:to_s).transform_values(&:to_s).compact_blank+ rescue JSON::ParserError, TypeError+ Rails.logger.error("OPENAI_EXTRA_HEADERS is not valid JSON; ignoring")+ {}+ end+# Builds a client that uses the effective request timeout for every OpenAI call.+ # Static extra headers from OPENAI_EXTRA_HEADERS are attached at construction;+ # session-valued headers are withheld for per-request resolution.+ #+ # @param access_token [String] API token for the OpenAI-compatible endpoint+ # @param uri_base [String, nil] custom endpoint base URL (OpenAI when nil)+ # @param model [String, nil] default model; required when uri_base is set+ # @return [void]def initialize(access_token, uri_base: nil, model: nil)client_options = { access_token: access_token }llm_uri_base = uri_base.presencellm_model = model.presenceclient_options[:uri_base] = llm_uri_base if llm_uri_base.present?client_options[:request_timeout] = self.class.request_timeout+ parsed_headers = self.class.extra_headers+ @session_extra_headers = parsed_headers.select { |_, value| value.include?("{session_id}") }+ static_headers = parsed_headers.except(*@session_extra_headers.keys)+ client_options[:extra_headers] = static_headers if static_headers.present?@client = ::OpenAI::Client.new(**client_options)@uri_base = llm_uri_base@@ -373,6 +409,26 @@ class Provider::Openai < Providerprivateattr_reader :client+ # Substitutes {session_id} into session-valued extra headers for this chat+ # request. Static headers were already set at construction; a session+ # header without a session_id is simply never applied. Returns a+ # request-scoped client copy carrying the resolved headers — session+ # headers must not persist on the shared client, so later batch requests+ # (which reuse this provider instance's client) never see them.+ #+ # @param session_id [String, nil] chat session UUID to substitute+ # @return [OpenAI::Client] scoped copy when session headers apply, otherwise+ # the shared client+ def with_session_headers(session_id:)+ return client if @session_extra_headers.blank? || session_id.blank?++ session_client = client.dup+ session_client.add_headers(+ @session_extra_headers.transform_values { |value| value.gsub("{session_id}") { session_id } }+ )+ session_client+ end+# Returns the first positive integer among env, setting, default. Treats# zero or negative values as "unset" and falls through — a 0-token budget# is never what the user meant.@@ -410,6 +466,8 @@ class Provider::Openai < Providerfamily: nil)with_provider_response do+ session_client = with_session_headers(session_id: session_id)+chat_config = ChatConfig.new(functions: functions,function_results: function_results@@ -445,7 +503,7 @@ class Provider::Openai < Providerrequest_params[:tool_choice] = "none" if tool_choice == :none && chat_config.tools.present?request_params[:max_output_tokens] = explicit_max_response_tokens if explicit_max_response_tokens- raw_response = client.responses.create(parameters: request_params)+ raw_response = session_client.responses.create(parameters: request_params)# If streaming, Ruby OpenAI does not return anything, so to normalize this method's API, we search# for the "response chunk" in the stream and return it (it is already parsed)@@ -518,6 +576,8 @@ class Provider::Openai < Providerfamily: nil)with_provider_response do+ session_client = with_session_headers(session_id: session_id)+messages = build_generic_messages(prompt: prompt,instructions: instructions,@@ -537,7 +597,7 @@ class Provider::Openai < Providerparams[:max_tokens] = explicit_max_response_tokens if explicit_max_response_tokensbegin- raw_response = client.chat(parameters: params)+ raw_response = session_client.chat(parameters: params)parsed = GenericChatParser.new(raw_response).parseddiff --git a/docs/hosting/ai.md b/docs/hosting/ai.mdindex 15fb6469b1..4587687820 100644--- a/docs/hosting/ai.md+++ b/docs/hosting/ai.md@@ -118,6 +118,9 @@ OPENAI_ACCESS_TOKEN=sk-proj-...# Optional: Request timeout in seconds (default: 60)# OPENAI_REQUEST_TIMEOUT=60++# Optional: extra HTTP headers as a JSON object (see "Extra HTTP Headers" below)+# OPENAI_EXTRA_HEADERS='{"x-opencode-session":"{session_id}"}'```**Recommended models:**@@ -167,6 +170,33 @@ Any service offering an OpenAI-compatible API should work:- [Anyscale](https://www.anyscale.com/) - Llama models- [Replicate](https://replicate.com/) - Various models+### Extra HTTP Headers++Some gateways require custom headers on requests to OpenAI-compatible+endpoints (e.g. OpenRouter's `HTTP-Referer`). Set `OPENAI_EXTRA_HEADERS`+to a JSON object mapping header names to values:++```bash+# Single-quoted so the shell does not interpret braces or quotes.+# A value containing the literal {session_id} is replaced with the chat's UUID+# on each chat request, identifying the conversation rather than the install.+OPENAI_EXTRA_HEADERS='{"x-opencode-session":"{session_id}"}'++# Static value instead — sent on every OpenAI-provider request, including+# batch jobs (auto-categorize, merchant detection, PDF processing):+OPENAI_EXTRA_HEADERS='{"x-opencode-session":"b3f1c2d4-0000-0000-0000-000000000000"}'+```++Behavior:++- A value containing the literal `{session_id}` is substituted with the chat's UUID on each chat request, so requests are attributable per conversation. Batch flows only receive static (non-`{session_id}`) headers, because a session only exists for a chat. If your gateway requires the header on every endpoint, use a static value.+- Extra headers are attached to **chat requests** made by the OpenAI-compatible provider. Batch flows (auto-categorize, merchant detection, PDF processing) only receive static headers.+- Values are stringified: nested JSON objects/arrays become Ruby inspect-style strings, not valid JSON. Header values must be plain strings.+- User headers merge over the client's managed headers — setting `Authorization` here would override the access token.+- Unset, blank, malformed, or non-object JSON is ignored with an error in the logs; chat keeps working. The raw value is never logged.+- These headers are NOT sent to embedding, vector-store, or AI-health-probe calls — those build separate clients. A gateway requiring the header on those endpoints is not supported.+- ENV-only: there is no settings-page equivalent. The value is re-read every time a provider client is built (nothing is cached), but updating the environment requires restarting the app.+## Local LLM Setup (Ollama)[Ollama](https://ollama.ai/) is the recommended tool for running LLMs locally.diff --git a/test/models/provider/openai_test.rb b/test/models/provider/openai_test.rbindex 10716bc9c9..33a2813f68 100644--- a/test/models/provider/openai_test.rb+++ b/test/models/provider/openai_test.rb@@ -26,7 +26,7 @@ class Provider::OpenaiTest < ActiveSupport::TestCaseendtest "request_timeout is passed to OpenAI client" do- with_env_overrides("OPENAI_REQUEST_TIMEOUT" => nil) do+ with_env_overrides("OPENAI_REQUEST_TIMEOUT" => nil, "OPENAI_EXTRA_HEADERS" => nil) doSetting.stubs(:openai_request_timeout).returns(180)::OpenAI::Client.expects(:new).with(access_token: "test-token", request_timeout: 180).returns(mock)@@ -34,6 +34,164 @@ class Provider::OpenaiTest < ActiveSupport::TestCaseendend+ test "extra_headers parses valid JSON, stringifies keys and values, drops blanks" do+ with_env_overrides("OPENAI_EXTRA_HEADERS" => '{"x-session": "abc", "Retry": 3, "empty": "", "drop": null}') do+ assert_equal({ "x-session" => "abc", "Retry" => "3" }, Provider::Openai.extra_headers)+ end+ end++ test "extra_headers stringifies nested values Ruby-style" do+ with_env_overrides("OPENAI_EXTRA_HEADERS" => '{"x-meta":{"a":1}}') do+ assert_equal({ "x-meta" => '{"a" => 1}' }, Provider::Openai.extra_headers)+ end+ end++ test "extra_headers returns empty hash for unset, blank, malformed, and non-object JSON" do+ with_env_overrides("OPENAI_EXTRA_HEADERS" => nil) do+ assert_equal({}, Provider::Openai.extra_headers)+ end++ with_env_overrides("OPENAI_EXTRA_HEADERS" => " ") do+ assert_equal({}, Provider::Openai.extra_headers)+ end++ with_env_overrides("OPENAI_EXTRA_HEADERS" => "{not json") do+ Rails.logger.expects(:error).with(regexp_matches(/OPENAI_EXTRA_HEADERS is not valid JSON/))+ assert_equal({}, Provider::Openai.extra_headers)+ end++ with_env_overrides("OPENAI_EXTRA_HEADERS" => "[1,2]") do+ Rails.logger.expects(:error).with(regexp_matches(/must be a JSON object/))+ assert_equal({}, Provider::Openai.extra_headers)+ end+ end++ test "client construction receives parsed extra_headers" do+ with_env_overrides(+ "OPENAI_REQUEST_TIMEOUT" => nil,+ "OPENAI_EXTRA_HEADERS" => '{"X-Static":"1"}'+ ) do+ Setting.stubs(:openai_request_timeout).returns(nil)+ ::OpenAI::Client.expects(:new).with(+ access_token: "test-token",+ request_timeout: 60,+ extra_headers: { "X-Static" => "1" }+ ).returns(mock)++ Provider::Openai.new("test-token")+ end+ end++ test "extra headers knob is documented in hosting docs and env examples" do+ doc = Rails.root.join("docs/hosting/ai.md").read+ assert_includes doc, "OPENAI_EXTRA_HEADERS"+ assert_includes doc, "{session_id}"++ assert_includes Rails.root.join(".env.example").read, "OPENAI_EXTRA_HEADERS"+ assert_includes Rails.root.join(".env.local.example").read, "OPENAI_EXTRA_HEADERS"+ end++ test "client construction receives static extra_headers only; session values withheld" do+ with_env_overrides(+ "OPENAI_REQUEST_TIMEOUT" => nil,+ "OPENAI_EXTRA_HEADERS" => '{"X-Static":"1","x-opencode-session":"sess-{session_id}"}'+ ) do+ Setting.stubs(:openai_request_timeout).returns(nil)+ ::OpenAI::Client.expects(:new).with(+ access_token: "test-token",+ request_timeout: 60,+ extra_headers: { "X-Static" => "1" }+ ).returns(mock)++ Provider::Openai.new("test-token")+ end+ end++ test "session headers substitute the chat id onto a request-scoped client copy" do+ with_env_overrides("OPENAI_EXTRA_HEADERS" => '{"x-opencode-session":"sess-{session_id}","X-Static":"1"}') do+ subject = Provider::Openai.new("test-token")+ fake_client = mock+ scoped_client = mock+ fake_client.expects(:dup).returns(scoped_client)+ scoped_client.expects(:add_headers).with({ "x-opencode-session" => "sess-chat-42" })+ subject.stubs(:client).returns(fake_client)++ assert_same scoped_client, subject.send(:with_session_headers, session_id: "chat-42")+ end+ end++ test "session headers are absent from the request when no session_id is given" do+ with_env_overrides("OPENAI_EXTRA_HEADERS" => '{"x-opencode-session":"sess-{session_id}"}') do+ subject = Provider::Openai.new("test-token")+ fake_client = mock+ fake_client.expects(:dup).never+ fake_client.expects(:add_headers).never+ subject.stubs(:client).returns(fake_client)++ assert_same subject.send(:client), subject.send(:with_session_headers, session_id: nil)+ end+ end++ test "session headers never persist onto the shared client after a chat request" do+ with_env_overrides("OPENAI_EXTRA_HEADERS" => '{"x-opencode-session":"sess-{session_id}"}') do+ subject = Provider::Openai.new("test-token")+ scoped_client = mock+ fake_client = mock+ fake_client.expects(:dup).returns(scoped_client)+ scoped_client.expects(:add_headers).with({ "x-opencode-session" => "sess-chat-42" })+ fake_client.expects(:responses).never+ subject.stubs(:client).returns(fake_client)++ scoped = subject.send(:with_session_headers, session_id: "chat-42")++ assert_same scoped_client, scoped+ assert_same fake_client, subject.send(:client)+ end+ end++ test "native chat path resolves session headers onto a request-scoped client" do+ with_env_overrides("OPENAI_EXTRA_HEADERS" => '{"x-opencode-session":"sess-{session_id}"}') do+ subject = Provider::Openai.new("test-token")+ fake_responses = mock+ scoped_client = mock+ scoped_client.stubs(:responses).returns(fake_responses)+ fake_client = mock+ fake_client.stubs(:dup).returns(scoped_client)+ scoped_client.expects(:add_headers).with({ "x-opencode-session" => "sess-chat-42" })+ fake_responses.stubs(:create).returns(+ { "id" => "resp_1", "model" => "gpt-4.1", "output" => [], "usage" => { "total_tokens" => 1 } }+ )+ subject.stubs(:client).returns(fake_client)++ response = subject.chat_response("hi", model: "gpt-4.1", session_id: "chat-42")++ assert response.success?+ end+ end++ test "generic chat path resolves session headers onto a request-scoped client" do+ with_env_overrides(+ "OPENAI_SUPPORTS_RESPONSES_ENDPOINT" => "false",+ "OPENAI_EXTRA_HEADERS" => '{"x-opencode-session":"sess-{session_id}"}'+ ) do+ subject = Provider::Openai.new("test-token")+ scoped_client = mock+ fake_client = mock+ fake_client.stubs(:dup).returns(scoped_client)+ scoped_client.expects(:add_headers).with({ "x-opencode-session" => "sess-chat-42" })+ scoped_client.stubs(:chat).returns(+ { "id" => "resp_1", "model" => "gpt-4.1", "choices" => [ { "message" => { "content" => "Yes" } } ],+ "usage" => { "total_tokens" => 1 } }+ )+ subject.stubs(:client).returns(fake_client)++ response = subject.chat_response("hi", model: "gpt-4.1", session_id: "chat-42")++ assert response.success?+ assert_equal "Yes", response.data.messages.first.output_text+ end+ end+test "openai errors are automatically raised" doVCR.use_cassette("openai/chat/error") doresponse = @openai.chat_response("Test", model: "invalid-model-that-will-trigger-api-error")