smith-agents 0.15.0 → 0.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +63 -0
  3. data/README.md +1 -1
  4. data/docs/AGENTS.md +48 -0
  5. data/docs/BUDGETS.md +10 -0
  6. data/docs/CONFIGURATION.md +6 -1
  7. data/docs/ERRORS_AND_RETRIES.md +13 -0
  8. data/docs/PATTERNS.md +51 -0
  9. data/lib/smith/agent/image_request.rb +38 -0
  10. data/lib/smith/agent/lifecycle.rb +2 -0
  11. data/lib/smith/agent/output_recovery.rb +4 -0
  12. data/lib/smith/agent/paint_input.rb +42 -0
  13. data/lib/smith/agent/painted_answer.rb +70 -0
  14. data/lib/smith/agent/provider_call_timing.rb +2 -1
  15. data/lib/smith/agent/provider_completion.rb +1 -1
  16. data/lib/smith/agent/provider_failure_handling.rb +27 -5
  17. data/lib/smith/agent/provider_paint.rb +128 -0
  18. data/lib/smith/agent/provider_usage.rb +27 -2
  19. data/lib/smith/agent/usage_tracking.rb +3 -1
  20. data/lib/smith/agent.rb +3 -1
  21. data/lib/smith/budget/host_ledger.rb +3 -1
  22. data/lib/smith/budget/request_hold.rb +16 -0
  23. data/lib/smith/errors.rb +8 -0
  24. data/lib/smith/pricing/catalog_validation.rb +20 -1
  25. data/lib/smith/pricing/images.rb +29 -0
  26. data/lib/smith/pricing.rb +37 -16
  27. data/lib/smith/providers/request_holds.rb +29 -4
  28. data/lib/smith/providers/request_outcome.rb +39 -0
  29. data/lib/smith/providers/stop_reason.rb +4 -2
  30. data/lib/smith/version.rb +1 -1
  31. data/lib/smith/workflow/agent_result.rb +5 -1
  32. data/lib/smith/workflow/composite/effects.rb +3 -1
  33. data/lib/smith/workflow/execution.rb +1 -0
  34. data/lib/smith/workflow/failure_reconstructor.rb +1 -0
  35. data/lib/smith/workflow/failure_record.rb +7 -3
  36. data/lib/smith/workflow/failure_record_validator.rb +7 -7
  37. data/lib/smith/workflow/nested_execution.rb +14 -4
  38. data/lib/smith/workflow/nested_items_execution.rb +122 -0
  39. data/lib/smith/workflow/parallel/nested_execution.rb +4 -1
  40. data/lib/smith/workflow/parallel/root_execution.rb +2 -1
  41. data/lib/smith/workflow/parallel.rb +13 -5
  42. data/lib/smith/workflow/transition.rb +27 -2
  43. data/lib/smith/workflow/usage_entry.rb +5 -0
  44. data/lib/smith.rb +2 -0
  45. metadata +8 -1
@@ -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
@@ -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)
@@ -28,17 +28,23 @@ module Smith
28
28
  count
29
29
  end
30
30
 
31
- def self.execute(branches:)
31
+ # `concurrency` caps how many of these branches run at once, below the
32
+ # configured parallel_concurrency.
33
+ def self.execute(branches:, concurrency: nil)
32
34
  validate_branch_count!(branches.length)
33
35
  context = ExecutionContext.current
34
- return NestedExecution.new(branches:, context:).call if context
36
+ return NestedExecution.new(branches:, context:, concurrency:).call if context
35
37
 
36
- RootExecution.new(branches:).call
38
+ RootExecution.new(branches:, concurrency:).call
37
39
  end
38
40
 
41
+ # A request that may have been billed outranks an interruption, which
42
+ # takes the step again: a branch's uncertain request is never sent
43
+ # twice because another branch was cut short.
39
44
  def self.preferred_error(reasons)
40
45
  errors = Array(reasons).compact
41
46
  process_fatal_error(errors) ||
47
+ uncertain_request(errors) ||
42
48
  interruption(errors) ||
43
49
  notification_failure(errors) ||
44
50
  terminal_execution_error(errors) ||
@@ -48,6 +54,8 @@ module Smith
48
54
 
49
55
  def self.process_fatal_error(errors) = errors.find { !_1.is_a?(StandardError) }
50
56
 
57
+ def self.uncertain_request(errors) = errors.find { _1.is_a?(RequestOutcomeUncertain) }
58
+
51
59
  def self.interruption(errors) = errors.find { Interruptions.find(_1) }
52
60
 
53
61
  def self.notification_failure(errors) = errors.find { _1.is_a?(ToolFailureNotificationFailed) }
@@ -56,8 +64,8 @@ module Smith
56
64
 
57
65
  def self.ordinary_error(errors) = errors.find { !_1.is_a?(Cancellation) }
58
66
 
59
- private_class_method :process_fatal_error, :interruption, :notification_failure, :terminal_execution_error,
60
- :ordinary_error
67
+ private_class_method :process_fatal_error, :uncertain_request, :interruption, :notification_failure,
68
+ :terminal_execution_error, :ordinary_error
61
69
  end
62
70
  end
63
71
  end
@@ -9,7 +9,7 @@ module Smith
9
9
  :router_config, :workflow_class, :optimization_config, :orchestrator_config,
10
10
  :fanout_config, :retry_config, :deterministic_block, :deterministic_kind,
11
11
  :deterministic_routes, :deterministic_fallthrough, :await_config, :timeout_transition,
12
- :step_input, :output_to, :stream, :batch_mode, :on_request_change
12
+ :step_input, :output_to, :stream, :batch_mode, :on_request_change, :nested_items
13
13
 
14
14
  def initialize(name, from:, to:, &)
15
15
  @name = own_identifier(name)
@@ -115,11 +115,22 @@ module Smith
115
115
  commit_execution_primitive!("route")
116
116
  end
117
117
 
118
- def workflow(klass)
118
+ # Runs `klass` in-process as one step. With `over:` (a callable of a
119
+ # copy of the context returning an Array of items) it is a fan-out
120
+ # over items: one nested run an item, each with its item under the
121
+ # context key `item_to:`, at most `concurrency:` at once (the
122
+ # configured parallel_concurrency when not given). Each item's outcome
123
+ # is its own: `{ "output" => ... }`, or `{ "refused" => message }` when
124
+ # its run ended on a refused response (OutputRefused), in the items'
125
+ # order; any other failure fails the step. No items is no runs and an
126
+ # empty Array. `output_to:` names the context key the outcomes go to.
127
+ def workflow(klass, over: nil, item_to: nil, concurrency: nil, output_to: nil)
119
128
  raise WorkflowError, "workflow binding must be a Class" unless klass.is_a?(Class)
120
129
  raise WorkflowError, "workflow binding must be a Smith::Workflow subclass" unless klass < Workflow
121
130
 
122
131
  validate_execution_primitive_conflict!("workflow")
132
+ @nested_items = nested_items!(over, item_to, concurrency)
133
+ assign_step_io!(nil, output_to) if output_to
123
134
 
124
135
  @workflow_class = klass
125
136
  commit_execution_primitive!("workflow")
@@ -474,6 +485,20 @@ module Smith
474
485
  normalized.freeze
475
486
  end
476
487
 
488
+ def nested_items!(over, item_to, concurrency)
489
+ return if [over, item_to, concurrency].all?(&:nil?)
490
+ raise WorkflowError, "workflow over: must respond to call" unless over.respond_to?(:call)
491
+ raise WorkflowError, "workflow item_to: must be a Symbol context key" unless item_to.is_a?(Symbol)
492
+
493
+ { over:, item_to:, concurrency: nested_concurrency!(concurrency) }.freeze
494
+ end
495
+
496
+ def nested_concurrency!(concurrency)
497
+ return concurrency if concurrency.nil? || (concurrency.is_a?(Integer) && concurrency.positive?)
498
+
499
+ raise WorkflowError, "workflow concurrency: must be a positive Integer"
500
+ end
501
+
477
502
  def validate_fanout_size!(branches)
478
503
  limit = Smith.config.parallel_branch_limit
479
504
  return if branches.length <= limit
@@ -26,6 +26,8 @@ module Smith
26
26
  # `thinking_tokens` are already inside `output_tokens`. `stop_reason` and
27
27
  # `provider_message_id` come from the provider response, and `mode` is
28
28
  # how the call was made (`:sync`, `:stream`, `:batch`).
29
+ # `image_input_tokens` and `image_output_tokens` are the image parts of
30
+ # `input_tokens` and `output_tokens`.
29
31
  # rubocop:disable Style/RedundantStructKeywordInit
30
32
  UsageEntry = Struct.new(
31
33
  :usage_id,
@@ -48,6 +50,8 @@ module Smith
48
50
  :stop_reason,
49
51
  :provider_message_id,
50
52
  :mode,
53
+ :image_input_tokens,
54
+ :image_output_tokens,
51
55
  keyword_init: true
52
56
  ) do
53
57
  def initialize(**attributes)
@@ -83,6 +87,7 @@ module Smith
83
87
  UsageEntry::OPTIONAL_MEMBERS = %i[
84
88
  transition branch_key round attempt_id workflow
85
89
  cache_read_tokens cache_write_tokens thinking_tokens stop_reason provider_message_id mode
90
+ image_input_tokens image_output_tokens
86
91
  ].freeze
87
92
  # rubocop:enable Style/RedundantStructKeywordInit
88
93
  end
data/lib/smith.rb CHANGED
@@ -206,6 +206,7 @@ require_relative "smith/errors"
206
206
  require_relative "smith/output_failure"
207
207
  require_relative "smith/child_runs_failed"
208
208
  require_relative "smith/providers/stop_reason"
209
+ require_relative "smith/providers/request_outcome"
209
210
  require_relative "smith/providers/output_limit"
210
211
  require_relative "smith/providers/schema_constraints"
211
212
  require_relative "smith/tool_failure_notification_failed"
@@ -351,6 +352,7 @@ require_relative "smith/workflow/artifact_integration"
351
352
  require_relative "smith/workflow/data_volume_policy"
352
353
  require_relative "smith/workflow/deadline_enforcement"
353
354
  require_relative "smith/workflow/nested_execution"
355
+ require_relative "smith/workflow/nested_items_execution"
354
356
  require_relative "smith/workflow/evaluator_optimizer"
355
357
  require_relative "smith/workflow/orchestrator_worker"
356
358
  require_relative "smith/workflow/parallel_execution"
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: smith-agents
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.15.0
4
+ version: 0.16.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Samuel Ralak
@@ -170,6 +170,7 @@ files:
170
170
  - lib/smith/agent/content_parts.rb
171
171
  - lib/smith/agent/dynamic_configuration.rb
172
172
  - lib/smith/agent/fallback_configuration.rb
173
+ - lib/smith/agent/image_request.rb
173
174
  - lib/smith/agent/invocation_preparation.rb
174
175
  - lib/smith/agent/lifecycle.rb
175
176
  - lib/smith/agent/model_reference.rb
@@ -178,12 +179,15 @@ files:
178
179
  - lib/smith/agent/output_integrity.rb
179
180
  - lib/smith/agent/output_policy.rb
180
181
  - lib/smith/agent/output_recovery.rb
182
+ - lib/smith/agent/paint_input.rb
183
+ - lib/smith/agent/painted_answer.rb
181
184
  - lib/smith/agent/prompt_cache.rb
182
185
  - lib/smith/agent/provider_attempt.rb
183
186
  - lib/smith/agent/provider_call_timing.rb
184
187
  - lib/smith/agent/provider_candidate_sequence.rb
185
188
  - lib/smith/agent/provider_completion.rb
186
189
  - lib/smith/agent/provider_failure_handling.rb
190
+ - lib/smith/agent/provider_paint.rb
187
191
  - lib/smith/agent/provider_request.rb
188
192
  - lib/smith/agent/provider_streaming.rb
189
193
  - lib/smith/agent/provider_usage.rb
@@ -299,6 +303,7 @@ files:
299
303
  - lib/smith/persistence_payload_conflict.rb
300
304
  - lib/smith/pricing.rb
301
305
  - lib/smith/pricing/catalog_validation.rb
306
+ - lib/smith/pricing/images.rb
302
307
  - lib/smith/pricing_configuration_error.rb
303
308
  - lib/smith/provider_errors.rb
304
309
  - lib/smith/provider_permanent_failure.rb
@@ -309,6 +314,7 @@ files:
309
314
  - lib/smith/providers/openai/tools_extensions.rb
310
315
  - lib/smith/providers/output_limit.rb
311
316
  - lib/smith/providers/request_holds.rb
317
+ - lib/smith/providers/request_outcome.rb
312
318
  - lib/smith/providers/response_facts.rb
313
319
  - lib/smith/providers/schema_constraint_check.rb
314
320
  - lib/smith/providers/schema_constraints.rb
@@ -522,6 +528,7 @@ files:
522
528
  - lib/smith/workflow/message_roles.rb
523
529
  - lib/smith/workflow/message_value_normalizer.rb
524
530
  - lib/smith/workflow/nested_execution.rb
531
+ - lib/smith/workflow/nested_items_execution.rb
525
532
  - lib/smith/workflow/optimization_state.rb
526
533
  - lib/smith/workflow/optimizer_batch.rb
527
534
  - lib/smith/workflow/orchestration_state.rb