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
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: d24b9d2b16aa4bc15335adf1ac519a2b1979306e78c5adbd9d79d7c4c37b4ae1
4
- data.tar.gz: f89dc27bdede7609559dd8b943c6f8a8ca430d8b65384cb2bee098589d9389b5
3
+ metadata.gz: becfd8870e143796ef08b737512b9ace6c0f08919c35716dbbd5ad769149286c
4
+ data.tar.gz: 8df467d0a83ad6c84028c1e4c2778ef41f1fd9ac1976a47ab43740df962d88b9
5
5
  SHA512:
6
- metadata.gz: 568b8f7e26296999a607319f95cebd0f6eab757a6bc109449b4a1e53738f74d57bbad20c13bfe02949204ea3e428ce19135b0713b8cb57d0f15c2f4806ec13ec
7
- data.tar.gz: 403c1afd783f9a811b8c9a3e1f8ecadef3ab340b4250f75e73ee596104ea5fa9246bdcb964ca01f4ce55fc9b4861a59d528a25625e37b23d43834248024c4602
6
+ metadata.gz: 3b067aa94dae4a63dd2de9b3494df7f8253f046ab12e43d7fe7a5ef31398053530381b779a67aa628f81b3f4690b930bca64614687939cb8ab9cb98d144617f9
7
+ data.tar.gz: ddc60cf738e866d30480488d234ead6ce2b74cd2ad414e8b0ded240688d0ce5ed26f41cdeff3850f4ba8a96d4ee3689527f1e04ce91b2d6708c5bf0a868735e1
data/CHANGELOG.md CHANGED
@@ -4,6 +4,153 @@ 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.16.0] - 2026-11-22
8
+
9
+ ### Added
10
+
11
+ - An agent may answer with an image: `image size:, quality:, background:,
12
+ output_format:` (the provider's own words). Its attempt paints instead of
13
+ chatting (RubyLLM's `Provider#paint`, OpenAI's image edits when its input
14
+ carries images): its instructions and its input's text are the prompt, its
15
+ input's images (`Smith::Content.image`) are drawn from in order, and its
16
+ answer is the image kept in the run's artifacts as `Smith::Content.image(ref,
17
+ media_type:)`. An image agent takes no tools, output schema or thinking, and
18
+ its step is neither streamed nor batched (a `Smith::WorkflowError`).
19
+ - An image's request is held on the run's budget ledger as any request is:
20
+ the pricing catalog says what an image of each size and quality writes
21
+ (`image_output_tokens`), and a model's image tokens may be priced apart
22
+ (`image_input_cost_per_token`, `image_output_cost_per_token`). Usage, usage
23
+ entries, `AgentResult` and the `:provider_call` trace carry the image parts
24
+ of the input and output (`image_input_tokens`, `image_output_tokens`), and
25
+ `Pricing.compute_cost` prices them.
26
+ - `Smith::RequestOutcomeUncertain`: an image's request sent whose answer never
27
+ came (a read timeout, a connection lost once sent) may have been billed. It
28
+ is never retried (`Smith::Errors.retry_forbidden?`), takes no fallback, is
29
+ charged its whole hold, and persists with a failure family of its own
30
+ (`request_outcome_uncertain`), its cause the transport's error. An image's
31
+ request turns RubyLLM's HTTP retries off, so it is never sent twice. A
32
+ moderation block (`moderation_blocked`) is a refused response, costing
33
+ nothing, which the agent's `on_refusal` takes (`Smith::OutputRefused` by
34
+ default), its fallback painting too. Only a throttle or a refusal of the
35
+ account, the model or the content sends an image's request again; a
36
+ server's error is a `ProviderPermanentFailure`, and a gateway's 504 or TLS
37
+ failing mid-exchange is an uncertain outcome. An answer with no image is an
38
+ `OutputInvalid` whose usage is kept, as is that of an image the store could
39
+ not keep. A paint keeps no response memo.
40
+ - A fan-out over items: `workflow Child, over: ->(context) { items },
41
+ item_to: :key, concurrency: n, output_to: :key` runs the nested workflow once
42
+ an item, each with its item under `item_to:` in its copy of the context, at
43
+ most `concurrency:` at once, each spending within an equal share of what the
44
+ run's budget has left in every dimension. Each item's outcome is its own, in
45
+ order: `{ output: ... }`, or `{ refused: message }` when its run ended on a
46
+ refused response; any other failure fails the step. A nested workflow step
47
+ may name `output_to:`.
48
+
49
+ ### Changed
50
+
51
+ - A retry-forbidden failure (an uncertain request or tool outcome) is never
52
+ replaced by an interrupting error among a step's fallbacks, an uncertain
53
+ request outranks an interruption among parallel branches, and a nested
54
+ workflow that routed a retry-forbidden failure through its own
55
+ `on_failure` fails its parent with that error rather than a
56
+ `WorkflowError`, so nothing takes the step again over a request that may
57
+ have been billed.
58
+
59
+ ### Upgrading
60
+
61
+ - `Smith::Workflow::AgentResult` and `UsageEntry` gain two optional members,
62
+ `image_input_tokens` and `image_output_tokens`, omitted from a usage entry's
63
+ hash when nil, so a checkpoint written before reads and writes back the same.
64
+ - A host that rescued `Smith::WorkflowError` around a nested workflow whose
65
+ child failed on an uncertain request or tool outcome now sees that error
66
+ itself.
67
+ - `Smith::EXECUTION_SEMANTICS_VERSION` stays `"7"`: a run stored by 0.15.0
68
+ holds no item fan-out and no image usage, and restores as it is.
69
+
70
+ ## [0.15.0] - 2026-11-22
71
+
72
+ ### Added
73
+
74
+ - `prompt_cache :automatic` on an agent asks Anthropic to cache each
75
+ request's longest prefix (a top-level `cache_control`, the breakpoint moving
76
+ with the request's last block), so a tool loop reads each request's prefix
77
+ from the cache rather than sending it again at full price. It counts as one
78
+ of a request's four breakpoints, as a top-level marker a chat's params
79
+ already carry does; other providers and a batch request are asked nothing;
80
+ the hold already prices a request-level marker at the cache-write rate.
81
+ Too many breakpoints now read "N cache breakpoints are asked for" (", an
82
+ automatic prompt cache counting one" where it does).
83
+ - `optimize ..., before_generate: ->(state, context)` runs before each round's
84
+ generator is asked, the first round of every attempt included. Whatever this
85
+ step's rounds and attempts did before it belongs to a round the loop
86
+ rejected or an attempt that failed, so a host whose generator's tools stage
87
+ work for the candidate (a pending write it publishes once the step is
88
+ accepted) sets it aside before the next round builds on it. `before_generate`,
89
+ `before_eval` and the exit modes read the round under way from
90
+ `state.round`, and each tool capture an optimize round takes names it
91
+ (`round` on its `tool_results` entry), so a host tells the accepted round's
92
+ captures from those of the rounds its step rejected. It returns
93
+ `{ rejected_round: String }` to say what the rejected round's tools left,
94
+ since a candidate does not carry its tools' work: a later round's generator
95
+ is told it after the evaluator's feedback (`[smith:rejected-round]`), copied
96
+ and bounded as a message's words are and kept with a batch wait, so the
97
+ generator revises the candidate. Round 0, blank words and any other return
98
+ value tell it nothing; a `rejected_round` that is not a String fails the step.
99
+ - An `optimize` step streams: `optimize ..., stream: :name` sends its
100
+ generator's replies to the sink, round after round, as `execute` does. The
101
+ evaluator never streams, since its reply is a verdict, and a rejected
102
+ round's text is withdrawn with `reset(:rejected)` as the generator writes
103
+ again; the last round ends as any streamed step does, with `finish` (the
104
+ output kept, `:return_last` included) or `fail`. Runtime readiness checks
105
+ the generator's route. A streamed `optimize` step cannot batch.
106
+ - A nested workflow's failure keeps the child's own error as the parent's
107
+ error's `cause`, so a host can read what the child failed on (a
108
+ `DeterministicStepFailure`'s details, for one) beyond the parent error's
109
+ message.
110
+ - `optimize ..., evaluator_context:` takes a callable, which builds the
111
+ evaluator's messages from copies of the candidate and the context, checked
112
+ as an `input:` callable's are. An evaluator can then read only its own part
113
+ of the context, and one whose round-by-round material sits in its last
114
+ message keeps the same prefix across rounds, which a provider's prompt
115
+ cache can reuse; under `:inject_state` it re-read the generator's whole
116
+ input every round.
117
+
118
+ ### Fixed
119
+
120
+ - An agent's output cap (`params max_tokens:`) reaches an OpenAI model that
121
+ reasons as `max_completion_tokens` (or `max_output_tokens` on the Responses
122
+ API) on every attempt, not only a retry: OpenAI's Chat Completions refuses
123
+ `max_tokens` from those models, so a step without tools on one failed its
124
+ first call. Any other OpenAI chat, an OpenAI-compatible server's among them,
125
+ keeps its own `max_tokens`.
126
+
127
+ - An agent step in a workflow whose budget declares `wall_clock` gets its
128
+ output repair, its truncation retry and its refusal fallback again. The
129
+ step's reservation names every budget dimension, `wall_clock` among them
130
+ at 0, and the check that stops follow-up calls once a call has spent its
131
+ reservation compared the tokens spent against that 0, so any response
132
+ counted as spent and no follow-up was made. The check now weighs only
133
+ tokens and cost; the deadline is still checked before a follow-up.
134
+ - A request's budget hold covers input written to a prompt cache. The hold
135
+ priced its estimated input at the plain input rate, so a prompt marked for
136
+ caching, whose writes cost more (1.25x on Anthropic's five-minute cache),
137
+ could spend past what was held for it. A request that marks a block for
138
+ the cache (`cache_control` on the request or on a message's block) is now
139
+ held with its input at the dearer of plain input and a cache write; any
140
+ other request, and a model with no cache-write rate, is held as before.
141
+
142
+ ### Upgrading
143
+
144
+ - A workflow whose budget declares `wall_clock` makes again the output
145
+ repairs, truncation retries and refusal fallbacks it had skipped, so its
146
+ steps may spend more of the budget than under 0.14.0.
147
+ - A request marked for the prompt cache is held at the dearer of plain input
148
+ and a cache write, so a budget close to its limit refuses such a request
149
+ sooner.
150
+ - `Smith::EXECUTION_SEMANTICS_VERSION` stays `"7"`: an optimize step's
151
+ stored batch wait may now carry the words `before_generate` told its round
152
+ (`told`), and a run stored by 0.14.0, which carries none, restores as it is.
153
+
7
154
  ## [0.14.0] - 2026-11-09
8
155
 
9
156
  ### Added
data/README.md CHANGED
@@ -30,7 +30,7 @@ What you get:
30
30
 
31
31
  ```ruby
32
32
  # Gemfile
33
- gem "smith-agents", "0.14.0", require: "smith"
33
+ gem "smith-agents", "0.16.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,8 +204,10 @@ 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
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
209
211
  delivers the result when the batch ends. `fan_out` and `optimize` take the same
210
212
  `mode:`; an `optimize` step batches each call of its loop in turn.
211
213
  [`docs/AGENTS.md`](docs/AGENTS.md)
data/docs/AGENTS.md CHANGED
@@ -76,6 +76,54 @@ with a failed step, and are never retried by `Smith::Errors.retryable?`, a job
76
76
  retry on `Smith::Errors.retryable_classes`, or a transition's
77
77
  `retry_on Smith::AgentError`: Smith's own retry, fallback and repairs have run.
78
78
 
79
+ ## Image agents
80
+
81
+ An agent may answer with an image:
82
+
83
+ ```ruby
84
+ class Drawer < Smith::Agent
85
+ register_as :drawer
86
+ model "gpt-image-2.6-sunburst", provider: :openai
87
+ image size: "1024x1024", quality: "low", background: "opaque", output_format: "png"
88
+ instructions "Draw this as a simple exercise illustration in blue ballpoint pen."
89
+ end
90
+ ```
91
+
92
+ Its attempt paints instead of chatting (RubyLLM's `Provider#paint`, OpenAI's
93
+ image edits when the input carries images): its instructions and its input's
94
+ text, joined, are the prompt, and its input's images (`Smith::Content.image`)
95
+ are drawn from in order. Its answer is the image, kept in the run's artifacts:
96
+ `{ type: "image", artifact: ref, media_type: "image/png" }`. The options are
97
+ the provider's own words, passed as they are.
98
+
99
+ - An image agent takes no tools, output schema or thinking, and its step is
100
+ neither streamed nor batched; any of them fails the step with a
101
+ `Smith::WorkflowError`.
102
+ - Its request is held on the run's budget ledger at the image its size and
103
+ quality write (the pricing catalog's `image_output_tokens`) and its prompt
104
+ and images, and settled at what its usage cost; usage carries the image
105
+ parts of the input and output (`image_input_tokens`, `image_output_tokens`),
106
+ priced at the catalog's image rates. A size and quality the catalog prices
107
+ not is held unpriced, which a ledger may refuse.
108
+ - A moderation block (`moderation_blocked`) is a refused response: it costs
109
+ nothing and goes to the agent's `on_refusal` (`Smith::OutputRefused` by
110
+ default).
111
+ - Each request is sent once: RubyLLM's HTTP retries are off for it, and only a
112
+ throttle or a refusal of the account, the model or the content goes again
113
+ (to a fallback, or the step's retry); a server's error never does, since it
114
+ may have done the work (`Smith::ProviderPermanentFailure`). A request sent
115
+ whose answer never came (a read timeout, a gateway's 504, a connection lost
116
+ or TLS failing mid-exchange) raises `Smith::RequestOutcomeUncertain`, never
117
+ retried and never answered by a fallback, and its hold is charged whole,
118
+ since the provider may have billed it. A refusal's fallback paints too. An
119
+ answer with no image is an `OutputInvalid` whose usage is kept. An image can
120
+ take minutes: give the agent its own timeout with RubyLLM's `context`.
121
+ - A paint keeps no response memo (an image is too large to keep twice), so a
122
+ step a crash replays paints again: a host that pays for images runs its
123
+ workflow in strict idempotency, where such a step fails instead.
124
+ - The prompt is read from the system and user turns alone: an assistant turn
125
+ (an earlier answer, such as a rejected round's) is not sent.
126
+
79
127
  ## Models and request shaping
80
128
 
81
129
  Smith ships a per-attempt normalizer that translates the request payload to whatever the resolved model's provider family expects:
@@ -84,6 +132,7 @@ Smith ships a per-attempt normalizer that translates the request payload to what
84
132
  - Anthropic 4.0–4.6 budget_tokens
85
133
  - OpenAI gpt-5 family reasoning_effort with `/v1/responses` routing when tools + thinking are combined
86
134
  - Gemini 2.5+ budget_tokens
135
+ - 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
136
 
88
137
  Override the inferred profile per-app via `Smith::Models.register(Profile.new(...))`.
89
138
  Profiles are keyed by both provider and model id. Pass `provider:` to
@@ -139,11 +188,17 @@ class Answer < Smith::Workflow
139
188
  end
140
189
  ```
141
190
 
191
+ An `optimize` step takes `stream:` too: its generator's replies stream round
192
+ after round, its evaluator's never (a verdict is not the step's words), and a
193
+ round the evaluator or `before_eval` rejects is withdrawn as the generator
194
+ writes again; the last round ends with `finish` or `fail` alone.
195
+
142
196
  A sink defines any of `start(info)` (each provider call: the step's info with
143
197
  the attempt, model and provider), `delta(text)` (each text chunk; tool calls,
144
198
  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)`
199
+ text sent so far: `:retry`, `:fallback`, `:truncation` or `:repair`;
200
+ `:rejected`, an `optimize` step's round its evaluator or `before_eval` refused;
201
+ and `:retry_wait`, the last word, while a durable retry waits), `finish(output)`
147
202
  (the output the step accepted, after guardrails, the output contract and
148
203
  `output_to:`, once the step is stored) and `fail(error_class)`. Streamed text is
149
204
  a draft: guardrails and output checks run on the whole reply, so nothing should
@@ -259,16 +314,17 @@ request of its own, a round's generator and then its evaluator, since the
259
314
  evaluator reads what the generator wrote: a round is two waits. Each call is
260
315
  queued under a wait of its own (its round and call tell the token apart), and
261
316
  the run's pending batch keeps the loop's progress (`progress`): the round, the
262
- call it waits for, the candidate, the feedback and last score, and the
263
- verdicts so far, as JSON gives them. A candidate or feedback that is not JSON
317
+ call it waits for, the candidate, the feedback and last score, what
318
+ `before_generate` told the round (`rejected_round`), and the verdicts so far,
319
+ as JSON gives them. A candidate or feedback that is not JSON
264
320
  fails the step before anything is queued, as does progress that would take a
265
321
  stored run past `persistence_max_bytes` (`Smith::PersistedStateTooLarge`). A
266
322
  delivery settles its result's hold, then runs the step again at its attempt,
267
323
  and the loop goes on from that progress: the call it waited for takes its
268
- result, nothing before it runs again (`before_eval` included), and the next
269
- call is batched in turn, so each call is made, charged and held on a budget
270
- ledger once. The mode callable is asked at each call; a call it gives `:sync`
271
- goes over the wire and the loop goes on.
324
+ result, nothing before it runs again (`before_generate` and `before_eval`
325
+ included), and the next call is batched in turn, so each call is made, charged
326
+ and held on a budget ledger once. The mode callable is asked at each call; a
327
+ call it gives `:sync` goes over the wire and the loop goes on.
272
328
 
273
329
  A failed or missing result fails its call as on any batch step, and
274
330
  `retry_on` (in process, as an optimize step takes no durable retry) runs the
data/docs/BUDGETS.md CHANGED
@@ -113,10 +113,23 @@ 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
 
123
+ An image agent's request (an image `Provider#paint` draws) is held as its
124
+ prompt counted as text, each image it draws from at 1,600 tokens priced as
125
+ image input, and the image it writes at what the pricing catalog says its size
126
+ and quality write (`image_output_tokens`), priced as image output; `cost` is
127
+ nil when the catalog says nothing of that size and quality. It is reconciled
128
+ at its usage, whose image parts are priced at the catalog's image rates. One
129
+ whose answer never came once it was sent (a read timeout, a lost connection)
130
+ is reconciled at its whole hold, since the provider may have billed it; its
131
+ own HTTP retries are off, so it is never sent twice under one hold.
132
+
120
133
  A key is the provider attempt's `attempt_id` (as on its `:provider_call` trace)
121
134
  and the request's round, `"<attempt_id>:<n>"`, and for a batch request its
122
135
  `custom_id`. A batch request is held when its step captures it, at the batch
@@ -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
 
@@ -160,7 +161,12 @@ sits inside a tier.
160
161
  Each entry, or each tier of a tiered entry, prices `input_cost_per_token` and
161
162
  `output_cost_per_token`, and optionally `cache_read_cost_per_token` and
162
163
  `cache_write_cost_per_token` for input read from or written to a prompt cache,
163
- which providers report apart from uncached input. A tier without its own cache
164
+ which providers report apart from uncached input. A model that reads or draws
165
+ images may price the image parts of its uncached input and its output apart
166
+ (`image_input_cost_per_token`, `image_output_cost_per_token`, each the plain
167
+ rate when absent), and say what an image of each size and quality writes
168
+ (`image_output_tokens: { "1024x1024" => { "low" => 823 } }`, each a positive
169
+ Integer), which an image agent's hold is priced from. A tier without its own cache
164
170
  rate uses the entry's. An entry may also carry `batch_discount`, the fraction
165
171
  taken off the cost of a call made in batch mode (`0.5` for half price). Cache
166
172
  rates and the batch discount are configured per catalog and count as `0` when
@@ -198,7 +204,7 @@ from JSON or YAML has.
198
204
  | `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
205
  | `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
206
  | `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 |
207
+ | `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
208
  | `persistence_adapter` | Adapter for durable workflow state | `:redis`, `:rails_cache`, `:active_record`, `:memory`, or a custom object |
203
209
  | `persistence_options` | Per-adapter options (client, namespace, model, columns) | See "Built-In Persistence Adapters" |
204
210
  | `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 |
@@ -82,6 +82,19 @@ took effect before a timeout. An error named in `new_idempotency_key_on:` (or
82
82
  took no effect, and the attempts after it use new keys. See
83
83
  [PERSISTENCE.md](PERSISTENCE.md), Replay Safety.
84
84
 
85
+ ## A request that may have been billed
86
+
87
+ A request an image agent sent whose answer never came (its read timed out, a
88
+ gateway answered 504, or its connection was lost once sent, TLS failing
89
+ included) raises `Smith::RequestOutcomeUncertain`, its cause the transport's
90
+ error: the provider may have done and billed the work. It is retry-forbidden
91
+ (`Smith::Errors.retry_forbidden?`), takes no fallback, and its hold on the
92
+ budget ledger is charged whole. A connection that never opened sent nothing,
93
+ and fails over as any provider failure does. A retry-forbidden failure is
94
+ never outranked by an interrupting error, in a step's fallbacks or among
95
+ parallel branches, and a nested workflow that routed one through its own
96
+ `on_failure` still fails its parent with it, so nothing takes the step again.
97
+
85
98
  ## Interrupting errors
86
99
 
87
100
  Some errors say the host could not do its part, not that a step went wrong:
data/docs/PATTERNS.md CHANGED
@@ -342,6 +342,57 @@ What you get:
342
342
  - nested best-known token/cost totals roll up into the parent result
343
343
  - artifact scope is preserved across nesting
344
344
 
345
+ ### A fan-out over items
346
+
347
+ `workflow Child, over:, item_to:` runs the child once an item, each run in a
348
+ branch of its own with its item under `item_to:` in its copy of the context:
349
+
350
+ ```ruby
351
+ class DrawFrame < Smith::Workflow
352
+ initial_state :idle
353
+ state :done
354
+
355
+ transition :draw, from: :idle, to: :done do
356
+ optimize generator: :drawer, evaluator: :frame_critic, evaluator_schema: Verdict, max_rounds: 3,
357
+ input: ->(context) { Drawer.input(context[:pose]) },
358
+ evaluator_context: ->(drawn, context) { FrameCritic.input(drawn, context[:pose]) }
359
+ end
360
+ end
361
+
362
+ class DrawSet < Smith::Workflow
363
+ initial_state :idle
364
+ state :drawn
365
+ state :failed
366
+
367
+ transition :draw, from: :idle, to: :drawn do
368
+ workflow DrawFrame, over: ->(context) { context[:poses] }, item_to: :pose, concurrency: 6,
369
+ output_to: :frames
370
+ on_failure :fail
371
+ end
372
+ end
373
+ ```
374
+
375
+ What you get:
376
+
377
+ - one outcome an item, in the items' order: `{ output: ... }` (the child's
378
+ final output), or `{ refused: message }` when the child ended on a refused
379
+ response (`Smith::OutputRefused`, routed through its `on_failure` or raised),
380
+ so a host can try a refused item again its own way
381
+ - any other failure of any item fails the step, as a nested workflow's does,
382
+ the other items cancelled as a fan-out's are
383
+ - at most `concurrency:` items at once (below `parallel_concurrency`), so
384
+ their writes (a database-backed artifact store, a ledger) fit a connection
385
+ pool
386
+ - each item's idempotency keys, usage entries and traces are its own
387
+ (`branch_key` is the item's index), and its usage rolls up into the parent
388
+ - each item's run spends within an equal share of what the run's budget has
389
+ left in every dimension, held while it runs and settled at what it spent
390
+ - a failure nothing may ask again for (`Smith::Errors.retry_forbidden?`) fails
391
+ the step as itself, however the item's run routed it
392
+ - an item is a value the host computes; one that carries outside words is
393
+ marked by naming its `item_to:` key untrusted in the run's context
394
+ - no items is no runs and an empty Array
395
+
345
396
  ## Example 8: Evaluator-Optimizer
346
397
 
347
398
  Use `optimize` when one agent generates candidates and another agent evaluates whether the result is acceptable.
@@ -389,6 +440,14 @@ class TranslationWorkflow < Smith::Workflow
389
440
  end
390
441
  ```
391
442
 
443
+ What the evaluator reads is `evaluator_context:`'s to say. Left out, it reads
444
+ the candidate alone; `:inject_state` gives it the generator's input followed by
445
+ the candidate; a callable `->(candidate, context) { messages }` builds its
446
+ messages itself from copies of the candidate and the context, checked as an
447
+ `input:` callable's are, so an evaluator reads only its own part of the context
448
+ and, with what changes each round in its last message, keeps the same prefix
449
+ from round to round for a provider's prompt cache.
450
+
392
451
  `before_eval: ->(state, context) { ... }` runs after each candidate is
393
452
  generated and before the evaluator is called, and may write to the workflow
394
453
  context (a new top-level key must be a Symbol that the context's `persist` list
@@ -403,9 +462,40 @@ value, including a Hash with `accept: true`, is ignored and the evaluator
403
462
  judges as before. A deterministic check that makes a candidate unacceptable
404
463
  can reject it this way without spending an evaluator call.
405
464
 
465
+ `before_generate: ->(state, context) { ... }` runs before each round's
466
+ generator is asked, the first round of every attempt included (a round a batch
467
+ delivery goes on from asked it when its request was batched), and may write to
468
+ the workflow context as `before_eval` may. Whatever this step's earlier rounds
469
+ and attempts did belongs to a round the loop rejected or an attempt that
470
+ failed, so a host whose generator's tools stage work for the candidate (a
471
+ pending write, for the host to publish once the step is accepted) sets aside
472
+ what they staged before the next round builds on it. The generator of a later
473
+ round is given the rejected candidate and the evaluator's feedback, not its
474
+ tool calls, so it should be told that a candidate sent back keeps nothing its
475
+ tools did. It returns `{ rejected_round: String }` to say what the rejected
476
+ round's tools left: a later round's generator is told it after the evaluator's
477
+ feedback (`[smith:rejected-round]`), copied and bounded as a message's words
478
+ are, so it revises the candidate rather than starts again; the words are kept
479
+ with a batch wait, so a delivered round is the request sent. A round 0, blank
480
+ words or any other return value tells the generator nothing more, and a
481
+ `rejected_round` that is not a String fails the step. A provider attempt the
482
+ call sets aside inside one round (a fallback model, a repair) is not a round:
483
+ its captures leave `tool_results` as before, and `before_generate` does not run
484
+ between it and the attempt that replaces it. A raise fails the step as a raise
485
+ from `before_eval` does. `before_generate`, `before_eval` and the exit modes read
486
+ the round under way from `state.round`, from 0 in each attempt, and every tool
487
+ capture a round takes names it (`round` on its `tool_results` entry), so a host
488
+ tells the accepted round's captures from those of the rounds its step
489
+ rejected. The round is the step's own: captures of two optimize steps in one
490
+ run, or of a transition that runs again, are told apart by the host, by the
491
+ tools it gives each step.
492
+
406
493
  `mode: :batch` (or a callable of the context and attempt) sends each call of
407
494
  the loop through the provider's batch API, the run waiting for each result
408
495
  and going on from where the loop stood: docs/AGENTS.md, Batch mode.
496
+ `stream: :name` instead sends the generator's drafts to a sink as they are
497
+ written, a rejected draft withdrawn as the next begins: docs/AGENTS.md,
498
+ Streaming.
409
499
 
410
500
  Every round's verdict is an output. Once its loop has run, the step's record
411
501
  carries its verdicts under `:evaluations`, in attempt and round order, whether
@@ -445,13 +535,13 @@ loop is kept, whether it accepts, converges, or trips the improvement
445
535
  threshold. A step whose completion fails after its loop (a split step's
446
536
  snapshot over its limits) keeps its verdicts on the failure record. A nested
447
537
  workflow's verdicts stay on its own run: the parent's step carries the child's
448
- usage, not its verdicts. A callable
449
- (`before_eval` or an exit mode) reads its own loop's verdicts so far from
450
- `state.evaluations`, a frozen copy without `attempt`, so it cannot rewrite the
451
- step's. Verdicts are content, so they are an output and never a
452
- trace: nothing about them reaches a trace adapter. Like `steps`, they belong to
453
- the run that executed the step, so a terminal restore has none; a host that
454
- needs them later stores them when the run returns.
538
+ usage, not its verdicts. A callable (`before_generate`, `before_eval` or an
539
+ exit mode) reads its own loop's verdicts so far from `state.evaluations`, a
540
+ frozen copy without `attempt`, so it cannot rewrite the step's. Verdicts are
541
+ content, so they are an output and never a trace: nothing about them reaches a
542
+ trace adapter. Like `steps`, they belong to the run that executed the step, so
543
+ a terminal restore has none; a host that needs them later stores them when the
544
+ run returns.
455
545
 
456
546
  Why this matters:
457
547
 
@@ -650,7 +740,7 @@ The yielded step object exposes a narrow, read-heavy surface:
650
740
  - **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.
651
741
  - **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`.
652
742
  - **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`.
653
- - **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.
743
+ - **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.
654
744
  - **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.
655
745
  - **No output**: Deterministic steps produce no session message output. `last_output` continues to mean the last agent output.
656
746
  - **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