squishling 0.4.0 → 0.5.1
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 +149 -0
- data/README.md +26 -10
- data/docs/adapters.md +257 -0
- data/docs/configuration.md +54 -19
- data/docs/failures.md +170 -22
- data/docs/harnesses.md +39 -15
- data/docs/measuring-tokens.md +12 -6
- data/docs/observers.md +3 -3
- data/docs/routing.md +14 -3
- data/docs/schemas.md +24 -2
- data/docs/testing.md +187 -0
- data/docs/verifying.md +86 -0
- data/lib/squishling/adapter/error_body.rb +54 -0
- data/lib/squishling/adapter.rb +328 -0
- data/lib/squishling/adapters/openai_compatible.rb +311 -0
- data/lib/squishling/adapters/openai_options.rb +114 -0
- data/lib/squishling/adapters/openai_transport.rb +123 -0
- data/lib/squishling/adapters/ruby_llm.rb +229 -0
- data/lib/squishling/budget.rb +71 -0
- data/lib/squishling/class_methods.rb +43 -7
- data/lib/squishling/class_registry.rb +63 -0
- data/lib/squishling/configuration.rb +58 -6
- data/lib/squishling/definition.rb +90 -16
- data/lib/squishling/errors.rb +94 -7
- data/lib/squishling/harness/judged_squishsum.rb +2 -2
- data/lib/squishling/harness/option_types.rb +2 -1
- data/lib/squishling/harness/registry.rb +8 -36
- data/lib/squishling/invoker.rb +44 -14
- data/lib/squishling/judge.rb +16 -3
- data/lib/squishling/llm_client.rb +66 -132
- data/lib/squishling/model_path.rb +60 -13
- data/lib/squishling/named_registry.rb +64 -0
- data/lib/squishling/observer.rb +13 -4
- data/lib/squishling/output_check.rb +13 -9
- data/lib/squishling/params.rb +7 -24
- data/lib/squishling/railtie.rb +10 -0
- data/lib/squishling/result.rb +50 -16
- data/lib/squishling/rotation.rb +5 -0
- data/lib/squishling/router.rb +3 -2
- data/lib/squishling/rspec.rb +18 -0
- data/lib/squishling/run/messages.rb +40 -3
- data/lib/squishling/run/rejections.rb +43 -0
- data/lib/squishling/run/reports.rb +63 -0
- data/lib/squishling/run.rb +60 -53
- data/lib/squishling/schema.rb +50 -9
- data/lib/squishling/secret.rb +45 -0
- data/lib/squishling/squawk.rb +37 -4
- data/lib/squishling/tasks/squishling.rake +18 -0
- data/lib/squishling/testing/adapter.rb +194 -0
- data/lib/squishling/testing/checks.rb +39 -0
- data/lib/squishling/testing/direct.rb +41 -0
- data/lib/squishling/testing/errors.rb +18 -0
- data/lib/squishling/testing/fixtures.rb +206 -0
- data/lib/squishling/testing/helpers.rb +71 -0
- data/lib/squishling/testing/minitest.rb +32 -0
- data/lib/squishling/testing/observer.rb +31 -0
- data/lib/squishling/testing/reply.rb +60 -0
- data/lib/squishling/testing/request.rb +75 -0
- data/lib/squishling/testing/rspec.rb +30 -0
- data/lib/squishling/testing/script.rb +189 -0
- data/lib/squishling/testing/state.rb +74 -0
- data/lib/squishling/testing/stubs.rb +112 -0
- data/lib/squishling/testing.rb +126 -0
- data/lib/squishling/verification.rb +39 -0
- data/lib/squishling/verifier.rb +179 -0
- data/lib/squishling/version.rb +1 -1
- data/lib/squishling/wrapper.rb +19 -1
- data/lib/squishling.rb +60 -4
- metadata +43 -21
|
@@ -5,6 +5,7 @@ module Squishling
|
|
|
5
5
|
# method's squish_validate check.
|
|
6
6
|
class OutputCheck
|
|
7
7
|
MAX_ERRORS = 20
|
|
8
|
+
EMPTY = "response was empty"
|
|
8
9
|
UNREPRESENTABLE = "response contained a value JSON can't represent (such as Infinity or invalid UTF-8)"
|
|
9
10
|
|
|
10
11
|
def initialize(definition, receiver, inputs)
|
|
@@ -13,32 +14,34 @@ module Squishling
|
|
|
13
14
|
@inputs = inputs
|
|
14
15
|
end
|
|
15
16
|
|
|
16
|
-
# Parses and validates a response: [typed result, []] when it passes, [nil or result,
|
|
17
|
+
# Parses and validates a response: [typed result, []] when it passes, [nil or result, error Details] otherwise.
|
|
17
18
|
# The judge's role skips squish_validate, which checks the operation's output, not a verdict.
|
|
18
19
|
def call(content, prompt)
|
|
19
20
|
data, errors = parse(content)
|
|
20
|
-
errors = prompt.schema.validate(data) if errors.empty?
|
|
21
|
+
errors = InvalidOutputError::Detail.from(prompt.schema.validate(data), :schema) if errors.empty?
|
|
21
22
|
return [nil, cap(errors)] if errors.any?
|
|
22
23
|
|
|
23
24
|
result = prompt.schema.build(data, squished: true)
|
|
24
|
-
[result, prompt.role == :judge ? [] : validator_errors(result)]
|
|
25
|
+
[result, prompt.role == :judge ? [] : InvalidOutputError::Detail.from(validator_errors(result), :validator)]
|
|
25
26
|
end
|
|
26
27
|
|
|
27
28
|
private
|
|
28
29
|
|
|
29
|
-
#
|
|
30
|
+
# An adapter may parse structured output itself (RubyLLM does) and leave the raw string when that fails, so
|
|
30
31
|
# content is a Hash on success, or a String/nil when the model refused, was cut off, or
|
|
31
32
|
# ignored the schema.
|
|
32
33
|
def parse(content)
|
|
33
|
-
return [nil, [UNREPRESENTABLE]] if content.is_a?(String) && !content.valid_encoding?
|
|
34
|
-
return [nil, [
|
|
34
|
+
return [nil, [parse_error(UNREPRESENTABLE)]] if content.is_a?(String) && !content.valid_encoding?
|
|
35
|
+
return [nil, [parse_error(EMPTY)]] if content.nil? || (content.is_a?(String) && content.strip.empty?)
|
|
35
36
|
|
|
36
37
|
data = content.is_a?(String) ? JSON.parse(strip_code_fence(content)) : content
|
|
37
|
-
representable?(data) ? [data, []] : [nil, [UNREPRESENTABLE]]
|
|
38
|
+
representable?(data) ? [data, []] : [nil, [parse_error(UNREPRESENTABLE)]]
|
|
38
39
|
rescue JSON::ParserError => e
|
|
39
|
-
[nil, ["response was not valid JSON#{parse_position(e)}"]]
|
|
40
|
+
[nil, [parse_error("response was not valid JSON#{parse_position(e)}")]]
|
|
40
41
|
end
|
|
41
42
|
|
|
43
|
+
def parse_error(message) = InvalidOutputError::Detail.new(message, :parse)
|
|
44
|
+
|
|
42
45
|
# JSON.parse turns an out-of-range number such as 1e400 into Infinity, and accepts invalid UTF-8 in a string.
|
|
43
46
|
# Both can satisfy the schema but can't be serialized again (and the deterministic path rejects them), so
|
|
44
47
|
# they are invalid output.
|
|
@@ -54,7 +57,8 @@ module Squishling
|
|
|
54
57
|
def cap(errors)
|
|
55
58
|
return errors if errors.size <= MAX_ERRORS
|
|
56
59
|
|
|
57
|
-
|
|
60
|
+
notice = "... and #{errors.size - MAX_ERRORS} more errors"
|
|
61
|
+
errors.first(MAX_ERRORS) + [InvalidOutputError::Detail.new(notice, :squishling)]
|
|
58
62
|
end
|
|
59
63
|
|
|
60
64
|
# The parser's message quotes a snippet of the response, which must not reach error messages or logs
|
data/lib/squishling/params.rb
CHANGED
|
@@ -5,20 +5,19 @@ module Squishling
|
|
|
5
5
|
module Params
|
|
6
6
|
THINKING_KEYS = %i[effort budget display].freeze
|
|
7
7
|
|
|
8
|
-
# Request keys Squishling or
|
|
9
|
-
#
|
|
10
|
-
# or the strict output format.
|
|
8
|
+
# Request keys Squishling or the adapter own. Provider params are merged into the request alongside what the
|
|
9
|
+
# adapter builds, so these would silently replace the model, the conversation, or the strict output format.
|
|
11
10
|
RESERVED_KEYS = %i[
|
|
12
11
|
model messages input inputs instructions contents system system_instruction systemInstruction cachedContent
|
|
13
|
-
stream stream_options store include response_format text output_config outputConfig tools
|
|
14
|
-
toolConfig tool_config schema
|
|
12
|
+
cached_content stream stream_options store include response_format text output_config outputConfig tools
|
|
13
|
+
tool_choice toolConfig tool_config schema functions function_call
|
|
15
14
|
].freeze
|
|
16
15
|
|
|
17
16
|
# Some protocols carry the structured-output format (or tool selection) inside a container that is
|
|
18
17
|
# itself allowed, because it also holds ordinary settings (Gemini's topK, Mistral's top_p, ...). RubyLLM
|
|
19
18
|
# deep-merges provider options, so these nested keys would override the strict format just like the
|
|
20
19
|
# top-level ones. Re-check each protocol's render_payload (ruby_llm protocols/*/chat.rb) on every
|
|
21
|
-
# ruby_llm upgrade.
|
|
20
|
+
# ruby_llm upgrade (the RubyLLM adapter is where they matter).
|
|
22
21
|
GENERATION_CONFIG_RESERVED_KEYS = %i[
|
|
23
22
|
responseMimeType response_mime_type responseSchema response_schema responseJsonSchema response_json_schema
|
|
24
23
|
response_format tools tool_choice toolConfig tool_config
|
|
@@ -49,11 +48,11 @@ module Squishling
|
|
|
49
48
|
return if reserved.empty?
|
|
50
49
|
|
|
51
50
|
raise ConfigurationError, "#{label}: #{reserved.join(', ')} can't be set through params " \
|
|
52
|
-
"(controlled by Squishling
|
|
51
|
+
"(controlled by Squishling and the adapter#{hint})"
|
|
53
52
|
end
|
|
54
53
|
|
|
55
54
|
# Nested keys are compared as symbols so a string-keyed "responseMimeType" can't slip past the check.
|
|
56
|
-
# A non-Hash container would replace (not merge into) the one
|
|
55
|
+
# A non-Hash container would replace (not merge into) the one the adapter builds, wiping the strict format.
|
|
57
56
|
# Validated containers are copied and frozen so they can't be mutated after the check.
|
|
58
57
|
def reject_nested_reserved!(params, label)
|
|
59
58
|
nested = NESTED_RESERVED_KEYS.flat_map do |container, reserved|
|
|
@@ -76,22 +75,6 @@ module Squishling
|
|
|
76
75
|
layers.compact.reduce({}) { |merged, layer| merged.merge(layer) }.compact
|
|
77
76
|
end
|
|
78
77
|
|
|
79
|
-
# Portable settings use RubyLLM's dedicated setters, which translate them for each provider;
|
|
80
|
-
# everything else is merged into the provider request as-is.
|
|
81
|
-
def apply(chat, params)
|
|
82
|
-
rest = params.except(:temperature, :thinking, :max_output_tokens)
|
|
83
|
-
chat.with_temperature(params[:temperature]) if params.key?(:temperature)
|
|
84
|
-
chat.with_max_output_tokens(params[:max_output_tokens]) if params.key?(:max_output_tokens)
|
|
85
|
-
apply_thinking(chat, params[:thinking]) if params.key?(:thinking)
|
|
86
|
-
chat.with_provider_options(rest) if rest.any?
|
|
87
|
-
chat
|
|
88
|
-
end
|
|
89
|
-
|
|
90
|
-
# true: the model's default thinking; false: off; a Hash: { effort:, budget:, display: }.
|
|
91
|
-
def apply_thinking(chat, thinking)
|
|
92
|
-
thinking.is_a?(Hash) ? chat.with_thinking(**thinking) : chat.with_thinking(thinking)
|
|
93
|
-
end
|
|
94
|
-
|
|
95
78
|
def normalize_thinking(thinking, label)
|
|
96
79
|
return thinking if [true, false].include?(thinking)
|
|
97
80
|
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Squishling
|
|
4
|
+
# Adds the squishling:verify rake task to a Rails app (loaded only when Rails is).
|
|
5
|
+
class Railtie < ::Rails::Railtie
|
|
6
|
+
rake_tasks do
|
|
7
|
+
load File.expand_path("tasks/squishling.rake", __dir__)
|
|
8
|
+
end
|
|
9
|
+
end
|
|
10
|
+
end
|
data/lib/squishling/result.rb
CHANGED
|
@@ -4,6 +4,17 @@ module Squishling
|
|
|
4
4
|
# Builds Data classes from a JSON Schema so both the LLM and deterministic paths return
|
|
5
5
|
# the same typed object.
|
|
6
6
|
module Result
|
|
7
|
+
# Property names a generated class can't take: a Data member of the same name replaces the method, which the
|
|
8
|
+
# result (or Squishling) needs. result_spec.rb probes every Object, Kernel, and Data method, so a method a newer
|
|
9
|
+
# Ruby adds can't slip through unreserved.
|
|
10
|
+
RESERVED_NAMES = %i[
|
|
11
|
+
squished? squishling_squished []
|
|
12
|
+
class is_a? kind_of? inspect to_s to_h hash == eql? members deconstruct_keys with dup
|
|
13
|
+
send public_send
|
|
14
|
+
__send__ object_id __id__
|
|
15
|
+
initialize initialize_copy initialize_dup initialize_clone respond_to_missing?
|
|
16
|
+
].freeze
|
|
17
|
+
|
|
7
18
|
# Mixed into every generated result class.
|
|
8
19
|
module Instance
|
|
9
20
|
def initialize(squishling_squished: false, **attrs)
|
|
@@ -28,15 +39,9 @@ module Squishling
|
|
|
28
39
|
module ClassMethods
|
|
29
40
|
def from_h(hash, squished: false)
|
|
30
41
|
hash = hash.transform_keys(&:to_sym)
|
|
31
|
-
attrs = members.to_h { |member| [member, squishling_fields[member].call(hash[member], squished)] }
|
|
42
|
+
attrs = members.to_h { |member| [member, @squishling_fields[member].call(hash[member], squished)] }
|
|
32
43
|
new(squishling_squished: squished, **attrs)
|
|
33
44
|
end
|
|
34
|
-
|
|
35
|
-
private
|
|
36
|
-
|
|
37
|
-
def squishling_fields
|
|
38
|
-
@squishling_fields ||= @squishling_builder.fields_for(@squishling_schema)
|
|
39
|
-
end
|
|
40
45
|
end
|
|
41
46
|
|
|
42
47
|
class << self
|
|
@@ -67,21 +72,50 @@ module Squishling
|
|
|
67
72
|
schema = resolve(schema)
|
|
68
73
|
return nil unless schema.is_a?(Hash) && schema["properties"].is_a?(Hash)
|
|
69
74
|
|
|
70
|
-
@classes[schema]
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
75
|
+
return @classes[schema] if @classes.key?(schema)
|
|
76
|
+
|
|
77
|
+
require_object_type!(schema)
|
|
78
|
+
klass = @classes[schema] = define_class(schema)
|
|
79
|
+
# Memoized first so recursive schemas stop; typing the fields builds nested classes now, so a bad
|
|
80
|
+
# property name in any object the result types (nested, array items, resolved $refs) raises at schema build.
|
|
81
|
+
klass.instance_variable_set(:@squishling_fields, fields_for(schema))
|
|
82
|
+
klass
|
|
83
|
+
end
|
|
84
|
+
|
|
85
|
+
private
|
|
86
|
+
|
|
87
|
+
# `properties` alone constrains objects only, so a schema without `type: "object"` accepts a String or Array
|
|
88
|
+
# that would then sit in the typed result where a nested result is expected. A raw Hash schema must say so.
|
|
89
|
+
def require_object_type!(schema)
|
|
90
|
+
type = schema["type"]
|
|
91
|
+
return if type == "object" || (type.is_a?(Array) && type.include?("object"))
|
|
92
|
+
|
|
93
|
+
raise ConfigurationError,
|
|
94
|
+
"output_schema has a schema with `properties` whose `type` isn't \"object\" (or missing), so a non-object " \
|
|
95
|
+
"value would pass validation and end up in the typed result. Set `type: \"object\"` on it " \
|
|
96
|
+
"(a union such as [\"object\", \"null\"] is also fine)"
|
|
78
97
|
end
|
|
79
98
|
|
|
80
99
|
def fields_for(schema)
|
|
81
100
|
schema["properties"].to_h { |key, property| [key.to_sym, converter_for(property)] }
|
|
82
101
|
end
|
|
83
102
|
|
|
84
|
-
|
|
103
|
+
def define_class(schema)
|
|
104
|
+
klass = Data.define(*property_names(schema))
|
|
105
|
+
klass.include(Instance)
|
|
106
|
+
klass.extend(ClassMethods)
|
|
107
|
+
klass
|
|
108
|
+
end
|
|
109
|
+
|
|
110
|
+
def property_names(schema)
|
|
111
|
+
names = schema["properties"].keys.map(&:to_sym)
|
|
112
|
+
clashes = names & RESERVED_NAMES
|
|
113
|
+
return names if clashes.empty?
|
|
114
|
+
|
|
115
|
+
raise ConfigurationError,
|
|
116
|
+
"output_schema property names clash with methods the result needs: #{clashes.join(', ')}. " \
|
|
117
|
+
"Rename the field(s) (e.g. `class` to `ticket_class`)"
|
|
118
|
+
end
|
|
85
119
|
|
|
86
120
|
def converter_for(property)
|
|
87
121
|
property = resolve(property)
|
data/lib/squishling/rotation.rb
CHANGED
|
@@ -12,6 +12,11 @@ module Squishling
|
|
|
12
12
|
private_constant :COUNTS, :COUNTS_LOCK
|
|
13
13
|
|
|
14
14
|
class << self
|
|
15
|
+
# The turn the next call will get, without counting it.
|
|
16
|
+
def peek(klass, name)
|
|
17
|
+
COUNTS_LOCK.synchronize { (COUNTS[klass] || {}).fetch(name, 0) }
|
|
18
|
+
end
|
|
19
|
+
|
|
15
20
|
# This call's turn, counting from 0, and counts it.
|
|
16
21
|
def advance(klass, name)
|
|
17
22
|
COUNTS_LOCK.synchronize do
|
data/lib/squishling/router.rb
CHANGED
|
@@ -25,9 +25,10 @@ module Squishling
|
|
|
25
25
|
begin
|
|
26
26
|
frame.phase = :ruby
|
|
27
27
|
value = impl.call
|
|
28
|
-
rescue NotImplementedError
|
|
28
|
+
rescue NotImplementedError => e
|
|
29
29
|
# After squish!, the error came from the LLM path (a fallback, a proc), not a missing implementation.
|
|
30
|
-
|
|
30
|
+
# Otherwise it propagates unless it is the method's own stub (see Wrapper.stub?).
|
|
31
|
+
raise if frame.handed_off || !Wrapper.stub?(e)
|
|
31
32
|
|
|
32
33
|
return route_to_llm(frame, definition, "not implemented")
|
|
33
34
|
end
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "rspec/expectations"
|
|
4
|
+
require "squishling"
|
|
5
|
+
|
|
6
|
+
# be_squishling_valid: passes when Squishling.verify finds no problems, and fails with its report.
|
|
7
|
+
# expect(Squishling).to be_squishling_valid # every squished class (eager load first in Rails)
|
|
8
|
+
# expect(InvoiceParser).to be_squishling_valid
|
|
9
|
+
# expect([InvoiceParser, Triage]).to be_squishling_valid
|
|
10
|
+
RSpec::Matchers.define :be_squishling_valid do
|
|
11
|
+
match do |actual|
|
|
12
|
+
@report = actual.equal?(Squishling) ? Squishling.verify : Squishling.verify(actual)
|
|
13
|
+
@report.ok?
|
|
14
|
+
end
|
|
15
|
+
|
|
16
|
+
failure_message { @report.to_s }
|
|
17
|
+
failure_message_when_negated { "expected Squishling.verify to find problems, but it found none" }
|
|
18
|
+
end
|
|
@@ -4,10 +4,48 @@ module Squishling
|
|
|
4
4
|
class Run
|
|
5
5
|
# The follow-up messages a Run sends a model after an output was rejected.
|
|
6
6
|
module Messages
|
|
7
|
+
RETRY_HEAD = "Your previous response was rejected:\n- "
|
|
8
|
+
RETRY_TAIL = "\nRespond again with corrected JSON only."
|
|
9
|
+
RETURNED = "\n\nA previous attempt at this request returned:\n"
|
|
10
|
+
REJECTED = "\nIt was rejected:\n- "
|
|
11
|
+
ESCALATION_TAIL = "\nRespond with corrected JSON only."
|
|
12
|
+
private_constant :RETRY_HEAD, :RETRY_TAIL, :RETURNED, :REJECTED, :ESCALATION_TAIL
|
|
13
|
+
|
|
14
|
+
# What an escalation message carried: the original input, the (capped) rejected output text, and the errors.
|
|
15
|
+
Escalation = Data.define(:input, :rejected, :errors)
|
|
16
|
+
|
|
17
|
+
RETRY_PATTERN = /\A#{Regexp.escape(RETRY_HEAD)}(.*)#{Regexp.escape(RETRY_TAIL)}\z/m
|
|
18
|
+
ESCALATION_PATTERN = Regexp.new(
|
|
19
|
+
"\\A(.*?)#{Regexp.escape(RETURNED)}(.*)#{Regexp.escape(REJECTED)}(.*)#{Regexp.escape(ESCALATION_TAIL)}\\z",
|
|
20
|
+
Regexp::MULTILINE
|
|
21
|
+
)
|
|
22
|
+
private_constant :RETRY_PATTERN, :ESCALATION_PATTERN
|
|
23
|
+
|
|
24
|
+
class << self
|
|
25
|
+
# The errors a retry message carries, or nil when text isn't one. The inverse of the message a Run sends, kept
|
|
26
|
+
# here so the two can't drift apart (the test helpers read what was sent through it). Errors are told apart
|
|
27
|
+
# by splitting on "\n- ", so one that itself contains that sequence reads back as several.
|
|
28
|
+
def parse_retry(text)
|
|
29
|
+
text.match(RETRY_PATTERN)&.then { |match| match[1].split("\n- ") }
|
|
30
|
+
end
|
|
31
|
+
|
|
32
|
+
# What an escalation message carried, or nil when text isn't one.
|
|
33
|
+
def parse_escalation(text)
|
|
34
|
+
match = text.match(ESCALATION_PATTERN)
|
|
35
|
+
match && Escalation.new(input: match[1], rejected: match[2], errors: match[3].split("\n- "))
|
|
36
|
+
end
|
|
37
|
+
end
|
|
38
|
+
|
|
7
39
|
private
|
|
8
40
|
|
|
9
41
|
def retry_message(errors)
|
|
10
|
-
"
|
|
42
|
+
"#{RETRY_HEAD}#{errors.join("\n- ")}#{RETRY_TAIL}"
|
|
43
|
+
end
|
|
44
|
+
|
|
45
|
+
# The first message to a chat: the input, along with the output rejected before it (if any) unless the step
|
|
46
|
+
# opts out of seeing it.
|
|
47
|
+
def fresh_message(step, input, rejected)
|
|
48
|
+
rejected && step.forward_rejected ? escalation_message(input, *rejected) : input
|
|
11
49
|
end
|
|
12
50
|
|
|
13
51
|
# The first message to a fresh chat after an earlier model's output was rejected. The rejected output is
|
|
@@ -19,8 +57,7 @@ module Squishling
|
|
|
19
57
|
omitted = previous.length - Invoker::MAX_FORWARDED_CHARS
|
|
20
58
|
previous = "#{previous[0, Invoker::MAX_FORWARDED_CHARS]}... [truncated, #{omitted} more characters]"
|
|
21
59
|
end
|
|
22
|
-
"#{input}
|
|
23
|
-
"It was rejected:\n- #{errors.join("\n- ")}\nRespond with corrected JSON only."
|
|
60
|
+
"#{input}#{RETURNED}#{previous}#{REJECTED}#{errors.join("\n- ")}#{ESCALATION_TAIL}"
|
|
24
61
|
end
|
|
25
62
|
|
|
26
63
|
# The rejected output as text. Output that was rejected for being unrepresentable in JSON (Infinity, invalid
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Squishling
|
|
4
|
+
class Run
|
|
5
|
+
# What a Run does with a reply it rejects: the attempt that follows, the error it raises, the reason it logs, and
|
|
6
|
+
# the token budget that can end the call before another request. A model that sends back the reply it was just told
|
|
7
|
+
# was invalid, in the same chat, would do it again, so a repeated reply gives up on the rest of its step's attempts.
|
|
8
|
+
module Rejections
|
|
9
|
+
private
|
|
10
|
+
|
|
11
|
+
# The number of the attempt after attempt in path, or nil when none is left.
|
|
12
|
+
def next_attempt(path, attempt, repeated)
|
|
13
|
+
return (attempt + 1 if attempt < path.size) unless repeated
|
|
14
|
+
|
|
15
|
+
skipped = path.drop(attempt).index { |step| step != path[attempt - 1] }
|
|
16
|
+
attempt + skipped + 1 if skipped
|
|
17
|
+
end
|
|
18
|
+
|
|
19
|
+
def invalid_output(response, errors, attempt, models, source = "LLM")
|
|
20
|
+
InvalidOutputError.new(errors:, raw: response.content, attempts: attempt, models:, source:,
|
|
21
|
+
finish_reason: response.finish_reason)
|
|
22
|
+
end
|
|
23
|
+
|
|
24
|
+
# Why an attempt was rejected, for the log: the output check's errors, plus a note when the reply was cut off.
|
|
25
|
+
def rejection_reason(errors, response)
|
|
26
|
+
reason = errors.join("; ")
|
|
27
|
+
response.truncated? ? "#{reason} (#{InvalidOutputError::CUTOFF_NOTE})" : reason
|
|
28
|
+
end
|
|
29
|
+
|
|
30
|
+
# Raises BudgetExhaustedError when the call has spent its token budget (see Budget), before another request.
|
|
31
|
+
# attempts is how many were made so far, models the ones tried, rejected the last [raw content, errors].
|
|
32
|
+
def check_budget!(attempts: 0, models: nil, rejected: nil)
|
|
33
|
+
exhausted = @client.exhausted_budget
|
|
34
|
+
return unless exhausted
|
|
35
|
+
|
|
36
|
+
error = BudgetExhaustedError.new(**exhausted, errors: rejected&.last || [], raw: rejected&.first,
|
|
37
|
+
attempts: (attempts if attempts.positive?), models: (models.dup if models&.any?))
|
|
38
|
+
log("stopped, #{error.errors.first}")
|
|
39
|
+
raise error
|
|
40
|
+
end
|
|
41
|
+
end
|
|
42
|
+
end
|
|
43
|
+
end
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Squishling
|
|
4
|
+
class Run
|
|
5
|
+
# What a Run tells the squawk hook (see Squawk): the report of each attempt, and the one final report of a call that
|
|
6
|
+
# a token budget or a disagreement stopped.
|
|
7
|
+
module Reports
|
|
8
|
+
# Set on a stop error once it has been reported (see #report_stop).
|
|
9
|
+
REPORTED = :@squawk_reported
|
|
10
|
+
private_constant :REPORTED
|
|
11
|
+
|
|
12
|
+
# Reports to squawk the BudgetExhaustedError or DisagreementError that stopped the call: one final report with
|
|
13
|
+
# the error, for an ending that no attempt of its own reported (the attempt before a budget stop was already
|
|
14
|
+
# reported, as not final, and a disagreement's samples were both accepted). Nothing was sent, so there is no
|
|
15
|
+
# output, and the provider and params are unknown (the stop comes from the harness, not from a step).
|
|
16
|
+
# Internal: Invoker calls it once, whatever the harness, so a custom harness has nothing to do.
|
|
17
|
+
def report_stop(error)
|
|
18
|
+
hook = @definition.squawk
|
|
19
|
+
attempts = error.attempts.to_i
|
|
20
|
+
return if error.instance_variable_get(REPORTED) || !hook
|
|
21
|
+
return unless Squawk.report?(@definition.squawk_on, attempts, error, true)
|
|
22
|
+
|
|
23
|
+
# Marked first, so an error that comes back through an outer squished call (or a second report_stop) is not
|
|
24
|
+
# reported again, and a hook that raises doesn't get the same error again either.
|
|
25
|
+
error.instance_variable_set(REPORTED, true)
|
|
26
|
+
metadata = squawk_metadata(
|
|
27
|
+
attempt: attempts, attempts:, final: true, model: error.models&.last, input: @prompt.input,
|
|
28
|
+
stopped: error.is_a?(BudgetExhaustedError) ? :budget : :disagreement
|
|
29
|
+
)
|
|
30
|
+
Squawk.call(hook, output: nil, metadata:, error:)
|
|
31
|
+
end
|
|
32
|
+
|
|
33
|
+
private
|
|
34
|
+
|
|
35
|
+
# Runs the observability hook, if any, with this attempt's raw output (nil when the call itself failed),
|
|
36
|
+
# the error that ended it (nil when it was accepted), and what was asked. role is nil for escalation
|
|
37
|
+
# attempts, :sample (with the sample's name) or :judge. reask is whether the attempt retried in the same chat,
|
|
38
|
+
# repeated whether it sent back the reply the attempt before it was rejected for, and final whether no attempt
|
|
39
|
+
# follows it.
|
|
40
|
+
def squawk(prompt, path, attempt, response, error, sample: nil, reask: false, repeated: false,
|
|
41
|
+
final: attempt == path.size)
|
|
42
|
+
hook = @definition.squawk
|
|
43
|
+
return unless hook && Squawk.report?(@definition.squawk_on, attempt, error, final)
|
|
44
|
+
|
|
45
|
+
step = path[attempt - 1]
|
|
46
|
+
metadata = squawk_metadata(
|
|
47
|
+
attempt:, attempts: path.size, final:, repeated:, model: response&.model || step.model,
|
|
48
|
+
provider: step.provider, params: step.request_params(reask), input: prompt.input, response:,
|
|
49
|
+
role: sample ? :sample : prompt.role, sample: sample&.name
|
|
50
|
+
)
|
|
51
|
+
Squawk.call(hook, output: response&.content, metadata:, error:)
|
|
52
|
+
end
|
|
53
|
+
|
|
54
|
+
def squawk_metadata(attempt:, attempts:, final:, model:, input:, repeated: false, provider: nil, params: nil,
|
|
55
|
+
response: nil, role: nil, sample: nil, stopped: nil)
|
|
56
|
+
{
|
|
57
|
+
label:, attempt:, attempts:, final:, repeated:, model:, provider:, params:, input:,
|
|
58
|
+
usage: response&.usage, finish_reason: response&.finish_reason, role:, sample:, stopped:
|
|
59
|
+
}
|
|
60
|
+
end
|
|
61
|
+
end
|
|
62
|
+
end
|
|
63
|
+
end
|