smith-agents 0.15.0 → 0.16.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +4 -4
- data/CHANGELOG.md +63 -0
- data/README.md +1 -1
- data/docs/AGENTS.md +48 -0
- data/docs/BUDGETS.md +10 -0
- data/docs/CONFIGURATION.md +6 -1
- data/docs/ERRORS_AND_RETRIES.md +13 -0
- data/docs/PATTERNS.md +51 -0
- data/lib/smith/agent/image_request.rb +38 -0
- data/lib/smith/agent/lifecycle.rb +2 -0
- data/lib/smith/agent/output_recovery.rb +4 -0
- data/lib/smith/agent/paint_input.rb +42 -0
- data/lib/smith/agent/painted_answer.rb +70 -0
- data/lib/smith/agent/provider_call_timing.rb +2 -1
- data/lib/smith/agent/provider_completion.rb +1 -1
- data/lib/smith/agent/provider_failure_handling.rb +27 -5
- data/lib/smith/agent/provider_paint.rb +128 -0
- data/lib/smith/agent/provider_usage.rb +27 -2
- data/lib/smith/agent/usage_tracking.rb +3 -1
- data/lib/smith/agent.rb +3 -1
- data/lib/smith/budget/host_ledger.rb +3 -1
- data/lib/smith/budget/request_hold.rb +16 -0
- data/lib/smith/errors.rb +8 -0
- data/lib/smith/pricing/catalog_validation.rb +20 -1
- data/lib/smith/pricing/images.rb +29 -0
- data/lib/smith/pricing.rb +37 -16
- data/lib/smith/providers/request_holds.rb +29 -4
- data/lib/smith/providers/request_outcome.rb +39 -0
- data/lib/smith/providers/stop_reason.rb +4 -2
- data/lib/smith/version.rb +1 -1
- data/lib/smith/workflow/agent_result.rb +5 -1
- data/lib/smith/workflow/composite/effects.rb +3 -1
- data/lib/smith/workflow/execution.rb +1 -0
- data/lib/smith/workflow/failure_reconstructor.rb +1 -0
- data/lib/smith/workflow/failure_record.rb +7 -3
- data/lib/smith/workflow/failure_record_validator.rb +7 -7
- data/lib/smith/workflow/nested_execution.rb +14 -4
- data/lib/smith/workflow/nested_items_execution.rb +122 -0
- data/lib/smith/workflow/parallel/nested_execution.rb +4 -1
- data/lib/smith/workflow/parallel/root_execution.rb +2 -1
- data/lib/smith/workflow/parallel.rb +13 -5
- data/lib/smith/workflow/transition.rb +27 -2
- data/lib/smith/workflow/usage_entry.rb +5 -0
- data/lib/smith.rb +2 -0
- metadata +8 -1
checksums.yaml
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
---
|
|
2
2
|
SHA256:
|
|
3
|
-
metadata.gz:
|
|
4
|
-
data.tar.gz:
|
|
3
|
+
metadata.gz: becfd8870e143796ef08b737512b9ace6c0f08919c35716dbbd5ad769149286c
|
|
4
|
+
data.tar.gz: 8df467d0a83ad6c84028c1e4c2778ef41f1fd9ac1976a47ab43740df962d88b9
|
|
5
5
|
SHA512:
|
|
6
|
-
metadata.gz:
|
|
7
|
-
data.tar.gz:
|
|
6
|
+
metadata.gz: 3b067aa94dae4a63dd2de9b3494df7f8253f046ab12e43d7fe7a5ef31398053530381b779a67aa628f81b3f4690b930bca64614687939cb8ab9cb98d144617f9
|
|
7
|
+
data.tar.gz: ddc60cf738e866d30480488d234ead6ce2b74cd2ad414e8b0ded240688d0ce5ed26f41cdeff3850f4ba8a96d4ee3689527f1e04ce91b2d6708c5bf0a868735e1
|
data/CHANGELOG.md
CHANGED
|
@@ -4,6 +4,69 @@ 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
|
+
|
|
7
70
|
## [0.15.0] - 2026-11-22
|
|
8
71
|
|
|
9
72
|
### Added
|
data/README.md
CHANGED
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:
|
data/docs/BUDGETS.md
CHANGED
|
@@ -120,6 +120,16 @@ written; `cost` is nil for an unpriced
|
|
|
120
120
|
model, which runtime readiness warns of (`:budget_ledger_unpriced`, for every
|
|
121
121
|
agent that charges the ledger), and its readiness metrics name the scope keys.
|
|
122
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
|
+
|
|
123
133
|
A key is the provider attempt's `attempt_id` (as on its `:provider_call` trace)
|
|
124
134
|
and the request's round, `"<attempt_id>:<n>"`, and for a batch request its
|
|
125
135
|
`custom_id`. A batch request is held when its step captures it, at the batch
|
data/docs/CONFIGURATION.md
CHANGED
|
@@ -161,7 +161,12 @@ sits inside a tier.
|
|
|
161
161
|
Each entry, or each tier of a tiered entry, prices `input_cost_per_token` and
|
|
162
162
|
`output_cost_per_token`, and optionally `cache_read_cost_per_token` and
|
|
163
163
|
`cache_write_cost_per_token` for input read from or written to a prompt cache,
|
|
164
|
-
which providers report apart from uncached input. A
|
|
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
|
|
165
170
|
rate uses the entry's. An entry may also carry `batch_discount`, the fraction
|
|
166
171
|
taken off the cost of a call made in batch mode (`0.5` for half price). Cache
|
|
167
172
|
rates and the batch discount are configured per catalog and count as `0` when
|
data/docs/ERRORS_AND_RETRIES.md
CHANGED
|
@@ -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.
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Smith
|
|
4
|
+
class Agent
|
|
5
|
+
# An agent that answers with an image rather than words:
|
|
6
|
+
#
|
|
7
|
+
# image size: "1024x1024", quality: "low", background: "opaque", output_format: "png"
|
|
8
|
+
#
|
|
9
|
+
# Its attempt paints instead of chatting (ProviderPaint): its instructions
|
|
10
|
+
# and its input's text are the prompt, its input's images (Content.image)
|
|
11
|
+
# are drawn from in order, and its answer is the image, kept in the run's
|
|
12
|
+
# artifacts, as `Smith::Content.image(ref, media_type:)`. The options are
|
|
13
|
+
# the provider's own words for the request, passed as they are; the size
|
|
14
|
+
# and quality also name what the image writes in the pricing catalog
|
|
15
|
+
# (`image_output_tokens`), which its hold is priced from. An image agent
|
|
16
|
+
# takes no tools, output schema or thinking, and its step is neither
|
|
17
|
+
# streamed nor batched: none of them has a meaning for a picture.
|
|
18
|
+
module ImageRequest
|
|
19
|
+
MEDIA_TYPES = { "png" => "image/png", "webp" => "image/webp", "jpeg" => "image/jpeg" }.freeze
|
|
20
|
+
|
|
21
|
+
def image(size:, quality:, background: nil, output_format: "png")
|
|
22
|
+
options = { size:, quality:, background: }
|
|
23
|
+
named = options.compact.all? { |_, value| value.is_a?(String) && !value.strip.empty? }
|
|
24
|
+
raise ArgumentError, "image size:, quality: and background: are the provider's words, as Strings" unless
|
|
25
|
+
named && size && quality
|
|
26
|
+
unless MEDIA_TYPES.key?(output_format)
|
|
27
|
+
raise ArgumentError, "image output_format: is one of #{MEDIA_TYPES.keys.join(", ")}"
|
|
28
|
+
end
|
|
29
|
+
|
|
30
|
+
@image_request = { **options, output_format: }.compact.freeze
|
|
31
|
+
end
|
|
32
|
+
|
|
33
|
+
def image_request = @image_request
|
|
34
|
+
|
|
35
|
+
def image_media_type = image_request && MEDIA_TYPES.fetch(image_request.fetch(:output_format))
|
|
36
|
+
end
|
|
37
|
+
end
|
|
38
|
+
end
|
|
@@ -2,12 +2,14 @@
|
|
|
2
2
|
|
|
3
3
|
require_relative "output_integrity"
|
|
4
4
|
require_relative "provider_completion"
|
|
5
|
+
require_relative "provider_paint"
|
|
5
6
|
require_relative "usage_tracking"
|
|
6
7
|
|
|
7
8
|
module Smith
|
|
8
9
|
class Agent
|
|
9
10
|
module Lifecycle
|
|
10
11
|
include ProviderCompletion
|
|
12
|
+
include ProviderPaint
|
|
11
13
|
include UsageTracking
|
|
12
14
|
include OutputIntegrity
|
|
13
15
|
|
|
@@ -109,8 +109,12 @@ module Smith
|
|
|
109
109
|
fail_follow_up(plan, attempt, pending)
|
|
110
110
|
end
|
|
111
111
|
|
|
112
|
+
# A follow-up whose outcome is uncertain says so, never the failure it
|
|
113
|
+
# was making up for, so nothing asks for it again.
|
|
112
114
|
def fail_follow_up(plan, attempt, pending)
|
|
113
115
|
account_failed_attempt(attempt.error, attempt.model_reference, plan.agent_class, attempt_id: attempt.attempt_id)
|
|
116
|
+
raise attempt.error if Smith::Errors.retry_forbidden?(attempt.error)
|
|
117
|
+
|
|
114
118
|
raise pending, cause: attempt.error
|
|
115
119
|
end
|
|
116
120
|
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "stringio"
|
|
4
|
+
|
|
5
|
+
module Smith
|
|
6
|
+
class Agent
|
|
7
|
+
# What an image agent's chat asks the provider to paint: its system and
|
|
8
|
+
# user text joined, in order, is the prompt, and the images its content
|
|
9
|
+
# parts attach are drawn from, in order. A refinement round's earlier
|
|
10
|
+
# answer (an assistant turn) is not sent; the feedback after it is.
|
|
11
|
+
module PaintInput
|
|
12
|
+
# Bytes Faraday sends as a named file part, so the provider sees the
|
|
13
|
+
# image's name and kind.
|
|
14
|
+
class NamedImage < StringIO
|
|
15
|
+
attr_reader :path
|
|
16
|
+
|
|
17
|
+
def initialize(bytes, name)
|
|
18
|
+
super(bytes)
|
|
19
|
+
@path = name
|
|
20
|
+
end
|
|
21
|
+
end
|
|
22
|
+
|
|
23
|
+
module_function
|
|
24
|
+
|
|
25
|
+
# [prompt, images]
|
|
26
|
+
def of(messages)
|
|
27
|
+
texts = []
|
|
28
|
+
images = []
|
|
29
|
+
messages.each { |message| add(message, texts, images) unless message.role.to_s == "assistant" }
|
|
30
|
+
[texts.reject { _1.strip.empty? }.join("\n\n"), images]
|
|
31
|
+
end
|
|
32
|
+
|
|
33
|
+
def add(message, texts, images)
|
|
34
|
+
content = message.content
|
|
35
|
+
return texts << content.to_s unless content.is_a?(::RubyLLM::Content)
|
|
36
|
+
|
|
37
|
+
texts << content.text.to_s
|
|
38
|
+
content.attachments.each { |attachment| images << NamedImage.new(attachment.content, attachment.filename) }
|
|
39
|
+
end
|
|
40
|
+
end
|
|
41
|
+
end
|
|
42
|
+
end
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Smith
|
|
4
|
+
class Agent
|
|
5
|
+
# What a paint answered, as an attempt's completion: the image kept in the
|
|
6
|
+
# run's artifacts as a content part with the usage it reported, or, for a
|
|
7
|
+
# moderation block, a refused response that cost nothing. An image drawn
|
|
8
|
+
# and billed that cannot be kept (none in the answer, or a store that
|
|
9
|
+
# failed) raises with its usage, so the usage is recorded before the
|
|
10
|
+
# error goes on.
|
|
11
|
+
module PaintedAnswer
|
|
12
|
+
Painted = Data.define(:content)
|
|
13
|
+
MODERATION_BLOCKED = "moderation_blocked"
|
|
14
|
+
private_constant :Painted
|
|
15
|
+
|
|
16
|
+
# An image drawn and billed that could not be kept: its usage, and why.
|
|
17
|
+
class Unkept < StandardError
|
|
18
|
+
attr_reader :usage, :reason
|
|
19
|
+
|
|
20
|
+
def initialize(usage, reason)
|
|
21
|
+
@usage = usage
|
|
22
|
+
@reason = reason
|
|
23
|
+
super(reason.message)
|
|
24
|
+
end
|
|
25
|
+
end
|
|
26
|
+
private_constant :Unkept
|
|
27
|
+
|
|
28
|
+
private
|
|
29
|
+
|
|
30
|
+
# An answer with no image is an output failure, billed and never asked
|
|
31
|
+
# for again; one the store cannot keep goes on as the store's error.
|
|
32
|
+
def painted_completion(agent_class, image)
|
|
33
|
+
usage = ProviderUsage.from_image(image.usage)
|
|
34
|
+
media_type = agent_class.image_media_type
|
|
35
|
+
ref = kept(agent_class, image, usage, media_type)
|
|
36
|
+
Completion.new(response: Painted.new(Content.image(ref, media_type:)), provider_usages: [usage].compact,
|
|
37
|
+
usage_complete: !usage.nil?)
|
|
38
|
+
end
|
|
39
|
+
|
|
40
|
+
def kept(agent_class, image, usage, media_type)
|
|
41
|
+
bytes = image.data&.unpack1("m")
|
|
42
|
+
if bytes.nil? || bytes.empty?
|
|
43
|
+
raise Unkept.new(usage, OutputInvalid.new(agent_name: agent_class.register_as, model_used: image.model_id,
|
|
44
|
+
problems: ["the answer held no image"]))
|
|
45
|
+
end
|
|
46
|
+
|
|
47
|
+
Smith.artifacts.store(bytes, content_type: media_type)
|
|
48
|
+
rescue Unkept
|
|
49
|
+
raise
|
|
50
|
+
rescue StandardError => e
|
|
51
|
+
raise Unkept.new(usage, e)
|
|
52
|
+
end
|
|
53
|
+
|
|
54
|
+
# Nothing was drawn and nothing was billed.
|
|
55
|
+
def refused_completion
|
|
56
|
+
usage = ProviderUsage.new(input_tokens: 0, output_tokens: 0, stop_reason: MODERATION_BLOCKED)
|
|
57
|
+
Completion.new(response: Painted.new(nil), provider_usages: [usage], usage_complete: true,
|
|
58
|
+
response_facts: { stop_reason: MODERATION_BLOCKED })
|
|
59
|
+
end
|
|
60
|
+
|
|
61
|
+
def moderation_blocked?(error)
|
|
62
|
+
body = error.response.body if error.response.respond_to?(:body)
|
|
63
|
+
body = JSON.parse(body) if body.is_a?(String)
|
|
64
|
+
body.is_a?(Hash) && body.dig("error", "code") == MODERATION_BLOCKED
|
|
65
|
+
rescue JSON::ParserError
|
|
66
|
+
false
|
|
67
|
+
end
|
|
68
|
+
end
|
|
69
|
+
end
|
|
70
|
+
end
|
|
@@ -74,7 +74,8 @@ module Smith
|
|
|
74
74
|
{
|
|
75
75
|
input_tokens: usage.input_tokens, output_tokens: usage.output_tokens,
|
|
76
76
|
cache_read_tokens: usage.cache_read_tokens, cache_write_tokens: usage.cache_write_tokens,
|
|
77
|
-
thinking_tokens: usage.thinking_tokens,
|
|
77
|
+
thinking_tokens: usage.thinking_tokens, image_input_tokens: usage.image_input_tokens,
|
|
78
|
+
image_output_tokens: usage.image_output_tokens, stop_reason: usage.stop_reason,
|
|
78
79
|
provider_message_id: usage.provider_message_id, mode: usage.mode
|
|
79
80
|
}
|
|
80
81
|
end
|
|
@@ -66,7 +66,7 @@ module Smith
|
|
|
66
66
|
fallback_available: candidates.fallback_available?, attempt_id: attempt.attempt_id)
|
|
67
67
|
set_aside.concat(attempt.captures)
|
|
68
68
|
rescue StandardError => e
|
|
69
|
-
raise if interrupted.nil? || Interruptions.find(e)
|
|
69
|
+
raise if interrupted.nil? || Interruptions.find(e) || Smith::Errors.retry_forbidden?(e)
|
|
70
70
|
|
|
71
71
|
raise terminal_provider_error(interrupted.error, interrupted.model_reference), cause: interrupted.error
|
|
72
72
|
end
|
|
@@ -21,20 +21,34 @@ module Smith
|
|
|
21
21
|
|
|
22
22
|
private
|
|
23
23
|
|
|
24
|
+
# A request whose outcome is uncertain is never sent again, to this
|
|
25
|
+
# model or another.
|
|
24
26
|
def handle_provider_failure!(error, model_reference, agent_class, fallback_available:, attempt_id: nil)
|
|
25
27
|
account_failed_attempt(error, model_reference, agent_class, attempt_id:)
|
|
28
|
+
raise error if error.is_a?(Smith::RequestOutcomeUncertain)
|
|
29
|
+
|
|
26
30
|
if uncertain_tool_calls?
|
|
27
31
|
raise Smith::ToolOutcomeUncertain.new(
|
|
28
32
|
"provider failed after tool execution began; retry or fallback could replay an uncertain outcome"
|
|
29
33
|
), cause: error
|
|
30
34
|
end
|
|
31
|
-
return if
|
|
35
|
+
return if goes_again?(error, agent_class) && fallback_available
|
|
36
|
+
|
|
37
|
+
raise terminal_provider_error(error, model_reference, agent_class), cause: error
|
|
38
|
+
end
|
|
39
|
+
|
|
40
|
+
# An image's request goes again, to another model or the step's retry,
|
|
41
|
+
# only after a throttle or a refusal of the account, the model or the
|
|
42
|
+
# content: a server's error may have done and billed the work.
|
|
43
|
+
def goes_again?(error, agent_class)
|
|
44
|
+
return fallback_eligible?(error) unless agent_class.image_request
|
|
32
45
|
|
|
33
|
-
|
|
46
|
+
throttled?(error) || provider_account_failure?(error) ||
|
|
47
|
+
model_permission_failure?(error) || model_unavailable?(error) || unsupported_content?(error)
|
|
34
48
|
end
|
|
35
49
|
|
|
36
50
|
def provider_failure?(error)
|
|
37
|
-
error.is_a?(RubyLLM::Error) ||
|
|
51
|
+
error.is_a?(RubyLLM::Error) || error.is_a?(Smith::RequestOutcomeUncertain) ||
|
|
38
52
|
(defined?(RubyLLM::ModelNotFoundError) && error.is_a?(RubyLLM::ModelNotFoundError)) ||
|
|
39
53
|
error.is_a?(Faraday::TimeoutError) ||
|
|
40
54
|
error.is_a?(Faraday::ConnectionFailed)
|
|
@@ -63,6 +77,14 @@ module Smith
|
|
|
63
77
|
TRANSIENT_ERRORS.any? { |error_class| error.is_a?(error_class) }
|
|
64
78
|
end
|
|
65
79
|
|
|
80
|
+
def throttled?(error) = error.is_a?(RubyLLM::RateLimitError)
|
|
81
|
+
|
|
82
|
+
# A provider that struggled leaves the step its retries, but for an
|
|
83
|
+
# image's request only a throttle does (`goes_again?`).
|
|
84
|
+
def step_may_retry?(error, agent_class)
|
|
85
|
+
(transient_failure?(error) || transport_failure?(error)) && (!agent_class&.image_request || throttled?(error))
|
|
86
|
+
end
|
|
87
|
+
|
|
66
88
|
def transport_failure?(error)
|
|
67
89
|
error.is_a?(Faraday::TimeoutError) || error.is_a?(Faraday::ConnectionFailed)
|
|
68
90
|
end
|
|
@@ -81,8 +103,8 @@ module Smith
|
|
|
81
103
|
false
|
|
82
104
|
end
|
|
83
105
|
|
|
84
|
-
def terminal_provider_error(error, model_reference)
|
|
85
|
-
return Smith::AgentError.new(error.message) if
|
|
106
|
+
def terminal_provider_error(error, model_reference, agent_class = nil)
|
|
107
|
+
return Smith::AgentError.new(error.message) if step_may_retry?(error, agent_class)
|
|
86
108
|
if unsupported_content?(error)
|
|
87
109
|
return Smith::ContentUnavailable.new("#{model_reference} takes none of this content: #{error.message}")
|
|
88
110
|
end
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require_relative "paint_input"
|
|
4
|
+
require_relative "painted_answer"
|
|
5
|
+
|
|
6
|
+
module Smith
|
|
7
|
+
class Agent
|
|
8
|
+
# An image agent's attempt (ImageRequest): its chat is built as any
|
|
9
|
+
# attempt's is (instructions, inputs, content parts), then painted from
|
|
10
|
+
# instead of completed (PaintInput). The request's options go as its
|
|
11
|
+
# params, the size among them, since RubyLLM's edit payload sends its
|
|
12
|
+
# params and not its size.
|
|
13
|
+
#
|
|
14
|
+
# Each request is sent once: the chat's config is copied with no HTTP
|
|
15
|
+
# retries, so a provider that billed a request is never asked for it
|
|
16
|
+
# again behind Smith's back, and only a refusal or a throttle goes again
|
|
17
|
+
# (ProviderFailureHandling). A moderation block is a refused response,
|
|
18
|
+
# which costs nothing and goes to the agent's on_refusal (OutputRefused
|
|
19
|
+
# by default). A request sent whose answer never came (a read timeout, a
|
|
20
|
+
# connection lost; Providers::RequestOutcome) raises
|
|
21
|
+
# RequestOutcomeUncertain, which no retry or fallback takes up. The
|
|
22
|
+
# image is kept in the run's artifacts and answered as a content part.
|
|
23
|
+
# A paint keeps no response memo (an image is too large to keep twice),
|
|
24
|
+
# so a step a crash replays paints again: a host that pays for images
|
|
25
|
+
# runs in strict idempotency, where such a step fails instead.
|
|
26
|
+
module ProviderPaint
|
|
27
|
+
include PaintedAnswer
|
|
28
|
+
|
|
29
|
+
private
|
|
30
|
+
|
|
31
|
+
# Every attempt an image agent makes (a candidate, a refusal's fallback,
|
|
32
|
+
# a retry) paints; any other agent's completes (ProviderCompletion).
|
|
33
|
+
def attempt_model(agent_class, prepared_input, model_reference, shape:, attempt_index:)
|
|
34
|
+
return super unless agent_class.image_request
|
|
35
|
+
|
|
36
|
+
paint_model(agent_class, prepared_input, model_reference, attempt_index:)
|
|
37
|
+
end
|
|
38
|
+
|
|
39
|
+
def check_image_agent!(agent_class)
|
|
40
|
+
refused = image_refusals(agent_class).select { |_, given| given }.keys
|
|
41
|
+
return if refused.empty?
|
|
42
|
+
|
|
43
|
+
raise WorkflowError, "#{agent_class} answers with an image, which takes no #{refused.join(", ")}"
|
|
44
|
+
end
|
|
45
|
+
|
|
46
|
+
def image_refusals(agent_class)
|
|
47
|
+
{
|
|
48
|
+
"tools" => !Array(agent_class.tools).empty?,
|
|
49
|
+
"an output schema" => !(agent_class.output_schema || agent_class.schema || agent_class.output_contract).nil?,
|
|
50
|
+
"thinking" => !agent_class.thinking.nil?,
|
|
51
|
+
"a streamed step" => !@step_stream.nil?,
|
|
52
|
+
"a batch" => @batch_capturing == true
|
|
53
|
+
}
|
|
54
|
+
end
|
|
55
|
+
|
|
56
|
+
# Every attempt of an image agent, a refusal's fallback included.
|
|
57
|
+
def paint_model(agent_class, prepared_input, model_reference, attempt_index:)
|
|
58
|
+
check_image_agent!(agent_class)
|
|
59
|
+
painting_attempt(agent_class, prepared_input, model_reference,
|
|
60
|
+
{ attempt_id: SecureRandom.uuid, attempt_index:, agent_name: agent_class.register_as })
|
|
61
|
+
end
|
|
62
|
+
|
|
63
|
+
def painting_attempt(agent_class, prepared_input, model_reference, facts)
|
|
64
|
+
chat = painting_chat(agent_class, prepared_input, model_reference)
|
|
65
|
+
observed = observed_model_reference(chat, fallback: model_reference)
|
|
66
|
+
timer = ProviderCallTiming::Timer.start
|
|
67
|
+
completion = painted(agent_class, chat, observed, facts[:attempt_id])
|
|
68
|
+
completed_provider_attempt(completion, observed, timer.stop, facts)
|
|
69
|
+
rescue StandardError => e
|
|
70
|
+
failed_paint(agent_class, e, observed || model_reference, timer&.stop, facts)
|
|
71
|
+
end
|
|
72
|
+
|
|
73
|
+
# A paint's failure traced as any attempt's: one whose outcome is
|
|
74
|
+
# uncertain is raised as RequestOutcomeUncertain, its cause the
|
|
75
|
+
# transport's error; an image that was drawn and billed but could not be
|
|
76
|
+
# kept has its usage recorded before its error goes on.
|
|
77
|
+
def failed_paint(agent_class, error, model_reference, timer, facts)
|
|
78
|
+
usages = error.is_a?(Unkept) ? [error.usage].compact : []
|
|
79
|
+
record_billed_usages(agent_class, usages, :partial_attempt, model_reference, attempt_id: facts[:attempt_id])
|
|
80
|
+
error = error.reason if error.is_a?(Unkept)
|
|
81
|
+
error = outcome_uncertain(error) if Providers::RequestOutcome.uncertain?(error)
|
|
82
|
+
attempt = failed_provider_attempt(error, model_reference, timer, facts, usages)
|
|
83
|
+
raise error unless provider_failure?(error) || unsupported_content?(error)
|
|
84
|
+
|
|
85
|
+
attempt
|
|
86
|
+
end
|
|
87
|
+
|
|
88
|
+
def painting_chat(agent_class, prepared_input, model_reference)
|
|
89
|
+
chat = agent_class.chat(**model_reference.chat_options, **bridge_workflow_inputs(agent_class))
|
|
90
|
+
chat = sent_once(chat, agent_class) if chat.respond_to?(:with_context) && chat.respond_to?(:with_model)
|
|
91
|
+
provider = observed_model_reference(chat, fallback: model_reference).provider
|
|
92
|
+
add_prepared_input(chat, prepared_input, provider,
|
|
93
|
+
ProviderRequest::Shape.new(output_schema: nil, output_limit: nil, prompt_cache: :none))
|
|
94
|
+
chat
|
|
95
|
+
end
|
|
96
|
+
|
|
97
|
+
def painted(agent_class, chat, model_reference, attempt_id)
|
|
98
|
+
prompt, images = PaintInput.of(chat.messages)
|
|
99
|
+
request = agent_class.image_request
|
|
100
|
+
provider = chat_provider(chat)
|
|
101
|
+
image = held_paint(provider, attempt_id) do
|
|
102
|
+
provider.paint(prompt, model: model_reference.model_id, size: request.fetch(:size),
|
|
103
|
+
with: images.empty? ? nil : images, params: request)
|
|
104
|
+
end
|
|
105
|
+
painted_completion(agent_class, image)
|
|
106
|
+
rescue ::RubyLLM::BadRequestError => e
|
|
107
|
+
raise unless moderation_blocked?(e)
|
|
108
|
+
|
|
109
|
+
refused_completion
|
|
110
|
+
end
|
|
111
|
+
|
|
112
|
+
def held_paint(provider, attempt_id, &paint)
|
|
113
|
+
ledger = run_budget_ledger
|
|
114
|
+
return paint.call unless ledger
|
|
115
|
+
|
|
116
|
+
Providers::RequestHolds.within(provider, ledger, attempt_id, &paint)
|
|
117
|
+
end
|
|
118
|
+
|
|
119
|
+
# Raised inside the transport error's rescue, so it is the cause.
|
|
120
|
+
def outcome_uncertain(error)
|
|
121
|
+
raise RequestOutcomeUncertain,
|
|
122
|
+
"the request was sent and no answer came (#{error.class}); it may have been billed"
|
|
123
|
+
rescue RequestOutcomeUncertain => e
|
|
124
|
+
e
|
|
125
|
+
end
|
|
126
|
+
end
|
|
127
|
+
end
|
|
128
|
+
end
|