Skip to content
29 changes: 29 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,35 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [Unreleased]

### Added

- **OpenRouter embeddings** (`activeagent`). `OpenRouterProvider#embed`
raised `NotImplementedError`, though OpenRouter serves an
OpenAI-compatible `/embeddings` endpoint. The provider now sends
embedding requests there, as the Requesty provider does.

### Fixed

- **RubyLLM totals count cached tokens** (`activeagent`). ruby_llm reports
input apart from cache reads and writes, and the provider's
`usage.total_tokens` fell back to input plus output, so a prompt that
read or wrote the cache was undercounted. The total is now input, output,
cache reads and cache writes, as the Anthropic provider already counts
it, and a stream totals after its chunks are merged. `total_tokens` for
a RubyLLM agent rises on cached prompts; `input_tokens`,
`cached_tokens` and `cache_creation_tokens` are unchanged.
- **`tool_choice` reaches RubyLLM** (`activeagent`). 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.
- **A streamed Mock prompt reports why it stopped** (`activeagent`). 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.

## [1.9.9] - 2026-11-18

Schema tools can ask whether a column is set: a filter takes
Expand Down
1 change: 1 addition & 0 deletions lib/active_agent/providers/mock_provider.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
13 changes: 13 additions & 0 deletions lib/active_agent/providers/open_router_provider.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
48 changes: 44 additions & 4 deletions lib/active_agent/providers/ruby_llm_provider.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -185,13 +188,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])
Expand Down Expand Up @@ -305,6 +312,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
Expand Down Expand Up @@ -538,7 +562,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

Expand Down Expand Up @@ -613,7 +640,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
Expand All @@ -640,6 +668,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
11 changes: 11 additions & 0 deletions test/providers/mock_provider_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
51 changes: 51 additions & 0 deletions test/providers/open_router/embed_test.rb
Original file line number Diff line number Diff line change
@@ -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
6 changes: 6 additions & 0 deletions test/providers/ruby_llm/response_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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
Expand All @@ -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 ---
Expand Down
36 changes: 36 additions & 0 deletions test/providers/ruby_llm/ruby_llm_provider_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
4 changes: 4 additions & 0 deletions test/providers/ruby_llm/streaming_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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" }
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand All @@ -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
Expand Down