feat(ai): add Anthropic provider with chat parity (1/5)

Merged
GA
6mo ago
+1512-20

Summary

Introduces Provider::Anthropic as a first-class LLM provider alongside Provider::Openai, implementing the LlmConcept#chat_response contract over the official anthropic Ruby SDK. Chat (text + streaming + tool use) is at parity. Batch ops, PDF, and RAG land in stacked follow-up PRs.

This is PR 1 of 5 in the Anthropic integration series. Each PR ships independently green.

Why Anthropic

The Sure assistant currently only speaks to OpenAI. Anthropic offers (a) native PDF understanding without rasterization, (b) explicit prompt-cache control, (c) competitive Sonnet pricing for chat and Haiku for batch ops, and (d) an alternative for users who already standardize on Claude. Adding a parallel provider gives operators a choice without locking anyone in.

What's in this PR

New code

  • Provider::Anthropic — uses Messages API for sync + streaming responses, wraps SDK errors as Provider::Anthropic::Error, records LLM usage with provider "anthropic", threads Langfuse traces with the same span name (chat_response) so dashboards stay comparable across providers.
  • Provider::Anthropic::ChatConfig — builds Messages API requests; tags the system prompt and the final tool definition with cache_control: { type: "ephemeral" } (Anthropic's prompt caching).
  • Provider::Anthropic::MessageFormatter — translates Chat#conversation_messages into Anthropic's content-block schema. Each historical assistant turn that used tools is rebuilt as the required tool_use block + paired user-role tool_result block before the next assistant turn. In-flight function_results (the responder's second-leg call) get the same treatment.
  • Provider::Anthropic::ChatParser — converts the SDK's Message (or a hash-shaped equivalent) into the shared Provider::LlmConcept::ChatResponse Data struct, surfacing both text blocks and tool_use blocks as function requests.

Wiring

  • Provider::Registry — new anthropic factory; reads ANTHROPIC_ACCESS_TOKEN / ANTHROPIC_API_KEY / Setting.anthropic_access_token, plus optional ANTHROPIC_BASE_URL (for Bedrock / Vertex proxies) and ANTHROPIC_MODEL. Listed under both :llm and the default available_providers set so existing supports_model? routing picks the right provider for claude-* models.
  • Setting — adds anthropic_access_token, anthropic_model, anthropic_base_url, and llm_provider (default "openai") fields.
  • User#ai_available? — now returns true when either OpenAI or Anthropic is configured; exposes openai_configured? / anthropic_configured? for consumers.
  • Chat.default_model — resolves from Setting.llm_provider, so installs that flip the provider don't have to update every chat default.
  • Assistant::Responder — passes a new conversation_history: kwarg (raw Array<Message>) alongside the existing messages: (OpenAI-shaped) so providers without hosted conversation state can rebuild context. The OpenAI provider accepts and ignores the new kwarg — no behavior change.
  • Provider::LlmConcept — signature extended to document the new kwarg.

What's not in this PR (intentional)

  • ❌ auto_categorize, auto_detect_merchants, enhance_provider_merchants — raise a clear not yet implemented error on this provider. PR 2/5 lands these via forced tool calls (tool_choice: {type: "tool", name: ...}) plus the cost-ledger migration.
  • ❌ process_pdf, extract_bank_statement — same story. PR 3/5 uses native document content blocks.
  • ❌ Vector::Store::* / RAG — PR 4/5 ships a pgvector-backed store so RAG works without Anthropic needing a hosted vector store.
  • ❌ Settings UI panel — PR 5/5 mirrors _openai_settings.html.erb and adds the data-retention disclosure (parity with OpenAI's panel).
  • ❌ Live VCR cassettes for chat_response. Cassettes need to be recorded with a real ANTHROPIC_API_KEY; mocked tests cover the wiring in the meantime.

Configuration (new env vars)

EnvSetting fieldDefault
ANTHROPIC_ACCESS_TOKEN (or) ANTHROPIC_API_KEYSetting.anthropic_access_tokennil
ANTHROPIC_MODELSetting.anthropic_modelclaude-sonnet-4-6
ANTHROPIC_BASE_URLSetting.anthropic_base_urlnil (uses api.anthropic.com)
ANTHROPIC_REQUEST_TIMEOUT—600
ANTHROPIC_MAX_TOKENS—4096
LLM_PROVIDERSetting.llm_provideropenai

Test plan

  • bin/rails test test/models/provider/anthropic_test.rb — 8 tests, init / supports_model / supports_pdf_processing / effective_model / chat_response success + error + tool_use paths
  • bin/rails test test/models/provider/anthropic/ — 14 tests across ChatConfig, ChatParser, MessageFormatter
  • bin/rails test test/models/provider/registry_test.rb — 8 tests, includes new :anthropic factory + env-empty fallback to Setting
  • bin/rails test test/models/provider/openai_test.rb — 27 tests, unchanged
  • Full suite: 4358 runs, 18008 assertions, 0 failures, 26 pre-existing skips, 1 pre-existing env error (libvips unavailable on the dev host)
  • bin/rubocop clean on all touched files
  • bin/brakeman --no-pager — 0 security warnings
  • Record live VCR cassettes (follow-up — needs ANTHROPIC_API_KEY)
  • System test exercising a chat turn through Provider::Anthropic (follow-up — bundled with cassettes)

Compliance notes

  • Anthropic's standard tier does not train on API inputs; 30-day Trust & Safety retention. The settings UI in PR 5/5 surfaces this alongside OpenAI's equivalent disclosure.
  • The financial-advice disclaimer already shown in the chat applies equally to either provider.
  • anthropic gem is MIT-licensed, compatible with Sure's AGPLv3.
  • OpenAI integration is untouched.

Summary by CodeRabbit

  • New Features

    • Anthropic added as an alternative LLM provider with configurable credentials and optional custom endpoint.
  • Behavior Changes

    • Default LLM selection now respects the deploy-time provider setting and prefers the configured provider.
    • Chat handling now includes prior conversation history to improve responses.
    • User AI availability now reflects either OpenAI or Anthropic being configured.
  • Chores

    • Added Anthropic client dependency to the project.
  • Tests

    • Expanded Anthropic-related test coverage (configuration, parsing, formatting, streaming).

Review Change Stack