Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

fix(provider): honor json_mode in the PDF document extraction path (#4261)

Shibu M57aa93de304c
diff --git a/app/models/provider/openai.rb b/app/models/provider/openai.rb
index bea435ce93..08a3b7f144 100644
--- a/app/models/provider/openai.rb
+++ b/app/models/provider/openai.rb
@@ -320,7 +320,7 @@ class Provider::Openai < Provider
# @param model [String] optional override of the configured model
# @param family [Family, nil] usage attribution
# @return [Provider::Response] structured result or provider failure
- def process_pdf(pdf_content:, model: "", family: nil)
+ def process_pdf(pdf_content:, model: "", family: nil, json_mode: nil)
with_provider_response do
effective_model = model.presence || @default_model
raise Error, "Model does not support PDF/vision processing: #{effective_model}" unless supports_pdf_processing?(model: effective_model)
@@ -345,7 +345,8 @@ class Provider::Openai < Provider
custom_provider: custom_provider?,
langfuse_trace: trace,
family: family,
- max_response_tokens: response_limit
+ max_response_tokens: response_limit,
+ json_mode: json_mode
).process
upsert_langfuse_trace(trace: trace, output: result.to_h)
@@ -354,7 +355,7 @@ class Provider::Openai < Provider
end
end
- def extract_bank_statement(pdf_content:, model: "", family: nil)
+ def extract_bank_statement(pdf_content:, model: "", family: nil, json_mode: nil)
with_provider_response do
effective_model = model.presence || @default_model
@@ -366,7 +367,8 @@ class Provider::Openai < Provider
result = BankStatementExtractor.new(
client: client,
pdf_content: pdf_content,
- model: effective_model
+ model: effective_model,
+ json_mode: json_mode
).extract
upsert_langfuse_trace(trace: trace, output: { transaction_count: result[:transactions].size })
diff --git a/app/models/provider/openai/auto_categorizer.rb b/app/models/provider/openai/auto_categorizer.rb
index bf412cfe05..d2c7c4d604 100644
--- a/app/models/provider/openai/auto_categorizer.rb
+++ b/app/models/provider/openai/auto_categorizer.rb
@@ -1,14 +1,6 @@
class Provider::Openai::AutoCategorizer
include Provider::Openai::Concerns::UsageRecorder
-
- # JSON response format modes for custom providers
- # - "strict": Use strict JSON schema (requires full OpenAI API compatibility)
- # - "json_object": Use json_object response format (broader compatibility)
- # - "none": No response format constraint (maximum compatibility with local LLMs)
- JSON_MODE_STRICT = "strict"
- JSON_MODE_OBJECT = "json_object"
- JSON_MODE_NONE = "none"
- JSON_MODE_AUTO = "auto"
+ include Provider::Openai::Concerns::JsonMode
# Threshold for auto mode: if more than this percentage returns null, retry with none mode
# This is a heuristic to detect when strict JSON mode is breaking the model's ability to reason
@@ -27,31 +19,6 @@ class Provider::Openai::AutoCategorizer
@json_mode = json_mode || default_json_mode
end
- VALID_JSON_MODES = [ JSON_MODE_STRICT, JSON_MODE_OBJECT, JSON_MODE_NONE, JSON_MODE_AUTO ].freeze
-
- # Determine default JSON mode based on configuration hierarchy:
- # 1. Environment variable (LLM_JSON_MODE) - highest priority, for testing/override
- # 2. Setting.openai_json_mode - user-configured in app settings
- # 3. Default: auto mode (recommended for all providers)
- #
- # Mode descriptions:
- # - "auto": Tries strict first, falls back to none if >50% fail (recommended default)
- # - "strict": Best for thinking models (qwen-thinking, deepseek-reasoner) - skips verbose <think> tags
- # - "none": Best for non-thinking models (gpt-oss, llama, mistral) - allows reasoning in output
- # - "json_object": Middle ground, broader compatibility than strict
- def default_json_mode
- # 1. Check environment variable first (allows runtime override for testing)
- env_mode = ENV["LLM_JSON_MODE"]
- return env_mode if env_mode.present? && VALID_JSON_MODES.include?(env_mode)
-
- # 2. Check app settings (user-configured)
- setting_mode = Setting.openai_json_mode
- return setting_mode if setting_mode.present? && VALID_JSON_MODES.include?(setting_mode)
-
- # 3. Default: auto mode for all providers (tries strict first, falls back to none if needed)
- JSON_MODE_AUTO
- end
-
def auto_categorize
if custom_provider
auto_categorize_openai_generic
@@ -219,20 +186,11 @@ class Provider::Openai::AutoCategorizer
}
# Add response format based on json_mode setting
- case mode
- when JSON_MODE_STRICT
- params[:response_format] = {
- type: "json_schema",
- json_schema: {
- name: "auto_categorize_personal_finance_transactions",
- strict: true,
- schema: json_schema
- }
- }
- when JSON_MODE_OBJECT
- params[:response_format] = { type: "json_object" }
- # JSON_MODE_NONE: no response_format constraint
- end
+ apply_json_mode(params, mode: mode, schema: {
+ name: "auto_categorize_personal_finance_transactions",
+ strict: true,
+ schema: json_schema
+ })
response = client.chat(parameters: params)
diff --git a/app/models/provider/openai/auto_merchant_detector.rb b/app/models/provider/openai/auto_merchant_detector.rb
index 3fb040539d..cb018ba58f 100644
--- a/app/models/provider/openai/auto_merchant_detector.rb
+++ b/app/models/provider/openai/auto_merchant_detector.rb
@@ -1,15 +1,6 @@
class Provider::Openai::AutoMerchantDetector
include Provider::Openai::Concerns::UsageRecorder
-
- # JSON response format modes for custom providers
- # - "strict": Use strict JSON schema (requires full OpenAI API compatibility)
- # - "json_object": Use json_object response format (broader compatibility)
- # - "none": No response format constraint (maximum compatibility with local LLMs)
- # - "auto": Try strict first, fall back to none if poor results
- JSON_MODE_STRICT = "strict"
- JSON_MODE_OBJECT = "json_object"
- JSON_MODE_NONE = "none"
- JSON_MODE_AUTO = "auto"
+ include Provider::Openai::Concerns::JsonMode
# Threshold for auto mode: if more than this percentage returns null, retry with none mode
AUTO_MODE_NULL_THRESHOLD = 0.5
@@ -27,31 +18,6 @@ class Provider::Openai::AutoMerchantDetector
@json_mode = json_mode || default_json_mode
end
- VALID_JSON_MODES = [ JSON_MODE_STRICT, JSON_MODE_OBJECT, JSON_MODE_NONE, JSON_MODE_AUTO ].freeze
-
- # Determine default JSON mode based on configuration hierarchy:
- # 1. Environment variable (LLM_JSON_MODE) - highest priority, for testing/override
- # 2. Setting.openai_json_mode - user-configured in app settings
- # 3. Default: auto mode (recommended for all providers)
- #
- # Mode descriptions:
- # - "auto": Tries strict first, falls back to none if >50% fail (recommended default)
- # - "strict": Best for thinking models (qwen-thinking, deepseek-reasoner) - skips verbose <think> tags
- # - "none": Best for non-thinking models (gpt-oss, llama, mistral) - allows reasoning in output
- # - "json_object": Middle ground, broader compatibility than strict
- def default_json_mode
- # 1. Check environment variable first (allows runtime override for testing)
- env_mode = ENV["LLM_JSON_MODE"]
- return env_mode if env_mode.present? && VALID_JSON_MODES.include?(env_mode)
-
- # 2. Check app settings (user-configured)
- setting_mode = Setting.openai_json_mode
- return setting_mode if setting_mode.present? && VALID_JSON_MODES.include?(setting_mode)
-
- # 3. Default: auto mode for all providers (tries strict first, falls back to none if needed)
- JSON_MODE_AUTO
- end
-
def auto_detect_merchants
if custom_provider
auto_detect_merchants_openai_generic
@@ -228,20 +194,11 @@ class Provider::Openai::AutoMerchantDetector
}
# Add response format based on json_mode setting
- case mode
- when JSON_MODE_STRICT
- params[:response_format] = {
- type: "json_schema",
- json_schema: {
- name: "auto_detect_personal_finance_merchants",
- strict: true,
- schema: json_schema
- }
- }
- when JSON_MODE_OBJECT
- params[:response_format] = { type: "json_object" }
- # JSON_MODE_NONE: no response_format constraint
- end
+ apply_json_mode(params, mode: mode, schema: {
+ name: "auto_detect_personal_finance_merchants",
+ strict: true,
+ schema: json_schema
+ })
response = client.chat(parameters: params)
diff --git a/app/models/provider/openai/bank_statement_extractor.rb b/app/models/provider/openai/bank_statement_extractor.rb
index 59456d80bf..c1871399d1 100644
--- a/app/models/provider/openai/bank_statement_extractor.rb
+++ b/app/models/provider/openai/bank_statement_extractor.rb
@@ -1,11 +1,14 @@
class Provider::Openai::BankStatementExtractor
+ include Provider::Openai::Concerns::JsonMode
+
MAX_CHARS_PER_CHUNK = 3000
- attr_reader :client, :pdf_content, :model
+ attr_reader :client, :pdf_content, :model, :json_mode
- def initialize(client:, pdf_content:, model:)
+ def initialize(client:, pdf_content:, model:, json_mode: nil)
@client = client
@pdf_content = pdf_content
@model = model
+ @json_mode = json_mode || default_json_mode
end
def extract
@@ -103,10 +106,11 @@ class Provider::Openai::BankStatementExtractor
messages: [
{ role: "system", content: is_first_chunk ? instructions_with_metadata : instructions_transactions_only },
{ role: "user", content: "Extract transactions:\n\n#{text}" }
- ],
- response_format: { type: "json_object" }
+ ]
}
+ apply_json_mode(params, mode: json_mode)
+
response = client.chat(parameters: params)
content = response.dig("choices", 0, "message", "content")
diff --git a/app/models/provider/openai/concerns/json_mode.rb b/app/models/provider/openai/concerns/json_mode.rb
new file mode 100644
index 0000000000..72dcab7150
--- /dev/null
+++ b/app/models/provider/openai/concerns/json_mode.rb
@@ -0,0 +1,75 @@
+# Resolves the JSON response-format mode and applies it to a chat params hash.
+#
+# Every provider call that asks the model for structured output has to decide
+# how hard to constrain decoding. `response_format` is the OpenAI parameter for
+# that, but it is also the most widely rejected parameter across
+# OpenAI-compatible runtimes -- LM Studio, for example, answers
+# "'response_format.type' must be 'json_schema' or 'text'" and never reaches the
+# model. Self-hosters need a way to turn the constraint off without patching the
+# app, which is what JSON_MODE_NONE is for.
+#
+# This concern was extracted from the identical copies that previously lived in
+# AutoCategorizer, AutoMerchantDetector, and ProviderMerchantEnhancer. Those
+# classes resolved the mode but not all of them applied it, and the document
+# extraction path (BankStatementExtractor, PdfProcessor) applied neither -- it
+# hardcoded `json_object`.
+module Provider::Openai::Concerns::JsonMode
+ extend ActiveSupport::Concern
+
+ # JSON response format modes for custom providers
+ # - "strict": Use strict JSON schema (requires full OpenAI API compatibility)
+ # - "json_object": Use json_object response format (broader compatibility)
+ # - "none": No response format constraint (maximum compatibility with local LLMs)
+ # - "auto": Let the caller's fallback strategy decide
+ JSON_MODE_STRICT = "strict"
+ JSON_MODE_OBJECT = "json_object"
+ JSON_MODE_NONE = "none"
+ JSON_MODE_AUTO = "auto"
+
+ VALID_JSON_MODES = [ JSON_MODE_STRICT, JSON_MODE_OBJECT, JSON_MODE_NONE, JSON_MODE_AUTO ].freeze
+
+ private
+ # Determine default JSON mode based on configuration hierarchy:
+ # 1. Environment variable (LLM_JSON_MODE) - highest priority, for testing/override
+ # 2. Setting.openai_json_mode - user-configured in app settings
+ # 3. Default: auto mode (recommended for all providers)
+ #
+ # Mode descriptions:
+ # - "auto": Tries strict first, falls back to none if >50% fail (recommended default)
+ # - "strict": Best for thinking models (qwen-thinking, deepseek-reasoner) - skips verbose <think> tags
+ # - "none": Best for non-thinking models (gpt-oss, llama, mistral) - allows reasoning in output
+ # - "json_object": Middle ground, broader compatibility than strict
+ def default_json_mode
+ # 1. Check environment variable first (allows runtime override for testing)
+ env_mode = ENV["LLM_JSON_MODE"]
+ return env_mode if env_mode.present? && VALID_JSON_MODES.include?(env_mode)
+
+ # 2. Check app settings (user-configured)
+ setting_mode = Setting.openai_json_mode
+ return setting_mode if setting_mode.present? && VALID_JSON_MODES.include?(setting_mode)
+
+ # 3. Default: auto mode for all providers (tries strict first, falls back to none if needed)
+ JSON_MODE_AUTO
+ end
+
+ # Applies the resolved mode to a `client.chat` params hash, in place.
+ #
+ # `strict` only becomes a JSON schema request when the caller supplies one;
+ # calls that have no schema to offer degrade to `json_object`, which is what
+ # they sent before modes existed. Callers that pair `auto` with a fallback
+ # strategy do the same, since there is nothing to fall back from here.
+ def apply_json_mode(params, mode:, schema: nil)
+ case mode
+ when JSON_MODE_NONE
+ params
+ when JSON_MODE_STRICT
+ if schema.present?
+ params[:response_format] = { type: "json_schema", json_schema: schema }
+ else
+ params[:response_format] = { type: "json_object" }
+ end
+ else
+ params[:response_format] = { type: "json_object" }
+ end
+ end
+end
diff --git a/app/models/provider/openai/pdf_processor.rb b/app/models/provider/openai/pdf_processor.rb
index 00a6f0072f..4059f21e0e 100644
--- a/app/models/provider/openai/pdf_processor.rb
+++ b/app/models/provider/openai/pdf_processor.rb
@@ -1,11 +1,12 @@
class Provider::Openai::PdfProcessor
include Provider::Openai::Concerns::UsageRecorder
+ include Provider::Openai::Concerns::JsonMode
attr_reader :client, :model, :pdf_content, :custom_provider, :langfuse_trace, :family, :max_response_tokens,
- :processing_mode
+ :processing_mode, :json_mode
def initialize(client, model: "", pdf_content: nil, custom_provider: false, langfuse_trace: nil, family: nil,
- max_response_tokens:, processing_mode: :auto)
+ max_response_tokens:, processing_mode: :auto, json_mode: nil)
@client = client
@model = model
@pdf_content = pdf_content
@@ -14,6 +15,7 @@ class Provider::Openai::PdfProcessor
@family = family
@max_response_tokens = max_response_tokens
@processing_mode = processing_mode
+ @json_mode = json_mode || default_json_mode
end
def process
@@ -125,10 +127,11 @@ class Provider::Openai::PdfProcessor
role: "user",
content: "Please analyze the following document text and provide a structured summary:\n\n#{pdf_text}"
}
- ],
- response_format: { type: "json_object" }
+ ]
}
+ apply_json_mode(params, mode: json_mode)
+
response = client.chat(parameters: params)
Rails.logger.info("Tokens used to process PDF: #{response.dig("usage", "total_tokens")}")
diff --git a/app/models/provider/openai/provider_merchant_enhancer.rb b/app/models/provider/openai/provider_merchant_enhancer.rb
index 4b9350df6b..0afdd08157 100644
--- a/app/models/provider/openai/provider_merchant_enhancer.rb
+++ b/app/models/provider/openai/provider_merchant_enhancer.rb
@@ -1,5 +1,6 @@
class Provider::Openai::ProviderMerchantEnhancer
include Provider::Openai::Concerns::UsageRecorder
+ include Provider::Openai::Concerns::JsonMode
attr_reader :client, :model, :merchants, :custom_provider, :langfuse_trace, :family, :json_mode
@@ -13,18 +14,6 @@ class Provider::Openai::ProviderMerchantEnhancer
@json_mode = json_mode || default_json_mode
end
- VALID_JSON_MODES = Provider::Openai::AutoMerchantDetector::VALID_JSON_MODES
-
- def default_json_mode
- env_mode = ENV["LLM_JSON_MODE"]
- return env_mode if env_mode.present? && VALID_JSON_MODES.include?(env_mode)
-
- setting_mode = Setting.openai_json_mode
- return setting_mode if setting_mode.present? && VALID_JSON_MODES.include?(setting_mode)
-
- Provider::Openai::AutoMerchantDetector::JSON_MODE_AUTO
- end
-
def enhance_merchants
if custom_provider
enhance_merchants_generic
@@ -136,22 +125,22 @@ class Provider::Openai::ProviderMerchantEnhancer
end
def enhance_merchants_generic
- if json_mode == Provider::Openai::AutoMerchantDetector::JSON_MODE_AUTO
+ if json_mode == JSON_MODE_AUTO
enhance_merchants_with_auto_mode
else
enhance_merchants_with_mode(json_mode)
end
rescue Faraday::BadRequestError => e
- if json_mode == Provider::Openai::AutoMerchantDetector::JSON_MODE_STRICT || json_mode == Provider::Openai::AutoMerchantDetector::JSON_MODE_AUTO
+ if json_mode == JSON_MODE_STRICT || json_mode == JSON_MODE_AUTO
Rails.logger.warn("Strict JSON mode failed for merchant enhancement, falling back to none mode: #{e.message}")
- enhance_merchants_with_mode(Provider::Openai::AutoMerchantDetector::JSON_MODE_NONE)
+ enhance_merchants_with_mode(JSON_MODE_NONE)
else
raise
end
end
def enhance_merchants_with_auto_mode
- result = enhance_merchants_with_mode(Provider::Openai::AutoMerchantDetector::JSON_MODE_STRICT)
+ result = enhance_merchants_with_mode(JSON_MODE_STRICT)
null_count = result.count { |r| r.business_url.nil? }
missing_count = merchants.size - result.size
@@ -160,7 +149,7 @@ class Provider::Openai::ProviderMerchantEnhancer
if failed_ratio > Provider::Openai::AutoMerchantDetector::AUTO_MODE_NULL_THRESHOLD
Rails.logger.info("Auto mode: #{(failed_ratio * 100).round}% failed in strict mode for merchant enhancement, retrying with none mode")
- enhance_merchants_with_mode(Provider::Openai::AutoMerchantDetector::JSON_MODE_NONE)
+ enhance_merchants_with_mode(JSON_MODE_NONE)
else
result
end
@@ -181,19 +170,11 @@ class Provider::Openai::ProviderMerchantEnhancer
]
}
- case mode
- when Provider::Openai::AutoMerchantDetector::JSON_MODE_STRICT
- params[:response_format] = {
- type: "json_schema",
- json_schema: {
- name: "enhance_provider_merchants",
- strict: true,
- schema: json_schema
- }
- }
- when Provider::Openai::AutoMerchantDetector::JSON_MODE_OBJECT
- params[:response_format] = { type: "json_object" }
- end
+ apply_json_mode(params, mode: mode, schema: {
+ name: "enhance_provider_merchants",
+ strict: true,
+ schema: json_schema
+ })
response = client.chat(parameters: params)
diff --git a/test/models/provider/openai/bank_statement_extractor_test.rb b/test/models/provider/openai/bank_statement_extractor_test.rb
index 0359e75175..f55320dc83 100644
--- a/test/models/provider/openai/bank_statement_extractor_test.rb
+++ b/test/models/provider/openai/bank_statement_extractor_test.rb
@@ -194,4 +194,76 @@ class Provider::Openai::BankStatementExtractorTest < ActiveSupport::TestCase
# Should return empty transactions on parse error
assert_equal [], result[:transactions]
end
+
+ test "omits response_format entirely when json_mode is none" do
+ @client.expects(:chat).with do |request|
+ !request[:parameters].key?(:response_format)
+ end.returns(chat_response)
+
+ extractor = build_extractor(json_mode: "none")
+
+ extractor.extract
+
+ assert_equal "none", extractor.json_mode
+ end
+
+ test "asks for json_object by default, preserving pre-fix behaviour" do
+ @client.expects(:chat).with do |request|
+ request[:parameters][:response_format] == { type: "json_object" }
+ end.returns(chat_response)
+
+ build_extractor.extract
+ end
+
+ test "resolves json_mode from LLM_JSON_MODE when none is passed" do
+ @client.expects(:chat).with do |request|
+ !request[:parameters].key?(:response_format)
+ end.returns(chat_response)
+
+ with_env_overrides("LLM_JSON_MODE" => "none") do
+ build_extractor.extract
+ end
+ end
+
+ test "an explicit json_mode wins over LLM_JSON_MODE" do
+ @client.expects(:chat).with do |request|
+ request[:parameters][:response_format] == { type: "json_object" }
+ end.returns(chat_response)
+
+ with_env_overrides("LLM_JSON_MODE" => "none") do
+ build_extractor(json_mode: "json_object").extract
+ end
+ end
+
+ test "strips a markdown fenced reply so none mode still parses" do
+ fenced = "```json\n" + { "transactions" => [ { "date" => "2024-01-15", "description" => "Coffee", "amount" => -5.50 } ] }.to_json + "\n```"
+ @client.expects(:chat).returns(chat_response(content: fenced))
+
+ result = build_extractor(json_mode: "none").extract
+
+ assert_equal 1, result[:transactions].size
+ assert_equal "Coffee", result[:transactions][0][:name]
+ end
+
+ private
+ def chat_response(content: nil)
+ {
+ "choices" => [ {
+ "message" => {
+ "content" => content || { "transactions" => [] }.to_json
+ }
+ } ]
+ }
+ end
+
+ def build_extractor(json_mode: nil)
+ extractor = Provider::Openai::BankStatementExtractor.new(
+ client: @client,
+ pdf_content: "dummy",
+ model: @model,
+ json_mode: json_mode
+ )
+ extractor.stubs(:extract_pages_from_pdf).returns([ "Page 1 text" ])
+ extractor
+ end
end
diff --git a/test/models/provider/openai/concerns/json_mode_test.rb b/test/models/provider/openai/concerns/json_mode_test.rb
new file mode 100644
index 0000000000..75c19e2d7b
--- /dev/null
+++ b/test/models/provider/openai/concerns/json_mode_test.rb
@@ -0,0 +1,102 @@
+require "test_helper"
+
+class Provider::Openai::Concerns::JsonModeTest < ActiveSupport::TestCase
+ class Subject
+ include Provider::Openai::Concerns::JsonMode
+
+ public :default_json_mode, :apply_json_mode
+ end
+
+ setup do
+ @subject = Subject.new
+ Setting.openai_json_mode = nil
+ end
+
+ teardown do
+ Setting.openai_json_mode = nil
+ end
+
+ test "the shared constants stay in the order the settings UI offers them" do
+ assert_equal %w[strict json_object none auto], Provider::Openai::Concerns::JsonMode::VALID_JSON_MODES
+ end
+
+ test "an explicit env mode wins over the stored setting" do
+ Setting.openai_json_mode = "strict"
+
+ with_env_overrides("LLM_JSON_MODE" => "none") do
+ assert_equal "none", @subject.default_json_mode
+ end
+ end
+
+ test "falls back to the stored setting when the env var is unset" do
+ Setting.openai_json_mode = "json_object"
+
+ with_env_overrides("LLM_JSON_MODE" => nil) do
+ assert_equal "json_object", @subject.default_json_mode
+ end
+ end
+
+ test "ignores an unrecognized env value and keeps looking" do
+ Setting.openai_json_mode = "none"
+
+ with_env_overrides("LLM_JSON_MODE" => "banana") do
+ assert_equal "none", @subject.default_json_mode
+ end
+ end
+
+ test "defaults to auto when nothing is configured" do
+ with_env_overrides("LLM_JSON_MODE" => nil) do
+ assert_equal "auto", @subject.default_json_mode
+ end
+ end
+
+ test "none omits response_format so strict runtimes are not rejected" do
+ params = { model: "local-model" }
+
+ @subject.apply_json_mode(params, mode: "none")
+
+ assert_not params.key?(:response_format)
+ end
+
+ test "json_object asks for an object" do
+ params = {}
+
+ @subject.apply_json_mode(params, mode: "json_object")
+
+ assert_equal({ type: "json_object" }, params[:response_format])
+ end
+
+ test "auto degrades to json_object because it has no fallback strategy of its own" do
+ params = {}
+
+ @subject.apply_json_mode(params, mode: "auto")
+
+ assert_equal({ type: "json_object" }, params[:response_format])
+ end
+
+ test "strict uses the supplied schema" do
+ params = {}
+ schema = { name: "things", strict: true, schema: { type: "object" } }
+
+ @subject.apply_json_mode(params, mode: "strict", schema: schema)
+
+ assert_equal({ type: "json_schema", json_schema: schema }, params[:response_format])
+ end
+
+ test "strict without a schema degrades to json_object" do
+ params = {}
+
+ @subject.apply_json_mode(params, mode: "strict")
+
+ assert_equal({ type: "json_object" }, params[:response_format])
+ end
+
+ test "applying a mode preserves the params it was handed" do
+ params = { model: "local-model", messages: [ { role: "user", content: "hi" } ] }
+
+ returned = @subject.apply_json_mode(params, mode: "none")
+
+ assert_same params, returned
+ assert_equal "local-model", returned[:model]
+ end
+end
diff --git a/test/models/provider/openai/pdf_processor_test.rb b/test/models/provider/openai/pdf_processor_test.rb
index 6ba946cae7..018e1f2f06 100644
--- a/test/models/provider/openai/pdf_processor_test.rb
+++ b/test/models/provider/openai/pdf_processor_test.rb
@@ -247,6 +247,57 @@ class Provider::Openai::PdfProcessorTest < ActiveSupport::TestCase
assert_equal [], processor.send(:convert_pdf_to_images)
end
+ test "text extraction omits response_format when json_mode is none" do
+ client = mock
+ client.expects(:chat).with do |request|
+ !request[:parameters].key?(:response_format)
+ end.returns(pdf_chat_response)
+
+ processor = build_processor_for(client, json_mode: "none")
+ processor.stubs(:extract_text_from_pdf).returns("Statement text")
+
+ assert_equal "Synthetic PDF", processor.process.summary
+ end
+
+ test "text extraction asks for json_object by default" do
+ client = mock
+ client.expects(:chat).with do |request|
+ request[:parameters][:response_format] == { type: "json_object" }
+ end.returns(pdf_chat_response)
+
+ processor = build_processor_for(client)
+ processor.stubs(:extract_text_from_pdf).returns("Statement text")
+
+ assert_equal "Synthetic PDF", processor.process.summary
+ end
+
+ test "text extraction resolves json_mode from LLM_JSON_MODE" do
+ client = mock
+ client.expects(:chat).with do |request|
+ !request[:parameters].key?(:response_format)
+ end.returns(pdf_chat_response)
+
+ with_env_overrides("LLM_JSON_MODE" => "none") do
+ processor = build_processor_for(client)
+ processor.stubs(:extract_text_from_pdf).returns("Statement text")
+ processor.process
+ end
+ end
+
+ test "auto mode falls back to vision when the provider rejects the text request" do
+ client = mock
+ client.expects(:chat).returns(pdf_chat_response)
+ client.expects(:chat).with do |request|
+ !request[:parameters].key?(:response_format)
+ end.raises(Provider::Openai::Error, "unsupported response_format")
+
+ processor = build_processor_for(client, json_mode: "none", processing_mode: :auto)
+ processor.stubs(:extract_text_from_pdf).returns("Statement text")
+ processor.stubs(:convert_pdf_to_images).returns([ "synthetic-image" ])
+
+ assert_equal "Synthetic PDF", processor.process.summary
+ end
+
private
# Build a vision processor with synthetic images and a mocked API client.
# @return [Provider::Openai::PdfProcessor] processor under test
@@ -299,4 +350,26 @@ class Provider::Openai::PdfProcessorTest < ActiveSupport::TestCase
trace.stubs(:span).returns(span)
trace
end
+ # Builds a processor around a mocked client for the json_mode tests.
+ # @return [Provider::Openai::PdfProcessor] processor under test
+ def build_processor_for(client, json_mode: nil, processing_mode: :text)
+ Provider::Openai::PdfProcessor.new(
+ client,
+ model: "gpt-4.1",
+ pdf_content: @pdf_content,
+ max_response_tokens: 512,
+ processing_mode: processing_mode,
+ json_mode: json_mode
+ )
+ end
+
+ # @return [Hash] a chat completion carrying a minimal PDF analysis result
+ def pdf_chat_response
+ {
+ "choices" => [ { "message" => { "content" => {
+ document_type: "other", summary: "Synthetic PDF", extracted_data: {}
+ }.to_json } } ],
+ "usage" => { "prompt_tokens" => 10, "completion_tokens" => 20, "total_tokens" => 30 }
+ }
+ end
end