smith-agents 0.14.0 → 0.16.0

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 (64) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +147 -0
  3. data/README.md +6 -4
  4. data/docs/AGENTS.md +64 -8
  5. data/docs/BUDGETS.md +14 -1
  6. data/docs/CONFIGURATION.md +9 -3
  7. data/docs/ERRORS_AND_RETRIES.md +13 -0
  8. data/docs/PATTERNS.md +98 -8
  9. data/docs/PERSISTENCE.md +21 -7
  10. data/docs/TOOLS_AND_GUARDRAILS.md +7 -0
  11. data/lib/smith/agent/content_parts.rb +18 -8
  12. data/lib/smith/agent/image_request.rb +38 -0
  13. data/lib/smith/agent/invocation_preparation.rb +2 -2
  14. data/lib/smith/agent/lifecycle.rb +2 -0
  15. data/lib/smith/agent/output_integrity.rb +1 -1
  16. data/lib/smith/agent/output_recovery.rb +10 -1
  17. data/lib/smith/agent/paint_input.rb +42 -0
  18. data/lib/smith/agent/painted_answer.rb +70 -0
  19. data/lib/smith/agent/prompt_cache.rb +31 -0
  20. data/lib/smith/agent/provider_call_timing.rb +2 -1
  21. data/lib/smith/agent/provider_completion.rb +4 -3
  22. data/lib/smith/agent/provider_failure_handling.rb +27 -5
  23. data/lib/smith/agent/provider_paint.rb +128 -0
  24. data/lib/smith/agent/provider_request.rb +29 -4
  25. data/lib/smith/agent/provider_usage.rb +27 -2
  26. data/lib/smith/agent/usage_tracking.rb +3 -1
  27. data/lib/smith/agent.rb +6 -1
  28. data/lib/smith/budget/host_ledger.rb +3 -1
  29. data/lib/smith/budget/request_hold.rb +49 -3
  30. data/lib/smith/errors.rb +8 -0
  31. data/lib/smith/pricing/catalog_validation.rb +20 -1
  32. data/lib/smith/pricing/images.rb +29 -0
  33. data/lib/smith/pricing.rb +37 -16
  34. data/lib/smith/providers/output_limit.rb +22 -1
  35. data/lib/smith/providers/request_holds.rb +29 -4
  36. data/lib/smith/providers/request_outcome.rb +39 -0
  37. data/lib/smith/providers/stop_reason.rb +4 -2
  38. data/lib/smith/streaming/session.rb +2 -0
  39. data/lib/smith/streaming.rb +3 -1
  40. data/lib/smith/version.rb +1 -1
  41. data/lib/smith/workflow/agent_result.rb +5 -1
  42. data/lib/smith/workflow/composite/effects.rb +3 -1
  43. data/lib/smith/workflow/evaluator_optimizer.rb +93 -17
  44. data/lib/smith/workflow/execution.rb +1 -0
  45. data/lib/smith/workflow/failure_reconstructor.rb +1 -0
  46. data/lib/smith/workflow/failure_record.rb +7 -3
  47. data/lib/smith/workflow/failure_record_validator.rb +7 -7
  48. data/lib/smith/workflow/graph/optimization_contract.rb +1 -0
  49. data/lib/smith/workflow/graph/stream_diagnostic.rb +9 -4
  50. data/lib/smith/workflow/graph/transition_optimization_configuration.rb +1 -0
  51. data/lib/smith/workflow/guarded_step_execution.rb +1 -1
  52. data/lib/smith/workflow/nested_execution.rb +18 -6
  53. data/lib/smith/workflow/nested_items_execution.rb +122 -0
  54. data/lib/smith/workflow/optimization_state.rb +7 -2
  55. data/lib/smith/workflow/optimizer_batch.rb +21 -9
  56. data/lib/smith/workflow/parallel/nested_execution.rb +4 -1
  57. data/lib/smith/workflow/parallel/root_execution.rb +2 -1
  58. data/lib/smith/workflow/parallel.rb +13 -5
  59. data/lib/smith/workflow/step_io.rb +10 -4
  60. data/lib/smith/workflow/step_stream.rb +9 -0
  61. data/lib/smith/workflow/transition.rb +54 -19
  62. data/lib/smith/workflow/usage_entry.rb +5 -0
  63. data/lib/smith.rb +2 -0
  64. metadata +9 -1
data/lib/smith/agent.rb CHANGED
@@ -34,7 +34,8 @@ module Smith
34
34
  subclass.instance_variable_set(:@fallback_models_block, @fallback_models_block)
35
35
  subclass.instance_variable_set(:@model_block, @model_block)
36
36
  subclass.instance_variable_set(:@tool_budget_exhaustion, @tool_budget_exhaustion)
37
- %i[@on_truncation @on_refusal @output_contract @output_repairs].each do |name|
37
+ subclass.instance_variable_set(:@prompt_cache, @prompt_cache)
38
+ %i[@on_truncation @on_refusal @output_contract @output_repairs @image_request].each do |name|
38
39
  subclass.instance_variable_set(name, instance_variable_get(name))
39
40
  end
40
41
  subclass.instance_variable_set(:@execution_identity, nil)
@@ -152,9 +153,13 @@ require_relative "agent/fallback_configuration"
152
153
  require_relative "agent/reserved_input_bridge"
153
154
  require_relative "agent/chat_construction"
154
155
  require_relative "agent/output_policy"
156
+ require_relative "agent/prompt_cache"
157
+ require_relative "agent/image_request"
155
158
 
156
159
  Smith::Agent.extend(Smith::Agent::DynamicConfiguration)
157
160
  Smith::Agent.extend(Smith::Agent::FallbackConfiguration)
158
161
  Smith::Agent.extend(Smith::Agent::ReservedInputBridge)
159
162
  Smith::Agent.extend(Smith::Agent::ChatConstruction)
160
163
  Smith::Agent.extend(Smith::Agent::OutputPolicy)
164
+ Smith::Agent.extend(Smith::Agent::PromptCache)
165
+ Smith::Agent.extend(Smith::Agent::ImageRequest)
@@ -74,7 +74,9 @@ module Smith
74
74
  Amount.new(
75
75
  input_tokens: input + reads + writes, output_tokens: output,
76
76
  cost: Pricing.compute_cost(model:, provider:, input_tokens: input, output_tokens: output,
77
- cache_read_tokens: reads, cache_write_tokens: writes, mode:)
77
+ cache_read_tokens: reads, cache_write_tokens: writes, mode:,
78
+ image_input_tokens: usage.image_input_tokens || 0,
79
+ image_output_tokens: usage.image_output_tokens || 0)
78
80
  )
79
81
  end
80
82
 
@@ -41,11 +41,57 @@ module Smith
41
41
  context_window = model.context_window if model.respond_to?(:context_window)
42
42
  input = [input_estimate(*request.values_at(:messages, :tools, :schema)), context_window].compact.min
43
43
  output = [output_cap(provider, request[:params], model), Smith.config.budget_hold_output_tokens].compact.min
44
- Amount.new(input_tokens: input, output_tokens: output,
45
- cost: Pricing.compute_cost(model: model.id, provider: provider.to_s, input_tokens: input,
46
- output_tokens: output, mode:))
44
+ price = price_for(provider, model, output, mode)
45
+ Amount.new(input_tokens: input, output_tokens: output, cost: most_cost(price, input, cache_marked?(request)))
47
46
  end
48
47
 
48
+ # The hold for an image a provider is asked to paint (Provider#paint):
49
+ # its prompt counted as text and each image it draws from (`images`, a
50
+ # count) at IMAGE_TOKENS, priced as image input, and the image it
51
+ # writes at what the pricing catalog says its `size` and `quality`
52
+ # write (Pricing.image_output_tokens), priced as image output. Unpriced
53
+ # (a nil cost) when the catalog says nothing of that size and quality.
54
+ def for_image(provider:, model:, prompt:, images:, image:)
55
+ text = ((prompt.to_s.bytesize + BYTES_PER_TOKEN - 1) / BYTES_PER_TOKEN) + MESSAGE_TOKENS
56
+ image_input = images * IMAGE_TOKENS
57
+ output = Pricing.image_output_tokens(model:, provider: provider.to_s, **image.slice(:size, :quality))
58
+ cost = output && Pricing.compute_cost(model:, provider: provider.to_s, input_tokens: text + image_input,
59
+ output_tokens: output, image_input_tokens: image_input,
60
+ image_output_tokens: output)
61
+ Amount.new(input_tokens: text + image_input, output_tokens: output || 0, cost:)
62
+ end
63
+
64
+ # The request's cost with its input as the tokens name it: read plainly,
65
+ # or written to a prompt cache.
66
+ def price_for(provider, model, output, mode)
67
+ lambda do |**tokens|
68
+ Pricing.compute_cost(model: model.id, provider: provider.to_s, output_tokens: output, mode:, **tokens)
69
+ end
70
+ end
71
+
72
+ # A request that marks a block for a prompt cache may have all its input
73
+ # written to it, which can cost more than input read plainly, so it is
74
+ # held at the dearer of the two; any other request, or a model with no
75
+ # cache-write rate, is held as plain input.
76
+ def most_cost(price, input, cached)
77
+ costs = [price.call(input_tokens: input)]
78
+ costs << price.call(input_tokens: 0, cache_write_tokens: input) if cached
79
+ costs.compact.max
80
+ end
81
+
82
+ # A cache marker on the request's own params or on a block of one of its
83
+ # messages, where Smith puts a cached part's.
84
+ def cache_marked?(request)
85
+ marked_block?(request[:params]) || Array(request[:messages]).any? { marked_message?(_1) }
86
+ end
87
+
88
+ def marked_message?(message)
89
+ content = message.content if message.respond_to?(:content)
90
+ content.is_a?(::RubyLLM::Content::Raw) && Array(content.value).any? { marked_block?(_1) }
91
+ end
92
+
93
+ def marked_block?(block) = block.is_a?(Hash) && !(block[:cache_control] || block["cache_control"]).nil?
94
+
49
95
  def input_estimate(messages, tools, schema)
50
96
  counter = Counter.new
51
97
  Array(messages).each { counter.message(_1) }
data/lib/smith/errors.rb CHANGED
@@ -53,6 +53,7 @@ module Smith
53
53
  @retry_forbidden_classes ||= [
54
54
  Smith::ToolCaptureFailed,
55
55
  Smith::ToolOutcomeUncertain,
56
+ Smith::RequestOutcomeUncertain,
56
57
  Smith::ToolExecutionNotAdmitted,
57
58
  Smith::ToolFailureNotificationFailed,
58
59
  Smith::BoundedCompletionError,
@@ -104,6 +105,13 @@ module Smith
104
105
  class ToolDispatchRejected < Error; end
105
106
  class BoundedCompletionError < Error; end
106
107
  class ToolOutcomeUncertain < Error; end
108
+
109
+ # A provider request that may have been billed although no answer came back:
110
+ # it was sent, then its answer timed out or its connection was lost. Never
111
+ # retried and never answered by a fallback, either of which could pay for
112
+ # the same work twice; its cause is the transport's error.
113
+ class RequestOutcomeUncertain < Error; end
114
+
107
115
  class AgentError < Error; end
108
116
 
109
117
  class BlankAgentOutputError < AgentError
@@ -5,7 +5,9 @@ module Smith
5
5
  # Admission-time catalog validation, the raising surface for the rules
6
6
  # `compute_cost` applies without raising. See Pricing.validate_catalog!.
7
7
  module CatalogValidation
8
- OPTIONAL_RATE_KEYS = %i[cache_read_cost_per_token cache_write_cost_per_token].freeze
8
+ OPTIONAL_RATE_KEYS = %i[
9
+ cache_read_cost_per_token cache_write_cost_per_token image_input_cost_per_token image_output_cost_per_token
10
+ ].freeze
9
11
 
10
12
  module_function
11
13
 
@@ -39,8 +41,25 @@ module Smith
39
41
  [entry, *tiers].each { |rates| validate_optional_rates!(key, rates) }
40
42
  values_at(entry, :batch_discount).each { |discount| validate_batch_discount!(key, discount) }
41
43
  reject_tier_batch_discount!(key, tiers)
44
+ values_at(entry, :image_output_tokens).each { |sizes| validate_image_output_tokens!(key, sizes) }
42
45
  end
43
46
 
47
+ # What an image of each size and quality writes, as the provider counts
48
+ # it: { "1024x1024" => { "low" => 823 } }, each count a positive Integer.
49
+ def validate_image_output_tokens!(key, sizes)
50
+ return if sizes.is_a?(Hash) && sizes.all? { |size, qualities| image_option?(size) && image_counts?(qualities) }
51
+
52
+ raise Smith::PricingConfigurationError, "image_output_tokens for #{key.inspect} must map each size to " \
53
+ "its qualities' positive Integer token counts"
54
+ end
55
+
56
+ def image_counts?(qualities)
57
+ qualities.is_a?(Hash) && !qualities.empty? &&
58
+ qualities.all? { |quality, count| image_option?(quality) && count.is_a?(Integer) && count.positive? }
59
+ end
60
+
61
+ def image_option?(value) = (value.is_a?(String) || value.is_a?(Symbol)) && !value.to_s.empty?
62
+
44
63
  def validate_optional_rates!(key, rates)
45
64
  return unless rates.is_a?(Hash)
46
65
 
@@ -0,0 +1,29 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Smith
4
+ module Pricing
5
+ # A model's image tokens, priced apart from its text (Pricing.compute_cost)
6
+ # and held at what its catalog entry says an image writes
7
+ # (Pricing.image_output_tokens).
8
+ module Images
9
+ module_function
10
+
11
+ # The image parts are inside the plain counts (`counts`: input, output),
12
+ # already priced at the plain rates: each adds what its image rate asks
13
+ # beyond its plain one, and never more of them than the plain count holds.
14
+ def priced(rates, counts, image_input_tokens, image_output_tokens)
15
+ ([image_input_tokens, counts[0]].min * ((rates[:image_input] || rates[:input]) - rates[:input])) +
16
+ ([image_output_tokens, counts[1]].min * ((rates[:image_output] || rates[:output]) - rates[:output]))
17
+ end
18
+
19
+ # What one image of `size` and `quality` writes, as the entry's
20
+ # `image_output_tokens` says; nil when it says nothing.
21
+ def output_tokens(entry, size, quality)
22
+ count = [:image_output_tokens, size, quality].reduce(entry) do |level, key|
23
+ Pricing.__send__(:value_at, level, key.to_s.to_sym) if level.is_a?(Hash)
24
+ end
25
+ count if count.is_a?(Integer) && count.positive?
26
+ end
27
+ end
28
+ end
29
+ end
data/lib/smith/pricing.rb CHANGED
@@ -1,6 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require_relative "pricing/catalog_validation"
4
+ require_relative "pricing/images"
4
5
 
5
6
  module Smith
6
7
  module Pricing
@@ -23,14 +24,21 @@ module Smith
23
24
  # Both shapes accept two optional rates beside input and output:
24
25
  # `:cache_read_cost_per_token` and `:cache_write_cost_per_token`, for
25
26
  # input read from or written to a prompt cache, which providers report
26
- # apart from uncached input. An entry may also carry `:batch_discount`,
27
- # the fraction a provider's batch API takes off (0.5 for half price),
28
- # applied to the whole cost of a call made in `mode: :batch`. These are
29
- # configured per catalog: a missing cache rate prices those tokens at 0,
30
- # and a missing batch discount is 0, so a batch call costs the full
31
- # rate. Tiers are
32
- # chosen on the call's total input, uncached plus cache read plus cache
33
- # write, since that is what long-context premiums are measured against.
27
+ # apart from uncached input. A model that reads or draws images may
28
+ # price its image tokens apart: `:image_input_cost_per_token` for the
29
+ # image part of its uncached input and `:image_output_cost_per_token`
30
+ # for the image part of its output, each falling back to the plain rate
31
+ # when absent, so an image token is never priced below a text one. Its
32
+ # entry says what an image of each size and quality writes
33
+ # (`:image_output_tokens`, { "1024x1024" => { "low" => 823 } }), which a
34
+ # request's hold is priced from (Budget::RequestHold). An entry may also
35
+ # carry `:batch_discount`, the fraction a provider's batch API takes off
36
+ # (0.5 for half price), applied to the whole cost of a call made in
37
+ # `mode: :batch`. These are configured per catalog: a missing cache rate
38
+ # prices those tokens at 0, and a missing batch discount is 0, so a batch
39
+ # call costs the full rate. Tiers are chosen on the call's total input,
40
+ # uncached plus cache read plus cache write, since that is what
41
+ # long-context premiums are measured against.
34
42
  #
35
43
  # Catalog keys are normalized once per assigned catalog object:
36
44
  # ["provider", "model"] / [:provider, :model] -> provider-qualified
@@ -44,17 +52,28 @@ module Smith
44
52
  # so accounting paths cannot mask a provider error with a pricing
45
53
  # configuration error. The legacy-only-key policy is enforced at
46
54
  # catalog admission time via `validate_catalog!`.
55
+ # `image_input_tokens` and `image_output_tokens` are the image parts of
56
+ # `input_tokens` and `output_tokens`, never more than them.
47
57
  # rubocop:disable Metrics/ParameterLists
48
58
  def self.compute_cost(model:, input_tokens:, output_tokens:, provider: nil, cache_read_tokens: 0,
49
- cache_write_tokens: 0, mode: :sync)
59
+ cache_write_tokens: 0, image_input_tokens: 0, image_output_tokens: 0, mode: :sync)
50
60
  counts = [input_tokens, output_tokens, cache_read_tokens, cache_write_tokens].map { |count| token_count(count) }
51
61
  rates = rates_for(model, provider, counts[0] + counts[2] + counts[3])
52
62
  return nil unless rates
53
63
 
54
- apply_mode(priced_tokens(rates, *counts), rates.fetch(:entry), mode)
64
+ images = Images.priced(rates, counts, token_count(image_input_tokens), token_count(image_output_tokens))
65
+ apply_mode(priced_tokens(rates, *counts) + images, rates.fetch(:entry), mode)
55
66
  end
56
67
  # rubocop:enable Metrics/ParameterLists
57
68
 
69
+ # What one image of `size` and `quality` writes on this model, as its
70
+ # catalog entry says (`:image_output_tokens`); nil when it says nothing.
71
+ def self.image_output_tokens(model:, provider:, size:, quality:)
72
+ catalog = Smith.config.pricing
73
+ entry = lookup_entry(normalized_index(catalog), model, provider) if catalog.is_a?(Hash)
74
+ Images.output_tokens(entry, size, quality)
75
+ end
76
+
58
77
  # True when the call's cache tokens were priced at 0 because its rates
59
78
  # have no cache rate for them; false when they were priced, absent, or
60
79
  # the call is unpriced altogether.
@@ -175,7 +194,8 @@ module Smith
175
194
  text unless text.nil? || text.empty?
176
195
  end
177
196
 
178
- # Returns { input:, output:, cache_read:, cache_write:, entry: } or nil
197
+ # Returns { input:, output:, cache_read:, cache_write:, image_input:,
198
+ # image_output:, entry: } or nil
179
199
  # if no applicable input and output rate. Tiered shape is recognized by
180
200
  # the presence of a :tiers key; flat shape is the legacy default. A tier
181
201
  # without its own cache rate uses the entry's.
@@ -191,14 +211,14 @@ module Smith
191
211
  end
192
212
 
193
213
  def self.rates_from(source, defaults: nil)
194
- rates = %i[input output cache_read cache_write].to_h { |name| [name, rate_at(source, defaults, name)] }
214
+ rates = RATES.to_h { |name| [name, rate_at(source, defaults, name)] }
195
215
  rates if rates[:input] && rates[:output]
196
216
  end
197
217
 
198
- # A tier's own rate, else, for a cache rate, the entry's.
218
+ # A tier's own rate, else, for a cache or image rate, the entry's.
199
219
  def self.rate_at(source, defaults, name)
200
220
  rate = value_at(source, :"#{name}_cost_per_token")
201
- rate = value_at(defaults, :"#{name}_cost_per_token") if rate.nil? && defaults && CACHE_RATES.include?(name)
221
+ rate = value_at(defaults, :"#{name}_cost_per_token") if rate.nil? && defaults && ENTRY_RATES.include?(name)
202
222
  rate if rate.is_a?(Numeric)
203
223
  end
204
224
 
@@ -207,8 +227,9 @@ module Smith
207
227
  maximum.nil? || input_tokens <= maximum
208
228
  end
209
229
 
210
- CACHE_RATES = %i[cache_read cache_write].freeze
211
- private_constant :CACHE_RATES
230
+ RATES = %i[input output cache_read cache_write image_input image_output].freeze
231
+ ENTRY_RATES = %i[cache_read cache_write image_input image_output].freeze
232
+ private_constant :RATES, :ENTRY_RATES
212
233
 
213
234
  private_class_method :rate_at, :lookup_entry, :normalized_index, :build_normalized_index, :canonical_key,
214
235
  :array_key, :text_key, :scalar_key, :resolve_rates, :rates_from, :tier_applies?,
@@ -5,7 +5,9 @@ module Smith
5
5
  # A provider's own parameter for the most tokens a response may hold,
6
6
  # merged into the request when an agent retries a cut-off response
7
7
  # (`on_truncation retry_with: { max_tokens: n }`). A provider not listed
8
- # here is not retried.
8
+ # here is not retried. An agent's own cap (`params max_tokens:`) goes to
9
+ # an OpenAI model that reasons under the name it takes on every attempt
10
+ # (`named`): its Chat Completions refuses `max_tokens` from those models.
9
11
  module OutputLimit
10
12
  PROVIDERS = %w[anthropic openai gemini vertexai bedrock].freeze
11
13
  PARAM_PATHS = {
@@ -42,6 +44,25 @@ module Smith
42
44
  anthropic_default(model_reference.model_id) if provider.to_s == "anthropic"
43
45
  end
44
46
 
47
+ # The params with the cap of a request to an OpenAI model that reasons
48
+ # under the name its path takes (`max_completion_tokens`, or
49
+ # `max_output_tokens` on the Responses API); any other request, an
50
+ # OpenAI-compatible server's `max_tokens` among them, unchanged.
51
+ def named(provider, chat_params, model_reference)
52
+ limit = provider.to_s == "openai" && reasons?(model_reference) ? current("openai", chat_params, nil) : nil
53
+ return chat_params unless limit.is_a?(Integer)
54
+
55
+ caps = PARAM_PATHS.fetch("openai").flatten.flat_map { |key| [key, key.to_s] }
56
+ unnamed = chat_params.except(*caps)
57
+ unnamed.merge(params("openai", unnamed, limit))
58
+ end
59
+
60
+ def reasons?(model_reference)
61
+ ::RubyLLM.models.find(model_reference.model_id.to_s, "openai").capabilities.include?("reasoning")
62
+ rescue ::RubyLLM::ModelNotFoundError
63
+ false
64
+ end
65
+
45
66
  def openai_key(chat_params)
46
67
  return :max_output_tokens if responses?(chat_params)
47
68
 
@@ -17,7 +17,11 @@ module Smith
17
17
  # it failed before anything came back, its hold is released. Only the
18
18
  # call's own provider object is held, so a tool's own RubyLLM call is
19
19
  # not. While a batch step captures its request, the hold is noted on the
20
- # capture instead, for the batch to reserve.
20
+ # capture instead, for the batch to reserve. An image agent's request
21
+ # (`Provider#paint`) is held the same way, at the image its size and
22
+ # quality write (Budget::RequestHold.for_image); one sent whose answer
23
+ # never came (RequestOutcome) is charged its whole hold, as it may have
24
+ # been billed.
21
25
  module RequestHolds
22
26
  HELD = :smith_request_holds
23
27
  private_constant :HELD
@@ -74,18 +78,31 @@ module Smith
74
78
  end
75
79
  end
76
80
 
81
+ # The paint (`request`: the provider's own), held.
82
+ def paint(provider, prompt, request, &paint)
83
+ holder = holder_for(provider)
84
+ return paint.call unless holder
85
+
86
+ amount = Budget::RequestHold.for_image(
87
+ provider: provider.slug, model: request.fetch(:model), prompt:, images: Array(request[:with]).length,
88
+ image: { size: request.fetch(:size), quality: request[:params].to_h[:quality] }
89
+ )
90
+ held(holder, amount, request.fetch(:model).to_s, charge_when_lost: true) { paint.call }
91
+ end
92
+
77
93
  def capture(provider, exchange, args, kwargs, block, &request)
78
94
  exchange.hold ||= hold(provider, args, kwargs, mode: :batch) if exchange.holding && exchange.result.nil?
79
95
  request.call(*args, **kwargs, &block)
80
96
  end
81
97
 
82
- def held(holder, amount, model_id)
98
+ def held(holder, amount, model_id, charge_when_lost: false)
83
99
  key, reserved = open_round(holder, amount)
84
100
  stream = Stream.new(false)
85
101
  begin
86
102
  message = busy(holder) { yield(stream) }
87
103
  rescue Exception => e # rubocop:disable Lint/RescueException -- an interrupted request settles too
88
- settle_failed(holder, key, spent(holder.provider, model_id, e) || (amount if stream.started), reserved)
104
+ lost = stream.started || (charge_when_lost && RequestOutcome.uncertain?(e))
105
+ settle_failed(holder, key, spent(holder.provider, model_id, e) || (amount if lost), reserved)
89
106
  raise
90
107
  end
91
108
  Budget::HostLedger.settle(holder.ledger, key, spent(holder.provider, model_id, message) || amount)
@@ -118,7 +135,11 @@ module Smith
118
135
  # What a request spent, from its reply (or the error that reported
119
136
  # usage), priced for the request's model; nil when it reported none.
120
137
  def spent(provider, model_id, reply)
121
- usage = Agent::ProviderUsage.from_message(reply)
138
+ usage = if reply.is_a?(::RubyLLM::Image)
139
+ Agent::ProviderUsage.from_image(reply.usage)
140
+ else
141
+ Agent::ProviderUsage.from_message(reply)
142
+ end
122
143
  Budget::HostLedger.amount(usage, model: model_id, provider: provider.slug) if usage
123
144
  end
124
145
 
@@ -130,6 +151,10 @@ module Smith
130
151
  super(*sent, **options, &chunks)
131
152
  end
132
153
  end
154
+
155
+ def paint(prompt, **request)
156
+ RequestHolds.paint(self, prompt, request) { super }
157
+ end
133
158
  end
134
159
  end
135
160
  end
@@ -0,0 +1,39 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Smith
4
+ module Providers
5
+ # Whether a request that failed in transport may have reached the provider
6
+ # and been billed: its answer timed out once it was sent (Faraday's
7
+ # TimeoutError, a read or write timeout, or a gateway's 504), or its
8
+ # connection was lost mid-exchange (a reset, a broken pipe, an end of
9
+ # file, or TLS failing, which on a live connection is how a drop arrives).
10
+ # A connection that never opened, or refused, sent nothing.
11
+ module RequestOutcome
12
+ LOST = %w[Errno::ECONNRESET Errno::EPIPE EOFError].freeze
13
+ EXCEPTION_CAUSE = Exception.instance_method(:cause)
14
+ private_constant :LOST, :EXCEPTION_CAUSE
15
+
16
+ module_function
17
+
18
+ def uncertain?(error)
19
+ return true if error.is_a?(Faraday::TimeoutError) || error.is_a?(Faraday::SSLError) || gateway_timeout?(error)
20
+ return false unless error.is_a?(Faraday::ConnectionFailed)
21
+
22
+ LOST.include?(transport_cause(error)&.class&.name)
23
+ end
24
+
25
+ def gateway_timeout?(error)
26
+ error.is_a?(::RubyLLM::ServiceUnavailableError) && error.response.respond_to?(:status) &&
27
+ error.response.status.to_i == 504
28
+ end
29
+
30
+ def transport_cause(error)
31
+ cause = EXCEPTION_CAUSE.bind_call(error)
32
+ cause ||= error.wrapped_exception if error.respond_to?(:wrapped_exception)
33
+ cause if cause.is_a?(Exception)
34
+ rescue StandardError
35
+ nil
36
+ end
37
+ end
38
+ end
39
+ end
@@ -16,7 +16,9 @@ module Smith
16
16
  # prompt_blocked (a Gemini prompt block),
17
17
  # content_filter (OpenAI), SAFETY, RECITATION, BLOCKLIST,
18
18
  # PROHIBITED_CONTENT, SPII, IMAGE_SAFETY (Gemini),
19
- # content_filtered, guardrail_intervened (Bedrock)
19
+ # content_filtered, guardrail_intervened (Bedrock),
20
+ # moderation_blocked (OpenAI's Images API, as an image
21
+ # agent's attempt reads its refusal)
20
22
  module StopReason
21
23
  TRUNCATED = %w[
22
24
  max_tokens model_context_window_exceeded length max_output_tokens MAX_TOKENS output_limit_reached
@@ -24,7 +26,7 @@ module Smith
24
26
  ].freeze
25
27
  REFUSED = %w[
26
28
  refusal prompt_blocked content_filter SAFETY RECITATION BLOCKLIST PROHIBITED_CONTENT SPII IMAGE_SAFETY
27
- content_filtered guardrail_intervened
29
+ content_filtered guardrail_intervened moderation_blocked
28
30
  ].freeze
29
31
 
30
32
  module_function
@@ -14,6 +14,8 @@ module Smith
14
14
  # :fallback another model answers (a provider failure, or a refusal)
15
15
  # :truncation the reply was cut off and is asked for again
16
16
  # :repair the reply could not be the output and is asked for again
17
+ # :rejected an `optimize` step's evaluator (or `before_eval`)
18
+ # rejected the round, and its generator writes again
17
19
  # :retry_wait the step waits out a durable retry's backoff
18
20
  #
19
21
  # The step then ends with `finish(output)`, the output it accepted
@@ -6,7 +6,9 @@ require_relative "streaming/json_field"
6
6
 
7
7
  module Smith
8
8
  # A step declared with `execute Agent, stream: :name` sends its reply's
9
- # text, as the model writes it, to a sink the host gives it. The host
9
+ # text, as the model writes it, to a sink the host gives it; one declared
10
+ # with `optimize ..., stream: :name` sends its generator's, round after
11
+ # round. The host
10
12
  # registers a callable under that name in `Smith.config.stream_sinks`;
11
13
  # when the step starts, Smith calls it with the step's info (the stream's
12
14
  # name, the run's execution key, the transition) and streams to the sink
data/lib/smith/version.rb CHANGED
@@ -1,6 +1,6 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Smith
4
- VERSION = "0.14.0"
4
+ VERSION = "0.16.0"
5
5
  EXECUTION_SEMANTICS_VERSION = "7"
6
6
  end
@@ -7,9 +7,12 @@ module Smith
7
7
  # `cache_write_tokens` are the prompt-cache input beside it, and
8
8
  # `total_tokens` adds all three to the output. `mode` is how the call was
9
9
  # made, set by streaming and batch steps (nil for an ordinary call).
10
+ # `image_input_tokens` and `image_output_tokens` are the image parts of
11
+ # the input and the output, inside their counts.
10
12
  AgentResult = Struct.new(
11
13
  :content, :input_tokens, :output_tokens, :cost, :model_used, :provider_used,
12
14
  :cache_read_tokens, :cache_write_tokens, :thinking_tokens, :stop_reason, :provider_message_id, :mode,
15
+ :image_input_tokens, :image_output_tokens,
13
16
  keyword_init: true
14
17
  ) do
15
18
  # The detail members of an AgentResult taken from a ProviderUsage.
@@ -57,7 +60,8 @@ module Smith
57
60
  end
58
61
  end
59
62
  AgentResult::USAGE_DETAIL_MEMBERS = %i[
60
- cache_read_tokens cache_write_tokens thinking_tokens stop_reason provider_message_id
63
+ cache_read_tokens cache_write_tokens thinking_tokens stop_reason provider_message_id image_input_tokens
64
+ image_output_tokens
61
65
  ].freeze
62
66
  # rubocop:enable Style/RedundantStructKeywordInit
63
67
  end
@@ -26,7 +26,9 @@ module Smith
26
26
  USAGE_ALLOWED_ATTRIBUTES = Workflow::UsageEntry.members.map(&:to_s).freeze
27
27
  USAGE_REQUIRED_ATTRIBUTES =
28
28
  (USAGE_ALLOWED_ATTRIBUTES - Workflow::UsageEntry::OPTIONAL_MEMBERS.map(&:to_s)).freeze
29
- USAGE_COUNT_ATTRIBUTES = %w[cache_read_tokens cache_write_tokens thinking_tokens].freeze
29
+ USAGE_COUNT_ATTRIBUTES = %w[
30
+ cache_read_tokens cache_write_tokens thinking_tokens image_input_tokens image_output_tokens
31
+ ].freeze
30
32
  USAGE_MODES = %w[sync stream batch].freeze
31
33
  TOOL_REQUIRED_ATTRIBUTES = %w[tool captured].freeze
32
34
  TOOL_ALLOWED_ATTRIBUTES = (TOOL_REQUIRED_ATTRIBUTES + %w[tool_call_id]).freeze