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
@@ -37,12 +37,16 @@ module Smith
37
37
  def run_optimization_loop(state, transition)
38
38
  first, call = resume_optimizer_progress(state)
39
39
  ((first || 0)...state.config[:max_rounds]).each do |round|
40
- at_evaluator = round == first && call == "evaluator"
40
+ state.round = round
41
+ resumed = round == first
42
+ at_evaluator = resumed && call == "evaluator"
41
43
  # The overlay scopes every trace and usage fact from this round's
42
44
  # generator and evaluator calls to the round that produced them.
43
45
  result = Attribution.with(round: round) do
44
46
  IdempotencyKey.__send__(:within, :round, round) do
45
- run_optimization_round(state, round, transition, at_evaluator:)
47
+ with_round_captures(round) do
48
+ run_optimization_round(state, round, transition, at_evaluator:, resumed:)
49
+ end
46
50
  end
47
51
  end
48
52
  return result if result
@@ -52,11 +56,34 @@ module Smith
52
56
  "optimization exhausted #{state.config[:max_rounds]} rounds without acceptance")
53
57
  end
54
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
+
55
80
  # Each role is a position of its own in the round, so the generator,
56
- # the before_eval callback and the evaluator never share a key. A
57
- # round a delivery goes on from at its evaluator has its candidate.
58
- def run_optimization_round(state, round, transition, at_evaluator: false)
59
- rejection = generate_and_screen(state, round, transition) unless at_evaluator
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
60
87
  evaluation = rejection || normalize_evaluation(
61
88
  IdempotencyKey.__send__(:within, :evaluator) { evaluate_candidate(state, round, transition) }
62
89
  )
@@ -212,27 +239,75 @@ module Smith
212
239
  end
213
240
 
214
241
  # The round's candidate, and a before_eval rejection of it, if any.
215
- def generate_and_screen(state, round, transition)
242
+ def generate_and_screen(state, round, transition, resumed: false)
243
+ IdempotencyKey.__send__(:within, :before_generate) { run_before_generate(state) } unless resumed
216
244
  IdempotencyKey.__send__(:within, :generator) { generate_candidate!(state, round, transition) }
217
245
  IdempotencyKey.__send__(:within, :before_eval) { before_eval_rejection(state) }
218
246
  end
219
247
 
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)`).
220
282
  def generate_candidate!(state, round, transition)
221
- input = prepare_generator_input(state.prepared_input, round, state.candidate, state.feedback)
283
+ withdraw_streamed(:rejected) if round.positive?
284
+ input = prepare_generator_input(state.prepared_input, round, state.candidate, state.feedback, state.told)
222
285
  state.candidate = optimizer_call(transition, state, round, "generator", input)
223
286
  end
224
287
 
288
+ # A verdict is never the step's words: a streamed step's sink hears its
289
+ # generator alone.
225
290
  def evaluate_candidate(state, round, transition)
226
- optimizer_call(transition, state, round, "evaluator", build_evaluator_input(state))
291
+ unstreamed { optimizer_call(transition, state, round, "evaluator", build_evaluator_input(state)) }
227
292
  end
228
293
 
229
294
  # evaluator_context: :inject_state appends the candidate as a
230
295
  # user turn to the prepared_input the generator received, so the
231
- # evaluator sees the same seed_messages + inject_state context.
232
- # 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.
233
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
+
234
309
  content = candidate_content(state.candidate)
235
- return [{ role: :user, content: }] unless state.config[:evaluator_context] == :inject_state
310
+ return [{ role: :user, content: }] unless mode == :inject_state
236
311
 
237
312
  prior = Array(state.prepared_input).dup
238
313
  prior.push(role: :user, content:)
@@ -305,15 +380,16 @@ module Smith
305
380
  nil
306
381
  end
307
382
 
308
- 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)
309
386
  return prepared_input if round.zero?
310
387
 
388
+ content = "[smith:refinement-round] #{round + 1}\n[smith:evaluator-feedback]\n#{feedback}"
389
+ content += "\n[smith:rejected-round]\n#{told}" if told
311
390
  (prepared_input&.dup || []).push(
312
391
  { role: :assistant, content: candidate_content(prior_candidate) },
313
- {
314
- role: :user,
315
- content: "[smith:refinement-round] #{round + 1}\n[smith:evaluator-feedback]\n#{feedback}"
316
- }
392
+ { role: :user, content: }
317
393
  )
318
394
  end
319
395
 
@@ -19,6 +19,7 @@ module Smith
19
19
  include StepStream
20
20
  include Agent::Lifecycle
21
21
  include NestedExecution
22
+ include NestedItemsExecution
22
23
  include EvaluatorOptimizer
23
24
  include OrchestratorWorker
24
25
  include ParallelExecution
@@ -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, :MODULE_MATCH
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(Smith::ToolOutcomeUncertain, error)
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 persisted_failure_invalid
45
- deadline_exceeded provider_permanent_failure budget_exceeded guardrail_failed agent_error workflow_error
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 tool_execution_not_admitted
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) },
@@ -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
@@ -20,12 +20,17 @@ module Smith
20
20
  next unless transition.stream
21
21
  next missing_sink(transition) unless Smith.config.stream_sinks.key?(transition.stream)
22
22
 
23
- whole_replies(transition) if responses_route?(transition.agent_name)
23
+ whole_replies(transition) if responses_route?(streamed_agent(transition))
24
24
  end
25
25
  end
26
26
 
27
27
  private
28
28
 
29
+ # The agent whose text streams: an `optimize` step's generator.
30
+ def streamed_agent(transition)
31
+ transition.optimized? ? transition.optimization_config.fetch(:generator) : transition.agent_name
32
+ end
33
+
29
34
  def responses_route?(agent)
30
35
  agent_class = Agent::Registry.binding_for(agent)&.fetch(:agent_class)
31
36
  return false unless agent_class.respond_to?(:chat_kwargs)
@@ -81,10 +86,10 @@ module Smith
81
86
  def whole_replies(transition)
82
87
  Diagnostic.new(
83
88
  severity: :warning, code: :stream_whole_replies, transition: transition.name,
84
- target: transition.agent_name,
89
+ target: streamed_agent(transition),
85
90
  message: "Transition #{Reference.format(transition.name)} streams agent " \
86
- "#{Reference.format(transition.agent_name)}, whose calls go to OpenAI's Responses API, which " \
87
- "does not stream: its sink gets each reply as one delta.",
91
+ "#{Reference.format(streamed_agent(transition))}, whose calls go to OpenAI's Responses API, " \
92
+ "which does not stream: its sink gets each reply as one delta.",
88
93
  suggestion: "Accept whole replies there, or keep the agent on Chat Completions " \
89
94
  "(Smith.config.openai_api_mode = :off, and no openai_api_mode param)."
90
95
  )
@@ -32,6 +32,7 @@ module Smith
32
32
  evaluator_schema_label: label(config.fetch(:evaluator_schema)),
33
33
  evaluator_context: callable_marker(config[:evaluator_context]),
34
34
  improvement_threshold: config[:improvement_threshold],
35
+ before_generate: callable_marker(config[:before_generate]),
35
36
  before_eval: callable_marker(config[:before_eval])
36
37
  }
37
38
  end
@@ -50,7 +50,7 @@ module Smith
50
50
  @resolved_parallel_branch_count = nil
51
51
  end
52
52
 
53
- # Hooks that receive the live context (`before_eval`,
53
+ # Hooks that receive the live context (`before_generate`, `before_eval`,
54
54
  # `after_completion`, guardrails) can write to it directly. At the end
55
55
  # of the step every new top-level key must be a Symbol that an explicit
56
56
  # `persist` list allows, and every new or replaced value takes the
@@ -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
- def new_nested_workflow(child_class)
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: @context.dup, ledger: @ledger, created_at: @created_at)
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
@@ -88,11 +94,17 @@ module Smith
88
94
 
89
95
  # A child that handled its failure through its own `on_failure` route
90
96
  # has already applied its failure policy, so the parent sees a
91
- # non-retryable WorkflowError, as before.
97
+ # non-retryable WorkflowError, as before, its cause the child's own
98
+ # error, so a host can still read what the child failed on.
92
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
+
93
104
  if failed_step
94
105
  raise WorkflowError,
95
- "nested workflow failed: #{DiagnosticText.capture(failed_step[:error]&.message.to_s, max_bytes: 1024)}"
106
+ "nested workflow failed: #{DiagnosticText.capture(failed_step[:error]&.message.to_s, max_bytes: 1024)}",
107
+ cause: failed_step[:error]
96
108
  end
97
109
 
98
110
  child_result.output
@@ -0,0 +1,122 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Smith
4
+ class Workflow
5
+ # A fan-out over items (Transition#workflow's `over:`): one nested run an
6
+ # item, each in a branch of its own (its idempotency keys and usage
7
+ # attributed to the item's index), at most `concurrency` at once, each
8
+ # item's outcome its own (NestedExecution builds and runs each child).
9
+ # Each item's run spends within an equal share of what the run's budget
10
+ # has left in every dimension it bounds, held from it while the item runs
11
+ # and settled at what it spent, so runs going at once never take one
12
+ # another's room.
13
+ module NestedItemsExecution
14
+ Envelope = Struct.new(:reservation, :ledger)
15
+ private_constant :Envelope
16
+
17
+ private
18
+
19
+ def execute_nested_items(transition)
20
+ config = transition.nested_items
21
+ items = nested_items_of(config)
22
+ return [] if items.empty?
23
+
24
+ env = items_environment(items.length)
25
+ branches = items.each_with_index.map do |item, index|
26
+ PreparedBranchExecution.instance_method(:prepared_branch).bind_call(
27
+ self, NestedItemsExecution.instance_method(:run_nested_item), transition, index, item, env
28
+ )
29
+ end
30
+ Parallel.execute(branches:, concurrency: config[:concurrency])
31
+ end
32
+
33
+ def items_environment(count)
34
+ BranchEnv.new(prepared_input: nil, guardrail_sources: Tool.current_guardrails,
35
+ scoped_store: propagate_scoped_artifacts,
36
+ branch_estimates: item_shares(count),
37
+ deadline: wall_clock_deadline)
38
+ end
39
+
40
+ # Each item's share of what the run's budget has left, in every dimension.
41
+ def item_shares(count)
42
+ @ledger && @ledger.limits.keys.to_h { |dimension| [dimension, @ledger.remaining_share(dimension, count)] }
43
+ end
44
+
45
+ def nested_items_of(config)
46
+ items = config[:over].call(snapshot_value(@context))
47
+ raise WorkflowError, "a workflow step's over: must return an Array of items" unless items.is_a?(Array)
48
+
49
+ limit = Smith.config.parallel_branch_limit
50
+ raise WorkflowError, "a workflow step's items exceed the configured limit #{limit}" if items.length > limit
51
+
52
+ snapshot_value(items)
53
+ end
54
+
55
+ def run_nested_item(transition, index, item, env, signal)
56
+ with_branch_context(env, @ledger, attribution_overlay: { branch_key: index }) do
57
+ check_cancellation!(signal)
58
+ check_deadline!
59
+ envelope = item_envelope(env)
60
+ begin
61
+ run_item_child(transition, item, envelope)
62
+ ensure
63
+ settle_item_envelope(envelope)
64
+ end
65
+ end
66
+ end
67
+
68
+ def run_item_child(transition, item, envelope)
69
+ child = build_child_workflow(transition.workflow_class, item: [transition.nested_items[:item_to], item],
70
+ ledger: envelope&.ledger || @ledger)
71
+ child_result = run_nested_item_child(child)
72
+ reject_waiting_child!(child, child_result)
73
+ nested_item_outcome(child_result)
74
+ end
75
+
76
+ # The item's share, held from the run's budget, and a budget of that
77
+ # share for its run to spend within.
78
+ def item_envelope(env)
79
+ return unless @ledger && env.branch_estimates
80
+
81
+ Envelope.new(reserve_branch_budget(@ledger, branch_estimates: env.branch_estimates),
82
+ Budget::Ledger.new(limits: env.branch_estimates))
83
+ end
84
+
85
+ def settle_item_envelope(envelope)
86
+ return unless envelope
87
+
88
+ spent = envelope.ledger.consumed
89
+ @ledger.reconcile_many!(envelope.reservation, actual: envelope.ledger.limits.to_h { [_1, spent.fetch(_1, 0)] })
90
+ end
91
+
92
+ # A child that raised a refusal is that item's outcome, its usage kept.
93
+ def run_nested_item_child(child)
94
+ run_child_workflow(child)
95
+ rescue OutputRefused => e
96
+ { "refused" => e.message }
97
+ end
98
+
99
+ # The item's outcome: its output, or its refusal when its run ended on a
100
+ # refused response, its own failure route taken or not (the refusal its
101
+ # last failure, nothing after it giving output); any other failure fails
102
+ # the step, as a nested workflow's does.
103
+ def nested_item_outcome(child_result)
104
+ return child_result if child_result.is_a?(Hash) && child_result.key?("refused")
105
+
106
+ refused = ended_refused(child_result.steps)
107
+ if refused
108
+ roll_up_child_totals(child_result)
109
+ return { "refused" => refused.message }
110
+ end
111
+
112
+ { "output" => handle_child_result(child_result) }
113
+ end
114
+
115
+ def ended_refused(steps)
116
+ failed = steps.rindex { |step| step.key?(:error) }
117
+ error = failed && steps[failed][:error]
118
+ error if error.is_a?(OutputRefused) && steps.drop(failed + 1).all? { |step| step[:output].nil? }
119
+ end
120
+ end
121
+ end
122
+ end
@@ -2,11 +2,16 @@
2
2
 
3
3
  module Smith
4
4
  class Workflow
5
+ # What an optimize step's callables read: `round` is the round under
6
+ # way, from 0 in each attempt, the one its verdicts and captures name;
7
+ # `told`, what before_generate said the rejected round left, for the
8
+ # round under way.
5
9
  OptimizationState = Struct.new(
6
- :config, :prepared_input, :candidate, :feedback, :last_score, :generator_class, :evaluator_class, :evaluations
10
+ :config, :prepared_input, :candidate, :feedback, :last_score, :generator_class, :evaluator_class, :evaluations,
11
+ :round, :told
7
12
  ) do
8
13
  def initialize(config, prepared_input)
9
- super(config, prepared_input, nil, nil, nil, nil, nil, [].freeze)
14
+ super(config, prepared_input, nil, nil, nil, nil, nil, [].freeze, nil, nil)
10
15
  end
11
16
  end
12
17
  end
@@ -17,12 +17,14 @@ module Smith
17
17
  # and charged, once. The step's mode is asked at each call.
18
18
  module OptimizerBatch
19
19
  ROLES = %w[generator evaluator].freeze
20
- PROGRESS_FIELDS = %w[candidate evaluations feedback last_score role round].freeze
20
+ PROGRESS_FIELDS = %w[candidate evaluations feedback last_score role round told].freeze
21
+ # A wait kept before the round carried what before_generate told it.
22
+ UNTOLD_FIELDS = (PROGRESS_FIELDS - %w[told]).freeze
21
23
  RECORD_FIELDS = %w[round source verdict].freeze
22
24
  SOURCES = %w[evaluator before_eval].freeze
23
25
  ATTEMPT = /\A[1-9]\d*\z/
24
26
  CAPTURED = :smith_optimizer_batch
25
- private_constant :ROLES, :PROGRESS_FIELDS, :RECORD_FIELDS, :SOURCES, :ATTEMPT, :CAPTURED
27
+ private_constant :ROLES, :PROGRESS_FIELDS, :UNTOLD_FIELDS, :RECORD_FIELDS, :SOURCES, :ATTEMPT, :CAPTURED
26
28
 
27
29
  private
28
30
 
@@ -70,7 +72,7 @@ module Smith
70
72
  # What a delivery's loop goes on from, as JSON gives it.
71
73
  def optimizer_progress(state, round, role)
72
74
  progress = { "round" => round, "role" => role, "candidate" => state.candidate, "feedback" => state.feedback,
73
- "last_score" => state.last_score, "evaluations" => kept_evaluations }
75
+ "last_score" => state.last_score, "evaluations" => kept_evaluations, "told" => state.told }
74
76
  Batch.deep_freeze(JSON.parse(JSON.generate(progress)))
75
77
  rescue JSON::GeneratorError, JSON::NestingError, Encoding::UndefinedConversionError
76
78
  raise WorkflowError, "an optimize step waits for a batch only with JSON values for its candidate and feedback"
@@ -90,13 +92,17 @@ module Smith
90
92
  progress = @pending_batch&.fetch("progress", nil) if delivering_batch?
91
93
  return unless progress
92
94
 
93
- state.candidate, state.feedback, state.last_score =
94
- snapshot_value(progress.values_at("candidate", "feedback", "last_score"))
95
+ restore_loop_state(state, progress)
95
96
  restore_kept_evaluations(progress.fetch("evaluations"))
96
97
  state.evaluations = @pending_evaluations.values.last.dup.freeze
97
98
  progress.values_at("round", "role")
98
99
  end
99
100
 
101
+ def restore_loop_state(state, progress)
102
+ state.candidate, state.feedback, state.last_score, state.told =
103
+ snapshot_value(progress.values_at("candidate", "feedback", "last_score", "told"))
104
+ end
105
+
100
106
  # Kept verdicts back as the loop records them, in attempt order, the
101
107
  # attempt under way last.
102
108
  def restore_kept_evaluations(kept)
@@ -119,14 +125,20 @@ module Smith
119
125
  end
120
126
 
121
127
  # A stored pending batch's `progress` (BatchWait): a call of a
122
- # round the step runs, a last score that is a number or none, and kept
123
- # verdicts of attempts up to the batch's.
128
+ # round the step runs, a last score that is a number or none, words
129
+ # before_generate told the round or none, and kept verdicts of attempts
130
+ # up to the batch's.
124
131
  def optimizer_progress?(transition, progress, attempt)
125
- progress.is_a?(Hash) && progress.keys.sort == PROGRESS_FIELDS && optimizer_position?(transition, progress) &&
126
- (progress["last_score"].nil? || progress["last_score"].is_a?(Numeric)) &&
132
+ progress.is_a?(Hash) && [PROGRESS_FIELDS, UNTOLD_FIELDS].include?(progress.keys.sort) &&
133
+ optimizer_position?(transition, progress) && progress_values?(progress) &&
127
134
  kept_evaluations?(progress["evaluations"], attempt)
128
135
  end
129
136
 
137
+ def progress_values?(progress)
138
+ (progress["last_score"].nil? || progress["last_score"].is_a?(Numeric)) &&
139
+ (progress["told"].nil? || progress["told"].is_a?(String))
140
+ end
141
+
130
142
  def optimizer_position?(transition, progress)
131
143
  round = progress["round"]
132
144
  ROLES.include?(progress["role"]) && round.is_a?(Integer) &&
@@ -11,6 +11,7 @@ module Smith
11
11
 
12
12
  option :branches
13
13
  option :context
14
+ option :concurrency, optional: true
14
15
 
15
16
  def initialize(...)
16
17
  super
@@ -34,7 +35,7 @@ module Smith
34
35
 
35
36
  def prepare
36
37
  context.raise_if_cancelled!
37
- @reserved_workers = context.reserve_workers(branches.length - 1)
38
+ @reserved_workers = context.reserve_workers(running_at_once - 1)
38
39
  return if @reserved_workers.zero?
39
40
 
40
41
  @values = Array.new(branches.length)
@@ -43,6 +44,8 @@ module Smith
43
44
  @reserved_workers.times { @futures << build_future }
44
45
  end
45
46
 
47
+ def running_at_once = [branches.length, concurrency].compact.min
48
+
46
49
  def execute
47
50
  return execute_inline if @reserved_workers.zero?
48
51
 
@@ -10,6 +10,7 @@ module Smith
10
10
  extend Dry::Initializer
11
11
 
12
12
  option :branches
13
+ option :concurrency, optional: true
13
14
 
14
15
  def call
15
16
  Thread.handle_interrupt(Object => :never) do
@@ -30,7 +31,7 @@ module Smith
30
31
  def prepare
31
32
  @completed = false
32
33
  @signal = CancellationSignal.new
33
- @concurrency = Smith.config.parallel_concurrency
34
+ @concurrency = [Smith.config.parallel_concurrency, concurrency].compact.min
34
35
  @nesting_limit = Smith.config.parallel_nesting_limit
35
36
  @executor = build_executor
36
37
  @futures = build_futures(build_context)