smith-agents 0.14.0 → 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.
- checksums.yaml +4 -4
- data/CHANGELOG.md +84 -0
- data/README.md +6 -4
- data/docs/AGENTS.md +16 -8
- data/docs/BUDGETS.md +4 -1
- data/docs/CONFIGURATION.md +3 -2
- data/docs/PATTERNS.md +47 -8
- data/docs/PERSISTENCE.md +21 -7
- data/docs/TOOLS_AND_GUARDRAILS.md +7 -0
- data/lib/smith/agent/content_parts.rb +18 -8
- data/lib/smith/agent/invocation_preparation.rb +2 -2
- data/lib/smith/agent/output_integrity.rb +1 -1
- data/lib/smith/agent/output_recovery.rb +6 -1
- data/lib/smith/agent/prompt_cache.rb +31 -0
- data/lib/smith/agent/provider_completion.rb +3 -2
- data/lib/smith/agent/provider_request.rb +29 -4
- data/lib/smith/agent.rb +3 -0
- data/lib/smith/budget/request_hold.rb +33 -3
- data/lib/smith/providers/output_limit.rb +22 -1
- data/lib/smith/streaming/session.rb +2 -0
- data/lib/smith/streaming.rb +3 -1
- data/lib/smith/version.rb +1 -1
- data/lib/smith/workflow/evaluator_optimizer.rb +93 -17
- data/lib/smith/workflow/graph/optimization_contract.rb +1 -0
- data/lib/smith/workflow/graph/stream_diagnostic.rb +9 -4
- data/lib/smith/workflow/graph/transition_optimization_configuration.rb +1 -0
- data/lib/smith/workflow/guarded_step_execution.rb +1 -1
- data/lib/smith/workflow/nested_execution.rb +4 -2
- data/lib/smith/workflow/optimization_state.rb +7 -2
- data/lib/smith/workflow/optimizer_batch.rb +21 -9
- data/lib/smith/workflow/step_io.rb +10 -4
- data/lib/smith/workflow/step_stream.rb +9 -0
- data/lib/smith/workflow/transition.rb +27 -17
- metadata +2 -1
checksums.yaml
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
---
|
|
2
2
|
SHA256:
|
|
3
|
-
metadata.gz:
|
|
4
|
-
data.tar.gz:
|
|
3
|
+
metadata.gz: 4e68bbf1f174434fef943c8ed78133e5536eb836b0cc04e11d338401f5cf14cf
|
|
4
|
+
data.tar.gz: 5daed55ca366c3eacd5728d720218f2af1464077d7584d0b77aef3e65b681986
|
|
5
5
|
SHA512:
|
|
6
|
-
metadata.gz:
|
|
7
|
-
data.tar.gz:
|
|
6
|
+
metadata.gz: aee4c70c34cc92db641757b7785b806e2ebfccc314a199f9c9c0ad23c243fa22efaddd53a6d012f02140fca7b8705555a3169e4493049923f1889e84a9ff3a1e
|
|
7
|
+
data.tar.gz: ba3d4f427da7b0fd7e95c66fdff91250aed9e815c7213f9a8919ed4bc922b96caa3abd12be23e6ae1bccdbca702ce6190f4b00cfda2f1478d730a0bef3704d01
|
data/CHANGELOG.md
CHANGED
|
@@ -4,6 +4,90 @@ 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
|
+
|
|
7
91
|
## [0.14.0] - 2026-11-09
|
|
8
92
|
|
|
9
93
|
### 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.
|
|
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,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. `
|
|
208
|
-
|
|
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
|
@@ -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`;
|
|
146
|
-
`:
|
|
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
|
|
@@ -259,16 +266,17 @@ request of its own, a round's generator and then its evaluator, since the
|
|
|
259
266
|
evaluator reads what the generator wrote: a round is two waits. Each call is
|
|
260
267
|
queued under a wait of its own (its round and call tell the token apart), and
|
|
261
268
|
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,
|
|
263
|
-
|
|
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
|
|
264
272
|
fails the step before anything is queued, as does progress that would take a
|
|
265
273
|
stored run past `persistence_max_bytes` (`Smith::PersistedStateTooLarge`). A
|
|
266
274
|
delivery settles its result's hold, then runs the step again at its attempt,
|
|
267
275
|
and the loop goes on from that progress: the call it waited for takes its
|
|
268
|
-
result, nothing before it runs again (`
|
|
269
|
-
call is batched in turn, so each call is made, charged
|
|
270
|
-
ledger once. The mode callable is asked at each call; a
|
|
271
|
-
goes over the wire and the loop goes on.
|
|
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.
|
|
272
280
|
|
|
273
281
|
A failed or missing result fails its call as on any batch step, and
|
|
274
282
|
`retry_on` (in process, as an optimize step takes no durable retry) runs the
|
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
|
|
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
|
|
data/docs/CONFIGURATION.md
CHANGED
|
@@ -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,9 +411,40 @@ 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
|
+
|
|
406
442
|
`mode: :batch` (or a callable of the context and attempt) sends each call of
|
|
407
443
|
the loop through the provider's batch API, the run waiting for each result
|
|
408
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.
|
|
409
448
|
|
|
410
449
|
Every round's verdict is an output. Once its loop has run, the step's record
|
|
411
450
|
carries its verdicts under `:evaluations`, in attempt and round order, whether
|
|
@@ -445,13 +484,13 @@ loop is kept, whether it accepts, converges, or trips the improvement
|
|
|
445
484
|
threshold. A step whose completion fails after its loop (a split step's
|
|
446
485
|
snapshot over its limits) keeps its verdicts on the failure record. A nested
|
|
447
486
|
workflow's verdicts stay on its own run: the parent's step carries the child's
|
|
448
|
-
usage, not its verdicts. A callable
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
trace
|
|
453
|
-
|
|
454
|
-
|
|
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.
|
|
455
494
|
|
|
456
495
|
Why this matters:
|
|
457
496
|
|
|
@@ -650,7 +689,7 @@ The yielded step object exposes a narrow, read-heavy surface:
|
|
|
650
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.
|
|
651
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`.
|
|
652
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`.
|
|
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.
|
|
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.
|
|
654
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.
|
|
655
694
|
- **No output**: Deterministic steps produce no session message output. `last_output` continues to mean the last agent output.
|
|
656
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
|
|
1191
|
-
task. A worker task is named by its content and
|
|
1192
|
-
is, so a replayed orchestrator that lists the
|
|
1193
|
-
keeps each task's key. A transition that runs
|
|
1194
|
-
or an `on_failure` route back to it) has a
|
|
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)
|
|
28
|
-
#
|
|
29
|
-
|
|
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
|
-
|
|
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
|
-
|
|
37
|
-
|
|
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
|
|
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
|
|
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
|
|
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
|
|
@@ -3,19 +3,44 @@
|
|
|
3
3
|
module Smith
|
|
4
4
|
class Agent
|
|
5
5
|
# What one provider call asks for beyond its messages: the output schema
|
|
6
|
-
# as the provider takes it,
|
|
7
|
-
#
|
|
6
|
+
# as the provider takes it, the agent's output limit under the name an
|
|
7
|
+
# OpenAI model that reasons takes, a larger one when a cut-off response
|
|
8
|
+
# is retried, and Anthropic's automatic prompt cache when the agent asks
|
|
9
|
+
# for it (Agent.prompt_cache) and the call goes over the wire: a batch
|
|
10
|
+
# request is one turn read once, which a cache write only makes dearer.
|
|
8
11
|
module ProviderRequest
|
|
9
|
-
Shape = Data.define(:output_schema, :output_limit)
|
|
12
|
+
Shape = Data.define(:output_schema, :output_limit, :prompt_cache)
|
|
10
13
|
|
|
11
14
|
private
|
|
12
15
|
|
|
13
16
|
def shaped_chat(chat, model_reference, shape)
|
|
14
|
-
|
|
17
|
+
observed = observed_model_reference(chat, fallback: model_reference)
|
|
18
|
+
provider = observed.provider
|
|
19
|
+
chat = named_output_limit(chat, observed)
|
|
15
20
|
chat = with_output_limit(chat, provider, shape.output_limit) if shape.output_limit
|
|
21
|
+
chat = with_automatic_cache(chat) if automatic_cache?(shape, provider)
|
|
16
22
|
shape.output_schema ? chat.with_schema(provider_output_schema(shape.output_schema, provider)) : chat
|
|
17
23
|
end
|
|
18
24
|
|
|
25
|
+
# Whether the call carries Anthropic's automatic prompt cache, as the
|
|
26
|
+
# breakpoints are counted (ContentParts) and the request is shaped.
|
|
27
|
+
def automatic_cache?(shape, provider)
|
|
28
|
+
shape.prompt_cache == :automatic && anthropic?(provider) && !@batch_capturing
|
|
29
|
+
end
|
|
30
|
+
|
|
31
|
+
def with_automatic_cache(chat)
|
|
32
|
+
return chat unless chat.respond_to?(:with_params)
|
|
33
|
+
|
|
34
|
+
params = (chat.params if chat.respond_to?(:params)) || {}
|
|
35
|
+
chat.with_params(**::RubyLLM::Utils.deep_merge(params, { cache_control: { type: "ephemeral" } }))
|
|
36
|
+
end
|
|
37
|
+
|
|
38
|
+
def named_output_limit(chat, observed)
|
|
39
|
+
return chat unless chat.respond_to?(:with_params) && chat.respond_to?(:params) && chat.params.is_a?(Hash)
|
|
40
|
+
|
|
41
|
+
chat.with_params(**Providers::OutputLimit.named(observed.provider, chat.params, observed))
|
|
42
|
+
end
|
|
43
|
+
|
|
19
44
|
def with_output_limit(chat, provider, limit)
|
|
20
45
|
return chat unless chat.respond_to?(:with_params)
|
|
21
46
|
|
data/lib/smith/agent.rb
CHANGED
|
@@ -34,6 +34,7 @@ module Smith
|
|
|
34
34
|
subclass.instance_variable_set(:@fallback_models_block, @fallback_models_block)
|
|
35
35
|
subclass.instance_variable_set(:@model_block, @model_block)
|
|
36
36
|
subclass.instance_variable_set(:@tool_budget_exhaustion, @tool_budget_exhaustion)
|
|
37
|
+
subclass.instance_variable_set(:@prompt_cache, @prompt_cache)
|
|
37
38
|
%i[@on_truncation @on_refusal @output_contract @output_repairs].each do |name|
|
|
38
39
|
subclass.instance_variable_set(name, instance_variable_get(name))
|
|
39
40
|
end
|
|
@@ -152,9 +153,11 @@ require_relative "agent/fallback_configuration"
|
|
|
152
153
|
require_relative "agent/reserved_input_bridge"
|
|
153
154
|
require_relative "agent/chat_construction"
|
|
154
155
|
require_relative "agent/output_policy"
|
|
156
|
+
require_relative "agent/prompt_cache"
|
|
155
157
|
|
|
156
158
|
Smith::Agent.extend(Smith::Agent::DynamicConfiguration)
|
|
157
159
|
Smith::Agent.extend(Smith::Agent::FallbackConfiguration)
|
|
158
160
|
Smith::Agent.extend(Smith::Agent::ReservedInputBridge)
|
|
159
161
|
Smith::Agent.extend(Smith::Agent::ChatConstruction)
|
|
160
162
|
Smith::Agent.extend(Smith::Agent::OutputPolicy)
|
|
163
|
+
Smith::Agent.extend(Smith::Agent::PromptCache)
|
|
@@ -41,11 +41,41 @@ module Smith
|
|
|
41
41
|
context_window = model.context_window if model.respond_to?(:context_window)
|
|
42
42
|
input = [input_estimate(*request.values_at(:messages, :tools, :schema)), context_window].compact.min
|
|
43
43
|
output = [output_cap(provider, request[:params], model), Smith.config.budget_hold_output_tokens].compact.min
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
output_tokens: output, mode:))
|
|
44
|
+
price = price_for(provider, model, output, mode)
|
|
45
|
+
Amount.new(input_tokens: input, output_tokens: output, cost: most_cost(price, input, cache_marked?(request)))
|
|
47
46
|
end
|
|
48
47
|
|
|
48
|
+
# The request's cost with its input as the tokens name it: read plainly,
|
|
49
|
+
# or written to a prompt cache.
|
|
50
|
+
def price_for(provider, model, output, mode)
|
|
51
|
+
lambda do |**tokens|
|
|
52
|
+
Pricing.compute_cost(model: model.id, provider: provider.to_s, output_tokens: output, mode:, **tokens)
|
|
53
|
+
end
|
|
54
|
+
end
|
|
55
|
+
|
|
56
|
+
# A request that marks a block for a prompt cache may have all its input
|
|
57
|
+
# written to it, which can cost more than input read plainly, so it is
|
|
58
|
+
# held at the dearer of the two; any other request, or a model with no
|
|
59
|
+
# cache-write rate, is held as plain input.
|
|
60
|
+
def most_cost(price, input, cached)
|
|
61
|
+
costs = [price.call(input_tokens: input)]
|
|
62
|
+
costs << price.call(input_tokens: 0, cache_write_tokens: input) if cached
|
|
63
|
+
costs.compact.max
|
|
64
|
+
end
|
|
65
|
+
|
|
66
|
+
# A cache marker on the request's own params or on a block of one of its
|
|
67
|
+
# messages, where Smith puts a cached part's.
|
|
68
|
+
def cache_marked?(request)
|
|
69
|
+
marked_block?(request[:params]) || Array(request[:messages]).any? { marked_message?(_1) }
|
|
70
|
+
end
|
|
71
|
+
|
|
72
|
+
def marked_message?(message)
|
|
73
|
+
content = message.content if message.respond_to?(:content)
|
|
74
|
+
content.is_a?(::RubyLLM::Content::Raw) && Array(content.value).any? { marked_block?(_1) }
|
|
75
|
+
end
|
|
76
|
+
|
|
77
|
+
def marked_block?(block) = block.is_a?(Hash) && !(block[:cache_control] || block["cache_control"]).nil?
|
|
78
|
+
|
|
49
79
|
def input_estimate(messages, tools, schema)
|
|
50
80
|
counter = Counter.new
|
|
51
81
|
Array(messages).each { counter.message(_1) }
|
|
@@ -5,7 +5,9 @@ module Smith
|
|
|
5
5
|
# A provider's own parameter for the most tokens a response may hold,
|
|
6
6
|
# merged into the request when an agent retries a cut-off response
|
|
7
7
|
# (`on_truncation retry_with: { max_tokens: n }`). A provider not listed
|
|
8
|
-
# here is not retried.
|
|
8
|
+
# here is not retried. An agent's own cap (`params max_tokens:`) goes to
|
|
9
|
+
# an OpenAI model that reasons under the name it takes on every attempt
|
|
10
|
+
# (`named`): its Chat Completions refuses `max_tokens` from those models.
|
|
9
11
|
module OutputLimit
|
|
10
12
|
PROVIDERS = %w[anthropic openai gemini vertexai bedrock].freeze
|
|
11
13
|
PARAM_PATHS = {
|
|
@@ -42,6 +44,25 @@ module Smith
|
|
|
42
44
|
anthropic_default(model_reference.model_id) if provider.to_s == "anthropic"
|
|
43
45
|
end
|
|
44
46
|
|
|
47
|
+
# The params with the cap of a request to an OpenAI model that reasons
|
|
48
|
+
# under the name its path takes (`max_completion_tokens`, or
|
|
49
|
+
# `max_output_tokens` on the Responses API); any other request, an
|
|
50
|
+
# OpenAI-compatible server's `max_tokens` among them, unchanged.
|
|
51
|
+
def named(provider, chat_params, model_reference)
|
|
52
|
+
limit = provider.to_s == "openai" && reasons?(model_reference) ? current("openai", chat_params, nil) : nil
|
|
53
|
+
return chat_params unless limit.is_a?(Integer)
|
|
54
|
+
|
|
55
|
+
caps = PARAM_PATHS.fetch("openai").flatten.flat_map { |key| [key, key.to_s] }
|
|
56
|
+
unnamed = chat_params.except(*caps)
|
|
57
|
+
unnamed.merge(params("openai", unnamed, limit))
|
|
58
|
+
end
|
|
59
|
+
|
|
60
|
+
def reasons?(model_reference)
|
|
61
|
+
::RubyLLM.models.find(model_reference.model_id.to_s, "openai").capabilities.include?("reasoning")
|
|
62
|
+
rescue ::RubyLLM::ModelNotFoundError
|
|
63
|
+
false
|
|
64
|
+
end
|
|
65
|
+
|
|
45
66
|
def openai_key(chat_params)
|
|
46
67
|
return :max_output_tokens if responses?(chat_params)
|
|
47
68
|
|
|
@@ -14,6 +14,8 @@ module Smith
|
|
|
14
14
|
# :fallback another model answers (a provider failure, or a refusal)
|
|
15
15
|
# :truncation the reply was cut off and is asked for again
|
|
16
16
|
# :repair the reply could not be the output and is asked for again
|
|
17
|
+
# :rejected an `optimize` step's evaluator (or `before_eval`)
|
|
18
|
+
# rejected the round, and its generator writes again
|
|
17
19
|
# :retry_wait the step waits out a durable retry's backoff
|
|
18
20
|
#
|
|
19
21
|
# The step then ends with `finish(output)`, the output it accepted
|
data/lib/smith/streaming.rb
CHANGED
|
@@ -6,7 +6,9 @@ require_relative "streaming/json_field"
|
|
|
6
6
|
|
|
7
7
|
module Smith
|
|
8
8
|
# A step declared with `execute Agent, stream: :name` sends its reply's
|
|
9
|
-
# text, as the model writes it, to a sink the host gives it
|
|
9
|
+
# text, as the model writes it, to a sink the host gives it; one declared
|
|
10
|
+
# with `optimize ..., stream: :name` sends its generator's, round after
|
|
11
|
+
# round. The host
|
|
10
12
|
# registers a callable under that name in `Smith.config.stream_sinks`;
|
|
11
13
|
# when the step starts, Smith calls it with the step's info (the stream's
|
|
12
14
|
# name, the run's execution key, the transition) and streams to the sink
|
data/lib/smith/version.rb
CHANGED
|
@@ -37,12 +37,16 @@ module Smith
|
|
|
37
37
|
def run_optimization_loop(state, transition)
|
|
38
38
|
first, call = resume_optimizer_progress(state)
|
|
39
39
|
((first || 0)...state.config[:max_rounds]).each do |round|
|
|
40
|
-
|
|
40
|
+
state.round = round
|
|
41
|
+
resumed = round == first
|
|
42
|
+
at_evaluator = resumed && call == "evaluator"
|
|
41
43
|
# The overlay scopes every trace and usage fact from this round's
|
|
42
44
|
# generator and evaluator calls to the round that produced them.
|
|
43
45
|
result = Attribution.with(round: round) do
|
|
44
46
|
IdempotencyKey.__send__(:within, :round, round) do
|
|
45
|
-
|
|
47
|
+
with_round_captures(round) do
|
|
48
|
+
run_optimization_round(state, round, transition, at_evaluator:, resumed:)
|
|
49
|
+
end
|
|
46
50
|
end
|
|
47
51
|
end
|
|
48
52
|
return result if result
|
|
@@ -52,11 +56,34 @@ module Smith
|
|
|
52
56
|
"optimization exhausted #{state.config[:max_rounds]} rounds without acceptance")
|
|
53
57
|
end
|
|
54
58
|
|
|
59
|
+
# Every tool capture the round takes names it (`round`), as its usage
|
|
60
|
+
# entries, traces and verdicts do. The round's collector stamps each
|
|
61
|
+
# entry on its way to the step's, in place, so the captures of an
|
|
62
|
+
# attempt a call sets aside still leave by identity
|
|
63
|
+
# (Agent::AttemptCaptures); it is the collector, not the attribution,
|
|
64
|
+
# that reaches concurrent tool calls.
|
|
65
|
+
def with_round_captures(round, &block)
|
|
66
|
+
collector = Tool.current_tool_result_collector
|
|
67
|
+
return yield unless collector.respond_to?(:call)
|
|
68
|
+
|
|
69
|
+
stamped = ->(entry) { collector.call(entry.is_a?(Hash) ? entry.merge!(round:) : entry) }
|
|
70
|
+
Thread.handle_interrupt(Object => :never) do
|
|
71
|
+
Tool.current_tool_result_collector = stamped
|
|
72
|
+
begin
|
|
73
|
+
Thread.handle_interrupt(Object => :immediate, &block)
|
|
74
|
+
ensure
|
|
75
|
+
Tool.current_tool_result_collector = collector
|
|
76
|
+
end
|
|
77
|
+
end
|
|
78
|
+
end
|
|
79
|
+
|
|
55
80
|
# Each role is a position of its own in the round, so the generator,
|
|
56
|
-
# the before_eval
|
|
57
|
-
# round a delivery goes on from at its evaluator has its
|
|
58
|
-
|
|
59
|
-
|
|
81
|
+
# the before_generate and before_eval callbacks and the evaluator never
|
|
82
|
+
# share a key. A round a delivery goes on from at its evaluator has its
|
|
83
|
+
# candidate, and one it goes on from at its generator asked
|
|
84
|
+
# before_generate when its request was batched.
|
|
85
|
+
def run_optimization_round(state, round, transition, at_evaluator: false, resumed: false)
|
|
86
|
+
rejection = generate_and_screen(state, round, transition, resumed:) unless at_evaluator
|
|
60
87
|
evaluation = rejection || normalize_evaluation(
|
|
61
88
|
IdempotencyKey.__send__(:within, :evaluator) { evaluate_candidate(state, round, transition) }
|
|
62
89
|
)
|
|
@@ -212,27 +239,75 @@ module Smith
|
|
|
212
239
|
end
|
|
213
240
|
|
|
214
241
|
# The round's candidate, and a before_eval rejection of it, if any.
|
|
215
|
-
def generate_and_screen(state, round, transition)
|
|
242
|
+
def generate_and_screen(state, round, transition, resumed: false)
|
|
243
|
+
IdempotencyKey.__send__(:within, :before_generate) { run_before_generate(state) } unless resumed
|
|
216
244
|
IdempotencyKey.__send__(:within, :generator) { generate_candidate!(state, round, transition) }
|
|
217
245
|
IdempotencyKey.__send__(:within, :before_eval) { before_eval_rejection(state) }
|
|
218
246
|
end
|
|
219
247
|
|
|
248
|
+
# Everything this step's earlier rounds and attempts did belongs to a
|
|
249
|
+
# round the loop rejected or an attempt that failed, so a host sets
|
|
250
|
+
# aside what they staged here, before a later round builds on it, and
|
|
251
|
+
# may say what they were (`{ rejected_round: String }`), since the
|
|
252
|
+
# candidate does not carry its tools' work.
|
|
253
|
+
def run_before_generate(state)
|
|
254
|
+
state.told = nil
|
|
255
|
+
callback = state.config[:before_generate]
|
|
256
|
+
return unless callback
|
|
257
|
+
|
|
258
|
+
state.told = rejected_round_note(callback.call(state, @context))
|
|
259
|
+
nil
|
|
260
|
+
end
|
|
261
|
+
|
|
262
|
+
# The words under `rejected_round` of a Hash before_generate returns,
|
|
263
|
+
# copied and bounded as a message's are; anything else, or blank
|
|
264
|
+
# words, tells the round nothing.
|
|
265
|
+
def rejected_round_note(returned)
|
|
266
|
+
return unless returned.is_a?(Hash)
|
|
267
|
+
|
|
268
|
+
note = returned.key?(:rejected_round) ? returned[:rejected_round] : returned["rejected_round"]
|
|
269
|
+
return if note.nil?
|
|
270
|
+
raise WorkflowError, "before_generate's rejected_round must be a String" unless note.is_a?(String)
|
|
271
|
+
|
|
272
|
+
copy = StringSnapshot.copy(note, freeze: true)
|
|
273
|
+
if StringSnapshot.bytesize(copy) > MessageValueNormalizer::MAX_BYTES
|
|
274
|
+
raise WorkflowError, "before_generate's rejected_round is over #{MessageValueNormalizer::MAX_BYTES} bytes"
|
|
275
|
+
end
|
|
276
|
+
|
|
277
|
+
copy unless copy.strip.empty?
|
|
278
|
+
end
|
|
279
|
+
|
|
280
|
+
# A later round's draft replaces the one rejected before it, whose
|
|
281
|
+
# streamed text is withdrawn first (`reset(:rejected)`).
|
|
220
282
|
def generate_candidate!(state, round, transition)
|
|
221
|
-
|
|
283
|
+
withdraw_streamed(:rejected) if round.positive?
|
|
284
|
+
input = prepare_generator_input(state.prepared_input, round, state.candidate, state.feedback, state.told)
|
|
222
285
|
state.candidate = optimizer_call(transition, state, round, "generator", input)
|
|
223
286
|
end
|
|
224
287
|
|
|
288
|
+
# A verdict is never the step's words: a streamed step's sink hears its
|
|
289
|
+
# generator alone.
|
|
225
290
|
def evaluate_candidate(state, round, transition)
|
|
226
|
-
optimizer_call(transition, state, round, "evaluator", build_evaluator_input(state))
|
|
291
|
+
unstreamed { optimizer_call(transition, state, round, "evaluator", build_evaluator_input(state)) }
|
|
227
292
|
end
|
|
228
293
|
|
|
229
294
|
# evaluator_context: :inject_state appends the candidate as a
|
|
230
295
|
# user turn to the prepared_input the generator received, so the
|
|
231
|
-
# evaluator sees the same seed_messages + inject_state context.
|
|
232
|
-
#
|
|
296
|
+
# evaluator sees the same seed_messages + inject_state context. A
|
|
297
|
+
# callable builds the evaluator's messages itself from copies of the
|
|
298
|
+
# candidate and the context, checked as a step's input: is, so the
|
|
299
|
+
# evaluator can read its own part of the context and keep a stable
|
|
300
|
+
# prefix across rounds. Default nil keeps the legacy candidate-only
|
|
301
|
+
# payload.
|
|
233
302
|
def build_evaluator_input(state)
|
|
303
|
+
mode = state.config[:evaluator_context]
|
|
304
|
+
if mode.respond_to?(:call)
|
|
305
|
+
return checked_input(mode.call(snapshot_value(state.candidate), snapshot_value(@context)),
|
|
306
|
+
"evaluator_context:")
|
|
307
|
+
end
|
|
308
|
+
|
|
234
309
|
content = candidate_content(state.candidate)
|
|
235
|
-
return [{ role: :user, content: }] unless
|
|
310
|
+
return [{ role: :user, content: }] unless mode == :inject_state
|
|
236
311
|
|
|
237
312
|
prior = Array(state.prepared_input).dup
|
|
238
313
|
prior.push(role: :user, content:)
|
|
@@ -305,15 +380,16 @@ module Smith
|
|
|
305
380
|
nil
|
|
306
381
|
end
|
|
307
382
|
|
|
308
|
-
|
|
383
|
+
# A later round is told its rejected candidate, the evaluator's
|
|
384
|
+
# feedback and what before_generate said the round's tools left.
|
|
385
|
+
def prepare_generator_input(prepared_input, round, prior_candidate, feedback, told)
|
|
309
386
|
return prepared_input if round.zero?
|
|
310
387
|
|
|
388
|
+
content = "[smith:refinement-round] #{round + 1}\n[smith:evaluator-feedback]\n#{feedback}"
|
|
389
|
+
content += "\n[smith:rejected-round]\n#{told}" if told
|
|
311
390
|
(prepared_input&.dup || []).push(
|
|
312
391
|
{ role: :assistant, content: candidate_content(prior_candidate) },
|
|
313
|
-
{
|
|
314
|
-
role: :user,
|
|
315
|
-
content: "[smith:refinement-round] #{round + 1}\n[smith:evaluator-feedback]\n#{feedback}"
|
|
316
|
-
}
|
|
392
|
+
{ role: :user, content: }
|
|
317
393
|
)
|
|
318
394
|
end
|
|
319
395
|
|
|
@@ -47,6 +47,7 @@ module Smith
|
|
|
47
47
|
evaluator_schema: config.fetch(:evaluator_schema_label),
|
|
48
48
|
evaluator_context: config[:evaluator_context],
|
|
49
49
|
improvement_threshold: config[:improvement_threshold],
|
|
50
|
+
before_generate: config[:before_generate],
|
|
50
51
|
before_eval: config[:before_eval]
|
|
51
52
|
}
|
|
52
53
|
end
|
|
@@ -20,12 +20,17 @@ module Smith
|
|
|
20
20
|
next unless transition.stream
|
|
21
21
|
next missing_sink(transition) unless Smith.config.stream_sinks.key?(transition.stream)
|
|
22
22
|
|
|
23
|
-
whole_replies(transition) if responses_route?(transition
|
|
23
|
+
whole_replies(transition) if responses_route?(streamed_agent(transition))
|
|
24
24
|
end
|
|
25
25
|
end
|
|
26
26
|
|
|
27
27
|
private
|
|
28
28
|
|
|
29
|
+
# The agent whose text streams: an `optimize` step's generator.
|
|
30
|
+
def streamed_agent(transition)
|
|
31
|
+
transition.optimized? ? transition.optimization_config.fetch(:generator) : transition.agent_name
|
|
32
|
+
end
|
|
33
|
+
|
|
29
34
|
def responses_route?(agent)
|
|
30
35
|
agent_class = Agent::Registry.binding_for(agent)&.fetch(:agent_class)
|
|
31
36
|
return false unless agent_class.respond_to?(:chat_kwargs)
|
|
@@ -81,10 +86,10 @@ module Smith
|
|
|
81
86
|
def whole_replies(transition)
|
|
82
87
|
Diagnostic.new(
|
|
83
88
|
severity: :warning, code: :stream_whole_replies, transition: transition.name,
|
|
84
|
-
target: transition
|
|
89
|
+
target: streamed_agent(transition),
|
|
85
90
|
message: "Transition #{Reference.format(transition.name)} streams agent " \
|
|
86
|
-
"#{Reference.format(transition
|
|
87
|
-
"does not stream: its sink gets each reply as one delta.",
|
|
91
|
+
"#{Reference.format(streamed_agent(transition))}, whose calls go to OpenAI's Responses API, " \
|
|
92
|
+
"which does not stream: its sink gets each reply as one delta.",
|
|
88
93
|
suggestion: "Accept whole replies there, or keep the agent on Chat Completions " \
|
|
89
94
|
"(Smith.config.openai_api_mode = :off, and no openai_api_mode param)."
|
|
90
95
|
)
|
|
@@ -32,6 +32,7 @@ module Smith
|
|
|
32
32
|
evaluator_schema_label: label(config.fetch(:evaluator_schema)),
|
|
33
33
|
evaluator_context: callable_marker(config[:evaluator_context]),
|
|
34
34
|
improvement_threshold: config[:improvement_threshold],
|
|
35
|
+
before_generate: callable_marker(config[:before_generate]),
|
|
35
36
|
before_eval: callable_marker(config[:before_eval])
|
|
36
37
|
}
|
|
37
38
|
end
|
|
@@ -50,7 +50,7 @@ module Smith
|
|
|
50
50
|
@resolved_parallel_branch_count = nil
|
|
51
51
|
end
|
|
52
52
|
|
|
53
|
-
# Hooks that receive the live context (`before_eval`,
|
|
53
|
+
# Hooks that receive the live context (`before_generate`, `before_eval`,
|
|
54
54
|
# `after_completion`, guardrails) can write to it directly. At the end
|
|
55
55
|
# of the step every new top-level key must be a Symbol that an explicit
|
|
56
56
|
# `persist` list allows, and every new or replaced value takes the
|
|
@@ -88,11 +88,13 @@ module Smith
|
|
|
88
88
|
|
|
89
89
|
# A child that handled its failure through its own `on_failure` route
|
|
90
90
|
# has already applied its failure policy, so the parent sees a
|
|
91
|
-
# non-retryable WorkflowError, as before
|
|
91
|
+
# non-retryable WorkflowError, as before, its cause the child's own
|
|
92
|
+
# error, so a host can still read what the child failed on.
|
|
92
93
|
failed_step = child_result.steps.find { |s| s.key?(:error) }
|
|
93
94
|
if failed_step
|
|
94
95
|
raise WorkflowError,
|
|
95
|
-
"nested workflow failed: #{DiagnosticText.capture(failed_step[:error]&.message.to_s, max_bytes: 1024)}"
|
|
96
|
+
"nested workflow failed: #{DiagnosticText.capture(failed_step[:error]&.message.to_s, max_bytes: 1024)}",
|
|
97
|
+
cause: failed_step[:error]
|
|
96
98
|
end
|
|
97
99
|
|
|
98
100
|
child_result.output
|
|
@@ -2,11 +2,16 @@
|
|
|
2
2
|
|
|
3
3
|
module Smith
|
|
4
4
|
class Workflow
|
|
5
|
+
# What an optimize step's callables read: `round` is the round under
|
|
6
|
+
# way, from 0 in each attempt, the one its verdicts and captures name;
|
|
7
|
+
# `told`, what before_generate said the rejected round left, for the
|
|
8
|
+
# round under way.
|
|
5
9
|
OptimizationState = Struct.new(
|
|
6
|
-
:config, :prepared_input, :candidate, :feedback, :last_score, :generator_class, :evaluator_class, :evaluations
|
|
10
|
+
:config, :prepared_input, :candidate, :feedback, :last_score, :generator_class, :evaluator_class, :evaluations,
|
|
11
|
+
:round, :told
|
|
7
12
|
) do
|
|
8
13
|
def initialize(config, prepared_input)
|
|
9
|
-
super(config, prepared_input, nil, nil, nil, nil, nil, [].freeze)
|
|
14
|
+
super(config, prepared_input, nil, nil, nil, nil, nil, [].freeze, nil, nil)
|
|
10
15
|
end
|
|
11
16
|
end
|
|
12
17
|
end
|
|
@@ -17,12 +17,14 @@ module Smith
|
|
|
17
17
|
# and charged, once. The step's mode is asked at each call.
|
|
18
18
|
module OptimizerBatch
|
|
19
19
|
ROLES = %w[generator evaluator].freeze
|
|
20
|
-
PROGRESS_FIELDS = %w[candidate evaluations feedback last_score role round].freeze
|
|
20
|
+
PROGRESS_FIELDS = %w[candidate evaluations feedback last_score role round told].freeze
|
|
21
|
+
# A wait kept before the round carried what before_generate told it.
|
|
22
|
+
UNTOLD_FIELDS = (PROGRESS_FIELDS - %w[told]).freeze
|
|
21
23
|
RECORD_FIELDS = %w[round source verdict].freeze
|
|
22
24
|
SOURCES = %w[evaluator before_eval].freeze
|
|
23
25
|
ATTEMPT = /\A[1-9]\d*\z/
|
|
24
26
|
CAPTURED = :smith_optimizer_batch
|
|
25
|
-
private_constant :ROLES, :PROGRESS_FIELDS, :RECORD_FIELDS, :SOURCES, :ATTEMPT, :CAPTURED
|
|
27
|
+
private_constant :ROLES, :PROGRESS_FIELDS, :UNTOLD_FIELDS, :RECORD_FIELDS, :SOURCES, :ATTEMPT, :CAPTURED
|
|
26
28
|
|
|
27
29
|
private
|
|
28
30
|
|
|
@@ -70,7 +72,7 @@ module Smith
|
|
|
70
72
|
# What a delivery's loop goes on from, as JSON gives it.
|
|
71
73
|
def optimizer_progress(state, round, role)
|
|
72
74
|
progress = { "round" => round, "role" => role, "candidate" => state.candidate, "feedback" => state.feedback,
|
|
73
|
-
"last_score" => state.last_score, "evaluations" => kept_evaluations }
|
|
75
|
+
"last_score" => state.last_score, "evaluations" => kept_evaluations, "told" => state.told }
|
|
74
76
|
Batch.deep_freeze(JSON.parse(JSON.generate(progress)))
|
|
75
77
|
rescue JSON::GeneratorError, JSON::NestingError, Encoding::UndefinedConversionError
|
|
76
78
|
raise WorkflowError, "an optimize step waits for a batch only with JSON values for its candidate and feedback"
|
|
@@ -90,13 +92,17 @@ module Smith
|
|
|
90
92
|
progress = @pending_batch&.fetch("progress", nil) if delivering_batch?
|
|
91
93
|
return unless progress
|
|
92
94
|
|
|
93
|
-
state
|
|
94
|
-
snapshot_value(progress.values_at("candidate", "feedback", "last_score"))
|
|
95
|
+
restore_loop_state(state, progress)
|
|
95
96
|
restore_kept_evaluations(progress.fetch("evaluations"))
|
|
96
97
|
state.evaluations = @pending_evaluations.values.last.dup.freeze
|
|
97
98
|
progress.values_at("round", "role")
|
|
98
99
|
end
|
|
99
100
|
|
|
101
|
+
def restore_loop_state(state, progress)
|
|
102
|
+
state.candidate, state.feedback, state.last_score, state.told =
|
|
103
|
+
snapshot_value(progress.values_at("candidate", "feedback", "last_score", "told"))
|
|
104
|
+
end
|
|
105
|
+
|
|
100
106
|
# Kept verdicts back as the loop records them, in attempt order, the
|
|
101
107
|
# attempt under way last.
|
|
102
108
|
def restore_kept_evaluations(kept)
|
|
@@ -119,14 +125,20 @@ module Smith
|
|
|
119
125
|
end
|
|
120
126
|
|
|
121
127
|
# A stored pending batch's `progress` (BatchWait): a call of a
|
|
122
|
-
# round the step runs, a last score that is a number or none,
|
|
123
|
-
#
|
|
128
|
+
# round the step runs, a last score that is a number or none, words
|
|
129
|
+
# before_generate told the round or none, and kept verdicts of attempts
|
|
130
|
+
# up to the batch's.
|
|
124
131
|
def optimizer_progress?(transition, progress, attempt)
|
|
125
|
-
progress.is_a?(Hash) && progress.keys.sort
|
|
126
|
-
(progress
|
|
132
|
+
progress.is_a?(Hash) && [PROGRESS_FIELDS, UNTOLD_FIELDS].include?(progress.keys.sort) &&
|
|
133
|
+
optimizer_position?(transition, progress) && progress_values?(progress) &&
|
|
127
134
|
kept_evaluations?(progress["evaluations"], attempt)
|
|
128
135
|
end
|
|
129
136
|
|
|
137
|
+
def progress_values?(progress)
|
|
138
|
+
(progress["last_score"].nil? || progress["last_score"].is_a?(Numeric)) &&
|
|
139
|
+
(progress["told"].nil? || progress["told"].is_a?(String))
|
|
140
|
+
end
|
|
141
|
+
|
|
130
142
|
def optimizer_position?(transition, progress)
|
|
131
143
|
round = progress["round"]
|
|
132
144
|
ROLES.include?(progress["role"]) && round.is_a?(Integer) &&
|
|
@@ -74,14 +74,20 @@ module Smith
|
|
|
74
74
|
"agent in an isolated session and must declare input:"
|
|
75
75
|
end
|
|
76
76
|
|
|
77
|
-
# A non-empty Array of at most MessageBatch::MAX_MESSAGES user and
|
|
78
|
-
# assistant messages, bounded and JSON-shaped like session messages.
|
|
79
77
|
# The callable gets a copy of the context, so it cannot change the
|
|
80
78
|
# run's.
|
|
81
79
|
def step_input_messages(transition)
|
|
82
|
-
|
|
80
|
+
checked_input(transition.step_input.call(snapshot_value(@context)), "input:")
|
|
81
|
+
end
|
|
82
|
+
|
|
83
|
+
# A non-empty Array of at most MessageBatch::MAX_MESSAGES user and
|
|
84
|
+
# assistant messages, bounded and JSON-shaped like session messages, as
|
|
85
|
+
# a step's `input:` or an optimizer's callable `evaluator_context:`
|
|
86
|
+
# (`option`) returns them.
|
|
87
|
+
def checked_input(messages, option)
|
|
83
88
|
unless messages.is_a?(Array) && !messages.empty? && messages.length <= MessageBatch::MAX_MESSAGES
|
|
84
|
-
raise WorkflowError,
|
|
89
|
+
raise WorkflowError,
|
|
90
|
+
"#{option} must return a non-empty Array of at most #{MessageBatch::MAX_MESSAGES} messages"
|
|
85
91
|
end
|
|
86
92
|
|
|
87
93
|
MessageValueNormalizer.new(messages, label: "step input").call.map { |message| step_input_message(message) }
|
|
@@ -30,6 +30,15 @@ module Smith
|
|
|
30
30
|
@step_stream = nil
|
|
31
31
|
end
|
|
32
32
|
|
|
33
|
+
# Calls the block's agent unheard by the step's sink.
|
|
34
|
+
def unstreamed
|
|
35
|
+
stream = @step_stream
|
|
36
|
+
@step_stream = nil
|
|
37
|
+
yield
|
|
38
|
+
ensure
|
|
39
|
+
@step_stream = stream
|
|
40
|
+
end
|
|
41
|
+
|
|
33
42
|
def accept_streamed(session, output)
|
|
34
43
|
return session.finish(output) unless @persistence_key
|
|
35
44
|
|
|
@@ -127,9 +127,15 @@ module Smith
|
|
|
127
127
|
|
|
128
128
|
# `mode:` and `on_request_change:` as on `execute`: in batch mode each
|
|
129
129
|
# of the loop's calls is a batch request of its own (OptimizerBatch).
|
|
130
|
+
# `stream:` as on `execute`, for the generator's replies alone, round
|
|
131
|
+
# after round: a round the evaluator or `before_eval` rejects is
|
|
132
|
+
# withdrawn (`reset(:rejected)`), and the evaluator never streams.
|
|
133
|
+
# `before_generate:` runs before each round's generator is asked, so a
|
|
134
|
+
# host can set aside what an earlier round or attempt left.
|
|
130
135
|
def optimize(generator:, evaluator:, max_rounds:, evaluator_schema:,
|
|
131
136
|
improvement_threshold: nil,
|
|
132
137
|
evaluator_context: nil,
|
|
138
|
+
before_generate: nil,
|
|
133
139
|
before_eval: nil,
|
|
134
140
|
on_exhaustion: :raise,
|
|
135
141
|
on_converged: :raise,
|
|
@@ -137,15 +143,16 @@ module Smith
|
|
|
137
143
|
input: nil,
|
|
138
144
|
output_to: nil,
|
|
139
145
|
mode: nil,
|
|
140
|
-
on_request_change: nil
|
|
146
|
+
on_request_change: nil,
|
|
147
|
+
stream: nil)
|
|
141
148
|
validate_execution_primitive_conflict!("optimize")
|
|
142
149
|
assign_step_io!(input, output_to)
|
|
143
|
-
assign_batch_mode!(mode, on_request_change)
|
|
150
|
+
assign_batch_mode!(mode, on_request_change, stream: stream_name!(stream, {}, primitive: "optimize"))
|
|
144
151
|
validate_optimize_controls!(generator, evaluator, max_rounds, evaluator_schema)
|
|
145
152
|
validate_optimize_exit_modes!(on_exhaustion: on_exhaustion, on_converged: on_converged,
|
|
146
153
|
on_threshold: on_threshold)
|
|
147
154
|
validate_optimize_evaluator_context!(evaluator_context)
|
|
148
|
-
|
|
155
|
+
validate_optimize_callbacks!(before_generate:, before_eval:)
|
|
149
156
|
|
|
150
157
|
@optimization_config = {
|
|
151
158
|
generator: normalize_agent_reference!(generator, "optimizer generator"),
|
|
@@ -153,7 +160,7 @@ module Smith
|
|
|
153
160
|
max_rounds: max_rounds,
|
|
154
161
|
evaluator_schema: evaluator_schema, improvement_threshold: improvement_threshold,
|
|
155
162
|
evaluator_context: evaluator_context,
|
|
156
|
-
before_eval: before_eval,
|
|
163
|
+
before_generate: before_generate, before_eval: before_eval,
|
|
157
164
|
on_exhaustion: on_exhaustion,
|
|
158
165
|
on_converged: on_converged,
|
|
159
166
|
on_threshold: on_threshold
|
|
@@ -325,10 +332,12 @@ module Smith
|
|
|
325
332
|
mode
|
|
326
333
|
end
|
|
327
334
|
|
|
328
|
-
# `mode:` and `on_request_change:` of a step that has no
|
|
329
|
-
#
|
|
330
|
-
|
|
331
|
-
|
|
335
|
+
# `mode:` and `on_request_change:` of a step that has no parallel copies
|
|
336
|
+
# (`fan_out`, `optimize`), and the sink it streams to (`optimize`'s,
|
|
337
|
+
# named through stream_name!).
|
|
338
|
+
def assign_batch_mode!(mode, on_request_change, stream: nil)
|
|
339
|
+
@stream = stream
|
|
340
|
+
@batch_mode = batch_mode!(mode, stream:, parallel: false)
|
|
332
341
|
@on_request_change = request_change!(on_request_change)
|
|
333
342
|
end
|
|
334
343
|
|
|
@@ -346,10 +355,10 @@ module Smith
|
|
|
346
355
|
end
|
|
347
356
|
|
|
348
357
|
# One reply streams to one sink: a parallel step has several.
|
|
349
|
-
def stream_name!(stream, opts)
|
|
358
|
+
def stream_name!(stream, opts, primitive: "execute")
|
|
350
359
|
return if stream.nil?
|
|
351
|
-
raise WorkflowError, "
|
|
352
|
-
raise WorkflowError, "
|
|
360
|
+
raise WorkflowError, "#{primitive} stream: must name a sink with a Symbol" unless stream.is_a?(Symbol)
|
|
361
|
+
raise WorkflowError, "#{primitive} stream: is not available on a parallel step" if opts[:parallel] == true
|
|
353
362
|
|
|
354
363
|
stream
|
|
355
364
|
end
|
|
@@ -705,17 +714,18 @@ module Smith
|
|
|
705
714
|
end
|
|
706
715
|
|
|
707
716
|
def validate_optimize_evaluator_context!(evaluator_context)
|
|
708
|
-
return if evaluator_context.nil? || evaluator_context == :inject_state
|
|
717
|
+
return if evaluator_context.nil? || evaluator_context == :inject_state || evaluator_context.respond_to?(:call)
|
|
709
718
|
|
|
710
719
|
raise WorkflowError,
|
|
711
|
-
"optimize evaluator_context must be nil or
|
|
720
|
+
"optimize evaluator_context must be nil, :inject_state or a callable; got #{evaluator_context.inspect}"
|
|
712
721
|
end
|
|
713
722
|
|
|
714
|
-
def
|
|
715
|
-
|
|
716
|
-
|
|
723
|
+
def validate_optimize_callbacks!(**callbacks)
|
|
724
|
+
callbacks.each do |name, callback|
|
|
725
|
+
next if callback.nil? || callback.respond_to?(:call)
|
|
717
726
|
|
|
718
|
-
|
|
727
|
+
raise WorkflowError, "optimize #{name} must respond to :call; got #{callback.inspect}"
|
|
728
|
+
end
|
|
719
729
|
end
|
|
720
730
|
end
|
|
721
731
|
end
|
metadata
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
--- !ruby/object:Gem::Specification
|
|
2
2
|
name: smith-agents
|
|
3
3
|
version: !ruby/object:Gem::Version
|
|
4
|
-
version: 0.
|
|
4
|
+
version: 0.15.0
|
|
5
5
|
platform: ruby
|
|
6
6
|
authors:
|
|
7
7
|
- Samuel Ralak
|
|
@@ -178,6 +178,7 @@ files:
|
|
|
178
178
|
- lib/smith/agent/output_integrity.rb
|
|
179
179
|
- lib/smith/agent/output_policy.rb
|
|
180
180
|
- lib/smith/agent/output_recovery.rb
|
|
181
|
+
- lib/smith/agent/prompt_cache.rb
|
|
181
182
|
- lib/smith/agent/provider_attempt.rb
|
|
182
183
|
- lib/smith/agent/provider_call_timing.rb
|
|
183
184
|
- lib/smith/agent/provider_candidate_sequence.rb
|