diff --git a/CHANGELOG.md b/CHANGELOG.md index 884b56c..215f5fa 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,12 @@ ## [Unreleased] +- Miniswen: upgrade ruby_llm to 2.1.1 (use its new built-in caching, finish reasons and reasoning replay, keep the ~10 min retry window, honor `RUBYLLM_DEBUG`, allow JSON 3). +- Miniswen: send `prompt_cache_key` for every OpenRouter model, not only Muse, so a session keeps its cache without a pinned provider order. +- Miniswen: turn on prompt caching for every model, so models that need it (like Claude, including on the Anthropic API) cache, and those that cache automatically are unaffected. +- Miniswen: OpenRouter runs cost what OpenRouter actually billed (including discounts or a pricier provider), with registry prices as the rare fallback. +- Miniswen: trajectories record which upstream provider served each OpenRouter turn. +- `lemans-remote`: forward all provider keys RubyLLM reads, not only `OPENROUTER_API_KEY`. + ## [1.5.2] - 2026-10-14 - `lemans --require/-r [command]`: load agent, backend plugins (`lemans -r plugin.rb restart RUN`) diff --git a/Gemfile b/Gemfile index c3abf3f..c0a2932 100644 --- a/Gemfile +++ b/Gemfile @@ -20,4 +20,4 @@ gem "minitest-mock", "~> 5.27" gem "rubocop", "~> 1.89" gem "rubocop-rails-omakase", require: false -gem "ruby_llm-test", "~> 0.2.0" +gem "ruby_llm-test", "~> 0.3.0" diff --git a/examples/codex/agent.rb b/examples/codex/agent.rb index 2df1e32..57c6557 100644 --- a/examples/codex/agent.rb +++ b/examples/codex/agent.rb @@ -154,8 +154,8 @@ def usage_for(events, token_usage: nil) end def priced_model - info = RubyLLM.models.find(model.to_s.split("#", 2).first, "openai") - info if info.input_price_per_million.is_a?(Numeric) && info.output_price_per_million.is_a?(Numeric) + info = RubyLLM.models.find(model.to_s.split("#", 2).first, provider: "openai") + info if info.price(:input).is_a?(Numeric) && info.price(:output).is_a?(Numeric) rescue RubyLLM::ModelNotFoundError nil end @@ -164,10 +164,10 @@ def priced_model def estimated_cost(totals, info) return unless info - input = info.input_price_per_million - output = info.output_price_per_million - cache_read = info.cache_read_input_price_per_million || input - cache_write = info.cache_write_input_price_per_million || input + input = info.price(:input) + output = info.price(:output) + cache_read = info.price(:cache_read) || input + cache_write = info.price(:cache_write) || input totals.sum do |tokens| cached = tokens["cached_input_tokens"].to_i written = tokens["cache_write_input_tokens"].to_i diff --git a/exe/lemans-remote b/exe/lemans-remote index f875909..af4e160 100755 --- a/exe/lemans-remote +++ b/exe/lemans-remote @@ -51,8 +51,9 @@ # exe/lemans-remote snapshots # exe/lemans-remote deprovision [--name SNAPSHOT] # -# Credentials come from the host ENV: DAYTONA_API_KEY (or DAYTONA_TOKEN), -# OPENROUTER_API_KEY, LEMANS_PROVIDER_ORDER (or OPENROUTER_PROVIDER_ORDER); +# Credentials come from the host ENV: DAYTONA_API_KEY (or DAYTONA_TOKEN), every +# provider key RubyLLM reads (OPENROUTER_API_KEY, ANTHROPIC_API_KEY, ...), +# LEMANS_PROVIDER_ORDER (or OPENROUTER_PROVIDER_ORDER); # forward extras with --env KEY. lib_path = File.expand_path("../lib", __dir__) @@ -101,7 +102,8 @@ module LemansRemote # :nodoc: all REMOTE_META = "/tmp/lemans-remote-run.json" REMOTE_REQUIRES_DIR = "/tmp/lemans-remote-requires" - ENV_ALLOWLIST = %w[OPENROUTER_API_KEY LEMANS_PROVIDER_ORDER OPENROUTER_PROVIDER_ORDER].freeze + ENV_ALLOWLIST = (RubyLLM::Provider.providers.values.flat_map(&:configuration_requirements).map { it.to_s.upcase } + + %w[LEMANS_PROVIDER_ORDER OPENROUTER_PROVIDER_ORDER]).uniq.freeze Backend = Lemans::Environments::Daytona diff --git a/lemans.gemspec b/lemans.gemspec index 54eafb6..e256528 100644 --- a/lemans.gemspec +++ b/lemans.gemspec @@ -32,13 +32,12 @@ Gem::Specification.new do |spec| spec.add_dependency "concurrent-ruby", "~> 1.3" spec.add_dependency "csv", "~> 3.3" spec.add_dependency "daytona", "~> 0.203" - spec.add_dependency "json", "< 3" # positional args change is not yet supported by faraday - spec.add_dependency "faraday", "~> 2.10" + spec.add_dependency "faraday", "~> 2.14", ">= 2.14.4" spec.add_dependency "faraday-multipart", "~> 1.1" spec.add_dependency "rack", "~> 3.1" spec.add_dependency "rackup", "~> 2.2" spec.add_dependency "rexml", "~> 3.4" - spec.add_dependency "ruby_llm", "~> 1.16" + spec.add_dependency "ruby_llm", "~> 2.1.1" spec.add_dependency "thor", "~> 1.5" spec.add_dependency "webrick", "~> 1.9" spec.add_dependency "zeitwerk", "~> 2.8" diff --git a/lib/lemans/agents/miniswen.rb b/lib/lemans/agents/miniswen.rb index cdf230e..b02da13 100644 --- a/lib/lemans/agents/miniswen.rb +++ b/lib/lemans/agents/miniswen.rb @@ -74,8 +74,8 @@ def detail_for(result) when :format_error "#{::Miniswen::Agent::MAX_CONSECUTIVE_FORMAT_ERRORS} consecutive responses without a valid bash tool call" when :content_filter - "the provider stopped the model: #{::Miniswen::Agent::MAX_CONSECUTIVE_FORMAT_ERRORS} consecutive turns " \ - "ended with #{::Miniswen::Agent::REFUSAL_FINISH_REASONS.join("/")} and no tool call" + "the provider stopped the model with content_filter: " \ + "#{::Miniswen::Agent::MAX_CONSECUTIVE_FORMAT_ERRORS} consecutive turns ended with no valid tool call" end end diff --git a/lib/miniswen.rb b/lib/miniswen.rb index e7f1a9b..26e12bf 100644 --- a/lib/miniswen.rb +++ b/lib/miniswen.rb @@ -16,14 +16,10 @@ class InfrastructureError < Error; end class AccountingError < Error; end class << self - def refresh_registry!(persist: false) + def refresh_registry! return true if @ruby_llm_refreshed - RubyLLM.models.refresh! - # save_to_json writes to the registry file every boot loads from (the - # gem's own models.json by default), so a persisted refresh outlives - # this process — later runs in the same environment boot from it. - RubyLLM.models.save_to_json if persist + RubyLLM.models.refresh @ruby_llm_refreshed = true rescue StandardError => e warn "Failed to refresh RubyLLM registry: #{e.message}" diff --git a/lib/miniswen/agent.rb b/lib/miniswen/agent.rb index 5739395..2e18fba 100644 --- a/lib/miniswen/agent.rb +++ b/lib/miniswen/agent.rb @@ -14,21 +14,6 @@ class Agent MAX_OBSERVATION_CHARS = 10_000 MAX_CONSECUTIVE_FORMAT_ERRORS = 3 - # Both finish_reason dialects accepted raw: OpenAI-shaped providers say - # "length"/"tool_calls", Anthropic says "max_tokens"/"tool_use". - TRUNCATION_FINISH_REASONS = %w[length max_tokens model_context_window_exceeded].freeze - CLAIMED_TOOL_FINISH_REASONS = %w[tool_calls tool_use].freeze - # A safety stop, which arrives looking exactly like a model that forgot - # to call the tool: no content, no tool call, and — since the provider - # bills nothing for a turn it refused — no tokens either. Only the - # finish reason tells the two apart, so the run is labelled by it. The - # retry is unchanged: the nudge still goes back, because matching - # mini-swe-agent turn for turn is what makes runs comparable. - REFUSAL_FINISH_REASONS = %w[content_filter refusal safety].freeze - - # The breakpoint marker Anthropic reads, shaped the way OpenRouter forwards it. - CACHE_CONTROL = { type: "ephemeral" }.freeze - EXEC_ENV = { "PAGER" => "cat", "MANPAGER" => "cat", @@ -37,9 +22,6 @@ class Agent "TQDM_DISABLE" => "1" }.freeze - # Providers that serve local inference (and cost zero) - LOCAL_PROVIDERS = %i[ollama gpustack].freeze - SYSTEM_TEMPLATE = <<~PROMPT You are a helpful assistant that can interact with a computer. PROMPT @@ -168,20 +150,10 @@ class Agent without any other command. MESSAGE - # Thinking that also carries the provider's reasoning_details for verbatim replay. - class VerbatimThinking < RubyLLM::Thinking - attr_reader :details - - def initialize(text: nil, signature: nil, details: nil) - super(text: text, signature: signature) - @details = details - end - end - # Only ever rendered into the request — the completion executes nothing — so no execute body. class BashTool < RubyLLM::Tool description "Execute a bash command" - param :command, desc: "The bash command to execute" + parameter :command, description: "The bash command to execute" # ruby_llm would otherwise derive "lemans--miniswen--bash" from the class path. def name = "bash" @@ -339,6 +311,7 @@ def start(instruction) @steps = 0 @cost = 0.0 @cost_known = true + @cost_reported = false @totals = { input_tokens: 0, output_tokens: 0, cached_tokens: 0, thinking_tokens: 0 } @started_at = @clock.call end @@ -350,6 +323,7 @@ def resume(history) @steps = history.steps.to_i @cost = history.cost_usd.to_f @cost_known = !history.cost_usd.nil? + @cost_reported = history.cost_source&.name == :provider_reported @totals = { input_tokens: history.input_tokens.to_i, output_tokens: history.output_tokens.to_i, cached_tokens: history.cached_tokens.to_i, thinking_tokens: history.thinking_tokens.to_i } @started_at = @clock.call - elapsed(history.messages) @@ -399,6 +373,7 @@ def next_actions # content, no tool call and no billed tokens. entry[:finish_reason] = response[:finish_reason] if response[:finish_reason] entry[:thinking] = response[:thinking] if response[:thinking] + entry[:provider] = response[:provider] if response[:provider] # The provider's opaque handles on this turn's reasoning: replayed back # to the provider only, never into the trajectory. entry[:thinking_signature] = response[:thinking_signature] if response[:thinking_signature] @@ -412,7 +387,7 @@ def next_actions # message with unanswered tool calls is a request providers reject. entry[:invalid_tool_calls] = tool_calls if tool_calls.any? @consecutive_format_errors += 1 - @refused_turns += 1 if refused?(response) + @refused_turns += 1 if response[:refused] observe_message({ role: "user", content: format_error_message(error, response, tool_calls) }) @@ -425,8 +400,6 @@ def next_actions tool_calls end - def refused?(response) = REFUSAL_FINISH_REASONS.include?(response[:finish_reason].to_s) - # An unpriced completion under a cost ceiling is fatal on the spot: only failing fast stops # the spend. Without a ceiling, unknown cost is just a fact to report. def track_cost(response) @@ -441,6 +414,7 @@ def track_cost(response) else @cost += cost end + @cost_reported = true if response[:reported] end def actions_error(tool_calls) @@ -466,10 +440,8 @@ def actions_error(tool_calls) end def format_error_message(error, response, tool_calls) - finish_reason = response[:finish_reason].to_s - if TRUNCATION_FINISH_REASONS.include?(finish_reason) || - (CLAIMED_TOOL_FINISH_REASONS.include?(finish_reason) && tool_calls.empty?) - format(TRUNCATION_ERROR_MESSAGE, finish_reason: finish_reason) + if response[:truncated] || (response[:finish_reason] == "tool_calls" && tool_calls.empty?) + format(TRUNCATION_ERROR_MESSAGE, finish_reason: response[:finish_reason]) else format(TOOL_CALL_ERROR_MESSAGE, error: error) end @@ -548,11 +520,13 @@ def finish(status, submission: nil) def complete(messages) model_info, provider = resolved response = provider.complete( - with_cache_breakpoints(messages.map { as_ruby_llm(it) }), + messages.map { as_ruby_llm(it) }, tools: { bash: @bash_tool }, temperature: nil, model: model_info, - params: routing_params.merge(output_cap_params(model_info)), + provider_options: routing_params, + max_output_tokens: output_cap, + caching: {}, thinking: (RubyLLM::Thinking::Config.new(effort: @effort) if @effort) ) payload(response) @@ -564,30 +538,10 @@ def complete(messages) raise InfrastructureError, "miniswen: the model call failed: #{e.class}: #{e.message}" end - # Anthropic bills every token fresh unless the request marks explicit cache - # breakpoints - def explicit_cache? = @provider == "openrouter" && @id.to_s.start_with?("anthropic/") - - def with_cache_breakpoints(messages) - return messages unless explicit_cache? - - system = messages.find { it.role == :system } - [ system, messages.last ].compact.uniq.each do |message| - text = message.content - next unless text.is_a?(String) && !text.empty? - - message.content = RubyLLM::Content::Raw.new( - [ { type: "text", text: text, cache_control: CACHE_CONTROL } ] - ) - end - messages - end - def routing_params return {} unless @provider == "openrouter" - params = {} - params[:prompt_cache_key] = cache_id if @id.start_with?("meta/muse-") + params = { prompt_cache_key: cache_id } if (order = provider_order) params[:provider] = { order: order.split(",").map(&:strip), allow_fallbacks: false } end @@ -596,20 +550,8 @@ def routing_params def provider_order = ENV["LEMANS_PROVIDER_ORDER"] || ENV["OPENROUTER_PROVIDER_ORDER"] - # OpenAI itself retired `max_tokens` for its reasoning models; the - # OpenAI-compatible providers and Anthropic still read it. - def output_cap_params(model_info) - return {} if max_output_tokens.zero? - - cap = [ info&.max_tokens, max_output_tokens ].compact.min - provider_class = RubyLLM::Provider.providers[model_info.provider.to_sym] - if [ RubyLLM::Providers::OpenAI, RubyLLM::Providers::Azure ].include?(provider_class) - { max_completion_tokens: cap } - elsif provider_class <= RubyLLM::Providers::OpenAI || provider_class <= RubyLLM::Providers::Anthropic - { max_tokens: cap } - else - {} - end + def output_cap + [ info&.max_output_tokens, max_output_tokens ].compact.min unless max_output_tokens.zero? end def cost_source @@ -618,12 +560,12 @@ def cost_source priced_as: "#{@provider || info&.provider}/#{@id} ($0.00, local)", registry: nil) end - return nil unless info - if free? - return CostSource.new(name: :free_model, model: @model, - priced_as: "#{info.provider}/#{info.id} ($0.00, free)", + if @cost_reported + return CostSource.new(name: :provider_reported, model: @model, + priced_as: "#{@provider || info&.provider}/#{@id} (as billed, else the registry price)", registry: Miniswen.registry_revision) end + return nil unless info CostSource.new(name: :model_registry, model: @model, priced_as: "#{info.provider}/#{info.id}", @@ -631,14 +573,16 @@ def cost_source end def resolved - @resolved ||= RubyLLM::Models.resolve(@id, provider: @provider, assume_exists: !@provider.nil?) + @resolved ||= RubyLLM::Models.resolve(@id, provider: @provider, assume_model_exists: !@provider.nil?) end def as_ruby_llm(entry) case entry[:role] when "assistant" - RubyLLM::Message.new(role: :assistant, content: entry[:content], - thinking: as_ruby_llm_thinking(entry), + thinking = RubyLLM::Thinking.build(text: entry[:thinking], signature: entry[:thinking_signature]) + RubyLLM::Message.new(role: :assistant, content: entry[:content], thinking:, + raw_reasoning: entry[:reasoning_details], + usage_entries: [ producing_entry ], tool_calls: as_ruby_llm_tool_calls(entry[:tool_calls])) when "tool" RubyLLM::Message.new(role: :tool, content: entry[:content], tool_call_id: entry[:tool_call_id]) @@ -647,13 +591,11 @@ def as_ruby_llm(entry) end end - def as_ruby_llm_thinking(entry) - details = entry[:reasoning_details] - if details && !details.empty? - VerbatimThinking.new(text: entry[:thinking], signature: entry[:thinking_signature], details: details) - else - RubyLLM::Thinking.build(text: entry[:thinking], signature: entry[:thinking_signature]) - end + # A rebuilt turn must name its provider, or ruby_llm drops its thinking signature. + def producing_entry + model_info, provider = resolved + RubyLLM::Accounting::Usage::Entry.new(operation: :chat, provider: provider.slug, model: model_info.id, + status: :succeeded) end def as_ruby_llm_tool_calls(tool_calls) @@ -674,16 +616,20 @@ def payload(response) content: response.content.to_s, thinking: response.thinking&.text, thinking_signature: response.thinking&.signature, - reasoning_details: reasoning_details_from(response), + reasoning_details: response.raw_reasoning, tool_calls: tool_calls_from(response), - finish_reason: finish_reason_from(response), + finish_reason: response.finish_reason&.to_s, + truncated: response.max_tokens?, + refused: response.content_filtered?, # ruby_llm's input_tokens is the cache-miss remainder only; the # convention counts the whole prompt, cached and cache-write included. - input_tokens: response.input_tokens.to_i + tokens&.cached.to_i + tokens&.cache_creation.to_i, - output_tokens: response.output_tokens.to_i, - cached_tokens: tokens&.cached.to_i, - thinking_tokens: tokens&.thinking.to_i, - cost_usd: price(response) + input_tokens: tokens.input.to_i + tokens.cache_read.to_i + tokens.cache_write.to_i, + output_tokens: tokens.output.to_i, + cached_tokens: tokens.cache_read.to_i, + thinking_tokens: tokens.thinking.to_i, + cost_usd: price(response), + reported: !tokens.reported_cost.nil?, + provider: response.raw&.body&.dig("provider") } end @@ -704,27 +650,7 @@ def normalize_arguments(arguments) arguments end - def finish_reason_from(response) - body = raw_body(response) - body && (body.dig("choices", 0, "finish_reason") || body["stop_reason"]) - end - - def reasoning_details_from(response) - details = raw_body(response)&.dig("choices", 0, "message", "reasoning_details") - details.is_a?(Array) && !details.empty? ? details : nil - end - - def raw_body(response) - body = response.raw&.body - body = JSON.parse(body) if body.is_a?(String) - body.is_a?(Hash) ? body : nil - rescue JSON::ParserError - nil - end - - def local? = LOCAL_PROVIDERS.include?((@provider || info&.provider)&.to_sym) - - def free? = info&.provider == "openrouter" && info.input_price_per_million.nil? && info.output_price_per_million.nil? + def local? = RubyLLM::Provider.providers[(@provider || info&.provider)&.to_sym]&.local? || false def info return @info if defined?(@info) @@ -733,28 +659,15 @@ def info end def find_model - @provider ? RubyLLM.models.find(@id, @provider) : RubyLLM.models.find(@id) + RubyLLM.models.find(@id, provider: @provider) rescue RubyLLM::ModelNotFoundError nil end def price(response) - return 0.0 if local? || free? + return 0.0 if local? || (response.tokens.to_h.empty? && response.tokens.reported_cost.nil?) - input = info&.input_price_per_million - output = info&.output_price_per_million - return nil unless input.is_a?(Numeric) && output.is_a?(Numeric) - - tokens = response.tokens - cache_read = info.cache_read_input_price_per_million || input - cache_write = info.cache_write_input_price_per_million || input - # Providers usually fold thinking into output_tokens; max() bills the - # larger count once and can never double-bill. - generated = [ response.output_tokens.to_i, tokens&.thinking.to_i ].max - ((response.input_tokens.to_i * input) + - (tokens&.cached.to_i * cache_read) + - (tokens&.cache_creation.to_i * cache_write) + - (generated * output)) / 1_000_000.0 + info ? info.cost_for(response.tokens).total : response.tokens.reported_cost end end end diff --git a/lib/miniswen/cli.rb b/lib/miniswen/cli.rb index 3067d0a..ff1aadb 100644 --- a/lib/miniswen/cli.rb +++ b/lib/miniswen/cli.rb @@ -99,7 +99,7 @@ def write_atif(result) end def refresh_registry_and_exit - refreshed = Miniswen.refresh_registry!(persist: true) + refreshed = Miniswen.refresh_registry! $stdout.puts Miniswen.registry_revision if refreshed Kernel.exit(refreshed ? 0 : 1) end diff --git a/lib/miniswen/ruby_llm.rb b/lib/miniswen/ruby_llm.rb index c8caf43..4ceaa40 100644 --- a/lib/miniswen/ruby_llm.rb +++ b/lib/miniswen/ruby_llm.rb @@ -4,8 +4,8 @@ # Logging configuration RubyLLM.configure do |config| - config.log_level = ENV.fetch("RUBYLLM_LOG_LEVEL", "info").to_sym - config.logger = Logger.new(IO::NULL) unless ENV["MINISWEN_DEBUG"] == "1" + config.log_level = ENV["RUBYLLM_LOG_LEVEL"].to_sym if ENV["RUBYLLM_LOG_LEVEL"] + config.logger = Logger.new(IO::NULL) unless ENV["MINISWEN_DEBUG"] == "1" || ENV["RUBYLLM_DEBUG"] == "1" end # About ten minutes of retries (1, 2, 4, ... 256s plus jitter): provider @@ -13,6 +13,7 @@ RubyLLM.configure do |config| config.max_retries = 9 config.retry_interval = 1 + config.retry_max_interval = 256 end # ruby_llm reads no API keys from ENV on its own; the conventional variable is the provider's @@ -27,36 +28,37 @@ end module Miniswen - # OpenRouter requires reasoning_details replayed exactly as received; ruby_llm - # rebuilds them from its collapsed text+signature pair, and providers that - # sign each block separately reject that as a corrupted thought signature. - module VerbatimReasoningDetails - def format_thinking(msg) - details = msg.thinking.respond_to?(:details) ? msg.thinking.details : nil - details && !details.empty? ? { reasoning_details: details } : super - end - end - - # ruby_llm lists SSL errors as fatal, but a handshake reset never sent the - # request; a 200 with a truncated JSON body is the same dropped connection - # one step later. + # A 200 cut off mid-body is a dropped connection, but ruby_llm doesn't retry it. module RetryTransientFailures - def retry_exceptions = super + [ Faraday::SSLError, Faraday::ParsingError ] + def retry_exceptions = super + [ Faraday::ParsingError ] end # ruby_llm parses tool-call arguments while it builds the message, so one # malformed call would raise and take the whole completion with it. The raw # string goes through instead and bounces as a format error. module LenientToolArguments - def parse_tool_call_arguments(tool_call) + def parse_tool_call_arguments(tool_call, **) super - rescue JSON::ParserError + rescue RubyLLM::ToolCallParseError tool_call.dig("function", "arguments") end + + def parse_function_call_arguments(arguments, **) + super + rescue RubyLLM::ToolCallParseError + arguments + end + + def parse_arguments(arguments, *) + super + rescue RubyLLM::ToolCallParseError + arguments + end end end -RubyLLM::Providers::OpenRouter.prepend(Miniswen::VerbatimReasoningDetails) -RubyLLM::Connection.prepend(Miniswen::RetryTransientFailures) -RubyLLM::Providers::OpenAI::Tools.prepend(Miniswen::LenientToolArguments) -RubyLLM::Providers::OpenAI::Tools.singleton_class.prepend(Miniswen::LenientToolArguments) +RubyLLM::Transport::Connection.singleton_class.prepend(Miniswen::RetryTransientFailures) +[ RubyLLM::Protocols::ChatCompletions::Tools, RubyLLM::Protocols::Responses::Chat, RubyLLM::Protocols::Cohere::Tools ].each do |parser| + parser.prepend(Miniswen::LenientToolArguments) + parser.singleton_class.prepend(Miniswen::LenientToolArguments) +end diff --git a/lib/miniswen/testing.rb b/lib/miniswen/testing.rb index c726e6e..5c0eaf7 100644 --- a/lib/miniswen/testing.rb +++ b/lib/miniswen/testing.rb @@ -21,22 +21,22 @@ def api_base = "http://test.invalid" # $20/M input (fresh and cached) and $400/M output price the default answer # (95 fresh + 5 cached input tokens, 20 output tokens) at exactly $0.01. - PRICED_MODEL = RubyLLM::Model::Info.new( - id: "test", name: "Test", provider: "test", + PRICED_MODEL = RubyLLM::Model.new( + id: "test", name: "Test", provider: "test", max_output_tokens: 4096, capabilities: %w[function_calling], modalities: { input: %w[text], output: %w[text] }, pricing: { text_tokens: { standard: { - input_per_million: 20.0, cached_input_per_million: 20.0, output_per_million: 400.0 + input_per_million: 20.0, cache_read_input_per_million: 20.0, output_per_million: 400.0 } } } ) - UNPRICED_MODEL = RubyLLM::Model::Info.new( + UNPRICED_MODEL = RubyLLM::Model.new( id: "test-unpriced", name: "Test unpriced", provider: "test", capabilities: %w[function_calling], modalities: { input: %w[text], output: %w[text] } ) - FREE_MODEL = RubyLLM::Model::Info.new( + FREE_MODEL = RubyLLM::Model.new( id: "test-free", name: "Test free", provider: "openrouter", capabilities: %w[function_calling], modalities: { input: %w[text], output: %w[text] } @@ -46,13 +46,11 @@ def api_base = "http://test.invalid" # Serves the test models from ruby_llm's registry lookups. module FindTestModels - def find(model_id, provider = nil) + def find(model_id, **) MODELS[model_id] || super end end - RawResponse = Data.define(:body) - SUBMIT = { content: "Done.", cmd: "echo #{Agent::SUBMIT_MARKER}" }.freeze # A shell made of a Hash. `echo` behaves like echo, so the submit marker @@ -91,7 +89,7 @@ def before_setup # Each answer is a command string, or a hash with :cmd (one command or many) # and/or :content, plus optional overrides (:tool_calls, :finish_reason, - # :thinking, token counts). Overrides given here apply to every answer. + # :thinking, :raw, token counts). Overrides given here apply to every answer. def stub_llm(*answers, **overrides) RubyLLM::Test.stub_responses(*answers.map { llm_answer(it, **overrides) }) end @@ -110,20 +108,17 @@ def llm_answer(answer, **overrides) signature: answer[:thinking_signature]), input_tokens: answer.fetch(:input_tokens, 95), output_tokens: answer.fetch(:output_tokens, 20), - cached_tokens: answer.fetch(:cached_tokens, 5), + cache_read_tokens: answer.fetch(:cached_tokens, 5), thinking_tokens: answer[:thinking] && 40, - raw: RawResponse.new(body: raw_body_for(answer, calls)) + raw_reasoning: answer[:reasoning_details], + reported_cost: answer[:reported_cost], + raw: answer[:raw], + finish_reason: answer.fetch(:finish_reason) { calls.empty? ? "stop" : "tool_calls" } ) end private - def raw_body_for(answer, calls) - choice = { "finish_reason" => answer.fetch(:finish_reason) { calls.empty? ? "stop" : "tool_calls" } } - choice["message"] = { "reasoning_details" => answer[:reasoning_details] } if answer[:reasoning_details] - { "choices" => [ choice ] } - end - def tool_calls_for(answer) calls = answer[:tool_calls] || Array(answer[:cmd]).map { { name: "bash", arguments: { "command" => it } } } calls.to_h do |call| diff --git a/lib/miniswen/trajectory.rb b/lib/miniswen/trajectory.rb index d848c25..9ed2095 100644 --- a/lib/miniswen/trajectory.rb +++ b/lib/miniswen/trajectory.rb @@ -78,7 +78,8 @@ def step_for(message, step_id) step[:llm_call_count] = 1 end # ATIF has no field for how a turn ended - step[:extra] = { finish_reason: message[:finish_reason] } if message[:finish_reason] + extra = { finish_reason: message[:finish_reason], provider: message[:provider] }.compact + step[:extra] = extra unless extra.empty? step end diff --git a/miniswen.gemspec b/miniswen.gemspec index 512e30e..c8d1f85 100644 --- a/miniswen.gemspec +++ b/miniswen.gemspec @@ -30,5 +30,5 @@ Gem::Specification.new do |spec| spec.executables = [ "miniswen" ] spec.add_dependency "logger" - spec.add_dependency "ruby_llm", "~> 1.16" + spec.add_dependency "ruby_llm", "~> 2.1.1" end diff --git a/test/lemans/agents/test_miniswen.rb b/test/lemans/agents/test_miniswen.rb index 1746db6..e4d09c4 100644 --- a/test/lemans/agents/test_miniswen.rb +++ b/test/lemans/agents/test_miniswen.rb @@ -130,6 +130,15 @@ def test_a_model_that_cannot_format_is_still_scored assert ATIFSchema.valid?(trajectory), ATIFSchema.errors(trajectory).join("\n") end + def test_content_filter + agent, task = build_agent(*Array.new(3) { { content: "stopped", finish_reason: "content_filter" } }) + response, = run_agent(agent, task) + + assert_predicate response.outcome, :completed? + assert_equal "the provider stopped the model with content_filter: " \ + "3 consecutive turns ended with no valid tool call", response.outcome.detail + end + def test_tokens_billed_at_an_unknown_rate_are_refused_not_free agent, task = build_agent(SUBMIT, model: "test-unpriced") diff --git a/test/miniswen/agent_test.rb b/test/miniswen/agent_test.rb index 49ac2b8..fb39dab 100644 --- a/test/miniswen/agent_test.rb +++ b/test/miniswen/agent_test.rb @@ -73,18 +73,12 @@ def test_a_response_without_tool_calls_is_bounced_back_and_the_model_may_recover end def test_a_truncated_response_is_told_to_be_concise - stub_llm({ content: "ramble", finish_reason: "length" }, "true", SUBMIT) + stub_llm({ content: "ramble", finish_reason: "max_tokens" }, "true", SUBMIT) result = agent.run("task") assert_equal :submitted, result.status - assert(result.messages.any? { it[:content].include?("reached the output token limit") }) - - stub_llm({ content: "ramble", finish_reason: "model_context_window_exceeded" }, "true", SUBMIT) - result = agent.run("task") - - assert_equal :submitted, result.status - assert(result.messages.any? { it[:content].include?("finish_reason=model_context_window_exceeded") }) + assert(result.messages.any? { it[:content].include?("finish_reason=max_tokens") }) end def test_three_malformed_answers_in_a_row_end_the_run @@ -119,9 +113,11 @@ def test_malformed_tool_arguments_are_bounced_back_and_the_model_may_recover result = agent.run("task") - assert_equal broken, RubyLLM::Providers::OpenAI::Tools.parse_tool_calls(raw)["c1"].arguments - assert_equal broken, openrouter_provider.send(:parse_tool_calls, raw)["c1"].arguments - assert_equal({ "command" => "ls" }, RubyLLM::Providers::OpenAI::Tools.parse_tool_calls( + assert_equal broken, RubyLLM::Protocols::ChatCompletions::Tools.parse_tool_calls(raw)["c1"].arguments + assert_equal broken, openrouter_protocol.send(:parse_tool_calls, raw)["c1"].arguments + assert_equal broken, RubyLLM::Protocols::Responses::Chat.parse_function_call_arguments(broken) + assert_equal broken, RubyLLM::Protocols::Cohere::Tools.parse_arguments(broken, nil, nil) + assert_equal({ "command" => "ls" }, RubyLLM::Protocols::ChatCompletions::Tools.parse_tool_calls( [ { "id" => "c2", "function" => { "name" => "bash", "arguments" => "{\"command\":\"ls\"}" } } ] )["c2"].arguments) assert_equal :submitted, result.status @@ -173,6 +169,14 @@ def test_a_turn_that_ends_past_the_deadline_runs_no_command refute_includes fake_env.commands, "bin/rails test" end + def test_replayed_turn_provider + build_agent + entry = { role: "assistant", content: "Done.", thinking: "plan", thinking_signature: "sig" } + message = agent.send(:as_ruby_llm, entry) + + assert_equal "test", message.model_info.provider + end + def test_a_flood_of_output_reaches_the_model_elided_head_and_tail stub_llm("make noise", SUBMIT) fake_env.on("make noise", "x" * 50_000) @@ -193,6 +197,17 @@ def test_an_empty_completion_is_an_infrastructure_failure_not_a_crash assert_match(/empty completion/, error.message) end + def test_turn_without_usage + build_agent(max_cost: 5.0) + no_usage = { cmd: "true", input_tokens: nil, output_tokens: nil, cached_tokens: nil } + stub_llm(no_usage, { **no_usage, reported_cost: 0.004 }, SUBMIT) + + result = agent.run("task") + + assert_equal :submitted, result.status + assert_in_delta 0.014, result.cost_usd + end + def test_an_unpriced_completion_under_a_cost_ceiling_stops_the_spend_immediately build_agent(model: "test-unpriced", max_cost: 5.0) stub_llm("true") @@ -214,14 +229,29 @@ def test_an_unpriced_model_is_reported_as_unknown_cost_not_as_free def test_a_free_openrouter_model_is_priced_at_zero_not_unknown with_api_key(:openrouter) { build_agent(model: "test-free", max_cost: 5.0) } - stub_llm("true", SUBMIT) + stub_llm({ cmd: "true", reported_cost: 0 }, { **SUBMIT, reported_cost: 0 }) result = agent.run("task") assert_equal :submitted, result.status assert_in_delta 0.0, result.cost_usd - assert_equal :free_model, result.cost_source.name - assert_equal "openrouter/test-free ($0.00, free)", result.cost_source.priced_as + assert_equal :provider_reported, result.cost_source.name + end + + def test_openrouter_billed_cost + with_api_key(:openrouter) { build_agent(model: "openrouter/anthropic/test") } + stub_llm({ cmd: "true", reported_cost: 0.0123 }, { **SUBMIT, reported_cost: 0.001 }) + result = agent.run("task") + + assert_in_delta 0.0133, result.cost_usd + assert_equal :provider_reported, result.cost_source.name + + build_agent + stub_llm({ cmd: "true", reported_cost: 0.0042 }, SUBMIT) + result = agent.run("task") + + assert_in_delta 0.0142, result.cost_usd + assert_equal :provider_reported, result.cost_source.name end def test_the_result_round_trips_through_json @@ -302,18 +332,14 @@ def test_anthropic_over_openrouter_marks_cache_breakpoints stub_llm(SUBMIT) agent.run("task") - contents = RubyLLM::Test.last_request.messages.map(&:content) - raw = contents.grep(RubyLLM::Content::Raw) - - refute_empty raw - assert(raw.all? { it.value.first[:cache_control] == { type: "ephemeral" } }) + assert_equal({}, RubyLLM::Test.last_request.caching) end - def test_a_plain_model_sends_no_cache_breakpoints + def test_prompt_caching stub_llm(SUBMIT) agent.run("task") - assert(RubyLLM::Test.last_request.messages.map(&:content).none?(RubyLLM::Content::Raw)) + assert_equal({}, RubyLLM::Test.last_request.caching) end def test_provider_order_pins_openrouter_routing @@ -323,81 +349,60 @@ def test_provider_order_pins_openrouter_routing agent.run("task") assert_equal({ order: [ "Chutes", "Io Net" ], allow_fallbacks: false }, - RubyLLM::Test.last_request.params[:provider]) + RubyLLM::Test.last_request.provider_options[:provider]) assert_equal "Chutes, Io Net", agent.provider_env["OPENROUTER_PROVIDER_ORDER"] ENV["LEMANS_PROVIDER_ORDER"] = "DeepInfra" stub_llm(SUBMIT) agent.run("task") - assert_equal [ "DeepInfra" ], RubyLLM::Test.last_request.params.dig(:provider, :order) + assert_equal [ "DeepInfra" ], RubyLLM::Test.last_request.provider_options.dig(:provider, :order) ensure ENV.delete("LEMANS_PROVIDER_ORDER") ENV.delete("OPENROUTER_PROVIDER_ORDER") end - def test_muse_cache_key - { - "openrouter/meta/muse-wonder#xhigh" => true, - "openrouter/meta/muse-spark-1.3#max" => true, - "openrouter/meta/llama-3.3-70b-instruct" => false - }.each do |model, cached| + def test_openrouter_cache_key + %w[openrouter/meta/muse-wonder#xhigh openrouter/meta/llama-3.3-70b-instruct].each do |model| with_api_key(:openrouter) { build_agent(model:) } stub_llm("true", SUBMIT) result = agent.run("task") requests = RubyLLM::Test.requests.last(2) - if cached - refute_empty result.cache_id - assert_equal [ result.cache_id ] * 2, requests.map { it.params[:prompt_cache_key] } + refute_empty result.cache_id + assert_equal [ result.cache_id ] * 2, requests.map { it.provider_options[:prompt_cache_key] } - stub_llm(SUBMIT) - fresh = agent.run("task") + stub_llm(SUBMIT) + fresh = agent.run("task") - refute_equal result.cache_id, fresh.cache_id - assert_equal fresh.cache_id, RubyLLM::Test.last_request.params[:prompt_cache_key] - else - assert(requests.none? { it.params.key?(:prompt_cache_key) }) - end + refute_equal result.cache_id, fresh.cache_id + assert_equal fresh.cache_id, RubyLLM::Test.last_request.provider_options[:prompt_cache_key] end build_agent(model: "test/meta/muse-wonder") stub_llm(SUBMIT) agent.run("task") - refute RubyLLM::Test.last_request.params.key?(:prompt_cache_key) + refute RubyLLM::Test.last_request.provider_options.key?(:prompt_cache_key) end def test_the_output_cap_is_sent_only_when_set_and_clamped_to_the_advertised_maximum - with_api_key(:openrouter) { build_agent(model: "openrouter/anthropic/test") } - stub_llm(SUBMIT) - agent.run("task") - - assert_equal({}, RubyLLM::Test.last_request.params) - - with_api_key(:openrouter) { build_agent(model: "openrouter/anthropic/test", max_output_tokens: 32_768) } stub_llm(SUBMIT) agent.run("task") - assert_equal 32_768, RubyLLM::Test.last_request.params[:max_tokens] + assert_nil RubyLLM::Test.last_request.max_output_tokens - with_api_key(:openrouter) { build_agent(model: "openrouter/ai21/jamba-large-1.7", max_output_tokens: 32_768) } + build_agent(max_output_tokens: 2048) stub_llm(SUBMIT) agent.run("task") - assert_equal 4096, RubyLLM::Test.last_request.params[:max_tokens] - - with_api_key(:openai) { build_agent(model: "openai/gpt-5.5", max_output_tokens: 32_768) } - stub_llm(SUBMIT) - agent.run("task") - - assert_equal({ max_completion_tokens: 32_768 }, RubyLLM::Test.last_request.params) + assert_equal 2048, RubyLLM::Test.last_request.max_output_tokens build_agent(max_output_tokens: 32_768) stub_llm(SUBMIT) agent.run("task") - assert_equal({}, RubyLLM::Test.last_request.params) + assert_equal 4096, RubyLLM::Test.last_request.max_output_tokens end def test_an_effort_suffix_sets_the_reasoning_effort_and_stays_out_of_the_model_id @@ -405,10 +410,9 @@ def test_an_effort_suffix_sets_the_reasoning_effort_and_stays_out_of_the_model_i stub_llm(SUBMIT) result = agent.run("task") - assert_equal "xhigh", RubyLLM::Test.last_request.thinking.effort + assert_equal :xhigh, RubyLLM::Test.last_request.thinking.effort assert_equal "anthropic/test", agent.send(:resolved).first.id assert_equal :submitted, result.status - assert agent.send(:explicit_cache?) build_agent(model: "ollama/qwen3:8b#high") source = agent.send(:cost_source) @@ -450,7 +454,7 @@ def test_reasoning_details_are_replayed_verbatim_not_collapsed assert_equal :submitted, result.status replayed = RubyLLM::Test.last_request.messages.find { it.role == :assistant } - assert_equal details, replayed.thinking.details + assert_equal details, replayed.raw_reasoning assert_equal "onetwo", replayed.thinking.text assert_equal "sig-1", replayed.thinking.signature restored = Miniswen::Agent::Result.from_h(JSON.parse(JSON.generate(result.to_h))) @@ -463,19 +467,10 @@ def test_openrouter_sends_verbatim_details_instead_of_the_rebuilt_pair { "type" => "reasoning.text", "text" => "one", "signature" => "sig-1" }, { "type" => "reasoning.text", "text" => "two", "signature" => "sig-2" } ] - verbatim = RubyLLM::Message.new( - role: :assistant, content: "", - thinking: Miniswen::Agent::VerbatimThinking.new(text: "onetwo", signature: "sig-1", details: details) - ) - collapsed = RubyLLM::Message.new( - role: :assistant, content: "", - thinking: RubyLLM::Thinking.new(text: "onetwo", signature: "sig-1") - ) - provider = openrouter_provider + verbatim = RubyLLM::Message.new(role: :assistant, content: "", raw_reasoning: details, + thinking: RubyLLM::Thinking.new(text: "onetwo", signature: "sig-1")) - assert_equal({ reasoning_details: details }, provider.send(:format_thinking, verbatim)) - assert_equal({ reasoning_details: [ { type: "reasoning.text", text: "onetwo", signature: "sig-1" } ] }, - provider.send(:format_thinking, collapsed)) + assert_equal({ reasoning_details: details }, openrouter_protocol.send(:format_thinking, verbatim)) end def test_a_transport_failure_becomes_an_infrastructure_error @@ -500,7 +495,7 @@ def test_a_truncated_response_body_becomes_an_infrastructure_error end def test_ssl_and_parsing_errors_join_the_transport_retry_list - exceptions = RubyLLM::Connection.allocate.retry_exceptions + exceptions = RubyLLM::Transport::Connection.send(:retry_exceptions) assert_includes exceptions, Faraday::SSLError assert_includes exceptions, Faraday::ParsingError @@ -510,7 +505,8 @@ def test_ssl_and_parsing_errors_join_the_transport_retry_list # minutes of provider rate limiting. def test_the_retry_budget_covers_about_ten_minutes config = RubyLLM.config - total = (0...config.max_retries).sum { config.retry_interval * config.retry_backoff_factor**it } + cap = config.retry_max_interval + total = (0...config.max_retries).sum { [ config.retry_interval * config.retry_backoff_factor**it, cap ].min } assert_operator total, :>=, 480 end @@ -582,10 +578,10 @@ def test_a_history_drops_a_turn_with_unanswered_calls attr_reader :agent, :fake_env - def openrouter_provider + def openrouter_protocol original = RubyLLM.config.openrouter_api_key RubyLLM.config.openrouter_api_key = "test-key" - RubyLLM::Providers::OpenRouter.new(RubyLLM.config) + RubyLLM::Providers::OpenRouter::ChatCompletions.new(RubyLLM::Providers::OpenRouter.new(RubyLLM.config)) ensure RubyLLM.config.openrouter_api_key = original end diff --git a/test/miniswen/trajectory_test.rb b/test/miniswen/trajectory_test.rb index 14cebe6..0ff1b8d 100644 --- a/test/miniswen/trajectory_test.rb +++ b/test/miniswen/trajectory_test.rb @@ -80,6 +80,15 @@ def test_model_turns_carry_timestamps_metrics_and_one_llm_call assert_equal trajectory.dig("final_metrics", "total_steps"), agent_steps end + def test_provider + stub_llm({ cmd: "true", raw: Faraday::Response.new(body: { "provider" => "Together" }) }, SUBMIT) + result = agent.run("task") + + turns = as_json(trajectory_for(result))["steps"].select { it["source"] == "agent" } + + assert_equal [ "Together", nil ], turns.map { it.dig("extra", "provider") } + end + def test_thinking_nests_as_reasoning_details stub_llm(SUBMIT, thinking: "just do it") result = agent.run("Just submit.")