feat(ai): Anthropic batch ops + LLM cost ledger (2/5)

Merged
GA
6mo ago
+1168-13

Summary

Implements auto_categorize, auto_detect_merchants, and enhance_provider_merchants on Provider::Anthropic via forced tool calls, plus the cost-ledger plumbing they need. This is PR 2 of 5, stacked on #1983.

Why forced tool calls

Anthropic has no first-class JSON-mode flag. The idiomatic replacement is to define a single output tool whose input_schema mirrors the desired output, then force the model to invoke it with tool_choice: { type: "tool", name: ..., disable_parallel_tool_use: true }. The model returns exactly one tool_use block whose input is guaranteed to validate against the schema.

Net effect:

  • No `` tag stripping
  • No `json_schema` ↔ `json_object` ↔ `none` fallback ladder
  • No `parse_json_flexibly` cascade with markdown-code-block heuristics
  • One clear failure mode ("model did not invoke the tool"), raised as Provider::Anthropic::Error

The three Anthropic task classes end up ~30% smaller than their OpenAI siblings while covering the same surface.

What's in this PR

Task classes (each is small: forced-tool-call request + schema + normalize)

  • Provider::Anthropic::AutoCategorizer → tool: report_categorizations
  • Provider::Anthropic::AutoMerchantDetector → tool: report_merchants
  • Provider::Anthropic::ProviderMerchantEnhancer → tool: report_enhancements

Each:

  • Caps batch size at 25 (parity with OpenAI) and raises a clear error above it.
  • Tags Langfuse spans with the operation name so dashboards aggregate across providers.
  • Records usage via Concerns::UsageRecorder (mirror of the OpenAI sibling).
  • Normalizes "null" strings and case-insensitive matches against the user's category / merchant list.

Cost ledger

  • Migration 20260525120000_add_anthropic_cache_tokens_to_llm_usages.rb adds nullable cache_creation_tokens and cache_read_tokens integer columns. OpenAI rows leave them null; Anthropic rows populate them.
  • LlmUsage::PRICING gains claude-opus-4-7 ($15/$75), claude-opus-4-6 ($15/$75), claude-sonnet-4-6 ($3/$15), claude-sonnet-4-5 ($3/$15), claude-haiku-4-5 ($1/$5) per MTok (Anthropic public pricing).
  • LlmUsage.infer_provider returns "anthropic" for claude-* via the existing exact/prefix lookup — no code change needed beyond the PRICING rows.
  • Provider::Anthropic#chat_response (introduced in PR 1) now persists cache columns directly instead of stashing them in metadata.

Not changed (intentional)

  • Anthropic cache-creation tokens are billed at ~1.25x input rate and reads at 0.1x. LlmUsage.calculate_cost continues to bill them at the regular input rate for now — a deliberate slight over/under depending on cache lifetime, refined in a follow-up if real-world bills warrant it.
  • OpenAI batch ops are untouched.

Test plan

  • test/models/provider/anthropic/auto_categorizer_test.rb — 3 tests: forced-tool-call request shape, null/None normalization, missing-tool_use error path
  • test/models/provider/anthropic/auto_merchant_detector_test.rb — 3 tests: same shape + case-insensitive user_merchants matching
  • test/models/provider/anthropic/provider_merchant_enhancer_test.rb — 2 tests: forced-tool-call mapping + error path
  • test/models/llm_usage_test.rb (new file) — Claude pricing math, provider inference
  • All PR 1 tests still green
  • Full suite: 4371 runs, 18048 assertions, 0 failures, 26 pre-existing skips, 1 pre-existing libvips env error
  • bin/rubocop clean
  • bin/brakeman --no-pager clean

Migration

bin/rails db:migrate

Backwards compatible: new columns are nullable and existing OpenAI write paths are untouched.

Summary by CodeRabbit

  • New Features

    • Added Anthropic Claude support for transaction categorization, merchant auto-detection, and merchant enhancement
    • Implemented prompt-cache token tracking and billing so cached reads/writes contribute to estimated LLM costs
    • Database schema updated to store cache token counts for usage records
  • Bug Fixes

    • Prevented duplicate usage recording for streaming responses to avoid inflated cost estimates
  • Tests

    • Added coverage for Anthropic flows and cache-billing logic