From c1e487c4fea8b794d9afa301dbadcdac7c65970f Mon Sep 17 00:00:00 2001 From: Alex Castillo Date: Fri, 13 Nov 2026 13:10:59 -0400 Subject: [PATCH 1/4] fix: include ruby_llm cache tokens in total_tokens ruby_llm reports cache reads and writes apart from input. The total was input plus output, so those tokens were missing. Stamp the total after a stream merges its chunks, so a later output-only chunk does not drop cache already counted. --- .../providers/ruby_llm_provider.rb | 28 ++++++++++++++++--- test/providers/ruby_llm/response_test.rb | 6 ++++ test/providers/ruby_llm/streaming_test.rb | 4 +++ 3 files changed, 34 insertions(+), 4 deletions(-) diff --git a/lib/active_agent/providers/ruby_llm_provider.rb b/lib/active_agent/providers/ruby_llm_provider.rb index e5e6908ac..23d390682 100644 --- a/lib/active_agent/providers/ruby_llm_provider.rb +++ b/lib/active_agent/providers/ruby_llm_provider.rb @@ -185,13 +185,17 @@ def process_stream_chunk(chunk) # Counts arrive in separate chunks (Anthropic sends input at the start # and output at the end). They are cumulative for this turn, so merge - # reported fields rather than adding each chunk's counts. + # reported fields rather than adding each chunk's counts. The total is + # stamped after the merge: a later chunk often carries only output, and + # its own total would drop the cache already counted. if (usage = ruby_llm_usage(chunk)) - (@stream_response[:usage] ||= {}).merge!(usage) do |field, previous, current| + merged = (@stream_response[:usage] ||= {}) + merged.merge!(usage) do |field, previous, current| # Chat Completions synthesizes zero when cache writes are omitted. # That cannot erase writes already counted in this turn. field == :cache_creation_tokens && current == 0 ? previous : current end + merged[:total_tokens] = ruby_llm_total_tokens(merged) end if chunk.respond_to?(:finish_reason) && chunk.finish_reason @stream_response[:stop_reason] = ruby_llm_stop_reason(chunk, tool_calls: message[:tool_calls]) @@ -517,7 +521,10 @@ def normalize_ruby_llm_response(response, model_id) end usage = ruby_llm_usage(response) - hash[:usage] = usage if usage + if usage + usage[:total_tokens] = ruby_llm_total_tokens(usage) + hash[:usage] = usage + end hash[:model] = model_id if model_id @@ -592,7 +599,8 @@ def ruby_llm_stop_reason(response, tool_calls: response.tool_calls) # none: the message has no Tokens then in ruby_llm 1.x. RubyLLM counts # cached tokens apart from the input, so input_tokens leaves them out. # A count the provider left out is left out here too, and Usage reads it - # as zero. + # as zero. Total is not set here: a stream merges these hashes field by + # field and stamps the total once the merge is done. # # @param response [RubyLLM::Message] # @return [Hash, nil] Common::Usage attributes @@ -619,6 +627,18 @@ def ruby_llm_usage(response) }.compact end end + + # Every token the response processed. ruby_llm's input excludes cache + # reads and writes: OpenAI and Gemini subtract them from the prompt + # count, and Anthropic already reports them apart from input_tokens. + # Output already includes thinking when that is billed as output, so + # reasoning_tokens is not added again. + # + # @param usage [Hash] fields from {#ruby_llm_usage}, after a stream merge + # @return [Integer] + def ruby_llm_total_tokens(usage) + %i[input_tokens output_tokens cached_tokens cache_creation_tokens].sum { |key| usage[key] || 0 } + end end end end diff --git a/test/providers/ruby_llm/response_test.rb b/test/providers/ruby_llm/response_test.rb index 13aa05828..4a2c07de9 100644 --- a/test/providers/ruby_llm/response_test.rb +++ b/test/providers/ruby_llm/response_test.rb @@ -48,6 +48,8 @@ class RubyLLMResponseTest < ActiveSupport::TestCase assert_equal 30, usage.cached_tokens assert_equal 4, usage.cache_creation_tokens assert_equal 2, usage.reasoning_tokens + # input excludes cache, and thinking is already inside output when billed. + assert_equal 49, usage.total_tokens end # ruby_llm 1.16 has no token counts at all on such a message (its tokens is @@ -83,6 +85,8 @@ class RubyLLMResponseTest < ActiveSupport::TestCase assert_equal 3, usage.public_send(field) assert_equal 0, usage.input_tokens assert_equal 0, usage.output_tokens + # A lone thinking count is a breakdown of output, not an extra bucket. + assert_equal(count == :thinking ? 0 : 3, usage.total_tokens) end end @@ -142,6 +146,7 @@ class RubyLLMResponseTest < ActiveSupport::TestCase assert_equal 7, usage.input_tokens assert_equal 4, usage.output_tokens assert_equal 5, usage.cached_tokens + assert_equal 16, usage.total_tokens end test "reports the tokens Anthropic counted, cache reads and writes included" do @@ -155,6 +160,7 @@ class RubyLLMResponseTest < ActiveSupport::TestCase assert_equal 4, usage.output_tokens assert_equal 5, usage.cached_tokens assert_equal 2, usage.cache_creation_tokens + assert_equal 23, usage.total_tokens end # --- Stop reason --- diff --git a/test/providers/ruby_llm/streaming_test.rb b/test/providers/ruby_llm/streaming_test.rb index f237ab2de..400f6ed7b 100644 --- a/test/providers/ruby_llm/streaming_test.rb +++ b/test/providers/ruby_llm/streaming_test.rb @@ -239,6 +239,7 @@ def message_delta(stop_reason) assert_not_nil response.usage assert_equal(stream.name == :chat_completions ? 7 : 12, response.usage.input_tokens) assert_equal 4, response.usage.output_tokens + assert_equal 16, response.usage.total_tokens assert_equal "end_turn", response.finish_reason assert_equal "Done.", response.messages.last.content assert_equal 1, response.messages.count { |message| message.role == "assistant" } @@ -414,6 +415,7 @@ def message_delta(stop_reason) assert_equal 5, response.usage.output_tokens assert_equal 5, response.usage.cached_tokens assert_equal 1, response.usage.reasoning_tokens + assert_equal 27, response.usage.total_tokens assert_equal "end_turn", response.finish_reason end end @@ -435,6 +437,7 @@ def message_delta(stop_reason) assert_equal 7, usage.input_tokens assert_equal 4, usage.output_tokens assert_equal 5, usage.cache_creation_tokens + assert_equal 16, usage.total_tokens end test "updates positive cumulative cache writes and starts a fresh count on each tool turn" do @@ -453,6 +456,7 @@ def message_delta(stop_reason) assert_equal 17, response.usage.input_tokens assert_equal 5, response.usage.output_tokens assert_equal 9, response.usage.cache_creation_tokens + assert_equal 31, response.usage.total_tokens assert_equal [ 9, 0 ], response.usages.map(&:cache_creation_tokens) end end From 6b2a5f4eff103e6aac9a58e41fd32814c1c287b7 Mon Sep 17 00:00:00 2001 From: Alex Castillo Date: Wed, 18 Nov 2026 05:47:35 -0400 Subject: [PATCH 2/4] feat(open_router): implement embeddings for OpenRouterProvider OpenRouterProvider inherits ChatProvider, which defines neither embed_request_type nor api_embed_execute, so embed raised NotImplementedError. Add both, mirroring RequestyProvider. --- .../providers/open_router_provider.rb | 13 +++++ test/providers/open_router/embed_test.rb | 51 +++++++++++++++++++ 2 files changed, 64 insertions(+) create mode 100644 test/providers/open_router/embed_test.rb diff --git a/lib/active_agent/providers/open_router_provider.rb b/lib/active_agent/providers/open_router_provider.rb index 88a015670..b27a00162 100644 --- a/lib/active_agent/providers/open_router_provider.rb +++ b/lib/active_agent/providers/open_router_provider.rb @@ -31,8 +31,21 @@ def self.prompt_request_type namespace::RequestType.new end + # @return [ActiveModel::Type::Value] + def self.embed_request_type + OpenAI::Embedding::RequestType.new + end + protected + # Executes an embedding request via OpenRouter's OpenAI-compatible API. + # + # @param parameters [Hash] + # @return [Hash] symbolized API response + def api_embed_execute(parameters) + client.embeddings.create(**parameters).as_json.deep_symbolize_keys + end + # @see BaseProvider#prepare_prompt_request # @return [Request] def prepare_prompt_request diff --git a/test/providers/open_router/embed_test.rb b/test/providers/open_router/embed_test.rb new file mode 100644 index 000000000..dbcc90618 --- /dev/null +++ b/test/providers/open_router/embed_test.rb @@ -0,0 +1,51 @@ +# frozen_string_literal: true + +require "test_helper" + +begin + require "openai" +rescue LoadError + puts "OpenAI gem not available, skipping OpenRouter embed tests" + return +end + +require_relative "../../../lib/active_agent/providers/open_router_provider" + +module Providers + module OpenRouter + class EmbedTest < ActiveSupport::TestCase + include WebMock::API + + EMBEDDINGS_ENDPOINT = "https://openrouter.ai/api/v1/embeddings" + + test "sends an embedding request to the OpenRouter embeddings endpoint" do + stub_request(:post, EMBEDDINGS_ENDPOINT).to_return( + status: 200, + headers: { "Content-Type" => "application/json" }, + body: embedding_response.to_json + ) + + response = ActiveAgent::Providers::OpenRouterProvider.new( + service: "OpenRouter", + model: "openai/text-embedding-3-small", + input: "hello", + api_key: "or-test" + ).embed + + assert_equal [ 0.1, 0.2 ], response.data.first[:embedding] + assert_requested(:post, EMBEDDINGS_ENDPOINT, headers: { "Authorization" => "Bearer or-test" }) + end + + private + + def embedding_response + { + object: "list", + model: "openai/text-embedding-3-small", + data: [ { object: "embedding", index: 0, embedding: [ 0.1, 0.2 ] } ], + usage: { prompt_tokens: 2, total_tokens: 2 } + } + end + end + end +end From ab5b21f2434ec422f56448b44f77810485fceb1d Mon Sep 17 00:00:00 2001 From: Alex Castillo Date: Wed, 18 Nov 2026 06:15:41 -0400 Subject: [PATCH 3/4] fix(mock): report finish_reason after a streamed prompt The mock emitted end_turn in its stream but never recorded it, so response.finish_reason was nil after a streamed prompt. --- CHANGELOG.md | 5 +++++ lib/active_agent/providers/mock_provider.rb | 1 + test/providers/mock_provider_test.rb | 11 +++++++++++ 3 files changed, 17 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index b92c2664a..5319fc0b6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed +- **A streamed Mock prompt reports why it stopped** (`MockProvider`). The + mock emitted `end_turn` in its stream but never recorded it, so + `response.finish_reason` was `nil` after a streamed prompt, as it was not + for the real providers. The mock now records it like they do. + - **An evaluation run is executed by one job** (`actionagent`). The run job read a run's status, then the scenario runner wrote `running`, as two steps, so a job delivered twice, or two workers that both loaded the run diff --git a/lib/active_agent/providers/mock_provider.rb b/lib/active_agent/providers/mock_provider.rb index 68065242b..608912d42 100644 --- a/lib/active_agent/providers/mock_provider.rb +++ b/lib/active_agent/providers/mock_provider.rb @@ -142,6 +142,7 @@ def process_stream_chunk(api_response_chunk) when :message_delta delta = api_response_chunk[:delta] message_stack.last[:stop_reason] = delta[:stop_reason] if delta[:stop_reason] + self.stream_finish_reason = delta[:stop_reason] if delta[:stop_reason] when :message_stop # Stream complete diff --git a/test/providers/mock_provider_test.rb b/test/providers/mock_provider_test.rb index d4e688067..48845c421 100644 --- a/test/providers/mock_provider_test.rb +++ b/test/providers/mock_provider_test.rb @@ -172,6 +172,17 @@ class MockProviderTest < ActiveSupport::TestCase assert stream_events.any? { |e| e[:type] == :close } end + test "a streamed generation reports why it stopped" do + provider = ActiveAgent::Providers::MockProvider.new( + service: "Mock", + messages: [ { role: "user", content: "hello" } ], + stream: true, + stream_broadcaster: ->(_message, _delta, _event_type) { } + ) + + assert_equal "end_turn", provider.prompt.finish_reason + end + test "returns appropriate response structure" do response = @provider.prompt From f7daf7d31329ad4a0ef38cfe9b8b07af047eef44 Mon Sep 17 00:00:00 2001 From: Alex Castillo Date: Wed, 18 Nov 2026 06:48:11 -0400 Subject: [PATCH 4/4] fix(ruby_llm): pass tool_choice to RubyLLM as tool_prefs The adapter read tool_choice only to clear it between turns and never sent it, so tool_choice: "required" (or a named tool) was ignored and a generation could end without any tool call. Co-Authored-By: Claude Sonnet 5.5 --- CHANGELOG.md | 5 +++ .../providers/ruby_llm_provider.rb | 20 +++++++++++ .../ruby_llm/ruby_llm_provider_test.rb | 36 +++++++++++++++++++ 3 files changed, 61 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index b92c2664a..07ad10396 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed +- **`tool_choice` reaches RubyLLM** (`ruby_llm`). The adapter read + `tool_choice` only to clear it between turns and never sent it, so + `tool_choice: "required"` or a named tool was ignored and a generation + could finish without calling a tool. It is now passed as RubyLLM's + `tool_prefs`, and still cleared once the tool has been used. - **An evaluation run is executed by one job** (`actionagent`). The run job read a run's status, then the scenario runner wrote `running`, as two steps, so a job delivered twice, or two workers that both loaded the run diff --git a/lib/active_agent/providers/ruby_llm_provider.rb b/lib/active_agent/providers/ruby_llm_provider.rb index 3515e6c5c..dc720084a 100644 --- a/lib/active_agent/providers/ruby_llm_provider.rb +++ b/lib/active_agent/providers/ruby_llm_provider.rb @@ -62,6 +62,9 @@ def api_prompt_execute(parameters) schema = ruby_llm_schema(parameters[:response_format]) kwargs[:schema] = schema if schema + tool_prefs = ruby_llm_tool_prefs(tools) + kwargs[:tool_prefs] = tool_prefs if tool_prefs + # RubyLLM 2 renamed params: and exposes a provider-neutral token limit. max_tokens = parameters[:max_tokens] || options.max_tokens if max_tokens @@ -305,6 +308,23 @@ def process_function_calls(tool_calls) private + # Maps the request's tool_choice to RubyLLM's tool_prefs. Without it + # the model is free to answer without calling a tool even when the + # caller requires one. Nil once ToolChoiceClearing has cleared it, so + # a follow-up turn is not forced into another call. + # + # @param tools [Hash, nil] RubyLLM tools sent with this request + # @return [Hash, nil] + def ruby_llm_tool_prefs(tools) + return nil if tools.blank? + + choice = request.tool_choice + choice = (choice[:name] || choice["name"]) if choice.is_a?(Hash) + return nil if choice.blank? + + { choice: choice.to_sym } + end + def ruby_llm_v2? Gem.loaded_specs.fetch("ruby_llm").version.segments.first >= 2 end diff --git a/test/providers/ruby_llm/ruby_llm_provider_test.rb b/test/providers/ruby_llm/ruby_llm_provider_test.rb index 64725a39a..ceb8b760b 100644 --- a/test/providers/ruby_llm/ruby_llm_provider_test.rb +++ b/test/providers/ruby_llm/ruby_llm_provider_test.rb @@ -964,6 +964,42 @@ def last_kwargs end end + test "tool_choice required is passed to RubyLLM as tool_prefs" do + provider = ActiveAgent::Providers::RubyLLMProvider.new( + service: "RubyLLM", + model: "gpt-4o-mini", + tool_choice: "required", + messages: [ { role: "user", content: "weather?" } ], + tools: [ tool_definition("get_weather") ], + tools_function: ->(_name, **_kwargs) { { temp: 72 } } + ) + + provider.prompt + + assert_equal({ choice: :required }, @fake_provider.last_kwargs[:tool_prefs]) + end + + test "tool_choice naming a tool is passed to RubyLLM as that tool" do + provider = ActiveAgent::Providers::RubyLLMProvider.new( + service: "RubyLLM", + model: "gpt-4o-mini", + tool_choice: { name: "get_weather" }, + messages: [ { role: "user", content: "weather?" } ], + tools: [ tool_definition("get_weather") ], + tools_function: ->(_name, **_kwargs) { { temp: 72 } } + ) + + provider.prompt + + assert_equal({ choice: :get_weather }, @fake_provider.last_kwargs[:tool_prefs]) + end + + test "tool_prefs is not passed without a tool_choice" do + @provider.prompt + + assert_nil @fake_provider.last_kwargs[:tool_prefs] + end + test "max_tokens is not passed when not set" do @provider.prompt