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
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 7c3bc332fe08b2ff077b3039603ddc8356ac65d5034f47abcf4253c3e167f8c6
4
- data.tar.gz: 9eaf0e8548b473da25838206b63e2a5639d7ee4391f7cb6e30980a5b5aa46e67
3
+ metadata.gz: 4e68bbf1f174434fef943c8ed78133e5536eb836b0cc04e11d338401f5cf14cf
4
+ data.tar.gz: 5daed55ca366c3eacd5728d720218f2af1464077d7584d0b77aef3e65b681986
5
5
  SHA512:
6
- metadata.gz: 1ff7f020acb2efd11f7143a074d3c65093137be5bc2646e10a668e1e5242b37255db15909f0c99aa3b6073ad73e31a2557f61fa3d2a35d2de716ba122d7deb4e
7
- data.tar.gz: fab4fd19cd33c21b6800a8d75740bc62533aa4100a2d9ae5e26bad31ad5a1fa57b4869cce9efc9a351b41366ee5ee5a8cb24c0d21dc8369effdbe5b8fd8e703c
6
+ metadata.gz: aee4c70c34cc92db641757b7785b806e2ebfccc314a199f9c9c0ad23c243fa22efaddd53a6d012f02140fca7b8705555a3169e4493049923f1889e84a9ff3a1e
7
+ data.tar.gz: ba3d4f427da7b0fd7e95c66fdff91250aed9e815c7213f9a8919ed4bc922b96caa3abd12be23e6ae1bccdbca702ce6190f4b00cfda2f1478d730a0bef3704d01
data/CHANGELOG.md CHANGED
@@ -4,6 +4,142 @@ All notable changes to Smith are documented in this file.
4
4
 
5
5
  Format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). Versioning follows [Semantic Versioning](https://semver.org/spec/v2.0.0.html). Smith is pre-1.0 and under active development; expect occasional contract tightening between minor versions until 1.0.
6
6
 
7
+ ## [0.15.0] - 2026-11-22
8
+
9
+ ### Added
10
+
11
+ - `prompt_cache :automatic` on an agent asks Anthropic to cache each
12
+ request's longest prefix (a top-level `cache_control`, the breakpoint moving
13
+ with the request's last block), so a tool loop reads each request's prefix
14
+ from the cache rather than sending it again at full price. It counts as one
15
+ of a request's four breakpoints, as a top-level marker a chat's params
16
+ already carry does; other providers and a batch request are asked nothing;
17
+ the hold already prices a request-level marker at the cache-write rate.
18
+ Too many breakpoints now read "N cache breakpoints are asked for" (", an
19
+ automatic prompt cache counting one" where it does).
20
+ - `optimize ..., before_generate: ->(state, context)` runs before each round's
21
+ generator is asked, the first round of every attempt included. Whatever this
22
+ step's rounds and attempts did before it belongs to a round the loop
23
+ rejected or an attempt that failed, so a host whose generator's tools stage
24
+ work for the candidate (a pending write it publishes once the step is
25
+ accepted) sets it aside before the next round builds on it. `before_generate`,
26
+ `before_eval` and the exit modes read the round under way from
27
+ `state.round`, and each tool capture an optimize round takes names it
28
+ (`round` on its `tool_results` entry), so a host tells the accepted round's
29
+ captures from those of the rounds its step rejected. It returns
30
+ `{ rejected_round: String }` to say what the rejected round's tools left,
31
+ since a candidate does not carry its tools' work: a later round's generator
32
+ is told it after the evaluator's feedback (`[smith:rejected-round]`), copied
33
+ and bounded as a message's words are and kept with a batch wait, so the
34
+ generator revises the candidate. Round 0, blank words and any other return
35
+ value tell it nothing; a `rejected_round` that is not a String fails the step.
36
+ - An `optimize` step streams: `optimize ..., stream: :name` sends its
37
+ generator's replies to the sink, round after round, as `execute` does. The
38
+ evaluator never streams, since its reply is a verdict, and a rejected
39
+ round's text is withdrawn with `reset(:rejected)` as the generator writes
40
+ again; the last round ends as any streamed step does, with `finish` (the
41
+ output kept, `:return_last` included) or `fail`. Runtime readiness checks
42
+ the generator's route. A streamed `optimize` step cannot batch.
43
+ - A nested workflow's failure keeps the child's own error as the parent's
44
+ error's `cause`, so a host can read what the child failed on (a
45
+ `DeterministicStepFailure`'s details, for one) beyond the parent error's
46
+ message.
47
+ - `optimize ..., evaluator_context:` takes a callable, which builds the
48
+ evaluator's messages from copies of the candidate and the context, checked
49
+ as an `input:` callable's are. An evaluator can then read only its own part
50
+ of the context, and one whose round-by-round material sits in its last
51
+ message keeps the same prefix across rounds, which a provider's prompt
52
+ cache can reuse; under `:inject_state` it re-read the generator's whole
53
+ input every round.
54
+
55
+ ### Fixed
56
+
57
+ - An agent's output cap (`params max_tokens:`) reaches an OpenAI model that
58
+ reasons as `max_completion_tokens` (or `max_output_tokens` on the Responses
59
+ API) on every attempt, not only a retry: OpenAI's Chat Completions refuses
60
+ `max_tokens` from those models, so a step without tools on one failed its
61
+ first call. Any other OpenAI chat, an OpenAI-compatible server's among them,
62
+ keeps its own `max_tokens`.
63
+
64
+ - An agent step in a workflow whose budget declares `wall_clock` gets its
65
+ output repair, its truncation retry and its refusal fallback again. The
66
+ step's reservation names every budget dimension, `wall_clock` among them
67
+ at 0, and the check that stops follow-up calls once a call has spent its
68
+ reservation compared the tokens spent against that 0, so any response
69
+ counted as spent and no follow-up was made. The check now weighs only
70
+ tokens and cost; the deadline is still checked before a follow-up.
71
+ - A request's budget hold covers input written to a prompt cache. The hold
72
+ priced its estimated input at the plain input rate, so a prompt marked for
73
+ caching, whose writes cost more (1.25x on Anthropic's five-minute cache),
74
+ could spend past what was held for it. A request that marks a block for
75
+ the cache (`cache_control` on the request or on a message's block) is now
76
+ held with its input at the dearer of plain input and a cache write; any
77
+ other request, and a model with no cache-write rate, is held as before.
78
+
79
+ ### Upgrading
80
+
81
+ - A workflow whose budget declares `wall_clock` makes again the output
82
+ repairs, truncation retries and refusal fallbacks it had skipped, so its
83
+ steps may spend more of the budget than under 0.14.0.
84
+ - A request marked for the prompt cache is held at the dearer of plain input
85
+ and a cache write, so a budget close to its limit refuses such a request
86
+ sooner.
87
+ - `Smith::EXECUTION_SEMANTICS_VERSION` stays `"7"`: an optimize step's
88
+ stored batch wait may now carry the words `before_generate` told its round
89
+ (`told`), and a run stored by 0.14.0, which carries none, restores as it is.
90
+
91
+ ## [0.14.0] - 2026-11-09
92
+
93
+ ### Added
94
+
95
+ - `optimize` takes `mode:` (`:sync`, `:batch`, or a callable of the context
96
+ and attempt) and `on_request_change:`, as `execute` and `fan_out` do. In
97
+ batch mode each call of the loop, a round's generator and then its
98
+ evaluator, is a batch request of its own, queued under a wait of its own,
99
+ and the run waits for its result without holding a worker; the pending
100
+ batch keeps the loop's `progress` (the round, the call it waits for, the
101
+ candidate, feedback and last score, and the verdicts so far, as JSON gives
102
+ them). A delivery runs the step again at its attempt and the loop goes on
103
+ from that progress: the call it waited for takes its result, nothing
104
+ before it runs again, and the next call is batched in turn, so each call is
105
+ made, charged and held on a budget ledger once. The mode callable is asked
106
+ at each call. A failed or missing result fails its call, and `retry_on`
107
+ runs the step again with its loop afresh, as any retry of an optimize step
108
+ does, making and paying for the earlier rounds' calls again. Progress that
109
+ is not JSON, or that would take a stored run past `persistence_max_bytes`,
110
+ fails the step before anything is queued. Restore checks the progress (its
111
+ round, call, last score and kept verdicts) and that it is the progress of
112
+ the call the run's wait was made for, and refuses any other with
113
+ `Smith::SerializationError`; lowering `max_rounds` or dropping batch mode
114
+ therefore strands runs waiting under the old setting. Runtime readiness
115
+ checks the generator and the evaluator for a batch interface.
116
+
117
+ ### Changed
118
+
119
+ - A batch wait's results settle their holds on a host's budget ledger before
120
+ the step runs again, so the request the step holds next (a retry's, or an
121
+ optimize step's next call) never overlaps them; a ledger with room for
122
+ one hold no longer refuses that request. Restore refuses a pending batch
123
+ whose attempt is not the one its wait's token was made for
124
+ (`Smith::SerializationError`); a run stored by Smith 0.13 restores as it
125
+ is.
126
+
127
+ ### Upgrading
128
+
129
+ - Restore checks that a stored batch wait's pending batch is the one its
130
+ token was made for (its attempt, and an optimize step's round and call).
131
+ Runs stored by Smith 0.13 pass; a pending batch edited by hand, or moved
132
+ to another attempt, is refused with `Smith::SerializationError`.
133
+ - A host ledger now sees a delivered result's hold settled before the
134
+ step's next hold is taken; a ledger that counted both at once no longer
135
+ needs room for them together.
136
+ - While runs wait on an optimize step's batch, keep its `max_rounds` and its
137
+ batch mode as they were: restore refuses progress the step could not go
138
+ on from, so lowering one or dropping the other strands those runs until
139
+ their waits have drained.
140
+ - `Smith::EXECUTION_SEMANTICS_VERSION` stays `"7"`: a workflow that does not
141
+ declare batch mode on an optimize step runs and stores as before.
142
+
7
143
  ## [0.13.1] - 2026-11-08
8
144
 
9
145
  ### Changed
data/README.md CHANGED
@@ -30,7 +30,7 @@ What you get:
30
30
 
31
31
  ```ruby
32
32
  # Gemfile
33
- gem "smith-agents", "0.13.1", require: "smith"
33
+ gem "smith-agents", "0.15.0", require: "smith"
34
34
  ```
35
35
 
36
36
  In a Rails app:
@@ -87,7 +87,7 @@ run's context for later steps.
87
87
  | Ruby | `compute { \|step\| ... }` | Runs your code; reads and writes the context |
88
88
  | Route | `route :classifier, routes: {...}` | Picks the next transition from an agent's answer |
89
89
  | Fan-out | `execute :agent, parallel: true`, `fan_out branches: {...}` | Calls agents concurrently |
90
- | Refine | `optimize generator:, evaluator:` | Drafts and critiques in bounded rounds |
90
+ | Refine | `optimize generator:, evaluator:` | Drafts and critiques in bounded rounds; `stream:` streams the drafts |
91
91
  | Delegate | `orchestrate orchestrator:, worker:` | Plans tasks and hands them to workers |
92
92
  | Nest | `workflow OtherWorkflow` | Runs another workflow as one step |
93
93
  | Wait | `await :event, into:, timeout:`, `delay seconds` | Waits for an event your app delivers, or for a time |
@@ -204,9 +204,12 @@ anything is sent, and a step can wait for budget instead.
204
204
 
205
205
  `execute :writer, stream: :answer` sends the reply's text to a sink you
206
206
  register as the model writes it. Treat it as a draft: Smith checks the reply
207
- only once it is complete. `execute :triager, mode: :batch` sends the request
208
- through Anthropic's batch API at half price; the run waits, and your app
209
- delivers the result when the batch ends.
207
+ only once it is complete. An `optimize` step streams its generator's drafts the
208
+ same way, a draft its evaluator or `before_eval` rejects withdrawn as the next
209
+ begins. `execute :triager, mode: :batch` sends the request through Anthropic's
210
+ batch API at half price; the run waits, and your app
211
+ delivers the result when the batch ends. `fan_out` and `optimize` take the same
212
+ `mode:`; an `optimize` step batches each call of its loop in turn.
210
213
  [`docs/AGENTS.md`](docs/AGENTS.md)
211
214
 
212
215
  ## Untrusted content
data/docs/AGENTS.md CHANGED
@@ -84,6 +84,7 @@ Smith ships a per-attempt normalizer that translates the request payload to what
84
84
  - Anthropic 4.0–4.6 budget_tokens
85
85
  - OpenAI gpt-5 family reasoning_effort with `/v1/responses` routing when tools + thinking are combined
86
86
  - Gemini 2.5+ budget_tokens
87
+ - Anthropic's automatic prompt cache (a top-level `cache_control`) for an agent declaring `prompt_cache :automatic`, on a call over the wire alone, counted among the request's four cache breakpoints
87
88
 
88
89
  Override the inferred profile per-app via `Smith::Models.register(Profile.new(...))`.
89
90
  Profiles are keyed by both provider and model id. Pass `provider:` to
@@ -139,11 +140,17 @@ class Answer < Smith::Workflow
139
140
  end
140
141
  ```
141
142
 
143
+ An `optimize` step takes `stream:` too: its generator's replies stream round
144
+ after round, its evaluator's never (a verdict is not the step's words), and a
145
+ round the evaluator or `before_eval` rejects is withdrawn as the generator
146
+ writes again; the last round ends with `finish` or `fail` alone.
147
+
142
148
  A sink defines any of `start(info)` (each provider call: the step's info with
143
149
  the attempt, model and provider), `delta(text)` (each text chunk; tool calls,
144
150
  thinking and `<think>` text are not sent), `reset(reason)` (Smith discarded the
145
- text sent so far: `:retry`, `:fallback`, `:truncation` or `:repair`; and
146
- `:retry_wait`, the last word, while a durable retry waits), `finish(output)`
151
+ text sent so far: `:retry`, `:fallback`, `:truncation` or `:repair`;
152
+ `:rejected`, an `optimize` step's round its evaluator or `before_eval` refused;
153
+ and `:retry_wait`, the last word, while a durable retry waits), `finish(output)`
147
154
  (the output the step accepted, after guardrails, the output contract and
148
155
  `output_to:`, once the step is stored) and `fail(error_class)`. Streamed text is
149
156
  a draft: guardrails and output checks run on the whole reply, so nothing should
@@ -219,7 +226,7 @@ end
219
226
  ```
220
227
 
221
228
  `mode:` is `:sync` (the default), `:batch`, or a callable of the context and
222
- the step attempt returning one, on `execute` and `fan_out`; a batch step
229
+ the step attempt returning one, on `execute`, `fan_out` and `optimize`; a batch step
223
230
  declares `on_failure`, and cannot stream or be `parallel:`. Smith prepares
224
231
  the call as a synchronous one, admits it against the budget, and hands the
225
232
  exact request (the provider payload and the call's own headers, never the
@@ -253,3 +260,35 @@ built in, and a batch request is one turn, so a batching agent has no tools;
253
260
  runtime readiness reports a missing queue (`:batch_queue_missing`) and an
254
261
  agent that cannot batch (`:batch_unavailable`), and graph inspection shows the
255
262
  mode.
263
+
264
+ An `optimize` step in batch mode sends each call of its loop as a batch
265
+ request of its own, a round's generator and then its evaluator, since the
266
+ evaluator reads what the generator wrote: a round is two waits. Each call is
267
+ queued under a wait of its own (its round and call tell the token apart), and
268
+ the run's pending batch keeps the loop's progress (`progress`): the round, the
269
+ call it waits for, the candidate, the feedback and last score, what
270
+ `before_generate` told the round (`rejected_round`), and the verdicts so far,
271
+ as JSON gives them. A candidate or feedback that is not JSON
272
+ fails the step before anything is queued, as does progress that would take a
273
+ stored run past `persistence_max_bytes` (`Smith::PersistedStateTooLarge`). A
274
+ delivery settles its result's hold, then runs the step again at its attempt,
275
+ and the loop goes on from that progress: the call it waited for takes its
276
+ result, nothing before it runs again (`before_generate` and `before_eval`
277
+ included), and the next call is batched in turn, so each call is made, charged
278
+ and held on a budget ledger once. The mode callable is asked at each call; a
279
+ call it gives `:sync` goes over the wire and the loop goes on.
280
+
281
+ A failed or missing result fails its call as on any batch step, and
282
+ `retry_on` (in process, as an optimize step takes no durable retry) runs the
283
+ step again: as on any retry of an optimize step, the loop starts afresh, so
284
+ the new attempt makes, and pays for, the earlier rounds' calls again, under
285
+ the mode the callable gives it (`attempt == 1 ? :batch : :sync` sends the
286
+ whole loop over the wire). A delivery that crashes leaves the stored wait as
287
+ it was: in lax mode the host delivers the results again and the loop goes on
288
+ as it would have; in strict mode the delivery was stored as a step under way,
289
+ so the run raises `Smith::StepInProgressOnRestore`, as any batch step's does,
290
+ and the host decides. Restore refuses progress the step could not go on from
291
+ (a round past `max_rounds`, or a call the run's wait was not made for) with
292
+ `Smith::SerializationError`, so lowering `max_rounds`, or dropping batch mode,
293
+ strands the runs waiting under the old setting: keep both until those waits
294
+ have drained.
data/docs/BUDGETS.md CHANGED
@@ -113,7 +113,10 @@ Images and documents count so as RubyLLM attachments and in raw content blocks
113
113
  set, caps the output part (an agent with no `max_tokens` is otherwise held for
114
114
  the model's maximum, which can be tens of thousands of tokens, and a longer
115
115
  reply is reconciled at what it cost). It is priced from the pricing catalog
116
- under the id RubyLLM resolves the model to; `cost` is nil for an unpriced
116
+ under the id RubyLLM resolves the model to, a request that marks a block for a
117
+ prompt cache (`cache_control` on the request or on a message's block) with its
118
+ input at the dearer of plain input and a cache write, since all of it may be
119
+ written; `cost` is nil for an unpriced
117
120
  model, which runtime readiness warns of (`:budget_ledger_unpriced`, for every
118
121
  agent that charges the ledger), and its readiness metrics name the scope keys.
119
122
 
@@ -26,6 +26,7 @@ Use agent classes for invocation behavior:
26
26
  - `output_schema`
27
27
  - `output_contract`, `output_repairs`
28
28
  - `on_truncation`, `on_refusal`
29
+ - `prompt_cache` (`:none` or `:automatic`, Anthropic's automatic prompt cache for an agent with a tool loop)
29
30
  - `data_volume`
30
31
  - `fallback_models`
31
32
  - `register_as`
@@ -108,7 +109,7 @@ Smith.configure do |config|
108
109
  }
109
110
  )
110
111
 
111
- # Streamed steps (`execute Agent, stream: :answer`): a callable that takes the
112
+ # Streamed steps (`execute Agent, stream: :answer`, and `optimize`'s): a callable that takes the
112
113
  # step's info and returns its sink, or nil to stream nothing.
113
114
  config.stream_sinks = { answer: ->(info) { AnswerStream.new(info[:execution_key]) } }
114
115
 
@@ -198,7 +199,7 @@ from JSON or YAML has.
198
199
  | `interrupting_errors` | Subclasses of StandardError that interrupt a step instead of failing it, such as the host's database or queue out of reach: met in a step (or as the cause of an error that was, never through a provider's own failure), they take no route, no retry and no failure record, reach the caller as raised, and leave the run as the step left it. Smith does not count them ([ERRORS_AND_RETRIES.md](ERRORS_AND_RETRIES.md), Interrupting errors). None by default | Name the errors that mean your own systems failed, never ones a step can cause every time (a query timeout) |
199
200
  | `budget_hold_ttl` | Seconds a provider request's hold on a workflow's `budget_ledger` lasts unsettled (default 3600): each hold's `expires_at` is this from now, and a batch request's is its 25-hour wait longer. Past it the request's process is taken to have died | Raise it above the longest request (its retries and stream included) |
200
201
  | `budget_hold_output_tokens` | The most output tokens a request's hold on a workflow's `budget_ledger` counts (default nil: the request's own `max_tokens`, else the model's maximum). Only the hold changes, not the request; a longer reply is reconciled at what it cost | Set it when agents leave `max_tokens` unset and a small budget would refuse calls on their huge holds |
201
- | `stream_sinks` | The sinks `execute Agent, stream: :name` steps send text to, by name: callables that take a step's info (`stream`, `execution_key`, `transition`) and return that step's sink, or nil to stream nothing | Register each name a workflow streams to; readiness reports a missing one |
202
+ | `stream_sinks` | The sinks `execute Agent, stream: :name` and `optimize ..., stream: :name` steps send text to, by name: callables that take a step's info (`stream`, `execution_key`, `transition`) and return that step's sink, or nil to stream nothing | Register each name a workflow streams to; readiness reports a missing one |
202
203
  | `persistence_adapter` | Adapter for durable workflow state | `:redis`, `:rails_cache`, `:active_record`, `:memory`, or a custom object |
203
204
  | `persistence_options` | Per-adapter options (client, namespace, model, columns) | See "Built-In Persistence Adapters" |
204
205
  | `persistence_ttl` | Global TTL for persisted state (Integer/Float seconds; nil = no expiry). `:active_record` cannot expire state, so its writes refuse a non-nil TTL (reads and deletes still work, and `smith doctor --durability` flags the combination) | Set when long-tail abandoned workflows accumulate in storage |
data/docs/PATTERNS.md CHANGED
@@ -389,6 +389,14 @@ class TranslationWorkflow < Smith::Workflow
389
389
  end
390
390
  ```
391
391
 
392
+ What the evaluator reads is `evaluator_context:`'s to say. Left out, it reads
393
+ the candidate alone; `:inject_state` gives it the generator's input followed by
394
+ the candidate; a callable `->(candidate, context) { messages }` builds its
395
+ messages itself from copies of the candidate and the context, checked as an
396
+ `input:` callable's are, so an evaluator reads only its own part of the context
397
+ and, with what changes each round in its last message, keeps the same prefix
398
+ from round to round for a provider's prompt cache.
399
+
392
400
  `before_eval: ->(state, context) { ... }` runs after each candidate is
393
401
  generated and before the evaluator is called, and may write to the workflow
394
402
  context (a new top-level key must be a Symbol that the context's `persist` list
@@ -403,6 +411,41 @@ value, including a Hash with `accept: true`, is ignored and the evaluator
403
411
  judges as before. A deterministic check that makes a candidate unacceptable
404
412
  can reject it this way without spending an evaluator call.
405
413
 
414
+ `before_generate: ->(state, context) { ... }` runs before each round's
415
+ generator is asked, the first round of every attempt included (a round a batch
416
+ delivery goes on from asked it when its request was batched), and may write to
417
+ the workflow context as `before_eval` may. Whatever this step's earlier rounds
418
+ and attempts did belongs to a round the loop rejected or an attempt that
419
+ failed, so a host whose generator's tools stage work for the candidate (a
420
+ pending write, for the host to publish once the step is accepted) sets aside
421
+ what they staged before the next round builds on it. The generator of a later
422
+ round is given the rejected candidate and the evaluator's feedback, not its
423
+ tool calls, so it should be told that a candidate sent back keeps nothing its
424
+ tools did. It returns `{ rejected_round: String }` to say what the rejected
425
+ round's tools left: a later round's generator is told it after the evaluator's
426
+ feedback (`[smith:rejected-round]`), copied and bounded as a message's words
427
+ are, so it revises the candidate rather than starts again; the words are kept
428
+ with a batch wait, so a delivered round is the request sent. A round 0, blank
429
+ words or any other return value tells the generator nothing more, and a
430
+ `rejected_round` that is not a String fails the step. A provider attempt the
431
+ call sets aside inside one round (a fallback model, a repair) is not a round:
432
+ its captures leave `tool_results` as before, and `before_generate` does not run
433
+ between it and the attempt that replaces it. A raise fails the step as a raise
434
+ from `before_eval` does. `before_generate`, `before_eval` and the exit modes read
435
+ the round under way from `state.round`, from 0 in each attempt, and every tool
436
+ capture a round takes names it (`round` on its `tool_results` entry), so a host
437
+ tells the accepted round's captures from those of the rounds its step
438
+ rejected. The round is the step's own: captures of two optimize steps in one
439
+ run, or of a transition that runs again, are told apart by the host, by the
440
+ tools it gives each step.
441
+
442
+ `mode: :batch` (or a callable of the context and attempt) sends each call of
443
+ the loop through the provider's batch API, the run waiting for each result
444
+ and going on from where the loop stood: docs/AGENTS.md, Batch mode.
445
+ `stream: :name` instead sends the generator's drafts to a sink as they are
446
+ written, a rejected draft withdrawn as the next begins: docs/AGENTS.md,
447
+ Streaming.
448
+
406
449
  Every round's verdict is an output. Once its loop has run, the step's record
407
450
  carries its verdicts under `:evaluations`, in attempt and round order, whether
408
451
  the step completed or failed (a step that failed before its loop, or any other
@@ -441,13 +484,13 @@ loop is kept, whether it accepts, converges, or trips the improvement
441
484
  threshold. A step whose completion fails after its loop (a split step's
442
485
  snapshot over its limits) keeps its verdicts on the failure record. A nested
443
486
  workflow's verdicts stay on its own run: the parent's step carries the child's
444
- usage, not its verdicts. A callable
445
- (`before_eval` or an exit mode) reads its own loop's verdicts so far from
446
- `state.evaluations`, a frozen copy without `attempt`, so it cannot rewrite the
447
- step's. Verdicts are content, so they are an output and never a
448
- trace: nothing about them reaches a trace adapter. Like `steps`, they belong to
449
- the run that executed the step, so a terminal restore has none; a host that
450
- needs them later stores them when the run returns.
487
+ usage, not its verdicts. A callable (`before_generate`, `before_eval` or an
488
+ exit mode) reads its own loop's verdicts so far from `state.evaluations`, a
489
+ frozen copy without `attempt`, so it cannot rewrite the step's. Verdicts are
490
+ content, so they are an output and never a trace: nothing about them reaches a
491
+ trace adapter. Like `steps`, they belong to the run that executed the step, so
492
+ a terminal restore has none; a host that needs them later stores them when the
493
+ run returns.
451
494
 
452
495
  Why this matters:
453
496
 
@@ -646,7 +689,7 @@ The yielded step object exposes a narrow, read-heavy surface:
646
689
  - **Idempotency keys**: `step.idempotency_key(scope = nil)` is a key for a request the step sends outside the system, the same on every attempt of the step and after a restore, unique to the run, the step and the scope. `step.attempt` is the attempt under way, from 1. See `docs/PERSISTENCE.md`, Replay Safety.
647
690
  - **Outcome**: `step.write_outcome(kind:, payload:)` stores a workflow-owned terminal payload without smuggling it through context. The payload is persisted with the workflow and surfaced on `RunResult.outcome`, `RunResult.outcome_kind`, and `RunResult.outcome_payload`.
648
691
  - **Context writes**: `step.write_context(key, value)` takes a Symbol key. The value is stored at the call in the context's key shape: every Hash key at every depth becomes the Symbol of its String form, which is what a restore produces, so `step.read_context` later in the same step, the next step, and a restored run all read the same keys. Values are not converted (see `docs/PERSISTENCE.md`). Two keys that become the same Symbol, a value that contains itself, or nesting deeper than 100 levels fail the write with `Smith::WorkflowError`.
649
- - **Persist list as an allow-list**: when the workflow's `Smith::Context` declares `persist :a, :b`, writing any other key raises `Smith::UndeclaredContextKey`, in every run, persisted or not and nested or not, so the list is the context's declared shape rather than a filter applied at checkpoints. A rejected write fails the step even when the step body rescues the error. With `persist :auto`, or no `persist` declaration, any Symbol key may be written. Hooks that receive the live context (`before_eval`, `after_completion`, guardrails) are held to the same rules at the end of their step: a new top-level key must be a Symbol the list allows, a violation fails the step and puts the context's top-level values back as they were when the step started, and new or replaced values take the context's key shape.
692
+ - **Persist list as an allow-list**: when the workflow's `Smith::Context` declares `persist :a, :b`, writing any other key raises `Smith::UndeclaredContextKey`, in every run, persisted or not and nested or not, so the list is the context's declared shape rather than a filter applied at checkpoints. A rejected write fails the step even when the step body rescues the error. With `persist :auto`, or no `persist` declaration, any Symbol key may be written. Hooks that receive the live context (`before_generate`, `before_eval`, `after_completion`, guardrails) are held to the same rules at the end of their step: a new top-level key must be a Symbol the list allows, a violation fails the step and puts the context's top-level values back as they were when the step started, and new or replaced values take the context's key shape.
650
693
  - **Context reads**: `step.context` returns an isolated snapshot of the workflow context at step start. Mutating that snapshot does not mutate workflow state. `step.read_context(key)` returns a merged view — pending `write_context` values override the snapshot. Use `read_context` when you need read-after-write coherence within the same step.
651
694
  - **No output**: Deterministic steps produce no session message output. `last_output` continues to mean the last agent output.
652
695
  - **No budget**: No tokens or cost consumed.
data/docs/PERSISTENCE.md CHANGED
@@ -677,7 +677,12 @@ end
677
677
  transcript, as it does for the transcript. A fan-out's branches share one
678
678
  `input:`. An optimizer's `input:` is its generator's, and also its
679
679
  evaluator's under `evaluator_context: :inject_state`, which then sees the
680
- input followed by the candidate and no injected state.
680
+ input followed by the candidate and no injected state. A callable
681
+ `evaluator_context:` builds the evaluator's messages itself instead: it gets
682
+ copies of the candidate and the context and returns messages checked as an
683
+ `input:` callable's are, so the evaluator can read only its own part of the
684
+ context and keep the same prefix from round to round (for a provider's
685
+ prompt cache).
681
686
  - `output_to: :key` writes the step's output to `key` instead of the
682
687
  transcript, once the step completes. The value is JSON-shaped (Symbols
683
688
  become Strings) and in the context's key shape, so it reads the same after a
@@ -787,7 +792,15 @@ Smith::Message.system([Smith::Content.text(house_style, cache: true)]) # in
787
792
  request: Smith counts the chat's own (cached instructions) with its parts,
788
793
  against every Anthropic model in the step's chain, and refuses more before
789
794
  the first call. Concurrent branches (`parallel:`, `fan_out`) each write the
790
- cache.
795
+ cache. An agent whose tool loop sends a growing conversation again declares
796
+ `prompt_cache :automatic`: each Anthropic request then carries a top-level
797
+ `cache_control`, Anthropic placing the breakpoint on the request's last
798
+ block and moving it forward as the loop grows, so each request reads the
799
+ one before it from the cache. It counts as one of the four breakpoints, as
800
+ a top-level marker the chat's params already carry does; other providers
801
+ and a batch request (one turn read once) are asked nothing. An agent whose
802
+ request ends in words read once (a judge's single call) pays the write
803
+ premium for nothing, so it is for agents with a tool loop.
791
804
  - **Other providers** get the parts as one text in their order: text parts as
792
805
  they are, a `text/plain` document inline (`<file name='document-2.txt'
793
806
  mime_type='text/plain'>...</file>`), and `[attached: image-3.png]` where each
@@ -1187,11 +1200,12 @@ end
1187
1200
  - A key is unique to the run, the step's position and the scope. The position
1188
1201
  is the step number and transition, then any nested workflow step, parallel or
1189
1202
  fan-out branch (durable composite branches included), optimizer round and
1190
- role (generator, `before_eval`, evaluator), or orchestrator round and worker
1191
- task. A worker task is named by its content and which copy of equal tasks it
1192
- is, so a replayed orchestrator that lists the same tasks in another order
1193
- keeps each task's key. A transition that runs again later in the run (a loop,
1194
- or an `on_failure` route back to it) has a new step number and so new keys.
1203
+ role (`before_generate`, generator, `before_eval`, evaluator), or
1204
+ orchestrator round and worker task. A worker task is named by its content and
1205
+ which copy of equal tasks it is, so a replayed orchestrator that lists the
1206
+ same tasks in another order keeps each task's key. A transition that runs
1207
+ again later in the run (a loop, or an `on_failure` route back to it) has a
1208
+ new step number and so new keys.
1195
1209
  - Use a scope to tell apart several requests of one step. A tool can run several
1196
1210
  times in a step, and a replayed model may word or order its calls
1197
1211
  differently, so a tool's scope is required and should be the request's stable
@@ -245,6 +245,13 @@ result.tool_results
245
245
 
246
246
  Captured tool results survive persistence — they are included in `to_state` and restored via `from_state`.
247
247
 
248
+ A capture taken in an `optimize` round names it (`round`, from 0 in each
249
+ attempt), so a host can tell the accepted round's captures from those of the
250
+ rounds its step rejected (docs/PATTERNS.md, Evaluator-Optimizer,
251
+ `before_generate`); any other capture has no `round`. The round is the step's
252
+ own: captures of two optimize steps in one run are told apart by the tools the
253
+ host gives each.
254
+
248
255
  `tool_results` is designed for compact structured evidence (URLs, metadata, refs). Hosts should avoid storing large raw payloads there. If large tool outputs are needed, use artifacts and capture refs or metadata instead.
249
256
 
250
257
  Capture is best-effort by default for backward compatibility. Hosts that cannot
@@ -24,23 +24,33 @@ module Smith
24
24
 
25
25
  private
26
26
 
27
- # Counts the cached blocks already in the chat (its instructions) and
28
- # those the prepared input adds, before any is added.
29
- def check_cache_breakpoints!(chat, messages, provider)
27
+ # Counts the cached blocks already in the chat (its instructions), those
28
+ # the prepared input adds, and an automatic prompt cache, the call's own
29
+ # (`shape`, ProviderRequest) or a top-level marker the chat's params
30
+ # carry, once, before any is added.
31
+ def check_cache_breakpoints!(chat, messages, provider, shape)
30
32
  return unless anthropic?(provider)
31
33
 
32
- cached = chat_cache_controls(chat) +
34
+ automatic = automatic_breakpoint?(chat, shape, provider)
35
+ cached = chat_cache_controls(chat) + (automatic ? 1 : 0) +
33
36
  messages.sum { |message| message_parts(message).count { |part| Content.cached?(part) } }
34
37
  return if cached <= MAX_CACHE_BREAKPOINTS
35
38
 
36
- raise ContentUnavailable, "#{cached} blocks ask to be cached; Anthropic takes at most " \
37
- "#{MAX_CACHE_BREAKPOINTS} cache breakpoints in one request"
39
+ counted = automatic ? ", an automatic prompt cache counting one" : ""
40
+ raise ContentUnavailable, "#{cached} cache breakpoints are asked for#{counted}; Anthropic takes at most " \
41
+ "#{MAX_CACHE_BREAKPOINTS} in one request"
38
42
  end
39
43
 
40
- def check_chain_cache_breakpoints!(chain, prepared_input)
44
+ def automatic_breakpoint?(chat, shape, provider) = automatic_cache?(shape, provider) || chat_cache_marked?(chat)
45
+
46
+ def check_chain_cache_breakpoints!(chain, prepared_input, shape)
41
47
  return unless chain.any? { |reference| anthropic?(reference.provider) }
42
48
 
43
- check_cache_breakpoints!(nil, Array(prepared_input), :anthropic)
49
+ check_cache_breakpoints!(nil, Array(prepared_input), :anthropic, shape)
50
+ end
51
+
52
+ def chat_cache_marked?(chat)
53
+ chat.respond_to?(:params) && chat.params.is_a?(Hash) && cached_block?(chat.params)
44
54
  end
45
55
 
46
56
  # A model the chain reaches whose provider takes no such content.
@@ -36,11 +36,11 @@ module Smith
36
36
 
37
37
  # The messages, with their content parts (ContentParts) as `provider`
38
38
  # takes them.
39
- def add_prepared_input(chat, prepared_input, provider = nil)
39
+ def add_prepared_input(chat, prepared_input, provider, shape)
40
40
  return unless prepared_input
41
41
 
42
42
  prepared_input = provider_safe_prepared_input(prepared_input)
43
- check_cache_breakpoints!(chat, prepared_input, provider)
43
+ check_cache_breakpoints!(chat, prepared_input, provider, shape)
44
44
  with_built_contents do
45
45
  prepared_input = prepared_input.map do |message|
46
46
  Message.parts?(message) ? provider_parts_message(message, provider) : message
@@ -29,7 +29,7 @@ module Smith
29
29
  # What one invocation has tried so far.
30
30
  Plan = Struct.new(:agent_class, :input, :output_schema, :json_schema, :repairs_left, :retried, :fell_back,
31
31
  :output_limit, :calls) do
32
- def shape = ProviderRequest::Shape.new(output_schema:, output_limit:)
32
+ def shape = ProviderRequest::Shape.new(output_schema:, output_limit:, prompt_cache: agent_class.prompt_cache)
33
33
  end
34
34
  private_constant :Plan
35
35
 
@@ -115,13 +115,18 @@ module Smith
115
115
  end
116
116
 
117
117
  # Whether the responses so far have reached what the call's step
118
- # reserved in any budget dimension.
118
+ # reserved in any token or cost dimension. A reservation names every
119
+ # budget the workflow declares, wall_clock among them at 0; a call
120
+ # spends only tokens and cost, and the deadline is checked before the
121
+ # follow-up is made.
119
122
  def budget_spent?(result)
120
123
  reservation = Thread.current[:smith_call_reservation]
121
124
  return false unless reservation
122
125
 
123
126
  spent = extract_actuals([*Array(Thread.current[:smith_failed_agent_results]), result])
124
127
  reservation.amounts.any? do |dimension, amount|
128
+ next false unless Workflow::BudgetIntegration::BUDGET_DIMENSIONS.include?(dimension)
129
+
125
130
  used = Workflow::BudgetIntegration::COST_DIMENSIONS.include?(dimension) ? spent[:cost] : spent[:tokens]
126
131
  used >= amount
127
132
  end
@@ -0,0 +1,31 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Smith
4
+ class Agent
5
+ # Which prompt cache an agent's requests ask for beyond the parts a host
6
+ # marks (`cache: true`):
7
+ #
8
+ # prompt_cache :automatic # Anthropic caches each request's longest prefix
9
+ # prompt_cache :none # the default
10
+ #
11
+ # `:automatic` puts a top-level cache_control on each Anthropic request:
12
+ # Anthropic places the breakpoint on the request's last block and moves
13
+ # it forward as a tool loop grows, so each request reads the one before
14
+ # it from the cache. It counts as one of a request's four breakpoints;
15
+ # any other provider is asked nothing (ProviderRequest).
16
+ module PromptCache
17
+ UNSET = Object.new.freeze
18
+ MODES = %i[none automatic].freeze
19
+ private_constant :UNSET, :MODES
20
+
21
+ def prompt_cache(mode = UNSET)
22
+ return @prompt_cache || :none if mode.equal?(UNSET)
23
+
24
+ chosen = mode.respond_to?(:to_sym) ? mode.to_sym : mode
25
+ raise ArgumentError, "prompt_cache must be :none or :automatic" unless MODES.include?(chosen)
26
+
27
+ @prompt_cache = chosen
28
+ end
29
+ end
30
+ end
31
+ end
@@ -31,7 +31,7 @@ module Smith
31
31
  # before the first attempt. A candidate that fails over to the next
32
32
  # joins `set_aside` (AttemptCaptures).
33
33
  def complete_with_provider(agent_class, prepared_input, shape:, set_aside: [])
34
- chain = build_model_chain(agent_class).tap { check_chain_cache_breakpoints!(_1, prepared_input) }
34
+ chain = build_model_chain(agent_class).tap { check_chain_cache_breakpoints!(_1, prepared_input, shape) }
35
35
  ContentBytes.with(prepared_input) { attempt_candidates(agent_class, prepared_input, chain, shape, set_aside) }
36
36
  end
37
37
 
@@ -150,7 +150,8 @@ module Smith
150
150
 
151
151
  def prepared_attempt_chat(agent_class, prepared_input, model_reference, shape)
152
152
  chat = attempt_chat(agent_class, model_reference)
153
- add_prepared_input(chat, prepared_input, observed_model_reference(chat, fallback: model_reference).provider)
153
+ add_prepared_input(chat, prepared_input, observed_model_reference(chat, fallback: model_reference).provider,
154
+ shape)
154
155
  continue_paused_loop(chat)
155
156
  shaped_chat(chat, model_reference, shape)
156
157
  end