smith-agents 0.13.1 → 0.15.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 (40) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +136 -0
  3. data/README.md +8 -5
  4. data/docs/AGENTS.md +42 -3
  5. data/docs/BUDGETS.md +4 -1
  6. data/docs/CONFIGURATION.md +3 -2
  7. data/docs/PATTERNS.md +51 -8
  8. data/docs/PERSISTENCE.md +21 -7
  9. data/docs/TOOLS_AND_GUARDRAILS.md +7 -0
  10. data/lib/smith/agent/content_parts.rb +18 -8
  11. data/lib/smith/agent/invocation_preparation.rb +2 -2
  12. data/lib/smith/agent/output_integrity.rb +1 -1
  13. data/lib/smith/agent/output_recovery.rb +6 -1
  14. data/lib/smith/agent/prompt_cache.rb +31 -0
  15. data/lib/smith/agent/provider_completion.rb +3 -2
  16. data/lib/smith/agent/provider_request.rb +29 -4
  17. data/lib/smith/agent.rb +3 -0
  18. data/lib/smith/budget/request_hold.rb +33 -3
  19. data/lib/smith/providers/output_limit.rb +22 -1
  20. data/lib/smith/streaming/session.rb +2 -0
  21. data/lib/smith/streaming.rb +3 -1
  22. data/lib/smith/version.rb +1 -1
  23. data/lib/smith/workflow/batch_charges.rb +7 -3
  24. data/lib/smith/workflow/batch_execution.rb +23 -13
  25. data/lib/smith/workflow/batch_holds.rb +5 -4
  26. data/lib/smith/workflow/batch_wait.rb +39 -12
  27. data/lib/smith/workflow/evaluator_optimizer.rb +115 -29
  28. data/lib/smith/workflow/execution.rb +1 -1
  29. data/lib/smith/workflow/graph/batch_diagnostic.rb +1 -0
  30. data/lib/smith/workflow/graph/optimization_contract.rb +1 -0
  31. data/lib/smith/workflow/graph/stream_diagnostic.rb +9 -4
  32. data/lib/smith/workflow/graph/transition_optimization_configuration.rb +1 -0
  33. data/lib/smith/workflow/guarded_step_execution.rb +1 -1
  34. data/lib/smith/workflow/nested_execution.rb +4 -2
  35. data/lib/smith/workflow/optimization_state.rb +7 -2
  36. data/lib/smith/workflow/optimizer_batch.rb +161 -0
  37. data/lib/smith/workflow/step_io.rb +10 -4
  38. data/lib/smith/workflow/step_stream.rb +9 -0
  39. data/lib/smith/workflow/transition.rb +36 -17
  40. metadata +3 -1
@@ -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
 
data/lib/smith/agent.rb CHANGED
@@ -34,6 +34,7 @@ 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
+ subclass.instance_variable_set(:@prompt_cache, @prompt_cache)
37
38
  %i[@on_truncation @on_refusal @output_contract @output_repairs].each do |name|
38
39
  subclass.instance_variable_set(name, instance_variable_get(name))
39
40
  end
@@ -152,9 +153,11 @@ 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"
155
157
 
156
158
  Smith::Agent.extend(Smith::Agent::DynamicConfiguration)
157
159
  Smith::Agent.extend(Smith::Agent::FallbackConfiguration)
158
160
  Smith::Agent.extend(Smith::Agent::ReservedInputBridge)
159
161
  Smith::Agent.extend(Smith::Agent::ChatConstruction)
160
162
  Smith::Agent.extend(Smith::Agent::OutputPolicy)
163
+ Smith::Agent.extend(Smith::Agent::PromptCache)
@@ -41,11 +41,41 @@ 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 request's cost with its input as the tokens name it: read plainly,
49
+ # or written to a prompt cache.
50
+ def price_for(provider, model, output, mode)
51
+ lambda do |**tokens|
52
+ Pricing.compute_cost(model: model.id, provider: provider.to_s, output_tokens: output, mode:, **tokens)
53
+ end
54
+ end
55
+
56
+ # A request that marks a block for a prompt cache may have all its input
57
+ # written to it, which can cost more than input read plainly, so it is
58
+ # held at the dearer of the two; any other request, or a model with no
59
+ # cache-write rate, is held as plain input.
60
+ def most_cost(price, input, cached)
61
+ costs = [price.call(input_tokens: input)]
62
+ costs << price.call(input_tokens: 0, cache_write_tokens: input) if cached
63
+ costs.compact.max
64
+ end
65
+
66
+ # A cache marker on the request's own params or on a block of one of its
67
+ # messages, where Smith puts a cached part's.
68
+ def cache_marked?(request)
69
+ marked_block?(request[:params]) || Array(request[:messages]).any? { marked_message?(_1) }
70
+ end
71
+
72
+ def marked_message?(message)
73
+ content = message.content if message.respond_to?(:content)
74
+ content.is_a?(::RubyLLM::Content::Raw) && Array(content.value).any? { marked_block?(_1) }
75
+ end
76
+
77
+ def marked_block?(block) = block.is_a?(Hash) && !(block[:cache_control] || block["cache_control"]).nil?
78
+
49
79
  def input_estimate(messages, tools, schema)
50
80
  counter = Counter.new
51
81
  Array(messages).each { counter.message(_1) }
@@ -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
 
@@ -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.13.1"
4
+ VERSION = "0.15.0"
5
5
  EXECUTION_SEMANTICS_VERSION = "7"
6
6
  end
@@ -16,17 +16,21 @@ module Smith
16
16
  Thread.current[:smith_call_reservation] = ledger.reserve_spent!(estimates)
17
17
  end
18
18
 
19
- def charge_untaken_batch_results(transition)
19
+ def charge_untaken_batch_results(transition, delivered)
20
20
  @batch_delivery.untaken.each do |branch_key, entry|
21
21
  next unless entry.result["type"] == "succeeded"
22
22
 
23
23
  Attribution.with(branch_key:) do
24
- charge_batch_result(batch_agent_class(transition, branch_key), entry.result.fetch("message"))
24
+ charge_batch_result(batch_agent_class(transition, branch_key, delivered), entry.result.fetch("message"))
25
25
  end
26
26
  end
27
27
  end
28
28
 
29
- def batch_agent_class(transition, branch_key)
29
+ # The agent whose call a result answers: a fan-out branch's, an
30
+ # optimize step's generator or evaluator (the call its pending batch
31
+ # `delivered` waited for), or the step's own.
32
+ def batch_agent_class(transition, branch_key, delivered)
33
+ return optimizer_batch_agent(transition, delivered.fetch("progress")) if transition.optimized?
30
34
  return resolve_agent_class(transition) unless branch_key
31
35
 
32
36
  resolve_fanout_agent_class(transition, transition.fanout_config.fetch(:branches).fetch(branch_key))
@@ -17,15 +17,19 @@ module Smith
17
17
  module BatchExecution
18
18
  # Batches end within 24 hours; the wait allows one more.
19
19
  WAIT_SECONDS = 25 * 3600
20
- # The requests an attempt captured, for the step to queue.
21
- Captured = Data.define(:token, :requests, :attempt, :key_generation)
20
+ # The requests an attempt captured, for the step to queue, and an
21
+ # optimize step's `progress` (OptimizerBatch).
22
+ Captured = Data.define(:token, :requests, :attempt, :key_generation, :progress) do
23
+ def initialize(progress: nil, **) = super
24
+ end
22
25
 
23
26
  private
24
27
 
25
28
  # The attempt sends its requests as a batch: its mode says so and no
26
- # result of it is being delivered.
29
+ # result of it is being delivered. An optimize step batches each of
30
+ # its loop's calls instead (OptimizerBatch).
27
31
  def batch_send?(transition)
28
- transition.batches? && !delivering_batch? && batch_mode_for(transition) == :batch
32
+ transition.batches? && !transition.optimized? && !delivering_batch? && batch_mode_for(transition) == :batch
29
33
  end
30
34
 
31
35
  # A delivery runs only the stored batch wait's step (BatchWait).
@@ -45,10 +49,11 @@ module Smith
45
49
 
46
50
  # An agent step's batch: its one call.
47
51
  def send_agent_batch(transition, agent_class, prepared_input)
48
- send_batch(transition, nil => lambda do
52
+ capture = lambda do
49
53
  admit_batch_call { reserve_for_serial(transition, effective_call_ledger) }
50
54
  with_agent_context(agent_class) { capture_batch_request(agent_class, prepared_input) }
51
- end)
55
+ end
56
+ send_batch(transition, { nil => capture })
52
57
  end
53
58
 
54
59
  # A fan-out's batch: each branch's call, captured in its own branch
@@ -82,11 +87,11 @@ module Smith
82
87
 
83
88
  # The request the agent's call would send (BatchExchange throws it out
84
89
  # of the call before anything is sent), and its hold.
85
- def capture_batch_request(agent_class, prepared_input)
90
+ def capture_batch_request(agent_class, prepared_input, **call)
86
91
  @batch_capture = nil
87
92
  request = catch(Providers::BatchExchange::CAPTURED) do
88
93
  @batch_capturing = true
89
- invoke_agent(agent_class, prepared_input)
94
+ invoke_agent(agent_class, prepared_input, **call)
90
95
  nil
91
96
  ensure
92
97
  @batch_capturing = false
@@ -94,13 +99,15 @@ module Smith
94
99
  [request || raise(BatchModeUnavailable, "a batch step's agent made no provider request"), @batch_capture.hold]
95
100
  end
96
101
 
97
- def send_batch(transition, captures)
102
+ # `position` tells apart the waits of one attempt (an optimize step's
103
+ # calls), `progress` is its loop's.
104
+ def send_batch(transition, captures, position: [], progress: nil)
98
105
  refuse_batch_wait!
99
- token = wait_token_for(transition, ["batch", @step_attempt || 1])
106
+ token = wait_token_for(transition, ["batch", @step_attempt || 1, *position])
100
107
  captured = captures.transform_values(&:call)
101
108
  hold_batch!(token, captured.transform_values(&:last))
102
109
  Captured.new(token:, requests: captured.transform_values(&:first), attempt: @step_attempt || 1,
103
- key_generation: @step_key_generation || 0)
110
+ key_generation: @step_key_generation || 0, progress:)
104
111
  end
105
112
 
106
113
  # The run can wait for a batch: a queue takes its requests, it is not
@@ -141,8 +148,11 @@ module Smith
141
148
  end
142
149
 
143
150
  def pending_batch_record(transition, captured, ids)
144
- { "transition" => transition.name.to_s, "attempt" => captured.attempt,
145
- "key_generation" => captured.key_generation, "requests" => ids.transform_values { Batch.digest(_1) } }.freeze
151
+ record = { "transition" => transition.name.to_s, "attempt" => captured.attempt,
152
+ "key_generation" => captured.key_generation,
153
+ "requests" => ids.transform_values { Batch.digest(_1) } }
154
+ record["progress"] = captured.progress if captured.progress
155
+ record.freeze
146
156
  end
147
157
  end
148
158
  end
@@ -40,12 +40,13 @@ module Smith
40
40
  # Each result settles the hold its request took on a host's budget
41
41
  # ledger (BatchExecution), taken by a call or not: a succeeded one
42
42
  # reconciles what it cost, any other (or a wait that expired) releases.
43
- def settle_batch_holds(transition, token, entries)
43
+ # `delivered` is the pending batch the results answer.
44
+ def settle_batch_holds(transition, token, entries, delivered)
44
45
  ledger = settling_ledger
45
46
  return unless ledger
46
47
 
47
48
  entries.each do |branch_key, entry|
48
- spent = batch_spent(transition, branch_key, entry.result)
49
+ spent = batch_spent(transition, branch_key, entry.result, delivered)
49
50
  Budget::HostLedger.settle(ledger, Batch.custom_id(token, branch_key), spent)
50
51
  end
51
52
  end
@@ -60,12 +61,12 @@ module Smith
60
61
  nil
61
62
  end
62
63
 
63
- def batch_spent(transition, branch_key, result)
64
+ def batch_spent(transition, branch_key, result, delivered)
64
65
  return unless result["type"] == "succeeded"
65
66
 
66
67
  message = result.fetch("message")
67
68
  usage = batch_reply_usage(message)
68
- model = batch_model_id(batch_agent_class(transition, branch_key), message)
69
+ model = batch_model_id(batch_agent_class(transition, branch_key, delivered), message)
69
70
  Budget::HostLedger.amount(usage, model:, provider: "anthropic", mode: :batch) if usage
70
71
  end
71
72
  end
@@ -16,8 +16,10 @@ module Smith
16
16
  # by a sibling's failure) is charged all the same (BatchCharges).
17
17
  module BatchWait
18
18
  PENDING_BATCH_FIELDS = %w[attempt key_generation requests transition].freeze
19
+ # An optimize step's pending batch also keeps its loop's progress.
20
+ PENDING_PROGRESS_FIELDS = (PENDING_BATCH_FIELDS + %w[progress]).sort.freeze
19
21
  DIGEST = /\A\h{64}\z/
20
- private_constant :PENDING_BATCH_FIELDS, :DIGEST
22
+ private_constant :PENDING_BATCH_FIELDS, :PENDING_PROGRESS_FIELDS, :DIGEST
21
23
 
22
24
  private
23
25
 
@@ -55,17 +57,19 @@ module Smith
55
57
 
56
58
  # The step runs again at the batch's attempt, each call taking its
57
59
  # result. It may enter another wait (a batch sent again, or a durable
58
- # retry's backoff); otherwise it counts. A completion that raises
59
- # leaves the run waiting.
60
+ # retry's backoff); otherwise it counts. The results settle their
61
+ # holds first, so a request the step holds next never overlaps them. A
62
+ # completion that raises leaves the run waiting.
60
63
  def complete_batch_wait(transition, entries, done)
61
64
  record = @awaiting
65
+ delivered = @pending_batch
62
66
  @awaiting = nil
63
67
  @batch_delivery = Batch::Delivery.new(entries, on_change: transition.on_request_change || :keep)
68
+ settle_batch_holds(transition, record.fetch("token"), entries, delivered)
64
69
  step = with_step_context(transition) do
65
70
  Execution.instance_method(:execute_step_body).bind_call(self, transition)
66
71
  ensure
67
- settle_batch_holds(transition, record.fetch("token"), entries)
68
- charge_untaken_batch_results(transition)
72
+ charge_untaken_batch_results(transition, delivered)
69
73
  end
70
74
  settle_batch_wait(step)
71
75
  return done if wait_pending?(step)
@@ -99,26 +103,49 @@ module Smith
99
103
  # A persisted pending batch names the stored batch wait's transition
100
104
  # (which WaitRecord checked is still a batch step), an attempt its
101
105
  # retry policy allows, a key generation only a declared
102
- # `new_idempotency_key_on` moves, and the digest of each request the
103
- # step's branches send; a stored batch wait needs one. Anything else
104
- # raises SerializationError.
106
+ # `new_idempotency_key_on` moves, the digest of each request the
107
+ # step's branches send, and for an optimize step its loop's progress
108
+ # (OptimizerBatch); a stored batch wait needs one, the one its token
109
+ # was made for. Anything else raises SerializationError.
105
110
  def restore_pending_batch(value)
106
111
  return if value.nil? && !batch_waiting?
107
112
 
108
113
  record = value.is_a?(Hash) ? value.transform_keys(&:to_s) : {}
114
+ check_pending_batch!(record)
115
+ record.transform_values(&:freeze).freeze
116
+ end
117
+
118
+ def check_pending_batch!(record)
109
119
  raise Smith::SerializationError, "persisted workflow pending_batch is invalid" unless
110
120
  well_formed_pending_batch?(record)
121
+ return if batch_wait_made_for?(record)
111
122
 
112
- record.transform_values(&:freeze).freeze
123
+ raise Smith::SerializationError, "persisted workflow pending_batch is not the one its wait was made for"
124
+ end
125
+
126
+ # The wait's token is the one the step makes for the record's attempt
127
+ # (and an optimize step's round and call), so no stored record moves a
128
+ # wait to another attempt or call.
129
+ def batch_wait_made_for?(record)
130
+ transition = self.class.transition_named(@awaiting["transition"])
131
+ position = transition.optimized? ? record["progress"].values_at("round", "role") : []
132
+ wait_token_for(transition, ["batch", record["attempt"], *position]) == @awaiting["token"]
113
133
  end
114
134
 
115
135
  def well_formed_pending_batch?(record)
116
136
  transition = self.class.transition_named(@awaiting["transition"]) if batch_waiting?
117
- transition && record.keys.sort == PENDING_BATCH_FIELDS && record["transition"] == transition.name.to_s &&
118
- allowed_batch_position?(transition, *record.values_at("attempt", "key_generation")) &&
119
- batch_digests?(transition, record["requests"])
137
+ transition && record.keys.sort == pending_batch_fields(transition) &&
138
+ record["transition"] == transition.name.to_s && pending_batch_parts?(transition, record)
139
+ end
140
+
141
+ def pending_batch_parts?(transition, record)
142
+ allowed_batch_position?(transition, *record.values_at("attempt", "key_generation")) &&
143
+ batch_digests?(transition, record["requests"]) &&
144
+ (!transition.optimized? || optimizer_progress?(transition, record["progress"], record["attempt"]))
120
145
  end
121
146
 
147
+ def pending_batch_fields(transition) = transition.optimized? ? PENDING_PROGRESS_FIELDS : PENDING_BATCH_FIELDS
148
+
122
149
  def allowed_batch_position?(transition, attempt, generation)
123
150
  config = transition.retry_config
124
151
  attempt.is_a?(Integer) && attempt.between?(1, config&.fetch(:attempts) || 1) && generation.is_a?(Integer) &&
@@ -5,10 +5,13 @@ require "json"
5
5
  require_relative "agent_result"
6
6
  require_relative "execution_result_snapshot"
7
7
  require_relative "optimization_state"
8
+ require_relative "optimizer_batch"
8
9
 
9
10
  module Smith
10
11
  class Workflow
11
12
  module EvaluatorOptimizer
13
+ include OptimizerBatch
14
+
12
15
  private
13
16
 
14
17
  def execute_optimization_step(transition, prepared_input: nil)
@@ -26,15 +29,25 @@ module Smith
26
29
  role: :evaluator
27
30
  )
28
31
  pend_evaluations
29
- run_optimization_loop(state)
32
+ run_optimization_loop(state, transition)
30
33
  end
31
34
 
32
- def run_optimization_loop(state)
33
- state.config[:max_rounds].times do |round|
35
+ # From round 0, or from the round and call a batch delivery goes on
36
+ # from (OptimizerBatch).
37
+ def run_optimization_loop(state, transition)
38
+ first, call = resume_optimizer_progress(state)
39
+ ((first || 0)...state.config[:max_rounds]).each do |round|
40
+ state.round = round
41
+ resumed = round == first
42
+ at_evaluator = resumed && call == "evaluator"
34
43
  # The overlay scopes every trace and usage fact from this round's
35
44
  # generator and evaluator calls to the round that produced them.
36
45
  result = Attribution.with(round: round) do
37
- IdempotencyKey.__send__(:within, :round, round) { run_optimization_round(state, round) }
46
+ IdempotencyKey.__send__(:within, :round, round) do
47
+ with_round_captures(round) do
48
+ run_optimization_round(state, round, transition, at_evaluator:, resumed:)
49
+ end
50
+ end
38
51
  end
39
52
  return result if result
40
53
  end
@@ -43,13 +56,37 @@ module Smith
43
56
  "optimization exhausted #{state.config[:max_rounds]} rounds without acceptance")
44
57
  end
45
58
 
59
+ # Every tool capture the round takes names it (`round`), as its usage
60
+ # entries, traces and verdicts do. The round's collector stamps each
61
+ # entry on its way to the step's, in place, so the captures of an
62
+ # attempt a call sets aside still leave by identity
63
+ # (Agent::AttemptCaptures); it is the collector, not the attribution,
64
+ # that reaches concurrent tool calls.
65
+ def with_round_captures(round, &block)
66
+ collector = Tool.current_tool_result_collector
67
+ return yield unless collector.respond_to?(:call)
68
+
69
+ stamped = ->(entry) { collector.call(entry.is_a?(Hash) ? entry.merge!(round:) : entry) }
70
+ Thread.handle_interrupt(Object => :never) do
71
+ Tool.current_tool_result_collector = stamped
72
+ begin
73
+ Thread.handle_interrupt(Object => :immediate, &block)
74
+ ensure
75
+ Tool.current_tool_result_collector = collector
76
+ end
77
+ end
78
+ end
79
+
46
80
  # Each role is a position of its own in the round, so the generator,
47
- # the before_eval callback and the evaluator never share a key.
48
- def run_optimization_round(state, round)
49
- IdempotencyKey.__send__(:within, :generator) { generate_candidate!(state, round) }
50
- rejection = IdempotencyKey.__send__(:within, :before_eval) { before_eval_rejection(state) }
51
- evaluation = rejection ||
52
- normalize_evaluation(IdempotencyKey.__send__(:within, :evaluator) { evaluate_candidate(state) })
81
+ # the before_generate and before_eval callbacks and the evaluator never
82
+ # share a key. A round a delivery goes on from at its evaluator has its
83
+ # candidate, and one it goes on from at its generator asked
84
+ # before_generate when its request was batched.
85
+ def run_optimization_round(state, round, transition, at_evaluator: false, resumed: false)
86
+ rejection = generate_and_screen(state, round, transition, resumed:) unless at_evaluator
87
+ evaluation = rejection || normalize_evaluation(
88
+ IdempotencyKey.__send__(:within, :evaluator) { evaluate_candidate(state, round, transition) }
89
+ )
53
90
  validate_evaluation_structure!(evaluation)
54
91
  validate_evaluation_fields!(evaluation, state.config)
55
92
  record_evaluation(state, evaluation, round, rejection ? :before_eval : :evaluator)
@@ -201,24 +238,76 @@ module Smith
201
238
  end
202
239
  end
203
240
 
204
- def generate_candidate!(state, round)
205
- input = prepare_generator_input(state.prepared_input, round, state.candidate, state.feedback)
206
- result = invoke_agent_with_budget(state.generator_class, input)
207
- state.candidate = result
241
+ # The round's candidate, and a before_eval rejection of it, if any.
242
+ def generate_and_screen(state, round, transition, resumed: false)
243
+ IdempotencyKey.__send__(:within, :before_generate) { run_before_generate(state) } unless resumed
244
+ IdempotencyKey.__send__(:within, :generator) { generate_candidate!(state, round, transition) }
245
+ IdempotencyKey.__send__(:within, :before_eval) { before_eval_rejection(state) }
208
246
  end
209
247
 
210
- def evaluate_candidate(state)
211
- input = build_evaluator_input(state)
212
- invoke_with_evaluator_schema(state.evaluator_class, state.config[:evaluator_schema], input)
248
+ # Everything this step's earlier rounds and attempts did belongs to a
249
+ # round the loop rejected or an attempt that failed, so a host sets
250
+ # aside what they staged here, before a later round builds on it, and
251
+ # may say what they were (`{ rejected_round: String }`), since the
252
+ # candidate does not carry its tools' work.
253
+ def run_before_generate(state)
254
+ state.told = nil
255
+ callback = state.config[:before_generate]
256
+ return unless callback
257
+
258
+ state.told = rejected_round_note(callback.call(state, @context))
259
+ nil
260
+ end
261
+
262
+ # The words under `rejected_round` of a Hash before_generate returns,
263
+ # copied and bounded as a message's are; anything else, or blank
264
+ # words, tells the round nothing.
265
+ def rejected_round_note(returned)
266
+ return unless returned.is_a?(Hash)
267
+
268
+ note = returned.key?(:rejected_round) ? returned[:rejected_round] : returned["rejected_round"]
269
+ return if note.nil?
270
+ raise WorkflowError, "before_generate's rejected_round must be a String" unless note.is_a?(String)
271
+
272
+ copy = StringSnapshot.copy(note, freeze: true)
273
+ if StringSnapshot.bytesize(copy) > MessageValueNormalizer::MAX_BYTES
274
+ raise WorkflowError, "before_generate's rejected_round is over #{MessageValueNormalizer::MAX_BYTES} bytes"
275
+ end
276
+
277
+ copy unless copy.strip.empty?
278
+ end
279
+
280
+ # A later round's draft replaces the one rejected before it, whose
281
+ # streamed text is withdrawn first (`reset(:rejected)`).
282
+ def generate_candidate!(state, round, transition)
283
+ withdraw_streamed(:rejected) if round.positive?
284
+ input = prepare_generator_input(state.prepared_input, round, state.candidate, state.feedback, state.told)
285
+ state.candidate = optimizer_call(transition, state, round, "generator", input)
286
+ end
287
+
288
+ # A verdict is never the step's words: a streamed step's sink hears its
289
+ # generator alone.
290
+ def evaluate_candidate(state, round, transition)
291
+ unstreamed { optimizer_call(transition, state, round, "evaluator", build_evaluator_input(state)) }
213
292
  end
214
293
 
215
294
  # evaluator_context: :inject_state appends the candidate as a
216
295
  # user turn to the prepared_input the generator received, so the
217
- # evaluator sees the same seed_messages + inject_state context.
218
- # Default nil keeps the legacy candidate-only payload.
296
+ # evaluator sees the same seed_messages + inject_state context. A
297
+ # callable builds the evaluator's messages itself from copies of the
298
+ # candidate and the context, checked as a step's input: is, so the
299
+ # evaluator can read its own part of the context and keep a stable
300
+ # prefix across rounds. Default nil keeps the legacy candidate-only
301
+ # payload.
219
302
  def build_evaluator_input(state)
303
+ mode = state.config[:evaluator_context]
304
+ if mode.respond_to?(:call)
305
+ return checked_input(mode.call(snapshot_value(state.candidate), snapshot_value(@context)),
306
+ "evaluator_context:")
307
+ end
308
+
220
309
  content = candidate_content(state.candidate)
221
- return [{ role: :user, content: }] unless state.config[:evaluator_context] == :inject_state
310
+ return [{ role: :user, content: }] unless mode == :inject_state
222
311
 
223
312
  prior = Array(state.prepared_input).dup
224
313
  prior.push(role: :user, content:)
@@ -248,10 +337,6 @@ module Smith
248
337
  evaluation if evaluation.key?(:accept) && evaluation[:accept].equal?(false)
249
338
  end
250
339
 
251
- def invoke_with_evaluator_schema(evaluator_class, schema, input)
252
- invoke_agent_with_budget(evaluator_class, input, output_schema: schema)
253
- end
254
-
255
340
  def invoke_agent_with_budget(agent_class, prepared_input, output_schema: agent_class.output_schema)
256
341
  Thread.current[:smith_last_agent_result] = nil
257
342
  clear_failed_billable_attempts
@@ -295,15 +380,16 @@ module Smith
295
380
  nil
296
381
  end
297
382
 
298
- def prepare_generator_input(prepared_input, round, prior_candidate, feedback)
383
+ # A later round is told its rejected candidate, the evaluator's
384
+ # feedback and what before_generate said the round's tools left.
385
+ def prepare_generator_input(prepared_input, round, prior_candidate, feedback, told)
299
386
  return prepared_input if round.zero?
300
387
 
388
+ content = "[smith:refinement-round] #{round + 1}\n[smith:evaluator-feedback]\n#{feedback}"
389
+ content += "\n[smith:rejected-round]\n#{told}" if told
301
390
  (prepared_input&.dup || []).push(
302
391
  { role: :assistant, content: candidate_content(prior_candidate) },
303
- {
304
- role: :user,
305
- content: "[smith:refinement-round] #{round + 1}\n[smith:evaluator-feedback]\n#{feedback}"
306
- }
392
+ { role: :user, content: }
307
393
  )
308
394
  end
309
395
 
@@ -76,7 +76,7 @@ module Smith
76
76
  prepared_input = step_prepared_input(transition)
77
77
  return send_agent_batch(transition, agent_class, prepared_input) if batch_send?(transition)
78
78
 
79
- guarded_agent_output(transition, agent_class, prepared_input)
79
+ optimizer_batch_output(transition) { guarded_agent_output(transition, agent_class, prepared_input) }
80
80
  end
81
81
 
82
82
  def guarded_agent_output(transition, agent_class, prepared_input)
@@ -27,6 +27,7 @@ module Smith
27
27
 
28
28
  def agents(transition)
29
29
  return transition.fanout_config.fetch(:branches).values if transition.fanout?
30
+ return transition.optimization_config.values_at(:generator, :evaluator) if transition.optimized?
30
31
 
31
32
  [transition.agent_name]
32
33
  end
@@ -47,6 +47,7 @@ module Smith
47
47
  evaluator_schema: config.fetch(:evaluator_schema_label),
48
48
  evaluator_context: config[:evaluator_context],
49
49
  improvement_threshold: config[:improvement_threshold],
50
+ before_generate: config[:before_generate],
50
51
  before_eval: config[:before_eval]
51
52
  }
52
53
  end