The personal finance app for everyone (by everyone)
Ruby
AI pipeline
Sure's AI calls go through thin transports over RubyLLM. The design is in the v0.8 AI plumbing
proposal (#4440, docs/proposals/v0.8/ai-plumbing-redesign.md on that branch).
Transports and instrumentation
flowchart LR
Caller["AiHealth::Probe"] --> T["Ai::Transport.for(endpoint)<br/>Compatible | Anthropic"]
T --> CC["Ai::CallContext.call<br/>usage owner + workflow"]
CC --> R["RubyLLM.context per endpoint"]
R --> I["Ai::Transport::Instrumenter<br/>attempt budget"]
I --> S[("model server")]
R -. "usage.ruby_llm" .-> U["UsageSubscriber → llm_usages"]
T -. "*.ai" .-> L["Langfuse (content mode)<br/>DebugLogEntry"]
Where things live
| Concern | File |
|---|---|
| Endpoint and model values a transport takes | app/models/ai/config/endpoint.rb, model.rb |
| Every HTTP client, the proxy resolver, the base URL rule | app/models/ai/transport/http.rb |
| The transports | app/models/ai/transport/{base,compatible,anthropic,ruby_llm_adapter}.rb |
| Errors | app/models/ai/error.rb |
| Token counts and cost | app/models/ai/tokens.rb |
| Usage owner, workflow and attempt budget around a call | app/models/ai/call_context.rb, transport/instrumenter.rb |
| Usage rows, the debug log, tracing modes, secret scrubbing | app/models/ai/instrumentation/* |
Rules
- A transport never reads ENV,
Settingor ActiveRecord. It takes anAi::Config::Endpointand anAi::Config::Model, built by its caller. - Build clients only in
Ai::Transport::Http. It applies the endpoint's timeout and headers, TLS options and the proxy. RubyLLM builds its own connections and takes no TLS options, so its contexts useHttp.ruby_llm_adapter, a Net::HTTP adapter that adds them. The contract test fails onOpenAI::Client.new,Anthropic::Client.neworFaraday.newanywhere else underapp/models/ai/. - Use RubyLLM's public API only:
RubyLLM.context,Context#chat/#embed,Chat#generate, thewith_*setters,RubyLLM::Tool,RubyLLM.workflow,RubyLLM.with_usage_owner,RubyLLM::OpenTelemetry.enable. Nothing marked:nodoc:.test/architecture/ai_transport_contract_test.rblists the surface Sure uses. - RubyLLM never retries. Every context has
max_retries = 0;Ai::Transport::Base#attemptretries rate limits, 5xx and timeouts up to the endpoint'smax_retries. RubyLLM retries inside one request with no hook before a retry, so only Sure can stop on a spent balance and check the time budget between tries. - Raise only
Ai::Error. Map client errors in the transport (mapping_errors). Mapped messages are scrubbed of the endpoint's secrets (Endpoint#secrets: the key and long static header values) before anything logs them. - Wrap every call in
Ai::CallContext.call. RubyLLM'susage.ruby_llmevent then carries the family (the usage owner) and the call (the workflow), andUsageSubscriberwrites onellm_usagesrow per request. A failed request's row takes its own error from therequest.ruby_llmevent (Ai::Transport::Instrumenter). - Never create
ruby_llm_usages. RubyLLM's ledger would then record every call a second time.
Tests
test/support/ai_test_helper.rb:ai_endpoint,ai_model,with_ai_call_contextandcapture_ai_events.- A new transport, or a new transport call, passes
ai_transport_contract_test.rb: every HTTP status maps ontoAi::Error, retries follow the endpoint, usage counts cached tokens, and the proxy is resolved byHttp.
Routing and consent
flowchart LR
Caller["a view, controller, job or tool"] -->|"Ai.available?(feature, family:, user:)"| R["Ai::Router"]
R --> C["Ai::Config.current<br/>endpoints, models, routes"]
C --> L["Ai::LegacyEnvConfig<br/>deprecated ENV + Setting"]
R --> M["Ai::Routes::MATRIX<br/>lane, needs, consent, sends"]
R --> K["Ai::Consent<br/>the user's or the family's"]
R -->|"Ai::Plan or Ai::Availability(reason)"| Caller
Where things live
| Concern | File |
|---|---|
| The routing table: each feature's lane, needs, consent level and data sent | app/models/ai/routes.rb, descriptions in config/locales/models/ai/en.yml |
| What may run for a feature, family and user, or why not | app/models/ai/router.rb, ai.rb (Ai.available?, Ai.availability, Ai.plan) |
| Consent | app/models/ai/consent.rb |
| The configuration snapshot and its routes | app/models/ai/config.rb, route.rb |
The deprecated AI ENV and Setting fields, read as configuration |
app/models/ai/legacy_env_config.rb |
| The controller guard | app/controllers/concerns/ai_feature_guard.rb (requires_ai) |
| The family's AI settings | app/models/family/ai_settings.rb |
Rules
- Ask the router, never a provider. Show an AI affordance with
ai_feature_available?(:feature)in a view, guard an action withrequires_ai :feature, and checkAi.available?(:feature, family:, user:)in a model or job. Don't testProvider::Registry,SettingorVectorStorefor availability. - No AI ENV. The cop
Sure/NoAiEnvflagsENVreads of AI-looking names outsideAi::LegacyEnvConfig; read AI configuration throughAi::Configinstead. The files on its allowlist in.rubocop.ymlstill read ENV; the list only shrinks. - A new feature is a row in
Ai::Routes::MATRIX, withsends:keys described inconfig/locales/models/ai/en.yml, and its key is permanent once released. Regenerate the table below withbin/rails ai:routes_doc;ai_routing_matrix_testfails when it's stale. - Consent is the level the matrix declares. A
userfeature needs the person's own AI switch (users.ai_enabled); afamilyfeature needsFamily#ai_consented?, which until families record consent means a family admin turned that switch on. Uploading a PDF for import is itself the request, soextract_pdf, andembedasked with no user (the upload's search copy), need no switch. - An AI tool declares its feature (
ai_feature :extract_pdfon anAssistant::Function), so chat and MCP list it only while the feature is available. Ai::Configis built in each process from its own ENV, so give the web and the worker containers the same AI variables.
| Feature | Lane | Needs | Consent row | Sends |
|---|---|---|---|---|
chat |
interactive | tools, streaming | Chat (user) | Your chat messages; The financial data the assistant looks up to answer; The text of statements stored in your vault |
bill_setup |
interactive | structured_output | Bills (user) | Transaction dates; Transaction amounts; Transaction names; Your category names; The bill's current settings |
extract_pdf |
prompt | structured_output | PDF import (user) | The document you upload |
embed |
prompt | embedding | Documents (user) | Your uploaded documents, as whole files to a vector store or as text chunks to an embedding model |
search_documents |
interactive | embedding | Documents (user) | Your search text |
categorize |
background | generation: structured_output; judgement: judge | Categories (family) | Transaction names; Transaction amounts; Categories your bank suggests; Your category names |
shadow_categorize |
background | generation: structured_output; judgement: judge | Categories (shadow runs) (family) | Transaction names; Transaction amounts; Categories your bank suggests; Your category names |
detect_merchants |
background | structured_output | Merchants (family) | Transaction names; Merchant names |
enhance_merchants |
background | structured_output | Merchants (family) | Merchant names |
Tests
use_ai_routes(categorize: %w[gpu/qwen3-8b openai/gpt-4.1-mini])routes the rest of the test through the test setup (AiTestHelper.test_config), the named features' routes replaced;use_no_aiconfigures nothing.test/architecture/ai_agreement_test.rbasks every entry point in each setup the provider code supports (test/support/ai_legacy_setups.rb) and fails when one disagrees with the router. Chat's entry points are on its allowlist, as chat doesn't go through the router yet.ai_config_test.rbchecks that the deprecated ENV path routes each feature to the provider and model the provider code uses;ai_feature_guard_test.rbthat every action starting an AI feature declaresrequires_ai.