Merge remote-tracking branch 'fork/feat/ai-2a-transports' into feat/ai-2b-routing

This commit is contained in:
josh-sanders
2026-11-09 22:44:39 +10:00
10 changed files with 125 additions and 14 deletions
+5 -1
View File
@@ -21,10 +21,14 @@ Ai::Tokens = Data.define(:input_tokens, :output_tokens, :cache_read_tokens, :cac
output_tokens: tokens&.output,
cache_read_tokens: tokens&.cache_read,
cache_write_tokens: tokens&.cache_write,
cost: reported || total
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)
+2 -5
View File
@@ -38,14 +38,11 @@ class Ai::Transport::Anthropic < Ai::Transport::Base
end
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.
# 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
type, message = error.is_a?(Hash) ? error.values_at("type", "message") : [ nil, error&.to_s ]
message = message.presence || "HTTP #{status}"
return Ai::Error::ModelMissing.new(message, status:) if status == 404 && type == "not_found_error" && message.start_with?("model:")
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
+27 -4
View File
@@ -35,7 +35,7 @@ class Ai::Transport::Base
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:) } }
instrument("probe", model:, request: { check: }) { attempt { run_probe(model, check, timeout: within_budget(timeout)) } }
end
end
@@ -49,7 +49,10 @@ class Ai::Transport::Base
tries = 0
begin
tries += 1
yield
check_budget!
result = yield
check_budget!(after: true)
result
rescue *Ai::Error::RETRYABLE => error
delay = retry_delay(tries)
remaining = Ai::CallContext.current&.remaining
@@ -60,6 +63,20 @@ class Ai::Transport::Base
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
@@ -100,10 +117,16 @@ class Ai::Transport::Base
# 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)
short, long = [ asked, answered ].map { model_stem(_1) }.minmax_by(&:length)
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) = name.to_s.downcase.split("/").last.to_s.delete_suffix(":latest").delete_suffix("-latest")
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
+4
View File
@@ -32,6 +32,10 @@ class Ai::Transport::Compatible < Ai::Transport::Base
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)
+2 -2
View File
@@ -17,7 +17,7 @@ module Ai::Transport::Http
# 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`.
# written, so `127.0.0.1` doesn't cover `localhost`, and `*` means every host, as curl reads it.
def proxy_for(url, env: ENV)
uri = parse(url)
return if uri&.host.blank? || loopback?(uri.host)
@@ -26,7 +26,7 @@ module Ai::Transport::Http
return if proxy.nil?
no_proxy = env["NO_PROXY"].presence || env["no_proxy"].presence
return if no_proxy && !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, uri.host, uri.port, no_proxy))
proxy
end
+12 -1
View File
@@ -77,9 +77,11 @@ module Ai::Transport::RubyLlmAdapter
# 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)
error.backtrace_locations&.first&.path.to_s.start_with?(RUBY_LLM_PATH) && !error.message.match?(ARITY_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)
@@ -110,11 +112,20 @@ module Ai::Transport::RubyLlmAdapter
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)
@@ -104,7 +104,8 @@ class AiTransportContractTest < ActiveSupport::TestCase
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 }.each do |answered, same|
{ "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
@@ -188,6 +189,37 @@ class AiTransportContractTest < ActiveSupport::TestCase
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 "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")
+29
View File
@@ -60,6 +60,35 @@ class Ai::CallContextTest < ActiveSupport::TestCase
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 "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)
+6
View File
@@ -30,4 +30,10 @@ class Ai::TokensTest < ActiveSupport::TestCase
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
+5
View File
@@ -28,6 +28,11 @@ class Ai::Transport::HttpTest < ActiveSupport::TestCase
assert_equal PROXY, Http.proxy_for("http://other.lan:8080", 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")