Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

AI plumbing 2a: transports and instrumentation (#4773)

Josh Sandersdbeebf14c17a
diff --git a/AGENTS.md b/AGENTS.md
index f83a670eeb..1a5dbebdb3 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -41,4 +41,5 @@ Adding or modifying `app/controllers/api/v1/` endpoints requires Minitest behavi
- Read [provider sync guidance](docs/llm-guides/providers.md) when changing imports, pending transactions, FX metadata or diagnostics. Use `DebugLogEntry.capture(...)` for support-relevant failures and partial responses, with provider/source metadata and family/account-provider context where available.
- For securities providers, follow [adding a securities provider](docs/llm-guides/adding-a-securities-provider.md).
+- For AI transports, AI HTTP clients, AI usage rows or tracing, follow the [AI pipeline guide](docs/llm-guides/ai-pipeline.md).
- For feature rollout, follow [preview-feature gating](docs/llm-guides/gating-a-preview-feature.md); for goals, read the [Goals guide](docs/llm-guides/goals.md).
diff --git a/Gemfile b/Gemfile
index ba24892b65..fcf01e5bd7 100644
--- a/Gemfile
+++ b/Gemfile
@@ -109,6 +109,9 @@ gem "after_commit_everywhere", "~> 1.0"
# AI
gem "ruby-openai"
gem "anthropic", "~> 1.0"
+# AI transports (app/models/ai/transport). RubyLLM's API changes between minor releases, so
+# Gemfile.lock holds the version the AI tests run against; a contract test checks the API Sure uses.
+gem "ruby_llm", "~> 2.1"
gem "opentelemetry-sdk", "~> 1.13"
gem "opentelemetry-exporter-otlp", "~> 0.36"
diff --git a/Gemfile.lock b/Gemfile.lock
index 7a87df0648..0a9b4b3aa4 100644
--- a/Gemfile.lock
+++ b/Gemfile.lock
@@ -771,12 +771,23 @@ GEM
ffi (~> 1.12)
logger
ruby2_keywords (0.0.5)
+ ruby_llm (2.1.1)
+ base64
+ faraday (>= 1.10.0, != 2.0.0)
+ faraday-multipart (>= 1)
+ faraday-net_http (>= 1)
+ faraday-retry (>= 1)
+ json (< 4)
+ marcel (>= 1.0, < 3)
+ schematist (~> 1.1)
+ zeitwerk (~> 2)
rubyzip (3.4.0)
safety_net_attestation (0.5.0)
jwt (>= 2.0, < 4.0)
sawyer (0.9.2)
addressable (>= 2.3.5)
faraday (>= 0.17.3, < 3)
+ schematist (1.1.0)
securerandom (0.4.1)
selenium-webdriver (4.49.0)
base64 (~> 0.2)
@@ -1004,6 +1015,7 @@ DEPENDENCIES
rubocop-rails-omakase
ruby-lsp-rails
ruby-openai
+ ruby_llm (~> 2.1)
rubyzip (~> 3.4)
selenium-webdriver
sentry-rails
diff --git a/app/controllers/settings/llm_usages_controller.rb b/app/controllers/settings/llm_usages_controller.rb
index cf736bb500..577d6cfeda 100644
--- a/app/controllers/settings/llm_usages_controller.rb
+++ b/app/controllers/settings/llm_usages_controller.rb
@@ -17,11 +17,10 @@ class Settings::LlmUsagesController < ApplicationController
@start_date, @end_date = @end_date - 30.days, @end_date
end
- # Get usage data
- @llm_usages = @family.llm_usages
- .for_date_range(@start_date.beginning_of_day, @end_date.end_of_day)
- .recent
- .limit(100)
+ # One row per call; a call's requests (retries, resends) open beneath it.
+ @llm_calls = @family.llm_usages
+ .for_date_range(@start_date.beginning_of_day, @end_date.end_of_day)
+ .recent_calls(limit: 100)
# Get statistics
@statistics = LlmUsage.statistics_for_family(@family, start_date: @start_date.beginning_of_day, end_date: @end_date.end_of_day)
diff --git a/app/models/ai/call_context.rb b/app/models/ai/call_context.rb
new file mode 100644
index 0000000000..fa55904377
--- /dev/null
+++ b/app/models/ai/call_context.rb
@@ -0,0 +1,43 @@
+# Who an AI call is for and what it belongs to, set around every transport call.
+# It's a thin layer over RubyLLM's documented scopes, so RubyLLM's own events carry it:
+#
+# - `RubyLLM.with_usage_owner(family)`: `usage.ruby_llm` carries the family as `owner`;
+# - `RubyLLM.workflow(name, id:, metadata:)`: every RubyLLM event carries `workflow_id` (the
+# call id) and `workflow_metadata`.
+#
+# Sure keeps its own copy in fiber storage, which threads and fibers started inside inherit,
+# so `.ai` events and the OpenTelemetry processor never read RubyLLM's internals. RubyLLM
+# 2.1.1 keeps the workflow in Thread.current, which tool threads don't inherit; 2.2 moves it to
+# fiber storage (RubyLLM #1327).
+module Ai::CallContext
+ CALL_KEY = :ai_call_context
+
+ Call = Data.define(:feature, :call_id, :family_id, :endpoint, :model, :deadline) do
+ # Seconds left in the attempt budget, or nil when the call has none.
+ def remaining = deadline && (deadline - Ai::CallContext.now)
+
+ def expired? = !deadline.nil? && remaining <= 0
+
+ def metadata = { feature:, call_id:, family_id:, endpoint:, model: }.compact.transform_values(&:to_s)
+ end
+
+ module_function
+
+ def current = Fiber[CALL_KEY]
+
+ # Around one transport call. `budget` is the seconds one attempt may take, retries included.
+ def call(feature:, model:, family: nil, budget: nil)
+ call = Call.new(feature: feature.to_s, call_id: SecureRandom.uuid, family_id: family&.id,
+ endpoint: model.endpoint.name, model: model.name, deadline: budget && now + budget)
+ previous = Fiber[CALL_KEY]
+ Fiber[CALL_KEY] = call
+
+ RubyLLM.with_usage_owner(family) do
+ RubyLLM.workflow("ai.#{call.feature}", id: call.call_id, metadata: call.metadata) { yield call }
+ end
+ ensure
+ Fiber[CALL_KEY] = previous
+ end
+
+ def now = Process.clock_gettime(Process::CLOCK_MONOTONIC)
+end
diff --git a/app/models/ai/config/endpoint.rb b/app/models/ai/config/endpoint.rb
new file mode 100644
index 0000000000..89466a9d86
--- /dev/null
+++ b/app/models/ai/config/endpoint.rb
@@ -0,0 +1,42 @@
+# One connection a transport talks to: protocol, URL, key and tuning. Transports take these
+# values and never read ENV, Setting or ActiveRecord themselves; AiHealth's probes build them
+# from the current settings.
+class Ai::Config::Endpoint < Data.define(:name, :protocol, :preset, :base_url, :api_key, :extra_headers,
+ :timeout_seconds, :max_retries, :responses_api, :probe_check,
+ :exact_base_url)
+ PROTOCOLS = %i[compatible anthropic].freeze
+ # What a health probe checks:
+ # :models lists the server's models and makes no chat call; :chat sends a tiny chat request,
+ # which also catches a spent balance and a server that answers for a model it hasn't loaded.
+ # :models is the default, so a probe makes no chat call unless its endpoint asks for one.
+ PROBE_CHECKS = %i[models chat].freeze
+ # exact_base_url: the base URL is used as written, without the `/v1` Ai::Transport::Http.compatible_base
+ # adds, as VectorStore::Embeddable posts `embeddings` straight onto EMBEDDING_URI_BASE.
+
+ def initialize(name:, protocol:, preset: nil, base_url: nil, api_key: nil, extra_headers: {},
+ timeout_seconds: 60, max_retries: 0, responses_api: false, probe_check: :models,
+ exact_base_url: false)
+ protocol = protocol.to_sym
+ probe_check = probe_check.to_sym
+ raise ArgumentError, "unknown protocol #{protocol.inspect}" unless PROTOCOLS.include?(protocol)
+ raise ArgumentError, "unknown probe check #{probe_check.inspect}" unless PROBE_CHECKS.include?(probe_check)
+
+ super(name: name.to_s, protocol:, preset: preset&.to_sym, base_url: base_url.presence, api_key: api_key.presence,
+ extra_headers: extra_headers.to_h.transform_keys(&:to_s).freeze, timeout_seconds: Integer(timeout_seconds),
+ max_retries: Integer(max_retries), responses_api: responses_api ? true : false, probe_check:,
+ exact_base_url: exact_base_url ? true : false)
+ end
+
+ # What scrubbing removes from any text about this endpoint: the key, and every static header
+ # value long enough to be a credential, since a gateway can take one in a header.
+ def secrets = [ api_key, *extra_headers.values.map(&:to_s).select { _1.length >= 8 } ].compact_blank
+
+ # Never shows the key or header values, which can carry credentials.
+ def inspect
+ "#<Ai::Config::Endpoint #{name} #{protocol} #{Ai::Instrumentation::Redactor.url(base_url).inspect}>"
+ end
+ alias_method :to_s, :inspect
+
+ # What instrumentation may record about the endpoint.
+ def to_event = { name:, protocol:, preset: }.compact
+end
diff --git a/app/models/ai/config/model.rb b/app/models/ai/config/model.rb
new file mode 100644
index 0000000000..c2ce6fae8c
--- /dev/null
+++ b/app/models/ai/config/model.rb
@@ -0,0 +1,12 @@
+# A model on an endpoint.
+class Ai::Config::Model < Data.define(:endpoint, :name, :embedding_dimensions)
+ def initialize(endpoint:, name:, embedding_dimensions: nil)
+ super
+ end
+
+ def inspect = "#<Ai::Config::Model #{endpoint&.name}/#{name}>"
+ alias_method :to_s, :inspect
+
+ # What instrumentation records as the route: endpoint and model, never the key.
+ def to_event = { endpoint: endpoint.name, model: name }
+end
diff --git a/app/models/ai/error.rb b/app/models/ai/error.rb
new file mode 100644
index 0000000000..8e4cce1e44
--- /dev/null
+++ b/app/models/ai/error.rb
@@ -0,0 +1,105 @@
+# The AI layer's error taxonomy.
+# Transports map client-library and HTTP errors onto these classes, so code above a transport
+# never rescues a provider's own errors.
+module Ai::Error
+ class Base < StandardError
+ attr_reader :status
+
+ def initialize(message = nil, status: nil)
+ @status = status
+ super(message)
+ end
+ end
+
+ Cancelled = Class.new(Base)
+ Unreachable = Class.new(Base) # connection refused, DNS, TLS: no response came back
+ Timeout = Class.new(Base)
+ RateLimited = Class.new(Base) # 429
+ Upstream = Class.new(Base) # 5xx
+ Unauthorized = Class.new(Base) # 401/403: the key is wrong
+ NoCredit = Class.new(Base) # the key's balance is spent
+ ModelMissing = Class.new(Base) # the endpoint doesn't have the model
+ ContextTooLong = Class.new(Base) # 400 saying the input is too long
+ InvalidOutput = Class.new(Base) # parse or schema failure after the transport's fallbacks
+ Refused = Class.new(Base) # any other 4xx: not retried anywhere
+
+ # Errors a transport retries itself, up to the endpoint's max_retries.
+ RETRYABLE = [ RateLimited, Upstream, Timeout ].freeze
+
+ # Each provider words these differently.
+ CONTEXT_TOO_LONG = [
+ /context length/i, /context window/i, /context size/i, /maximum context/i, /context limit/i,
+ /too many tokens/i, /prompt is too long/i, /input is too long/i, /reduce the length/i,
+ /exceeds the available context/i
+ ].freeze
+
+ # Anthropic: 400 "credit balance is too low". OpenAI: 429 insufficient_quota or
+ # credit_balance_exhausted ("You have no credits remaining."). OpenRouter: 402.
+ NO_CREDIT = [
+ /credit balance is too low/i, /insufficient_quota/i, /credit_balance_exhausted/i,
+ /no credits remaining/i, /insufficient credits/i, /exceeded your current quota/i
+ ].freeze
+
+ # Ollama: 404 "model 'x' not found". OpenAI: 404 model_not_found, "The model `x` does not exist".
+ MODEL_MISSING = [ /model_not_found/i, /model\b.{0,120}\bnot found/im, /model\b.{0,120}\bdoes not exist/im ].freeze
+
+ module_function
+
+ def for_status(status, message = nil, body: nil)
+ text = [ message, body.is_a?(String) ? body : body&.to_json ].compact.join(" ")
+
+ case status.to_i
+ when 401, 403 then Unauthorized
+ when 402 then NoCredit
+ when 404 then matches?(text, MODEL_MISSING) ? ModelMissing : Refused
+ when 408 then Timeout
+ when 429 then matches?(text, NO_CREDIT) ? NoCredit : RateLimited
+ when 400, 413
+ if matches?(text, CONTEXT_TOO_LONG) then ContextTooLong
+ elsif matches?(text, NO_CREDIT) then NoCredit
+ else Refused
+ end
+ when 500..599 then Upstream
+ else Refused
+ end
+ end
+
+ def from_status(status, message = nil, body: nil)
+ for_status(status, message, body:).new(message, status: status.to_i)
+ end
+
+ # Maps an error from Faraday, Net::HTTP or a client gem that exposes an HTTP status onto the
+ # taxonomy. Returns nil for an error it doesn't recognise, so the caller decides.
+ def from_exception(error)
+ case error
+ when Base then error
+ when Faraday::TimeoutError, ::Timeout::Error, Net::ReadTimeout, Net::OpenTimeout
+ Timeout.new(error.message)
+ when Faraday::ConnectionFailed, Faraday::SSLError, SocketError, Errno::ECONNREFUSED,
+ Errno::EHOSTUNREACH, Errno::ENETUNREACH, Errno::ECONNRESET, OpenSSL::SSL::SSLError
+ Unreachable.new(error.message)
+ when Faraday::ParsingError
+ # A body that isn't JSON. Its status is often 200, which from_status would call a refusal.
+ InvalidOutput.new(error.message)
+ else
+ status, body = status_and_body(error)
+ from_status(status, error.message, body:) if status
+ end
+ end
+
+ # ruby-openai raises Faraday errors whose response is a Hash; the anthropic gem's errors
+ # carry `status` and `body`.
+ def status_and_body(error)
+ response = error.respond_to?(:response) ? error.response : nil
+ if response.is_a?(Hash)
+ [ response[:status] || response["status"], response[:body] || response["body"] ]
+ elsif response.respond_to?(:status)
+ [ response.status, response.respond_to?(:body) ? response.body : nil ]
+ elsif error.respond_to?(:status) && error.status.is_a?(Integer)
+ [ error.status, error.respond_to?(:body) ? error.body : nil ]
+ end
+ end
+
+ def matches?(text, patterns) = patterns.any? { text.match?(_1) }
+ private_class_method :status_and_body, :matches?
+end
diff --git a/app/models/ai/instrumentation.rb b/app/models/ai/instrumentation.rb
new file mode 100644
index 0000000000..b7b9d7f4fe
--- /dev/null
+++ b/app/models/ai/instrumentation.rb
@@ -0,0 +1,56 @@
+# AI instrumentation as subscribers to one set of events. Usage rows and the debug
+# log run in every mode; tracing has two modes, never at once, or Langfuse would get each
+# generation twice:
+#
+# content Sure's `.ai` events through LangfuseSubscriber: prompts, outputs, usage, route,
+# Sure's error class and session. The default, when Langfuse keys are set.
+# metadata RubyLLM's OpenTelemetry spans to OTLP_ENDPOINT: model, settings, tokens, latency,
+# no content. For operators who want cost and latency without sending financial
+# data to a tracing backend.
+# off Neither.
+#
+# The mode follows from the variables an operator already sets, so no AI variable is added:
+# Langfuse keys mean content, OTLP_ENDPOINT alone means metadata.
+module Ai::Instrumentation
+ module_function
+
+ def mode(env: ENV)
+ langfuse = env["LANGFUSE_PUBLIC_KEY"].present? && env["LANGFUSE_SECRET_KEY"].present?
+ return :content if langfuse
+ return :metadata if env["OTLP_ENDPOINT"].present?
+
+ :off
+ end
+
+ # The subscribers for this mode, returned so the caller can unsubscribe them when code
+ # reloads (config/initializers/ai_instrumentation.rb).
+ def subscribe!(env: ENV)
+ usage = UsageSubscriber.new
+ subscriptions = [
+ ActiveSupport::Notifications.subscribe("usage.ruby_llm", usage),
+ ActiveSupport::Notifications.subscribe("request.ruby_llm", usage),
+ ActiveSupport::Notifications.subscribe(/\.ai\z/, usage),
+ ActiveSupport::Notifications.subscribe(/\.ai\z/, DebugLogSubscriber.new)
+ ]
+ subscriptions << ActiveSupport::Notifications.subscribe(/\.ai\z/, LangfuseSubscriber.new) if mode(env:) == :content
+ subscriptions
+ end
+
+ # Once per process: metadata mode sets the global OpenTelemetry tracer provider.
+ def start_tracing!(env: ENV)
+ case mode(env:)
+ when :content then warn_both_tracing_modes if env["OTLP_ENDPOINT"].present?
+ when :metadata
+ provider = MetadataTracing.enable(endpoint: env["OTLP_ENDPOINT"], headers: env["OTLP_HEADERS"])
+ # The batch processor exports on a timer; without a shutdown a process loses its last batch
+ # at exit, which for a rake task or `rails runner` is every span (seen live against Langfuse).
+ at_exit { provider.shutdown }
+ end
+ end
+
+ def warn_both_tracing_modes
+ Rails.logger.warn("[AI] Langfuse keys and OTLP_ENDPOINT are both set: tracing in content mode (Langfuse). " \
+ "Unset the Langfuse keys to send metadata-only spans to OTLP_ENDPOINT instead.")
+ end
+ private_class_method :warn_both_tracing_modes
+end
diff --git a/app/models/ai/instrumentation/debug_log_subscriber.rb b/app/models/ai/instrumentation/debug_log_subscriber.rb
new file mode 100644
index 0000000000..2b95689bbb
--- /dev/null
+++ b/app/models/ai/instrumentation/debug_log_subscriber.rb
@@ -0,0 +1,29 @@
+# A DebugLogEntry for every AI call that fails, so an operator sees it on the
+# debug page with its feature, route and error, never its key or prompt. Health probes are
+# skipped: AiHealth::Probe logs its own failures, with its failure codes.
+class Ai::Instrumentation::DebugLogSubscriber
+ SKIPPED = %w[probe.ai].freeze
+
+ def call(event)
+ payload = event.payload
+ return if payload[:error].blank? || SKIPPED.include?(event.name)
+
+ DebugLogEntry.capture(
+ category: "ai",
+ level: "error",
+ message: "AI #{payload[:feature] || "call"} failed: #{payload[:error].to_s.demodulize}",
+ source: self.class.name,
+ provider_key: payload.dig(:endpoint, :name),
+ family_id: payload[:family_id],
+ metadata: {
+ feature: payload[:feature],
+ route: payload[:route],
+ endpoint: payload[:endpoint],
+ error_class: payload[:error],
+ error_message: payload[:error_message],
+ http_status: payload[:http_status],
+ call_id: payload[:call_id]
+ }.compact
+ )
+ end
+end
diff --git a/app/models/ai/instrumentation/langfuse_subscriber.rb b/app/models/ai/instrumentation/langfuse_subscriber.rb
new file mode 100644
index 0000000000..c9a0225f42
--- /dev/null
+++ b/app/models/ai/instrumentation/langfuse_subscriber.rb
@@ -0,0 +1,57 @@
+# The `content` tracing mode: each `.ai` event becomes a Langfuse trace with one
+# generation holding the request, the output, usage and the error. Health probes aren't traced:
+# they carry no family data and run every time an admin opens the health page.
+class Ai::Instrumentation::LangfuseSubscriber
+ SKIPPED = %w[probe.ai].freeze
+ CREDENTIAL_FIELD = /\A(?:api[_-]?key|access[_-]?token|secret|password|authorization)\z/i
+
+ def initialize(client: Rails.configuration.x.langfuse, environment: Rails.env)
+ @client = client
+ @environment = environment
+ end
+
+ def call(event)
+ return if @client.nil? || SKIPPED.include?(event.name)
+
+ payload = event.payload
+ scrub = payload[:scrub] || Ai::Instrumentation::Redactor.method(:scrub)
+ input = plain(payload[:request], scrub)
+ output = payload[:error] ? { error: payload[:error], message: payload[:error_message] } : plain(payload[:output], scrub)
+ level = payload[:error] ? "ERROR" : nil
+
+ trace = @client.trace(name: "#{payload[:feature] || "ai"}.#{event.name.delete_suffix(".ai")}", input:,
+ environment: @environment, start_time: event_start(event),
+ metadata: { route: payload[:route], call_id: payload[:call_id], error: payload[:error] }.compact)
+ generation = trace&.generation(name: event.name, input:, model: payload.dig(:route, :model), start_time: event_start(event))
+ generation&.end(output:, usage: usage(payload[:usage]), level:)
+ trace&.end(output:, level:)
+ rescue StandardError => error
+ Rails.logger.warn("[Ai::Instrumentation::LangfuseSubscriber] #{error.class}")
+ end
+
+ private
+ # Langfuse wants the whole prompt, cached tokens included, as input.
+ def usage(tokens)
+ return unless tokens.is_a?(Ai::Tokens) && tokens.known?
+
+ { input_tokens: tokens.prompt_tokens.to_i, output_tokens: tokens.output_tokens.to_i,
+ prompt_tokens_details: { cached_tokens: tokens.cache_read_tokens.to_i } }
+ end
+
+ def event_start(event) = Time.current - (event.duration.to_f / 1000)
+
+ # Value objects become plain hashes, all the way down; the endpoint's key and header values,
+ # and anything shaped like a key, are scrubbed from strings.
+ def plain(value, scrub)
+ case value
+ when Data then plain(value.to_h, scrub)
+ when Hash then value.to_h { |key, item| [ key, credential_field?(key, item) ? Ai::Instrumentation::Redactor::MASK : plain(item, scrub) ] }
+ when Array then value.map { plain(_1, scrub) }
+ when String then scrub.call(value)
+ else value
+ end
+ end
+
+ # A field named like a credential is masked whole, whatever its value looks like.
+ def credential_field?(key, value) = value.is_a?(String) && value.present? && key.to_s.match?(CREDENTIAL_FIELD)
+end
diff --git a/app/models/ai/instrumentation/metadata_tracing.rb b/app/models/ai/instrumentation/metadata_tracing.rb
new file mode 100644
index 0000000000..7a9b7f570a
--- /dev/null
+++ b/app/models/ai/instrumentation/metadata_tracing.rb
@@ -0,0 +1,66 @@
+require "opentelemetry/sdk"
+require "opentelemetry-exporter-otlp"
+
+# The `metadata` tracing mode: RubyLLM's own OpenTelemetry spans (model, settings,
+# finish reason, tokens, latency, error class) go to any OTLP backend at OTLP_ENDPOINT, with no
+# prompt, tool result or answer. It loses the route, the prompt key, Sure's error class and
+# errors raised before RubyLLM is called.
+#
+# RubyLLM 2.1.1 has no code to put content on spans. 2.2 adds `enable(content: true)` (RubyLLM #1333),
+# off by default; `content: false` is passed explicitly whenever the gem accepts it, and
+# test/models/ai/instrumentation/metadata_tracing_test.rb fails if any span carries content.
+module Ai::Instrumentation::MetadataTracing
+ # Health probes carry no family data and aren't traced (docs/hosting/ai.md), so every span
+ # started inside a probe call is dropped; any other span is sampled as the SDK's default does.
+ class ProbeSampler
+ DEFAULT = OpenTelemetry::SDK::Trace::Samplers.parent_based(root: OpenTelemetry::SDK::Trace::Samplers::ALWAYS_ON)
+
+ def should_sample?(trace_id:, parent_context:, links:, name:, kind:, attributes:)
+ return DEFAULT.should_sample?(trace_id:, parent_context:, links:, name:, kind:, attributes:) unless probe?
+
+ OpenTelemetry::SDK::Trace::Samplers::Result.new(decision: OpenTelemetry::SDK::Trace::Samplers::Decision::DROP,
+ tracestate: OpenTelemetry::Trace.current_span(parent_context).context.tracestate)
+ end
+
+ def description = "SureProbeSampler"
+
+ private
+ def probe? = Ai::CallContext.current&.feature == "probe"
+ end
+
+ module_function
+
+ # The app owns the tracer provider and exporter, as RubyLLM's OpenTelemetry docs ask.
+ def enable(endpoint: nil, headers: nil, processor: nil)
+ processor ||= OpenTelemetry::SDK::Trace::Export::BatchSpanProcessor.new(
+ OpenTelemetry::Exporter::OTLP::Exporter.new(endpoint:, headers: parse_headers(headers))
+ )
+ provider = OpenTelemetry::SDK::Trace::TracerProvider.new(sampler: ProbeSampler.new)
+ provider.add_span_processor(processor)
+ OpenTelemetry.tracer_provider = provider
+
+ if RubyLLM::OpenTelemetry.method(:enable).parameters.any? { |_, name| name == :content }
+ RubyLLM::OpenTelemetry.enable(content: false)
+ else
+ RubyLLM::OpenTelemetry.enable
+ end
+ provider
+ end
+
+ # OTLP_HEADERS uses the OpenTelemetry form: `key=value,key=value`, values percent-encoded.
+ def parse_headers(value)
+ value.to_s.split(",").filter_map do |pair|
+ key, header = pair.split("=", 2).map { _1.to_s.strip }
+ [ key, percent_decode(header) ] if key.present?
+ end.to_h
+ end
+
+ # Percent-decoding only, as the OTLP exporter parses its own headers variable: a literal `+`
+ # stays, since a value is RFC 3986 text, not form data, so a base64 credential keeps its
+ # pluses. A malformed sequence stays as written rather than raising: the value is operator-set.
+ def percent_decode(value)
+ URI.decode_uri_component(value.to_s)
+ rescue ArgumentError
+ value.to_s
+ end
+end
diff --git a/app/models/ai/instrumentation/redactor.rb b/app/models/ai/instrumentation/redactor.rb
new file mode 100644
index 0000000000..bee6fcc40a
--- /dev/null
+++ b/app/models/ai/instrumentation/redactor.rb
@@ -0,0 +1,40 @@
+# The one place AI instrumentation scrubs secrets. Every subscriber, and every
+# `inspect` of an endpoint, goes through it, so a key never reaches a log, the debug log or a
+# trace. Providers often quote the request back in an error, so error text is scrubbed too.
+module Ai::Instrumentation::Redactor
+ MASK = "[REDACTED]".freeze
+
+ # [pattern, replacement]: key shapes are masked whole; a header or field keeps its name.
+ PATTERNS = [
+ [ /\b(?:sk|pk|rk)-[A-Za-z0-9_\-]{8,}/, MASK ],
+ [ /\bAIza[0-9A-Za-z_\-]{20,}/, MASK ],
+ [ /\b(Bearer|Basic)\s+[A-Za-z0-9._~+\/=\-]{8,}/i, "\\1 #{MASK}" ],
+ [ /\b(api[_-]?key|access[_-]?token|secret|password)(["']?\s*[:=]\s*["']?)[^"'\s,&}]{4,}/i, "\\1\\2#{MASK}" ]
+ ].freeze
+
+ module_function
+
+ # Masks known key shapes, plus every exact secret the caller passes (an endpoint's key).
+ # Longest first: a secret that contains a shorter one would otherwise keep the rest visible.
+ def scrub(text, secrets: [])
+ return text if text.blank?
+
+ exact = Array(secrets).compact_blank.map(&:to_s).sort_by { -_1.length }
+ scrubbed = exact.reduce(text.to_s) { |memo, secret| memo.gsub(secret, MASK) }
+ PATTERNS.reduce(scrubbed) { |memo, (pattern, replacement)| memo.gsub(pattern, replacement) }
+ end
+
+ # A URL without credentials, query or fragment.
+ def url(value)
+ return if value.blank?
+
+ uri = URI.parse(value.to_s)
+ uri.user = nil if uri.respond_to?(:user=)
+ uri.password = nil if uri.respond_to?(:password=)
+ uri.query = nil if uri.respond_to?(:query=)
+ uri.fragment = nil if uri.respond_to?(:fragment=)
+ uri.to_s
+ rescue URI::InvalidURIError
+ MASK # an unparseable URL may still hold credentials, so none of it is shown
+ end
+end
diff --git a/app/models/ai/instrumentation/usage_subscriber.rb b/app/models/ai/instrumentation/usage_subscriber.rb
new file mode 100644
index 0000000000..73f7af90b5
--- /dev/null
+++ b/app/models/ai/instrumentation/usage_subscriber.rb
@@ -0,0 +1,94 @@
+# One llm_usages row per HTTP request, retries and failures included, from RubyLLM's
+# `usage.ruby_llm`: the family is the usage owner and the call is the workflow Ai::CallContext
+# opened. That event carries no error, so a failed row takes it from the `request.ruby_llm` event
+# that finishes next, or else from the call's `.ai` event, which finishes last.
+#
+# Requests outside a call context with a family (health probes, eval runs) write nothing.
+class Ai::Instrumentation::UsageSubscriber
+ STATUSES = { succeeded: "succeeded", failed: "failed", cancelled: "cancelled" }.freeze
+
+ def call(event)
+ case event.name
+ when "usage.ruby_llm" then record_request(event.payload)
+ when "request.ruby_llm" then record_request_error(event.payload)
+ else record_error(event.payload)
+ end
+ rescue StandardError => error
+ Rails.logger.error("[Ai::Instrumentation::UsageSubscriber] #{error.class}: #{error.message}")
+ end
+
+ private
+ # RubyLLM 2.1.1 keeps the usage owner and workflow in Thread.current, so a request from a thread
+ # started inside a call has neither (2.2 moves them to fiber storage, RubyLLM #1327). Sure's
+ # own call context is in fiber storage, which threads inherit, so it fills the gap.
+ def owner_and_call(payload)
+ call = (payload[:workflow_metadata] || {}).to_h.stringify_keys
+ return [ payload[:owner], call ] if call["call_id"].present?
+
+ context = Ai::CallContext.current
+ return [ payload[:owner], call ] if context.nil?
+
+ [ payload[:owner] || (Family.find_by(id: context.family_id) if context.family_id), context.metadata.stringify_keys ]
+ end
+
+ def record_request(payload)
+ family, call = owner_and_call(payload)
+ return unless family.is_a?(Family) && call["call_id"].present?
+
+ status = STATUSES.fetch(payload[:status], nil)
+ return if status.nil? # :pending entries finish later as another event
+
+ tokens = Ai::Tokens.from_ruby_llm(payload[:tokens], payload[:cost])
+ model = call["model"].presence || payload[:model].to_s
+
+ family.llm_usages.create!(
+ provider: call["endpoint"],
+ model:,
+ operation: call["feature"],
+ status:,
+ call_id: call["call_id"],
+ prompt_tokens: tokens.prompt_tokens.to_i,
+ completion_tokens: tokens.output_tokens.to_i,
+ total_tokens: tokens.total_tokens.to_i,
+ cache_read_tokens: tokens.cache_read_tokens,
+ cache_creation_tokens: tokens.cache_write_tokens,
+ estimated_cost: cost(tokens, model),
+ metadata: {
+ route: { endpoint: call["endpoint"], model: },
+ tokens_unknown: (true unless tokens.known?)
+ }.compact
+ )
+ end
+
+ # The provider's reported cost first, otherwise the published prices. Unknown tokens have no
+ # cost. LlmUsage prices cache reads and writes apart only for Anthropic; any other
+ # provider's cached input is priced as input, as its own usage recorder does.
+ def cost(tokens, model)
+ return tokens.cost unless tokens.cost.nil?
+ return unless tokens.known?
+
+ prompt = LlmUsage.infer_provider(model) == "anthropic" ? tokens.input_tokens : tokens.prompt_tokens
+ LlmUsage.calculate_cost(model:, prompt_tokens: prompt.to_i, completion_tokens: tokens.output_tokens.to_i,
+ cache_creation_tokens: tokens.cache_write_tokens.to_i, cache_read_tokens: tokens.cache_read_tokens.to_i)
+ end
+
+ # The request that just failed is the call's newest failed row without an error.
+ def record_request_error(payload)
+ _family, call = owner_and_call(payload)
+ call_id = call["call_id"]
+ return if payload[:ai_error].blank? || call_id.blank?
+
+ LlmUsage.where(id: unexplained_failures(call_id).order(created_at: :desc).limit(1).select(:id))
+ .update_all([ "metadata = metadata || ?::jsonb", payload[:ai_error].to_json ])
+ end
+
+ def unexplained_failures(call_id) = LlmUsage.where(call_id:, status: "failed").where("NOT (metadata ? 'error')")
+
+ def record_error(payload)
+ return if payload[:error].blank? || payload[:call_id].blank? || payload[:family_id].blank?
+
+ details = { error: payload[:error_message].presence || payload[:error], error_class: payload[:error],
+ http_status_code: payload[:http_status] }.compact
+ unexplained_failures(payload[:call_id]).update_all([ "metadata = metadata || ?::jsonb", details.to_json ])
+ end
+end
diff --git a/app/models/ai/tokens.rb b/app/models/ai/tokens.rb
new file mode 100644
index 0000000000..1002cedc2d
--- /dev/null
+++ b/app/models/ai/tokens.rb
@@ -0,0 +1,41 @@
+# Token counts and cost for one request, named after RubyLLM::Tokens, which
+# holds the same counts. `Usage` is taken twice already: installation telemetry
+# (`Usage`) and the `llm_usages` table (`LlmUsage`).
+#
+# Counts a provider didn't report stay nil rather than 0, as RubyLLM 2.2 does (RubyLLM #1099, #1126).
+# RubyLLM's `input` excludes cached tokens, unlike the raw APIs, so the prompt's size is
+# input plus cache reads and cache writes (Anthropic reports writes apart from input).
+Ai::Tokens = Data.define(:input_tokens, :output_tokens, :cache_read_tokens, :cache_write_tokens, :cost) do
+ def initialize(input_tokens: nil, output_tokens: nil, cache_read_tokens: nil, cache_write_tokens: nil, cost: nil)
+ super
+ end
+
+ # tokens: a RubyLLM::Tokens or nil; cost: a RubyLLM::Cost, a number or nil. A cost the
+ # provider reported (OpenRouter's usage.cost, a BYOK key's upstream cost included) wins.
+ def self.from_ruby_llm(tokens, cost = nil)
+ reported = tokens.respond_to?(:reported_cost) ? tokens.reported_cost : nil
+ total = cost.respond_to?(:total) ? cost.total : cost
+
+ new(
+ input_tokens: tokens&.input,
+ output_tokens: tokens&.output,
+ cache_read_tokens: tokens&.cache_read,
+ cache_write_tokens: tokens&.cache_write,
+ cost: valid_cost(reported) || valid_cost(total)
+ )
+ end
+
+ # A negative or non-finite cost would fail LlmUsage's validation and lose the row; without
+ # one the subscriber estimates from the tokens.
+ def self.valid_cost(value) = value.is_a?(Numeric) && value.finite? && value >= 0 ? value : nil
+
+ def known? = [ input_tokens, output_tokens, cache_read_tokens, cache_write_tokens ].any?
+
+ def prompt_tokens = sum(sum(input_tokens, cache_read_tokens), cache_write_tokens)
+
+ def total_tokens = sum(prompt_tokens, output_tokens)
+
+ private
+ # Unknown plus unknown stays unknown; unknown plus a count is the count.
+ def sum(a, b) = a.nil? && b.nil? ? nil : (a || 0) + (b || 0)
+end
diff --git a/app/models/ai/transport.rb b/app/models/ai/transport.rb
new file mode 100644
index 0000000000..a0aadaa6cd
--- /dev/null
+++ b/app/models/ai/transport.rb
@@ -0,0 +1,11 @@
+# Thin adapters over RubyLLM, one per protocol. Everything above a transport sees
+# Ai::Config values, Ai::Tokens and Ai::Error, never a client library's types.
+module Ai::Transport
+ def self.for(endpoint)
+ case endpoint.protocol
+ when :compatible then Ai::Transport::Compatible.new(endpoint)
+ when :anthropic then Ai::Transport::Anthropic.new(endpoint)
+ else raise ArgumentError, "no transport for the #{endpoint.protocol} protocol"
+ end
+ end
+end
diff --git a/app/models/ai/transport/anthropic.rb b/app/models/ai/transport/anthropic.rb
new file mode 100644
index 0000000000..04aee97d47
--- /dev/null
+++ b/app/models/ai/transport/anthropic.rb
@@ -0,0 +1,58 @@
+# Claude through the native Messages API; its OpenAI-compatible layer drops
+# features.
+class Ai::Transport::Anthropic < Ai::Transport::Base
+ include Ai::Transport::RubyLlmAdapter
+
+ DEFAULT_BASE = "https://api.anthropic.com".freeze
+ API_VERSION = "2023-06-01".freeze
+
+ private
+ def run_probe(model, check, timeout:)
+ case check
+ when :models then probe_models(model, timeout:)
+ when :chat then probe_chat(model, timeout:)
+ when :tools then probe_tools(model, timeout:)
+ when :embedding then raise Ai::Error::Refused, "Anthropic has no embedding models"
+ end
+ end
+
+ # RubyLLM 2.1.1 has no public per-context model listing, so this is a plain GET through
+ # Faraday with Ai::Transport::Http's proxy and TLS options, as every other call gets. The
+ # anthropic gem, used here before, reads only HTTP_PROXY: live, it went direct when only
+ # HTTPS_PROXY was set, so the probe checked a different path from the calls it vouches for.
+ def probe_models(model, timeout:)
+ url = "#{ruby_llm_api_base.delete_suffix("/")}/v1/models/#{ERB::Util.url_encode(model.name)}"
+ mapping_errors do
+ response = Ai::Transport::Http.faraday(url, timeout:).get(url) do |request|
+ request.headers.update(Ai::Transport::Http.headers(endpoint))
+ request.headers["x-api-key"] = endpoint.api_key.to_s
+ request.headers["anthropic-version"] = API_VERSION
+ end
+ body = JSON.parse(response.body.to_s) rescue nil
+ raise models_error(response.status, body) unless response.success?
+ raise Ai::Error::InvalidOutput, "the model lookup didn't answer with JSON" unless body.is_a?(Hash)
+ raise Ai::Error::ModelMissing, "#{model.name} isn't listed" if body["id"].blank?
+
+ check_answering_model!(model.name, body["id"]) # a gateway may answer with another model
+ body["id"]
+ end
+ end
+
+ # A body that isn't Anthropic's error shape still maps by its status.
+ def models_error(status, body)
+ error = body.is_a?(Hash) ? body["error"] : nil
+ message = (error.is_a?(Hash) ? error["message"] : error&.to_s).presence || "HTTP #{status}"
+ return Ai::Error::ModelMissing.new(message, status:) if missing_model?(status, body)
+
+ Ai::Error.from_status(status, message, body:)
+ end
+
+ def ruby_llm_provider = :anthropic
+ def ruby_llm_protocol = nil
+ def ruby_llm_api_base = endpoint.base_url.presence || DEFAULT_BASE
+
+ def configure_provider(config)
+ config.anthropic_api_key = endpoint.api_key
+ config.anthropic_api_base = endpoint.base_url if endpoint.base_url.present?
+ end
+end
diff --git a/app/models/ai/transport/base.rb b/app/models/ai/transport/base.rb
new file mode 100644
index 0000000000..ac14904357
--- /dev/null
+++ b/app/models/ai/transport/base.rb
@@ -0,0 +1,132 @@
+# The transport interface: health probes, with retries and one `.ai` event per call.
+class Ai::Transport::Base
+ # Health checks a probe can make. Which one AiHealth runs for "is the model up" is the
+ # endpoint's `probe_check`; tools and embedding are their own probes.
+ PROBE_CHECKS = %i[models chat tools embedding].freeze
+ PROBE_PROMPT = "Reply with OK.".freeze
+ PROBE_TOOL_PROMPT = "Call the sure_health_check tool with status set to ok.".freeze
+ PROBE_TOOL_NAME = "sure_health_check".freeze
+ PROBE_TOOL_SCHEMA = {
+ type: "object",
+ properties: { status: { type: "string", description: "Always the literal string \"ok\"." } },
+ required: [ "status" ],
+ additionalProperties: false
+ }.freeze
+ PROBE_EMBEDDING_INPUT = "Sure AI health check".freeze
+ PROBE_MAX_OUTPUT_TOKENS = 16
+ PROBE_TOOL_MAX_OUTPUT_TOKENS = 256
+ # What a provider may add to a model's name for a dated snapshot of it.
+ SNAPSHOT_SUFFIX = /\A-(?:\d{4}-\d{2}-\d{2}|\d{8}|\d{4})\z/
+
+ attr_reader :endpoint
+
+ def initialize(endpoint)
+ @endpoint = endpoint
+ end
+
+ # Health probes reuse the production path, so they can't drift from it: the same client settings,
+ # headers, timeout, proxy and error mapping. Returns what the check found, or raises an
+ # Ai::Error:
+ # :models -> the model's id, when the server lists it (no chat call);
+ # :chat -> the answer's text, after checking the model that answered;
+ # :tools -> true when the model called the test tool, false when it answered in text;
+ # :embedding -> the embedding's dimensions.
+ def probe(model, check, timeout: endpoint.timeout_seconds)
+ raise ArgumentError, "unknown probe check #{check.inspect}" unless PROBE_CHECKS.include?(check)
+
+ Ai::CallContext.call(feature: :probe, model:, budget: timeout) do
+ instrument("probe", model:, request: { check: }) { attempt { run_probe(model, check, timeout: within_budget(timeout)) } }
+ end
+ end
+
+ private
+ def run_probe(model, check, timeout:) = raise(NotImplementedError)
+
+ # Sure retries, not RubyLLM: RubyLLM has no hook before a retry, so only here can a spent
+ # balance (OpenAI's 429 insufficient_quota) stop retrying and the attempt budget, wait
+ # included, be checked between tries.
+ def attempt
+ tries = 0
+ begin
+ tries += 1
+ check_budget!
+ result = yield
+ check_budget!(after: true)
+ result
+ rescue *Ai::Error::RETRYABLE => error
+ delay = retry_delay(tries)
+ remaining = Ai::CallContext.current&.remaining
+ raise if tries > endpoint.max_retries || (remaining && remaining <= delay)
+
+ sleep(delay)
+ retry
+ end
+ end
+
+ # Requests RubyLLM doesn't send, such as the models list, aren't checked by its instrumenter.
+ # After an attempt too, so an answer that arrives late isn't taken as a pass.
+ def check_budget!(after: false)
+ return unless Ai::CallContext.current&.expired?
+
+ raise Ai::Error::Timeout, "the attempt's time budget was spent #{after ? "before the answer arrived" : "before the request was sent"}"
+ end
+
+ # A request's timeout, cut to what's left of the call's budget, so a retry can't outlast it.
+ def within_budget(timeout)
+ remaining = Ai::CallContext.current&.remaining
+ remaining ? [ timeout, remaining ].min : timeout
+ end
+
+ def retry_delay(tries) = [ 0.5 * (2**(tries - 1)), 8 ].min * (0.75 + rand * 0.5)
+
+ # One `.ai` event per call, carrying what subscribers need: the route, the
+ # request (files by name and size, never their bytes), the output, usage and error class.
+ def instrument(name, model:, request:)
+ call = Ai::CallContext.current
+ payload = { feature: call&.feature, call_id: call&.call_id,
+ family_id: call&.family_id, endpoint: endpoint.to_event, route: model.to_event, request:,
+ scrub: scrubber }
+
+ ActiveSupport::Notifications.instrument("#{name}.ai", payload) do
+ result = yield
+ payload[:output] = result
+ result
+ rescue Ai::Error::Base => error
+ payload[:error] = error.class.name
+ payload[:error_message] = Ai::Instrumentation::Redactor.scrub(error.message, secrets: endpoint.secrets)
+ payload[:http_status] = error.status
+ raise
+ end
+ end
+
+ # Scrubs a string of this endpoint's key and header values, for a subscriber that sends
+ # content elsewhere. A function, so the payload never holds the secrets themselves.
+ def scrubber
+ secrets = endpoint.secrets
+ ->(text) { Ai::Instrumentation::Redactor.scrub(text, secrets:) }
+ end
+
+ # The model that answered differs from the one asked for: LM Studio answers a request for a
+ # model it doesn't have with whichever model is loaded, and a 200.
+ def check_answering_model!(asked, answered)
+ return if answered.blank? || same_model?(asked, answered)
+
+ raise Ai::Error::ModelMissing, "asked for #{asked}, but #{answered} answered"
+ end
+
+ # The same model under a vendor prefix (openai/gpt-4.1), a snapshot date (gpt-4.1-2025-04-14,
+ # claude-sonnet-4-5-20250929, gpt-4-0613) or for a `latest` alias. Any other difference is
+ # another model: gpt-4.1-mini isn't gpt-4.1, nor gpt-4o gpt-4.
+ # Two qualified ids (org-a/model, org-b/model) keep their namespaces.
+ def same_model?(asked, answered)
+ qualified = [ asked, answered ].all? { _1.to_s.include?("/") }
+ short, long = [ asked, answered ].map { model_stem(_1, qualified:) }.sort_by(&:length)
+ short == long || (long.start_with?(short) && long.delete_prefix(short).match?(SNAPSHOT_SUFFIX))
+ end
+
+ def model_stem(name, qualified: false)
+ stem = name.to_s.downcase
+ stem = stem.split("/").last.to_s unless qualified
+ stem.delete_suffix(":latest").delete_suffix("-latest")
+ end
+end
diff --git a/app/models/ai/transport/compatible.rb b/app/models/ai/transport/compatible.rb
new file mode 100644
index 0000000000..035c158a05
--- /dev/null
+++ b/app/models/ai/transport/compatible.rb
@@ -0,0 +1,87 @@
+# The OpenAI API, whoever runs it: OpenAI, Gemini's compatible API, OpenRouter,
+# LiteLLM, llama.cpp, Ollama, vLLM, LM Studio, embedding servers and the external assistant.
+class Ai::Transport::Compatible < Ai::Transport::Base
+ include Ai::Transport::RubyLlmAdapter
+
+ private
+ def run_probe(model, check, timeout:)
+ case check
+ when :models then probe_models(model, timeout:)
+ when :chat then probe_chat(model, timeout:)
+ when :tools then probe_tools(model, timeout:)
+ when :embedding then probe_embedding(model, timeout:)
+ end
+ end
+
+ # Model listing stays on ruby-openai, built by Ai::Transport::Http: RubyLLM 2.1.1 has no
+ # public per-context model listing (Provider#list_models is :nodoc:).
+ def probe_models(model, timeout:)
+ response = mapping_errors { Ai::Transport::Http.openai_client(endpoint, timeout:).models.list }
+ raise Ai::Error::InvalidOutput, "the models list has no data" unless response.is_a?(Hash) && response["data"].is_a?(Array)
+ raise Ai::Error::InvalidOutput, "the models list has entries that aren't objects" unless response["data"].all?(Hash)
+
+ ids = response["data"].filter_map { _1["id"] }
+ # Ollama lists `llama3` as `llama3:latest`.
+ unless ids.include?(model.name) || ids.include?("#{model.name}:latest")
+ raise Ai::Error::ModelMissing, "#{model.name} isn't listed"
+ end
+
+ model.name
+ end
+
+ # One vector per text, with the model's dimensions. RubyLLM 2.1.1 doesn't check the row
+ # count itself (2.2 does, RubyLLM #1297).
+ # RubyLLM 2.1.1's embed takes no headers (crmne/ruby_llm#1556), so an endpoint that needs
+ # them is refused rather than probed without them.
+ def probe_embedding(model, timeout:)
+ if Ai::Transport::Http.headers(endpoint).any?
+ raise Ai::Error::Refused, "embedding requests can't carry the endpoint's static headers yet"
+ end
+
+ embedding = mapping_errors do
+ ruby_llm_context(timeout:).embed(Ai::Transport::Base::PROBE_EMBEDDING_INPUT, model: model.name, provider: ruby_llm_provider,
+ assume_model_exists: true)
+ end
+ vectors = embedding.vectors
+ vectors = [ vectors ] if vectors.first.is_a?(Numeric)
+ raise Ai::Error::InvalidOutput, "expected 1 vector, got #{vectors.size}" unless vectors.size == 1
+ unless vectors.first.is_a?(Array) && vectors.first.all? { _1.is_a?(Numeric) && _1.finite? }
+ raise Ai::Error::InvalidOutput, "the embedding has components that aren't finite numbers"
+ end
+
+ dimensions = vectors.first.size
+ expected = model.embedding_dimensions
+ raise Ai::Error::InvalidOutput, "expected #{expected} dimensions, got #{dimensions}" if expected && dimensions != expected
+
+ dimensions
+ end
+
+ # OpenRouter keeps its own RubyLLM provider: only it round-trips reasoning_details
+ # (Gemini's thought signatures). Every other compatible server is :openai.
+ def ruby_llm_provider = endpoint.preset == :openrouter ? :openrouter : :openai
+
+ # Always explicit: RubyLLM's :openai provider defaults to the Responses API, a bare 404 on
+ # other compatible servers.
+ def ruby_llm_protocol = endpoint.responses_api ? :responses : :chat_completions
+
+ # An OpenRouter endpoint without a URL is OpenRouter's, as for ruby-openai's client.
+ def ruby_llm_api_base
+ return endpoint.base_url.chomp("/") if endpoint.exact_base_url && endpoint.base_url
+
+ base = endpoint.base_url.presence || (Ai::Transport::Http::OPENROUTER_BASE if ruby_llm_provider == :openrouter)
+ Ai::Transport::Http.compatible_base(base)
+ end
+
+ def configure_provider(config)
+ config.openai_use_system_role = true # both providers read it; otherwise system prompts go as "developer"
+ if ruby_llm_provider == :openrouter
+ config.openrouter_api_key = endpoint.api_key
+ config.openrouter_api_base = ruby_llm_api_base if endpoint.base_url.present?
+ config.openrouter_app_name = OPENROUTER_APP_NAME # RubyLLM otherwise sends "RubyLLM"
+ config.openrouter_app_url = OPENROUTER_APP_URL
+ else
+ config.openai_api_key = endpoint.api_key.presence || "none" # RubyLLM requires one; local servers ignore it
+ config.openai_api_base = ruby_llm_api_base
+ end
+ end
+end
diff --git a/app/models/ai/transport/http.rb b/app/models/ai/transport/http.rb
new file mode 100644
index 0000000000..4035609943
--- /dev/null
+++ b/app/models/ai/transport/http.rb
@@ -0,0 +1,148 @@
+# Every AI HTTP client is built here: the endpoint's timeout and headers, TLS
+# settings, and the proxy, resolved once. A contract test checks that nothing under
+# app/models/ai/ builds a client anywhere else.
+#
+# Proxy coverage: RubyLLM's contexts, the ruby-openai clients built below (health
+# probes, Provider::Openai) and Assistant::External::Client. The anthropic gem takes no proxy
+# option (Net::HTTP reads only HTTP_PROXY, even for HTTPS), so Anthropic's own client goes
+# direct.
+module Ai::Transport::Http
+ extend SslConfigurable
+
+ OPENAI_BASE = "https://api.openai.com/v1".freeze
+ OPENROUTER_BASE = "https://openrouter.ai/api/v1".freeze
+ PROXY_VARIABLES = %w[HTTPS_PROXY https_proxy HTTP_PROXY http_proxy].freeze
+
+ class << self
+ # The proxy URL for a request to `url`, or nil to go direct: HTTPS_PROXY, then HTTP_PROXY,
+ # whatever the target's scheme, so a setup that sets only one still covers every call.
+ # Loopback is never proxied, as Ruby's own lookup does; NO_PROXY matches a host exactly as
+ # written, so `127.0.0.1` doesn't cover `localhost`, and `*` means every host, as curl reads it.
+ # A leading dot is dropped, as curl and the external assistant's old matcher do, so
+ # `.agents.example.com` covers `agents.example.com` itself as well as its subdomains.
+ def proxy_for(url, env: ENV)
+ uri = parse(url)
+ return if uri&.host.blank? || loopback?(uri.host)
+
+ proxy = PROXY_VARIABLES.lazy.filter_map { env[_1].presence }.first
+ return if proxy.nil?
+
+ no_proxy = env["NO_PROXY"].presence || env["no_proxy"].presence
+ no_proxy &&= no_proxy.split(",").map { _1.strip.delete_prefix(".") }.join(",")
+ return if no_proxy && (no_proxy.strip == "*" || !URI::Generic.use_proxy?(uri.host, address(uri.host, no_proxy), uri.port, no_proxy))
+
+ proxy
+ end
+
+ # The host's address, for NO_PROXY's IP and CIDR entries, as Ruby's own lookup resolves it
+ # (URI#find_proxy). Names are resolved only when NO_PROXY has such an entry.
+ def address(host, no_proxy)
+ return host if ip?(host.delete("[]"))
+ return host unless no_proxy.split(",").any? { ip?(_1.strip) }
+
+ IPSocket.getaddress(host)
+ rescue SocketError
+ host
+ end
+
+ def ip?(value) = IPAddr.new(value).present? rescue false
+
+ # The proxy for Net::HTTP.new, which takes host, port, user and password.
+ def net_http_proxy(url, env: ENV)
+ proxy = proxy_for(url, env:)
+ URI(proxy) if proxy
+ rescue URI::InvalidURIError
+ Rails.logger.warn("[Ai::Transport::Http] Invalid proxy URL ignored")
+ nil
+ end
+
+ # One base URL rule for every OpenAI-compatible server, the same as ruby-openai's, so an
+ # endpoint configured for ruby-openai keeps its URL: a URL that contains "v1" is used as given
+ # (`/v1`, Gemini's `/v1beta/openai`, Cloudflare's `/ai/v1`); any other gets `/v1`. Agent
+ # URLs are stored whole, so a trailing `/chat/completions` goes.
+ def compatible_base(base_url)
+ url = base_url.to_s.strip.chomp("/").delete_suffix("/chat/completions")
+ return OPENAI_BASE if url.blank?
+
+ url.include?("v1") ? url : "#{url}/v1"
+ end
+
+ # Headers sent on every request. Values holding `{session_id}` are filled per chat request
+ # by Provider::Openai, so they're left out here.
+ def headers(endpoint) = endpoint.extra_headers.reject { |_, value| value.to_s.include?("{session_id}") }
+
+ # The ruby-openai client for an endpoint: vector stores, the PDF probes and model listing
+ # stay on ruby-openai (RubyLLM has no vector store calls).
+ # Its base follows compatible_base, as RubyLLM's does, so the models list and the chat calls
+ # it checks reach the same server; an OpenRouter endpoint without a URL is OpenRouter's.
+ def openai_client(endpoint, timeout: endpoint.timeout_seconds)
+ base = endpoint.base_url.presence || (OPENROUTER_BASE if endpoint.preset == :openrouter)
+ options = { access_token: endpoint.api_key.to_s, request_timeout: timeout }
+ options[:uri_base] = compatible_base(base) if base
+ static = headers(endpoint)
+ options[:extra_headers] = static if static.any?
+
+ ::OpenAI::Client.new(**options, &faraday_options(base || OPENAI_BASE))
+ end
+
+ # The anthropic gem's client, for the Anthropic PDF probe, as PDF import uses it. It takes no
+ # proxy or TLS options, so it ignores HTTPS_PROXY and SSL_VERIFY=false, as PDF import does
+ # until it moves onto RubyLLM.
+ def anthropic_client(endpoint, timeout: endpoint.timeout_seconds)
+ options = { api_key: endpoint.api_key.to_s, max_retries: 0, timeout: }
+ options[:base_url] = endpoint.base_url if endpoint.base_url.present?
+ ::Anthropic::Client.new(**options)
+ end
+
+ # A plain Faraday connection for a request no client library makes (Anthropic's model lookup),
+ # with the resolved proxy and TLS options.
+ def faraday(url, timeout:)
+ Faraday.new(request: { timeout:, open_timeout: timeout }, &faraday_options(url))
+ end
+
+ # The Faraday adapter for RubyLLM's contexts, which take no TLS options of their own.
+ def ruby_llm_adapter = TlsNetHttp
+
+ # A Faraday block for a client built elsewhere (ruby-openai): the resolved proxy, which
+ # also stops Faraday's own ENV lookup when the resolver says direct, and TLS options.
+ def faraday_options(url)
+ proxy = proxy_for(url)
+ ssl = faraday_ssl_options
+
+ lambda do |faraday|
+ faraday.proxy = proxy
+ faraday.ssl.update(ssl) if ssl.present?
+ end
+ end
+
+ private
+ def parse(url)
+ URI(url.to_s)
+ rescue URI::InvalidURIError
+ nil
+ end
+
+ def loopback?(host)
+ host = host.delete_prefix("[").delete_suffix("]")
+ host.casecmp?("localhost") || IPAddr.new(host).loopback?
+ rescue IPAddr::InvalidAddressError
+ false
+ end
+ end
+
+ # Net::HTTP with Sure's TLS settings (SSL_VERIFY, SSL_CA_FILE) and Sure's proxy decision on
+ # every request. RubyLLM 2.1.1 builds its own Faraday connections and takes only an adapter,
+ # so this is how a self-hosted server with its own certificate is reached by RubyLLM as by every
+ # other client. RubyLLM sets a proxy only when given one; without this, a request
+ # Ai::Transport::Http.proxy_for sends direct would fall back to Faraday's own ENV lookup, which
+ # ignores the port in a NO_PROXY entry such as `10.0.0.5:8080`.
+ class TlsNetHttp < Faraday::Adapter::NetHttp
+ def build_connection(env)
+ ssl = Ai::Transport::Http.faraday_ssl_options
+ env[:ssl] = env[:ssl] ? env[:ssl].merge(ssl) : Faraday::SSLOptions.from(ssl) if ssl.present?
+ proxy = Ai::Transport::Http.proxy_for(env[:url].to_s)
+ env[:request][:proxy] = proxy && Faraday::ProxyOptions.from(proxy)
+ super
+ end
+ end
+end
diff --git a/app/models/ai/transport/instrumenter.rb b/app/models/ai/transport/instrumenter.rb
new file mode 100644
index 0000000000..73ae39fd60
--- /dev/null
+++ b/app/models/ai/transport/instrumenter.rb
@@ -0,0 +1,52 @@
+# RubyLLM's `config.instrumenter` on every context Sure builds. RubyLLM wraps each HTTP request
+# in `instrument("request.ruby_llm")`, so every request passes here: a request that would start
+# after the call's deadline isn't sent, and a failed request's mapped, scrubbed error goes on the
+# payload as `:ai_error`, which UsageSubscriber adds to that request's usage row.
+class Ai::Transport::Instrumenter
+ # map_error: turns a raised error into the Ai::Error the transport raises, scrubbed, or nil.
+ # scrub: removes the endpoint's secrets from an error that has no Ai::Error.
+ def initialize(delegate = ActiveSupport::Notifications, map_error: ->(error) { error }, scrub: ->(text) { text })
+ @delegate = delegate
+ @map_error = map_error
+ @scrub = scrub
+ end
+
+ def instrument(name, payload = {}, &block)
+ if name == "request.ruby_llm"
+ check_budget!
+ block = recording_failure(payload, block) if block
+ end
+
+ if @delegate
+ @delegate.instrument(name, payload, &block)
+ elsif block
+ block.call(payload)
+ end
+ end
+
+ private
+ def recording_failure(payload, block)
+ lambda do |event_payload|
+ block.call(event_payload)
+ rescue StandardError => error
+ payload[:ai_error] = failure_details(error)
+ raise
+ end
+ end
+
+ def failure_details(error)
+ mapped = @map_error.call(error)
+ return { error: @scrub.call(error.message), error_class: error.class.name } if mapped.nil?
+
+ { error: mapped.message, error_class: mapped.class.name, http_status_code: mapped.try(:status) }.compact
+ rescue StandardError
+ nil
+ end
+
+ def check_budget!
+ call = Ai::CallContext.current
+ return unless call&.expired?
+
+ raise Ai::Error::Timeout, "the attempt's time budget was spent before the request was sent"
+ end
+end
diff --git a/app/models/ai/transport/ruby_llm_adapter.rb b/app/models/ai/transport/ruby_llm_adapter.rb
new file mode 100644
index 0000000000..ded66206a8
--- /dev/null
+++ b/app/models/ai/transport/ruby_llm_adapter.rb
@@ -0,0 +1,162 @@
+# What the RubyLLM transports share: one RubyLLM context per endpoint, errors mapped onto
+# Ai::Error, and the probe calls. Only RubyLLM's public API is used (context, chat, generate,
+# the with_* setters, embed, Tool), so an upgrade can't break Sure through a private method.
+module Ai::Transport::RubyLlmAdapter
+ OPENROUTER_APP_NAME = "Sure".freeze
+ OPENROUTER_APP_URL = "https://sure.am".freeze
+ RUBY_LLM_PATH = Gem.loaded_specs.fetch("ruby_llm").full_gem_path.freeze
+ ARITY_ERROR = /wrong number of arguments|(?:missing|unknown) keywords?/
+ # The assistant declares its tools strict in both OpenAI protocols (Assistant::Function#strict_mode?),
+ # so the probe does too: a gateway that refuses strict tools fails the check, not the chat.
+ STRICT_TOOL_OPTIONS = {
+ chat_completions: { function: { strict: true } },
+ responses: { strict: true }
+ }.freeze
+
+ private
+ # Settings RubyLLM would otherwise choose:
+ # - request_timeout from the endpoint, or the probe's own (RubyLLM's default is 300 s per read);
+ # - max_retries 0: Sure retries itself (Ai::Transport::Base#attempt);
+ # - the proxy and TLS settings from Ai::Transport::Http, for every provider;
+ # - no upload of large files to a provider's Files API, where a statement would stay;
+ # - Sure's instrumenter, which every request passes (the attempt budget, each failed request's error).
+ def ruby_llm_context(timeout: endpoint.timeout_seconds)
+ @ruby_llm_contexts ||= {}
+ @ruby_llm_contexts[timeout] ||= RubyLLM.context do |config|
+ config.request_timeout = timeout
+ config.max_retries = 0
+ config.http_proxy = Ai::Transport::Http.proxy_for(ruby_llm_api_base)
+ config.faraday_adapter = Ai::Transport::Http.ruby_llm_adapter
+ config.auto_upload_large_files = false
+ config.instrumenter = Ai::Transport::Instrumenter.new(config.instrumenter, map_error: method(:mapped_error), scrub: scrubber)
+ configure_provider(config)
+ end
+ end
+
+ def ruby_llm_chat(model, timeout: endpoint.timeout_seconds)
+ ruby_llm_context(timeout:)
+ .chat(model: model.name, provider: ruby_llm_provider, protocol: ruby_llm_protocol, assume_model_exists: true)
+ .with_headers(Ai::Transport::Http.headers(endpoint))
+ end
+
+ def probe_chat(model, timeout: endpoint.timeout_seconds)
+ chat = ruby_llm_chat(model, timeout:).with_max_output_tokens(Ai::Transport::Base::PROBE_MAX_OUTPUT_TOKENS)
+ chat.add_message(role: :user, content: Ai::Transport::Base::PROBE_PROMPT)
+ message = mapping_errors { chat.generate }
+ check_answering_model!(model.name, message.model)
+ message.content.to_s
+ end
+
+ def probe_tools(model, timeout: endpoint.timeout_seconds)
+ chat = ruby_llm_chat(model, timeout:)
+ .with_max_output_tokens(Ai::Transport::Base::PROBE_TOOL_MAX_OUTPUT_TOKENS)
+ .with_tools(ProbeTool.new(provider_options: STRICT_TOOL_OPTIONS.fetch(ruby_llm_protocol, {})))
+ chat.add_message(role: :user, content: Ai::Transport::Base::PROBE_TOOL_PROMPT)
+ message = mapping_errors { chat.generate }
+ check_answering_model!(model.name, message.model)
+ tool_calls(message).any? { _1.name == Ai::Transport::Base::PROBE_TOOL_NAME }
+ end
+
+ # A Hash keyed by call id on 2.1.1, a collection of ToolCall on 2.2 (RubyLLM #1380).
+ def tool_calls(message)
+ calls = message.tool_calls
+ calls = calls.values if calls.is_a?(Hash)
+ Array(calls)
+ end
+
+ # Providers often quote the request, and sometimes the key, back in an error, so every
+ # mapped error's message is scrubbed here, before anything logs or instruments it.
+ def mapping_errors
+ yield
+ rescue Ai::Error::Base => error
+ raise scrubbed(error)
+ rescue ArgumentError => error
+ raise unless refused_by_ruby_llm?(error)
+
+ raise scrubbed(Ai::Error::Refused.new(error.message))
+ rescue NoMethodError, TypeError => error
+ # RubyLLM parsing a 200 that isn't the API's shape (`{}`, an HTML page); in Sure's own code it's a bug.
+ raise unless raised_in_ruby_llm?(error)
+
+ raise Ai::Error::InvalidOutput, "the response isn't the expected shape"
+ rescue StandardError => error
+ mapped = ruby_llm_error(error)
+ raise mapped ? scrubbed(mapped) : error
+ end
+
+ # RubyLLM 2.2 raises ArgumentError for an option a protocol can't carry (RubyLLM #1379, #1382):
+ # a request every model would refuse. Any other ArgumentError, such as a wrong call from Sure's
+ # own code, is a bug and stays one.
+ def refused_by_ruby_llm?(error)
+ raised_in_ruby_llm?(error) && !error.message.match?(ARITY_ERROR)
+ end
+
+ def raised_in_ruby_llm?(error) = error.backtrace_locations&.first&.path.to_s.start_with?(RUBY_LLM_PATH)
+
+ # A raised error as mapping_errors would raise it, or nil when it has no Ai::Error.
+ def mapped_error(error)
+ mapped = error.is_a?(Ai::Error::Base) ? error : ruby_llm_error(error)
+ scrubbed(mapped) if mapped
+ end
+
+ def scrubbed(error)
+ message = Ai::Instrumentation::Redactor.scrub(error.message, secrets: endpoint.secrets)
+ return error if message == error.message
+
+ error.class.new(message, status: error.status).tap { _1.set_backtrace(error.backtrace) if error.backtrace }
+ end
+
+ def ruby_llm_error(error)
+ status = error.respond_to?(:response) && error.response.respond_to?(:status) ? error.response.status : nil
+ body = error.respond_to?(:response) && error.response.respond_to?(:body) ? error.response.body : nil
+
+ klass =
+ case error
+ when RubyLLM::PaymentRequiredError then Ai::Error::NoCredit
+ when RubyLLM::UnauthorizedError, RubyLLM::ForbiddenError then Ai::Error::Unauthorized
+ when RubyLLM::RateLimitError then Ai::Error.for_status(429, error.message, body:)
+ when RubyLLM::ContextLengthExceededError then Ai::Error::ContextTooLong
+ when RubyLLM::ServerError, RubyLLM::ServiceUnavailableError, RubyLLM::OverloadedError then Ai::Error::Upstream
+ when RubyLLM::CancelledError then Ai::Error::Cancelled
+ when RubyLLM::ModelNotFoundError then Ai::Error::ModelMissing # not a RubyLLM::Error
+ end
+ klass ||= connection_error_class(error)
+ return klass.new(error.message, status:) if klass
+
+ return Ai::Error::ModelMissing.new(error.message, status:) if missing_model?(status, body)
+ return Ai::Error.from_status(status || 400, error.message, body:) if error.is_a?(RubyLLM::Error)
+
+ Ai::Error.from_exception(error)
+ end
+
+ # Anthropic answers an unknown model with a 404 `not_found_error` whose message is
+ # "model: <name>"; any other 404 (a wrong base URL, a gateway's own page) maps by its status.
+ def missing_model?(status, body)
+ body = JSON.parse(body) rescue nil if body.is_a?(String)
+ error = body.is_a?(Hash) ? body["error"] : nil
+ status == 404 && error.is_a?(Hash) && error["type"] == "not_found_error" && error["message"].to_s.start_with?("model:")
+ end
+
+ # RubyLLM 2.2 raises RubyLLM::ConnectionError (with `timeout?`) where 2.1.1 lets Faraday's
+ # errors through (RubyLLM #1407); Ai::Error.from_exception handles the 2.1.1 ones.
+ def connection_error_class(error)
+ return unless defined?(RubyLLM::ConnectionError) && error.is_a?(RubyLLM::ConnectionError)
+
+ error.respond_to?(:timeout?) && error.timeout? ? Ai::Error::Timeout : Ai::Error::Unreachable
+ end
+
+ # Declared to the model, never run: `Chat#generate` makes one request and doesn't run tools.
+ class ProbeTool < RubyLLM::Tool
+ description "Records the result of a Sure health check. Always call this tool."
+ parameters Ai::Transport::Base::PROBE_TOOL_SCHEMA
+
+ attr_reader :provider_options
+
+ def initialize(provider_options: {})
+ @provider_options = provider_options
+ end
+
+ def name = Ai::Transport::Base::PROBE_TOOL_NAME
+ def execute(status:) = raise(Ai::Error::Refused, "the health check tool is never run (#{status})")
+ end
+end
diff --git a/app/models/ai_health.rb b/app/models/ai_health.rb
index 1d440b809a..f7cec8a5c4 100644
--- a/app/models/ai_health.rb
+++ b/app/models/ai_health.rb
@@ -134,22 +134,6 @@ class AiHealth
.max
end
- def self.redact_endpoint(value)
- return if value.blank?
-
- uri = URI.parse(value.to_s)
- uri.user = nil if uri.respond_to?(:user=)
- uri.password = nil if uri.respond_to?(:password=)
- uri.query = nil if uri.respond_to?(:query=)
- uri.fragment = nil if uri.respond_to?(:fragment=)
- uri.to_s
- rescue URI::InvalidURIError
- value.to_s
- .sub(%r{\A([^:]+://)[^/@]+@}, "\\1")
- .split(/[?#]/, 2)
- .first
- end
-
private
def load_llm_status
@selected_llm_protocol = normalized_llm_provider(Setting.llm_provider)
@@ -211,8 +195,7 @@ class AiHealth
provider: @effective_llm_protocol,
endpoint: @llm_raw_endpoint,
access_token: @llm_access_token,
- model: llm_model,
- openai_compatible: @effective_llm_protocol == :openai && openai_compatible_endpoint?
+ model: llm_model
)
@function_calling_probe = probe.function_calling(
provider: @effective_llm_protocol,
@@ -390,9 +373,7 @@ class AiHealth
Provider::Openai.hosted_endpoint?(value)
end
- def redact_endpoint(value)
- self.class.redact_endpoint(value)
- end
+ def redact_endpoint(value) = Ai::Instrumentation::Redactor.url(value)
def safely(fallback)
yield
diff --git a/app/models/ai_health/probe.rb b/app/models/ai_health/probe.rb
index 182738fc01..b95785b2d4 100644
--- a/app/models/ai_health/probe.rb
+++ b/app/models/ai_health/probe.rb
@@ -8,41 +8,19 @@ class AiHealth
# by Sure. Results are cached briefly because this runs in an admin request,
# and a failed check is recorded once per cache fill in both operator-facing
# debug logs and the application log.
+ #
+ # The checks go through the AI transports (Ai::Transport#probe) and the
+ # clients Ai::Transport::Http builds, so a probe exercises the same client
+ # settings, headers, proxy and error mapping as production calls, and can't
+ # drift from them. The probe builds no client of its own.
class Probe
- CACHE_NAMESPACE = "ai_health/probes/v1"
+ CACHE_NAMESPACE = "ai_health/probes/v2"
DEFAULT_CACHE_TTL = 60.seconds
DEFAULT_TIMEOUT = 5
- EMBEDDING_TEST_INPUT = "Sure AI health check"
- CHAT_TEST_INPUT = "Reply with OK."
- FUNCTION_CALL_TEST_INPUT = "Call the sure_health_check tool with status set to ok."
- FUNCTION_CALL_TEST_TOOL = {
- name: "sure_health_check",
- description: "Records the result of a Sure health check. Always call this tool.",
- schema: {
- type: "object",
- properties: {
- status: { type: "string", description: "Always the literal string \"ok\"." }
- },
- required: [ "status" ],
- additionalProperties: false
- }
- }.freeze
- FUNCTION_CALL_MAX_RESPONSE_TOKENS = 256
# 4xx statuses that mean "not now" or "not you" rather than "not this
# request": a retry, a payment, or a fixed credential clears them, so they
# are never worth re-asking without the tools.
TRANSIENT_HTTP_STATUSES = [ 401, 402, 403, 408, 429 ].freeze
- PDF_TEST_INSTITUTION = "SUREHEALTHCHECKBANK"
- PDF_TEST_LINES = [
- "Bank Statement",
- "Institution: #{PDF_TEST_INSTITUTION}",
- "Account holder: Health Check",
- "Statement period: 2026-01-01 to 2026-01-31",
- "Opening balance: USD 100.00",
- "Closing balance: USD 125.00",
- "Transactions: 2",
- "Synthetic data only. No customer data."
- ].freeze
PDF_MAX_RESPONSE_TOKENS = 512
Result = Data.define(:status, :checked_at, :failure_code, :http_status) do
@@ -88,8 +66,10 @@ class AiHealth
@cache = cache
end
- def llm(provider:, endpoint:, access_token:, model:, openai_compatible: false)
- verification = openai_compatible ? :chat_completion : :models
+ # Whether the model is up, by the endpoint's `probe_check`
+ # (Ai::Config::Endpoint::PROBE_CHECKS).
+ def llm(provider:, endpoint:, access_token:, model:)
+ probe_endpoint = config_endpoint(provider:, base_url: endpoint, api_key: access_token)
run(
component: "llm",
@@ -97,24 +77,10 @@ class AiHealth
endpoint: endpoint,
model: model,
credential: access_token,
- verification: verification
+ verification: probe_endpoint.probe_check
) do
- model_available = case provider
- when :openai
- if openai_compatible
- openai_chat_completion_available?(access_token:, endpoint:, model:)
- else
- response = openai_client(access_token:, endpoint:).models.list
- openai_model_ids(response).include?(model)
- end
- when :anthropic
- model_info = anthropic_client(access_token:, endpoint:).models.retrieve(model)
- model_info.respond_to?(:id) && model_info.id.present?
- else
- raise Failure, :unsupported_provider
- end
-
- raise Failure, :model_not_available unless model_available
+ raise_unsupported_provider!(provider)
+ transport_for(probe_endpoint).probe(config_model(probe_endpoint, model), probe_endpoint.probe_check, timeout:)
end
end
@@ -134,18 +100,15 @@ class AiHealth
credential: access_token,
verification: use_responses_endpoint ? :responses_tool_call : :chat_tool_call
) do
- tool_called = case provider
- when :openai
- if use_responses_endpoint
- openai_responses_tool_call?(access_token:, endpoint:, model:)
- else
- openai_chat_tool_call?(access_token:, endpoint:, model:)
- end
- when :anthropic
- anthropic_tool_call?(access_token:, endpoint:, model:)
- else
- raise Failure, :unsupported_provider
- end
+ raise_unsupported_provider!(provider)
+ probe_endpoint = config_endpoint(provider:, base_url: endpoint, api_key: access_token, responses_api: use_responses_endpoint)
+ transport = transport_for(probe_endpoint)
+ probe_model = config_model(probe_endpoint, model)
+
+ tool_called = confirming_tools_refusal(
+ tools: -> { transport.probe(probe_model, :tools, timeout:) },
+ control: -> { transport.probe(probe_model, :chat, timeout:) }
+ )
raise Failure, :no_tool_call unless tool_called
end
@@ -184,7 +147,8 @@ class AiHealth
endpoint: endpoint,
credential: access_token
) do
- response = openai_client(access_token:, endpoint:).vector_stores.list(parameters: { limit: 1 })
+ client = Ai::Transport::Http.openai_client(config_endpoint(provider: :openai, base_url: endpoint, api_key: access_token), timeout:)
+ response = client.vector_stores.list(parameters: { limit: 1 })
raise Failure, :invalid_response unless response.is_a?(Hash) && response["data"].is_a?(Array)
end
end
@@ -208,13 +172,10 @@ class AiHealth
credential: access_token,
dimensions: dimensions
) do
- response = embedding_client(endpoint:, access_token:).post("embeddings") do |request|
- request.body = { model: model, input: EMBEDDING_TEST_INPUT }
- end
-
- vector = response.body.dig("data", 0, "embedding") if response.body.is_a?(Hash)
- raise Failure, :invalid_response unless vector.is_a?(Array)
- raise Failure, :dimensions_mismatch unless vector.length == dimensions
+ probe_endpoint = config_endpoint(provider: :openai_compatible, base_url: endpoint, api_key: access_token, extra_headers: {},
+ exact_base_url: true)
+ returned = transport_for(probe_endpoint).probe(config_model(probe_endpoint, model), :embedding, timeout:)
+ raise Failure, :dimensions_mismatch unless returned == dimensions
end
end
@@ -235,9 +196,9 @@ class AiHealth
case provider
when :openai
Provider::Openai::PdfProcessor.new(
- openai_client(access_token:, endpoint:),
+ Ai::Transport::Http.openai_client(config_endpoint(provider:, base_url: endpoint, api_key: access_token), timeout:),
model: model,
- pdf_content: synthetic_pdf,
+ pdf_content: SyntheticPdf.bytes,
custom_provider: openai_compatible,
max_response_tokens: PDF_MAX_RESPONSE_TOKENS,
processing_mode: processing_mode
@@ -246,16 +207,16 @@ class AiHealth
raise Failure, :unsupported_provider unless processing_mode == :vision
Provider::Anthropic::PdfProcessor.new(
- anthropic_client(access_token:, endpoint:),
+ Ai::Transport::Http.anthropic_client(config_endpoint(provider:, base_url: endpoint, api_key: access_token), timeout:),
model: model,
- pdf_content: synthetic_pdf
+ pdf_content: SyntheticPdf.bytes
).process
else
raise Failure, :unsupported_provider
end
end
- raise Failure, :invalid_response unless valid_pdf_result?(result)
+ raise Failure, :invalid_response unless SyntheticPdf.valid_result?(result)
end
end
@@ -286,94 +247,26 @@ class AiHealth
result
end
- def openai_client(access_token:, endpoint:)
- options = { access_token: access_token, request_timeout: timeout }
- options[:uri_base] = endpoint if endpoint.present?
- ::OpenAI::Client.new(**options)
- end
-
- def anthropic_client(access_token:, endpoint:)
- options = { api_key: access_token, max_retries: 0, timeout: timeout }
- options[:base_url] = endpoint if endpoint.present?
- ::Anthropic::Client.new(**options)
- end
-
- def embedding_client(endpoint:, access_token:)
- Faraday.new(url: endpoint) do |faraday|
- faraday.request :json
- faraday.response :json
- faraday.response :raise_error
- faraday.headers["Authorization"] = "Bearer #{access_token}" if access_token.present?
- faraday.options.timeout = timeout
- faraday.options.open_timeout = [ timeout, 3 ].min
- end
- end
-
- def openai_model_ids(response)
- raise Failure, :invalid_response unless response.is_a?(Hash) && response["data"].is_a?(Array)
-
- response["data"].filter_map { |item| item["id"] || item[:id] }
- end
-
- def openai_chat_completion_available?(access_token:, endpoint:, model:)
- response = openai_client(access_token:, endpoint:).chat(
- parameters: {
- model: model,
- messages: [ { role: "user", content: CHAT_TEST_INPUT } ]
- }
- )
-
- response.is_a?(Hash) && response["choices"].is_a?(Array) && response["choices"].any?
- end
-
- def openai_chat_tool_call?(access_token:, endpoint:, model:)
- client = openai_client(access_token:, endpoint:)
- parameters = {
- model: model,
- messages: [ { role: "user", content: FUNCTION_CALL_TEST_INPUT } ]
- }
-
- response = confirming_tools_refusal(
- tools: -> { client.chat(parameters: parameters.merge(tools: [ { type: "function", function: openai_test_tool } ])) },
- control: -> { client.chat(parameters: parameters) }
- )
-
- raise Failure, :invalid_response unless response.is_a?(Hash) && response["choices"].is_a?(Array)
-
- response.dig("choices", 0, "message", "tool_calls").present?
- end
-
- def openai_responses_tool_call?(access_token:, endpoint:, model:)
- client = openai_client(access_token:, endpoint:)
- parameters = {
- model: model,
- input: [ { role: "user", content: FUNCTION_CALL_TEST_INPUT } ]
- }
+ # The endpoint value the transports take, built from what AiHealth resolved.
+ # OpenAI-compatible LLM endpoints send the static OPENAI_EXTRA_HEADERS, as
+ # Provider::Openai does; the embedding endpoint sends none, as
+ # VectorStore::Embeddable doesn't.
+ def config_endpoint(provider:, base_url:, api_key:, responses_api: false, extra_headers: nil, exact_base_url: false)
+ protocol = provider.to_sym == :anthropic ? :anthropic : :compatible
+ extra_headers ||= protocol == :compatible ? Provider::Openai.extra_headers : {}
- response = confirming_tools_refusal(
- tools: -> { client.responses.create(parameters: parameters.merge(tools: [ { type: "function" }.merge(openai_test_tool) ])) },
- control: -> { client.responses.create(parameters: parameters) }
+ Ai::Config::Endpoint.new(
+ name: provider.to_s, protocol:, base_url:, api_key:, extra_headers:,
+ timeout_seconds: timeout, max_retries: 0, responses_api:, exact_base_url:
)
-
- raise Failure, :invalid_response unless response.is_a?(Hash) && response["output"].is_a?(Array)
-
- response["output"].any? { |item| item["type"] == "function_call" }
end
- def anthropic_tool_call?(access_token:, endpoint:, model:)
- client = anthropic_client(access_token:, endpoint:)
- parameters = {
- model: model,
- max_tokens: FUNCTION_CALL_MAX_RESPONSE_TOKENS,
- messages: [ { role: "user", content: FUNCTION_CALL_TEST_INPUT } ]
- }
+ def config_model(endpoint, name) = Ai::Config::Model.new(endpoint:, name:)
- message = confirming_tools_refusal(
- tools: -> { client.messages.create(**parameters, tools: [ anthropic_test_tool ]) },
- control: -> { client.messages.create(**parameters) }
- )
+ def transport_for(endpoint) = Ai::Transport.for(endpoint)
- Array(message.content).any? { |block| block_type(block) == "tool_use" }
+ def raise_unsupported_provider!(provider)
+ raise Failure, :unsupported_provider unless provider.to_sym.in?(%i[openai anthropic])
end
# A client error can mean "your tools payload" or "your request, tools or
@@ -403,72 +296,6 @@ class AiHealth
status.between?(400, 499) && !status.in?(TRANSIENT_HTTP_STATUSES)
end
- # Mirrors the tool payload `Provider::Openai` sends for assistant
- # functions, `strict` included, so an endpoint that only chokes on strict
- # schemas is caught here rather than in chat.
- def openai_test_tool
- {
- name: FUNCTION_CALL_TEST_TOOL[:name],
- description: FUNCTION_CALL_TEST_TOOL[:description],
- parameters: FUNCTION_CALL_TEST_TOOL[:schema],
- strict: true
- }
- end
-
- # Anthropic names the schema differently and rejects OpenAI's `strict`.
- def anthropic_test_tool
- {
- name: FUNCTION_CALL_TEST_TOOL[:name],
- description: FUNCTION_CALL_TEST_TOOL[:description],
- input_schema: FUNCTION_CALL_TEST_TOOL[:schema]
- }
- end
-
- def block_type(block)
- raw = if block.respond_to?(:type)
- block.type
- elsif block.is_a?(Hash)
- block[:type] || block["type"]
- end
-
- raw.to_s
- end
-
- def valid_pdf_result?(result)
- result.is_a?(Provider::LlmConcept::PdfProcessingResult) &&
- result.document_type == "bank_statement" &&
- result.extracted_data.is_a?(Hash) &&
- result.extracted_data["institution_name"] == PDF_TEST_INSTITUTION
- end
-
- def synthetic_pdf
- return @synthetic_pdf if defined?(@synthetic_pdf)
-
- text = PDF_TEST_LINES.map { |line| "(#{line}) Tj T*" }.join("\n")
- content = "BT /F1 14 Tf 24 190 Td 22 TL\n#{text}\nET\n".b
- objects = [
- "<< /Type /Catalog /Pages 2 0 R >>",
- "<< /Type /Pages /Kids [3 0 R] /Count 1 >>",
- "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 480 216] /Resources << /Font << /F1 5 0 R >> >> /Contents 4 0 R >>",
- "<< /Length #{content.bytesize} >>\nstream\n#{content}endstream",
- "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>"
- ]
-
- pdf = "%PDF-1.4\n".b
- offsets = [ 0 ]
- objects.each_with_index do |object, index|
- offsets << pdf.bytesize
- pdf << "#{index + 1} 0 obj\n#{object}\nendobj\n".b
- end
-
- xref_offset = pdf.bytesize
- pdf << "xref\n0 #{objects.size + 1}\n".b
- pdf << "0000000000 65535 f \n".b
- offsets.drop(1).each { |offset| pdf << format("%010d 00000 n \n", offset).b }
- pdf << "trailer\n<< /Size #{objects.size + 1} /Root 1 0 R >>\nstartxref\n#{xref_offset}\n%%EOF\n".b
- @synthetic_pdf = pdf.freeze
- end
-
def cache_key(component:, provider_key:, endpoint:, model:, credential:, dimensions:, verification:)
fingerprint = Digest::SHA256.hexdigest(
[ component, provider_key, endpoint, model, credential, dimensions, verification ].join("\0")
@@ -494,7 +321,16 @@ class AiHealth
code = error.failure_code if error.respond_to?(:failure_code)
return code if code
- error.is_a?(Faraday::TimeoutError) || error.is_a?(Timeout::Error) ? :timeout : :request_failed
+ # The vector store and PDF probes call client gems directly, whose errors aren't mapped yet.
+ case Ai::Error.from_exception(error) || error
+ when Ai::Error::ModelMissing then :model_not_available
+ when Ai::Error::NoCredit then :no_credit
+ when Ai::Error::Unauthorized then :unauthorized
+ when Ai::Error::Unreachable then :unreachable
+ when Ai::Error::InvalidOutput then :invalid_response
+ when Ai::Error::Timeout, Faraday::TimeoutError, Timeout::Error then :timeout
+ else :request_failed
+ end
end
def http_status(error)
@@ -508,7 +344,7 @@ class AiHealth
message = "AI health #{component.tr('_', ' ')} liveness probe failed"
metadata = {
component: component,
- endpoint: AiHealth.redact_endpoint(endpoint),
+ endpoint: Ai::Instrumentation::Redactor.url(endpoint),
model: model,
failure_code: result.failure_code,
exception_class: error.class.name,
diff --git a/app/models/ai_health/probe/synthetic_pdf.rb b/app/models/ai_health/probe/synthetic_pdf.rb
new file mode 100644
index 0000000000..a07225811d
--- /dev/null
+++ b/app/models/ai_health/probe/synthetic_pdf.rb
@@ -0,0 +1,56 @@
+# A one-page bank statement with made-up data, built by hand so the PDF probes send no customer
+# data and need no PDF library. A model that reads it should name INSTITUTION.
+module AiHealth::Probe::SyntheticPdf
+ INSTITUTION = "SUREHEALTHCHECKBANK"
+ LINES = [
+ "Bank Statement",
+ "Institution: #{INSTITUTION}",
+ "Account holder: Health Check",
+ "Statement period: 2026-01-01 to 2026-01-31",
+ "Opening balance: USD 100.00",
+ "Closing balance: USD 125.00",
+ "Transactions: 2",
+ "Synthetic data only. No customer data."
+ ].freeze
+
+ module_function
+
+ def bytes
+ @bytes ||= build.freeze
+ end
+
+ # Whether a PDF processor read this statement: a bank statement naming INSTITUTION.
+ def valid_result?(result)
+ result.is_a?(Provider::LlmConcept::PdfProcessingResult) &&
+ result.document_type == "bank_statement" &&
+ result.extracted_data.is_a?(Hash) &&
+ result.extracted_data["institution_name"] == INSTITUTION
+ end
+
+ def build
+ text = LINES.map { |line| "(#{line}) Tj T*" }.join("\n")
+ content = "BT /F1 14 Tf 24 190 Td 22 TL\n#{text}\nET\n".b
+ objects = [
+ "<< /Type /Catalog /Pages 2 0 R >>",
+ "<< /Type /Pages /Kids [3 0 R] /Count 1 >>",
+ "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 480 216] /Resources << /Font << /F1 5 0 R >> >> /Contents 4 0 R >>",
+ "<< /Length #{content.bytesize} >>\nstream\n#{content}endstream",
+ "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>"
+ ]
+
+ pdf = "%PDF-1.4\n".b
+ offsets = [ 0 ]
+ objects.each_with_index do |object, index|
+ offsets << pdf.bytesize
+ pdf << "#{index + 1} 0 obj\n#{object}\nendobj\n".b
+ end
+
+ xref_offset = pdf.bytesize
+ pdf << "xref\n0 #{objects.size + 1}\n".b
+ pdf << "0000000000 65535 f \n".b
+ offsets.drop(1).each { |offset| pdf << format("%010d 00000 n \n", offset).b }
+ pdf << "trailer\n<< /Size #{objects.size + 1} /Root 1 0 R >>\nstartxref\n#{xref_offset}\n%%EOF\n".b
+ pdf
+ end
+ private_class_method :build
+end
diff --git a/app/models/assistant/external/client.rb b/app/models/assistant/external/client.rb
index 1521f6fd1c..95868adca6 100644
--- a/app/models/assistant/external/client.rb
+++ b/app/models/assistant/external/client.rb
@@ -111,44 +111,19 @@ class Assistant::External::Client
model
end
+ # The proxy comes from Ai::Transport::Http, the one resolver every AI client uses:
+ # HTTPS_PROXY, then HTTP_PROXY, whatever the scheme; NO_PROXY with CIDR blocks; loopback
+ # never proxied. A nil proxy address stops Net::HTTP's own ENV lookup.
def build_http(uri)
- proxy_uri = resolve_proxy(uri)
-
- if proxy_uri
- http = Net::HTTP.new(uri.host, uri.port, proxy_uri.host, proxy_uri.port, proxy_uri.user, proxy_uri.password)
- else
- http = Net::HTTP.new(uri.host, uri.port)
- end
+ proxy_uri = Ai::Transport::Http.net_http_proxy(uri.to_s)
+ http = Net::HTTP.new(uri.host, uri.port, proxy_uri&.host, proxy_uri&.port, proxy_uri&.user, proxy_uri&.password)
http.use_ssl = (uri.scheme == "https")
http.open_timeout = TIMEOUT_CONNECT
http.read_timeout = TIMEOUT_READ
http
end
- def resolve_proxy(uri)
- proxy_env = (uri.scheme == "https") ? "HTTPS_PROXY" : "HTTP_PROXY"
- proxy_url = ENV[proxy_env] || ENV[proxy_env.downcase]
- return nil if proxy_url.blank?
-
- no_proxy = ENV["NO_PROXY"] || ENV["no_proxy"]
- return nil if host_bypasses_proxy?(uri.host, no_proxy)
-
- URI(proxy_url)
- rescue URI::InvalidURIError => e
- Rails.logger.warn("[External::Client] Invalid proxy URL ignored: #{e.message}")
- nil
- end
-
- def host_bypasses_proxy?(host, no_proxy)
- return false if no_proxy.blank?
- host_down = host.downcase
- no_proxy.split(",").any? do |pattern|
- pattern = pattern.strip.downcase.delete_prefix(".")
- host_down == pattern || host_down.end_with?(".#{pattern}")
- end
- end
-
def build_request(uri, messages, user)
request = Net::HTTP::Post.new(uri.request_uri)
request["Content-Type"] = "application/json"
diff --git a/app/models/llm_usage.rb b/app/models/llm_usage.rb
index c43c82135e..3354a5ef7e 100644
--- a/app/models/llm_usage.rb
+++ b/app/models/llm_usage.rb
@@ -5,6 +5,17 @@ class LlmUsage < ApplicationRecord
validates :prompt_tokens, :completion_tokens, :total_tokens, presence: true, numericality: { greater_than_or_equal_to: 0 }
validates :estimated_cost, numericality: { greater_than_or_equal_to: 0 }, allow_nil: true
+ # One row per request; a call's requests share a call_id. Rows from before
+ # call_id existed, and rows the per-provider usage recorders still write, have none: each is a
+ # call of one request.
+ CALL_KEY = "COALESCE(llm_usages.call_id, llm_usages.id)".freeze
+
+ enum :status, { succeeded: "succeeded", failed: "failed", cancelled: "cancelled" }, validate: true
+
+ # The per-provider usage recorders mark a failed request by its error in metadata, under a
+ # symbol key until the row is saved and read back.
+ before_validation -> { self.status = "failed" }, if: -> { succeeded? && metadata.is_a?(Hash) && metadata.with_indifferent_access[:error].present? }
+
scope :for_family, ->(family) { where(family: family) }
scope :for_operation, ->(operation) { where(operation: operation) }
scope :recent, -> { order(created_at: :desc) }
@@ -127,7 +138,8 @@ class LlmUsage < ApplicationRecord
"openai"
end
- # Aggregate statistics for a family
+ # Aggregate statistics for a family, counting calls rather than requests: a call RubyLLM or
+ # the transport retried is still one call.
def self.statistics_for_family(family, start_date: nil, end_date: nil)
scope = for_family(family)
scope = scope.for_date_range(start_date, end_date) if start_date && end_date
@@ -135,13 +147,15 @@ class LlmUsage < ApplicationRecord
# Exclude records with nil cost from cost calculations
scope_with_cost = scope.where.not(estimated_cost: nil)
- requests_with_cost = scope_with_cost.count
- total_cost = scope_with_cost.sum(:estimated_cost).to_f.round(2)
- avg_cost = requests_with_cost > 0 ? (total_cost / requests_with_cost).round(4) : 0.0
+ calls_with_cost = scope_with_cost.distinct.count(Arel.sql(CALL_KEY))
+ cost = scope_with_cost.sum(:estimated_cost).to_f
+ total_cost = cost.round(2)
+ avg_cost = calls_with_cost > 0 ? (cost / calls_with_cost).round(4) : 0.0 # from the unrounded total
{
+ total_calls: scope.distinct.count(Arel.sql(CALL_KEY)),
total_requests: scope.count,
- requests_with_cost: requests_with_cost,
+ calls_with_cost: calls_with_cost,
total_prompt_tokens: scope.sum(:prompt_tokens),
total_completion_tokens: scope.sum(:completion_tokens),
total_tokens: scope.sum(:total_tokens),
@@ -152,16 +166,22 @@ class LlmUsage < ApplicationRecord
}
end
+ # The most recent calls in scope, newest first, each with all its requests in order, even one
+ # outside the date range (a retry just after midnight).
+ # @return [Array<LlmUsage::Call>]
+ def self.recent_calls(limit: 100)
+ keys = group(Arel.sql(CALL_KEY)).order(Arel.sql("MAX(llm_usages.created_at) DESC")).limit(limit).pluck(Arel.sql(CALL_KEY))
+ history = unscope(where: :created_at)
+ requests = history.where(id: keys).or(history.where(call_id: keys)).order(:created_at).group_by { _1.call_id || _1.id }
+
+ keys.filter_map { requests[_1] }.map { LlmUsage::Call.new(_1) }
+ end
+
# Format cost as currency
def formatted_cost
estimated_cost.nil? ? "N/A" : "$#{estimated_cost.round(4)}"
end
- # Check if this usage record represents a failed API call
- def failed?
- metadata.present? && metadata["error"].present?
- end
-
# Get the HTTP status code from metadata
def http_status_code
metadata&.dig("http_status_code")
diff --git a/app/models/llm_usage/call.rb b/app/models/llm_usage/call.rb
new file mode 100644
index 0000000000..7f48cc00f5
--- /dev/null
+++ b/app/models/llm_usage/call.rb
@@ -0,0 +1,43 @@
+# One AI call on the usage page: its requests (retries, JSON-mode resends) summed into one row,
+# which opens to show each request.
+class LlmUsage::Call
+ attr_reader :requests
+
+ # requests: the call's LlmUsage rows, oldest first.
+ def initialize(requests)
+ @requests = requests
+ end
+
+ def id = first.call_id || first.id
+ def created_at = first.created_at
+ def operation = first.operation
+ def model = last.model
+
+ # The last request decides: a call whose retry succeeded succeeded.
+ def status = last.status
+ def failed? = last.failed?
+ def cancelled? = last.cancelled?
+
+ def multiple_requests? = requests.size > 1
+ def requests_count = requests.size
+
+ def prompt_tokens = requests.sum(&:prompt_tokens)
+ def completion_tokens = requests.sum(&:completion_tokens)
+ def total_tokens = requests.sum(&:total_tokens)
+
+ # nil when no request has a cost (self-hosted models, unknown prices).
+ def estimated_cost
+ costs = requests.filter_map(&:estimated_cost)
+ costs.sum if costs.any?
+ end
+
+ def formatted_cost = estimated_cost.nil? ? "N/A" : "$#{estimated_cost.round(4)}"
+
+ def error_message = failed_request&.error_message
+ def http_status_code = failed_request&.http_status_code
+
+ private
+ def first = requests.first
+ def last = requests.last
+ def failed_request = requests.reverse.find(&:failed?)
+end
diff --git a/app/models/provider/openai.rb b/app/models/provider/openai.rb
index 9f79d7c2f0..6d78649a82 100644
--- a/app/models/provider/openai.rb
+++ b/app/models/provider/openai.rb
@@ -113,7 +113,9 @@ class Provider::Openai < Provider
static_headers = parsed_headers.except(*@session_extra_headers.keys)
client_options[:extra_headers] = static_headers if static_headers.present?
- @client = ::OpenAI::Client.new(**client_options)
+ # The proxy and TLS settings come from Ai::Transport::Http, the one resolver every AI client
+ # uses (loopback never proxied, HTTPS_PROXY then HTTP_PROXY, NO_PROXY with CIDR blocks).
+ @client = ::OpenAI::Client.new(**client_options, &Ai::Transport::Http.faraday_options(llm_uri_base || Ai::Transport::Http::OPENAI_BASE))
@uri_base = llm_uri_base
if custom_provider? && llm_model.blank?
raise Error, "Model is required when using a custom OpenAI‑compatible provider"
diff --git a/app/views/settings/llm_usages/_requests.html.erb b/app/views/settings/llm_usages/_requests.html.erb
new file mode 100644
index 0000000000..52c5015cf3
--- /dev/null
+++ b/app/views/settings/llm_usages/_requests.html.erb
@@ -0,0 +1,23 @@
+<%# locals: (call:) %>
+<%= render DS::Disclosure.new(variant: :inline, body_class: "mt-2") do |disclosure| %>
+ <% disclosure.with_summary_content do %>
+ <span class="flex items-center gap-1 text-xs text-secondary hover:text-primary">
+ <%= t(".summary", count: call.requests_count) %>
+ <%= icon "chevron-right", size: "sm", class: "group-open:rotate-90 motion-safe:transition-transform motion-safe:duration-150" %>
+ </span>
+ <% end %>
+
+ <ol class="space-y-1 text-xs text-secondary">
+ <% call.requests.each_with_index do |request, index| %>
+ <li class="flex flex-wrap gap-x-3">
+ <span><%= t(".request", number: index + 1) %></span>
+ <span class="<%= request.failed? ? "text-destructive" : "text-primary" %>"><%= t(".status.#{request.status}") %></span>
+ <span><%= t(".tokens", prompt: number_with_delimiter(request.prompt_tokens), completion: number_with_delimiter(request.completion_tokens)) %></span>
+ <span><%= request.formatted_cost %></span>
+ <% if request.failed? && request.error_message.present? %>
+ <span class="break-words"><%= request.error_message %></span>
+ <% end %>
+ </li>
+ <% end %>
+ </ol>
+<% end %>
diff --git a/app/views/settings/llm_usages/show.html.erb b/app/views/settings/llm_usages/show.html.erb
index ea22258798..5416561785 100644
--- a/app/views/settings/llm_usages/show.html.erb
+++ b/app/views/settings/llm_usages/show.html.erb
@@ -25,9 +25,12 @@
<div class="bg-container-inset rounded-lg p-4">
<div class="flex items-center gap-2 mb-2">
<%= icon "activity", class: "w-5 h-5 text-secondary" %>
- <p class="text-xs font-medium text-secondary uppercase"><%= t(".total_requests") %></p>
+ <p class="text-xs font-medium text-secondary uppercase"><%= t(".total_calls") %></p>
</div>
- <p class="text-2xl font-semibold text-primary"><%= number_with_delimiter(@statistics[:total_requests]) %></p>
+ <p class="text-2xl font-semibold text-primary"><%= number_with_delimiter(@statistics[:total_calls]) %></p>
+ <% if @statistics[:total_requests] > @statistics[:total_calls] %>
+ <p class="text-xs text-secondary mt-1"><%= t(".requests_in_calls", count: @statistics[:total_requests]) %></p>
+ <% end %>
</div>
<div class="bg-container-inset rounded-lg p-4">
@@ -53,14 +56,14 @@
<div class="bg-container-inset rounded-lg p-4">
<div class="flex items-center gap-2 mb-2">
<%= icon "trending-up", class: "w-5 h-5 text-secondary" %>
- <p class="text-xs font-medium text-secondary uppercase"><%= t(".avg_cost_per_request") %></p>
+ <p class="text-xs font-medium text-secondary uppercase"><%= t(".avg_cost_per_call") %></p>
</div>
<p class="text-2xl font-semibold text-primary">
$<%= sprintf("%.4f", @statistics[:avg_cost]) %>
</p>
- <% if @statistics[:requests_with_cost] < @statistics[:total_requests] %>
+ <% if @statistics[:calls_with_cost] < @statistics[:total_calls] %>
<p class="text-xs text-secondary mt-1">
- <%= t(".based_on_requests", with_cost: number_with_delimiter(@statistics[:requests_with_cost]), total: number_with_delimiter(@statistics[:total_requests])) %>
+ <%= t(".based_on_calls", with_cost: number_with_delimiter(@statistics[:calls_with_cost]), total: number_with_delimiter(@statistics[:total_calls])) %>
</p>
<% end %>
</div>
@@ -102,9 +105,10 @@
<!-- Recent Usage Table -->
<div>
- <h2 class="text-lg font-semibold text-primary mb-3"><%= t(".recent_usage") %></h2>
+ <h2 class="text-lg font-semibold text-primary mb-1"><%= t(".recent_usage") %></h2>
+ <p class="text-xs text-secondary mb-3"><%= t(".recent_usage_scope") %></p>
<div class="table-scroll rounded-lg" tabindex="0" role="region" aria-label="<%= t(".recent_usage") %>">
- <% if @llm_usages.any? %>
+ <% if @llm_calls.any? %>
<table class="w-full">
<thead class="bg-surface border-b border-primary">
<tr>
@@ -116,13 +120,16 @@
</tr>
</thead>
<tbody class="divide-y divide-alpha-black-200 theme-dark:divide-alpha-white-200">
- <% @llm_usages.each do |usage| %>
+ <% @llm_calls.each do |usage| %>
<tr class="<%= "bg-red-tint-5 theme-dark:bg-red-tint-10" if usage.failed? %>">
<td class="px-4 py-3 text-sm text-primary whitespace-nowrap">
<%= usage.created_at.strftime("%b %d, %Y %I:%M %p") %>
</td>
<td class="px-4 py-3 text-sm text-primary">
<%= usage.operation.humanize %>
+ <% if usage.multiple_requests? %>
+ <%= render "settings/llm_usages/requests", call: usage %>
+ <% end %>
</td>
<td class="px-4 py-3 text-sm text-primary font-mono">
<%= usage.model %>
@@ -144,6 +151,9 @@
</div>
</div>
<% else %>
+ <% if usage.cancelled? %>
+ <span class="text-secondary font-medium"><%= t(".cancelled") %></span>
+ <% end %>
<%= number_with_delimiter(usage.total_tokens) %>
<span class="text-xs text-secondary">
(<%= number_with_delimiter(usage.prompt_tokens) %>/<%= number_with_delimiter(usage.completion_tokens) %>)
diff --git a/config/initializers/ai_instrumentation.rb b/config/initializers/ai_instrumentation.rb
new file mode 100644
index 0000000000..f87692a923
--- /dev/null
+++ b/config/initializers/ai_instrumentation.rb
@@ -0,0 +1,12 @@
+# Usage rows, the debug log and tracing for AI calls (app/models/ai/instrumentation.rb).
+#
+# The subscribers are reloadable code, so they're subscribed again on every reload and the
+# previous ones removed; the OpenTelemetry tracer provider (metadata mode) is set once.
+Rails.application.config.to_prepare do
+ Array(Rails.application.config.x.ai_subscriptions).each { ActiveSupport::Notifications.unsubscribe(_1) }
+ Rails.application.config.x.ai_subscriptions = Ai::Instrumentation.subscribe!
+end
+
+Rails.application.config.after_initialize do
+ Ai::Instrumentation.start_tracing!
+end
diff --git a/config/initializers/ruby_llm.rb b/config/initializers/ruby_llm.rb
new file mode 100644
index 0000000000..55abfbffd4
--- /dev/null
+++ b/config/initializers/ruby_llm.rb
@@ -0,0 +1,28 @@
+# RubyLLM is the HTTP layer under Sure's AI transports (app/models/ai/transport). Nothing calls
+# RubyLLM's global configuration: every request goes through a RubyLLM.context built per
+# endpoint by Ai::Transport::RubyLlmAdapter, so no key, URL, timeout or retry is set here.
+#
+# RubyLLM's railtie, loaded by Bundler, also:
+# - adds `acts_as_chat`/`acts_as_message` to ActiveRecord::Base (Sure doesn't use them);
+# - sets ActiveSupport::Notifications as the instrumenter, so `*.ruby_llm` events publish in
+# this process (Ai::Instrumentation::UsageSubscriber reads `usage.ruby_llm`);
+# - adds an after_destroy hook to Active Storage blobs, guarded by `ruby_llm_provider_files`,
+# a table Sure doesn't create;
+# - installs its usage ledger. Sure records usage in `llm_usages` and never creates
+# `ruby_llm_usages`, so the ledger writes nothing (test/models/ai/ruby_llm_setup_test.rb).
+#
+# Don't add `ruby_llm-monitoring`: it rewrites app-wide inflections, after which Zeitwerk
+# expects `LLMUsage` instead of `LlmUsage`.
+#
+# RubyLLM logs to Rails' logger, but never at debug: at debug it logs response bodies and raw
+# exceptions through Faraday, before Ai::Instrumentation::Redactor sees them, and a gateway can
+# quote a key back in an error. Its info and warn lines carry no request or response content.
+class RubyLlmLogger < SimpleDelegator
+ def debug(*) = true
+ def debug? = false
+ def level = [ __getobj__.level, Logger::INFO ].max
+end
+
+RubyLLM.configure do |config|
+ config.logger = RubyLlmLogger.new(Rails.logger)
+end
diff --git a/config/locales/views/admin/system_health/en.yml b/config/locales/views/admin/system_health/en.yml
index 3298b65426..d4e3d628df 100644
--- a/config/locales/views/admin/system_health/en.yml
+++ b/config/locales/views/admin/system_health/en.yml
@@ -402,6 +402,9 @@ en:
table_not_found: The vector_store_chunks table was not found
render_missing_binary: The pdftoppm renderer (poppler-utils) is not available in this container
timeout: The service did not respond before the probe timeout
+ no_credit: The service refused the request because the key's balance is spent
+ unauthorized: The service rejected the API key
+ unreachable: The service could not be reached
request_failed: The service request failed
unsupported_provider: The provider does not support this check
worker:
diff --git a/config/locales/views/settings/llm_usages/ca.yml b/config/locales/views/settings/llm_usages/ca.yml
index 85b9d0f25b..13198b47b3 100644
--- a/config/locales/views/settings/llm_usages/ca.yml
+++ b/config/locales/views/settings/llm_usages/ca.yml
@@ -3,9 +3,6 @@ ca:
settings:
llm_usages:
show:
- avg_cost_per_request: Cost mitjà/sol·licitud
- based_on_requests: Basat en %{with_cost} de %{total} sol·licituds amb dades
- de cost
col_cost: Cost
col_date: Data
col_model: Model
@@ -26,5 +23,4 @@ ca:
start_date: Data d'inici
subtitle: Fes el seguiment del teu ús d'IA i els costos estimats
total_cost: Cost total
- total_requests: Total de sol·licituds
total_tokens: Total de tokens
diff --git a/config/locales/views/settings/llm_usages/de.yml b/config/locales/views/settings/llm_usages/de.yml
index e4f5b86407..0bdc009226 100644
--- a/config/locales/views/settings/llm_usages/de.yml
+++ b/config/locales/views/settings/llm_usages/de.yml
@@ -3,8 +3,6 @@ de:
settings:
llm_usages:
show:
- avg_cost_per_request: Ø Kosten/Anfrage
- based_on_requests: Grundlage sind %{with_cost} von %{total} Anfragen mit Kostendaten
col_cost: Kosten
col_date: Datum
col_model: Modell
@@ -25,5 +23,4 @@ de:
start_date: Startdatum
subtitle: Behalte deine KI-Nutzung und die geschätzten Kosten im Blick
total_cost: Kosten gesamt
- total_requests: Anfragen gesamt
total_tokens: Tokens gesamt
diff --git a/config/locales/views/settings/llm_usages/en.yml b/config/locales/views/settings/llm_usages/en.yml
index 09ed3a88f2..4d2537580d 100644
--- a/config/locales/views/settings/llm_usages/en.yml
+++ b/config/locales/views/settings/llm_usages/en.yml
@@ -8,22 +8,37 @@ en:
start_date: "Start Date"
end_date: "End Date"
filter: "Filter"
- total_requests: "Total Requests"
+ total_calls: "Total Calls"
+ requests_in_calls:
+ one: "%{count} request, retries included"
+ other: "%{count} requests, retries included"
total_tokens: "Total Tokens"
prompt: "prompt"
completion: "completion"
total_cost: "Total Cost"
- avg_cost_per_request: "Avg Cost/Request"
- based_on_requests: "Based on %{with_cost} of %{total} requests with cost data"
+ avg_cost_per_call: "Avg Cost/Call"
+ based_on_calls: "Based on %{with_cost} of %{total} calls with cost data"
cost_by_operation: "Cost by Operation"
cost_by_model: "Cost by Model"
recent_usage: "Recent Usage"
+ recent_usage_scope: "Each call shows all its requests, even ones outside the selected dates, so its total can differ from the totals above, which count only requests in the range."
col_date: "Date"
col_operation: "Operation"
col_model: "Model"
col_tokens: "Tokens"
col_cost: "Cost"
failed: "Failed"
+ cancelled: "Cancelled"
no_usage_data: "No usage data found for the selected period"
cost_estimates_title: "About Cost Estimates"
cost_estimates_description: "Costs are estimated from published provider pricing last verified on %{date}. Actual costs may vary. Pricing is per 1 million tokens and varies by model. Custom or self-hosted models will show \"N/A\" and are not included in cost totals."
+ requests:
+ summary:
+ one: "%{count} request"
+ other: "%{count} requests"
+ request: "Request %{number}"
+ tokens: "%{prompt}/%{completion} tokens"
+ status:
+ succeeded: "Succeeded"
+ failed: "Failed"
+ cancelled: "Cancelled"
diff --git a/config/locales/views/settings/llm_usages/es.yml b/config/locales/views/settings/llm_usages/es.yml
index f9dedddbf2..c0deb52fd5 100644
--- a/config/locales/views/settings/llm_usages/es.yml
+++ b/config/locales/views/settings/llm_usages/es.yml
@@ -8,13 +8,10 @@ es:
start_date: Fecha de inicio
end_date: Fecha de fin
filter: Filtrar
- total_requests: Peticiones totales
total_tokens: Tokens totales
prompt: prompt
completion: respuesta
total_cost: Coste total
- avg_cost_per_request: Coste medio/petición
- based_on_requests: Basado en %{with_cost} de %{total} peticiones con datos de coste
cost_by_operation: Coste por operación
cost_by_model: Coste por modelo
recent_usage: Uso reciente
diff --git a/config/locales/views/settings/llm_usages/fr.yml b/config/locales/views/settings/llm_usages/fr.yml
index 2c5825dc79..75b5db27b1 100644
--- a/config/locales/views/settings/llm_usages/fr.yml
+++ b/config/locales/views/settings/llm_usages/fr.yml
@@ -3,8 +3,6 @@ fr:
settings:
llm_usages:
show:
- avg_cost_per_request: Coût moyen/demande
- based_on_requests: Basé sur %{with_cost} requêtes sur %{total} avec données de coût
col_cost: Coût
col_date: Date
col_model: Modèle
@@ -25,5 +23,4 @@ fr:
start_date: Date de début
subtitle: Suivez votre utilisation de l'IA et les coûts estimés
total_cost: Coût total
- total_requests: Total demandes
total_tokens: Total jetons
diff --git a/config/locales/views/settings/llm_usages/hu.yml b/config/locales/views/settings/llm_usages/hu.yml
index ec7c926f11..bcb7d5c05e 100644
--- a/config/locales/views/settings/llm_usages/hu.yml
+++ b/config/locales/views/settings/llm_usages/hu.yml
@@ -8,13 +8,10 @@ hu:
start_date: "Kezdő dátum"
end_date: "Záró dátum"
filter: "Szűrő"
- total_requests: "Összes kérés"
total_tokens: "Összes token"
prompt: "prompt"
completion: "befejezés"
total_cost: "Összes költség"
- avg_cost_per_request: "Átl. költség/kérés"
- based_on_requests: "%{total} kérésből %{with_cost} rendelkezik költségadattal"
cost_by_operation: "Költség műveletek szerint"
cost_by_model: "Költség modellek szerint"
recent_usage: "Legutóbbi használat"
diff --git a/config/locales/views/settings/llm_usages/id.yml b/config/locales/views/settings/llm_usages/id.yml
index a37c8a5a2e..28883e36b0 100644
--- a/config/locales/views/settings/llm_usages/id.yml
+++ b/config/locales/views/settings/llm_usages/id.yml
@@ -8,13 +8,10 @@ id:
start_date: "Tanggal Mulai"
end_date: "Tanggal Akhir"
filter: "Filter"
- total_requests: "Total Permintaan"
total_tokens: "Total Token"
prompt: "prompt"
completion: "penyelesaian"
total_cost: "Total Biaya"
- avg_cost_per_request: "Rata-rata Biaya/Permintaan"
- based_on_requests: "Berdasarkan %{with_cost} dari %{total} permintaan yang memiliki data biaya"
cost_by_operation: "Biaya per Operasi"
cost_by_model: "Biaya per Model"
recent_usage: "Penggunaan Terbaru"
diff --git a/config/locales/views/settings/llm_usages/it.yml b/config/locales/views/settings/llm_usages/it.yml
index e96c36dce3..4f68a9888c 100644
--- a/config/locales/views/settings/llm_usages/it.yml
+++ b/config/locales/views/settings/llm_usages/it.yml
@@ -8,13 +8,10 @@ it:
start_date: "Data inizio"
end_date: "Data fine"
filter: "Filtra"
- total_requests: "Richieste totali"
total_tokens: "Token totali"
prompt: "prompt"
completion: "completamento"
total_cost: "Costo totale"
- avg_cost_per_request: "Costo medio/richiesta"
- based_on_requests: "Basato su %{with_cost} di %{total} richieste con dati di costo"
cost_by_operation: "Costo per operazione"
cost_by_model: "Costo per modello"
recent_usage: "Utilizzo recente"
diff --git a/config/locales/views/settings/llm_usages/nl.yml b/config/locales/views/settings/llm_usages/nl.yml
index af075edbe5..5207ccae9f 100644
--- a/config/locales/views/settings/llm_usages/nl.yml
+++ b/config/locales/views/settings/llm_usages/nl.yml
@@ -8,13 +8,10 @@ nl:
start_date: "Startdatum"
end_date: "Einddatum"
filter: "Filteren"
- total_requests: "Totaal aantal verzoeken"
total_tokens: "Totaal aantal tokens"
prompt: "prompt"
completion: "voltooiing"
total_cost: "Totale kosten"
- avg_cost_per_request: "Gem. kosten/verzoek"
- based_on_requests: "Gebaseerd op %{with_cost} van %{total} verzoeken met kostengegevens"
cost_by_operation: "Kosten per bewerking"
cost_by_model: "Kosten per model"
recent_usage: "Recent gebruik"
diff --git a/config/locales/views/settings/llm_usages/pl.yml b/config/locales/views/settings/llm_usages/pl.yml
index 9c9721fb40..f11dfa3830 100644
--- a/config/locales/views/settings/llm_usages/pl.yml
+++ b/config/locales/views/settings/llm_usages/pl.yml
@@ -3,9 +3,6 @@ pl:
settings:
llm_usages:
show:
- avg_cost_per_request: Śr. koszt/zapytanie
- based_on_requests: Na podstawie %{with_cost} z %{total} zapytań z danymi o
- koszcie
col_cost: Koszt
col_date: Data
col_model: Model
@@ -29,5 +26,4 @@ pl:
start_date: Data początkowa
subtitle: Śledź swoje użycie AI i szacowane koszty
total_cost: Łączny koszt
- total_requests: Łączna liczba zapytań
total_tokens: Łączna liczba tokenów
diff --git a/config/locales/views/settings/llm_usages/pt-PT.yml b/config/locales/views/settings/llm_usages/pt-PT.yml
index f63bd8634c..ddaa48c6e5 100644
--- a/config/locales/views/settings/llm_usages/pt-PT.yml
+++ b/config/locales/views/settings/llm_usages/pt-PT.yml
@@ -8,13 +8,10 @@ pt-PT:
start_date: "Data de início"
end_date: "Data de fim"
filter: "Filtrar"
- total_requests: "Total de Pedidos"
total_tokens: "Total de Tokens"
prompt: "pré-preenchimento"
completion: "conclusão"
total_cost: "Custo Total"
- avg_cost_per_request: "Custo Médio/Pedido"
- based_on_requests: "Com base em %{with_cost} de %{total} pedidos com dados de custo"
cost_by_operation: "Custo por Operação"
cost_by_model: "Custo por Modelo"
recent_usage: "Utilização Recente"
diff --git a/config/locales/views/settings/llm_usages/ru.yml b/config/locales/views/settings/llm_usages/ru.yml
index 32a5abd8e8..ffec01c616 100644
--- a/config/locales/views/settings/llm_usages/ru.yml
+++ b/config/locales/views/settings/llm_usages/ru.yml
@@ -3,9 +3,6 @@ ru:
settings:
llm_usages:
show:
- avg_cost_per_request: Средняя стоимость/запрос
- based_on_requests: Основано на %{with_cost} из %{total} запросов с данными
- о стоимости
col_cost: Стоимость
col_date: Дата
col_model: Модель
@@ -26,5 +23,4 @@ ru:
start_date: Дата начала
subtitle: Отслеживайте использование ИИ и предполагаемые затраты
total_cost: Общая стоимость
- total_requests: Всего запросов
total_tokens: Всего токенов
diff --git a/config/locales/views/settings/llm_usages/tr.yml b/config/locales/views/settings/llm_usages/tr.yml
index fa39632d68..8cfd225314 100644
--- a/config/locales/views/settings/llm_usages/tr.yml
+++ b/config/locales/views/settings/llm_usages/tr.yml
@@ -3,9 +3,6 @@ tr:
settings:
llm_usages:
show:
- avg_cost_per_request: Ort. Maliyet/İstek
- based_on_requests: Maliyet verisi bulunan %{total} istekten %{with_cost} tanesine
- dayanmaktadır
col_cost: Maliyet
col_date: Tarih
col_model: Model
@@ -29,5 +26,4 @@ tr:
start_date: Başlangıç Tarihi
subtitle: Yapay zeka kullanımınızı ve tahmini maliyetlerinizi takip edin
total_cost: Toplam Maliyet
- total_requests: Toplam İstek
total_tokens: Toplam Token
diff --git a/config/locales/views/settings/llm_usages/uk.yml b/config/locales/views/settings/llm_usages/uk.yml
index 83698a6be2..85bff15dcd 100644
--- a/config/locales/views/settings/llm_usages/uk.yml
+++ b/config/locales/views/settings/llm_usages/uk.yml
@@ -8,13 +8,10 @@ uk:
start_date: "Дата початку"
end_date: "Дата закінчення"
filter: "Фільтрувати"
- total_requests: "Усього запитів"
total_tokens: "Усього токенів"
prompt: "промпт"
completion: "завершення"
total_cost: "Загальна вартість"
- avg_cost_per_request: "Середня вартість/запит"
- based_on_requests: "На основі %{with_cost} з %{total} запитів з даними про вартість"
cost_by_operation: "Вартість за операцією"
cost_by_model: "Вартість за моделлю"
recent_usage: "Нещодавнє використання"
diff --git a/config/locales/views/settings/llm_usages/vi.yml b/config/locales/views/settings/llm_usages/vi.yml
index cfd60d05bd..acf908cb70 100644
--- a/config/locales/views/settings/llm_usages/vi.yml
+++ b/config/locales/views/settings/llm_usages/vi.yml
@@ -8,13 +8,10 @@ vi:
start_date: "Ngày bắt đầu"
end_date: "Ngày kết thúc"
filter: "Lọc"
- total_requests: "Tổng yêu cầu"
total_tokens: "Tổng token"
prompt: "lệnh"
completion: "hoàn thành"
total_cost: "Tổng chi phí"
- avg_cost_per_request: "Chi phí tb/yêu cầu"
- based_on_requests: "Dựa trên %{with_cost} trong %{total} yêu cầu có dữ liệu chi phí"
cost_by_operation: "Chi phí theo thao tác"
cost_by_model: "Chi phí theo mô hình"
recent_usage: "Sử dụng gần đây"
diff --git a/config/locales/views/settings/llm_usages/zh-CN.yml b/config/locales/views/settings/llm_usages/zh-CN.yml
index ca5e27bb46..833d56ccd1 100644
--- a/config/locales/views/settings/llm_usages/zh-CN.yml
+++ b/config/locales/views/settings/llm_usages/zh-CN.yml
@@ -8,13 +8,10 @@ zh-CN:
start_date: 开始日期
end_date: 结束日期
filter: 筛选
- total_requests: 请求总数
total_tokens: Token 总数
prompt: 提示词
completion: 补全
total_cost: 总费用
- avg_cost_per_request: 平均每次请求费用
- based_on_requests: 基于 %{with_cost} / %{total} 个带费用数据的请求
cost_by_operation: 按操作统计费用
cost_by_model: 按模型统计费用
recent_usage: 最近用量
diff --git a/config/locales/views/settings/llm_usages/zh-TW.yml b/config/locales/views/settings/llm_usages/zh-TW.yml
index 2524c14c73..5a1e065180 100644
--- a/config/locales/views/settings/llm_usages/zh-TW.yml
+++ b/config/locales/views/settings/llm_usages/zh-TW.yml
@@ -8,13 +8,10 @@ zh-TW:
start_date: 開始日期
end_date: 結束日期
filter: 篩選
- total_requests: 總請求數
total_tokens: Token 總數
prompt: 提示 Token
completion: 輸出 Token
total_cost: 總費用
- avg_cost_per_request: 平均每次請求費用
- based_on_requests: 根據 %{total} 次請求中有費用資料的 %{with_cost} 次計算
cost_by_operation: 各作業費用
cost_by_model: 各模型費用
recent_usage: 近期使用量
diff --git a/db/migrate/20261106120000_add_call_id_and_status_to_llm_usages.rb b/db/migrate/20261106120000_add_call_id_and_status_to_llm_usages.rb
new file mode 100644
index 0000000000..9ff2699f18
--- /dev/null
+++ b/db/migrate/20261106120000_add_call_id_and_status_to_llm_usages.rb
@@ -0,0 +1,35 @@
+# One llm_usages row per request, grouped per call. Rows written before this, and rows the
+# per-provider usage recorders write, have no call_id: each counts as a call of one request.
+class AddCallIdAndStatusToLlmUsages < ActiveRecord::Migration[8.1]
+ STATUSES = %w[succeeded failed cancelled].freeze
+
+ def up
+ add_column :llm_usages, :call_id, :uuid
+ add_column :llm_usages, :status, :string, null: false, default: "succeeded"
+ add_index :llm_usages, :call_id
+ add_check_constraint :llm_usages, "status IN (#{STATUSES.map { "'#{_1}'" }.join(", ")})", name: "chk_llm_usages_status"
+
+ # The per-provider recorders mark a failed request by putting its error in metadata. An error
+ # that's blank by LlmUsage's `present?` check (missing, null, false, only whitespace, an
+ # empty object or array) was never shown as a failure and isn't one now. Rails counts Unicode
+ # spaces as blank whatever the locale, so they're listed rather than left to the database's.
+ execute <<~'SQL'
+ UPDATE llm_usages SET status = 'failed'
+ WHERE CASE jsonb_typeof(metadata->'error')
+ WHEN 'string' THEN metadata->>'error' ~ '[^[:space:]\u0085\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000]'
+ WHEN 'object' THEN metadata->'error' <> '{}'::jsonb
+ WHEN 'array' THEN metadata->'error' <> '[]'::jsonb
+ WHEN 'boolean' THEN (metadata->'error')::boolean
+ WHEN 'number' THEN true
+ ELSE false
+ END
+ SQL
+ end
+
+ def down
+ remove_check_constraint :llm_usages, name: "chk_llm_usages_status"
+ remove_index :llm_usages, :call_id
+ remove_column :llm_usages, :status
+ remove_column :llm_usages, :call_id
+ end
+end
diff --git a/db/schema.rb b/db/schema.rb
index 88076b347f..3418d65708 100644
--- a/db/schema.rb
+++ b/db/schema.rb
@@ -1598,6 +1598,7 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_14_233000) do
create_table "llm_usages", id: :uuid, default: -> { "gen_random_uuid()" }, force: :cascade do |t|
t.integer "cache_creation_tokens"
t.integer "cache_read_tokens"
+ t.uuid "call_id"
t.integer "completion_tokens", default: 0, null: false
t.datetime "created_at", null: false
t.decimal "estimated_cost", precision: 10, scale: 6
@@ -1607,13 +1608,16 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_14_233000) do
t.string "operation", null: false
t.integer "prompt_tokens", default: 0, null: false
t.string "provider", null: false
+ t.string "status", default: "succeeded", null: false
t.integer "total_tokens", default: 0, null: false
t.datetime "updated_at", null: false
+ t.index ["call_id"], name: "index_llm_usages_on_call_id"
t.index ["family_id", "created_at"], name: "index_llm_usages_on_family_id_and_created_at"
t.index ["family_id", "operation"], name: "index_llm_usages_on_family_id_and_operation"
t.index ["family_id"], name: "index_llm_usages_on_family_id"
t.check_constraint "cache_creation_tokens IS NULL OR cache_creation_tokens >= 0", name: "chk_llm_usages_cache_creation_tokens_non_negative"
t.check_constraint "cache_read_tokens IS NULL OR cache_read_tokens >= 0", name: "chk_llm_usages_cache_read_tokens_non_negative"
+ t.check_constraint "status::text = ANY (ARRAY['succeeded'::character varying, 'failed'::character varying, 'cancelled'::character varying]::text[])", name: "chk_llm_usages_status"
end
create_table "loans", id: :uuid, default: -> { "gen_random_uuid()" }, force: :cascade do |t|
diff --git a/docs/hosting/ai.md b/docs/hosting/ai.md
index 1c3cdadf49..14b1a8e302 100644
--- a/docs/hosting/ai.md
+++ b/docs/hosting/ai.md
@@ -1125,6 +1125,48 @@ All LLM operations will now be logged to Langfuse, including:
**For maximum privacy:** Self-host Langfuse on your own infrastructure.
+### Tracing modes: content or metadata
+
+AI calls made through Sure's AI transports are traced in one of two modes, never both. Health
+probes aren't traced in either: they carry no family data and run each time an admin opens the
+health page. The mode follows the variables you already set:
+
+| You set | Mode | What leaves the server |
+|---|---|---|
+| `LANGFUSE_PUBLIC_KEY` and `LANGFUSE_SECRET_KEY` | `content` | Prompts, outputs, token usage, the model and endpoint, and Sure's error class |
+| Only `OTLP_ENDPOINT` (and `OTLP_HEADERS` for authentication) | `metadata` | Model, settings, finish reason, token counts and latency, as OpenTelemetry spans to any OTLP backend (Langfuse, Tempo, Jaeger, OpenObserve). No prompts, tool results or answers |
+| Both | `content`, with a warning in the log | As `content` |
+| Neither | off | Nothing |
+
+```bash
+# metadata mode: cost and latency without sending financial data to a tracing backend
+OTLP_ENDPOINT=https://otel.example.com/v1/traces
+OTLP_HEADERS=Authorization=Basic%20${OTLP_BASIC_AUTH}
+```
+
+`OTLP_HEADERS` uses the OpenTelemetry form, `key=value` pairs separated by commas, with values
+URL-encoded. In `metadata` mode traces lose the endpoint name, Sure's error class and errors
+raised before a request is sent.
+
+### Usage: one row per request, shown per call
+
+The LLM usage page shows one row per AI call. A call that took several requests (a retried
+`429` or `503`, for example) opens to show each request with its status, tokens, cost and error,
+and the totals count calls. If you query the `llm_usages` table yourself, group by
+`COALESCE(call_id, id)` to count calls: older rows, and rows from features that don't use the
+transports, have no `call_id` and are calls of one request.
+
+### Outbound proxy
+
+Sure resolves the proxy once for its AI clients: `HTTPS_PROXY`, then `HTTP_PROXY`, whatever the
+scheme of the server it calls, honouring `NO_PROXY` (CIDR blocks such as `10.0.0.0/8` included).
+Loopback addresses (`127.0.0.0/8`, `::1`, `localhost`) never go through the proxy. `NO_PROXY`
+matches a host exactly as written: `127.0.0.1` doesn't cover `localhost`.
+
+This covers the OpenAI and OpenAI-compatible clients, the external assistant, and the AI health
+probes. Anthropic's client library takes no proxy setting, so native Anthropic calls that don't
+use the transports go direct, unless `HTTP_PROXY` is set (the only variable that library reads).
+
## Testing and Evaluation
### Manual Testing
@@ -1775,7 +1817,10 @@ endpoint**.
Results are cached for 60 seconds by default. **Run checks again** bypasses the
cache. Set `AI_HEALTH_PROBE_TIMEOUT` to change the default five-second request
-timeout and `AI_HEALTH_PROBE_CACHE_TTL` to change the cache duration. Failed
+timeout and `AI_HEALTH_PROBE_CACHE_TTL` to change the cache duration. Five
+seconds is too short for a model running on CPU, such as llama.cpp without a GPU:
+the function-calling check can take 20 seconds there and shows as a timeout, so
+set `AI_HEALTH_PROBE_TIMEOUT=60` or more. Failed
checks are written as system-wide entries in **Settings → Debug logs** and to
`Rails.logger`; endpoints are redacted and credentials are never included.
diff --git a/docs/llm-guides/README.md b/docs/llm-guides/README.md
index 16d33f63f2..d663e35473 100644
--- a/docs/llm-guides/README.md
+++ b/docs/llm-guides/README.md
@@ -14,6 +14,7 @@ being changed. These guides hold the detailed conventions and procedures.
| Change provider imports, pending/FX metadata or diagnostics | [Provider sync guidance](providers.md) |
| Add a securities price provider | [Provider walkthrough](adding-a-securities-provider.md) |
| Add a typed classification provider (Jev/TypeSafe) | [Classification provider walkthrough](adding-a-classification-provider.md) |
+| Change AI transports, AI HTTP clients, AI usage or tracing | [AI pipeline](ai-pipeline.md) |
| Add a preview survey or usage event | [Feedback surveys](feedback-surveys.md) |
| Gate or release a preview feature | [Preview-feature gating](gating-a-preview-feature.md) |
| Change goals, pledges or reconciliation | [Goals](goals.md) |
diff --git a/docs/llm-guides/ai-pipeline.md b/docs/llm-guides/ai-pipeline.md
new file mode 100644
index 0000000000..805a21755c
--- /dev/null
+++ b/docs/llm-guides/ai-pipeline.md
@@ -0,0 +1,63 @@
+# 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
+
+```mermaid
+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, `Setting` or ActiveRecord.** It takes an `Ai::Config::Endpoint`
+ and an `Ai::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 use `Http.ruby_llm_adapter`, a Net::HTTP adapter that adds them. The
+ contract test fails on `OpenAI::Client.new`, `Anthropic::Client.new` or `Faraday.new`
+ anywhere else under `app/models/ai/`.
+- **Use RubyLLM's public API only**: `RubyLLM.context`, `Context#chat`/`#embed`,
+ `Chat#generate`, the `with_*` setters, `RubyLLM::Tool`, `RubyLLM.workflow`,
+ `RubyLLM.with_usage_owner`, `RubyLLM::OpenTelemetry.enable`. Nothing marked `:nodoc:`.
+ `test/architecture/ai_transport_contract_test.rb` lists the surface Sure uses.
+- **RubyLLM never retries.** Every context has `max_retries = 0`; `Ai::Transport::Base#attempt`
+ retries rate limits, 5xx and timeouts up to the endpoint's `max_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's `usage.ruby_llm` event then carries
+ the family (the usage owner) and the call (the workflow), and `UsageSubscriber` writes one
+ `llm_usages` row per request. A failed request's row takes its own error from the
+ `request.ruby_llm` event (`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_context` and
+ `capture_ai_events`.
+- A new transport, or a new transport call, passes `ai_transport_contract_test.rb`: every HTTP
+ status maps onto `Ai::Error`, retries follow the endpoint, usage counts cached tokens, and the
+ proxy is resolved by `Http`.
diff --git a/test/architecture/ai_transport_contract_test.rb b/test/architecture/ai_transport_contract_test.rb
new file mode 100644
index 0000000000..2fa6701d81
--- /dev/null
+++ b/test/architecture/ai_transport_contract_test.rb
@@ -0,0 +1,278 @@
+require "test_helper"
+
+# One contract every transport passes: error mapping, retries, usage normalisation, the
+# proxy, and that clients are built only by Ai::Transport::Http.
+class AiTransportContractTest < ActiveSupport::TestCase
+ JSON_HEADERS = { "Content-Type" => "application/json" }.freeze
+
+ TRANSPORTS = {
+ compatible: {
+ endpoint: { protocol: :compatible, base_url: "https://llm.example.test/v1" },
+ url: "https://llm.example.test/v1/chat/completions",
+ ok: { id: "c1", model: "test-model", choices: [ { index: 0, message: { role: "assistant", content: "OK" }, finish_reason: "stop" } ],
+ usage: { prompt_tokens: 12_457, completion_tokens: 2, total_tokens: 12_459, prompt_tokens_details: { cached_tokens: 11_945 } } },
+ error: ->(message, code = nil) { { error: { message:, type: "invalid_request_error", code: }.compact } }
+ },
+ anthropic: {
+ endpoint: { protocol: :anthropic, base_url: "https://anthropic.example.test" },
+ url: "https://anthropic.example.test/v1/messages",
+ ok: { id: "m1", type: "message", role: "assistant", model: "test-model", content: [ { type: "text", text: "OK" } ],
+ stop_reason: "end_turn", usage: { input_tokens: 512, output_tokens: 2, cache_read_input_tokens: 11_945 } },
+ error: ->(message, code = nil) { { type: "error", error: { type: code || "invalid_request_error", message: } } }
+ }
+ }.freeze
+
+ ERRORS = [
+ [ 401, "Invalid API Key", nil, Ai::Error::Unauthorized ],
+ [ 402, "Insufficient credits", nil, Ai::Error::NoCredit ],
+ [ 403, "Forbidden", nil, Ai::Error::Unauthorized ],
+ [ 404, "model 'test-model' not found", nil, Ai::Error::ModelMissing ],
+ [ 408, "Request timeout", nil, Ai::Error::Timeout ],
+ [ 429, "Rate limit reached", nil, Ai::Error::RateLimited ],
+ [ 429, "You exceeded your current quota", "insufficient_quota", Ai::Error::NoCredit ],
+ [ 400, "Your credit balance is too low to access the Anthropic API.", nil, Ai::Error::NoCredit ],
+ [ 400, "request (287168 tokens) exceeds the available context size (65536 tokens)", nil, Ai::Error::ContextTooLong ],
+ [ 400, "This model's maximum context length is 8192 tokens", nil, Ai::Error::ContextTooLong ],
+ [ 400, "prompt is too long: 210000 tokens > 200000 maximum", nil, Ai::Error::ContextTooLong ],
+ [ 400, "Input is too long for requested model.", nil, Ai::Error::ContextTooLong ],
+ [ 400, "Unsupported value: 'temperature'", nil, Ai::Error::Refused ],
+ [ 500, "Internal error", nil, Ai::Error::Upstream ],
+ [ 503, "Service unavailable", nil, Ai::Error::Upstream ],
+ [ 529, "Overloaded", nil, Ai::Error::Upstream ]
+ ].freeze
+
+ TRANSPORTS.each do |protocol, spec|
+ ERRORS.each do |status, message, code, expected|
+ test "#{protocol}: HTTP #{status} #{code || message.truncate(30)} maps to #{expected.name.demodulize}" do
+ stub_request(:post, spec[:url]).to_return(status:, headers: JSON_HEADERS, body: spec[:error].call(message, code).to_json)
+
+ error = assert_raises(expected) { probe(protocol, :chat) }
+ assert_equal status, error.status
+ end
+ end
+
+ # No response came back for the first two, so they're Unreachable (a connect timeout
+ # marks the server down); a server that accepted the request and went quiet is Timeout.
+ test "#{protocol}: a refused connection or connect timeout is Unreachable; a read timeout is Timeout" do
+ stub_request(:post, spec[:url]).to_raise(Errno::ECONNREFUSED)
+ assert_raises(Ai::Error::Unreachable) { probe(protocol, :chat) }
+
+ stub_request(:post, spec[:url]).to_timeout
+ assert_raises(Ai::Error::Unreachable) { probe(protocol, :chat) }
+
+ stub_request(:post, spec[:url]).to_raise(Net::ReadTimeout)
+ assert_raises(Ai::Error::Timeout) { probe(protocol, :chat) }
+ end
+
+ test "#{protocol}: retries follow the endpoint, not RubyLLM's defaults" do
+ Ai::Transport::Base.any_instance.stubs(:retry_delay).returns(0)
+ stub_request(:post, spec[:url]).to_return(status: 503, headers: JSON_HEADERS, body: spec[:error].call("unavailable").to_json)
+
+ assert_raises(Ai::Error::Upstream) { probe(protocol, :chat) }
+ assert_requested :post, spec[:url], times: 1
+
+ WebMock.reset_executed_requests!
+ assert_raises(Ai::Error::Upstream) { probe(protocol, :chat, max_retries: 2) }
+ assert_requested :post, spec[:url], times: 3
+ end
+
+ test "#{protocol}: a spent balance is never retried" do
+ Ai::Transport::Base.any_instance.stubs(:retry_delay).returns(0)
+ stub_request(:post, spec[:url]).to_return(status: 429, headers: JSON_HEADERS,
+ body: spec[:error].call("You exceeded your current quota", "insufficient_quota").to_json)
+
+ assert_raises(Ai::Error::NoCredit) { probe(protocol, :chat, max_retries: 3) }
+ assert_requested :post, spec[:url], times: 1
+ end
+
+ test "#{protocol}: usage comes through RubyLLM's usage event, cached tokens included in the prompt" do
+ stub_request(:post, spec[:url]).to_return(status: 200, headers: JSON_HEADERS, body: spec[:ok].to_json)
+
+ usage = capture_ai_events("usage.ruby_llm") { assert_equal "OK", probe(protocol, :chat) }.sole.payload
+ tokens = Ai::Tokens.from_ruby_llm(usage[:tokens], usage[:cost])
+
+ assert_equal :succeeded, usage[:status]
+ assert_equal 12_457, tokens.prompt_tokens
+ assert_equal 11_945, tokens.cache_read_tokens
+ assert_equal 2, tokens.output_tokens
+ end
+
+ test "#{protocol}: a probe answered by another model is ModelMissing" do
+ stub_request(:post, spec[:url]).to_return(status: 200, headers: JSON_HEADERS, body: spec[:ok].merge(model: "loaded-model").to_json)
+
+ assert_raises(Ai::Error::ModelMissing) { probe(protocol, :chat) }
+ end
+
+ test "#{protocol}: a dated snapshot of the model passes the probe; a sibling model doesn't" do
+ { "test-model-2025-04-14" => true, "vendor/test-model-20250929" => true, "test-model-mini" => false, "test-model2" => false,
+ "test-model-o" => false }.each do |answered, same|
+ stub_request(:post, spec[:url]).to_return(status: 200, headers: JSON_HEADERS, body: spec[:ok].merge(model: answered).to_json)
+
+ if same
+ assert_equal "OK", probe(protocol, :chat), answered
+ else
+ assert_raises(Ai::Error::ModelMissing, answered) { probe(protocol, :chat) }
+ end
+ end
+ end
+
+ test "#{protocol}: a tool probe answered by another model is ModelMissing" do
+ stub_request(:post, spec[:url]).to_return(status: 200, headers: JSON_HEADERS, body: spec[:ok].merge(model: "loaded-model").to_json)
+
+ assert_raises(Ai::Error::ModelMissing) { probe(protocol, :tools) }
+ end
+
+ test "#{protocol}: a probe's own timeout applies to its RubyLLM requests" do
+ transport = Ai::Transport.for(endpoint(protocol, timeout_seconds: 60))
+
+ assert_equal 1, transport.send(:ruby_llm_context, timeout: 1).config.request_timeout
+ assert_equal 60, transport.send(:ruby_llm_context).config.request_timeout
+ end
+
+ test "#{protocol}: RubyLLM's requests get Sure's TLS settings" do
+ Ai::Transport::Http.stubs(:faraday_ssl_options).returns(verify: false)
+ adapter = Ai::Transport.for(endpoint(protocol)).send(:ruby_llm_context).config.faraday_adapter
+ env = Faraday::Env.from(url: URI("https://self-hosted.example.test/v1"), request: Faraday::RequestOptions.new, ssl: Faraday::SSLOptions.new)
+
+ http = adapter.new.build_connection(env)
+
+ assert_equal OpenSSL::SSL::VERIFY_NONE, http.verify_mode
+ end
+
+ test "#{protocol}: one probe.ai event per call, with the route and the error class but never the key" do
+ stub_request(:post, spec[:url]).to_return(status: 401, headers: JSON_HEADERS, body: spec[:error].call("Invalid key test-secret-value-1").to_json)
+
+ event = capture_ai_events { assert_raises(Ai::Error::Unauthorized) { probe(protocol, :chat) } }.sole
+
+ assert_equal "probe.ai", event.name
+ assert_equal({ endpoint: "contract", model: "test-model" }, event.payload[:route])
+ assert_equal "Ai::Error::Unauthorized", event.payload[:error]
+ assert_not_includes event.payload.to_s, "test-secret-value-1"
+ end
+
+ test "#{protocol}: requests go through the resolved proxy" do
+ stub_request(:post, spec[:url]).to_return(status: 200, headers: JSON_HEADERS, body: spec[:ok].to_json)
+
+ with_env_overrides("HTTPS_PROXY" => "http://proxy.internal:8888", "HTTP_PROXY" => nil, "NO_PROXY" => nil, "no_proxy" => nil) do
+ transport = Ai::Transport.for(endpoint(protocol))
+ assert_equal "http://proxy.internal:8888", transport.send(:ruby_llm_context).config.http_proxy
+ # The proxy RubyLLM's own Faraday connection uses (Provider#connection is :nodoc:, read here only).
+ chat = transport.send(:ruby_llm_chat, ai_model(endpoint: endpoint(protocol)))
+ assert_equal "http://proxy.internal:8888", chat.instance_variable_get(:@provider).connection.connection.proxy.uri.to_s
+
+ host = URI(spec[:url]).host
+ with_env_overrides("NO_PROXY" => host) do
+ assert_nil Ai::Transport.for(endpoint(protocol)).send(:ruby_llm_context).config.http_proxy, "NO_PROXY goes direct"
+ end
+ end
+ end
+ end
+
+ # Faraday's own ENV lookup drops the port before matching NO_PROXY, so it would proxy a
+ # request Sure's resolver sends direct. RubyLLM's adapter applies Sure's decision instead.
+ test "RubyLLM's adapter connects as Sure's proxy resolver decides, port-qualified NO_PROXY included" do
+ with_env_overrides("HTTP_PROXY" => "http://proxy.internal:8888", "HTTPS_PROXY" => nil, "NO_PROXY" => "10.0.0.5:8080") do
+ adapter = Ai::Transport::Http::TlsNetHttp.new(->(_env) { })
+ connect = ->(url) { adapter.send(:build_connection, Faraday::Env.from(url: URI(url), request: Faraday::RequestOptions.new)) }
+
+ assert_not connect.("http://10.0.0.5:8080/v1/chat/completions").proxy?, "NO_PROXY's host:port goes direct"
+ proxied = connect.("http://10.0.0.6:8080/v1/chat/completions")
+ assert_equal [ "proxy.internal", 8888 ], [ proxied.proxy_address, proxied.proxy_port ]
+ assert_not connect.("http://127.0.0.1:8080/v1/chat/completions").proxy?, "loopback goes direct"
+ end
+ end
+
+ test "an OpenRouter endpoint without a URL resolves its proxy against OpenRouter" do
+ model_endpoint = ai_endpoint(name: "router", preset: :openrouter, base_url: nil, api_key: "k")
+ with_env_overrides("HTTPS_PROXY" => "http://proxy.internal:8888", "HTTP_PROXY" => nil, "NO_PROXY" => "openrouter.ai") do
+ transport = Ai::Transport.for(model_endpoint)
+
+ assert_equal "https://openrouter.ai/api/v1", transport.send(:ruby_llm_api_base)
+ assert_nil transport.send(:ruby_llm_context).config.http_proxy
+ end
+ end
+
+ test "two qualified ids are the same model only within one namespace" do
+ transport = Ai::Transport.for(ai_endpoint(name: "gw", base_url: "https://llm.example.test/v1"))
+
+ assert transport.send(:same_model?, "org-a/model-x", "org-a/model-x-2025-04-14")
+ assert_not transport.send(:same_model?, "org-a/model-x", "org-b/model-x")
+ assert transport.send(:same_model?, "model-x", "org-b/model-x")
+ end
+
+ test "two different names of the same length are different models" do
+ transport = Ai::Transport.for(ai_endpoint(name: "gw", base_url: "https://llm.example.test/v1"))
+
+ assert_not transport.send(:same_model?, "gpt-4o", "gpt-41")
+ assert_not transport.send(:same_model?, "test-model", "loaded-mod")
+ end
+
+ test "anthropic: a chat probe for a model the API doesn't have is ModelMissing" do
+ stub_request(:post, TRANSPORTS[:anthropic][:url]).to_return(
+ status: 404, headers: JSON_HEADERS, body: TRANSPORTS[:anthropic][:error].("model: test-model", "not_found_error").to_json
+ )
+
+ assert_raises(Ai::Error::ModelMissing) { probe(:anthropic, :chat) }
+ assert_raises(Ai::Error::ModelMissing) { probe(:anthropic, :tools) }
+ end
+
+ test "a chat answer that isn't the API's shape, such as an HTML page with a 200, is InvalidOutput" do
+ stub_request(:post, TRANSPORTS[:compatible][:url]).to_return(status: 200, headers: { "Content-Type" => "text/html" }, body: "<html>login</html>")
+
+ assert_raises(Ai::Error::InvalidOutput) { probe(:compatible, :chat) }
+ end
+
+ test "an embedding endpoint with static headers is refused, since RubyLLM 2.1.1 can't send them" do
+ model_endpoint = ai_endpoint(name: "embed", base_url: "https://llm.example.test/v1", extra_headers: { "X-Gateway-Key" => "k" })
+
+ assert_raises(Ai::Error::Refused) { Ai::Transport.for(model_endpoint).probe(ai_model(endpoint: model_endpoint), :embedding) }
+ assert_not_requested :post, "https://llm.example.test/v1/embeddings"
+ end
+
+ test "an embedding response that isn't the expected shape is InvalidOutput" do
+ model_endpoint = ai_endpoint(name: "embed", base_url: "https://llm.example.test/v1")
+ stub_request(:post, "https://llm.example.test/v1/embeddings").to_return(status: 200, headers: JSON_HEADERS, body: "{}")
+
+ assert_raises(Ai::Error::InvalidOutput) { Ai::Transport.for(model_endpoint).probe(ai_model(endpoint: model_endpoint), :embedding) }
+ end
+
+ test "a models list with an entry that isn't an object is InvalidOutput" do
+ Ai::Transport::Http.stubs(:openai_client).returns(stub(models: stub(list: { "data" => [ nil ] })))
+ model_endpoint = ai_endpoint(name: "listing", base_url: "https://llm.example.test/v1")
+
+ assert_raises(Ai::Error::InvalidOutput) { Ai::Transport.for(model_endpoint).probe(ai_model(endpoint: model_endpoint), :models) }
+ end
+
+ test "only Ai::Transport::Http builds HTTP clients under app/models/ai" do
+ offenders = Dir[Rails.root.join("app/models/ai/**/*.rb")].reject { _1.end_with?("ai/transport/http.rb") }.select do |path|
+ File.read(path).match?(/(OpenAI::Client|Anthropic::Client|Faraday)\.new\b/)
+ end
+
+ assert_empty offenders.map { Pathname(_1).relative_path_from(Rails.root).to_s },
+ "Build clients in app/models/ai/transport/http.rb, so every client gets the timeout, headers, TLS settings and proxy"
+ end
+
+ # RubyLLM hides internal helpers from its documented API between releases (RubyLLM #1438). These are
+ # the public methods Sure relies on; an upgrade that drops one fails here, not in production.
+ test "the RubyLLM surface Sure uses is still public" do
+ { RubyLLM => %i[context workflow with_usage_owner], RubyLLM::OpenTelemetry => %i[enable] }.each do |owner, methods|
+ methods.each { assert owner.respond_to?(_1), "RubyLLM.#{_1}" }
+ end
+ { RubyLLM::Context => %i[chat embed], RubyLLM::Chat => %i[generate add_message with_headers with_max_output_tokens with_tools],
+ RubyLLM::Message => %i[content model tokens cost tool_calls], RubyLLM::Embedding => %i[vectors],
+ RubyLLM::Tokens => %i[input output cache_read cache_write reported_cost] }.each do |klass, methods|
+ methods.each { assert klass.public_method_defined?(_1), "#{klass}##{_1}" }
+ end
+ assert_kind_of RubyLLM::Error, RubyLLM::PaymentRequiredError.new
+ end
+
+ private
+ def endpoint(protocol, **attributes)
+ ai_endpoint(name: "contract", api_key: "test-secret-value-1", **TRANSPORTS.fetch(protocol)[:endpoint], **attributes)
+ end
+
+ def probe(protocol, check, **endpoint_attributes)
+ model_endpoint = endpoint(protocol, **endpoint_attributes)
+ Ai::Transport.for(model_endpoint).probe(ai_model(endpoint: model_endpoint), check)
+ end
+end
diff --git a/test/controllers/settings/llm_usages_controller_test.rb b/test/controllers/settings/llm_usages_controller_test.rb
index c0a465a4df..180227ce7f 100644
--- a/test/controllers/settings/llm_usages_controller_test.rb
+++ b/test/controllers/settings/llm_usages_controller_test.rb
@@ -8,6 +8,34 @@ class Settings::LlmUsagesControllerTest < ActionDispatch::IntegrationTest
assert_includes response.body, I18n.l(LlmUsage::PRICING_VERIFIED_ON)
end
+ test "usage shows one row per call, which opens to show its requests" do
+ family = users(:family_admin).family
+ call_id = SecureRandom.uuid
+ attributes = { provider: "openai", model: "gpt-4.1", operation: "bill_setup", prompt_tokens: 100, completion_tokens: 10, total_tokens: 110 }
+ family.llm_usages.create!(**attributes, call_id:, status: "failed", metadata: { "error" => "Service unavailable" }, created_at: 2.minutes.ago)
+ family.llm_usages.create!(**attributes, call_id:, status: "succeeded", created_at: 1.minute.ago)
+
+ sign_in users(:family_admin)
+ get settings_llm_usage_path
+
+ assert_response :success
+ assert_select "tbody tr", 1
+ assert_select "tbody tr details", 1
+ assert_includes response.body, I18n.t("settings.llm_usages.requests.summary", count: 2)
+ assert_includes response.body, "Service unavailable"
+ assert_includes response.body, I18n.t("settings.llm_usages.show.total_calls")
+ end
+
+ test "a cancelled call of one request says so" do
+ users(:family_admin).family.llm_usages.create!(provider: "openai", model: "gpt-4.1", operation: "bill_setup", prompt_tokens: 100,
+ completion_tokens: 0, total_tokens: 100, status: "cancelled")
+
+ sign_in users(:family_admin)
+ get settings_llm_usage_path
+
+ assert_select "tbody tr td", text: /#{I18n.t("settings.llm_usages.show.cancelled")}/
+ end
+
test "non-admin member cannot view family LLM usage" do
sign_in users(:family_member)
get settings_llm_usage_path
diff --git a/test/migrations/add_call_id_and_status_to_llm_usages_migration_test.rb b/test/migrations/add_call_id_and_status_to_llm_usages_migration_test.rb
new file mode 100644
index 0000000000..595b844ede
--- /dev/null
+++ b/test/migrations/add_call_id_and_status_to_llm_usages_migration_test.rb
@@ -0,0 +1,75 @@
+# frozen_string_literal: true
+
+require "test_helper"
+require Rails.root.join("db/migrate/20261106120000_add_call_id_and_status_to_llm_usages")
+
+# The backfill marks a row failed only when its error is present, as LlmUsage's own check has
+# it; the schema changes roll back with the test's transaction.
+class AddCallIdAndStatusToLlmUsagesMigrationTest < ActiveSupport::TestCase
+ ERRORS = {
+ "HTTP 500" => "failed",
+ { "message" => "busy" } => "failed",
+ [ "busy" ] => "failed",
+ true => "failed",
+ 429 => "failed",
+ "" => "succeeded",
+ {} => "succeeded",
+ [] => "succeeded",
+ false => "succeeded",
+ " " => "succeeded",
+ "\t\n" => "succeeded",
+ "\u00a0" => "succeeded",
+ "\u3000\u2003" => "succeeded",
+ "\u00a0busy" => "failed",
+ nil => "succeeded"
+ }.freeze
+
+ teardown { LlmUsage.reset_column_information }
+
+ test "up marks failed exactly the rows whose error is present" do
+ migrate(:down)
+ ids = ERRORS.keys.map { insert_usage({ "error" => _1 }) }
+ without_error = insert_usage({})
+
+ migrate(:up)
+
+ assert_equal ERRORS.values, ids.map { status_of(_1) }
+ assert_equal "succeeded", status_of(without_error)
+ end
+
+ test "down then up restores the columns, the index and the constraint" do
+ before = shape
+
+ migrate(:down)
+ assert_not connection.column_exists?(:llm_usages, :status)
+ migrate(:up)
+
+ assert_equal before, shape
+ end
+
+ private
+ def connection = ActiveRecord::Base.connection
+
+ def migrate(direction)
+ ActiveRecord::Migration.suppress_messages { AddCallIdAndStatusToLlmUsages.new.migrate(direction) }
+ LlmUsage.reset_column_information
+ end
+
+ def insert_usage(metadata)
+ connection.select_value(<<~SQL)
+ INSERT INTO llm_usages (family_id, provider, model, operation, prompt_tokens, completion_tokens, total_tokens, metadata, created_at, updated_at)
+ VALUES (#{connection.quote(families(:dylan_family).id)}, 'openai', 'gpt-4.1', 'bill_setup', 1, 1, 2, #{connection.quote(metadata.to_json)}::jsonb, now(), now())
+ RETURNING id
+ SQL
+ end
+
+ def status_of(id) = connection.select_value("SELECT status FROM llm_usages WHERE id = #{connection.quote(id)}")
+
+ def shape
+ {
+ columns: connection.columns(:llm_usages).map { [ _1.name, _1.sql_type, _1.default, _1.null ] }.sort,
+ indexes: connection.indexes(:llm_usages).map(&:name).sort,
+ constraints: connection.check_constraints(:llm_usages).map(&:name).sort
+ }
+ end
+end
diff --git a/test/models/ai/call_context_test.rb b/test/models/ai/call_context_test.rb
new file mode 100644
index 0000000000..cadc6bbd4d
--- /dev/null
+++ b/test/models/ai/call_context_test.rb
@@ -0,0 +1,117 @@
+require "test_helper"
+
+class Ai::CallContextTest < ActiveSupport::TestCase
+ setup do
+ @family = families(:dylan_family)
+ @model = ai_model(name: "test-model")
+ stub_request(:post, "https://llm.example.test/v1/chat/completions").to_return(
+ status: 200, headers: { "Content-Type" => "application/json" },
+ body: { id: "c1", model: "test-model", choices: [ { index: 0, message: { role: "assistant", content: "OK" }, finish_reason: "stop" } ],
+ usage: { prompt_tokens: 5, completion_tokens: 1, total_tokens: 6 } }.to_json
+ )
+ end
+
+ test "RubyLLM's usage event carries the family, and the call id" do
+ usage = capture_ai_events("usage.ruby_llm") do
+ with_ai_call_context(feature: :bill_setup, model: @model, family: @family) do |call|
+ @call = call
+ Ai::Transport.for(@model.endpoint).send(:probe_chat, @model)
+ end
+ end.sole.payload
+
+ assert_equal @family, usage[:owner]
+ assert_equal @call.call_id, usage[:workflow_id]
+ assert_equal({ "feature" => "bill_setup", "call_id" => @call.call_id,
+ "family_id" => @family.id.to_s, "endpoint" => "test", "model" => "test-model" },
+ usage[:workflow_metadata].transform_keys(&:to_s))
+ end
+
+ test "the context is fiber storage, so threads started inside a call inherit it" do
+ seen = with_ai_call_context(feature: :chat, model: @model) do |call|
+ [ call.call_id, Thread.new { Ai::CallContext.current&.call_id }.value ]
+ end
+
+ assert_equal seen.first, seen.last
+ assert_nil Ai::CallContext.current
+ end
+
+ test "a RubyLLM request from a thread started inside a call is recorded for the family and the call" do
+ call_id = with_ai_call_context(feature: :chat, model: @model, family: @family) do |call|
+ Thread.new { Ai::Transport.for(@model.endpoint).send(:probe_chat, @model) }.join
+ call.call_id
+ end
+
+ row = @family.llm_usages.sole
+ assert_equal call_id, row.call_id
+ assert_equal "chat", row.operation
+ end
+
+ test "a request that would start after the attempt's budget raises Timeout and isn't sent" do
+ error = assert_raises(Ai::Error::Timeout) do
+ with_ai_call_context(model: @model, budget: 0) do
+ Ai::Transport.for(@model.endpoint).send(:probe_chat, @model)
+ end
+ end
+
+ assert_match(/time budget/, error.message)
+ assert_not_requested :post, "https://llm.example.test/v1/chat/completions"
+ end
+
+ test "a retry whose wait would outlast the attempt's budget isn't made" do
+ model = ai_model(name: "test-model", endpoint: ai_endpoint(name: "test", base_url: "https://llm.example.test/v1", max_retries: 3))
+ transport = Ai::Transport.for(model.endpoint)
+ transport.stubs(:retry_delay).returns(5)
+ transport.expects(:sleep).never
+ tries = 0
+
+ with_ai_call_context(model:, budget: 2) do
+ assert_raises(Ai::Error::Upstream) { transport.send(:attempt) { tries += 1; raise Ai::Error::Upstream, "busy" } }
+ end
+
+ assert_equal 1, tries
+ end
+
+ test "a request outside RubyLLM, such as the models list, isn't sent once the budget is spent" do
+ model = ai_model(name: "test-model")
+ Ai::Transport::Http.expects(:openai_client).never
+
+ with_ai_call_context(model:, budget: 0) do
+ assert_raises(Ai::Error::Timeout) { Ai::Transport.for(model.endpoint).send(:attempt) { Ai::Transport::Http.openai_client(model.endpoint) } }
+ end
+ end
+
+ test "each attempt's request timeout is cut to what's left of the budget" do
+ model = ai_model(name: "test-model")
+ transport = Ai::Transport.for(model.endpoint)
+
+ with_ai_call_context(model:, budget: 0.2) { assert_operator transport.send(:within_budget, 60), :<=, 0.2 }
+ assert_equal 60, transport.send(:within_budget, 60)
+ end
+
+ test "an answer that arrives after the budget is spent is a Timeout, not a pass" do
+ model = ai_model(name: "test-model")
+ transport = Ai::Transport.for(model.endpoint)
+
+ with_ai_call_context(model:, budget: 1) do |call|
+ error = assert_raises(Ai::Error::Timeout) do
+ transport.send(:attempt) { Ai::CallContext.stubs(:now).returns(call.deadline + 0.1); :ok }
+ end
+ assert_match(/before the answer arrived/, error.message)
+ end
+ end
+
+ test "an error with no Ai::Error is scrubbed before it goes on the request event" do
+ instrumenter = Ai::Transport::Instrumenter.new(nil, map_error: ->(_) { }, scrub: ->(text) { text.gsub("sk-secret", "[REDACTED]") })
+ payload = {}
+
+ assert_raises(RuntimeError) { instrumenter.instrument("request.ruby_llm", payload) { raise "failed with sk-secret" } }
+ assert_equal({ error: "failed with [REDACTED]", error_class: "RuntimeError" }, payload[:ai_error])
+ end
+
+ test "the instrumenter forwards every event to RubyLLM's own instrumenter" do
+ delegate = mock
+ delegate.expects(:instrument).with("chat.ruby_llm", { a: 1 }).yields.returns(:done)
+
+ assert_equal :done, Ai::Transport::Instrumenter.new(delegate).instrument("chat.ruby_llm", { a: 1 }) { :ignored }
+ end
+end
diff --git a/test/models/ai/config_test.rb b/test/models/ai/config_test.rb
new file mode 100644
index 0000000000..60344bac59
--- /dev/null
+++ b/test/models/ai/config_test.rb
@@ -0,0 +1,30 @@
+require "test_helper"
+
+class Ai::ConfigTest < ActiveSupport::TestCase
+ test "an endpoint normalises its values and probes by listing models by default" do
+ endpoint = Ai::Config::Endpoint.new(name: :gpu, protocol: "compatible", base_url: "", timeout_seconds: "300")
+
+ assert_equal "gpu", endpoint.name
+ assert_equal :compatible, endpoint.protocol
+ assert_nil endpoint.base_url
+ assert_equal 300, endpoint.timeout_seconds
+ assert_equal 0, endpoint.max_retries
+ assert_equal :models, endpoint.probe_check
+ end
+
+ test "an endpoint refuses unknown protocols and probe checks" do
+ assert_raises(ArgumentError) { Ai::Config::Endpoint.new(name: "x", protocol: :grpc) }
+ assert_raises(ArgumentError) { Ai::Config::Endpoint.new(name: "x", protocol: :compatible, probe_check: :ping) }
+ end
+
+ test "an endpoint never shows its key or header values" do
+ endpoint = ai_endpoint(base_url: "https://user:[email protected]/v1?key=abc", api_key: "test-secret-value-1",
+ extra_headers: { "X-Api-Key" => "header-secret" })
+
+ [ endpoint.inspect, endpoint.to_s, endpoint.to_event.to_s ].each do |shown|
+ assert_not_includes shown, "test-secret-value-1"
+ assert_not_includes shown, "header-secret"
+ assert_not_includes shown, "pass"
+ end
+ end
+end
diff --git a/test/models/ai/error_test.rb b/test/models/ai/error_test.rb
new file mode 100644
index 0000000000..930c760ac3
--- /dev/null
+++ b/test/models/ai/error_test.rb
@@ -0,0 +1,63 @@
+require "test_helper"
+
+class Ai::ErrorTest < ActiveSupport::TestCase
+ test "statuses map onto the taxonomy" do
+ {
+ 401 => Ai::Error::Unauthorized, 403 => Ai::Error::Unauthorized, 402 => Ai::Error::NoCredit,
+ 404 => Ai::Error::Refused, 408 => Ai::Error::Timeout, 429 => Ai::Error::RateLimited,
+ 400 => Ai::Error::Refused, 422 => Ai::Error::Refused, 500 => Ai::Error::Upstream,
+ 503 => Ai::Error::Upstream, 529 => Ai::Error::Upstream
+ }.each do |status, klass|
+ assert_equal klass, Ai::Error.for_status(status, "something"), "HTTP #{status}"
+ end
+ end
+
+ test "each provider's context-length wording is ContextTooLong" do
+ [
+ "This model's maximum context length is 8192 tokens", # OpenAI, vLLM
+ "request (287168 tokens) exceeds the available context size (65536 tokens)", # llama.cpp
+ "prompt is too long: 210000 tokens > 200000 maximum", # Anthropic
+ "Input is too long for requested model.", # Bedrock
+ "Engine protocol predict request returned 400: context length exceeded" # LM Studio
+ ].each do |message|
+ assert_equal Ai::Error::ContextTooLong, Ai::Error.for_status(400, message), message
+ end
+ end
+
+ test "a spent balance is NoCredit, however the provider says it" do
+ assert_equal Ai::Error::NoCredit, Ai::Error.for_status(400, "Your credit balance is too low to access the Anthropic API")
+ assert_equal Ai::Error::NoCredit, Ai::Error.for_status(429, "You exceeded your current quota", body: { "error" => { "code" => "insufficient_quota" } })
+ assert_equal Ai::Error::NoCredit, Ai::Error.for_status(429, "You have no credits remaining.", body: { "error" => { "code" => "credit_balance_exhausted" } })
+ assert_equal Ai::Error::NoCredit, Ai::Error.for_status(402, "Insufficient credits")
+ assert_equal Ai::Error::RateLimited, Ai::Error.for_status(429, "Rate limit reached for requests")
+ end
+
+ test "a 404 naming the model is ModelMissing; any other 404 is Refused" do
+ assert_equal Ai::Error::ModelMissing, Ai::Error.for_status(404, "model 'qwen3:8b' not found")
+ assert_equal Ai::Error::ModelMissing, Ai::Error.for_status(404, "The model `gpt-9` does not exist or you do not have access to it.")
+ assert_equal Ai::Error::ModelMissing, Ai::Error.for_status(404, "x", body: { "error" => { "code" => "model_not_found" } })
+ assert_equal Ai::Error::Refused, Ai::Error.for_status(404, "Not Found")
+ end
+
+ test "from_status keeps the status" do
+ error = Ai::Error.from_status(503, "overloaded")
+
+ assert_instance_of Ai::Error::Upstream, error
+ assert_equal 503, error.status
+ end
+
+ test "from_exception maps network failures and HTTP errors from client gems" do
+ assert_instance_of Ai::Error::Timeout, Ai::Error.from_exception(Faraday::TimeoutError.new("slow"))
+ assert_instance_of Ai::Error::Timeout, Ai::Error.from_exception(Net::ReadTimeout.new)
+ assert_instance_of Ai::Error::Unreachable, Ai::Error.from_exception(Faraday::ConnectionFailed.new("refused"))
+ assert_instance_of Ai::Error::Unreachable, Ai::Error.from_exception(Errno::ECONNREFUSED.new)
+
+ ruby_openai = Faraday::UnauthorizedError.new("401", { status: 401, body: { "error" => "bad key" } })
+ assert_instance_of Ai::Error::Unauthorized, Ai::Error.from_exception(ruby_openai)
+
+ garbled = Faraday::ParsingError.new(JSON::ParserError.new("unexpected token"), Faraday::Response.new(status: 200))
+ assert_instance_of Ai::Error::InvalidOutput, Ai::Error.from_exception(garbled)
+
+ assert_nil Ai::Error.from_exception(RuntimeError.new("ours"))
+ end
+end
diff --git a/test/models/ai/instrumentation/metadata_tracing_test.rb b/test/models/ai/instrumentation/metadata_tracing_test.rb
new file mode 100644
index 0000000000..215c8a617c
--- /dev/null
+++ b/test/models/ai/instrumentation/metadata_tracing_test.rb
@@ -0,0 +1,79 @@
+require "test_helper"
+
+# `metadata` mode must never send content: no prompt, answer, tool result or error body on any
+# span. RubyLLM 2.2 can put content on spans when asked (RubyLLM #1333), so this test guards upgrades.
+class Ai::Instrumentation::MetadataTracingTest < ActiveSupport::TestCase
+ URL = "https://llm.example.test/v1/chat/completions".freeze
+ SECRET_PROMPT = "Reply with OK.".freeze
+ SECRET_ANSWER = "NETFLIX-CHARGE-15.49".freeze
+
+ setup do
+ @previous_provider = OpenTelemetry.tracer_provider
+ @exporter = OpenTelemetry::SDK::Trace::Export::InMemorySpanExporter.new
+ Ai::Instrumentation::MetadataTracing.enable(processor: OpenTelemetry::SDK::Trace::Export::SimpleSpanProcessor.new(@exporter))
+ @model = ai_model(name: "test-model")
+ end
+
+ teardown do
+ RubyLLM::OpenTelemetry.disable
+ OpenTelemetry.tracer_provider = @previous_provider
+ end
+
+ test "spans carry the model and tokens, and none of the content" do
+ stub_request(:post, URL).to_return(status: 200, headers: { "Content-Type" => "application/json" }, body: {
+ id: "c1", model: "test-model", choices: [ { index: 0, message: { role: "assistant", content: SECRET_ANSWER }, finish_reason: "stop" } ],
+ usage: { prompt_tokens: 9, completion_tokens: 4, total_tokens: 13 }
+ }.to_json)
+
+ chat_call
+
+ spans = @exporter.finished_spans
+ chat = spans.find { _1.attributes["gen_ai.operation.name"] == "chat" }
+ assert chat, "a chat span: #{spans.map(&:name)}"
+ assert_equal "test-model", chat.attributes["gen_ai.request.model"]
+
+ everything = spans.flat_map { [ _1.name, _1.attributes.to_a, _1.events.to_a.map { |e| [ e.name, e.attributes.to_a ] }, _1.status.description ] }.to_s
+ assert_not_includes everything, SECRET_PROMPT
+ assert_not_includes everything, SECRET_ANSWER
+ end
+
+ test "an error body never reaches a span" do
+ stub_request(:post, URL).to_return(status: 500, headers: { "Content-Type" => "application/json" },
+ body: { error: { message: "failed on #{SECRET_ANSWER}" } }.to_json)
+
+ assert_raises(Ai::Error::Upstream) { chat_call }
+
+ assert @exporter.finished_spans.any? { _1.attributes["gen_ai.operation.name"] == "chat" && _1.attributes["error.type"].present? },
+ "a failed chat span: #{@exporter.finished_spans.map { [ _1.name, _1.attributes ] }}"
+ assert_not_includes @exporter.finished_spans.map { [ _1.attributes.to_a, _1.events.to_a.map(&:attributes), _1.status.description ] }.to_s, SECRET_ANSWER
+ end
+
+ test "health probes aren't traced; the calls around them are" do
+ stub_request(:post, URL).to_return(status: 200, headers: { "Content-Type" => "application/json" }, body: {
+ id: "c1", model: "test-model", choices: [ { index: 0, message: { role: "assistant", content: "OK" }, finish_reason: "stop" } ]
+ }.to_json)
+
+ Ai::Transport.for(@model.endpoint).probe(@model, :chat)
+ assert_empty @exporter.finished_spans
+
+ chat_call
+ assert @exporter.finished_spans.any? { _1.attributes["gen_ai.operation.name"] == "chat" }
+ end
+
+ test "OTLP_HEADERS takes the OpenTelemetry key=value form" do
+ assert_equal({ "Authorization" => "Basic abc=", "x-team" => "home" },
+ Ai::Instrumentation::MetadataTracing.parse_headers("Authorization=Basic%20abc%3D, x-team=home"))
+ end
+
+ test "a literal + in a header value stays; %2B decodes to +" do
+ assert_equal({ "Authorization" => "Basic ab+c/d==" },
+ Ai::Instrumentation::MetadataTracing.parse_headers("Authorization=Basic ab+c/d=="))
+ assert_equal({ "x-team" => "a+b" }, Ai::Instrumentation::MetadataTracing.parse_headers("x-team=a%2Bb"))
+ end
+
+ private
+ # A chat request inside a feature's call, as a generation makes it.
+ def chat_call
+ Ai::CallContext.call(feature: :bill_setup, model: @model) { Ai::Transport.for(@model.endpoint).send(:probe_chat, @model) }
+ end
+end
diff --git a/test/models/ai/instrumentation/redactor_test.rb b/test/models/ai/instrumentation/redactor_test.rb
new file mode 100644
index 0000000000..7a1c52b2b4
--- /dev/null
+++ b/test/models/ai/instrumentation/redactor_test.rb
@@ -0,0 +1,15 @@
+require "test_helper"
+
+class Ai::Instrumentation::RedactorTest < ActiveSupport::TestCase
+ test "a URL loses its credentials, query and fragment" do
+ assert_equal "https://llm.example.test/v1", Ai::Instrumentation::Redactor.url("https://user:[email protected]/v1?key=abc#top")
+ end
+
+ test "a URL that doesn't parse is masked whole, since its credentials can't be found reliably" do
+ assert_equal "[REDACTED]", Ai::Instrumentation::Redactor.url("http://user:pa/ss@llm example/v1?key=abc")
+ end
+
+ test "a blank URL stays nil" do
+ assert_nil Ai::Instrumentation::Redactor.url("")
+ end
+end
diff --git a/test/models/ai/instrumentation/subscribers_test.rb b/test/models/ai/instrumentation/subscribers_test.rb
new file mode 100644
index 0000000000..78bca48bf0
--- /dev/null
+++ b/test/models/ai/instrumentation/subscribers_test.rb
@@ -0,0 +1,129 @@
+require "test_helper"
+
+class Ai::Instrumentation::SubscribersTest < ActiveSupport::TestCase
+ FakeObservation = Struct.new(:log) do
+ def generation(**attributes) = tap { log << [ :generation, attributes ] }
+ def end(**attributes) = log << [ :end, attributes ]
+ end
+
+ FakeLangfuse = Struct.new(:log) do
+ def trace(**attributes)
+ log << [ :trace, attributes ]
+ FakeObservation.new(log)
+ end
+ end
+
+ test "the tracing mode follows the variables an operator already sets" do
+ assert_equal :content, Ai::Instrumentation.mode(env: { "LANGFUSE_PUBLIC_KEY" => "pk", "LANGFUSE_SECRET_KEY" => "sk" })
+ assert_equal :content, Ai::Instrumentation.mode(env: { "LANGFUSE_PUBLIC_KEY" => "pk", "LANGFUSE_SECRET_KEY" => "sk", "OTLP_ENDPOINT" => "http://otel:4318" })
+ assert_equal :metadata, Ai::Instrumentation.mode(env: { "OTLP_ENDPOINT" => "http://otel:4318/v1/traces" })
+ assert_equal :off, Ai::Instrumentation.mode(env: { "LANGFUSE_PUBLIC_KEY" => "pk" })
+ end
+
+ test "metadata mode shuts its tracer provider down at exit, so the last batch is exported" do
+ provider = mock("tracer provider")
+ Ai::Instrumentation::MetadataTracing.expects(:enable).with(endpoint: "https://otlp.example.test/v1/traces", headers: nil).returns(provider)
+ provider.expects(:shutdown)
+ Ai::Instrumentation.expects(:at_exit).yields
+
+ Ai::Instrumentation.start_tracing!(env: { "OTLP_ENDPOINT" => "https://otlp.example.test/v1/traces" })
+ end
+
+ test "content mode subscribes Langfuse; the other modes don't" do
+ content = Ai::Instrumentation.subscribe!(env: { "LANGFUSE_PUBLIC_KEY" => "pk", "LANGFUSE_SECRET_KEY" => "sk" })
+ off = Ai::Instrumentation.subscribe!(env: {})
+
+ assert_equal 5, content.size
+ assert_equal 4, off.size
+ ensure
+ [ *content, *off ].each { ActiveSupport::Notifications.unsubscribe(_1) }
+ end
+
+ test "Langfuse gets one trace per call with the route and scrubbed output; probes aren't traced" do
+ log = []
+ subscriber = Ai::Instrumentation::LangfuseSubscriber.new(client: FakeLangfuse.new(log))
+ payload = { feature: "bill_setup", call_id: "c1", route: { endpoint: "openai", model: "gpt-4.1" },
+ request: { input: "charges" }, output: { name: "Netflix", notes: [ "billed with sk-live-abcdef123456" ] },
+ usage: Ai::Tokens.new(input_tokens: 512, cache_read_tokens: 11_945, output_tokens: 20) }
+
+ subscriber.call(event("generate.ai", payload))
+ subscriber.call(event("probe.ai", payload))
+
+ trace = log.find { _1.first == :trace }.last
+ assert_equal "bill_setup.generate", trace[:name]
+ generation_end = log.select { _1.first == :end }.first.last
+ assert_equal({ input_tokens: 12_457, output_tokens: 20, prompt_tokens_details: { cached_tokens: 11_945 } }, generation_end[:usage])
+ assert_equal 1, log.count { _1.first == :trace }, "probe.ai is skipped"
+ ends = log.select { _1.first == :end }.map(&:last)
+ assert_equal 2, ends.size, "the generation and the trace"
+ ends.each { assert_equal({ name: "Netflix", notes: [ "billed with [REDACTED]" ] }, _1[:output]) }
+ end
+
+ test "Langfuse masks a field named like a credential, whatever its value looks like" do
+ log = []
+ subscriber = Ai::Instrumentation::LangfuseSubscriber.new(client: FakeLangfuse.new(log))
+ payload = { feature: "bill_setup", call_id: "c1", route: { endpoint: "gateway", model: "m" },
+ request: { input: "hi", options: { api_key: "opaque", "Authorization" => "opaque too" } }, output: { text: "ok" } }
+
+ subscriber.call(event("generate.ai", payload))
+
+ assert_equal({ input: "hi", options: { api_key: "[REDACTED]", "Authorization" => "[REDACTED]" } },
+ log.find { _1.first == :trace }.last[:input])
+ end
+
+ test "Langfuse content is scrubbed of the endpoint's own secrets, whatever their shape" do
+ log = []
+ subscriber = Ai::Instrumentation::LangfuseSubscriber.new(client: FakeLangfuse.new(log))
+ scrub = ->(text) { Ai::Instrumentation::Redactor.scrub(text, secrets: [ "opaque-gateway-token" ]) }
+ payload = { feature: "bill_setup", call_id: "c1", route: { endpoint: "gateway", model: "m" }, scrub:,
+ request: { input: "use opaque-gateway-token" }, output: { text: "echo opaque-gateway-token" } }
+
+ subscriber.call(event("generate.ai", payload))
+
+ trace = log.find { _1.first == :trace }.last
+ assert_equal({ input: "use [REDACTED]" }, trace[:input])
+ assert_equal({ text: "echo [REDACTED]" }, log.find { _1.first == :end }.last[:output])
+ end
+
+ test "a failed call writes a debug log entry with its route and error, never its key" do
+ payload = { feature: "categorize", call_id: "c1", family_id: families(:dylan_family).id,
+ endpoint: { name: "gpu", protocol: :compatible }, route: { endpoint: "gpu", model: "qwen3-8b" },
+ error: "Ai::Error::Upstream", error_message: "busy", http_status: 503 }
+
+ assert_difference -> { DebugLogEntry.where(category: "ai").count }, 1 do
+ Ai::Instrumentation::DebugLogSubscriber.new.call(ActiveSupport::Notifications::Event.new("generate.ai", nil, nil, "1", payload))
+ Ai::Instrumentation::DebugLogSubscriber.new.call(ActiveSupport::Notifications::Event.new("probe.ai", nil, nil, "2", payload))
+ Ai::Instrumentation::DebugLogSubscriber.new.call(ActiveSupport::Notifications::Event.new("generate.ai", nil, nil, "3", payload.except(:error)))
+ end
+
+ entry = DebugLogEntry.where(category: "ai").last
+ assert_equal "error", entry.level
+ assert_equal "gpu", entry.provider_key
+ assert_equal families(:dylan_family), entry.family
+ assert_equal "Ai::Error::Upstream", entry.metadata["error_class"]
+ assert_equal({ "endpoint" => "gpu", "model" => "qwen3-8b" }, entry.metadata["route"])
+ end
+
+ test "the redactor masks key shapes, authorization values and the endpoint's own key" do
+ text = "key sk-proj-abcdefghijkl Bearer abc.def.ghi123 api_key=hunter22hunter custom-secret-value"
+
+ scrubbed = Ai::Instrumentation::Redactor.scrub(text, secrets: [ "custom-secret-value" ])
+
+ %w[sk-proj-abcdefghijkl abc.def.ghi123 hunter22hunter custom-secret-value].each { assert_not_includes scrubbed, _1 }
+ assert_includes scrubbed, "Bearer [REDACTED]"
+ assert_includes scrubbed, "api_key=[REDACTED]"
+ end
+
+ test "a secret that contains another of the endpoint's secrets is masked whole" do
+ scrubbed = Ai::Instrumentation::Redactor.scrub("tenant tenant-opaque-123-region-eu",
+ secrets: [ "tenant-opaque-123", "tenant-opaque-123-region-eu" ])
+
+ assert_equal "tenant [REDACTED]", scrubbed
+ end
+
+ private
+ def event(name, payload)
+ now = Process.clock_gettime(Process::CLOCK_MONOTONIC)
+ ActiveSupport::Notifications::Event.new(name, now - 1.5, now, SecureRandom.hex(4), payload)
+ end
+end
diff --git a/test/models/ai/instrumentation/usage_subscriber_test.rb b/test/models/ai/instrumentation/usage_subscriber_test.rb
new file mode 100644
index 0000000000..1b8997e05c
--- /dev/null
+++ b/test/models/ai/instrumentation/usage_subscriber_test.rb
@@ -0,0 +1,133 @@
+require "test_helper"
+
+class Ai::Instrumentation::UsageSubscriberTest < ActiveSupport::TestCase
+ URL = "https://llm.example.test/v1/chat/completions".freeze
+ OK = { id: "c1", model: "gpt-4.1-2025-04-14", choices: [ { index: 0, message: { role: "assistant", content: "OK" }, finish_reason: "stop" } ],
+ usage: { prompt_tokens: 1_200, completion_tokens: 30, total_tokens: 1_230, prompt_tokens_details: { cached_tokens: 1_000 } } }.freeze
+
+ setup do
+ @family = families(:dylan_family)
+ @endpoint = ai_endpoint(name: "openai", max_retries: 2)
+ @model = ai_model(name: "gpt-4.1", endpoint: @endpoint)
+ @transport = Ai::Transport.for(@endpoint)
+ Ai::Transport::Base.any_instance.stubs(:retry_delay).returns(0)
+ end
+
+ test "each request of a call is one row, grouped by the call id" do
+ stub_request(:post, URL).to_return({ status: 503, body: { error: { message: "busy" } }.to_json, headers: json },
+ { status: 200, body: OK.to_json, headers: json })
+
+ call_id = run_call(feature: :bill_setup)
+
+ rows = @family.llm_usages.where(call_id:).order(:created_at)
+ assert_equal %w[failed succeeded], rows.map(&:status)
+ assert_equal [ "bill_setup" ], rows.map(&:operation).uniq
+ assert_equal [ "openai" ], rows.map(&:provider).uniq
+ assert_equal [ "gpt-4.1" ], rows.map(&:model).uniq
+
+ succeeded = rows.last
+ assert_equal 1_200, succeeded.prompt_tokens, "the prompt counts cached tokens"
+ assert_equal 1_000, succeeded.cache_read_tokens
+ assert_equal 30, succeeded.completion_tokens
+ assert_in_delta 0.00114, succeeded.estimated_cost, 1e-9, "RubyLLM's price for the model, cache reads at the cached rate"
+ end
+
+ test "without RubyLLM's price, the published table prices cached input as input, except Anthropic's" do
+ subscriber = Ai::Instrumentation::UsageSubscriber.new
+ tokens = Ai::Tokens.new(input_tokens: 200, cache_read_tokens: 1_000, output_tokens: 30)
+
+ assert_in_delta LlmUsage.calculate_cost(model: "gpt-4.1", prompt_tokens: 1_200, completion_tokens: 30),
+ subscriber.send(:cost, tokens, "gpt-4.1"), 1e-9
+ assert_in_delta LlmUsage.calculate_cost(model: "claude-opus-5-5", prompt_tokens: 200, completion_tokens: 30, cache_read_tokens: 1_000),
+ subscriber.send(:cost, tokens, "claude-opus-5-5"), 1e-9
+ end
+
+ test "a failed call's rows get the error class and scrubbed message from its .ai event" do
+ stub_request(:post, URL).to_return(status: 401, body: { error: { message: "Invalid key test-key" } }.to_json, headers: json)
+
+ call_id = nil
+ assert_raises(Ai::Error::Unauthorized) { call_id = run_call(feature: :categorize) }
+
+ row = @family.llm_usages.find_by!(call_id: LlmUsage.where(family: @family).order(:created_at).last.call_id)
+ assert row.failed?
+ assert_equal "Ai::Error::Unauthorized", row.metadata["error_class"]
+ assert_equal 401, row.metadata["http_status_code"]
+ assert_not_includes row.metadata["error"], "test-key"
+ assert_nil call_id
+ end
+
+ test "each failed retry keeps its own error, even when a later retry succeeds" do
+ stub_request(:post, URL).to_return({ status: 503, body: { error: { message: "busy" } }.to_json, headers: json },
+ { status: 429, body: { error: { message: "slow down" } }.to_json, headers: json },
+ { status: 200, body: OK.to_json, headers: json })
+
+ rows = @family.llm_usages.where(call_id: run_call(feature: :bill_setup)).order(:created_at)
+
+ assert_equal %w[failed failed succeeded], rows.map(&:status)
+ assert_equal [ [ "Ai::Error::Upstream", 503 ], [ "Ai::Error::RateLimited", 429 ] ],
+ rows.first(2).map { [ _1.metadata["error_class"], _1.metadata["http_status_code"] ] }
+ assert_match "busy", rows.first.error_message
+ assert_match "slow down", rows.second.error_message
+ assert_nil rows.last.error_message
+ end
+
+ test "a request from a thread started inside the call still gets its error" do
+ stub_request(:post, URL).to_return({ status: 503, body: { error: { message: "busy" } }.to_json, headers: json },
+ { status: 200, body: OK.to_json, headers: json })
+
+ call_id = Ai::CallContext.call(feature: :bill_setup, model: @model, family: @family, budget: 30) do |call|
+ Thread.new do
+ @transport.send(:instrument, "generate", model: @model, request: {}) do
+ @transport.send(:attempt) { @transport.send(:probe_chat, @model) }
+ end
+ end.join
+ call.call_id
+ end
+
+ failed = @family.llm_usages.find_by!(call_id:, status: "failed")
+ assert_equal [ "Ai::Error::Upstream", 503 ], [ failed.metadata["error_class"], failed.metadata["http_status_code"] ]
+ end
+
+ test "a credential in a static header is scrubbed from the error, as the key is" do
+ @endpoint = ai_endpoint(name: "gateway", extra_headers: { "X-Tenant-Key" => "tenant-opaque-123" })
+ @model = ai_model(name: "gpt-4.1", endpoint: @endpoint)
+ @transport = Ai::Transport.for(@endpoint)
+ stub_request(:post, URL).to_return(status: 401, body: { error: { message: "unknown tenant tenant-opaque-123" } }.to_json, headers: json)
+
+ error = assert_raises(Ai::Error::Unauthorized) { run_call(feature: :categorize) }
+
+ assert_not_includes error.message, "tenant-opaque-123"
+ assert_not_includes LlmUsage.where(family: @family).order(:created_at).last.error_message, "tenant-opaque-123"
+ end
+
+ test "requests outside a family's call write nothing: health probes, evals" do
+ stub_request(:post, URL).to_return(status: 200, body: OK.to_json, headers: json)
+
+ assert_no_difference -> { LlmUsage.count } do
+ @transport.probe(@model, :chat) rescue Ai::Error::ModelMissing
+ Ai::CallContext.call(feature: :eval, model: @model) { @transport.send(:probe_chat, @model) } rescue Ai::Error::ModelMissing
+ end
+ end
+
+ test "a broken row never breaks the call" do
+ stub_request(:post, URL).to_return(status: 200, body: OK.to_json, headers: json)
+ LlmUsage.any_instance.stubs(:save!).raises(ActiveRecord::RecordInvalid)
+ Rails.logger.expects(:error).with(includes("UsageSubscriber")).at_least_once
+
+ assert_nothing_raised { run_call(feature: :bill_setup) }
+ end
+
+ private
+ def json = { "Content-Type" => "application/json" }
+
+ # A call as a generation makes it: a call context with the family, the transport's
+ # retries, one .ai event.
+ def run_call(feature:)
+ Ai::CallContext.call(feature:, model: @model, family: @family, budget: 30) do |call|
+ @transport.send(:instrument, "generate", model: @model, request: {}) do
+ @transport.send(:attempt) { @transport.send(:probe_chat, @model) }
+ end
+ call.call_id
+ end
+ end
+end
diff --git a/test/models/ai/ruby_llm_setup_test.rb b/test/models/ai/ruby_llm_setup_test.rb
new file mode 100644
index 0000000000..b471cdd32b
--- /dev/null
+++ b/test/models/ai/ruby_llm_setup_test.rb
@@ -0,0 +1,55 @@
+require "test_helper"
+
+# RubyLLM is set up as config/initializers/ruby_llm.rb describes.
+class Ai::RubyLlmSetupTest < ActiveSupport::TestCase
+ test "the gem is on the 2.x line the plan builds on" do
+ assert Gem::Requirement.new("~> 2.1").satisfied_by?(Gem::Version.new(RubyLLM::VERSION)), RubyLLM::VERSION
+ end
+
+ # Sure records usage in llm_usages; RubyLLM's ledger writes a row per attempt only once its
+ # table exists, so the table must never be created.
+ test "RubyLLM's usage ledger has no table to write to" do
+ assert_not ActiveRecord::Base.connection.table_exists?("ruby_llm_usages")
+ end
+
+ test "no global keys or endpoints: every call goes through a per-endpoint context" do
+ assert_nil RubyLLM.config.openai_api_key
+ assert_nil RubyLLM.config.anthropic_api_key
+ assert_equal Rails.logger, RubyLLM.config.logger.__getobj__
+ end
+
+ # At debug RubyLLM logs response bodies and raw exceptions, which can quote a key back.
+ test "RubyLLM never logs at debug, even when Rails does" do
+ output = StringIO.new
+ rails_logger = ActiveSupport::Logger.new(output, level: Logger::DEBUG)
+ logger = RubyLlmLogger.new(rails_logger)
+
+ assert_not logger.debug?
+ assert_equal Logger::INFO, logger.level
+
+ logger.debug("body with sk-secret")
+ logger.debug { "block with sk-secret" }
+ logger.warn("a warning")
+
+ assert_no_match(/sk-secret/, output.string)
+ assert_match(/a warning/, output.string)
+ end
+
+ test "Faraday's logger under RubyLLM writes no response body or error at debug" do
+ output = StringIO.new
+ logger = RubyLlmLogger.new(ActiveSupport::Logger.new(output, level: Logger::DEBUG))
+ stubs = Faraday::Adapter::Test::Stubs.new { _1.post("/x") { [ 401, {}, "bad key sk-secret" ] } }
+ connection = Faraday.new do |f|
+ f.response :logger, logger, bodies: true, errors: true, log_level: :debug
+ f.response :raise_error
+ f.adapter :test, stubs
+ end
+
+ assert_raises(Faraday::UnauthorizedError) { connection.post("/x") }
+ assert_empty output.string
+ end
+
+ test "RubyLLM publishes its events through ActiveSupport::Notifications" do
+ assert_equal ActiveSupport::Notifications, RubyLLM.config.instrumenter
+ end
+end
diff --git a/test/models/ai/tokens_test.rb b/test/models/ai/tokens_test.rb
new file mode 100644
index 0000000000..b9f7e1f3eb
--- /dev/null
+++ b/test/models/ai/tokens_test.rb
@@ -0,0 +1,39 @@
+require "test_helper"
+
+class Ai::TokensTest < ActiveSupport::TestCase
+ test "the prompt counts cached tokens, which RubyLLM's input leaves out" do
+ tokens = Ai::Tokens.from_ruby_llm(RubyLLM::Tokens.new(input: 512, output: 40, cache_read: 11_945, cache_write: 0))
+
+ assert_equal 512, tokens.input_tokens
+ assert_equal 12_457, tokens.prompt_tokens
+ assert_equal 12_497, tokens.total_tokens
+ end
+
+ test "the prompt counts cache writes too" do
+ tokens = Ai::Tokens.from_ruby_llm(RubyLLM::Tokens.new(input: 20, output: 10, cache_read: 100, cache_write: 1_000))
+
+ assert_equal 1_120, tokens.prompt_tokens
+ assert_equal 1_130, tokens.total_tokens
+ end
+
+ test "counts a provider didn't report stay unknown" do
+ tokens = Ai::Tokens.from_ruby_llm(nil)
+
+ assert_not tokens.known?
+ assert_nil tokens.prompt_tokens
+ assert_nil tokens.total_tokens
+ end
+
+ test "a reported cost wins over an estimate" do
+ tokens = RubyLLM::Tokens.new(input: 100, output: 10, reported_cost: 0.0042)
+
+ assert_in_delta 0.0042, Ai::Tokens.from_ruby_llm(tokens, 9.99).cost
+ assert_in_delta 0.5, Ai::Tokens.from_ruby_llm(RubyLLM::Tokens.new(input: 1), 0.5).cost
+ end
+
+ test "a negative or non-finite cost is dropped, so the row is kept and its cost estimated" do
+ assert_in_delta 0.5, Ai::Tokens.from_ruby_llm(RubyLLM::Tokens.new(input: 1, reported_cost: -0.1), 0.5).cost
+ assert_nil Ai::Tokens.from_ruby_llm(RubyLLM::Tokens.new(input: 1), -1).cost
+ assert_nil Ai::Tokens.from_ruby_llm(RubyLLM::Tokens.new(input: 1), Float::NAN).cost
+ end
+end
diff --git a/test/models/ai/transport/http_test.rb b/test/models/ai/transport/http_test.rb
new file mode 100644
index 0000000000..55cbfefbf6
--- /dev/null
+++ b/test/models/ai/transport/http_test.rb
@@ -0,0 +1,121 @@
+require "test_helper"
+
+class Ai::Transport::HttpTest < ActiveSupport::TestCase
+ Http = Ai::Transport::Http
+ PROXY = "http://proxy.internal:8888"
+
+ test "HTTPS_PROXY is used, then HTTP_PROXY, whatever the target's scheme" do
+ assert_equal PROXY, Http.proxy_for("https://api.anthropic.com", env: { "HTTPS_PROXY" => PROXY })
+ assert_equal PROXY, Http.proxy_for("http://llm.lan:8080", env: { "HTTPS_PROXY" => PROXY })
+ assert_equal PROXY, Http.proxy_for("https://api.openai.com", env: { "HTTP_PROXY" => PROXY })
+ assert_equal "http://a:1", Http.proxy_for("https://x.test", env: { "HTTPS_PROXY" => "http://a:1", "HTTP_PROXY" => "http://b:2" })
+ assert_nil Http.proxy_for("https://api.openai.com", env: {})
+ end
+
+ test "loopback is never proxied, as Ruby's own lookup doesn't" do
+ env = { "HTTPS_PROXY" => PROXY }
+
+ %w[http://127.0.0.1:8080 http://127.1.2.3:11434 http://localhost:1234 http://[::1]:8080].each do |url|
+ assert_nil Http.proxy_for(url, env:), url
+ end
+ end
+
+ test "NO_PROXY matches the host as written, with CIDR blocks" do
+ env = { "HTTPS_PROXY" => PROXY, "NO_PROXY" => "llm.lan,10.0.0.0/8" }
+
+ assert_nil Http.proxy_for("http://llm.lan:8080", env:)
+ assert_nil Http.proxy_for("http://10.72.200.61:8180", env:)
+ assert_equal PROXY, Http.proxy_for("http://other.lan:8080", env:)
+ end
+
+ test "a host named by DNS goes direct when its address is in a NO_PROXY CIDR block" do
+ IPSocket.stubs(:getaddress).with("llm.internal").returns("10.72.200.61")
+ env = { "HTTPS_PROXY" => PROXY, "NO_PROXY" => "10.0.0.0/8" }
+
+ assert_nil Http.proxy_for("http://llm.internal:8180", env:)
+ IPSocket.stubs(:getaddress).with("api.openai.com").returns("162.159.140.245")
+ assert_equal PROXY, Http.proxy_for("https://api.openai.com", env:)
+ end
+
+ test "a name is never resolved when NO_PROXY lists only names" do
+ IPSocket.expects(:getaddress).never
+
+ assert_nil Http.proxy_for("http://llm.lan:8080", env: { "HTTPS_PROXY" => PROXY, "NO_PROXY" => "llm.lan" })
+ end
+
+ test "a NO_PROXY entry with a leading dot covers the domain itself and its subdomains" do
+ env = { "HTTPS_PROXY" => PROXY, "NO_PROXY" => "other.test, .agents.example.com" }
+
+ assert_nil Http.proxy_for("https://agents.example.com", env:)
+ assert_nil Http.proxy_for("https://eu.agents.example.com", env:)
+ assert_equal PROXY, Http.proxy_for("https://badagents.example.com", env:)
+ end
+
+ test "NO_PROXY=* sends every host direct" do
+ assert_nil Http.proxy_for("https://api.openai.com", env: { "HTTPS_PROXY" => PROXY, "NO_PROXY" => "*" })
+ assert_nil Http.proxy_for("http://llm.lan:8080", env: { "HTTP_PROXY" => PROXY, "no_proxy" => " * " })
+ end
+
+ test "the models list goes to the same server as the chat calls it checks" do
+ full = Ai::Config::Endpoint.new(name: "gw", protocol: :compatible, base_url: "https://gw.example.test/v1/chat/completions", api_key: "k")
+ openrouter = Ai::Config::Endpoint.new(name: "or", protocol: :compatible, preset: :openrouter, api_key: "or-key")
+ stub_request(:get, "https://gw.example.test/v1/models").to_return(status: 200, body: { data: [] }.to_json, headers: { "Content-Type" => "application/json" })
+ stub_request(:get, "https://openrouter.ai/api/v1/models").to_return(status: 200, body: { data: [] }.to_json, headers: { "Content-Type" => "application/json" })
+
+ Http.openai_client(full).models.list
+ Http.openai_client(openrouter).models.list
+
+ assert_requested :get, "https://gw.example.test/v1/models"
+ assert_requested :get, "https://openrouter.ai/api/v1/models", headers: { "Authorization" => "Bearer or-key" }
+ assert_not_requested :get, %r{api\.openai\.com}
+ end
+
+ test "net_http_proxy returns a URI for Net::HTTP" do
+ uri = Http.net_http_proxy("https://agent.example.test", env: { "HTTPS_PROXY" => "http://user:[email protected]:8888" })
+
+ assert_equal [ "proxy.internal", 8888, "user", "pw" ], [ uri.host, uri.port, uri.user, uri.password ]
+ end
+
+ test "compatible base URLs follow ruby-openai's rule, so today's URLs keep working" do
+ {
+ nil => "https://api.openai.com/v1",
+ "http://llm:8080" => "http://llm:8080/v1",
+ "http://llm:8080/" => "http://llm:8080/v1",
+ "http://ollama:11434/v1/" => "http://ollama:11434/v1",
+ "https://generativelanguage.googleapis.com/v1beta/openai/" => "https://generativelanguage.googleapis.com/v1beta/openai",
+ "https://api.cloudflare.com/client/v4/accounts/a/ai/v1" => "https://api.cloudflare.com/client/v4/accounts/a/ai/v1",
+ "http://agent:18789/v1/chat/completions" => "http://agent:18789/v1"
+ }.each do |given, expected|
+ assert_equal expected, Http.compatible_base(given), given.inspect
+ end
+ end
+
+ test "headers leave out per-chat {session_id} values" do
+ endpoint = ai_endpoint(extra_headers: { "X-Team" => "home", "X-Session" => "sure-{session_id}" })
+
+ assert_equal({ "X-Team" => "home" }, Http.headers(endpoint))
+ end
+
+ test "the ruby-openai client gets the endpoint's settings and the resolved proxy" do
+ endpoint = ai_endpoint(base_url: "https://llm.example.test/v1", extra_headers: { "X-Team" => "home" }, timeout_seconds: 7)
+
+ with_env_overrides("HTTPS_PROXY" => PROXY, "NO_PROXY" => nil, "no_proxy" => nil) do
+ client = Http.openai_client(endpoint)
+ connection = Faraday.new.tap { client.faraday_middleware.call(_1) }
+
+ assert_equal 7, client.request_timeout
+ assert_equal({ "X-Team" => "home" }, client.extra_headers)
+ assert_equal URI(PROXY), connection.proxy.uri
+ end
+ end
+
+ test "a direct client stops Faraday's own proxy lookup" do
+ endpoint = ai_endpoint(base_url: "http://127.0.0.1:8080/v1")
+
+ with_env_overrides("HTTP_PROXY" => PROXY) do
+ connection = Faraday.new.tap { Http.openai_client(endpoint).faraday_middleware.call(_1) }
+
+ assert_nil connection.proxy
+ end
+ end
+end
diff --git a/test/models/ai/transport/ruby_llm_adapter_test.rb b/test/models/ai/transport/ruby_llm_adapter_test.rb
new file mode 100644
index 0000000000..63782c9651
--- /dev/null
+++ b/test/models/ai/transport/ruby_llm_adapter_test.rb
@@ -0,0 +1,23 @@
+require "test_helper"
+
+class Ai::Transport::RubyLlmAdapterTest < ActiveSupport::TestCase
+ setup do
+ @transport = Ai::Transport.for(ai_endpoint(api_key: "sk-test-secret-123456"))
+ end
+
+ test "an option RubyLLM refuses becomes Refused" do
+ error = assert_raises(Ai::Error::Refused) do
+ @transport.send(:mapping_errors) { RubyLLM::Attachment.new("statement.pdf", resolution: :huge) }
+ end
+
+ assert_match "resolution must be one of", error.message
+ end
+
+ test "an ArgumentError from Sure's own code stays a bug" do
+ assert_raises(ArgumentError) { @transport.send(:mapping_errors) { Integer("not a number") } }
+ end
+
+ test "a wrong call into RubyLLM stays a bug" do
+ assert_raises(ArgumentError) { @transport.send(:mapping_errors) { RubyLLM::Attachment.new } }
+ end
+end
diff --git a/test/models/ai_health/probe/synthetic_pdf_test.rb b/test/models/ai_health/probe/synthetic_pdf_test.rb
new file mode 100644
index 0000000000..14b00111bf
--- /dev/null
+++ b/test/models/ai_health/probe/synthetic_pdf_test.rb
@@ -0,0 +1,10 @@
+require "test_helper"
+
+class AiHealth::Probe::SyntheticPdfTest < ActiveSupport::TestCase
+ test "is a valid one-page PDF holding only the synthetic statement" do
+ reader = PDF::Reader.new(StringIO.new(AiHealth::Probe::SyntheticPdf.bytes))
+
+ assert_equal 1, reader.page_count
+ AiHealth::Probe::SyntheticPdf::LINES.each { assert_includes reader.pages.first.text, _1 }
+ end
+end
diff --git a/test/models/ai_health/probe_test.rb b/test/models/ai_health/probe_test.rb
index 364431d524..8a05721862 100644
--- a/test/models/ai_health/probe_test.rb
+++ b/test/models/ai_health/probe_test.rb
@@ -27,6 +27,43 @@ class AiHealth::ProbeTest < ActiveSupport::TestCase
assert_requested request
end
+ test "Ollama's `:latest` listing counts as the model it aliases; another tag doesn't" do
+ stub_request(:get, "https://ollama.example.test/v1/models")
+ .to_return(status: 200, headers: { "Content-Type" => "application/json" },
+ body: { data: [ { id: "llama3:latest" }, { id: "qwen3:8b" } ] }.to_json)
+
+ probe = ->(model) { @probe.llm(provider: :openai, endpoint: "https://ollama.example.test/v1", access_token: "t", model:) }
+
+ assert probe.call("llama3").passing?
+ assert_equal "model_not_available", probe.call("qwen3").failure_code.to_s
+ end
+
+ test "a 200 whose body isn't JSON is an invalid response, not a refusal" do
+ stub_request(:get, "https://api.openai.example.test/v1/models")
+ .to_return(status: 200, headers: { "Content-Type" => "application/json" }, body: "<html>login</html>")
+
+ result = @probe.llm(provider: :openai, endpoint: "https://api.openai.example.test/v1", access_token: "t", model: "gpt-4.1")
+
+ assert_equal "invalid_response", result.failure_code.to_s
+ end
+
+ test "a rejected key on the vector store is reported by name" do
+ stub_request(:get, "https://api.openai.example.test/v1/vector_stores?limit=1")
+ .to_return(status: 401, headers: { "Content-Type" => "application/json" }, body: { error: { message: "bad key" } }.to_json)
+
+ result = @probe.openai_vector_store(endpoint: "https://api.openai.example.test/v1", access_token: "t")
+
+ assert_equal [ "unauthorized", 401 ], [ result.failure_code.to_s, result.http_status ]
+ end
+
+ test "an unsupported provider is a failing result, not an exception" do
+ result = @probe.llm(provider: :mistral, endpoint: "https://api.mistral.example.test/v1", access_token: "token", model: "small")
+
+ assert result.failing?
+ assert_equal "unsupported_provider", result.failure_code.to_s
+ assert_not_requested :any, /mistral/
+ end
+
test "timeout honors AI_HEALTH_PROBE_TIMEOUT and falls back for missing or non-positive values" do
ClimateControl.modify(AI_HEALTH_PROBE_TIMEOUT: "42") do
assert_equal 42, AiHealth::Probe.timeout
@@ -72,42 +109,57 @@ class AiHealth::ProbeTest < ActiveSupport::TestCase
end
end
- test "OpenAI-compatible LLM probe calls chat completions instead of the models endpoint" do
+ test "OpenAI-compatible LLM probe lists models too, making no chat call" do
endpoint = "https://api.cloudflare.com/client/v4/accounts/account-id/ai/v1"
- request = stub_request(:post, "#{endpoint}/chat/completions")
- .with(
- headers: { "Authorization" => "Bearer cf-token" },
- body: {
- model: "@cf/zai-org/glm-5.2",
- messages: [ { role: "user", content: AiHealth::Probe::CHAT_TEST_INPUT } ]
- }
- )
- .to_return(
- status: 200,
- headers: { "Content-Type" => "application/json" },
- body: { choices: [ { message: { content: "OK" } } ] }.to_json
- )
+ request = stub_request(:get, "#{endpoint}/models")
+ .with(headers: { "Authorization" => "Bearer cf-token" })
+ .to_return(status: 200, headers: { "Content-Type" => "application/json" },
+ body: { data: [ { id: "@cf/zai-org/glm-5.2" } ] }.to_json)
+ chat = stub_request(:post, "#{endpoint}/chat/completions")
result = @probe.llm(
provider: :openai,
endpoint: endpoint,
access_token: "cf-token",
- model: "@cf/zai-org/glm-5.2",
- openai_compatible: true
+ model: "@cf/zai-org/glm-5.2"
)
assert result.passing?
- assert result.checked_at
assert_requested request
+ assert_not_requested chat
+ end
+
+ test "LLM probe sends OPENAI_EXTRA_HEADERS, as production calls do" do
+ request = stub_request(:get, "https://llm.example.test/v1/models")
+ .with(headers: { "X-Team" => "home" })
+ .to_return(status: 200, headers: { "Content-Type" => "application/json" }, body: { data: [ { id: "qwen3" } ] }.to_json)
+
+ ClimateControl.modify(OPENAI_EXTRA_HEADERS: { "X-Team" => "home" }.to_json) do
+ assert @probe.llm(provider: :openai, endpoint: "https://llm.example.test/v1", access_token: "t", model: "qwen3").passing?
+ end
+ assert_requested request
+ end
+
+ test "LLM probe reports a spent balance and a wrong key by name" do
+ stub_request(:get, "https://llm.example.test/v1/models").to_return(
+ { status: 429, headers: { "Content-Type" => "application/json" }, body: { error: { message: "no credits", code: "insufficient_quota" } }.to_json },
+ { status: 401, headers: { "Content-Type" => "application/json" }, body: { error: { message: "Invalid API key" } }.to_json }
+ )
+ Rails.logger.stubs(:error)
+ DebugLogEntry.stubs(:capture)
+
+ spent = AiHealth::Probe.new(cache: @cache, force: true).llm(provider: :openai, endpoint: "https://llm.example.test/v1", access_token: "t", model: "m")
+ wrong = AiHealth::Probe.new(cache: @cache, force: true).llm(provider: :openai, endpoint: "https://llm.example.test/v1", access_token: "t", model: "m")
+
+ assert_equal [ :no_credit, 429 ], [ spent.failure_code, spent.http_status ]
+ assert_equal [ :unauthorized, 401 ], [ wrong.failure_code, wrong.http_status ]
end
test "Anthropic LLM probe calls the models endpoint and verifies the configured model" do
- model_info = Struct.new(:id).new("claude-sonnet-4-6")
- models = mock("models")
- models.expects(:retrieve).with("claude-sonnet-4-6").returns(model_info)
- client = mock("anthropic_client")
- client.expects(:models).returns(models)
- @probe.stubs(:anthropic_client).returns(client)
+ request = stub_request(:get, "https://api.anthropic.com/v1/models/claude-sonnet-4-6")
+ .with(headers: { "X-Api-Key" => "anthropic-token" })
+ .to_return(status: 200, headers: { "Content-Type" => "application/json" },
+ body: { id: "claude-sonnet-4-6", type: "model", display_name: "Claude Sonnet 4.6", created_at: "2026-01-01T00:00:00Z" }.to_json)
result = @probe.llm(
provider: :anthropic,
@@ -117,15 +169,58 @@ class AiHealth::ProbeTest < ActiveSupport::TestCase
)
assert result.passing?
+ assert_requested request
end
- test "synthetic PDF is valid and contains no customer data" do
- pdf = @probe.send(:synthetic_pdf)
- reader = PDF::Reader.new(StringIO.new(pdf))
+ test "the Anthropic models probe takes its proxy from Sure's resolver, as the calls it checks do" do
+ url = "https://api.anthropic.com/v1/models/claude-sonnet-4-6"
+ Ai::Transport::Http.stubs(:proxy_for).returns(nil)
+ Ai::Transport::Http.expects(:proxy_for).with(url).returns("http://proxy.example.test:3128").at_least_once
+ stub_request(:get, url).to_return(status: 200, headers: { "Content-Type" => "application/json" }, body: { id: "claude-sonnet-4-6" }.to_json)
- assert_equal 1, reader.page_count
- AiHealth::Probe::PDF_TEST_LINES.each do |line|
- assert_includes reader.pages.first.text, line
+ result = @probe.llm(provider: :anthropic, endpoint: "https://api.anthropic.com", access_token: "anthropic-token", model: "claude-sonnet-4-6")
+
+ assert result.passing?
+ end
+
+ test "an Anthropic lookup answered for another model fails; a dated snapshot of an alias passes" do
+ url = "https://api.anthropic.com/v1/models/claude-sonnet-4-6"
+ transport = Ai::Transport.for(Ai::Config::Endpoint.new(name: "anthropic", protocol: :anthropic, api_key: "anthropic-token"))
+ model = Ai::Config::Model.new(endpoint: transport.endpoint, name: "claude-sonnet-4-6")
+
+ stub_request(:get, url).to_return(status: 200, headers: { "Content-Type" => "application/json" }, body: { id: "claude-haiku-4-5" }.to_json)
+ assert_raises(Ai::Error::ModelMissing) { transport.probe(model, :models) }
+
+ stub_request(:get, url).to_return(status: 200, headers: { "Content-Type" => "application/json" }, body: { id: "claude-sonnet-4-6-20260101" }.to_json)
+ assert_equal "claude-sonnet-4-6-20260101", transport.probe(model, :models)
+ end
+
+ test "an Anthropic model the API doesn't have fails the models probe" do
+ stub_request(:get, "https://api.anthropic.com/v1/models/claude-nope")
+ .to_return(status: 404, headers: { "Content-Type" => "application/json" },
+ body: { type: "error", error: { type: "not_found_error", message: "model: claude-nope" } }.to_json)
+ Rails.logger.stubs(:error)
+ DebugLogEntry.stubs(:capture)
+
+ result = @probe.llm(provider: :anthropic, endpoint: "https://api.anthropic.com", access_token: "anthropic-token", model: "claude-nope")
+
+ assert_not result.passing?
+ assert_equal 404, result.http_status
+ assert_equal "model_not_available", result.failure_code.to_s
+ end
+
+ test "an Anthropic lookup maps by status whatever the body, and a garbled 200 is invalid output" do
+ url = "https://api.anthropic.com/v1/models/claude-sonnet-4-6"
+ transport = Ai::Transport.for(Ai::Config::Endpoint.new(name: "anthropic", protocol: :anthropic, api_key: "anthropic-token"))
+ model = Ai::Config::Model.new(endpoint: transport.endpoint, name: "claude-sonnet-4-6")
+ {
+ { status: 503, body: { error: "busy" }.to_json } => Ai::Error::Upstream,
+ { status: 404, body: "<html>not here</html>" } => Ai::Error::Refused,
+ { status: 200, body: "<html>sign in</html>" } => Ai::Error::InvalidOutput
+ }.each do |response, error|
+ stub_request(:get, url).to_return(**response, headers: { "Content-Type" => "application/json" })
+
+ assert_raises(error, response.inspect) { transport.probe(model, :models) }
end
end
@@ -138,7 +233,7 @@ class AiHealth::ProbeTest < ActiveSupport::TestCase
document_type: "bank_statement",
summary: "A synthetic bank statement containing no customer data.",
extracted_data: {
- institution_name: AiHealth::Probe::PDF_TEST_INSTITUTION
+ institution_name: AiHealth::Probe::SyntheticPdf::INSTITUTION
}
}.to_json
}
@@ -151,7 +246,7 @@ class AiHealth::ProbeTest < ActiveSupport::TestCase
captured = params
true
end.returns(response)
- @probe.stubs(:openai_client).returns(client)
+ Ai::Transport::Http.stubs(:openai_client).returns(client)
Provider::Openai::PdfProcessor.any_instance.expects(:convert_pdf_to_images).never
result = @probe.pdf_text_extraction(
@@ -165,8 +260,8 @@ class AiHealth::ProbeTest < ActiveSupport::TestCase
assert result.passing?
instructions = captured.dig(:parameters, :messages, 0, :content)
document_text = captured.dig(:parameters, :messages, 1, :content)
- assert_not_includes instructions, AiHealth::Probe::PDF_TEST_INSTITUTION
- assert_includes document_text, AiHealth::Probe::PDF_TEST_INSTITUTION
+ assert_not_includes instructions, AiHealth::Probe::SyntheticPdf::INSTITUTION
+ assert_includes document_text, AiHealth::Probe::SyntheticPdf::INSTITUTION
end
test "PDF vision probe exercises only the OpenAI vision processor and validates its result" do
@@ -178,7 +273,7 @@ class AiHealth::ProbeTest < ActiveSupport::TestCase
document_type: "bank_statement",
summary: "A synthetic bank statement containing no customer data.",
extracted_data: {
- institution_name: AiHealth::Probe::PDF_TEST_INSTITUTION
+ institution_name: AiHealth::Probe::SyntheticPdf::INSTITUTION
}
}.to_json
}
@@ -191,7 +286,7 @@ class AiHealth::ProbeTest < ActiveSupport::TestCase
captured = params
true
end.returns(response)
- @probe.stubs(:openai_client).returns(client)
+ Ai::Transport::Http.stubs(:openai_client).returns(client)
Provider::Openai::PdfProcessor.any_instance.expects(:convert_pdf_to_images).once.returns([ "encoded-page" ])
result = @probe.pdf_vision_processing(
@@ -204,7 +299,7 @@ class AiHealth::ProbeTest < ActiveSupport::TestCase
assert result.passing?
instructions = captured.dig(:parameters, :messages, 0, :content)
- assert_not_includes instructions, AiHealth::Probe::PDF_TEST_INSTITUTION
+ assert_not_includes instructions, AiHealth::Probe::SyntheticPdf::INSTITUTION
end
test "PDF processing probes require the expected institution in the standard result fields" do
@@ -222,7 +317,7 @@ class AiHealth::ProbeTest < ActiveSupport::TestCase
]
}
client = stub(chat: response)
- @probe.stubs(:openai_client).returns(client)
+ Ai::Transport::Http.stubs(:openai_client).returns(client)
Provider::Openai::PdfProcessor.any_instance.stubs(:convert_pdf_to_images).returns([ "encoded-page" ])
Rails.logger.stubs(:error)
DebugLogEntry.stubs(:capture)
@@ -248,7 +343,7 @@ class AiHealth::ProbeTest < ActiveSupport::TestCase
document_type: :bank_statement,
summary: "A synthetic bank statement containing no customer data.",
extracted_data: {
- institution_name: AiHealth::Probe::PDF_TEST_INSTITUTION
+ institution_name: AiHealth::Probe::SyntheticPdf::INSTITUTION
}
}
)
@@ -258,12 +353,12 @@ class AiHealth::ProbeTest < ActiveSupport::TestCase
source = params.dig(:messages, 0, :content, 0, :source)
extracted_data_schema = params.dig(:tools, 0, :input_schema, :properties, :extracted_data)
source[:media_type] == "application/pdf" &&
- Base64.strict_decode64(source[:data]) == @probe.send(:synthetic_pdf) &&
+ Base64.strict_decode64(source[:data]) == AiHealth::Probe::SyntheticPdf.bytes &&
extracted_data_schema[:properties].key?(:institution_name) &&
extracted_data_schema[:required].empty? &&
- !params[:system_].include?(AiHealth::Probe::PDF_TEST_INSTITUTION)
+ !params[:system_].include?(AiHealth::Probe::SyntheticPdf::INSTITUTION)
end.returns(response)
- @probe.stubs(:anthropic_client).returns(stub(messages: messages))
+ Ai::Transport::Http.stubs(:anthropic_client).returns(stub(messages: messages))
result = @probe.pdf_vision_processing(
provider: :anthropic,
@@ -277,7 +372,7 @@ class AiHealth::ProbeTest < ActiveSupport::TestCase
test "failed LLM probe writes a system-wide debug entry and Rails log without secrets" do
models = stub(list: { "data" => [ { "id" => "another-model" } ] })
- @probe.stubs(:openai_client).returns(stub(models: models))
+ Ai::Transport::Http.stubs(:openai_client).returns(stub(models: models))
endpoint = URI::HTTP.build(
userinfo: "operator:uri-secret",
host: "ollama",
@@ -322,7 +417,7 @@ class AiHealth::ProbeTest < ActiveSupport::TestCase
models = mock("models")
models.expects(:list).once.returns({ "data" => [ { "id" => "gpt-4.1" } ] })
client = stub(models: models)
- @probe.stubs(:openai_client).returns(client)
+ Ai::Transport::Http.stubs(:openai_client).returns(client)
2.times do
result = @probe.llm(
@@ -339,7 +434,7 @@ class AiHealth::ProbeTest < ActiveSupport::TestCase
models = mock("models")
models.expects(:list).twice.returns({ "data" => [ { "id" => "gpt-4.1" } ] })
client = stub(models: models)
- @probe.stubs(:openai_client).returns(client)
+ Ai::Transport::Http.stubs(:openai_client).returns(client)
arguments = {
provider: :openai,
@@ -350,7 +445,6 @@ class AiHealth::ProbeTest < ActiveSupport::TestCase
@probe.llm(**arguments)
forced_probe = AiHealth::Probe.new(cache: @cache, force: true)
- forced_probe.stubs(:openai_client).returns(client)
assert forced_probe.llm(**arguments).passing?
end
@@ -385,15 +479,12 @@ class AiHealth::ProbeTest < ActiveSupport::TestCase
test "embedding probe sends a small request and verifies dimensions" do
request = stub_request(:post, "http://ollama.example.test:11434/v1/embeddings")
.with(
- body: {
- model: "nomic-embed-text",
- input: AiHealth::Probe::EMBEDDING_TEST_INPUT
- }
+ body: hash_including(model: "nomic-embed-text", input: Ai::Transport::Base::PROBE_EMBEDDING_INPUT)
)
.to_return(
status: 200,
headers: { "Content-Type" => "application/json" },
- body: { data: [ { embedding: [ 0.1, 0.2, 0.3 ] } ] }.to_json
+ body: { data: [ { embedding: [ 0.1, 0.2, 0.3 ] } ], model: "nomic-embed-text", usage: { prompt_tokens: 4, total_tokens: 4 } }.to_json
)
result = @probe.embedding(
@@ -407,11 +498,37 @@ class AiHealth::ProbeTest < ActiveSupport::TestCase
assert_requested request
end
+ test "embedding probe posts to the base URL as given, as VectorStore::Embeddable does" do
+ request = stub_request(:post, "http://gateway.example.test/api/embeddings").to_return(
+ status: 200, headers: { "Content-Type" => "application/json" },
+ body: { data: [ { embedding: [ 0.1, 0.2, 0.3 ] } ], model: "nomic-embed-text", usage: { prompt_tokens: 4, total_tokens: 4 } }.to_json
+ )
+
+ result = @probe.embedding(endpoint: "http://gateway.example.test/api", access_token: nil, model: "nomic-embed-text", dimensions: 3)
+
+ assert result.passing?
+ assert_requested request
+ end
+
+ test "embedding probe fails on a vector with a component that isn't a finite number" do
+ stub_request(:post, "http://ollama:11434/v1/embeddings").to_return(
+ status: 200, headers: { "Content-Type" => "application/json" },
+ body: { data: [ { embedding: [ 0.1, nil, 0.3 ] } ], model: "nomic-embed-text", usage: { prompt_tokens: 4, total_tokens: 4 } }.to_json
+ )
+ Rails.logger.stubs(:error)
+ DebugLogEntry.stubs(:capture)
+
+ result = @probe.embedding(endpoint: "http://ollama:11434/v1", access_token: nil, model: "nomic-embed-text", dimensions: 3)
+
+ assert result.failing?
+ assert_equal :invalid_response, result.failure_code
+ end
+
test "embedding probe fails when returned dimensions do not match configuration" do
- response = Struct.new(:body).new({ "data" => [ { "embedding" => [ 0.1, 0.2 ] } ] })
- client = stub
- client.stubs(:post).yields(Struct.new(:body).new).returns(response)
- @probe.stubs(:embedding_client).returns(client)
+ stub_request(:post, "http://ollama:11434/v1/embeddings").to_return(
+ status: 200, headers: { "Content-Type" => "application/json" },
+ body: { data: [ { embedding: [ 0.1, 0.2 ] } ], model: "nomic-embed-text", usage: { prompt_tokens: 4, total_tokens: 4 } }.to_json
+ )
Rails.logger.stubs(:error)
DebugLogEntry.stubs(:capture)
@@ -434,17 +551,23 @@ class AiHealth::ProbeTest < ActiveSupport::TestCase
tool = body.dig("tools", 0, "function")
body["model"] == "tools-model" &&
- body.dig("messages", 0, "content") == AiHealth::Probe::FUNCTION_CALL_TEST_INPUT &&
- tool["name"] == AiHealth::Probe::FUNCTION_CALL_TEST_TOOL[:name] &&
- tool["strict"] == true
+ body.dig("messages", 0, "content") == Ai::Transport::Base::PROBE_TOOL_PROMPT &&
+ tool["name"] == Ai::Transport::Base::PROBE_TOOL_NAME &&
+ tool["strict"] == true &&
+ tool["parameters"] == Ai::Transport::Base::PROBE_TOOL_SCHEMA.deep_stringify_keys
}
.to_return(
status: 200,
headers: { "Content-Type" => "application/json" },
body: {
+ id: "chatcmpl-1",
+ model: "tools-model",
choices: [
{
+ index: 0,
+ finish_reason: "tool_calls",
message: {
+ role: "assistant",
tool_calls: [
{ id: "call_1", type: "function", function: { name: "sure_health_check", arguments: "{}" } }
]
@@ -562,12 +685,13 @@ class AiHealth::ProbeTest < ActiveSupport::TestCase
.with { |req|
tool = JSON.parse(req.body).dig("tools", 0)
- tool["type"] == "function" && tool["name"] == AiHealth::Probe::FUNCTION_CALL_TEST_TOOL[:name]
+ tool["type"] == "function" && tool["name"] == Ai::Transport::Base::PROBE_TOOL_NAME && tool["strict"] == true
}
.to_return(
status: 200,
headers: { "Content-Type" => "application/json" },
- body: { output: [ { type: "function_call", name: "sure_health_check", arguments: "{}" } ] }.to_json
+ body: { id: "resp_1", model: "gpt-4.1", status: "completed",
+ output: [ { type: "function_call", id: "fc_1", call_id: "call_1", name: "sure_health_check", arguments: "{}" } ] }.to_json
)
result = @probe.function_calling(
@@ -583,13 +707,13 @@ class AiHealth::ProbeTest < ActiveSupport::TestCase
end
test "function-calling probe reads an Anthropic tool_use block" do
- response = Struct.new(:content).new([ Struct.new(:type, :name).new(:tool_use, "sure_health_check") ])
- messages = mock("anthropic_messages")
- messages.expects(:create).with do |params|
- params[:tools].first[:input_schema] == AiHealth::Probe::FUNCTION_CALL_TEST_TOOL[:schema] &&
- !params[:tools].first.key?(:strict)
- end.returns(response)
- @probe.stubs(:anthropic_client).returns(stub(messages: messages))
+ request = stub_request(:post, "https://api.anthropic.com/v1/messages")
+ .with { |req| JSON.parse(req.body).dig("tools", 0, "input_schema") == Ai::Transport::Base::PROBE_TOOL_SCHEMA.deep_stringify_keys }
+ .to_return(status: 200, headers: { "Content-Type" => "application/json" }, body: {
+ id: "msg_1", type: "message", role: "assistant", model: "claude-sonnet-4-6", stop_reason: "tool_use",
+ content: [ { type: "tool_use", id: "toolu_1", name: "sure_health_check", input: { status: "ok" } } ],
+ usage: { input_tokens: 20, output_tokens: 10 }
+ }.to_json)
result = @probe.function_calling(
provider: :anthropic,
@@ -599,6 +723,13 @@ class AiHealth::ProbeTest < ActiveSupport::TestCase
)
assert result.passing?
+ assert_requested request
+ end
+
+ test "probes build no clients of their own" do
+ source = Rails.root.join("app/models/ai_health/probe.rb").read
+
+ assert_no_match(/(OpenAI::Client|Anthropic::Client|Faraday)\.new\b/, source)
end
private
diff --git a/test/models/assistant/external/client_test.rb b/test/models/assistant/external/client_test.rb
index a3c5a6a1b5..463d6dab36 100644
--- a/test/models/assistant/external/client_test.rb
+++ b/test/models/assistant/external/client_test.rb
@@ -229,8 +229,24 @@ class Assistant::External::ClientTest < ActiveSupport::TestCase
client.chat(messages: [ { role: "user", content: "test" } ]) { |_| }
end
- # Should NOT pass proxy args — only host and port
- assert_equal 2, captured_args.length
+ assert_nil captured_args[2], "no proxy for a NO_PROXY host"
+ end
+
+ test "an http gateway goes through HTTPS_PROXY when only it is set, and loopback never does" do
+ captured = []
+ mock_http = stub("http", :use_ssl= => nil, :open_timeout= => nil, :read_timeout= => nil)
+ mock_response = stub("response", code: "200", read_body: nil)
+ mock_response.stubs(:is_a?).with(Net::HTTPSuccess).returns(true)
+ mock_http.stubs(:request).yields(mock_response)
+ Net::HTTP.stubs(:new).with { |*args| captured << args }.returns(mock_http)
+
+ ClimateControl.modify(HTTPS_PROXY: "http://proxy:8888", HTTP_PROXY: nil, NO_PROXY: "127.0.0.0/8") do
+ [ "http://openclaw.lan:18789/v1/chat", "http://127.0.0.1:18789/v1/chat", "http://localhost:18789/v1/chat" ].each do |url|
+ Assistant::External::Client.new(url:, token: "test-token").chat(messages: [ { role: "user", content: "x" } ]) { |_| }
+ end
+ end
+
+ assert_equal [ "proxy", nil, nil ], captured.map { _1[2] }
end
private
diff --git a/test/models/llm_usage/call_test.rb b/test/models/llm_usage/call_test.rb
new file mode 100644
index 0000000000..4560f58829
--- /dev/null
+++ b/test/models/llm_usage/call_test.rb
@@ -0,0 +1,73 @@
+require "test_helper"
+
+class LlmUsage::CallTest < ActiveSupport::TestCase
+ setup do
+ @family = families(:dylan_family)
+ @family.llm_usages.delete_all
+ end
+
+ test "requests sharing a call id are one call; rows without one are calls of their own" do
+ call_id = SecureRandom.uuid
+ usage(call_id:, status: "failed", created_at: 3.minutes.ago, estimated_cost: nil, metadata: { "error" => "busy" })
+ usage(call_id:, status: "succeeded", created_at: 2.minutes.ago, estimated_cost: 0.002)
+ legacy = usage(created_at: 1.minute.ago, estimated_cost: 0.001)
+
+ calls = @family.llm_usages.recent_calls
+
+ assert_equal [ legacy.id, call_id ], calls.map(&:id)
+ retried = calls.last
+ assert retried.multiple_requests?
+ assert_equal 2, retried.requests_count
+ assert_equal "succeeded", retried.status, "a call whose retry succeeded succeeded"
+ assert_equal 200, retried.prompt_tokens
+ assert_in_delta 0.002, retried.estimated_cost
+ assert_not calls.first.multiple_requests?
+ end
+
+ test "a call shows all its requests when one falls outside the date range" do
+ call_id = SecureRandom.uuid
+ usage(call_id:, status: "failed", created_at: 2.days.ago.end_of_day - 1.second, metadata: { "error" => "busy" })
+ usage(call_id:, status: "succeeded", created_at: 1.day.ago.beginning_of_day + 1.second)
+
+ call = @family.llm_usages.for_date_range(1.day.ago.beginning_of_day, Time.current).recent_calls.sole
+
+ assert_equal 2, call.requests_count
+ assert_equal "succeeded", call.status
+ end
+
+ test "statistics count calls, not requests" do
+ call_id = SecureRandom.uuid
+ 2.times { usage(call_id:, estimated_cost: 0.01) }
+ usage(estimated_cost: 0.02)
+
+ stats = LlmUsage.statistics_for_family(@family)
+
+ assert_equal 2, stats[:total_calls]
+ assert_equal 3, stats[:total_requests]
+ assert_equal 2, stats[:calls_with_cost]
+ assert_in_delta 0.02, stats[:avg_cost]
+ end
+
+ test "the average cost comes from the unrounded total, over priced calls only" do
+ usage(estimated_cost: 0.002)
+ usage(estimated_cost: nil)
+
+ assert_in_delta 0.002, LlmUsage.statistics_for_family(@family)[:avg_cost], 0.00001
+ end
+
+ test "a row the old recorders write with an error in metadata is a failed request" do
+ row = usage(metadata: { error: "HTTP 500", http_status_code: 500 })
+
+ assert row.failed?, "the recorders write symbol keys"
+ assert_equal "HTTP 500", row.reload.error_message
+ assert usage(metadata: { "error" => "busy" }).failed?
+ row.status = "exploded"
+ assert_not row.valid?
+ end
+
+ private
+ def usage(**attributes)
+ @family.llm_usages.create!(provider: "openai", model: "gpt-4.1", operation: "bill_setup", prompt_tokens: 100,
+ completion_tokens: 10, total_tokens: 110, **attributes)
+ end
+end
diff --git a/test/models/provider/openai_test.rb b/test/models/provider/openai_test.rb
index 0c46b173e7..ff2ea3e510 100644
--- a/test/models/provider/openai_test.rb
+++ b/test/models/provider/openai_test.rb
@@ -1136,6 +1136,16 @@ class Provider::OpenaiTest < ActiveSupport::TestCase
assert_equal [ 10, 5, 15 ], [ recorded.prompt_tokens, recorded.completion_tokens, recorded.total_tokens ]
end
+ test "the client takes its proxy from Ai::Transport::Http, never proxying loopback" do
+ ClimateControl.modify(HTTPS_PROXY: "http://proxy.internal:8888", HTTP_PROXY: nil, NO_PROXY: nil, no_proxy: nil) do
+ cloud = Faraday.new.tap { Provider::Openai.new("token").send(:client).faraday_middleware.call(_1) }
+ local = Faraday.new.tap { Provider::Openai.new("token", uri_base: "http://127.0.0.1:8080/v1", model: "qwen3").send(:client).faraday_middleware.call(_1) }
+
+ assert_equal URI("http://proxy.internal:8888"), cloud.proxy.uri
+ assert_nil local.proxy
+ end
+ end
+
private
# Verify the response budget at the provider-to-processor boundary.
# @param limit [Integer, nil] expected explicit cap or omitted cap
diff --git a/test/support/ai_test_helper.rb b/test/support/ai_test_helper.rb
new file mode 100644
index 0000000000..54af12a9bd
--- /dev/null
+++ b/test/support/ai_test_helper.rb
@@ -0,0 +1,26 @@
+# Helpers for testing AI code at the transport level: endpoints, models, call contexts and
+# captured events.
+module AiTestHelper
+ def ai_endpoint(name: "test", protocol: :compatible, base_url: "https://llm.example.test/v1", api_key: "test-key", **attributes)
+ Ai::Config::Endpoint.new(name:, protocol:, base_url:, api_key:, **attributes)
+ end
+
+ def ai_model(name: "test-model", endpoint: ai_endpoint, **attributes)
+ Ai::Config::Model.new(endpoint:, name:, **attributes)
+ end
+
+ # Runs the block inside a call context, as a transport would.
+ def with_ai_call_context(feature: :test, model: ai_model, family: nil, budget: nil, &block)
+ Ai::CallContext.call(feature:, model:, family:, budget:, &block)
+ end
+
+ # The `.ai` events the block emits (or any other pattern's events).
+ def capture_ai_events(pattern = /\.ai\z/)
+ events = []
+ subscriber = ActiveSupport::Notifications.subscribe(pattern) { |event| events << event }
+ yield
+ events
+ ensure
+ ActiveSupport::Notifications.unsubscribe(subscriber) if subscriber
+ end
+end
diff --git a/test/test_helper.rb b/test/test_helper.rb
index cdccda1076..2ea27cdd8f 100644
--- a/test/test_helper.rb
+++ b/test/test_helper.rb
@@ -29,6 +29,7 @@ require "uri"
require Rails.root.join("test/support/sql_query_capture").to_s
require Rails.root.join("test/support/rake_task_test_helper").to_s
require Rails.root.join("test/support/family_lock_test_helper").to_s
+require Rails.root.join("test/support/ai_test_helper").to_s
VCR.configure do |config|
config.cassette_library_dir = "test/vcr_cassettes"
@@ -89,6 +90,7 @@ module ActiveSupport
setup { Setting.clear_cache }
include SqlQueryCapture
+ include AiTestHelper
# Add more helper methods to be used by all tests here...
def sign_in(user)