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
@@ -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
@@ -88,11 +88,13 @@ module Smith
88
88
 
89
89
  # A child that handled its failure through its own `on_failure` route
90
90
  # has already applied its failure policy, so the parent sees a
91
- # non-retryable WorkflowError, as before.
91
+ # non-retryable WorkflowError, as before, its cause the child's own
92
+ # error, so a host can still read what the child failed on.
92
93
  failed_step = child_result.steps.find { |s| s.key?(:error) }
93
94
  if failed_step
94
95
  raise WorkflowError,
95
- "nested workflow failed: #{DiagnosticText.capture(failed_step[:error]&.message.to_s, max_bytes: 1024)}"
96
+ "nested workflow failed: #{DiagnosticText.capture(failed_step[:error]&.message.to_s, max_bytes: 1024)}",
97
+ cause: failed_step[:error]
96
98
  end
97
99
 
98
100
  child_result.output
@@ -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
@@ -0,0 +1,161 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+
5
+ module Smith
6
+ class Workflow
7
+ # Batch mode on an optimize step (`optimize ..., mode: :batch`). Each of
8
+ # the loop's calls, a round's generator and then its evaluator, is a
9
+ # batch request of its own, as the evaluator reads what the generator
10
+ # wrote. The call is captured as an agent step's is (BatchExecution), the
11
+ # attempt ends, and the run waits for the result, its pending batch
12
+ # keeping the loop's progress (`progress`: the round, the call it waits for,
13
+ # the candidate, feedback and last score, and the verdicts so far, as
14
+ # JSON gives them). A delivery runs the step again at its attempt, and
15
+ # the loop goes on from that progress: the call it waited for takes its
16
+ # result, and the next call is batched in turn, so each call is made,
17
+ # and charged, once. The step's mode is asked at each call.
18
+ module OptimizerBatch
19
+ ROLES = %w[generator evaluator].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
23
+ RECORD_FIELDS = %w[round source verdict].freeze
24
+ SOURCES = %w[evaluator before_eval].freeze
25
+ ATTEMPT = /\A[1-9]\d*\z/
26
+ CAPTURED = :smith_optimizer_batch
27
+ private_constant :ROLES, :PROGRESS_FIELDS, :UNTOLD_FIELDS, :RECORD_FIELDS, :SOURCES, :ATTEMPT, :CAPTURED
28
+
29
+ private
30
+
31
+ # The step's output, or the call its loop batched, thrown out of the
32
+ # loop for the step to queue.
33
+ def optimizer_batch_output(transition, &)
34
+ return yield unless transition.optimized? && transition.batches?
35
+
36
+ catch(CAPTURED, &)
37
+ end
38
+
39
+ # One of the loop's calls (`role` "generator" or "evaluator"): batched
40
+ # when the step's mode says so and no result of it is being
41
+ # delivered, else made as ever.
42
+ def optimizer_call(transition, state, round, role, input)
43
+ if transition.batches? && !batch_result_due? && batch_mode_for(transition) == :batch
44
+ throw(CAPTURED, batch_optimizer_call(transition, state, round, role, input))
45
+ end
46
+
47
+ agent_class, output_schema = optimizer_agent(state, role)
48
+ invoke_agent_with_budget(agent_class, input, output_schema:)
49
+ end
50
+
51
+ def optimizer_agent(state, role)
52
+ return [state.generator_class, state.generator_class.output_schema] if role == "generator"
53
+
54
+ [state.evaluator_class, state.config[:evaluator_schema]]
55
+ end
56
+
57
+ # The call's request, admitted and held as an agent step's is, under
58
+ # a wait of its own: the round and the call tell its token apart. A
59
+ # stored run whose progress would take it past persistence_max_bytes
60
+ # fails here, before anything is queued.
61
+ def batch_optimizer_call(transition, state, round, role, input)
62
+ agent_class, output_schema = optimizer_agent(state, role)
63
+ progress = optimizer_progress(state, round, role)
64
+ StepCompletion.instance_method(:check_result_storable!).bind_call(self, progress)
65
+ capture = lambda do
66
+ admit_batch_call { reserve_serial_budget(effective_call_ledger, agent_budget: agent_class&.budget) }
67
+ with_agent_context(agent_class) { capture_batch_request(agent_class, input, output_schema:) }
68
+ end
69
+ send_batch(transition, { nil => capture }, position: [round, role], progress:)
70
+ end
71
+
72
+ # What a delivery's loop goes on from, as JSON gives it.
73
+ def optimizer_progress(state, round, role)
74
+ progress = { "round" => round, "role" => role, "candidate" => state.candidate, "feedback" => state.feedback,
75
+ "last_score" => state.last_score, "evaluations" => kept_evaluations, "told" => state.told }
76
+ Batch.deep_freeze(JSON.parse(JSON.generate(progress)))
77
+ rescue JSON::GeneratorError, JSON::NestingError, Encoding::UndefinedConversionError
78
+ raise WorkflowError, "an optimize step waits for a batch only with JSON values for its candidate and feedback"
79
+ end
80
+
81
+ # Every attempt's verdicts so far, by attempt.
82
+ def kept_evaluations
83
+ @pending_evaluations.to_h do |attempt, records|
84
+ [attempt.to_s, records.map { |record| record.merge(source: record[:source].to_s) }]
85
+ end
86
+ end
87
+
88
+ # The round and call the loop goes on from, with its state and
89
+ # verdicts as the pending batch kept them; none unless a result of
90
+ # this step's loop is being delivered.
91
+ def resume_optimizer_progress(state)
92
+ progress = @pending_batch&.fetch("progress", nil) if delivering_batch?
93
+ return unless progress
94
+
95
+ restore_loop_state(state, progress)
96
+ restore_kept_evaluations(progress.fetch("evaluations"))
97
+ state.evaluations = @pending_evaluations.values.last.dup.freeze
98
+ progress.values_at("round", "role")
99
+ end
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
+
106
+ # Kept verdicts back as the loop records them, in attempt order, the
107
+ # attempt under way last.
108
+ def restore_kept_evaluations(kept)
109
+ restored = kept.to_h do |attempt, records|
110
+ [attempt.to_i, records.map { kept_record(_1) }]
111
+ end
112
+ @pending_evaluations = @pending_evaluations.merge(restored).sort.to_h
113
+ end
114
+
115
+ def kept_record(record)
116
+ { round: record.fetch("round"), source: record.fetch("source").to_sym,
117
+ verdict: frozen_verdict(normalize_evaluation(record.fetch("verdict"))) }.freeze
118
+ end
119
+
120
+ # The agent whose call an optimize step's pending batch waited for.
121
+ def optimizer_batch_agent(transition, progress)
122
+ role = progress.fetch("role").to_sym
123
+ resolve_registered_agent!(transition.optimization_config.fetch(role), workflow_class: self.class,
124
+ transition_name: transition.name, role:)
125
+ end
126
+
127
+ # A stored pending batch's `progress` (BatchWait): a call of a
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.
131
+ def optimizer_progress?(transition, progress, attempt)
132
+ progress.is_a?(Hash) && [PROGRESS_FIELDS, UNTOLD_FIELDS].include?(progress.keys.sort) &&
133
+ optimizer_position?(transition, progress) && progress_values?(progress) &&
134
+ kept_evaluations?(progress["evaluations"], attempt)
135
+ end
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
+
142
+ def optimizer_position?(transition, progress)
143
+ round = progress["round"]
144
+ ROLES.include?(progress["role"]) && round.is_a?(Integer) &&
145
+ round.between?(0, transition.optimization_config.fetch(:max_rounds) - 1)
146
+ end
147
+
148
+ def kept_evaluations?(kept, attempt)
149
+ kept.is_a?(Hash) && kept.all? do |key, records|
150
+ key.is_a?(String) && ATTEMPT.match?(key) && key.to_i <= attempt && records.is_a?(Array) &&
151
+ records.all? { kept_record?(_1) }
152
+ end
153
+ end
154
+
155
+ def kept_record?(record)
156
+ record.is_a?(Hash) && record.keys.sort == RECORD_FIELDS && record["round"].is_a?(Integer) &&
157
+ !record["round"].negative? && SOURCES.include?(record["source"]) && record["verdict"].is_a?(Hash)
158
+ end
159
+ end
160
+ end
161
+ end
@@ -74,14 +74,20 @@ module Smith
74
74
  "agent in an isolated session and must declare input:"
75
75
  end
76
76
 
77
- # A non-empty Array of at most MessageBatch::MAX_MESSAGES user and
78
- # assistant messages, bounded and JSON-shaped like session messages.
79
77
  # The callable gets a copy of the context, so it cannot change the
80
78
  # run's.
81
79
  def step_input_messages(transition)
82
- messages = transition.step_input.call(snapshot_value(@context))
80
+ checked_input(transition.step_input.call(snapshot_value(@context)), "input:")
81
+ end
82
+
83
+ # A non-empty Array of at most MessageBatch::MAX_MESSAGES user and
84
+ # assistant messages, bounded and JSON-shaped like session messages, as
85
+ # a step's `input:` or an optimizer's callable `evaluator_context:`
86
+ # (`option`) returns them.
87
+ def checked_input(messages, option)
83
88
  unless messages.is_a?(Array) && !messages.empty? && messages.length <= MessageBatch::MAX_MESSAGES
84
- raise WorkflowError, "input: must return a non-empty Array of at most #{MessageBatch::MAX_MESSAGES} messages"
89
+ raise WorkflowError,
90
+ "#{option} must return a non-empty Array of at most #{MessageBatch::MAX_MESSAGES} messages"
85
91
  end
86
92
 
87
93
  MessageValueNormalizer.new(messages, label: "step input").call.map { |message| step_input_message(message) }
@@ -30,6 +30,15 @@ module Smith
30
30
  @step_stream = nil
31
31
  end
32
32
 
33
+ # Calls the block's agent unheard by the step's sink.
34
+ def unstreamed
35
+ stream = @step_stream
36
+ @step_stream = nil
37
+ yield
38
+ ensure
39
+ @step_stream = stream
40
+ end
41
+
33
42
  def accept_streamed(session, output)
34
43
  return session.finish(output) unless @persistence_key
35
44
 
@@ -125,36 +125,46 @@ module Smith
125
125
  commit_execution_primitive!("workflow")
126
126
  end
127
127
 
128
+ # `mode:` and `on_request_change:` as on `execute`: in batch mode each
129
+ # of the loop's calls is a batch request of its own (OptimizerBatch).
130
+ # `stream:` as on `execute`, for the generator's replies alone, round
131
+ # after round: a round the evaluator or `before_eval` rejects is
132
+ # withdrawn (`reset(:rejected)`), and the evaluator never streams.
133
+ # `before_generate:` runs before each round's generator is asked, so a
134
+ # host can set aside what an earlier round or attempt left.
128
135
  def optimize(generator:, evaluator:, max_rounds:, evaluator_schema:,
129
136
  improvement_threshold: nil,
130
137
  evaluator_context: nil,
138
+ before_generate: nil,
131
139
  before_eval: nil,
132
140
  on_exhaustion: :raise,
133
141
  on_converged: :raise,
134
142
  on_threshold: :raise,
135
143
  input: nil,
136
- output_to: nil)
144
+ output_to: nil,
145
+ mode: nil,
146
+ on_request_change: nil,
147
+ stream: nil)
137
148
  validate_execution_primitive_conflict!("optimize")
138
149
  assign_step_io!(input, output_to)
150
+ assign_batch_mode!(mode, on_request_change, stream: stream_name!(stream, {}, primitive: "optimize"))
139
151
  validate_optimize_controls!(generator, evaluator, max_rounds, evaluator_schema)
140
152
  validate_optimize_exit_modes!(on_exhaustion: on_exhaustion, on_converged: on_converged,
141
153
  on_threshold: on_threshold)
142
154
  validate_optimize_evaluator_context!(evaluator_context)
143
- validate_optimize_before_eval!(before_eval)
155
+ validate_optimize_callbacks!(before_generate:, before_eval:)
144
156
 
145
- config = {
157
+ @optimization_config = {
146
158
  generator: normalize_agent_reference!(generator, "optimizer generator"),
147
159
  evaluator: normalize_agent_reference!(evaluator, "optimizer evaluator"),
148
160
  max_rounds: max_rounds,
149
161
  evaluator_schema: evaluator_schema, improvement_threshold: improvement_threshold,
150
162
  evaluator_context: evaluator_context,
151
- before_eval: before_eval,
163
+ before_generate: before_generate, before_eval: before_eval,
152
164
  on_exhaustion: on_exhaustion,
153
165
  on_converged: on_converged,
154
166
  on_threshold: on_threshold
155
167
  }.freeze
156
-
157
- @optimization_config = config
158
168
  commit_execution_primitive!("optimize")
159
169
  end
160
170
 
@@ -174,8 +184,7 @@ module Smith
174
184
  def fan_out(branches:, input: nil, output_to: nil, mode: nil, on_request_change: nil)
175
185
  validate_execution_primitive_conflict!("fan_out")
176
186
  assign_step_io!(input, output_to)
177
- @batch_mode = batch_mode!(mode, stream: nil, parallel: false)
178
- @on_request_change = request_change!(on_request_change)
187
+ assign_batch_mode!(mode, on_request_change)
179
188
 
180
189
  normalized = normalize_fanout_branches!(branches)
181
190
  @fanout_branch_lookup = normalized.to_h do |key, agent|
@@ -323,6 +332,15 @@ module Smith
323
332
  mode
324
333
  end
325
334
 
335
+ # `mode:` and `on_request_change:` of a step that has no parallel copies
336
+ # (`fan_out`, `optimize`), and the sink it streams to (`optimize`'s,
337
+ # named through stream_name!).
338
+ def assign_batch_mode!(mode, on_request_change, stream: nil)
339
+ @stream = stream
340
+ @batch_mode = batch_mode!(mode, stream:, parallel: false)
341
+ @on_request_change = request_change!(on_request_change)
342
+ end
343
+
326
344
  # What a batch result does when the step renders another request by
327
345
  # the time it comes: :keep it (the default), :resend the request over
328
346
  # the wire, or :fail the step with BatchRequestChanged.
@@ -337,10 +355,10 @@ module Smith
337
355
  end
338
356
 
339
357
  # One reply streams to one sink: a parallel step has several.
340
- def stream_name!(stream, opts)
358
+ def stream_name!(stream, opts, primitive: "execute")
341
359
  return if stream.nil?
342
- raise WorkflowError, "execute stream: must name a sink with a Symbol" unless stream.is_a?(Symbol)
343
- raise WorkflowError, "execute stream: is not available on a parallel step" if opts[:parallel] == true
360
+ raise WorkflowError, "#{primitive} stream: must name a sink with a Symbol" unless stream.is_a?(Symbol)
361
+ raise WorkflowError, "#{primitive} stream: is not available on a parallel step" if opts[:parallel] == true
344
362
 
345
363
  stream
346
364
  end
@@ -696,17 +714,18 @@ module Smith
696
714
  end
697
715
 
698
716
  def validate_optimize_evaluator_context!(evaluator_context)
699
- return if evaluator_context.nil? || evaluator_context == :inject_state
717
+ return if evaluator_context.nil? || evaluator_context == :inject_state || evaluator_context.respond_to?(:call)
700
718
 
701
719
  raise WorkflowError,
702
- "optimize evaluator_context must be nil or :inject_state; got #{evaluator_context.inspect}"
720
+ "optimize evaluator_context must be nil, :inject_state or a callable; got #{evaluator_context.inspect}"
703
721
  end
704
722
 
705
- def validate_optimize_before_eval!(before_eval)
706
- return if before_eval.nil?
707
- return if before_eval.respond_to?(:call)
723
+ def validate_optimize_callbacks!(**callbacks)
724
+ callbacks.each do |name, callback|
725
+ next if callback.nil? || callback.respond_to?(:call)
708
726
 
709
- raise WorkflowError, "optimize before_eval must respond to :call; got #{before_eval.inspect}"
727
+ raise WorkflowError, "optimize #{name} must respond to :call; got #{callback.inspect}"
728
+ end
710
729
  end
711
730
  end
712
731
  end
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.13.1
4
+ version: 0.15.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Samuel Ralak
@@ -178,6 +178,7 @@ files:
178
178
  - lib/smith/agent/output_integrity.rb
179
179
  - lib/smith/agent/output_policy.rb
180
180
  - lib/smith/agent/output_recovery.rb
181
+ - lib/smith/agent/prompt_cache.rb
181
182
  - lib/smith/agent/provider_attempt.rb
182
183
  - lib/smith/agent/provider_call_timing.rb
183
184
  - lib/smith/agent/provider_candidate_sequence.rb
@@ -522,6 +523,7 @@ files:
522
523
  - lib/smith/workflow/message_value_normalizer.rb
523
524
  - lib/smith/workflow/nested_execution.rb
524
525
  - lib/smith/workflow/optimization_state.rb
526
+ - lib/smith/workflow/optimizer_batch.rb
525
527
  - lib/smith/workflow/orchestration_state.rb
526
528
  - lib/smith/workflow/orchestrator_worker.rb
527
529
  - lib/smith/workflow/parallel.rb