The personal finance app for everyone (by everyone)
Ruby
feat(ai): Anthropic native PDF processing (3/5) (#1985)
Guillem Arias Fauste8ccc434b3d16
diff --git a/app/models/assistant/function/import_bank_statement.rb b/app/models/assistant/function/import_bank_statement.rbindex dee54602f7..d3bf86decc 100644--- a/app/models/assistant/function/import_bank_statement.rb+++ b/app/models/assistant/function/import_bank_statement.rb@@ -93,6 +93,8 @@ class Assistant::Function::ImportBankStatement < Assistant::Functionend# Extract transactions from the PDF using provider+ # TODO(#2113): hardcoded to OpenAI. Provider::Anthropic implements+ # extract_bank_statement (PR #1985); this should honor Setting.llm_provider.provider = Provider::Registry.get_provider(:openai)unless providerreturn {diff --git a/app/models/pdf_import.rb b/app/models/pdf_import.rbindex 1e1f494ef9..69c74cb9e0 100644--- a/app/models/pdf_import.rb+++ b/app/models/pdf_import.rb@@ -89,6 +89,8 @@ class PdfImport < Importenddef process_with_ai+ # TODO(#2113): hardcoded to OpenAI. Provider::Anthropic implements+ # process_pdf (PR #1985); this should honor Setting.llm_provider.provider = Provider::Registry.get_provider(:openai)raise "AI provider not configured" unless providerraise "AI provider does not support PDF processing" unless provider.supports_pdf_processing?@@ -115,6 +117,8 @@ class PdfImport < Importdef extract_transactionsreturn unless statement_with_transactions?+ # TODO(#2113): hardcoded to OpenAI. Provider::Anthropic implements+ # extract_bank_statement (PR #1985); this should honor Setting.llm_provider.provider = Provider::Registry.get_provider(:openai)raise "AI provider not configured" unless providerdiff --git a/app/models/provider/anthropic.rb b/app/models/provider/anthropic.rbindex 8e2e1fa50b..ab05a0e0bf 100644--- a/app/models/provider/anthropic.rb+++ b/app/models/provider/anthropic.rb@@ -155,11 +155,50 @@ class Provider::Anthropic < Providerenddef process_pdf(pdf_content:, model: "", family: nil)- raise Error, "process_pdf not yet implemented for Provider::Anthropic"+ with_provider_response do+ effective_model = model.presence || @default_model+ raise Error, "Model does not support PDF processing: #{effective_model}" unless supports_pdf_processing?(model: effective_model)++ trace = create_langfuse_trace(+ name: "anthropic.process_pdf",+ input: { pdf_size: pdf_content&.bytesize }+ )++ result = PdfProcessor.new(+ client,+ model: effective_model,+ pdf_content: pdf_content,+ langfuse_trace: trace,+ family: family+ ).process++ upsert_langfuse_trace(trace: trace, output: result.to_h)++ result+ endenddef extract_bank_statement(pdf_content:, model: "", family: nil)- raise Error, "extract_bank_statement not yet implemented for Provider::Anthropic"+ with_provider_response do+ effective_model = model.presence || @default_model++ trace = create_langfuse_trace(+ name: "anthropic.extract_bank_statement",+ input: { pdf_size: pdf_content&.bytesize }+ )++ result = BankStatementExtractor.new(+ client: client,+ pdf_content: pdf_content,+ model: effective_model,+ langfuse_trace: trace,+ family: family+ ).extract++ upsert_langfuse_trace(trace: trace, output: { transaction_count: result[:transactions].size })++ result+ endenddef chat_response(diff --git a/app/models/provider/anthropic/bank_statement_extractor.rb b/app/models/provider/anthropic/bank_statement_extractor.rbnew file mode 100644index 0000000000..e91d44b47b--- /dev/null+++ b/app/models/provider/anthropic/bank_statement_extractor.rb@@ -0,0 +1,229 @@+class Provider::Anthropic::BankStatementExtractor+ include Provider::Anthropic::Concerns::UsageRecorder++ TOOL_NAME = "report_bank_statement".freeze++ # Mirrors Provider::Anthropic::PdfProcessor::MAX_PDF_BYTES.+ MAX_PDF_BYTES = 32 * 1024 * 1024++ attr_reader :client, :model, :pdf_content, :langfuse_trace, :family++ def initialize(client:, model:, pdf_content:, langfuse_trace: nil, family: nil)+ @client = client+ @model = model+ @pdf_content = pdf_content+ @langfuse_trace = langfuse_trace+ @family = family+ end++ def extract+ raise Provider::Anthropic::Error, "PDF content is required" if pdf_content.blank?+ if pdf_content.bytesize > MAX_PDF_BYTES+ raise Provider::Anthropic::Error,+ "PDF exceeds Anthropic's 32 MB limit (#{pdf_content.bytesize} bytes)"+ end++ span = langfuse_trace&.span(name: "extract_bank_statement_api_call", input: {+ model: model,+ pdf_size: pdf_content.bytesize+ })++ response = client.messages.create(+ model: model,+ max_tokens: max_tokens,+ system_: instructions,+ messages: [ { role: "user", content: user_content } ],+ tools: [ output_tool ],+ tool_choice: { type: "tool", name: TOOL_NAME, disable_parallel_tool_use: true }+ )++ parsed = extract_tool_input(response)+ result = build_result(parsed)++ truncated = stop_reason(response) == :max_tokens+ if truncated+ Rails.logger.warn(+ "[BankStatementExtractor] response truncated by max_tokens — extracted #{result[:transactions].size} " \+ "transactions but more may be present in the statement. Raise ANTHROPIC_MAX_TOKENS or chunk the PDF."+ )+ result[:truncated] = true+ end++ record_usage(model, response.usage, operation: "extract_bank_statement", metadata: {+ pdf_size: pdf_content.bytesize,+ transaction_count: result[:transactions].size,+ truncated: truncated+ })++ span&.end(output: { transaction_count: result[:transactions].size }, usage: usage_hash(response.usage))+ result+ rescue => e+ span&.end(output: { error: e.message }, level: "ERROR")+ record_usage_error(model, operation: "extract_bank_statement", error: e, metadata: { pdf_size: pdf_content&.bytesize })+ raise+ end++ private+ def max_tokens+ ENV.fetch("ANTHROPIC_MAX_TOKENS", 4096).to_i+ end++ def user_content+ [+ {+ type: "document",+ source: {+ type: "base64",+ media_type: "application/pdf",+ data: Base64.strict_encode64(pdf_content)+ }+ },+ {+ type: "text",+ text: "Extract every transaction from this bank statement and return them via the report_bank_statement tool."+ }+ ]+ end++ def output_tool+ {+ name: TOOL_NAME,+ description: "Return the full set of transactions and statement metadata extracted from the PDF.",+ input_schema: {+ type: "object",+ properties: {+ bank_name: { type: [ "string", "null" ] },+ account_holder: { type: [ "string", "null" ] },+ account_number: { type: [ "string", "null" ], description: "Typically last 4 digits only." },+ statement_period: {+ type: "object",+ properties: {+ start_date: { type: [ "string", "null" ], description: "YYYY-MM-DD" },+ end_date: { type: [ "string", "null" ], description: "YYYY-MM-DD" }+ },+ required: [],+ additionalProperties: false+ },+ opening_balance: { type: [ "number", "null" ] },+ closing_balance: { type: [ "number", "null" ] },+ transactions: {+ type: "array",+ description: "Every transaction in the statement, in document order.",+ items: {+ type: "object",+ properties: {+ date: { type: "string", description: "YYYY-MM-DD" },+ description: { type: "string" },+ amount: { type: "number", description: "Negative for debits / expenses, positive for credits / deposits." },+ reference: { type: [ "string", "null" ] },+ category: { type: [ "string", "null" ] }+ },+ required: [ "date", "description", "amount" ],+ additionalProperties: false+ }+ }+ },+ required: [ "transactions" ],+ additionalProperties: false+ }+ }+ end++ def instructions+ <<~INSTRUCTIONS+ Extract bank statement data from the attached PDF and return the result via the report_bank_statement tool.++ Rules:+ - Extract EVERY transaction in document order+ - Negative amounts for debits / expenses, positive for credits / deposits+ - Dates in YYYY-MM-DD+ - Use null for any field you cannot read; do not invent values+ INSTRUCTIONS+ end++ def stop_reason(response)+ raw = response.respond_to?(:stop_reason) ? response.stop_reason : nil+ raw.to_s.to_sym if raw+ end++ def extract_tool_input(response)+ tool_use = Array(response.content).find { |block| block_type(block) == :tool_use }+ raise Provider::Anthropic::Error, "Model did not invoke #{TOOL_NAME}" unless tool_use++ input = block_input(tool_use)+ input = JSON.parse(input) if input.is_a?(String)+ input+ end++ def build_result(parsed)+ # Intentionally NOT deduplicated, unlike Provider::Openai's extractor. That+ # one chunks the PDF text with overlap and must drop transactions repeated+ # across adjacent chunks. We send the whole PDF as a single native document+ # block — no chunk artifacts — so deduping here would wrongly merge+ # legitimate same-day, same-amount rows (e.g. two identical purchases).+ # Preserve every transaction the model returns.+ transactions = Array(parsed["transactions"] || parsed[:transactions]).map { |t| normalize_transaction(t) }.compact++ {+ transactions: transactions,+ period: {+ start_date: dig_period(parsed, :start_date),+ end_date: dig_period(parsed, :end_date)+ },+ account_holder: parsed["account_holder"] || parsed[:account_holder],+ account_number: parsed["account_number"] || parsed[:account_number],+ bank_name: parsed["bank_name"] || parsed[:bank_name],+ opening_balance: parsed["opening_balance"] || parsed[:opening_balance],+ closing_balance: parsed["closing_balance"] || parsed[:closing_balance]+ }+ end++ def dig_period(parsed, key)+ period = parsed["statement_period"] || parsed[:statement_period]+ return nil unless period.is_a?(Hash)+ period[key.to_s] || period[key]+ end++ def normalize_transaction(txn)+ return nil unless txn.is_a?(Hash)++ {+ date: parse_date(txn["date"] || txn[:date]),+ amount: parse_amount(txn["amount"] || txn[:amount]),+ name: txn["description"] || txn[:description] || txn["name"] || txn[:name],+ category: txn["category"] || txn[:category],+ notes: txn["reference"] || txn[:reference]+ }+ end++ def parse_date(date_str)+ return nil if date_str.blank?+ Date.parse(date_str.to_s).strftime("%Y-%m-%d")+ rescue ArgumentError+ nil+ end++ def parse_amount(amount)+ return nil if amount.nil?+ return amount.to_f if amount.is_a?(Numeric)+ amount.to_s.gsub(/[^0-9.\-]/, "").to_f+ end++ def block_type(block)+ raw = block.respond_to?(:type) ? block.type : block[:type] || block["type"]+ raw.to_s.to_sym+ end++ def block_input(block)+ block.respond_to?(:input) ? block.input : (block[:input] || block["input"])+ end++ def usage_hash(raw_usage)+ return {} unless raw_usage+ {+ "input_tokens" => raw_usage.input_tokens.to_i,+ "output_tokens" => raw_usage.output_tokens.to_i,+ "total_tokens" => raw_usage.input_tokens.to_i + raw_usage.output_tokens.to_i+ }+ end+enddiff --git a/app/models/provider/anthropic/pdf_processor.rb b/app/models/provider/anthropic/pdf_processor.rbnew file mode 100644index 0000000000..dc6dc2c96a--- /dev/null+++ b/app/models/provider/anthropic/pdf_processor.rb@@ -0,0 +1,185 @@+class Provider::Anthropic::PdfProcessor+ include Provider::Anthropic::Concerns::UsageRecorder++ TOOL_NAME = "report_document_analysis".freeze++ # Anthropic enforces a 32 MB limit on the whole Messages *request body*, and+ # the PDF travels base64-encoded (~4/3 larger) inside that body alongside the+ # JSON envelope (instructions, tool schema). So a 32 MB raw PDF would encode+ # to ~42 MB and be rejected. Cap the raw bytes at 3/4 of the request budget,+ # minus a generous envelope reserve, so the encoded request stays under the+ # limit. Guarding upstream also avoids base64-encoding an over-size blob in+ # vain (peak heap before the API would reject it).+ MAX_REQUEST_BYTES = 32 * 1024 * 1024+ REQUEST_ENVELOPE_BYTES = 1 * 1024 * 1024+ MAX_PDF_BYTES = (MAX_REQUEST_BYTES - REQUEST_ENVELOPE_BYTES) * 3 / 4++ attr_reader :client, :model, :pdf_content, :langfuse_trace, :family++ def initialize(client, model:, pdf_content:, langfuse_trace: nil, family: nil)+ @client = client+ @model = model+ @pdf_content = pdf_content+ @langfuse_trace = langfuse_trace+ @family = family+ end++ def process+ raise Provider::Anthropic::Error, "PDF content is required" if pdf_content.blank?+ if pdf_content.bytesize > MAX_PDF_BYTES+ raise Provider::Anthropic::Error,+ "PDF is too large (#{pdf_content.bytesize} bytes); base64-encoded it would exceed Anthropic's 32 MB request limit"+ end++ span = langfuse_trace&.span(name: "process_pdf_api_call", input: {+ model: model,+ pdf_size: pdf_content&.bytesize+ })++ response = client.messages.create(+ model: model,+ max_tokens: max_tokens,+ system_: instructions,+ messages: [ { role: "user", content: user_content } ],+ tools: [ output_tool ],+ tool_choice: { type: "tool", name: TOOL_NAME, disable_parallel_tool_use: true }+ )++ parsed = extract_tool_input(response)+ result = build_result(parsed)++ record_usage(model, response.usage, operation: "process_pdf", metadata: { pdf_size: pdf_content.bytesize })++ span&.end(output: result.to_h, usage: usage_hash(response.usage))+ result+ rescue => e+ span&.end(output: { error: e.message }, level: "ERROR")+ record_usage_error(model, operation: "process_pdf", error: e, metadata: { pdf_size: pdf_content&.bytesize })+ raise+ end++ private+ PdfProcessingResult = Provider::LlmConcept::PdfProcessingResult++ def max_tokens+ ENV.fetch("ANTHROPIC_MAX_TOKENS", 4096).to_i+ end++ def user_content+ [+ {+ type: "document",+ source: {+ type: "base64",+ media_type: "application/pdf",+ data: Base64.strict_encode64(pdf_content)+ }+ },+ {+ type: "text",+ text: "Analyze the attached document and return the result via the report_document_analysis tool."+ }+ ]+ end++ def output_tool+ {+ name: TOOL_NAME,+ description: "Return the structured analysis of the attached document.",+ input_schema: {+ type: "object",+ properties: {+ document_type: {+ type: "string",+ enum: Import::DOCUMENT_TYPES,+ description: "Classification of the document."+ },+ summary: {+ type: "string",+ description: "Concise human-readable summary of the document."+ },+ extracted_data: {+ type: "object",+ properties: {+ institution_name: { type: [ "string", "null" ] },+ statement_period_start: { type: [ "string", "null" ], pattern: "^\\d{4}-\\d{2}-\\d{2}$", description: "YYYY-MM-DD or null" },+ statement_period_end: { type: [ "string", "null" ], pattern: "^\\d{4}-\\d{2}-\\d{2}$", description: "YYYY-MM-DD or null" },+ transaction_count: { type: [ "integer", "null" ] },+ opening_balance: { type: [ "number", "null" ] },+ closing_balance: { type: [ "number", "null" ] },+ currency: { type: [ "string", "null" ] },+ account_holder: { type: [ "string", "null" ] }+ },+ required: [],+ additionalProperties: false+ }+ },+ required: [ "document_type", "summary", "extracted_data" ],+ additionalProperties: false+ }+ }+ end++ def instructions+ <<~INSTRUCTIONS+ You analyze financial documents. For the attached PDF, classify the document type,+ summarize it, and extract key metadata. Return the result via the report_document_analysis tool.++ Classification options:+ - bank_statement: bank account statements (incl. mobile money / digital wallets)+ - credit_card_statement: credit card statements+ - investment_statement: brokerage / investment statements+ - financial_document: tax forms, receipts, invoices, financial reports+ - contract: legal agreements, loans, terms of service+ - other: anything else++ Rules:+ - Be factual; only report what is clearly visible+ - If a field is unclear/redacted, return null for it+ - Do not invent figures or names you cannot read+ - For statements with many transactions, return the count rather than enumerating them+ INSTRUCTIONS+ end++ def extract_tool_input(response)+ tool_use = Array(response.content).find { |block| block_type(block) == :tool_use }+ raise Provider::Anthropic::Error, "Model did not invoke #{TOOL_NAME}" unless tool_use++ input = block_input(tool_use)+ input = JSON.parse(input) if input.is_a?(String)+ input+ end++ def build_result(parsed)+ PdfProcessingResult.new(+ summary: parsed["summary"] || parsed[:summary],+ document_type: normalize_document_type(parsed["document_type"] || parsed[:document_type]),+ extracted_data: parsed["extracted_data"] || parsed[:extracted_data] || {}+ )+ end++ def normalize_document_type(doc_type)+ return "other" if doc_type.blank?++ normalized = doc_type.to_s.strip.downcase.gsub(/\s+/, "_")+ Import::DOCUMENT_TYPES.include?(normalized) ? normalized : "other"+ end++ def block_type(block)+ raw = block.respond_to?(:type) ? block.type : block[:type] || block["type"]+ raw.to_s.to_sym+ end++ def block_input(block)+ block.respond_to?(:input) ? block.input : (block[:input] || block["input"])+ end++ def usage_hash(raw_usage)+ return {} unless raw_usage+ {+ "input_tokens" => raw_usage.input_tokens.to_i,+ "output_tokens" => raw_usage.output_tokens.to_i,+ "total_tokens" => raw_usage.input_tokens.to_i + raw_usage.output_tokens.to_i+ }+ end+enddiff --git a/test/models/provider/anthropic/bank_statement_extractor_test.rb b/test/models/provider/anthropic/bank_statement_extractor_test.rbnew file mode 100644index 0000000000..2032462219--- /dev/null+++ b/test/models/provider/anthropic/bank_statement_extractor_test.rb@@ -0,0 +1,141 @@+require "test_helper"+require "ostruct"++class Provider::Anthropic::BankStatementExtractorTest < ActiveSupport::TestCase+ setup do+ @pdf_content = "%PDF-1.4 fake bytes".b+ end++ test "sends PDF as native document and returns normalized transactions + metadata" do+ fake_response = build_response(content: [+ tool_use_block(+ id: "toolu_1",+ name: "report_bank_statement",+ input: {+ "bank_name" => "Bank of Example",+ "account_holder" => "Jane Doe",+ "account_number" => "1234",+ "statement_period" => { "start_date" => "2026-03-01", "end_date" => "2026-03-31" },+ "opening_balance" => 1000.0,+ "closing_balance" => 1500.0,+ "transactions" => [+ { "date" => "2026-03-05", "description" => "Coffee", "amount" => -4.5 },+ { "date" => "2026-03-15", "description" => "Salary", "amount" => 3000.0, "reference" => "Payroll Mar" }+ ]+ }+ )+ ])+ client = stub_client(fake_response)++ result = Provider::Anthropic::BankStatementExtractor.new(+ client: client,+ model: "claude-sonnet-4-6",+ pdf_content: @pdf_content+ ).extract++ assert_equal "Bank of Example", result[:bank_name]+ assert_equal "Jane Doe", result[:account_holder]+ assert_equal "1234", result[:account_number]+ assert_equal "2026-03-01", result[:period][:start_date]+ assert_equal "2026-03-31", result[:period][:end_date]+ assert_equal 1000.0, result[:opening_balance]+ assert_equal 1500.0, result[:closing_balance]++ assert_equal 2, result[:transactions].size+ txn1 = result[:transactions].first+ assert_equal "2026-03-05", txn1[:date]+ assert_equal "Coffee", txn1[:name]+ assert_equal(-4.5, txn1[:amount])++ txn2 = result[:transactions].last+ assert_equal "Salary", txn2[:name]+ assert_equal 3000.0, txn2[:amount]+ assert_equal "Payroll Mar", txn2[:notes]+ end++ test "raises when pdf_content is blank" do+ err = assert_raises(Provider::Anthropic::Error) do+ Provider::Anthropic::BankStatementExtractor.new(+ client: mock,+ model: "claude-sonnet-4-6",+ pdf_content: nil+ ).extract+ end+ assert_match(/PDF content is required/i, err.message)+ end++ test "raises when model omits the tool call" do+ fake_response = build_response(content: [ OpenStruct.new(type: :text, text: "no tool") ])+ client = stub_client(fake_response)++ err = assert_raises(Provider::Anthropic::Error) do+ Provider::Anthropic::BankStatementExtractor.new(+ client: client,+ model: "claude-sonnet-4-6",+ pdf_content: @pdf_content+ ).extract+ end+ assert_match(/did not invoke report_bank_statement/i, err.message)+ end++ test "raises before API call when pdf_content exceeds the 32 MB limit" do+ oversized = "a".b * (Provider::Anthropic::BankStatementExtractor::MAX_PDF_BYTES + 1)+ client = mock+ client.expects(:messages).never++ err = assert_raises(Provider::Anthropic::Error) do+ Provider::Anthropic::BankStatementExtractor.new(+ client: client,+ model: "claude-sonnet-4-6",+ pdf_content: oversized+ ).extract+ end+ assert_match(/exceeds Anthropic's 32 MB limit/i, err.message)+ end++ test "flags result as truncated when stop_reason is max_tokens" do+ fake_response = build_response(+ content: [+ tool_use_block(+ id: "toolu_1",+ name: "report_bank_statement",+ input: { "transactions" => [ { "date" => "2026-03-05", "description" => "Coffee", "amount" => -4.5 } ] }+ )+ ]+ )+ fake_response.stop_reason = :max_tokens+ client = stub_client(fake_response)++ Rails.logger.expects(:warn).with(regexp_matches(/truncated by max_tokens/i))++ result = Provider::Anthropic::BankStatementExtractor.new(+ client: client,+ model: "claude-sonnet-4-6",+ pdf_content: @pdf_content+ ).extract++ assert_equal true, result[:truncated]+ end++ private+ def stub_client(response)+ messages = mock+ messages.stubs(:create).returns(response)+ client = mock+ client.stubs(:messages).returns(messages)+ client+ end++ def build_response(content:, usage: { input_tokens: 1500, output_tokens: 400 })+ OpenStruct.new(+ id: "msg_test",+ model: "claude-sonnet-4-6",+ content: content,+ usage: OpenStruct.new(input_tokens: usage[:input_tokens], output_tokens: usage[:output_tokens])+ )+ end++ def tool_use_block(id:, name:, input:)+ OpenStruct.new(type: :tool_use, id: id, name: name, input: input)+ end+enddiff --git a/test/models/provider/anthropic/pdf_processor_test.rb b/test/models/provider/anthropic/pdf_processor_test.rbnew file mode 100644index 0000000000..d2cdbb3a7c--- /dev/null+++ b/test/models/provider/anthropic/pdf_processor_test.rb@@ -0,0 +1,126 @@+require "test_helper"+require "ostruct"++class Provider::Anthropic::PdfProcessorTest < ActiveSupport::TestCase+ setup do+ @pdf_content = "%PDF-1.4 fake bytes".b+ end++ test "sends PDF as native document content block and parses tool response" do+ fake_response = build_response(content: [+ tool_use_block(+ id: "toolu_1",+ name: "report_document_analysis",+ input: {+ "document_type" => "bank_statement",+ "summary" => "Bank of Example, Mar 2026 statement.",+ "extracted_data" => {+ "institution_name" => "Bank of Example",+ "statement_period_start" => "2026-03-01",+ "statement_period_end" => "2026-03-31",+ "transaction_count" => 42,+ "opening_balance" => 1000.0,+ "closing_balance" => 1500.0,+ "currency" => "USD",+ "account_holder" => "Account Holder"+ }+ }+ )+ ])+ captured = nil+ client = stub_client(fake_response) { |params| captured = params }++ result = Provider::Anthropic::PdfProcessor.new(+ client,+ model: "claude-sonnet-4-6",+ pdf_content: @pdf_content+ ).process++ document_block = captured[:messages].first[:content].first+ assert_equal "document", document_block[:type]+ assert_equal "application/pdf", document_block[:source][:media_type]+ assert_equal "base64", document_block[:source][:type]+ assert_equal Base64.strict_encode64(@pdf_content), document_block[:source][:data]++ assert_equal "report_document_analysis", captured[:tool_choice][:name]+ assert captured[:tool_choice][:disable_parallel_tool_use]++ assert_equal "bank_statement", result.document_type+ assert_equal "Bank of Example, Mar 2026 statement.", result.summary+ assert_equal 42, result.extracted_data["transaction_count"]+ end++ test "normalizes unknown document_type to other" do+ fake_response = build_response(content: [+ tool_use_block(+ id: "toolu_2",+ name: "report_document_analysis",+ input: {+ "document_type" => "alien_invasion_form",+ "summary" => "Unknown.",+ "extracted_data" => {}+ }+ )+ ])+ client = stub_client(fake_response)++ result = Provider::Anthropic::PdfProcessor.new(+ client,+ model: "claude-sonnet-4-6",+ pdf_content: @pdf_content+ ).process++ assert_equal "other", result.document_type+ end++ test "raises when pdf_content is blank" do+ err = assert_raises(Provider::Anthropic::Error) do+ Provider::Anthropic::PdfProcessor.new(+ mock,+ model: "claude-sonnet-4-6",+ pdf_content: ""+ ).process+ end+ assert_match(/PDF content is required/i, err.message)+ end++ test "raises before any API call when pdf_content exceeds the base64-adjusted cap" do+ oversized = "a".b * (Provider::Anthropic::PdfProcessor::MAX_PDF_BYTES + 1)+ client = mock+ client.expects(:messages).never++ err = assert_raises(Provider::Anthropic::Error) do+ Provider::Anthropic::PdfProcessor.new(+ client,+ model: "claude-sonnet-4-6",+ pdf_content: oversized+ ).process+ end+ assert_match(/32 MB request limit/i, err.message)+ end++ private+ def stub_client(response)+ messages = mock+ messages.expects(:create).with do |params|+ yield(params) if block_given?+ true+ end.returns(response)+ client = mock+ client.stubs(:messages).returns(messages)+ client+ end++ def build_response(content:, usage: { input_tokens: 800, output_tokens: 200 })+ OpenStruct.new(+ id: "msg_test",+ model: "claude-sonnet-4-6",+ content: content,+ usage: OpenStruct.new(input_tokens: usage[:input_tokens], output_tokens: usage[:output_tokens])+ )+ end++ def tool_use_block(id:, name:, input:)+ OpenStruct.new(type: :tool_use, id: id, name: name, input: input)+ end+end