squishling 0.6.0 → 0.7.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 +52 -0
- data/README.md +2 -1
- data/docs/adapters.md +70 -2
- data/docs/configuration.md +3 -1
- data/docs/images.md +92 -0
- data/docs/observers.md +1 -0
- data/docs/routing.md +8 -0
- data/docs/testing.md +14 -9
- data/docs/verifying.md +3 -1
- data/lib/squishling/adapter.rb +18 -6
- data/lib/squishling/adapters/openai_compatible.rb +10 -2
- data/lib/squishling/adapters/openai_content.rb +23 -0
- data/lib/squishling/adapters/ruby_llm.rb +36 -5
- data/lib/squishling/configuration.rb +56 -0
- data/lib/squishling/image.rb +169 -0
- data/lib/squishling/invoker.rb +16 -33
- data/lib/squishling/judge.rb +14 -5
- data/lib/squishling/llm_client.rb +85 -32
- data/lib/squishling/model_path.rb +22 -7
- data/lib/squishling/observer.rb +6 -2
- data/lib/squishling/payload.rb +68 -0
- data/lib/squishling/run.rb +13 -6
- data/lib/squishling/testing/adapter.rb +13 -4
- data/lib/squishling/testing/checks.rb +1 -1
- data/lib/squishling/testing/direct.rb +4 -3
- data/lib/squishling/testing/request.rb +19 -5
- data/lib/squishling/testing/script.rb +12 -10
- data/lib/squishling/testing.rb +14 -7
- data/lib/squishling/verifier.rb +24 -4
- data/lib/squishling/version.rb +1 -1
- data/lib/squishling.rb +3 -0
- metadata +5 -1
|
@@ -65,8 +65,19 @@ module Squishling
|
|
|
65
65
|
# gem is available. Built when assigned, so a mistake fails at setup rather than on the first request.
|
|
66
66
|
attr_reader :adapter
|
|
67
67
|
|
|
68
|
+
# More adapters, by name, for escalation steps that pick one with adapter: (see ModelPath), e.g.
|
|
69
|
+
# config.adapters = { local: { type: :openai_compatible, base_url: "http://localhost:11434/v1" }, claude: :claude_code }
|
|
70
|
+
# Each value is anything config.adapter takes. A step without adapter: uses config.adapter. Built when assigned.
|
|
71
|
+
attr_reader :adapters
|
|
72
|
+
|
|
73
|
+
# Squishling::Testing only: when set, every adapter name resolves to this adapter, so a scripted adapter answers
|
|
74
|
+
# for steps that pick another one.
|
|
75
|
+
attr_accessor :adapter_override
|
|
76
|
+
|
|
68
77
|
def initialize
|
|
69
78
|
@adapter = nil
|
|
79
|
+
@adapters = {}.freeze
|
|
80
|
+
@adapter_override = nil
|
|
70
81
|
@detected_adapter = nil
|
|
71
82
|
@adapter_lock = Mutex.new
|
|
72
83
|
@observer = nil
|
|
@@ -103,6 +114,37 @@ module Squishling
|
|
|
103
114
|
end
|
|
104
115
|
end
|
|
105
116
|
|
|
117
|
+
def adapters=(named)
|
|
118
|
+
unless named.nil? || named.is_a?(Hash)
|
|
119
|
+
raise ConfigurationError, "Squishling.configure: adapters must be a Hash of name => adapter, got #{named.class}"
|
|
120
|
+
end
|
|
121
|
+
|
|
122
|
+
built = {}
|
|
123
|
+
(named || {}).each do |name, adapter|
|
|
124
|
+
key = adapter_key(name, built)
|
|
125
|
+
built[key] = Adapter.build(adapter, "Squishling.configure adapters[#{key.inspect}]")
|
|
126
|
+
end
|
|
127
|
+
@adapter_lock.synchronize { @adapters = built.freeze }
|
|
128
|
+
end
|
|
129
|
+
|
|
130
|
+
# The adapter a step's adapter: names (nil is the default one, see #resolved_adapter). Raises ConfigurationError
|
|
131
|
+
# for a name that isn't configured.
|
|
132
|
+
def adapter_for(name)
|
|
133
|
+
return resolved_adapter if name.nil?
|
|
134
|
+
|
|
135
|
+
@adapter_override || named_adapter(name)
|
|
136
|
+
end
|
|
137
|
+
|
|
138
|
+
# The adapter configured under a name, whatever Squishling::Testing routes to. Raises ConfigurationError for a name
|
|
139
|
+
# that isn't configured.
|
|
140
|
+
def named_adapter(name)
|
|
141
|
+
named = @adapter_lock.synchronize { @adapters }
|
|
142
|
+
named.fetch(name) do
|
|
143
|
+
known = named.empty? ? "none; set config.adapters" : named.keys.map(&:inspect).join(", ")
|
|
144
|
+
raise ConfigurationError, "unknown adapter #{name.inspect} (configured: #{known})"
|
|
145
|
+
end
|
|
146
|
+
end
|
|
147
|
+
|
|
106
148
|
# The adapter requests go through: the configured one, else RubyLLM's (when its gem is available) built on first
|
|
107
149
|
# use. Raises ConfigurationError when there is neither.
|
|
108
150
|
def resolved_adapter
|
|
@@ -171,5 +213,19 @@ module Squishling
|
|
|
171
213
|
def max_retries=(_value)
|
|
172
214
|
raise ConfigurationError, MAX_RETRIES_REMOVED
|
|
173
215
|
end
|
|
216
|
+
|
|
217
|
+
private
|
|
218
|
+
|
|
219
|
+
# An adapters: name as a Symbol; a blank or non-name key, or one already in taken, is a ConfigurationError.
|
|
220
|
+
def adapter_key(name, taken)
|
|
221
|
+
unless (name.is_a?(Symbol) || name.is_a?(String)) && !name.to_s.strip.empty?
|
|
222
|
+
raise ConfigurationError, "Squishling.configure: an adapter name must be a Symbol, got #{name.inspect}"
|
|
223
|
+
end
|
|
224
|
+
|
|
225
|
+
key = name.to_sym
|
|
226
|
+
raise ConfigurationError, "Squishling.configure: adapters names #{key.inspect} twice" if taken.key?(key)
|
|
227
|
+
|
|
228
|
+
key
|
|
229
|
+
end
|
|
174
230
|
end
|
|
175
231
|
end
|
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "uri"
|
|
4
|
+
|
|
5
|
+
module Squishling
|
|
6
|
+
# An image sent to the model with a squished call. Pass it as an argument (or inside one, in a Hash or an Array):
|
|
7
|
+
# in the JSON input the model sees {"attached_image": N} where the image was, and the image itself goes with the
|
|
8
|
+
# call's first message as an image content part, through any adapter that takes images (Adapter::Base#images?).
|
|
9
|
+
# The Ruby path gets the Image as it was passed.
|
|
10
|
+
#
|
|
11
|
+
# Squishling::Image.from_path("receipt.jpg")
|
|
12
|
+
# Squishling::Image.new(data: blob.download, media_type: "image/png", detail: :high)
|
|
13
|
+
# Squishling::Image.from_url("https://example.com/receipt.png")
|
|
14
|
+
#
|
|
15
|
+
# The bytes are never logged, inspected, or serialized: #inspect, #to_s, #as_json and #to_json describe the image
|
|
16
|
+
# (media type and size, or a URL without its query), so an image in an error, a log line, or a squawk report
|
|
17
|
+
# carries no content. Images are immutable and compare by content.
|
|
18
|
+
class Image
|
|
19
|
+
MEDIA_TYPES = { "image/png" => "png", "image/jpeg" => "jpg", "image/gif" => "gif", "image/webp" => "webp" }.freeze
|
|
20
|
+
EXTENSIONS = { ".png" => "image/png", ".jpg" => "image/jpeg", ".jpeg" => "image/jpeg", ".gif" => "image/gif",
|
|
21
|
+
".webp" => "image/webp" }.freeze
|
|
22
|
+
# How much of the image the provider looks at: :low or :high (nil for the provider's default). Providers without
|
|
23
|
+
# the setting ignore it.
|
|
24
|
+
DETAILS = %i[low high].freeze
|
|
25
|
+
|
|
26
|
+
# The bytes, or nil for an image given by URL.
|
|
27
|
+
attr_reader :data
|
|
28
|
+
attr_reader :media_type, :detail, :url
|
|
29
|
+
|
|
30
|
+
class << self
|
|
31
|
+
# An image read from a file. The media type comes from the bytes, or the extension when given none.
|
|
32
|
+
def from_path(path, media_type: nil, detail: nil)
|
|
33
|
+
data = File.binread(path)
|
|
34
|
+
new(data:, media_type: media_type || sniff(data) || EXTENSIONS[File.extname(path.to_s).downcase], detail:)
|
|
35
|
+
end
|
|
36
|
+
|
|
37
|
+
# An image the provider fetches itself (http or https). Nothing is downloaded here.
|
|
38
|
+
def from_url(url, detail: nil)
|
|
39
|
+
new(url:, detail:)
|
|
40
|
+
end
|
|
41
|
+
|
|
42
|
+
# The media type the bytes start with, or nil.
|
|
43
|
+
def sniff(data)
|
|
44
|
+
head = data.byteslice(0, 12).b
|
|
45
|
+
if head.start_with?("\x89PNG\r\n\x1A\n".b) then "image/png"
|
|
46
|
+
elsif head.start_with?("\xFF\xD8\xFF".b) then "image/jpeg"
|
|
47
|
+
elsif head.start_with?("GIF87a", "GIF89a") then "image/gif"
|
|
48
|
+
elsif head.start_with?("RIFF") && head.byteslice(8, 4) == "WEBP" then "image/webp"
|
|
49
|
+
end
|
|
50
|
+
end
|
|
51
|
+
end
|
|
52
|
+
|
|
53
|
+
# Exactly one of data: (the image's bytes, with its media_type:, which is read from the bytes when left out) and
|
|
54
|
+
# url: (http or https). Raises ConfigurationError for anything else.
|
|
55
|
+
def initialize(data: nil, media_type: nil, url: nil, detail: nil)
|
|
56
|
+
raise ConfigurationError, "Squishling::Image takes data: or url:, not both" if data && url
|
|
57
|
+
|
|
58
|
+
@detail = checked_detail(detail)
|
|
59
|
+
if url
|
|
60
|
+
raise ConfigurationError, "Squishling::Image from a url: takes no media_type:" if media_type
|
|
61
|
+
|
|
62
|
+
@url = checked_url(url)
|
|
63
|
+
else
|
|
64
|
+
@data = checked_data(data)
|
|
65
|
+
@media_type = checked_media_type(media_type&.to_s || self.class.sniff(@data))
|
|
66
|
+
end
|
|
67
|
+
freeze
|
|
68
|
+
end
|
|
69
|
+
|
|
70
|
+
def url?
|
|
71
|
+
!@url.nil?
|
|
72
|
+
end
|
|
73
|
+
|
|
74
|
+
def bytesize
|
|
75
|
+
@data&.bytesize
|
|
76
|
+
end
|
|
77
|
+
|
|
78
|
+
# The bytes as a data: URI (nil for an image given by URL).
|
|
79
|
+
def data_uri
|
|
80
|
+
@data && "data:#{@media_type};base64,#{[@data].pack('m0')}"
|
|
81
|
+
end
|
|
82
|
+
|
|
83
|
+
# A file name for adapters that need one ("image.png"), or nil for an image given by URL.
|
|
84
|
+
def filename
|
|
85
|
+
@data && "image.#{MEDIA_TYPES.fetch(@media_type)}"
|
|
86
|
+
end
|
|
87
|
+
|
|
88
|
+
def inspect
|
|
89
|
+
described = url? ? safe_url : "#{@media_type}, #{@data.bytesize} bytes"
|
|
90
|
+
"#<#{self.class.name} #{described}#{", detail: #{@detail}" if @detail}>"
|
|
91
|
+
end
|
|
92
|
+
alias_method :to_s, :inspect
|
|
93
|
+
|
|
94
|
+
# Serializers (Rails' as_json walks instance variables) get the description, never the bytes.
|
|
95
|
+
def as_json(*)
|
|
96
|
+
inspect
|
|
97
|
+
end
|
|
98
|
+
|
|
99
|
+
def to_json(*)
|
|
100
|
+
JSON.generate(inspect)
|
|
101
|
+
end
|
|
102
|
+
|
|
103
|
+
# YAML gets the description, and Marshal refuses (the way Secret does), so a cache or job payload can't carry bytes.
|
|
104
|
+
def encode_with(coder)
|
|
105
|
+
coder.scalar = inspect
|
|
106
|
+
end
|
|
107
|
+
|
|
108
|
+
def marshal_dump
|
|
109
|
+
raise TypeError, "Squishling::Image can't be dumped: it holds the image's bytes"
|
|
110
|
+
end
|
|
111
|
+
|
|
112
|
+
def ==(other)
|
|
113
|
+
other.is_a?(Image) && other.state == state
|
|
114
|
+
end
|
|
115
|
+
alias_method :eql?, :==
|
|
116
|
+
|
|
117
|
+
def hash
|
|
118
|
+
[self.class, *state].hash
|
|
119
|
+
end
|
|
120
|
+
|
|
121
|
+
protected
|
|
122
|
+
|
|
123
|
+
def state
|
|
124
|
+
[@data, @media_type, @url, @detail]
|
|
125
|
+
end
|
|
126
|
+
|
|
127
|
+
private
|
|
128
|
+
|
|
129
|
+
def checked_data(data)
|
|
130
|
+
unless data.is_a?(String) && !data.empty?
|
|
131
|
+
raise ConfigurationError, "Squishling::Image needs data: (the image's bytes) or url:"
|
|
132
|
+
end
|
|
133
|
+
|
|
134
|
+
data.b.freeze
|
|
135
|
+
end
|
|
136
|
+
|
|
137
|
+
def checked_media_type(media_type)
|
|
138
|
+
return -media_type if MEDIA_TYPES.key?(media_type)
|
|
139
|
+
|
|
140
|
+
problem = media_type ? "got #{media_type.inspect}" : "it couldn't be read from the bytes"
|
|
141
|
+
raise ConfigurationError,
|
|
142
|
+
"Squishling::Image media_type must be one of #{MEDIA_TYPES.keys.join(', ')} (#{problem})"
|
|
143
|
+
end
|
|
144
|
+
|
|
145
|
+
def checked_url(url)
|
|
146
|
+
uri = URI.parse(url.to_s)
|
|
147
|
+
return uri.to_s.freeze if %w[http https].include?(uri.scheme&.downcase) && uri.host
|
|
148
|
+
|
|
149
|
+
raise ConfigurationError, "Squishling::Image url: must be an http or https URL"
|
|
150
|
+
rescue URI::InvalidURIError
|
|
151
|
+
raise ConfigurationError, "Squishling::Image url: must be an http or https URL"
|
|
152
|
+
end
|
|
153
|
+
|
|
154
|
+
def checked_detail(detail)
|
|
155
|
+
return nil if detail.nil?
|
|
156
|
+
|
|
157
|
+
detail = detail.to_s.to_sym
|
|
158
|
+
return detail if DETAILS.include?(detail)
|
|
159
|
+
|
|
160
|
+
raise ConfigurationError, "Squishling::Image detail: must be #{DETAILS.map(&:inspect).join(' or ')}, or nil"
|
|
161
|
+
end
|
|
162
|
+
|
|
163
|
+
# The URL without credentials, query, or fragment: a signed URL's query holds its token.
|
|
164
|
+
def safe_url
|
|
165
|
+
uri = URI.parse(@url)
|
|
166
|
+
"#{uri.scheme}://#{uri.host}#{":#{uri.port}" unless uri.port == uri.default_port}#{uri.path}"
|
|
167
|
+
end
|
|
168
|
+
end
|
|
169
|
+
end
|
data/lib/squishling/invoker.rb
CHANGED
|
@@ -8,12 +8,20 @@ module Squishling
|
|
|
8
8
|
present, holds additional state about the caller. Respond only with JSON matching the required schema.
|
|
9
9
|
NOTE
|
|
10
10
|
|
|
11
|
+
IMAGE_NOTE = <<~NOTE
|
|
12
|
+
Images are attached to this message. Each {"attached_image": N} value in the input stands for the Nth image.
|
|
13
|
+
NOTE
|
|
14
|
+
|
|
11
15
|
# The most of a rejected output that is forwarded to the next escalation step.
|
|
12
16
|
MAX_FORWARDED_CHARS = 4_000
|
|
13
17
|
|
|
14
|
-
# One escalation's request: the system prompt, the output Schema,
|
|
15
|
-
# role (:judge) skips squish_validate and names the judge in errors and logs.
|
|
16
|
-
Prompt = Data.define(:instructions, :schema, :input, :role)
|
|
18
|
+
# One escalation's request: the system prompt, the output Schema, the first user message, and the Images that go
|
|
19
|
+
# with it. The judge's role (:judge) skips squish_validate and names the judge in errors and logs.
|
|
20
|
+
Prompt = Data.define(:instructions, :schema, :input, :role, :images) do
|
|
21
|
+
def initialize(instructions:, schema:, input:, role:, images: [])
|
|
22
|
+
super
|
|
23
|
+
end
|
|
24
|
+
end
|
|
17
25
|
|
|
18
26
|
def initialize(definition, receiver, inputs)
|
|
19
27
|
@definition = definition
|
|
@@ -55,8 +63,10 @@ module Squishling
|
|
|
55
63
|
raise ConfigurationError, "#{@definition.label} has no purpose" if purpose.nil? || purpose.empty?
|
|
56
64
|
raise ConfigurationError, "#{@definition.label} has no output_schema" unless schema
|
|
57
65
|
|
|
66
|
+
@images = []
|
|
58
67
|
body = payload
|
|
59
|
-
|
|
68
|
+
instructions = "#{purpose}\n\n#{INPUT_NOTE}#{IMAGE_NOTE if @images.any?}"
|
|
69
|
+
prompt = Prompt.new(instructions:, schema:, input: JSON.generate(body), role: nil, images: @images.dup.freeze)
|
|
60
70
|
Built.new(prompt:, payload: body, purpose:)
|
|
61
71
|
end
|
|
62
72
|
|
|
@@ -71,39 +81,12 @@ module Squishling
|
|
|
71
81
|
|
|
72
82
|
# Only the arguments, the declared squish_context names, and a squish! call's context leave the process.
|
|
73
83
|
def payload
|
|
74
|
-
body = { arguments:
|
|
84
|
+
body = { arguments: Payload.jsonify(@inputs, @definition.label, @images) }
|
|
75
85
|
context = @definition.context_names.to_h { |name| [name, context_value(name)] }.merge(@definition.call_context)
|
|
76
|
-
body[:context] =
|
|
86
|
+
body[:context] = Payload.jsonify(context, @definition.label, @images) if context.any?
|
|
77
87
|
body
|
|
78
88
|
end
|
|
79
89
|
|
|
80
|
-
# Exceptions are sent as their class and message. Plain JSON would send only the message, and with
|
|
81
|
-
# json/add/exception loaded it would also send the backtrace, which exposes file paths. path is the Hashes and
|
|
82
|
-
# Arrays being walked: one that contains itself is a ConfigurationError rather than a SystemStackError.
|
|
83
|
-
def describe(value, path = [])
|
|
84
|
-
case value
|
|
85
|
-
when Exception then { class: exception_class_name(value.class), message: value.message }
|
|
86
|
-
when Hash then within(value, path) { |inner| value.transform_values { |item| describe(item, inner) } }
|
|
87
|
-
when Array then within(value, path) { |inner| value.map { |item| describe(item, inner) } }
|
|
88
|
-
else value
|
|
89
|
-
end
|
|
90
|
-
end
|
|
91
|
-
|
|
92
|
-
def within(container, path)
|
|
93
|
-
if path.any? { |ancestor| ancestor.equal?(container) }
|
|
94
|
-
raise ConfigurationError, "#{@definition.label}: an argument or context value contains itself, " \
|
|
95
|
-
"so it can't be sent as JSON"
|
|
96
|
-
end
|
|
97
|
-
|
|
98
|
-
yield path + [container]
|
|
99
|
-
end
|
|
100
|
-
|
|
101
|
-
# An anonymous error class (Class.new(StandardError)) is named after its closest named ancestor.
|
|
102
|
-
def exception_class_name(klass)
|
|
103
|
-
klass = klass.superclass until klass.name
|
|
104
|
-
klass.name
|
|
105
|
-
end
|
|
106
|
-
|
|
107
90
|
def context_value(name)
|
|
108
91
|
return @receiver.send(name) if @receiver.respond_to?(name, true)
|
|
109
92
|
|
data/lib/squishling/judge.rb
CHANGED
|
@@ -43,13 +43,15 @@ module Squishling
|
|
|
43
43
|
|
|
44
44
|
# judge: is a normalized judge step (see Harness::JudgedSquishsum) or nil for the escalation's next stage,
|
|
45
45
|
# instructions: a String, a Proc evaluated against the receiver, or nil for the default prompt.
|
|
46
|
+
# images: the call's Images, which a chat judge is sent with the input; a :judgment judge can't take them.
|
|
46
47
|
def initialize(definition:, receiver:, client:, judge:, instructions:, path:, purpose:, payload:, escalate:,
|
|
47
|
-
log_failure:, guard:, budget_check:, harness_type:)
|
|
48
|
+
log_failure:, guard:, budget_check:, harness_type:, images: [])
|
|
48
49
|
@definition = definition
|
|
49
50
|
@receiver = receiver
|
|
50
51
|
@client = client
|
|
51
52
|
@judge = judge
|
|
52
53
|
@instructions = instructions
|
|
54
|
+
@images = images
|
|
53
55
|
check!
|
|
54
56
|
check_judgments!
|
|
55
57
|
@guard = guard
|
|
@@ -60,6 +62,7 @@ module Squishling
|
|
|
60
62
|
@escalate = escalate
|
|
61
63
|
@log_failure = log_failure
|
|
62
64
|
@steps = resolve_steps(path)
|
|
65
|
+
@client.check_adapters!(@steps, @images)
|
|
63
66
|
end
|
|
64
67
|
|
|
65
68
|
# The judge's first attempt, for logs and DisagreementError#models.
|
|
@@ -101,10 +104,16 @@ module Squishling
|
|
|
101
104
|
|
|
102
105
|
# Raised before any request, like the rest of the judge's checks.
|
|
103
106
|
def check_judgments!
|
|
104
|
-
return
|
|
107
|
+
return unless judgment?
|
|
108
|
+
|
|
109
|
+
if @images.any?
|
|
110
|
+
raise ConfigurationError, "#{@definition.label}: judge type: :judgment can't see the call's images; use " \
|
|
111
|
+
"type: :chat"
|
|
112
|
+
end
|
|
113
|
+
return if @client.judgments?(judgment_steps(@judge).first)
|
|
105
114
|
|
|
106
115
|
raise ConfigurationError, "#{@definition.label}: judge type: :judgment needs an adapter that supports " \
|
|
107
|
-
"judgments (the
|
|
116
|
+
"judgments (the judge's adapter doesn't); use type: :chat or the :ruby_llm adapter"
|
|
108
117
|
end
|
|
109
118
|
|
|
110
119
|
def non_blank_string?(value)
|
|
@@ -141,8 +150,8 @@ module Squishling
|
|
|
141
150
|
def chat(candidates)
|
|
142
151
|
prompt = Invoker::Prompt.new(
|
|
143
152
|
instructions: "#{judge_instructions}\n\nThe operation's purpose:\n<purpose>\n#{@purpose}\n" \
|
|
144
|
-
"</purpose>\n\n#{INPUT_NOTE}",
|
|
145
|
-
schema: Schema.for(VERDICT_SCHEMA), input: JSON.generate(state(candidates)), role: :judge
|
|
153
|
+
"</purpose>\n\n#{INPUT_NOTE}#{Invoker::IMAGE_NOTE if @images.any?}",
|
|
154
|
+
schema: Schema.for(VERDICT_SCHEMA), input: JSON.generate(state(candidates)), role: :judge, images: @images
|
|
146
155
|
)
|
|
147
156
|
result = @escalate.call(@steps, prompt)
|
|
148
157
|
Verdict.new(choice: result[:verdict].to_sym, reason: result[:reason], detail: nil)
|
|
@@ -1,12 +1,13 @@
|
|
|
1
1
|
# frozen_string_literal: true
|
|
2
2
|
|
|
3
3
|
module Squishling
|
|
4
|
-
# The requests for one squished method, made through the
|
|
5
|
-
# conversation: each Conversation holds the system prompt, the output
|
|
6
|
-
# request sends all of it to the adapter.
|
|
4
|
+
# The requests for one squished method, made through the adapter each step names (see Adapter; the default one
|
|
5
|
+
# when it names none). Squishling owns the conversation: each Conversation holds the system prompt, the output
|
|
6
|
+
# schema, and the messages so far, and every request sends all of it to the adapter.
|
|
7
7
|
class LLMClient
|
|
8
|
-
# One chat on one escalation step. messages are { role:, content: } Hashes, grown by #ask.
|
|
9
|
-
|
|
8
|
+
# One chat on one escalation step. messages are { role:, content: } Hashes, grown by #ask. images go with the
|
|
9
|
+
# chat's first message.
|
|
10
|
+
Conversation = Struct.new(:step, :instructions, :schema, :messages, :images)
|
|
10
11
|
|
|
11
12
|
# purpose, harness (the harness type), and handed_off (squish! sent the call here) are only told to the observer.
|
|
12
13
|
# budget (see Budget) caps the tokens the requests of this client may use between them.
|
|
@@ -15,8 +16,19 @@ module Squishling
|
|
|
15
16
|
@purpose = purpose
|
|
16
17
|
@harness = harness
|
|
17
18
|
@handed_off = handed_off
|
|
18
|
-
@
|
|
19
|
-
@
|
|
19
|
+
@config = Squishling.config
|
|
20
|
+
@adapters = {}
|
|
21
|
+
@adapters_lock = Mutex.new
|
|
22
|
+
@tally = Budget::Tally.new(budget, cache_reads: @config.budget_counts_cache_reads)
|
|
23
|
+
end
|
|
24
|
+
|
|
25
|
+
# Raises ConfigurationError if any of the steps names an adapter that isn't configured, or (given images) names one
|
|
26
|
+
# that doesn't take them, so a mistake ends the call before it has made a request.
|
|
27
|
+
def check_adapters!(steps, images = [])
|
|
28
|
+
steps.each do |step|
|
|
29
|
+
adapter_for(step)
|
|
30
|
+
check_images!(step, images)
|
|
31
|
+
end
|
|
20
32
|
end
|
|
21
33
|
|
|
22
34
|
# The budget limit this client's requests have reached ({ limit:, max:, used: }), or nil. Checked before each
|
|
@@ -25,17 +37,19 @@ module Squishling
|
|
|
25
37
|
@tally.exhausted
|
|
26
38
|
end
|
|
27
39
|
|
|
28
|
-
# Runs each job on its own thread and returns, in order, each job's [value, exception].
|
|
29
|
-
#
|
|
30
|
-
#
|
|
31
|
-
#
|
|
32
|
-
# requests still running are stopped rather
|
|
33
|
-
|
|
40
|
+
# Runs each job on its own thread and returns, in order, each job's [value, exception]. steps are the
|
|
41
|
+
# escalation steps the jobs ask on, in the same order. Only provider requests run here: parsing, validation, and
|
|
42
|
+
# the developer's callbacks stay on the caller's thread. Fiber storage is inherited by the threads, and each
|
|
43
|
+
# job's adapter carries over whatever request context it keeps (see Adapter::Base#capture_context). If the
|
|
44
|
+
# caller is interrupted while waiting (a timeout, Thread#raise), the requests still running are stopped rather
|
|
45
|
+
# than left running unobserved.
|
|
46
|
+
def concurrently(jobs, steps)
|
|
34
47
|
return jobs.map { |job| capture(job) } if jobs.size < 2
|
|
35
48
|
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
49
|
+
adapters = steps.map { |step| adapter_for(step) }
|
|
50
|
+
contexts = captured_contexts(adapters)
|
|
51
|
+
threads = jobs.zip(adapters).map do |job, adapter|
|
|
52
|
+
thread = Thread.new { with_context(adapter, contexts.fetch(adapter)) { capture(job) } }
|
|
39
53
|
thread.report_on_exception = false
|
|
40
54
|
thread
|
|
41
55
|
end
|
|
@@ -44,9 +58,11 @@ module Squishling
|
|
|
44
58
|
threads&.each { |thread| thread.kill.join if thread.alive? }
|
|
45
59
|
end
|
|
46
60
|
|
|
47
|
-
# A fresh conversation on one escalation step, with the system prompt
|
|
48
|
-
|
|
49
|
-
|
|
61
|
+
# A fresh conversation on one escalation step, with the system prompt, the strict output schema, and the Images
|
|
62
|
+
# its first message carries. Raises ConfigurationError for images when the step's adapter doesn't take them.
|
|
63
|
+
def chat(step, instructions:, schema:, images: [])
|
|
64
|
+
check_images!(step, images)
|
|
65
|
+
Conversation.new(step, instructions, schema, [], images)
|
|
50
66
|
end
|
|
51
67
|
|
|
52
68
|
# One request in the conversation: the message goes in, and the adapter's answer is kept in it so the next
|
|
@@ -61,15 +77,16 @@ module Squishling
|
|
|
61
77
|
Observer.around(call) { complete(chat, message, step, reask) }
|
|
62
78
|
end
|
|
63
79
|
|
|
64
|
-
# Whether the adapter can make System One judgments (judges with type: :judgment).
|
|
65
|
-
def judgments?
|
|
66
|
-
|
|
80
|
+
# Whether the step's adapter can make System One judgments (judges with type: :judgment).
|
|
81
|
+
def judgments?(step)
|
|
82
|
+
adapter = adapter_for(step)
|
|
83
|
+
adapter.respond_to?(:judgments?) && adapter.respond_to?(:judge) && adapter.judgments?
|
|
67
84
|
end
|
|
68
85
|
|
|
69
|
-
# A System One judgment on one step, through the adapter.
|
|
86
|
+
# A System One judgment on one step, through the step's adapter.
|
|
70
87
|
# Judge#check_judgments! has already refused an adapter that can't.
|
|
71
88
|
def judge(input, questions:, step:)
|
|
72
|
-
@tally.add(
|
|
89
|
+
@tally.add(adapter_for(step).judge(input, questions:, step:, label: @label))
|
|
73
90
|
end
|
|
74
91
|
|
|
75
92
|
# #judge inside the configured observer (see Observer), attempt counting in attempts.
|
|
@@ -80,6 +97,22 @@ module Squishling
|
|
|
80
97
|
|
|
81
98
|
private
|
|
82
99
|
|
|
100
|
+
# The step's adapter, looked up once per call: the adapter a job's context was captured from is the one that
|
|
101
|
+
# makes its request, even if the configuration changes meanwhile.
|
|
102
|
+
def check_images!(step, images)
|
|
103
|
+
return if images.empty?
|
|
104
|
+
|
|
105
|
+
adapter = adapter_for(step)
|
|
106
|
+
return if adapter.respond_to?(:images?) && adapter.images?
|
|
107
|
+
|
|
108
|
+
raise ConfigurationError, "#{@label}: the call has images, but the #{adapter.class} adapter doesn't take " \
|
|
109
|
+
"them (see Adapter::Base#images?)"
|
|
110
|
+
end
|
|
111
|
+
|
|
112
|
+
def adapter_for(step)
|
|
113
|
+
@adapters_lock.synchronize { @adapters[step.adapter] ||= @config.adapter_for(step.adapter) }
|
|
114
|
+
end
|
|
115
|
+
|
|
83
116
|
def capture(job)
|
|
84
117
|
[job.call, nil]
|
|
85
118
|
rescue Exception => e # rubocop:disable Lint/RescueException -- re-raised on the caller's thread
|
|
@@ -87,13 +120,14 @@ module Squishling
|
|
|
87
120
|
end
|
|
88
121
|
|
|
89
122
|
def complete(chat, message, step, reask)
|
|
90
|
-
messages = chat.messages + [{ role: :user, content: message }]
|
|
123
|
+
messages = chat.messages + [{ role: :user, content: content(chat, message) }]
|
|
91
124
|
request = Adapter::Request.new(label: @label, model: step.model, provider: step.provider,
|
|
92
125
|
instructions: chat.instructions, messages:, schema: chat.schema, params: step.request_params(reask),
|
|
93
|
-
cache: step.cache)
|
|
94
|
-
|
|
126
|
+
cache: step.cache, adapter: step.adapter)
|
|
127
|
+
adapter = adapter_for(step)
|
|
128
|
+
response = adapter.complete(request)
|
|
95
129
|
unless response.is_a?(Adapter::Response)
|
|
96
|
-
raise ConfigurationError, "#{@label}: the #{
|
|
130
|
+
raise ConfigurationError, "#{@label}: the #{adapter.class} adapter must return a " \
|
|
97
131
|
"Squishling::Adapter::Response from #complete, got #{response.class}"
|
|
98
132
|
end
|
|
99
133
|
|
|
@@ -101,15 +135,34 @@ module Squishling
|
|
|
101
135
|
@tally.add(response)
|
|
102
136
|
end
|
|
103
137
|
|
|
104
|
-
|
|
105
|
-
|
|
138
|
+
# Each distinct adapter's request context, taken once on the caller's thread.
|
|
139
|
+
def captured_contexts(adapters)
|
|
140
|
+
adapters.each_with_object({}.compare_by_identity) do |adapter, contexts|
|
|
141
|
+
contexts[adapter] = capture_context(adapter) unless contexts.key?(adapter)
|
|
142
|
+
end
|
|
143
|
+
end
|
|
144
|
+
|
|
145
|
+
def capture_context(adapter)
|
|
146
|
+
adapter.capture_context if adapter.respond_to?(:capture_context)
|
|
147
|
+
end
|
|
148
|
+
|
|
149
|
+
# A chat's first message carries its images, after the text, as content parts (see Adapter::Request); every other
|
|
150
|
+
# message is the text alone.
|
|
151
|
+
def content(chat, message)
|
|
152
|
+
return message unless chat.messages.empty? && chat.images&.any?
|
|
153
|
+
|
|
154
|
+
[{ type: :text, text: message }, *chat.images.map { |image| { type: :image, image: } }]
|
|
155
|
+
end
|
|
156
|
+
|
|
157
|
+
def with_context(adapter, context, &)
|
|
158
|
+
return yield unless adapter.respond_to?(:with_context)
|
|
106
159
|
|
|
107
|
-
|
|
160
|
+
adapter.with_context(context, &)
|
|
108
161
|
end
|
|
109
162
|
|
|
110
163
|
def call_info(step, request, attempt:, attempts:, role: nil, sample: nil)
|
|
111
164
|
Observer::Call.new(label: @label, purpose: @purpose, harness: @harness, handed_off: @handed_off, role:, sample:,
|
|
112
|
-
attempt:, attempts:, model: step.model, provider: step.provider, request:)
|
|
165
|
+
attempt:, attempts:, model: step.model, provider: step.provider, adapter: step.adapter, request:)
|
|
113
166
|
end
|
|
114
167
|
end
|
|
115
168
|
end
|
|
@@ -16,11 +16,12 @@ module Squishling
|
|
|
16
16
|
# method's inputs as keywords, on the instance) drops the step from any call where it is falsy.
|
|
17
17
|
# retry_temperature: (a Numeric) is the temperature for the step's same-chat retries after the first attempt.
|
|
18
18
|
module ModelPath
|
|
19
|
-
# One attempt: the model, its provider, the
|
|
19
|
+
# One attempt: the model, its provider, the name of the adapter that makes the request (nil for the default
|
|
20
|
+
# one, see Configuration#adapters), the fully resolved generation params, whether the previous
|
|
20
21
|
# step's rejected output is shown to it, the temperature its retries in the same chat use, if any, and the
|
|
21
22
|
# prompt caching options to request (false for none, see Cache).
|
|
22
|
-
Step = Data.define(:model, :provider, :params, :forward_rejected, :retry_temperature, :cache) do
|
|
23
|
-
def initialize(model:, provider:, params:, forward_rejected:, retry_temperature: nil, cache: false)
|
|
23
|
+
Step = Data.define(:model, :provider, :params, :forward_rejected, :retry_temperature, :cache, :adapter) do
|
|
24
|
+
def initialize(model:, provider:, params:, forward_rejected:, adapter: nil, retry_temperature: nil, cache: false)
|
|
24
25
|
super
|
|
25
26
|
end
|
|
26
27
|
|
|
@@ -36,7 +37,7 @@ module Squishling
|
|
|
36
37
|
end
|
|
37
38
|
end
|
|
38
39
|
|
|
39
|
-
STEP_KEYS = %i[model provider params cache attempts priority order rotate forward_rejected include_when
|
|
40
|
+
STEP_KEYS = %i[model provider adapter params cache attempts priority order rotate forward_rejected include_when
|
|
40
41
|
retry_temperature].freeze
|
|
41
42
|
|
|
42
43
|
module_function
|
|
@@ -78,7 +79,7 @@ module Squishling
|
|
|
78
79
|
# (see Rotation): each tier of tied priorities starts turn steps further along.
|
|
79
80
|
def steps(path, provider:, params:, cache: false, turn: 0)
|
|
80
81
|
rotated(path, turn).flat_map do |step|
|
|
81
|
-
attempt = Step.new(model: step[:model], provider: step[:provider] || provider,
|
|
82
|
+
attempt = Step.new(model: step[:model], provider: step[:provider] || provider, adapter: step[:adapter],
|
|
82
83
|
params: Params.resolve(params, step[:params]), forward_rejected: step[:forward_rejected],
|
|
83
84
|
retry_temperature: step[:retry_temperature], cache: Cache.resolve(cache, step[:cache]))
|
|
84
85
|
[attempt] * step[:attempts]
|
|
@@ -133,7 +134,8 @@ module Squishling
|
|
|
133
134
|
def normalize_step(step, label, extras: [])
|
|
134
135
|
case step
|
|
135
136
|
when String, Symbol
|
|
136
|
-
{ model: model_name(step, label), provider: nil, params: nil, cache: nil, attempts: 1,
|
|
137
|
+
{ model: model_name(step, label), provider: nil, adapter: nil, params: nil, cache: nil, attempts: 1,
|
|
138
|
+
forward_rejected: true }
|
|
137
139
|
when Hash then normalize_hash(step, label, extras)
|
|
138
140
|
else
|
|
139
141
|
raise ConfigurationError, "#{label}: each step must be a model name or a Hash with model:, got #{step.inspect}"
|
|
@@ -172,10 +174,23 @@ module Squishling
|
|
|
172
174
|
|
|
173
175
|
params = step[:params] && Params.normalize(step[:params], "#{label} (#{model}) params")
|
|
174
176
|
cache = Cache.normalize(step[:cache], "#{label} (#{model}) cache")
|
|
175
|
-
|
|
177
|
+
adapter = adapter_name(step[:adapter], label, model)
|
|
178
|
+
normalized = { model:, provider: step[:provider], adapter:, params:, cache:, attempts:, forward_rejected: }
|
|
176
179
|
normalized.merge(step.slice(:priority, :rotate, :include_when, :retry_temperature, *extras))
|
|
177
180
|
end
|
|
178
181
|
|
|
182
|
+
# The name of a configured adapter (see Configuration#adapters) as a Symbol, or nil for the default adapter. Whether
|
|
183
|
+
# the name is configured is checked when the step is used, since a class can load before Squishling.configure runs.
|
|
184
|
+
def adapter_name(adapter, label, model)
|
|
185
|
+
return if adapter.nil?
|
|
186
|
+
unless (adapter.is_a?(Symbol) || adapter.is_a?(String)) && !adapter.to_s.strip.empty?
|
|
187
|
+
raise ConfigurationError,
|
|
188
|
+
"#{label} (#{model}): adapter: must be the name of a configured adapter, got #{adapter.inspect}"
|
|
189
|
+
end
|
|
190
|
+
|
|
191
|
+
adapter.to_sym
|
|
192
|
+
end
|
|
193
|
+
|
|
179
194
|
def check_include_when!(step, label, model)
|
|
180
195
|
return if !step.key?(:include_when) || step[:include_when].is_a?(Proc)
|
|
181
196
|
|
data/lib/squishling/observer.rb
CHANGED
|
@@ -12,9 +12,13 @@ module Squishling
|
|
|
12
12
|
# LLM (typically from a rescue) and false when squish_when or a missing implementation did. role is nil for an
|
|
13
13
|
# escalation attempt, :sample (with sample "a", "b", ...) or :judge, like squawk's metadata. attempt and
|
|
14
14
|
# attempts count the (expanded) escalation path the request belongs to. request is :chat, or :judgment for a
|
|
15
|
-
# System One judge.
|
|
15
|
+
# System One judge. adapter is the name of the configured adapter the step picked (nil for the default one).
|
|
16
16
|
Call = Data.define(:label, :purpose, :harness, :handed_off, :role, :sample, :attempt, :attempts, :model, :provider,
|
|
17
|
-
:request)
|
|
17
|
+
:request, :adapter) do
|
|
18
|
+
def initialize(adapter: nil, **attributes)
|
|
19
|
+
super
|
|
20
|
+
end
|
|
21
|
+
end
|
|
18
22
|
|
|
19
23
|
# What an observer's block returns: the request's token usage and the model that answered, never the content.
|
|
20
24
|
# A count the provider didn't report is nil. cache_read_tokens and cache_write_tokens are the input tokens served
|