smith-agents 0.15.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.
- checksums.yaml +4 -4
- data/CHANGELOG.md +63 -0
- data/README.md +1 -1
- data/docs/AGENTS.md +48 -0
- data/docs/BUDGETS.md +10 -0
- data/docs/CONFIGURATION.md +6 -1
- data/docs/ERRORS_AND_RETRIES.md +13 -0
- data/docs/PATTERNS.md +51 -0
- data/lib/smith/agent/image_request.rb +38 -0
- data/lib/smith/agent/lifecycle.rb +2 -0
- data/lib/smith/agent/output_recovery.rb +4 -0
- data/lib/smith/agent/paint_input.rb +42 -0
- data/lib/smith/agent/painted_answer.rb +70 -0
- data/lib/smith/agent/provider_call_timing.rb +2 -1
- data/lib/smith/agent/provider_completion.rb +1 -1
- data/lib/smith/agent/provider_failure_handling.rb +27 -5
- data/lib/smith/agent/provider_paint.rb +128 -0
- data/lib/smith/agent/provider_usage.rb +27 -2
- data/lib/smith/agent/usage_tracking.rb +3 -1
- data/lib/smith/agent.rb +3 -1
- data/lib/smith/budget/host_ledger.rb +3 -1
- data/lib/smith/budget/request_hold.rb +16 -0
- data/lib/smith/errors.rb +8 -0
- data/lib/smith/pricing/catalog_validation.rb +20 -1
- data/lib/smith/pricing/images.rb +29 -0
- data/lib/smith/pricing.rb +37 -16
- data/lib/smith/providers/request_holds.rb +29 -4
- data/lib/smith/providers/request_outcome.rb +39 -0
- data/lib/smith/providers/stop_reason.rb +4 -2
- data/lib/smith/version.rb +1 -1
- data/lib/smith/workflow/agent_result.rb +5 -1
- data/lib/smith/workflow/composite/effects.rb +3 -1
- data/lib/smith/workflow/execution.rb +1 -0
- data/lib/smith/workflow/failure_reconstructor.rb +1 -0
- data/lib/smith/workflow/failure_record.rb +7 -3
- data/lib/smith/workflow/failure_record_validator.rb +7 -7
- data/lib/smith/workflow/nested_execution.rb +14 -4
- data/lib/smith/workflow/nested_items_execution.rb +122 -0
- data/lib/smith/workflow/parallel/nested_execution.rb +4 -1
- data/lib/smith/workflow/parallel/root_execution.rb +2 -1
- data/lib/smith/workflow/parallel.rb +13 -5
- data/lib/smith/workflow/transition.rb +27 -2
- data/lib/smith/workflow/usage_entry.rb +5 -0
- data/lib/smith.rb +2 -0
- metadata +8 -1
|
@@ -17,7 +17,9 @@ module Smith
|
|
|
17
17
|
COUNT_READERS = {
|
|
18
18
|
cache_read_tokens: %i[cache_read_tokens cached_tokens],
|
|
19
19
|
cache_write_tokens: %i[cache_write_tokens cache_creation_tokens],
|
|
20
|
-
thinking_tokens: %i[thinking_tokens]
|
|
20
|
+
thinking_tokens: %i[thinking_tokens],
|
|
21
|
+
image_input_tokens: %i[image_input_tokens],
|
|
22
|
+
image_output_tokens: %i[image_output_tokens]
|
|
21
23
|
}.freeze
|
|
22
24
|
OPTIONAL_COUNTS = COUNT_READERS.keys.freeze
|
|
23
25
|
|
|
@@ -26,6 +28,8 @@ module Smith
|
|
|
26
28
|
attribute :cache_read_tokens, Types::Integer.optional.default(nil)
|
|
27
29
|
attribute :cache_write_tokens, Types::Integer.optional.default(nil)
|
|
28
30
|
attribute :thinking_tokens, Types::Integer.optional.default(nil)
|
|
31
|
+
attribute :image_input_tokens, Types::Integer.optional.default(nil)
|
|
32
|
+
attribute :image_output_tokens, Types::Integer.optional.default(nil)
|
|
29
33
|
attribute :stop_reason, Types::String.optional.default(nil)
|
|
30
34
|
attribute :provider_message_id, Types::String.optional.default(nil)
|
|
31
35
|
# How the response was made: :stream, :batch, or nil (synchronous).
|
|
@@ -41,6 +45,27 @@ module Smith
|
|
|
41
45
|
new(input_tokens:, output_tokens:, **optional_counts(message), **Providers::ResponseFacts.from_message(message))
|
|
42
46
|
end
|
|
43
47
|
|
|
48
|
+
# The usage an image answer reports, as OpenAI's Images API words it:
|
|
49
|
+
# its input and output with the image part of each
|
|
50
|
+
# (`input_tokens_details`, `output_tokens_details`), its output all
|
|
51
|
+
# image when it gives no parts; nil when it reported none. The image
|
|
52
|
+
# API reads no prompt cache.
|
|
53
|
+
def self.from_image(usage, stop_reason: nil)
|
|
54
|
+
return unless usage.is_a?(Hash)
|
|
55
|
+
|
|
56
|
+
input, output = %w[input_tokens output_tokens].map { |name| image_count(usage, name) }
|
|
57
|
+
return unless input && output
|
|
58
|
+
|
|
59
|
+
new(input_tokens: input, output_tokens: output, stop_reason:,
|
|
60
|
+
image_input_tokens: image_count(usage.fetch("input_tokens_details", nil), "image_tokens"),
|
|
61
|
+
image_output_tokens: image_count(usage.fetch("output_tokens_details", nil), "image_tokens") || output)
|
|
62
|
+
end
|
|
63
|
+
|
|
64
|
+
def self.image_count(source, name)
|
|
65
|
+
value = source[name] || source[name.to_sym] if source.is_a?(Hash)
|
|
66
|
+
value if value.is_a?(Integer) && value >= 0
|
|
67
|
+
end
|
|
68
|
+
|
|
44
69
|
def self.optional_counts(message)
|
|
45
70
|
COUNT_READERS.transform_values do |readers|
|
|
46
71
|
readers.lazy.filter_map { |reader| count_from(message, reader) }.first
|
|
@@ -67,7 +92,7 @@ module Smith
|
|
|
67
92
|
stop_reason: usages.last.stop_reason, provider_message_id: usages.last.provider_message_id,
|
|
68
93
|
mode: usages.last.mode)
|
|
69
94
|
end
|
|
70
|
-
private_class_method :optional_counts, :count_from
|
|
95
|
+
private_class_method :optional_counts, :count_from, :image_count
|
|
71
96
|
|
|
72
97
|
# This usage with the stop reason and message id of `facts`, a
|
|
73
98
|
# ResponseFacts result, in place of its own: a tool loop's summed
|
|
@@ -123,7 +123,9 @@ module Smith
|
|
|
123
123
|
cache_read_tokens: agent_result.cache_read_tokens || 0,
|
|
124
124
|
cache_write_tokens: agent_result.cache_write_tokens || 0
|
|
125
125
|
}
|
|
126
|
-
|
|
126
|
+
images = { image_input_tokens: agent_result.image_input_tokens || 0,
|
|
127
|
+
image_output_tokens: agent_result.image_output_tokens || 0 }
|
|
128
|
+
agent_result.cost = Smith::Pricing.compute_cost(**usage, **images, mode: agent_result.mode || :sync)
|
|
127
129
|
agent_result.cache_unpriced = Smith::Pricing.cache_unpriced?(**usage.except(:output_tokens))
|
|
128
130
|
end
|
|
129
131
|
end
|
data/lib/smith/agent.rb
CHANGED
|
@@ -35,7 +35,7 @@ module Smith
|
|
|
35
35
|
subclass.instance_variable_set(:@model_block, @model_block)
|
|
36
36
|
subclass.instance_variable_set(:@tool_budget_exhaustion, @tool_budget_exhaustion)
|
|
37
37
|
subclass.instance_variable_set(:@prompt_cache, @prompt_cache)
|
|
38
|
-
%i[@on_truncation @on_refusal @output_contract @output_repairs].each do |name|
|
|
38
|
+
%i[@on_truncation @on_refusal @output_contract @output_repairs @image_request].each do |name|
|
|
39
39
|
subclass.instance_variable_set(name, instance_variable_get(name))
|
|
40
40
|
end
|
|
41
41
|
subclass.instance_variable_set(:@execution_identity, nil)
|
|
@@ -154,6 +154,7 @@ require_relative "agent/reserved_input_bridge"
|
|
|
154
154
|
require_relative "agent/chat_construction"
|
|
155
155
|
require_relative "agent/output_policy"
|
|
156
156
|
require_relative "agent/prompt_cache"
|
|
157
|
+
require_relative "agent/image_request"
|
|
157
158
|
|
|
158
159
|
Smith::Agent.extend(Smith::Agent::DynamicConfiguration)
|
|
159
160
|
Smith::Agent.extend(Smith::Agent::FallbackConfiguration)
|
|
@@ -161,3 +162,4 @@ Smith::Agent.extend(Smith::Agent::ReservedInputBridge)
|
|
|
161
162
|
Smith::Agent.extend(Smith::Agent::ChatConstruction)
|
|
162
163
|
Smith::Agent.extend(Smith::Agent::OutputPolicy)
|
|
163
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
|
|
|
@@ -45,6 +45,22 @@ module Smith
|
|
|
45
45
|
Amount.new(input_tokens: input, output_tokens: output, cost: most_cost(price, input, cache_marked?(request)))
|
|
46
46
|
end
|
|
47
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
|
+
|
|
48
64
|
# The request's cost with its input as the tokens name it: read plainly,
|
|
49
65
|
# or written to a prompt cache.
|
|
50
66
|
def price_for(provider, model, output, mode)
|
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[
|
|
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.
|
|
27
|
-
#
|
|
28
|
-
#
|
|
29
|
-
#
|
|
30
|
-
#
|
|
31
|
-
#
|
|
32
|
-
#
|
|
33
|
-
#
|
|
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
|
-
|
|
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:,
|
|
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 =
|
|
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 &&
|
|
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
|
-
|
|
211
|
-
|
|
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?,
|
|
@@ -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
|
-
|
|
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 =
|
|
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
|
data/lib/smith/version.rb
CHANGED
|
@@ -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[
|
|
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
|
|
@@ -14,6 +14,7 @@ module Smith
|
|
|
14
14
|
"tool_failure_notification_failed" => ->(record) { tool_failure_notification_failure(record) },
|
|
15
15
|
"tool_capture_failed" => ->(record) { Smith::ToolCaptureFailed.from_details(record.fetch(:error_details)) },
|
|
16
16
|
"tool_outcome_uncertain" => ->(record) { Smith::ToolOutcomeUncertain.new(record[:error_message]) },
|
|
17
|
+
"request_outcome_uncertain" => ->(record) { Smith::RequestOutcomeUncertain.new(record[:error_message]) },
|
|
17
18
|
"tool_execution_not_admitted" => ->(record) { Smith::ToolExecutionNotAdmitted.new(record[:error_message]) },
|
|
18
19
|
"bounded_completion_error" => ->(record) { Smith::BoundedCompletionError.new(record[:error_message]) },
|
|
19
20
|
"persisted_failure_invalid" => ->(record) { Smith::PersistedFailureInvalid.new(record[:error_message]) },
|
|
@@ -17,6 +17,7 @@ module Smith
|
|
|
17
17
|
[Smith::ToolFailureNotificationFailed, "tool_failure_notification_failed"],
|
|
18
18
|
[Smith::ToolCaptureFailed, "tool_capture_failed"],
|
|
19
19
|
[Smith::ToolOutcomeUncertain, "tool_outcome_uncertain"],
|
|
20
|
+
[Smith::RequestOutcomeUncertain, "request_outcome_uncertain"],
|
|
20
21
|
[Smith::ToolExecutionNotAdmitted, "tool_execution_not_admitted"],
|
|
21
22
|
[Smith::BoundedCompletionError, "bounded_completion_error"],
|
|
22
23
|
[Smith::PersistedFailureInvalid, "persisted_failure_invalid"],
|
|
@@ -31,11 +32,13 @@ module Smith
|
|
|
31
32
|
[Smith::ChildRunsFailed, "child_runs_failed"],
|
|
32
33
|
[Smith::WorkflowError, "workflow_error"]
|
|
33
34
|
].freeze
|
|
35
|
+
UNCERTAINTY_WRAPPERS = [Smith::ToolOutcomeUncertain, Smith::RequestOutcomeUncertain].freeze
|
|
34
36
|
BOOLEAN_VALUES = [true, false].freeze
|
|
35
37
|
EXCEPTION_CAUSE = Exception.instance_method(:cause)
|
|
36
38
|
EXCEPTION_MESSAGE = Exception.instance_method(:message)
|
|
37
39
|
MODULE_MATCH = Module.instance_method(:===)
|
|
38
|
-
private_constant :ERROR_FAMILIES, :BOOLEAN_VALUES, :EXCEPTION_CAUSE, :EXCEPTION_MESSAGE,
|
|
40
|
+
private_constant :ERROR_FAMILIES, :UNCERTAINTY_WRAPPERS, :BOOLEAN_VALUES, :EXCEPTION_CAUSE, :EXCEPTION_MESSAGE,
|
|
41
|
+
:MODULE_MATCH
|
|
39
42
|
|
|
40
43
|
extend Dry::Initializer
|
|
41
44
|
|
|
@@ -71,7 +74,8 @@ module Smith
|
|
|
71
74
|
# Uncertainty wrappers replace the causal failure at the transition
|
|
72
75
|
# boundary; without this classification a restored host cannot
|
|
73
76
|
# distinguish a deadline, cancellation, or defect behind an
|
|
74
|
-
# uncertain tool outcome
|
|
77
|
+
# uncertain tool outcome, nor which transport error left a request's
|
|
78
|
+
# outcome uncertain.
|
|
75
79
|
def cause_attributes(error)
|
|
76
80
|
cause = uncertainty_cause(error)
|
|
77
81
|
{
|
|
@@ -82,7 +86,7 @@ module Smith
|
|
|
82
86
|
end
|
|
83
87
|
|
|
84
88
|
def uncertainty_cause(error)
|
|
85
|
-
return unless MODULE_MATCH.bind_call(
|
|
89
|
+
return unless UNCERTAINTY_WRAPPERS.any? { |wrapper| MODULE_MATCH.bind_call(wrapper, error) }
|
|
86
90
|
|
|
87
91
|
cause = EXCEPTION_CAUSE.bind_call(error)
|
|
88
92
|
cause if MODULE_MATCH.bind_call(Exception, cause)
|
|
@@ -16,6 +16,7 @@ module Smith
|
|
|
16
16
|
"Smith::ToolCaptureFailed" => "tool_capture_failed",
|
|
17
17
|
"Smith::ToolFailureNotificationFailed" => "tool_failure_notification_failed",
|
|
18
18
|
"Smith::ToolOutcomeUncertain" => "tool_outcome_uncertain",
|
|
19
|
+
"Smith::RequestOutcomeUncertain" => "request_outcome_uncertain",
|
|
19
20
|
"Smith::ToolExecutionNotAdmitted" => "tool_execution_not_admitted",
|
|
20
21
|
"Smith::BoundedCompletionError" => "bounded_completion_error",
|
|
21
22
|
"Smith::PersistedFailureInvalid" => "persisted_failure_invalid",
|
|
@@ -25,8 +26,7 @@ module Smith
|
|
|
25
26
|
"Smith::DeadlineExceeded" => "deadline_exceeded",
|
|
26
27
|
"Smith::ProviderPermanentFailure" => "provider_permanent_failure",
|
|
27
28
|
"Smith::BudgetExceeded" => "budget_exceeded", "Smith::BudgetUnavailable" => "budget_exceeded",
|
|
28
|
-
"Smith::GuardrailFailed" => "guardrail_failed",
|
|
29
|
-
"Smith::WaitTimedOut" => "wait_timed_out",
|
|
29
|
+
"Smith::GuardrailFailed" => "guardrail_failed", "Smith::WaitTimedOut" => "wait_timed_out",
|
|
30
30
|
"Smith::ChildRunsFailed" => "child_runs_failed",
|
|
31
31
|
"Smith::WorkflowError" => "workflow_error", "Smith::PersistedStateTooLarge" => "workflow_error",
|
|
32
32
|
"Smith::UnresolvedTransitionError" => "workflow_error",
|
|
@@ -41,13 +41,13 @@ module Smith
|
|
|
41
41
|
}.freeze
|
|
42
42
|
KNOWN_FAMILIES = %w[
|
|
43
43
|
deterministic_step_failure tool_guardrail_failed tool_failure_notification_failed tool_capture_failed
|
|
44
|
-
tool_outcome_uncertain tool_execution_not_admitted bounded_completion_error
|
|
45
|
-
deadline_exceeded provider_permanent_failure budget_exceeded guardrail_failed
|
|
46
|
-
wait_timed_out output_failure child_runs_failed other
|
|
44
|
+
tool_outcome_uncertain request_outcome_uncertain tool_execution_not_admitted bounded_completion_error
|
|
45
|
+
persisted_failure_invalid deadline_exceeded provider_permanent_failure budget_exceeded guardrail_failed
|
|
46
|
+
agent_error workflow_error wait_timed_out output_failure child_runs_failed other
|
|
47
47
|
].freeze
|
|
48
48
|
RETRY_FORBIDDEN_FAMILIES = %w[
|
|
49
|
-
tool_capture_failed tool_failure_notification_failed tool_outcome_uncertain
|
|
50
|
-
bounded_completion_error persisted_failure_invalid
|
|
49
|
+
tool_capture_failed tool_failure_notification_failed tool_outcome_uncertain request_outcome_uncertain
|
|
50
|
+
tool_execution_not_admitted bounded_completion_error persisted_failure_invalid
|
|
51
51
|
].freeze
|
|
52
52
|
DETAIL_VALIDATORS = {
|
|
53
53
|
"Smith::ToolCaptureFailed" => ->(details) { Smith::ToolCaptureFailed.from_details(details) },
|
|
@@ -9,6 +9,8 @@ module Smith
|
|
|
9
9
|
|
|
10
10
|
def execute_nested_workflow(transition)
|
|
11
11
|
check_deadline!
|
|
12
|
+
return execute_nested_items(transition) if transition.nested_items
|
|
13
|
+
|
|
12
14
|
child = build_child_workflow(transition.workflow_class)
|
|
13
15
|
child_result = run_child_workflow(child)
|
|
14
16
|
reject_waiting_child!(child, child_result)
|
|
@@ -47,19 +49,23 @@ module Smith
|
|
|
47
49
|
|
|
48
50
|
# A nested workflow inherits the run's untrusted keys, and charges the
|
|
49
51
|
# run's budget ledger unless it names its own.
|
|
50
|
-
|
|
52
|
+
# An item's child takes its item under its key (`item`: [key, value]),
|
|
53
|
+
# and spends within its own budget when it is given one.
|
|
54
|
+
def new_nested_workflow(child_class, item: nil, ledger: @ledger)
|
|
55
|
+
context = @context.dup
|
|
56
|
+
context[item.first] = item.last if item
|
|
51
57
|
StepIO.with_inherited_untrusted_keys(untrusted_context_keys) do
|
|
52
58
|
Budget::HostLedger.inheriting(method(:run_budget_ledger)) do
|
|
53
59
|
ResponseMemo.inheriting([*@memo_attempts, @step_attempt.to_i]) do
|
|
54
|
-
child_class.new(context
|
|
60
|
+
child_class.new(context:, ledger:, created_at: @created_at)
|
|
55
61
|
end
|
|
56
62
|
end
|
|
57
63
|
end
|
|
58
64
|
end
|
|
59
65
|
|
|
60
|
-
def build_child_workflow(child_class)
|
|
66
|
+
def build_child_workflow(child_class, item: nil, ledger: @ledger)
|
|
61
67
|
@split_step_active_execution_authorization&.verify_workflow!(child_class)
|
|
62
|
-
child = new_nested_workflow(child_class)
|
|
68
|
+
child = new_nested_workflow(child_class, item:, ledger:)
|
|
63
69
|
unless child.instance_of?(child_class)
|
|
64
70
|
raise WorkflowError, "nested workflow constructor returned #{child.class} instead of #{child_class}"
|
|
65
71
|
end
|
|
@@ -91,6 +97,10 @@ module Smith
|
|
|
91
97
|
# non-retryable WorkflowError, as before, its cause the child's own
|
|
92
98
|
# error, so a host can still read what the child failed on.
|
|
93
99
|
failed_step = child_result.steps.find { |s| s.key?(:error) }
|
|
100
|
+
# A failure nothing may ask again for (an uncertain request, a tool's
|
|
101
|
+
# uncertain outcome) stays itself, however the child routed it.
|
|
102
|
+
raise failed_step[:error] if failed_step && Smith::Errors.retry_forbidden?(failed_step[:error])
|
|
103
|
+
|
|
94
104
|
if failed_step
|
|
95
105
|
raise WorkflowError,
|
|
96
106
|
"nested workflow failed: #{DiagnosticText.capture(failed_step[:error]&.message.to_s, max_bytes: 1024)}",
|