ruby_llm 2.2.1 → 2.2.3

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.
Files changed (46) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +2 -2
  3. data/lib/generators/ruby_llm/chat_ui/templates/tailwind/views/questions/_question.html.erb.tt +2 -2
  4. data/lib/generators/ruby_llm/chat_ui/templates/views/questions/_question.html.erb.tt +2 -2
  5. data/lib/ruby_llm/accounting/usage.rb +1 -0
  6. data/lib/ruby_llm/active_record/chat_methods.rb +28 -1
  7. data/lib/ruby_llm/active_record/model.rb +28 -3
  8. data/lib/ruby_llm/active_record/run_claims.rb +73 -18
  9. data/lib/ruby_llm/agent.rb +2 -2
  10. data/lib/ruby_llm/aliases.json +14 -0
  11. data/lib/ruby_llm/chat/tool_call_state.rb +1 -1
  12. data/lib/ruby_llm/chat/tool_concurrency.rb +58 -18
  13. data/lib/ruby_llm/chat.rb +20 -13
  14. data/lib/ruby_llm/code_execution/input_names.rb +80 -0
  15. data/lib/ruby_llm/code_execution/workspace.rb +4 -37
  16. data/lib/ruby_llm/code_execution.rb +44 -12
  17. data/lib/ruby_llm/configuration.rb +55 -0
  18. data/lib/ruby_llm/file_store/directory.rb +10 -7
  19. data/lib/ruby_llm/mcp/content.rb +2 -0
  20. data/lib/ruby_llm/model/pricing.rb +46 -0
  21. data/lib/ruby_llm/model.rb +55 -4
  22. data/lib/ruby_llm/models/lookup.rb +2 -1
  23. data/lib/ruby_llm/models.json +3167 -1709
  24. data/lib/ruby_llm/models.rb +1 -1
  25. data/lib/ruby_llm/protocol/stream_accumulator.rb +9 -4
  26. data/lib/ruby_llm/protocol/streaming.rb +22 -8
  27. data/lib/ruby_llm/protocols/bedrock/event_stream.rb +3 -7
  28. data/lib/ruby_llm/protocols/converse/streaming.rb +2 -2
  29. data/lib/ruby_llm/protocols/gemini/decisions.rb +106 -0
  30. data/lib/ruby_llm/protocols/gemini/streaming.rb +1 -1
  31. data/lib/ruby_llm/providers/gemini.rb +2 -0
  32. data/lib/ruby_llm/providers/minimax.rb +0 -6
  33. data/lib/ruby_llm/providers/openai/rerank.rb +13 -0
  34. data/lib/ruby_llm/providers/openai.rb +14 -0
  35. data/lib/ruby_llm/question.rb +82 -10
  36. data/lib/ruby_llm/railtie.rb +10 -2
  37. data/lib/ruby_llm/tool.rb +24 -5
  38. data/lib/ruby_llm/transport/connection.rb +8 -5
  39. data/lib/ruby_llm/transport/log_formatter.rb +39 -0
  40. data/lib/ruby_llm/transport/release_request.rb +6 -2
  41. data/lib/ruby_llm/version.rb +1 -1
  42. data/lib/ruby_llm.rb +0 -1
  43. data/skills/rubyllm/references/cost-and-tracing.md +1 -1
  44. data/skills/rubyllm/references/tools-and-agents.md +1 -1
  45. metadata +5 -3
  46. data/lib/ruby_llm/providers/minimax/chat_completions.rb +0 -48
@@ -48,11 +48,14 @@ module RubyLLM
48
48
  f.proxy = config.http_proxy if config.http_proxy
49
49
  f.ssl.update(ssl_snapshot(config.ssl)) if config.ssl
50
50
  f.response :logger,
51
- RubyLLM.logger,
51
+ config.logger || RubyLLM.logger,
52
52
  bodies: false,
53
53
  errors: true,
54
54
  headers: false,
55
- log_level: :debug
55
+ log_level: :debug,
56
+ formatter: LogFormatter do |formatter|
57
+ formatter.config = config
58
+ end
56
59
  f.response :raise_error
57
60
  yield f if block_given?
58
61
  end
@@ -186,7 +189,7 @@ module RubyLLM
186
189
 
187
190
  private
188
191
 
189
- def instrument_request(method, url)
192
+ def instrument_request(method, url, &block)
190
193
  payload = {
191
194
  provider: @provider.slug,
192
195
  method: method,
@@ -194,7 +197,7 @@ module RubyLLM
194
197
  }
195
198
 
196
199
  RubyLLM.instrument('request.ruby_llm', payload, config: @config) do |event|
197
- response = ReleaseRequest.release(yield)
200
+ response = ReleaseRequest.release(LogFormatter.with_config(@config, &block))
198
201
  event[:status] = response.status if response.respond_to?(:status)
199
202
  response
200
203
  rescue RubyLLM::Error => e
@@ -216,7 +219,7 @@ module RubyLLM
216
219
  proxy: @config.http_proxy,
217
220
  ssl: (self.class.ssl_snapshot(@config.ssl) if @config.ssl),
218
221
  logger: logger,
219
- log_bodies: logger.debug?,
222
+ log_bodies: @config.log_bodies.nil? ? logger.debug? : @config.log_bodies,
220
223
  log_regexp_timeout: @config.log_regexp_timeout,
221
224
  max_retries: @config.max_retries,
222
225
  retry_interval: @config.retry_interval,
@@ -7,7 +7,46 @@ module RubyLLM
7
7
  module Transport
8
8
  # A request that succeeded and was billed must not fail because a debug
9
9
  # log filter ran out of time on a large body.
10
+ #
11
+ # The cached connection's formatter is shared by every context, so the
12
+ # configuration whose credentials it filters is set in fiber storage for
13
+ # the duration of each request. A Connection.basic formatter serves one
14
+ # configuration and is given it directly.
10
15
  class LogFormatter < Faraday::Logging::Formatter # :nodoc:
16
+ CONFIG_KEY = :ruby_llm_log_config
17
+ FILTERED = '[FILTERED]'
18
+
19
+ attr_writer :config
20
+
21
+ def self.with_config(config)
22
+ previous = Fiber[CONFIG_KEY]
23
+ Fiber[CONFIG_KEY] = config
24
+ yield
25
+ ensure
26
+ Fiber[CONFIG_KEY] = previous
27
+ end
28
+
29
+ # Writes a debug line to +config+'s logger with its credentials
30
+ # replaced. The block runs only when the logger is at debug level.
31
+ def self.log_debug(config, &message)
32
+ (config.logger || RubyLLM.logger).debug { redact(message.call, config.secret_values) }
33
+ end
34
+
35
+ # Longer secrets go first, so a key that contains another key is
36
+ # replaced whole instead of leaving its remainder in the line.
37
+ def self.redact(text, secrets)
38
+ secrets.uniq.sort_by { |secret| -secret.length }
39
+ .reduce(text.to_s) { |output, secret| output.gsub(secret, FILTERED) }
40
+ end
41
+
42
+ # Faraday 2.12 and earlier write exception messages without
43
+ # apply_filters, so credentials are replaced on the way out instead.
44
+ # Connection.setup_logging logs every line at debug.
45
+ def debug(progname = nil)
46
+ config = @config || Fiber[CONFIG_KEY]
47
+ @logger.debug(progname) { config ? self.class.redact(yield, config.secret_values) : yield }
48
+ end
49
+
11
50
  private
12
51
 
13
52
  def apply_filters(output)
@@ -19,8 +19,12 @@ module RubyLLM
19
19
 
20
20
  env.request_body = nil
21
21
  env.request_headers = Faraday::Utils::Headers.new
22
- env.request.on_data = nil
23
- env.request.context = nil
22
+ # A response built by hand, such as one a protocol attaches to the
23
+ # error it raises, has no request options to clear.
24
+ if env.request
25
+ env.request.on_data = nil
26
+ env.request.context = nil
27
+ end
24
28
  response
25
29
  end
26
30
 
@@ -2,5 +2,5 @@
2
2
 
3
3
  module RubyLLM
4
4
  # The version of the ruby_llm gem, as a string.
5
- VERSION = '2.2.1'
5
+ VERSION = '2.2.3'
6
6
  end
data/lib/ruby_llm.rb CHANGED
@@ -6,7 +6,6 @@ require 'faraday/multipart'
6
6
  require 'faraday/retry'
7
7
  require 'json'
8
8
  require 'logger'
9
- require 'marcel'
10
9
  require 'schematist'
11
10
  require 'securerandom'
12
11
  require 'date'
@@ -2,7 +2,7 @@
2
2
 
3
3
  Read this when the task reports spend or adds instrumentation.
4
4
 
5
- - RubyLLM prices tokens from its model registry, so read cost through `message.cost.total` and `chat.cost.total`. Do not keep a table of token prices in the application, and do not copy them from another skill, an article, or memory: those go stale, and a table beside `cost` gives two answers. Prices come from [models.dev](https://models.dev) through the registry, or from the provider when it reports the amount. To check one, compare `RubyLLM.models.find(id, provider: :openai).pricing` with the provider's pricing page, and refresh with `RubyLLM.models.refresh`. Unknown cost is `nil`, not zero, and a total can leave out what the provider didn't report. The exception to the rule is a provider tool billed per use, such as web search, when the provider doesn't report the request's price: `cost.total` covers tokens only, so add that charge from the provider's rate (see `cost-and-usage-tracking/`).
5
+ - RubyLLM prices tokens from its model registry, so read cost through `message.cost.total` and `chat.cost.total`. Do not keep a table of token prices in the application, and do not copy them from another skill, an article, or memory: those go stale, and a table beside `cost` gives two answers. Prices come from [models.dev](https://models.dev) through the registry, or from the provider when it reports the amount. To check one, compare `RubyLLM.models.find(id, provider: :openai).pricing` with the provider's pricing page, and refresh with `RubyLLM.models.refresh`. When the application pays another price than the list price (an Azure Data Zone deployment, a negotiated rate, a model the registry has no price for), set it once with `config.price "model-id", provider: :azure, input: 0.12, output: 0.6` in `RubyLLM.configure`, in USD per million; `cache_read`, `cache_write`, `characters`, `audio_seconds` and `search_units` work the same way. Every `cost` then uses it and a refresh keeps it. It is global only: a context raises. Unknown cost is `nil`, not zero, and a total can leave out what the provider didn't report. The exception to the rule is a provider tool billed per use, such as web search, when the provider doesn't report the request's price: `cost.total` covers tokens only, so add that charge from the provider's rate (see `cost-and-usage-tracking/`).
6
6
  - Read tokens through `message.tokens.input`, `.output`, `.cache_read`, `.cache_write`, and `.thinking`. The ledger includes individual attempts; a successful answer can include earlier failed attempts.
7
7
  - To count cancelled and failed attempts, which may have no message, subscribe to `usage.ruby_llm`. It fires when each attempt finishes, with `status`, `tokens`, and `cost`. Rails also writes a row per attempt to `ruby_llm_usages`. Outside Rails, set `config.instrumenter` to receive it. Do not patch protocols or parse provider events for usage. Attribute usage with `owner:` on individual operations or `RubyLLM.with_owner` (2.1), and a chat's with `chat.with_owner(user)`, or in Rails by naming the association once with `acts_as_chat owner: :user` (2.2). Persisted chat usage keeps both its chat and owner associations.
8
8
  - Group related calls with `RubyLLM.workflow` and `workflow.step` for instrumentation. To send traces to an existing OpenTelemetry setup, call `RubyLLM::OpenTelemetry.enable` after configuring the SDK (2.1). RubyLLM never configures the SDK or exporters, and does not export prompts or responses.
@@ -2,7 +2,7 @@
2
2
 
3
3
  Read this when the task adds tools, agents, subagents, or per-request state.
4
4
 
5
- - Subclass `RubyLLM::Tool`. Use `description`, `parameter`, or a `parameters` block, and keyword arguments on `execute`. Register tools with `with_tools`; configure choice and concurrency with `with_tool_options`. For models that loop on tools, set `with_tool_options(rounds: 25)` (off by default, 2.2): after that many model responses asking for tools, `complete` raises `RubyLLM::ToolRoundLimitError` with every call answered, and calling `complete` again continues with a fresh count. To stop one response from making hundreds of calls, add `calls: 50` (2.2.1): the calls past it get an error result telling the model to go step by step, without running or asking for approval. Keep application authorization in the tool or underlying service. Use `requires_approval` when the product needs a user's decision before execution, and `ask` inside `execute` when the tool needs the user's answer to go on: the call runs again from the top with the answer, so ask first, then act (2.2). Call `halt(result)` in a tool that says the last word, so the turn ends without another model call (2.2). Declare `exclusive` on tools that share state, such as a browser page, so they run alone in a concurrent round (2.2). With large tool sets, pass `defer: true` to `with_tools` or `with_mcp` (or declare `defer` on the class) so the model searches for tools instead of receiving them all (2.1).
5
+ - Subclass `RubyLLM::Tool`. Use `description`, `parameter`, or a `parameters` block, and keyword arguments on `execute`. Register tools with `with_tools`; configure choice and concurrency with `with_tool_options`. For models that loop on tools, set `with_tool_options(rounds: 25)` (off by default, 2.2): after that many model responses asking for tools, `complete` raises `RubyLLM::ToolRoundLimitError` with every call answered, and calling `complete` again continues with a fresh count. To stop one response from making hundreds of calls, add `calls: 50` (2.2.1): the calls past it get an error result telling the model to go step by step, without running or asking for approval. Keep application authorization in the tool or underlying service. Use `requires_approval` when the product needs a user's decision before execution, and `ask` inside `execute` when the tool needs the user's answer to go on: the call runs again from the top with the answer, so ask first, then act (2.2); if a run asks a different question in an answered one's place (a skipped `ask`, changed choices), it pauses on the new question instead of reusing the old answer. Call `halt(result)` in a tool that says the last word, so the turn ends without another model call (2.2). Declare `exclusive` on tools that share state, such as a browser page, so they run alone in a concurrent round (2.2). To cap how many calls run at once without skipping any, add `workers: 4` next to `concurrency:` (2.2.3); for a limit shared between chats, take a slot from a `Thread::Queue` in `around_tool_call`. With large tool sets, pass `defer: true` to `with_tools` or `with_mcp` (or declare `defer` on the class) so the model searches for tools instead of receiving them all (2.1).
6
6
  - To hand work to another agent, put the agent class in `tools` (or `ResearchAgent.to_tool(customer:)` to fix its inputs): the model gives it a task, and a fresh agent answers within the call (2.2). That subagent can't wait, so it raises `RubyLLM::ConfigurationError` if it stops for an approval, a question, or a task. For a subagent that waits for a person in Rails, write a tool whose `execute` creates the subagent's chat with `BillingAgent.create!` and asks it, returns `RubyLLM::Task.new(status: :input_required, data: { "chat_id" => chat.id })` while that chat is `waiting?`, and whose `resume` finds it with `BillingAgent.find` and calls `complete`. The person answers the subagent chat's `pending_questions`; see `agents/#subagents-that-wait-for-a-person`.
7
7
  - When tools need a tenant, `Current` attributes, or other per-request state, set it with `around_tool_call` (or the agent macro), which runs in the tool's own thread or fiber (2.2), rather than passing the chat into every tool.
8
8
  - To turn a tool's exceptions into results the model reads, declare `rescue_from` on a base tool class, on `RubyLLM::Tool` for every tool, on `RubyLLM::CodeExecution`, or on an MCP server's class, rather than prepending a module around `call` (2.2). Subclasses use handlers declared later on their parents. The handler's return value becomes the call's result; re-raise to stop the chat. Handlers cover the calls a chat makes. Calling a tool directly (`tool.call(**args)` or `execute`) is still supported and isn't wrapped by handlers, so its exceptions reach the caller. A question from `ask` and a cancellation never reach it.
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: ruby_llm
3
3
  version: !ruby/object:Gem::Version
4
- version: 2.2.1
4
+ version: 2.2.3
5
5
  platform: ruby
6
6
  authors:
7
7
  - Carmine Paolino
@@ -383,6 +383,7 @@ files:
383
383
  - lib/ruby_llm/chunk.rb
384
384
  - lib/ruby_llm/citation.rb
385
385
  - lib/ruby_llm/code_execution.rb
386
+ - lib/ruby_llm/code_execution/input_names.rb
386
387
  - lib/ruby_llm/code_execution/language.rb
387
388
  - lib/ruby_llm/code_execution/node_installation.rb
388
389
  - lib/ruby_llm/code_execution/packages.rb
@@ -577,6 +578,7 @@ files:
577
578
  - lib/ruby_llm/protocols/gemini/batches.rb
578
579
  - lib/ruby_llm/protocols/gemini/caches.rb
579
580
  - lib/ruby_llm/protocols/gemini/chat.rb
581
+ - lib/ruby_llm/protocols/gemini/decisions.rb
580
582
  - lib/ruby_llm/protocols/gemini/embedding_batches.rb
581
583
  - lib/ruby_llm/protocols/gemini/embeddings.rb
582
584
  - lib/ruby_llm/protocols/gemini/file_transcription.rb
@@ -721,7 +723,6 @@ files:
721
723
  - lib/ruby_llm/providers/meta/responses.rb
722
724
  - lib/ruby_llm/providers/minimax.rb
723
725
  - lib/ruby_llm/providers/minimax/anthropic.rb
724
- - lib/ruby_llm/providers/minimax/chat_completions.rb
725
726
  - lib/ruby_llm/providers/minimax/responses.rb
726
727
  - lib/ruby_llm/providers/mistral.rb
727
728
  - lib/ruby_llm/providers/mistral/capabilities.rb
@@ -753,6 +754,7 @@ files:
753
754
  - lib/ruby_llm/providers/openai.rb
754
755
  - lib/ruby_llm/providers/openai/capabilities.rb
755
756
  - lib/ruby_llm/providers/openai/models.rb
757
+ - lib/ruby_llm/providers/openai/rerank.rb
756
758
  - lib/ruby_llm/providers/openai/responses.rb
757
759
  - lib/ruby_llm/providers/openrouter.rb
758
760
  - lib/ruby_llm/providers/openrouter/chat.rb
@@ -884,7 +886,7 @@ metadata:
884
886
  funding_uri: https://github.com/sponsors/crmne
885
887
  rubygems_mfa_required: 'true'
886
888
  post_install_message: |
887
- RubyLLM 2.2.1
889
+ RubyLLM 2.2.3
888
890
 
889
891
  Upgrading? Read the upgrade guide before you boot:
890
892
 
@@ -1,48 +0,0 @@
1
- # frozen_string_literal: true
2
-
3
- module RubyLLM
4
- module Providers
5
- class MiniMax
6
- # MiniMax's own Chat Completion v2 route, used only for structured
7
- # output on the one model that applies response_format. That model
8
- # nests its answer under the schema name, so parsing removes the
9
- # wrapper, which cannot be done part by part on a stream.
10
- class ChatCompletions < Protocols::ChatCompletions
11
- def completion_url
12
- "#{@provider.media_base}/v1/text/chatcompletion_v2"
13
- end
14
-
15
- def render_payload(messages, schema: nil, stream: false, **)
16
- raise ArgumentError, "#{@model.id} does not stream structured output" if schema && stream
17
-
18
- @schema_name = schema&.dig(:name)
19
- super
20
- end
21
-
22
- def parse_completion_body(data, raw:)
23
- super(unwrap_schema_result(data), raw: raw)
24
- end
25
-
26
- private
27
-
28
- def unwrap_schema_result(data)
29
- content = data.dig('choices', 0, 'message', 'content')
30
- return data unless @schema_name && content.is_a?(String)
31
-
32
- parsed = parse_json(content)
33
- return data unless parsed.is_a?(Hash) && parsed.keys == [@schema_name]
34
-
35
- choice = data['choices'][0]
36
- message = choice['message'].merge('content' => JSON.generate(parsed[@schema_name]))
37
- data.merge('choices' => [choice.merge('message' => message), *data['choices'][1..]])
38
- end
39
-
40
- def parse_json(content)
41
- JSON.parse(content)
42
- rescue JSON::ParserError
43
- nil
44
- end
45
- end
46
- end
47
- end
48
- end