activeagent 1.9.9 → 1.9.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: e5cf4f1304cb0d939f96e270b950dbe8bc3505e6e4d8dacba9f0f16083c1b485
4
- data.tar.gz: 7716fbc50b2e06ac508cf88a63b8515bbec0f17d6ab632b57a05706f0fe1187b
3
+ metadata.gz: 74cdf346c2238da0eda25a4c53a047f56b5557ca991520558cfc88e56290d6e4
4
+ data.tar.gz: 563d490b5800e9735f9ef9ec765ee15799d7bbd431773d5bde2623ccff5c441d
5
5
  SHA512:
6
- metadata.gz: f237aff2404b739fa66c77e0d5a6e2925be257423fc2072ae7b1387c00a144cf0fdbb95466237981170bcf1f2f9b468c0f592bdc5d3442522300fc0dce6b581a
7
- data.tar.gz: ef1161bd9b4d39338594946354ce0f455f212f9508ff0a8f0119fd2762fb965a7b32798a3913a2473a27424c6c918e7102d3a14e78233d4b67a96f1771aac108
6
+ metadata.gz: cd95ef40bf18ed3d6920530c4e7500f17a4cc24a9c9e8c575b7fe6cb6fd245be7b8707e32ddee8d5d90fda58a1fdad7650e184bedfa66e8040b538d86e57ceae
7
+ data.tar.gz: a81a674b55407298ad5935f3e20beece07669944792f4a27c5d7c81bacc2293055ad79cc32f44bdd93db93d0476fe7067120136424c7af95c8e975ad94e7eb6c
data/CHANGELOG.md CHANGED
@@ -5,6 +5,165 @@ All notable changes to this project will be documented in this file.
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6
6
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
+ ## [1.9.10] - 2026-12-02
9
+
10
+ The dashboard takes OpenTelemetry: an application in any language can
11
+ report traces with its own OTLP exporter. An agent run whose worker died
12
+ is now failed as lost instead of staying "running" forever. The rest is
13
+ provider fixes, most of them from the community: the OpenAI providers
14
+ load the `openai` gem 1.x, Anthropic keeps `cache_control` on a
15
+ single-block system prompt (prompt caching was silently lost), OpenRouter
16
+ sends `tool_choice: "required"`, Ollama honours `format` and `options` and
17
+ keeps parallel tool results apart, Azure and OpenRouter serve embeddings,
18
+ and the RubyLLM provider passes `tool_choice`, array instructions, a
19
+ tool's `input_schema` and cache and embedding token counts through.
20
+
21
+ Upgrading: one dashboard migration, 036 `add_agent_run_execution_leases`:
22
+ run `bin/rails generate action_agent:install --skip` and `bin/rails
23
+ db:migrate`. It is numbered after 1.9.9's 034 and 035 so that a new
24
+ install and an upgraded one run the three in the same order; 033 stays
25
+ unused. Until it runs, agent runs take no leases and a run whose
26
+ worker dies stays running as before; once it has, a run that makes no
27
+ progress for 30 minutes is failed as lost. `activeagent` now requires
28
+ activeagents-telemetry 0.4 or later (it allowed 0.1 and up), which OTLP
29
+ ingest needs: `bundle update activeagent` brings it in. Schema tools now return an error for a
30
+ range filter that cannot apply (an empty range, an unreadable bound, a
31
+ comparison on a string or boolean column) where they used to answer with
32
+ a count of 0. `usage.total_tokens` for a RubyLLM agent rises on cached
33
+ prompts, since cache reads and writes are now counted.
34
+
35
+ ### Added
36
+
37
+ - **OpenTelemetry ingest** (`actionagent`). The trace ingest endpoint
38
+ (`POST <mount>/api/traces`, and `<mount>/api/otlp/v1/traces` for exporters
39
+ given a base endpoint) reads OTLP over HTTP, protobuf or JSON, gzipped or
40
+ not, so an application in any language can report to the dashboard with
41
+ its OpenTelemetry exporter. Spans following the OpenTelemetry GenAI
42
+ semantic conventions become the dashboard's `llm`, `tool` and agent
43
+ spans; other spans are dropped. Because an exporter sends spans as they
44
+ end, a trace is stored with its first span and takes the rest as they
45
+ arrive. activeagents-telemetry 0.4, which `activeagent` now requires,
46
+ does the decoding. The native format is unchanged.
47
+
48
+ - **OpenRouter embeddings** (`activeagent`). `OpenRouterProvider#embed`
49
+ raised `NotImplementedError`, though OpenRouter serves an
50
+ OpenAI-compatible `/embeddings` endpoint. The provider now sends
51
+ embedding requests there, as the Requesty provider does.
52
+ - **Azure OpenAI embeddings** (`activeagent`). `AzureProvider#embed` built
53
+ the request and then raised `NotImplementedError`. It now calls the
54
+ deployment's `/embeddings` endpoint. The Azure client's `auth_headers`
55
+ also accepts the options newer `openai` gem versions pass to it.
56
+
57
+ ### Fixed
58
+
59
+ - **Ollama `format` and `options` take effect** (`activeagent`). Requests
60
+ go to Ollama's OpenAI-compatible endpoint, which ignores the native
61
+ `format` and `options` fields, so `format: "json"`, a JSON schema and
62
+ `options: { num_predict: }` did nothing. They are now also sent as
63
+ `response_format`, `max_tokens` and the matching sampling parameters. A
64
+ value given at the top level wins.
65
+ - **OpenRouter accepts a custom base URL** (`activeagent`). `base_url` was
66
+ read-only on the OpenRouter options, so passing it (or `uri_base`)
67
+ raised `ArgumentError`. The default endpoint is unchanged.
68
+ - **RubyLLM embeddings report token usage** (`activeagent`).
69
+ `response.usage` was nil after an embedding even when the provider
70
+ reported prompt tokens. The input tokens are now summed across the
71
+ inputs. ruby_llm 1.x reports zero for an omitted count, so only positive
72
+ counts are kept there.
73
+ - **OpenAI Chat cache writes are reported** (`activeagent`).
74
+ `prompt_tokens_details.cache_write_tokens` is now mapped to
75
+ `usage.cache_creation_tokens`, as the Anthropic provider already maps
76
+ its own field.
77
+ - **Sampling parameters are dropped for prefixed model ids**
78
+ (`activeagent`). Model capability rules matched only a bare model name,
79
+ so a Bedrock id such as `eu.anthropic.claude-sonnet-5-v1:0` or a routed
80
+ `openai/gpt-5` kept `temperature` and `top_p` for a model that rejects
81
+ them. The region or vendor prefix and the `-vN:M` suffix are now ignored
82
+ when matching.
83
+ - **The OpenAI providers load the `openai` gem 1.x** (`activeagent`).
84
+ The `openai` loader pinned the client gem to `~> 0.34`, so a bundle
85
+ holding openai 1.0 or later raised `LoadError` the moment any
86
+ OpenAI-family provider (OpenAI, OpenRouter, Ollama and the other
87
+ OpenAI-compatible providers) loaded. The loader and the gemspec's
88
+ development dependency now accept openai 0.34 through 1.x, and CI runs
89
+ the OpenAI, Azure, OpenRouter and Ollama provider tests against 1.3.
90
+ - **Required tool choice works with OpenRouter** (`activeagent`). The
91
+ adapter now sends `tool_choice: "required"` and clears it after the
92
+ first tool call so the model can finish its response.
93
+ - **RubyLLM keeps a tool's `input_schema`** (`activeagent`). A tool
94
+ defined with `input_schema` instead of `parameters` reached ruby_llm with
95
+ an empty schema, so the model was told the tool takes no arguments. The
96
+ provider now accepts either key, as the OpenAI providers do.
97
+ - **Array instructions work with RubyLLM** (`activeagent`). An agent whose
98
+ `instructions` were an array raised `ArgumentError: Message content must
99
+ be a String` before any request. Each entry is now sent as its own system
100
+ message.
101
+ - **Anthropic tool choice** (`activeagent`). The common `tool_choice: "none"`
102
+ option now disables tool use without a conversion error.
103
+ - **Ollama keeps parallel tool results apart** (`activeagent`). Before a
104
+ request, consecutive same-role messages were merged, and parallel tool
105
+ calls append one `tool` message per call, so their results were
106
+ concatenated into a single message holding only the first
107
+ `tool_call_id`. Tool results and assistant messages with `tool_calls` are
108
+ no longer merged.
109
+
110
+ - **RubyLLM totals count cached tokens** (`activeagent`). ruby_llm reports
111
+ input apart from cache reads and writes, and the provider's
112
+ `usage.total_tokens` fell back to input plus output, so a prompt that
113
+ read or wrote the cache was undercounted. The total is now input, output,
114
+ cache reads and cache writes, as the Anthropic provider already counts
115
+ it, and a stream totals after its chunks are merged. `total_tokens` for
116
+ a RubyLLM agent rises on cached prompts; `input_tokens`,
117
+ `cached_tokens` and `cache_creation_tokens` are unchanged.
118
+ - **`tool_choice` reaches RubyLLM** (`activeagent`). The adapter read
119
+ `tool_choice` only to clear it between turns and never sent it, so
120
+ `tool_choice: "required"` or a named tool was ignored and a generation
121
+ could finish without calling a tool. It is now passed as RubyLLM's
122
+ `tool_prefs`, and still cleared once the tool has been used.
123
+ - **A streamed Mock prompt reports why it stopped** (`activeagent`). The
124
+ mock emitted `end_turn` in its stream but never recorded it, so
125
+ `response.finish_reason` was `nil` after a streamed prompt, as it was not
126
+ for the real providers. The mock now records it like they do.
127
+ - **A Symbol `tool_choice` is cleared under RubyLLM** (`activeagent`). The
128
+ provider sends `tool_choice: :required` or `{ name: :get_weather }` to
129
+ RubyLLM, but the checks that clear a forced choice once the tool has run
130
+ compared Strings, so a Symbol choice forced every turn into another tool
131
+ call until `max_tool_turns` stopped it. Both forms are now cleared after
132
+ the tool is used, as the String forms already were.
133
+ - **Anthropic keeps `cache_control` on a single text block** (`activeagent`).
134
+ A system prompt or message holding one text block was sent as a bare
135
+ string, which dropped the block's `cache_control` (or `citations`), so a
136
+ prompt marked for caching was never cached. Only a block holding nothing
137
+ but its text is shortened now.
138
+ - **A catalog set run against a project keeps its selection** (`actionagent`).
139
+ Running a set with `project_id` stored the requested `keys` and `models`,
140
+ but `ProjectEvaluationJob` did not pass them on, so the run replayed every
141
+ enabled scenario under the agent's own model. It now replays the ones
142
+ asked for.
143
+ - **Schema tools refuse a range filter that cannot apply** (`activeagent`).
144
+ A bound the column cannot read (`{"before" => "yesterday"}`,
145
+ `{"gt" => "thirty"}`, a blank or `nil` bound), an empty range object, and
146
+ a comparison on a string or boolean column were each answered as if they
147
+ had filtered: zero rows, every row, or a comparison with 0. Each now
148
+ returns the tool's error, as an unknown comparison already did.
149
+ - **A run whose worker died is failed as lost instead of running forever**
150
+ (`actionagent`). Since a run is claimed once, a worker that died after
151
+ its claim left the run `running` for good: a redelivered job leaves a
152
+ running run alone. Each claim (the execution job's, the resume job's,
153
+ `Agent#test_execute`'s) now takes a lease (migration 036,
154
+ `config.run_lease_duration`, 30 minutes by default) that each LLM or
155
+ tool call renews. A running run whose lease ran out is failed with
156
+ `error_class` `ActionAgent::AgentRun::WorkerLost` when its page or the
157
+ run list is read, or when `ActionAgent::AgentRunExpiryJob` runs (not
158
+ scheduled by default). Nothing is executed again: the run's provider and
159
+ tool calls may already have taken effect. A worker that was only slow
160
+ has its result discarded, as a cancelled run's is, and a result now
161
+ only lands while the run holds its worker's lease, so whatever ended
162
+ the run first is kept. `test_execute` records its result the same way,
163
+ so a cancel during a synchronous test run is no longer overwritten. A
164
+ run with no lease, such as one running when the migration is installed,
165
+ is never failed as lost.
166
+
8
167
  ## [1.9.9] - 2026-11-18
9
168
 
10
169
  Schema tools can ask whether a column is set: a filter takes
@@ -29,6 +29,11 @@ module ActiveAgent
29
29
  { pattern: /\Agpt-5/, unsupported: SAMPLING_PARAMS }
30
30
  ].freeze
31
31
 
32
+ # Cloud-hosted ids wrap the bare model name, e.g. Bedrock's
33
+ # "eu.anthropic.claude-sonnet-5-v1:0" or "anthropic.claude-opus-5-v1:0".
34
+ PROVIDER_PREFIX = /\A(?:[a-z]{2,6}\.)?(?:anthropic|openai)[.\/]/
35
+ VERSION_SUFFIX = /-v\d+(?::\d+)?\z/
36
+
32
37
  class << self
33
38
  # Master switch; on by default. Set false to send parameters through
34
39
  # untouched (the vendor then enforces its own rules).
@@ -61,12 +66,21 @@ module ActiveAgent
61
66
  def unsupported_params(model)
62
67
  return [] if model.nil?
63
68
 
69
+ name = model.to_s
70
+ bare = normalize_model(name)
71
+
64
72
  (custom_rules + BUILTIN_RULES).each do |rule|
65
- return rule[:unsupported] if model.to_s.match?(rule[:pattern])
73
+ return rule[:unsupported] if name.match?(rule[:pattern]) || bare.match?(rule[:pattern])
66
74
  end
67
75
  []
68
76
  end
69
77
 
78
+ # Strips the region/provider prefix and "-vN:M" suffix that Bedrock-style
79
+ # ids add around the bare model name.
80
+ def normalize_model(name)
81
+ name.sub(PROVIDER_PREFIX, "").sub(VERSION_SUFFIX, "")
82
+ end
83
+
70
84
  def sampling_supported?(model)
71
85
  (unsupported_params(model) & SAMPLING_PARAMS).empty?
72
86
  end
@@ -11,7 +11,7 @@ require_relative "concerns/tool_choice_clearing"
11
11
  # @private
12
12
  GEM_LOADERS = {
13
13
  anthropic: [ "anthropic", [ ">= 1.12", "< 3" ], "anthropic" ],
14
- openai: [ "openai", "~> 0.34", "openai" ],
14
+ openai: [ "openai", [ ">= 0.34", "< 2" ], "openai" ],
15
15
  # Keep a tested floor: 1.2 lacks the provider APIs this adapter uses.
16
16
  ruby_llm: [ "ruby_llm", [ ">= 1.16", "< 3" ], "ruby_llm" ]
17
17
  }
@@ -187,6 +187,7 @@ module ActiveAgent
187
187
  # Maps:
188
188
  # - "required" → ToolChoiceAny (force tool use)
189
189
  # - "auto" → ToolChoiceAuto (let model decide)
190
+ # - "none" → ToolChoiceNone (disable tool use)
190
191
  # - { name: "..." } → ToolChoiceTool with name
191
192
  #
192
193
  # @param tool_choice [String, Hash, Object]
@@ -205,6 +206,8 @@ module ActiveAgent
205
206
  when "auto"
206
207
  # Create ToolChoiceAuto model for letting model decide
207
208
  ::Anthropic::Models::ToolChoiceAuto.new(type: :auto)
209
+ when "none"
210
+ ::Anthropic::Models::ToolChoiceNone.new(type: :none)
208
211
  when Hash
209
212
  choice_hash = tool_choice.deep_symbolize_keys
210
213
 
@@ -567,6 +570,10 @@ module ActiveAgent
567
570
  #
568
571
  # `[{type: "text", text: "hello"}]` → `"hello"`
569
572
  #
573
+ # A block that carries anything besides its text, such as
574
+ # cache_control or citations, stays a block: the string form has
575
+ # nowhere to keep it.
576
+ #
570
577
  # @param msg [Hash] message with :content key
571
578
  # @return [void]
572
579
  def compress_message_content!(msg)
@@ -574,7 +581,7 @@ module ActiveAgent
574
581
  return unless content.is_a?(Array)
575
582
 
576
583
  # Single text block → string shorthand
577
- if content.one? && content.first.is_a?(Hash) && content.first[:type] == "text"
584
+ if content.one? && plain_text_block?(content.first)
578
585
  msg[:content] = content.first[:text]
579
586
  end
580
587
  end
@@ -639,12 +646,20 @@ module ActiveAgent
639
646
  return system unless system.is_a?(Array)
640
647
 
641
648
  # Single text block → string shorthand
642
- if system.one? && system.first.is_a?(Hash) && system.first[:type] == "text"
649
+ if system.one? && plain_text_block?(system.first)
643
650
  system.first[:text]
644
651
  else
645
652
  system
646
653
  end
647
654
  end
655
+
656
+ # True for a text block holding nothing but its text.
657
+ #
658
+ # @param block [Object]
659
+ # @return [Boolean]
660
+ def plain_text_block?(block)
661
+ block.is_a?(Hash) && block[:type] == "text" && block.except(:type, :text).compact.empty?
662
+ end
648
663
  end
649
664
  end
650
665
  end
@@ -60,6 +60,17 @@ module ActiveAgent
60
60
  )
61
61
  end
62
62
 
63
+ protected
64
+
65
+ # Executes an embedding request against the Azure deployment's
66
+ # +/embeddings+ endpoint.
67
+ #
68
+ # @param parameters [Hash]
69
+ # @return [Hash] symbolized API response
70
+ def api_embed_execute(parameters)
71
+ client.embeddings.create(**parameters).as_json.deep_symbolize_keys
72
+ end
73
+
63
74
  # Custom OpenAI client for Azure OpenAI Service.
64
75
  #
65
76
  # Azure uses different authentication headers (api-key instead of Authorization: Bearer)
@@ -103,7 +114,8 @@ module ActiveAgent
103
114
  # Azure uses api-key header instead of Authorization: Bearer.
104
115
  #
105
116
  # @return [Hash{String=>String}]
106
- def auth_headers
117
+ # Newer OpenAI SDK versions pass security options to this hook.
118
+ def auth_headers(**)
107
119
  return {} if @api_key.nil?
108
120
 
109
121
  { "api-key" => @api_key }
@@ -183,6 +183,7 @@ module ActiveAgent
183
183
  input_tokens: usage[:prompt_tokens] || 0,
184
184
  output_tokens: usage[:completion_tokens] || 0,
185
185
  cached_tokens: prompt_details[:cached_tokens],
186
+ cache_creation_tokens: prompt_details[:cache_write_tokens],
186
187
  reasoning_tokens: completion_details[:reasoning_tokens],
187
188
  audio_tokens: audio_sum > 0 ? audio_sum : nil,
188
189
  provider_details: usage.slice(:prompt_tokens_details, :completion_tokens_details).compact
@@ -142,6 +142,7 @@ module ActiveAgent
142
142
  when :message_delta
143
143
  delta = api_response_chunk[:delta]
144
144
  message_stack.last[:stop_reason] = delta[:stop_reason] if delta[:stop_reason]
145
+ self.stream_finish_reason = delta[:stop_reason] if delta[:stop_reason]
145
146
 
146
147
  when :message_stop
147
148
  # Stream complete
@@ -98,13 +98,54 @@ module ActiveAgent
98
98
  cleaned[key] = value
99
99
  end
100
100
 
101
+ map_to_openai_compatible_params(cleaned)
102
+ end
103
+
104
+ # Option keys with a direct equivalent on Ollama's /v1/chat/completions
105
+ OPENAI_COMPATIBLE_OPTIONS = {
106
+ num_predict: :max_tokens,
107
+ temperature: :temperature,
108
+ top_p: :top_p,
109
+ seed: :seed,
110
+ stop: :stop,
111
+ frequency_penalty: :frequency_penalty,
112
+ presence_penalty: :presence_penalty
113
+ }.freeze
114
+
115
+ # Copies format/options into their OpenAI-compatible fields
116
+ #
117
+ # Requests go to Ollama's OpenAI-compatible endpoint, which ignores the
118
+ # native top-level format/options fields. Explicit top-level params win.
119
+ #
120
+ # @param cleaned [Hash] cleaned request hash
121
+ # @return [Hash] request hash with OpenAI-compatible equivalents added
122
+ def map_to_openai_compatible_params(cleaned)
123
+ format = cleaned[:format]
124
+ if format && !cleaned.key?(:response_format)
125
+ if format.is_a?(Hash)
126
+ cleaned[:response_format] = { type: "json_schema", json_schema: { name: "response", schema: format } }
127
+ elsif format.to_s == "json"
128
+ cleaned[:response_format] = { type: "json_object" }
129
+ end
130
+ end
131
+
132
+ if cleaned[:options].is_a?(Hash)
133
+ cleaned[:options].symbolize_keys.each do |key, value|
134
+ target = OPENAI_COMPATIBLE_OPTIONS[key]
135
+ cleaned[target] = value if target && !value.nil? && !cleaned.key?(target)
136
+ end
137
+ end
138
+
101
139
  cleaned
102
140
  end
103
141
 
104
142
  # Groups consecutive same-role messages for Ollama
105
143
  #
106
144
  # Ollama requires consecutive messages with the same role to be merged
107
- # by concatenating their content.
145
+ # by concatenating their content. Tool results and assistant messages
146
+ # carrying tool calls are never merged: each tool result is tied to
147
+ # its own tool_call_id (parallel calls produce consecutive tool
148
+ # messages), and merging would drop ids and calls.
108
149
  #
109
150
  # @param messages [Array<Hash>] array of message hashes
110
151
  # @return [Array<Hash>] grouped messages
@@ -113,7 +154,8 @@ module ActiveAgent
113
154
 
114
155
  grouped = []
115
156
  messages.each do |message|
116
- if grouped.empty? || grouped.last[:role] != message[:role]
157
+ if grouped.empty? || grouped.last[:role] != message[:role] ||
158
+ tool_message?(grouped.last) || tool_message?(message)
117
159
  grouped << message.deep_dup
118
160
  else
119
161
  # Concatenate content for same-role messages
@@ -133,6 +175,12 @@ module ActiveAgent
133
175
 
134
176
  grouped
135
177
  end
178
+
179
+ # @param message [Hash]
180
+ # @return [Boolean] true for tool results and assistant tool calls
181
+ def tool_message?(message)
182
+ message[:role].to_s == "tool" || message[:tool_calls].present? || message.key?(:tool_call_id)
183
+ end
136
184
  end
137
185
  end
138
186
  end
@@ -30,7 +30,7 @@ module ActiveAgent
30
30
  class Options < ActiveAgent::Providers::OpenAI::Options
31
31
  # @!attribute base_url
32
32
  # @return [String] API endpoint (default: "https://openrouter.ai/api/v1")
33
- attribute :base_url, :string, as: "https://openrouter.ai/api/v1"
33
+ attribute :base_url, :string, fallback: "https://openrouter.ai/api/v1"
34
34
 
35
35
  # @!attribute app_name
36
36
  # @return [String] application name for X-Title header (default: "ActiveAgent" or Rails app name)
@@ -150,7 +150,7 @@ module ActiveAgent
150
150
 
151
151
  # Gets tool_choice bypassing gem validation
152
152
  #
153
- # OpenRouter supports "any" which isn't valid in OpenAI gem types.
153
+ # Read the raw value so a cleared tool choice can be read as nil.
154
154
  #
155
155
  # @return [String, Hash, nil]
156
156
  def tool_choice
@@ -159,8 +159,7 @@ module ActiveAgent
159
159
 
160
160
  # Sets tool_choice bypassing gem validation
161
161
  #
162
- # OpenRouter supports "any" which isn't valid in OpenAI gem types,
163
- # so we bypass the gem's type validation by setting @data directly.
162
+ # Write the raw value so the tool loop can clear it with nil.
164
163
  #
165
164
  # @param value [String, Hash, nil]
166
165
  # @return [void]
@@ -62,11 +62,6 @@ module ActiveAgent
62
62
  # Use OpenAI transforms for the base parameters
63
63
  openai_params = OpenAI::Chat::Transforms.normalize_params(params)
64
64
 
65
- # Override tool_choice normalization for OpenRouter's "any" vs "required" difference
66
- if openai_params[:tool_choice]
67
- openai_params[:tool_choice] = normalize_tool_choice(openai_params[:tool_choice])
68
- end
69
-
70
65
  [ openai_params, openrouter_params ]
71
66
  end
72
67
 
@@ -78,23 +73,6 @@ module ActiveAgent
78
73
  OpenAI::Chat::Transforms.normalize_tools(tools)
79
74
  end
80
75
 
81
- # Normalizes tool_choice for OpenRouter API differences
82
- #
83
- # OpenRouter uses "any" instead of OpenAI's "required" for forcing tool use.
84
- # Converts common format to OpenRouter-specific format:
85
- # - "required" (common) → "any" (OpenRouter)
86
- # - Everything else delegates to OpenAI transforms
87
- #
88
- # @param tool_choice [String, Hash, Symbol]
89
- # @return [String, Hash, Symbol]
90
- def normalize_tool_choice(tool_choice)
91
- # Convert "required" to OpenRouter's "any"
92
- return "any" if tool_choice.to_s == "required"
93
-
94
- # For everything else, use OpenAI transforms
95
- OpenAI::Chat::Transforms.normalize_tool_choice(tool_choice)
96
- end
97
-
98
76
  # Normalizes messages using OpenAI transforms
99
77
  #
100
78
  # @param messages [Array, String, Hash, nil]
@@ -31,8 +31,21 @@ module ActiveAgent
31
31
  namespace::RequestType.new
32
32
  end
33
33
 
34
+ # @return [ActiveModel::Type::Value]
35
+ def self.embed_request_type
36
+ OpenAI::Embedding::RequestType.new
37
+ end
38
+
34
39
  protected
35
40
 
41
+ # Executes an embedding request via OpenRouter's OpenAI-compatible API.
42
+ #
43
+ # @param parameters [Hash]
44
+ # @return [Hash] symbolized API response
45
+ def api_embed_execute(parameters)
46
+ client.embeddings.create(**parameters).as_json.deep_symbolize_keys
47
+ end
48
+
36
49
  # @see BaseProvider#prepare_prompt_request
37
50
  # @return [Request]
38
51
  def prepare_prompt_request
@@ -40,11 +53,11 @@ module ActiveAgent
40
53
  super
41
54
  end
42
55
 
43
- # Returns true if tool_choice == "any" (OpenRouter's equivalent of "required").
56
+ # Returns true if tool_choice == "required".
44
57
  #
45
58
  # @return [Boolean]
46
59
  def tool_choice_forces_required?
47
- request.tool_choice == "any"
60
+ request.tool_choice == "required"
48
61
  end
49
62
 
50
63
  # Merges streaming delta into the message with role cleanup.
@@ -62,6 +62,9 @@ module ActiveAgent
62
62
  schema = ruby_llm_schema(parameters[:response_format])
63
63
  kwargs[:schema] = schema if schema
64
64
 
65
+ tool_prefs = ruby_llm_tool_prefs(tools)
66
+ kwargs[:tool_prefs] = tool_prefs if tool_prefs
67
+
65
68
  # RubyLLM 2 renamed params: and exposes a provider-neutral token limit.
66
69
  max_tokens = parameters[:max_tokens] || options.max_tokens
67
70
  if max_tokens
@@ -106,10 +109,18 @@ module ActiveAgent
106
109
 
107
110
  input = parameters[:input]
108
111
  inputs = input.is_a?(Array) ? input : [ input ]
112
+ input_tokens = nil
109
113
 
110
114
  data = inputs.map.with_index do |text, index|
111
115
  embedding_model = ruby_llm_v2? ? @ruby_llm_model : model_id
112
116
  embedding = @ruby_llm_provider.embed(text, model: embedding_model, dimensions: parameters[:dimensions])
117
+ count = if ruby_llm_v2?
118
+ embedding.tokens&.input
119
+ else
120
+ # RubyLLM 1.x also uses zero when the provider omitted usage.
121
+ embedding.input_tokens if embedding.input_tokens&.positive?
122
+ end
123
+ input_tokens = (input_tokens || 0) + count if count
113
124
 
114
125
  {
115
126
  object: "embedding",
@@ -118,11 +129,13 @@ module ActiveAgent
118
129
  }
119
130
  end
120
131
 
121
- {
132
+ response = {
122
133
  object: :list,
123
134
  data: data,
124
135
  model: model_id
125
136
  }
137
+ response[:usage] = { input_tokens: input_tokens, total_tokens: input_tokens } if input_tokens
138
+ response
126
139
  end
127
140
 
128
141
  # Processes streaming chunks from RubyLLM.
@@ -185,13 +198,17 @@ module ActiveAgent
185
198
 
186
199
  # Counts arrive in separate chunks (Anthropic sends input at the start
187
200
  # and output at the end). They are cumulative for this turn, so merge
188
- # reported fields rather than adding each chunk's counts.
201
+ # reported fields rather than adding each chunk's counts. The total is
202
+ # stamped after the merge: a later chunk often carries only output, and
203
+ # its own total would drop the cache already counted.
189
204
  if (usage = ruby_llm_usage(chunk))
190
- (@stream_response[:usage] ||= {}).merge!(usage) do |field, previous, current|
205
+ merged = (@stream_response[:usage] ||= {})
206
+ merged.merge!(usage) do |field, previous, current|
191
207
  # Chat Completions synthesizes zero when cache writes are omitted.
192
208
  # That cannot erase writes already counted in this turn.
193
209
  field == :cache_creation_tokens && current == 0 ? previous : current
194
210
  end
211
+ merged[:total_tokens] = ruby_llm_total_tokens(merged)
195
212
  end
196
213
  if chunk.respond_to?(:finish_reason) && chunk.finish_reason
197
214
  @stream_response[:stop_reason] = ruby_llm_stop_reason(chunk, tool_calls: message[:tool_calls])
@@ -258,19 +275,21 @@ module ActiveAgent
258
275
 
259
276
  # Returns true if tool_choice forces any tool to be used.
260
277
  #
261
- # Handles both string ("required") and hash ({name: "..."}) formats.
278
+ # Accepts "required" or :required, as ruby_llm_tool_prefs does.
262
279
  #
263
280
  # @return [Boolean]
264
281
  def tool_choice_forces_required?
265
- request.tool_choice == "required"
282
+ request.tool_choice.to_s == "required"
266
283
  end
267
284
 
268
- # Returns [true, name] if tool_choice forces a specific tool.
285
+ # Returns [true, name] if tool_choice forces a specific tool. The name
286
+ # is a String, like the names extract_used_function_names returns,
287
+ # whether the choice gave it as a String or a Symbol.
269
288
  #
270
289
  # @return [Array<Boolean, String|nil>]
271
290
  def tool_choice_forces_specific?
272
291
  if request.tool_choice.is_a?(Hash)
273
- [ true, request.tool_choice[:name] ]
292
+ [ true, request.tool_choice[:name]&.to_s ]
274
293
  else
275
294
  [ false, nil ]
276
295
  end
@@ -305,6 +324,23 @@ module ActiveAgent
305
324
 
306
325
  private
307
326
 
327
+ # Maps the request's tool_choice to RubyLLM's tool_prefs. Without it
328
+ # the model is free to answer without calling a tool even when the
329
+ # caller requires one. Nil once ToolChoiceClearing has cleared it, so
330
+ # a follow-up turn is not forced into another call.
331
+ #
332
+ # @param tools [Hash, nil] RubyLLM tools sent with this request
333
+ # @return [Hash, nil]
334
+ def ruby_llm_tool_prefs(tools)
335
+ return nil if tools.blank?
336
+
337
+ choice = request.tool_choice
338
+ choice = (choice[:name] || choice["name"]) if choice.is_a?(Hash)
339
+ return nil if choice.blank?
340
+
341
+ { choice: choice.to_sym }
342
+ end
343
+
308
344
  def ruby_llm_v2?
309
345
  Gem.loaded_specs.fetch("ruby_llm").version.segments.first >= 2
310
346
  end
@@ -341,11 +377,12 @@ module ActiveAgent
341
377
  def build_ruby_llm_messages(parameters)
342
378
  messages = []
343
379
 
344
- # Add system instructions
345
- if parameters[:instructions].present?
380
+ # Add system instructions, one message each: RubyLLM takes only a
381
+ # String as content, and instructions may be an Array
382
+ Array(parameters[:instructions]).compact_blank.each do |instruction|
346
383
  messages << ::RubyLLM::Message.new(
347
384
  role: :system,
348
- content: parameters[:instructions]
385
+ content: instruction
349
386
  )
350
387
  end
351
388
 
@@ -495,7 +532,7 @@ module ActiveAgent
495
532
  proxy = RubyLLM::ToolProxy.new(
496
533
  name: func[:name],
497
534
  description: func[:description] || "",
498
- parameters: func[:parameters] || {}
535
+ parameters: func[:parameters] || func[:input_schema] || {}
499
536
  )
500
537
  hash[proxy.name] = proxy
501
538
  end
@@ -538,7 +575,10 @@ module ActiveAgent
538
575
  end
539
576
 
540
577
  usage = ruby_llm_usage(response)
541
- hash[:usage] = usage if usage
578
+ if usage
579
+ usage[:total_tokens] = ruby_llm_total_tokens(usage)
580
+ hash[:usage] = usage
581
+ end
542
582
 
543
583
  hash[:model] = model_id if model_id
544
584
 
@@ -613,7 +653,8 @@ module ActiveAgent
613
653
  # none: the message has no Tokens then in ruby_llm 1.x. RubyLLM counts
614
654
  # cached tokens apart from the input, so input_tokens leaves them out.
615
655
  # A count the provider left out is left out here too, and Usage reads it
616
- # as zero.
656
+ # as zero. Total is not set here: a stream merges these hashes field by
657
+ # field and stamps the total once the merge is done.
617
658
  #
618
659
  # @param response [RubyLLM::Message]
619
660
  # @return [Hash, nil] Common::Usage attributes
@@ -640,6 +681,18 @@ module ActiveAgent
640
681
  }.compact
641
682
  end
642
683
  end
684
+
685
+ # Every token the response processed. ruby_llm's input excludes cache
686
+ # reads and writes: OpenAI and Gemini subtract them from the prompt
687
+ # count, and Anthropic already reports them apart from input_tokens.
688
+ # Output already includes thinking when that is billed as output, so
689
+ # reasoning_tokens is not added again.
690
+ #
691
+ # @param usage [Hash] fields from {#ruby_llm_usage}, after a stream merge
692
+ # @return [Integer]
693
+ def ruby_llm_total_tokens(usage)
694
+ %i[input_tokens output_tokens cached_tokens cache_creation_tokens].sum { |key| usage[key] || 0 }
695
+ end
643
696
  end
644
697
  end
645
698
  end
@@ -73,6 +73,11 @@ module ActiveAgent
73
73
  # question nobody asked.
74
74
  RANGE_FILTERABLE_TYPES = %i[date datetime time integer float decimal].freeze
75
75
 
76
+ # The range-filterable types whose bound must be a number, and the
77
+ # strings accepted as one ("42", "-3.5").
78
+ NUMERIC_TYPES = %i[integer float decimal].freeze
79
+ NUMERIC_BOUND = /\A-?\d+(?:\.\d+)?\z/
80
+
76
81
  # The comparison operators a range filter may use, mapped to the Arel
77
82
  # predicate that builds them. Names are the ones models reach for
78
83
  # unprompted (`before`/`after` for dates, `lt`/`gte` for numbers), so a
@@ -388,11 +393,21 @@ module ActiveAgent
388
393
  # Rails silently turns `where(col: { "before" => x })` into `col = NULL`,
389
394
  # which matches nothing and reports zero rather than failing — the worst
390
395
  # outcome for an agent, which reads it as a truthful empty answer. So an
391
- # unknown operator is rejected loudly here instead.
396
+ # unknown operator is rejected loudly here instead, and so is anything
397
+ # else that would answer without filtering as asked: an empty object
398
+ # (no condition at all), a comparison on a column not offered the range
399
+ # form, and a bound the column's type cannot read.
392
400
  #
393
401
  # @api private
394
- # @raise [UnpermittedAttribute] on an unknown operator
402
+ # @raise [UnpermittedAttribute] on an empty range, an unknown operator,
403
+ # a column that is not range-filterable, or an unreadable bound
395
404
  def range_predicates!(column, value)
405
+ if value.empty?
406
+ raise UnpermittedAttribute,
407
+ "The range object for `#{column}` names no comparison. " \
408
+ "Use one of: #{[ *RANGE_OPERATORS.keys, PRESENCE_OPERATOR ].join(", ")}"
409
+ end
410
+
396
411
  arel = @model.arel_table[column]
397
412
  type = @model.type_for_attribute(column)
398
413
 
@@ -406,10 +421,40 @@ module ActiveAgent
406
421
  "Allowed comparisons: #{[ *RANGE_OPERATORS.keys, PRESENCE_OPERATOR ].join(", ")}"
407
422
  end
408
423
 
409
- arel.public_send(predicate, type.cast(operand))
424
+ unless range_filterable?(column)
425
+ raise UnpermittedAttribute,
426
+ "`#{column}` cannot be compared as a range. " \
427
+ "Match it by an exact value, or ask {\"#{PRESENCE_OPERATOR}\": true|false}"
428
+ end
429
+
430
+ arel.public_send(predicate, range_bound!(column, type, operand))
410
431
  end
411
432
  end
412
433
 
434
+ # Casts a range bound to the column's type, refusing one it cannot read.
435
+ #
436
+ # ActiveModel casts what it cannot read to nil for a date or time
437
+ # (`published_at < NULL`, which matches nothing) and to 0 for a number
438
+ # ("thirty".to_i), so either would answer a question the model did
439
+ # not ask. A number column therefore takes only a number or a numeric
440
+ # string.
441
+ #
442
+ # @api private
443
+ # @raise [UnpermittedAttribute] on a bound the column's type cannot read
444
+ def range_bound!(column, type, operand)
445
+ bound = type.cast(operand)
446
+ readable = NUMERIC_TYPES.include?(type.type) ? numeric_bound?(operand) : !bound.nil?
447
+ return bound if readable
448
+
449
+ raise UnpermittedAttribute,
450
+ "#{operand.inspect} is not a valid `#{column}` to compare against"
451
+ end
452
+
453
+ # @api private
454
+ def numeric_bound?(operand)
455
+ operand.is_a?(Numeric) || (operand.is_a?(String) && operand.match?(NUMERIC_BOUND))
456
+ end
457
+
413
458
  # Builds IS NULL / IS NOT NULL for `{ "present" => ... }`.
414
459
  #
415
460
  # Only true and false (or their strings) are accepted: anything else
@@ -1,3 +1,3 @@
1
1
  module ActiveAgent
2
- VERSION = "1.9.9"
2
+ VERSION = "1.9.10"
3
3
  end
metadata CHANGED
@@ -1,14 +1,14 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: activeagent
3
3
  version: !ruby/object:Gem::Version
4
- version: 1.9.9
4
+ version: 1.9.10
5
5
  platform: ruby
6
6
  authors:
7
7
  - Justin Bowen
8
8
  autorequire:
9
9
  bindir: exe
10
10
  cert_chain: []
11
- date: 2026-11-19 00:00:00.000000000 Z
11
+ date: 2026-12-04 00:00:00.000000000 Z
12
12
  dependencies:
13
13
  - !ruby/object:Gem::Dependency
14
14
  name: actionpack
@@ -136,14 +136,14 @@ dependencies:
136
136
  requirements:
137
137
  - - "~>"
138
138
  - !ruby/object:Gem::Version
139
- version: '0.1'
139
+ version: '0.4'
140
140
  type: :runtime
141
141
  prerelease: false
142
142
  version_requirements: !ruby/object:Gem::Requirement
143
143
  requirements:
144
144
  - - "~>"
145
145
  - !ruby/object:Gem::Version
146
- version: '0.1'
146
+ version: '0.4'
147
147
  - !ruby/object:Gem::Dependency
148
148
  name: jbuilder
149
149
  requirement: !ruby/object:Gem::Requirement
@@ -210,16 +210,22 @@ dependencies:
210
210
  name: openai
211
211
  requirement: !ruby/object:Gem::Requirement
212
212
  requirements:
213
- - - "~>"
213
+ - - ">="
214
214
  - !ruby/object:Gem::Version
215
215
  version: '0.34'
216
+ - - "<"
217
+ - !ruby/object:Gem::Version
218
+ version: '2'
216
219
  type: :development
217
220
  prerelease: false
218
221
  version_requirements: !ruby/object:Gem::Requirement
219
222
  requirements:
220
- - - "~>"
223
+ - - ">="
221
224
  - !ruby/object:Gem::Version
222
225
  version: '0.34'
226
+ - - "<"
227
+ - !ruby/object:Gem::Version
228
+ version: '2'
223
229
  - !ruby/object:Gem::Dependency
224
230
  name: ruby_llm
225
231
  requirement: !ruby/object:Gem::Requirement