diff --git a/app/models/ai/instrumentation/usage_subscriber.rb b/app/models/ai/instrumentation/usage_subscriber.rb index fde75cdc1a..0f715c0fa4 100644 --- a/app/models/ai/instrumentation/usage_subscriber.rb +++ b/app/models/ai/instrumentation/usage_subscriber.rb @@ -18,9 +18,21 @@ class Ai::Instrumentation::UsageSubscriber end private - def record_request(payload) - family = payload[:owner] + # 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) diff --git a/app/models/ai/transport/compatible.rb b/app/models/ai/transport/compatible.rb index 6880f7a4a5..89814b435c 100644 --- a/app/models/ai/transport/compatible.rb +++ b/app/models/ai/transport/compatible.rb @@ -28,14 +28,16 @@ class Ai::Transport::Compatible < Ai::Transport::Base # 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) - rescue NoMethodError, TypeError => error - raise unless raised_in_ruby_llm?(error) - - raise Ai::Error::InvalidOutput, "the embedding response isn't the expected shape" end vectors = embedding.vectors vectors = [ vectors ] if vectors.first.is_a?(Numeric) diff --git a/app/models/ai/transport/http.rb b/app/models/ai/transport/http.rb index 34d0f9cecf..cb0e59ac2f 100644 --- a/app/models/ai/transport/http.rb +++ b/app/models/ai/transport/http.rb @@ -26,11 +26,24 @@ module Ai::Transport::Http return if proxy.nil? no_proxy = env["NO_PROXY"].presence || env["no_proxy"].presence - return if no_proxy && (no_proxy.strip == "*" || !URI::Generic.use_proxy?(uri.host, uri.host, uri.port, no_proxy)) + 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:) @@ -69,7 +82,9 @@ module Ai::Transport::Http ::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. + # 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? diff --git a/app/models/ai/transport/instrumenter.rb b/app/models/ai/transport/instrumenter.rb index 8c89c71af4..73ae39fd60 100644 --- a/app/models/ai/transport/instrumenter.rb +++ b/app/models/ai/transport/instrumenter.rb @@ -3,10 +3,12 @@ # 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. - def initialize(delegate = ActiveSupport::Notifications, map_error: ->(error) { error }) + # 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) @@ -33,7 +35,9 @@ class Ai::Transport::Instrumenter end def failure_details(error) - mapped = @map_error.call(error) || 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 diff --git a/app/models/ai/transport/ruby_llm_adapter.rb b/app/models/ai/transport/ruby_llm_adapter.rb index 59796a7d03..7dc65ce613 100644 --- a/app/models/ai/transport/ruby_llm_adapter.rb +++ b/app/models/ai/transport/ruby_llm_adapter.rb @@ -22,7 +22,7 @@ module Ai::Transport::RubyLlmAdapter 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)) + config.instrumenter = Ai::Transport::Instrumenter.new(config.instrumenter, map_error: method(:mapped_error), scrub: scrubber) configure_provider(config) end end @@ -68,6 +68,11 @@ module Ai::Transport::RubyLlmAdapter 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 diff --git a/app/views/settings/llm_usages/show.html.erb b/app/views/settings/llm_usages/show.html.erb index 679c745c10..5416561785 100644 --- a/app/views/settings/llm_usages/show.html.erb +++ b/app/views/settings/llm_usages/show.html.erb @@ -105,7 +105,8 @@
-

<%= t(".recent_usage") %>

+

<%= t(".recent_usage") %>

+

<%= t(".recent_usage_scope") %>

"> <% if @llm_calls.any? %> diff --git a/config/locales/views/settings/en.yml b/config/locales/views/settings/en.yml index 021a11e0d6..b2d53583b8 100644 --- a/config/locales/views/settings/en.yml +++ b/config/locales/views/settings/en.yml @@ -106,6 +106,7 @@ en: 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" diff --git a/test/architecture/ai_transport_contract_test.rb b/test/architecture/ai_transport_contract_test.rb index a49ad7b950..2fa6701d81 100644 --- a/test/architecture/ai_transport_contract_test.rb +++ b/test/architecture/ai_transport_contract_test.rb @@ -153,9 +153,12 @@ class AiTransportContractTest < ActiveSupport::TestCase 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) do + 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 @@ -213,6 +216,19 @@ class AiTransportContractTest < ActiveSupport::TestCase 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: "login") + + 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: "{}") diff --git a/test/models/ai/call_context_test.rb b/test/models/ai/call_context_test.rb index 49eff1fd14..cadc6bbd4d 100644 --- a/test/models/ai/call_context_test.rb +++ b/test/models/ai/call_context_test.rb @@ -35,6 +35,17 @@ class Ai::CallContextTest < ActiveSupport::TestCase 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 @@ -89,6 +100,14 @@ class Ai::CallContextTest < ActiveSupport::TestCase 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) diff --git a/test/models/ai/transport/http_test.rb b/test/models/ai/transport/http_test.rb index d05f7ba02d..5401903ce1 100644 --- a/test/models/ai/transport/http_test.rb +++ b/test/models/ai/transport/http_test.rb @@ -28,6 +28,21 @@ class Ai::Transport::HttpTest < ActiveSupport::TestCase 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 "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" => " * " }) @@ -76,7 +91,7 @@ class Ai::Transport::HttpTest < ActiveSupport::TestCase 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) do + 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) } diff --git a/test/models/llm_usage/call_test.rb b/test/models/llm_usage/call_test.rb index 4333721334..4560f58829 100644 --- a/test/models/llm_usage/call_test.rb +++ b/test/models/llm_usage/call_test.rb @@ -48,10 +48,11 @@ class LlmUsage::CallTest < ActiveSupport::TestCase assert_in_delta 0.02, stats[:avg_cost] end - test "the average cost comes from the unrounded total" do + 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] + 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