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
@@ -24,23 +24,33 @@ module Smith
24
24
 
25
25
  private
26
26
 
27
- # Counts the cached blocks already in the chat (its instructions) and
28
- # those the prepared input adds, before any is added.
29
- def check_cache_breakpoints!(chat, messages, provider)
27
+ # Counts the cached blocks already in the chat (its instructions), those
28
+ # the prepared input adds, and an automatic prompt cache, the call's own
29
+ # (`shape`, ProviderRequest) or a top-level marker the chat's params
30
+ # carry, once, before any is added.
31
+ def check_cache_breakpoints!(chat, messages, provider, shape)
30
32
  return unless anthropic?(provider)
31
33
 
32
- cached = chat_cache_controls(chat) +
34
+ automatic = automatic_breakpoint?(chat, shape, provider)
35
+ cached = chat_cache_controls(chat) + (automatic ? 1 : 0) +
33
36
  messages.sum { |message| message_parts(message).count { |part| Content.cached?(part) } }
34
37
  return if cached <= MAX_CACHE_BREAKPOINTS
35
38
 
36
- raise ContentUnavailable, "#{cached} blocks ask to be cached; Anthropic takes at most " \
37
- "#{MAX_CACHE_BREAKPOINTS} cache breakpoints in one request"
39
+ counted = automatic ? ", an automatic prompt cache counting one" : ""
40
+ raise ContentUnavailable, "#{cached} cache breakpoints are asked for#{counted}; Anthropic takes at most " \
41
+ "#{MAX_CACHE_BREAKPOINTS} in one request"
38
42
  end
39
43
 
40
- def check_chain_cache_breakpoints!(chain, prepared_input)
44
+ def automatic_breakpoint?(chat, shape, provider) = automatic_cache?(shape, provider) || chat_cache_marked?(chat)
45
+
46
+ def check_chain_cache_breakpoints!(chain, prepared_input, shape)
41
47
  return unless chain.any? { |reference| anthropic?(reference.provider) }
42
48
 
43
- check_cache_breakpoints!(nil, Array(prepared_input), :anthropic)
49
+ check_cache_breakpoints!(nil, Array(prepared_input), :anthropic, shape)
50
+ end
51
+
52
+ def chat_cache_marked?(chat)
53
+ chat.respond_to?(:params) && chat.params.is_a?(Hash) && cached_block?(chat.params)
44
54
  end
45
55
 
46
56
  # A model the chain reaches whose provider takes no such content.
@@ -0,0 +1,38 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Smith
4
+ class Agent
5
+ # An agent that answers with an image rather than words:
6
+ #
7
+ # image size: "1024x1024", quality: "low", background: "opaque", output_format: "png"
8
+ #
9
+ # Its attempt paints instead of chatting (ProviderPaint): its instructions
10
+ # and its input's text are the prompt, its input's images (Content.image)
11
+ # are drawn from in order, and its answer is the image, kept in the run's
12
+ # artifacts, as `Smith::Content.image(ref, media_type:)`. The options are
13
+ # the provider's own words for the request, passed as they are; the size
14
+ # and quality also name what the image writes in the pricing catalog
15
+ # (`image_output_tokens`), which its hold is priced from. An image agent
16
+ # takes no tools, output schema or thinking, and its step is neither
17
+ # streamed nor batched: none of them has a meaning for a picture.
18
+ module ImageRequest
19
+ MEDIA_TYPES = { "png" => "image/png", "webp" => "image/webp", "jpeg" => "image/jpeg" }.freeze
20
+
21
+ def image(size:, quality:, background: nil, output_format: "png")
22
+ options = { size:, quality:, background: }
23
+ named = options.compact.all? { |_, value| value.is_a?(String) && !value.strip.empty? }
24
+ raise ArgumentError, "image size:, quality: and background: are the provider's words, as Strings" unless
25
+ named && size && quality
26
+ unless MEDIA_TYPES.key?(output_format)
27
+ raise ArgumentError, "image output_format: is one of #{MEDIA_TYPES.keys.join(", ")}"
28
+ end
29
+
30
+ @image_request = { **options, output_format: }.compact.freeze
31
+ end
32
+
33
+ def image_request = @image_request
34
+
35
+ def image_media_type = image_request && MEDIA_TYPES.fetch(image_request.fetch(:output_format))
36
+ end
37
+ end
38
+ end
@@ -36,11 +36,11 @@ module Smith
36
36
 
37
37
  # The messages, with their content parts (ContentParts) as `provider`
38
38
  # takes them.
39
- def add_prepared_input(chat, prepared_input, provider = nil)
39
+ def add_prepared_input(chat, prepared_input, provider, shape)
40
40
  return unless prepared_input
41
41
 
42
42
  prepared_input = provider_safe_prepared_input(prepared_input)
43
- check_cache_breakpoints!(chat, prepared_input, provider)
43
+ check_cache_breakpoints!(chat, prepared_input, provider, shape)
44
44
  with_built_contents do
45
45
  prepared_input = prepared_input.map do |message|
46
46
  Message.parts?(message) ? provider_parts_message(message, provider) : message
@@ -2,12 +2,14 @@
2
2
 
3
3
  require_relative "output_integrity"
4
4
  require_relative "provider_completion"
5
+ require_relative "provider_paint"
5
6
  require_relative "usage_tracking"
6
7
 
7
8
  module Smith
8
9
  class Agent
9
10
  module Lifecycle
10
11
  include ProviderCompletion
12
+ include ProviderPaint
11
13
  include UsageTracking
12
14
  include OutputIntegrity
13
15
 
@@ -29,7 +29,7 @@ module Smith
29
29
  # What one invocation has tried so far.
30
30
  Plan = Struct.new(:agent_class, :input, :output_schema, :json_schema, :repairs_left, :retried, :fell_back,
31
31
  :output_limit, :calls) do
32
- def shape = ProviderRequest::Shape.new(output_schema:, output_limit:)
32
+ def shape = ProviderRequest::Shape.new(output_schema:, output_limit:, prompt_cache: agent_class.prompt_cache)
33
33
  end
34
34
  private_constant :Plan
35
35
 
@@ -109,19 +109,28 @@ module Smith
109
109
  fail_follow_up(plan, attempt, pending)
110
110
  end
111
111
 
112
+ # A follow-up whose outcome is uncertain says so, never the failure it
113
+ # was making up for, so nothing asks for it again.
112
114
  def fail_follow_up(plan, attempt, pending)
113
115
  account_failed_attempt(attempt.error, attempt.model_reference, plan.agent_class, attempt_id: attempt.attempt_id)
116
+ raise attempt.error if Smith::Errors.retry_forbidden?(attempt.error)
117
+
114
118
  raise pending, cause: attempt.error
115
119
  end
116
120
 
117
121
  # Whether the responses so far have reached what the call's step
118
- # reserved in any budget dimension.
122
+ # reserved in any token or cost dimension. A reservation names every
123
+ # budget the workflow declares, wall_clock among them at 0; a call
124
+ # spends only tokens and cost, and the deadline is checked before the
125
+ # follow-up is made.
119
126
  def budget_spent?(result)
120
127
  reservation = Thread.current[:smith_call_reservation]
121
128
  return false unless reservation
122
129
 
123
130
  spent = extract_actuals([*Array(Thread.current[:smith_failed_agent_results]), result])
124
131
  reservation.amounts.any? do |dimension, amount|
132
+ next false unless Workflow::BudgetIntegration::BUDGET_DIMENSIONS.include?(dimension)
133
+
125
134
  used = Workflow::BudgetIntegration::COST_DIMENSIONS.include?(dimension) ? spent[:cost] : spent[:tokens]
126
135
  used >= amount
127
136
  end
@@ -0,0 +1,42 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "stringio"
4
+
5
+ module Smith
6
+ class Agent
7
+ # What an image agent's chat asks the provider to paint: its system and
8
+ # user text joined, in order, is the prompt, and the images its content
9
+ # parts attach are drawn from, in order. A refinement round's earlier
10
+ # answer (an assistant turn) is not sent; the feedback after it is.
11
+ module PaintInput
12
+ # Bytes Faraday sends as a named file part, so the provider sees the
13
+ # image's name and kind.
14
+ class NamedImage < StringIO
15
+ attr_reader :path
16
+
17
+ def initialize(bytes, name)
18
+ super(bytes)
19
+ @path = name
20
+ end
21
+ end
22
+
23
+ module_function
24
+
25
+ # [prompt, images]
26
+ def of(messages)
27
+ texts = []
28
+ images = []
29
+ messages.each { |message| add(message, texts, images) unless message.role.to_s == "assistant" }
30
+ [texts.reject { _1.strip.empty? }.join("\n\n"), images]
31
+ end
32
+
33
+ def add(message, texts, images)
34
+ content = message.content
35
+ return texts << content.to_s unless content.is_a?(::RubyLLM::Content)
36
+
37
+ texts << content.text.to_s
38
+ content.attachments.each { |attachment| images << NamedImage.new(attachment.content, attachment.filename) }
39
+ end
40
+ end
41
+ end
42
+ end
@@ -0,0 +1,70 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Smith
4
+ class Agent
5
+ # What a paint answered, as an attempt's completion: the image kept in the
6
+ # run's artifacts as a content part with the usage it reported, or, for a
7
+ # moderation block, a refused response that cost nothing. An image drawn
8
+ # and billed that cannot be kept (none in the answer, or a store that
9
+ # failed) raises with its usage, so the usage is recorded before the
10
+ # error goes on.
11
+ module PaintedAnswer
12
+ Painted = Data.define(:content)
13
+ MODERATION_BLOCKED = "moderation_blocked"
14
+ private_constant :Painted
15
+
16
+ # An image drawn and billed that could not be kept: its usage, and why.
17
+ class Unkept < StandardError
18
+ attr_reader :usage, :reason
19
+
20
+ def initialize(usage, reason)
21
+ @usage = usage
22
+ @reason = reason
23
+ super(reason.message)
24
+ end
25
+ end
26
+ private_constant :Unkept
27
+
28
+ private
29
+
30
+ # An answer with no image is an output failure, billed and never asked
31
+ # for again; one the store cannot keep goes on as the store's error.
32
+ def painted_completion(agent_class, image)
33
+ usage = ProviderUsage.from_image(image.usage)
34
+ media_type = agent_class.image_media_type
35
+ ref = kept(agent_class, image, usage, media_type)
36
+ Completion.new(response: Painted.new(Content.image(ref, media_type:)), provider_usages: [usage].compact,
37
+ usage_complete: !usage.nil?)
38
+ end
39
+
40
+ def kept(agent_class, image, usage, media_type)
41
+ bytes = image.data&.unpack1("m")
42
+ if bytes.nil? || bytes.empty?
43
+ raise Unkept.new(usage, OutputInvalid.new(agent_name: agent_class.register_as, model_used: image.model_id,
44
+ problems: ["the answer held no image"]))
45
+ end
46
+
47
+ Smith.artifacts.store(bytes, content_type: media_type)
48
+ rescue Unkept
49
+ raise
50
+ rescue StandardError => e
51
+ raise Unkept.new(usage, e)
52
+ end
53
+
54
+ # Nothing was drawn and nothing was billed.
55
+ def refused_completion
56
+ usage = ProviderUsage.new(input_tokens: 0, output_tokens: 0, stop_reason: MODERATION_BLOCKED)
57
+ Completion.new(response: Painted.new(nil), provider_usages: [usage], usage_complete: true,
58
+ response_facts: { stop_reason: MODERATION_BLOCKED })
59
+ end
60
+
61
+ def moderation_blocked?(error)
62
+ body = error.response.body if error.response.respond_to?(:body)
63
+ body = JSON.parse(body) if body.is_a?(String)
64
+ body.is_a?(Hash) && body.dig("error", "code") == MODERATION_BLOCKED
65
+ rescue JSON::ParserError
66
+ false
67
+ end
68
+ end
69
+ end
70
+ end
@@ -0,0 +1,31 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Smith
4
+ class Agent
5
+ # Which prompt cache an agent's requests ask for beyond the parts a host
6
+ # marks (`cache: true`):
7
+ #
8
+ # prompt_cache :automatic # Anthropic caches each request's longest prefix
9
+ # prompt_cache :none # the default
10
+ #
11
+ # `:automatic` puts a top-level cache_control on each Anthropic request:
12
+ # Anthropic places the breakpoint on the request's last block and moves
13
+ # it forward as a tool loop grows, so each request reads the one before
14
+ # it from the cache. It counts as one of a request's four breakpoints;
15
+ # any other provider is asked nothing (ProviderRequest).
16
+ module PromptCache
17
+ UNSET = Object.new.freeze
18
+ MODES = %i[none automatic].freeze
19
+ private_constant :UNSET, :MODES
20
+
21
+ def prompt_cache(mode = UNSET)
22
+ return @prompt_cache || :none if mode.equal?(UNSET)
23
+
24
+ chosen = mode.respond_to?(:to_sym) ? mode.to_sym : mode
25
+ raise ArgumentError, "prompt_cache must be :none or :automatic" unless MODES.include?(chosen)
26
+
27
+ @prompt_cache = chosen
28
+ end
29
+ end
30
+ end
31
+ end
@@ -74,7 +74,8 @@ module Smith
74
74
  {
75
75
  input_tokens: usage.input_tokens, output_tokens: usage.output_tokens,
76
76
  cache_read_tokens: usage.cache_read_tokens, cache_write_tokens: usage.cache_write_tokens,
77
- thinking_tokens: usage.thinking_tokens, stop_reason: usage.stop_reason,
77
+ thinking_tokens: usage.thinking_tokens, image_input_tokens: usage.image_input_tokens,
78
+ image_output_tokens: usage.image_output_tokens, stop_reason: usage.stop_reason,
78
79
  provider_message_id: usage.provider_message_id, mode: usage.mode
79
80
  }
80
81
  end
@@ -31,7 +31,7 @@ module Smith
31
31
  # before the first attempt. A candidate that fails over to the next
32
32
  # joins `set_aside` (AttemptCaptures).
33
33
  def complete_with_provider(agent_class, prepared_input, shape:, set_aside: [])
34
- chain = build_model_chain(agent_class).tap { check_chain_cache_breakpoints!(_1, prepared_input) }
34
+ chain = build_model_chain(agent_class).tap { check_chain_cache_breakpoints!(_1, prepared_input, shape) }
35
35
  ContentBytes.with(prepared_input) { attempt_candidates(agent_class, prepared_input, chain, shape, set_aside) }
36
36
  end
37
37
 
@@ -66,7 +66,7 @@ module Smith
66
66
  fallback_available: candidates.fallback_available?, attempt_id: attempt.attempt_id)
67
67
  set_aside.concat(attempt.captures)
68
68
  rescue StandardError => e
69
- raise if interrupted.nil? || Interruptions.find(e)
69
+ raise if interrupted.nil? || Interruptions.find(e) || Smith::Errors.retry_forbidden?(e)
70
70
 
71
71
  raise terminal_provider_error(interrupted.error, interrupted.model_reference), cause: interrupted.error
72
72
  end
@@ -150,7 +150,8 @@ module Smith
150
150
 
151
151
  def prepared_attempt_chat(agent_class, prepared_input, model_reference, shape)
152
152
  chat = attempt_chat(agent_class, model_reference)
153
- add_prepared_input(chat, prepared_input, observed_model_reference(chat, fallback: model_reference).provider)
153
+ add_prepared_input(chat, prepared_input, observed_model_reference(chat, fallback: model_reference).provider,
154
+ shape)
154
155
  continue_paused_loop(chat)
155
156
  shaped_chat(chat, model_reference, shape)
156
157
  end
@@ -21,20 +21,34 @@ module Smith
21
21
 
22
22
  private
23
23
 
24
+ # A request whose outcome is uncertain is never sent again, to this
25
+ # model or another.
24
26
  def handle_provider_failure!(error, model_reference, agent_class, fallback_available:, attempt_id: nil)
25
27
  account_failed_attempt(error, model_reference, agent_class, attempt_id:)
28
+ raise error if error.is_a?(Smith::RequestOutcomeUncertain)
29
+
26
30
  if uncertain_tool_calls?
27
31
  raise Smith::ToolOutcomeUncertain.new(
28
32
  "provider failed after tool execution began; retry or fallback could replay an uncertain outcome"
29
33
  ), cause: error
30
34
  end
31
- return if fallback_eligible?(error) && fallback_available
35
+ return if goes_again?(error, agent_class) && fallback_available
36
+
37
+ raise terminal_provider_error(error, model_reference, agent_class), cause: error
38
+ end
39
+
40
+ # An image's request goes again, to another model or the step's retry,
41
+ # only after a throttle or a refusal of the account, the model or the
42
+ # content: a server's error may have done and billed the work.
43
+ def goes_again?(error, agent_class)
44
+ return fallback_eligible?(error) unless agent_class.image_request
32
45
 
33
- raise terminal_provider_error(error, model_reference), cause: error
46
+ throttled?(error) || provider_account_failure?(error) ||
47
+ model_permission_failure?(error) || model_unavailable?(error) || unsupported_content?(error)
34
48
  end
35
49
 
36
50
  def provider_failure?(error)
37
- error.is_a?(RubyLLM::Error) ||
51
+ error.is_a?(RubyLLM::Error) || error.is_a?(Smith::RequestOutcomeUncertain) ||
38
52
  (defined?(RubyLLM::ModelNotFoundError) && error.is_a?(RubyLLM::ModelNotFoundError)) ||
39
53
  error.is_a?(Faraday::TimeoutError) ||
40
54
  error.is_a?(Faraday::ConnectionFailed)
@@ -63,6 +77,14 @@ module Smith
63
77
  TRANSIENT_ERRORS.any? { |error_class| error.is_a?(error_class) }
64
78
  end
65
79
 
80
+ def throttled?(error) = error.is_a?(RubyLLM::RateLimitError)
81
+
82
+ # A provider that struggled leaves the step its retries, but for an
83
+ # image's request only a throttle does (`goes_again?`).
84
+ def step_may_retry?(error, agent_class)
85
+ (transient_failure?(error) || transport_failure?(error)) && (!agent_class&.image_request || throttled?(error))
86
+ end
87
+
66
88
  def transport_failure?(error)
67
89
  error.is_a?(Faraday::TimeoutError) || error.is_a?(Faraday::ConnectionFailed)
68
90
  end
@@ -81,8 +103,8 @@ module Smith
81
103
  false
82
104
  end
83
105
 
84
- def terminal_provider_error(error, model_reference)
85
- return Smith::AgentError.new(error.message) if transient_failure?(error) || transport_failure?(error)
106
+ def terminal_provider_error(error, model_reference, agent_class = nil)
107
+ return Smith::AgentError.new(error.message) if step_may_retry?(error, agent_class)
86
108
  if unsupported_content?(error)
87
109
  return Smith::ContentUnavailable.new("#{model_reference} takes none of this content: #{error.message}")
88
110
  end
@@ -0,0 +1,128 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "paint_input"
4
+ require_relative "painted_answer"
5
+
6
+ module Smith
7
+ class Agent
8
+ # An image agent's attempt (ImageRequest): its chat is built as any
9
+ # attempt's is (instructions, inputs, content parts), then painted from
10
+ # instead of completed (PaintInput). The request's options go as its
11
+ # params, the size among them, since RubyLLM's edit payload sends its
12
+ # params and not its size.
13
+ #
14
+ # Each request is sent once: the chat's config is copied with no HTTP
15
+ # retries, so a provider that billed a request is never asked for it
16
+ # again behind Smith's back, and only a refusal or a throttle goes again
17
+ # (ProviderFailureHandling). A moderation block is a refused response,
18
+ # which costs nothing and goes to the agent's on_refusal (OutputRefused
19
+ # by default). A request sent whose answer never came (a read timeout, a
20
+ # connection lost; Providers::RequestOutcome) raises
21
+ # RequestOutcomeUncertain, which no retry or fallback takes up. The
22
+ # image is kept in the run's artifacts and answered as a content part.
23
+ # A paint keeps no response memo (an image is too large to keep twice),
24
+ # so a step a crash replays paints again: a host that pays for images
25
+ # runs in strict idempotency, where such a step fails instead.
26
+ module ProviderPaint
27
+ include PaintedAnswer
28
+
29
+ private
30
+
31
+ # Every attempt an image agent makes (a candidate, a refusal's fallback,
32
+ # a retry) paints; any other agent's completes (ProviderCompletion).
33
+ def attempt_model(agent_class, prepared_input, model_reference, shape:, attempt_index:)
34
+ return super unless agent_class.image_request
35
+
36
+ paint_model(agent_class, prepared_input, model_reference, attempt_index:)
37
+ end
38
+
39
+ def check_image_agent!(agent_class)
40
+ refused = image_refusals(agent_class).select { |_, given| given }.keys
41
+ return if refused.empty?
42
+
43
+ raise WorkflowError, "#{agent_class} answers with an image, which takes no #{refused.join(", ")}"
44
+ end
45
+
46
+ def image_refusals(agent_class)
47
+ {
48
+ "tools" => !Array(agent_class.tools).empty?,
49
+ "an output schema" => !(agent_class.output_schema || agent_class.schema || agent_class.output_contract).nil?,
50
+ "thinking" => !agent_class.thinking.nil?,
51
+ "a streamed step" => !@step_stream.nil?,
52
+ "a batch" => @batch_capturing == true
53
+ }
54
+ end
55
+
56
+ # Every attempt of an image agent, a refusal's fallback included.
57
+ def paint_model(agent_class, prepared_input, model_reference, attempt_index:)
58
+ check_image_agent!(agent_class)
59
+ painting_attempt(agent_class, prepared_input, model_reference,
60
+ { attempt_id: SecureRandom.uuid, attempt_index:, agent_name: agent_class.register_as })
61
+ end
62
+
63
+ def painting_attempt(agent_class, prepared_input, model_reference, facts)
64
+ chat = painting_chat(agent_class, prepared_input, model_reference)
65
+ observed = observed_model_reference(chat, fallback: model_reference)
66
+ timer = ProviderCallTiming::Timer.start
67
+ completion = painted(agent_class, chat, observed, facts[:attempt_id])
68
+ completed_provider_attempt(completion, observed, timer.stop, facts)
69
+ rescue StandardError => e
70
+ failed_paint(agent_class, e, observed || model_reference, timer&.stop, facts)
71
+ end
72
+
73
+ # A paint's failure traced as any attempt's: one whose outcome is
74
+ # uncertain is raised as RequestOutcomeUncertain, its cause the
75
+ # transport's error; an image that was drawn and billed but could not be
76
+ # kept has its usage recorded before its error goes on.
77
+ def failed_paint(agent_class, error, model_reference, timer, facts)
78
+ usages = error.is_a?(Unkept) ? [error.usage].compact : []
79
+ record_billed_usages(agent_class, usages, :partial_attempt, model_reference, attempt_id: facts[:attempt_id])
80
+ error = error.reason if error.is_a?(Unkept)
81
+ error = outcome_uncertain(error) if Providers::RequestOutcome.uncertain?(error)
82
+ attempt = failed_provider_attempt(error, model_reference, timer, facts, usages)
83
+ raise error unless provider_failure?(error) || unsupported_content?(error)
84
+
85
+ attempt
86
+ end
87
+
88
+ def painting_chat(agent_class, prepared_input, model_reference)
89
+ chat = agent_class.chat(**model_reference.chat_options, **bridge_workflow_inputs(agent_class))
90
+ chat = sent_once(chat, agent_class) if chat.respond_to?(:with_context) && chat.respond_to?(:with_model)
91
+ provider = observed_model_reference(chat, fallback: model_reference).provider
92
+ add_prepared_input(chat, prepared_input, provider,
93
+ ProviderRequest::Shape.new(output_schema: nil, output_limit: nil, prompt_cache: :none))
94
+ chat
95
+ end
96
+
97
+ def painted(agent_class, chat, model_reference, attempt_id)
98
+ prompt, images = PaintInput.of(chat.messages)
99
+ request = agent_class.image_request
100
+ provider = chat_provider(chat)
101
+ image = held_paint(provider, attempt_id) do
102
+ provider.paint(prompt, model: model_reference.model_id, size: request.fetch(:size),
103
+ with: images.empty? ? nil : images, params: request)
104
+ end
105
+ painted_completion(agent_class, image)
106
+ rescue ::RubyLLM::BadRequestError => e
107
+ raise unless moderation_blocked?(e)
108
+
109
+ refused_completion
110
+ end
111
+
112
+ def held_paint(provider, attempt_id, &paint)
113
+ ledger = run_budget_ledger
114
+ return paint.call unless ledger
115
+
116
+ Providers::RequestHolds.within(provider, ledger, attempt_id, &paint)
117
+ end
118
+
119
+ # Raised inside the transport error's rescue, so it is the cause.
120
+ def outcome_uncertain(error)
121
+ raise RequestOutcomeUncertain,
122
+ "the request was sent and no answer came (#{error.class}); it may have been billed"
123
+ rescue RequestOutcomeUncertain => e
124
+ e
125
+ end
126
+ end
127
+ end
128
+ end
@@ -3,19 +3,44 @@
3
3
  module Smith
4
4
  class Agent
5
5
  # What one provider call asks for beyond its messages: the output schema
6
- # as the provider takes it, and a larger output limit when a cut-off
7
- # response is retried.
6
+ # as the provider takes it, the agent's output limit under the name an
7
+ # OpenAI model that reasons takes, a larger one when a cut-off response
8
+ # is retried, and Anthropic's automatic prompt cache when the agent asks
9
+ # for it (Agent.prompt_cache) and the call goes over the wire: a batch
10
+ # request is one turn read once, which a cache write only makes dearer.
8
11
  module ProviderRequest
9
- Shape = Data.define(:output_schema, :output_limit)
12
+ Shape = Data.define(:output_schema, :output_limit, :prompt_cache)
10
13
 
11
14
  private
12
15
 
13
16
  def shaped_chat(chat, model_reference, shape)
14
- provider = observed_model_reference(chat, fallback: model_reference).provider
17
+ observed = observed_model_reference(chat, fallback: model_reference)
18
+ provider = observed.provider
19
+ chat = named_output_limit(chat, observed)
15
20
  chat = with_output_limit(chat, provider, shape.output_limit) if shape.output_limit
21
+ chat = with_automatic_cache(chat) if automatic_cache?(shape, provider)
16
22
  shape.output_schema ? chat.with_schema(provider_output_schema(shape.output_schema, provider)) : chat
17
23
  end
18
24
 
25
+ # Whether the call carries Anthropic's automatic prompt cache, as the
26
+ # breakpoints are counted (ContentParts) and the request is shaped.
27
+ def automatic_cache?(shape, provider)
28
+ shape.prompt_cache == :automatic && anthropic?(provider) && !@batch_capturing
29
+ end
30
+
31
+ def with_automatic_cache(chat)
32
+ return chat unless chat.respond_to?(:with_params)
33
+
34
+ params = (chat.params if chat.respond_to?(:params)) || {}
35
+ chat.with_params(**::RubyLLM::Utils.deep_merge(params, { cache_control: { type: "ephemeral" } }))
36
+ end
37
+
38
+ def named_output_limit(chat, observed)
39
+ return chat unless chat.respond_to?(:with_params) && chat.respond_to?(:params) && chat.params.is_a?(Hash)
40
+
41
+ chat.with_params(**Providers::OutputLimit.named(observed.provider, chat.params, observed))
42
+ end
43
+
19
44
  def with_output_limit(chat, provider, limit)
20
45
  return chat unless chat.respond_to?(:with_params)
21
46
 
@@ -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
- agent_result.cost = Smith::Pricing.compute_cost(**usage, mode: agent_result.mode || :sync)
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