squishling 0.5.1 → 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.
@@ -8,19 +8,32 @@ module Squishling
8
8
  # and registering it (Squishling.register_adapter) or assigning an instance to config.adapter. See docs/adapters.md.
9
9
  module Adapter
10
10
  # One completion to make. messages holds the conversation so far as { role: :user | :assistant, content: String }
11
- # Hashes, ending with the user message to answer; instructions is the system prompt. schema is the strict
12
- # structured-output payload ({ "name", "description", "schema", "strict" => true }). params is the resolved
13
- # generation params: the portable :temperature, :max_output_tokens, and :thinking, plus any provider-specific keys
11
+ # Hashes, ending with the user message to answer; instructions is the system prompt. When the call has images
12
+ # (see Image), a chat's first user message has an Array of content parts instead of a String: { type: :text,
13
+ # text: String } and then { type: :image, image: Squishling::Image } per image. Only adapters whose #images? is
14
+ # true are sent them. schema is the strict structured-output payload
15
+ # ({ "name", "description", "schema", "strict" => true }). params is the resolved generation params: the
16
+ # portable :temperature, :max_output_tokens, and :thinking, plus any provider-specific keys
14
17
  # (see Params). label ("Class#method") prefixes the adapter's error messages. model and provider are the step's
15
- # (nil when it names none).
16
- Request = Data.define(:label, :model, :provider, :instructions, :messages, :schema, :params)
18
+ # (nil when it names none). adapter is the name this adapter was configured under (config.adapters), nil for the
19
+ # default adapter. cache is the prompt caching to ask the provider for: false (none), or a Hash of options
20
+ # ({} for the provider's default, { ttl: "1h" }), see Cache. An adapter whose provider has no prompt caching, or
21
+ # caches on its own, ignores it.
22
+ Request = Data.define(:label, :model, :provider, :instructions, :messages, :schema, :params, :cache,
23
+ :adapter) do
24
+ def initialize(label:, model:, provider:, instructions:, messages:, schema:, params:, cache: false,
25
+ adapter: nil)
26
+ super
27
+ end
28
+ end
17
29
 
18
30
  # Stands in for an empty reply when the conversation is replayed: some servers reject an empty assistant message.
19
31
  EMPTY_REPLY = "(no output)"
20
32
 
21
33
  # What a completion returns. content is the model's output: the raw String, or a Hash the adapter already parsed.
22
- # model is the model id the provider reports. tokens is a Hash of counts (:input_tokens, :output_tokens, and
23
- # whatever else the provider reports, such as :cache_read_tokens and :thinking_tokens), empty when unknown.
34
+ # model is the model id the provider reports. tokens is a Hash of counts (:input_tokens, the input not read from or
35
+ # written to the prompt cache, :output_tokens, and whatever else the provider reports, such as :cache_read_tokens,
36
+ # :cache_write_tokens and :thinking_tokens), empty when unknown.
24
37
  # finish_reason is why the provider stopped, as a Symbol: :stop, :max_tokens (the output cap cut the reply off),
25
38
  # :content_filter, :tool_calls, or the provider's own spelling; nil when it reported none.
26
39
  Response = Data.define(:content, :model, :tokens, :finish_reason) do
@@ -108,6 +121,12 @@ module Squishling
108
121
  false
109
122
  end
110
123
 
124
+ # Whether #complete takes images: a message whose content is an Array of parts (see Request). A call with images
125
+ # through an adapter that doesn't is a ConfigurationError, made before any request.
126
+ def images?
127
+ false
128
+ end
129
+
111
130
  # A System One judgment: input (a Hash) and questions (a Hash of name => question), with the step's model and
112
131
  # params. Returns an object answering [name] with an answer that responds to choice and probabilities. label
113
132
  # ("Class#method") prefixes error messages. Called as judge(input, questions:, step:, label:).
@@ -20,7 +20,8 @@ module Squishling
20
20
  class OpenAICompatible < Adapter::Base
21
21
  Options = OpenAIOptions
22
22
  Transport = OpenAITransport
23
- private_constant :Options, :Transport
23
+ Content = OpenAIContent
24
+ private_constant :Options, :Transport, :Content
24
25
 
25
26
  DEFAULT_BASE_URL = "https://api.openai.com/v1"
26
27
  STRUCTURED_OUTPUT = %i[json_schema json_object none].freeze
@@ -76,6 +77,11 @@ module Squishling
76
77
  "default_model=#{@default_model.inspect} structured_output=#{@structured_output.inspect}>"
77
78
  end
78
79
 
80
+ # Images go out as image_url content parts (a data: URI, or the image's own URL).
81
+ def images?
82
+ true
83
+ end
84
+
79
85
  def complete(request)
80
86
  model = request.model || @default_model
81
87
  unless model
@@ -117,7 +123,9 @@ module Squishling
117
123
 
118
124
  def messages(request)
119
125
  system = system_prompt(request)
120
- turns = request.messages.map { |message| { "role" => message[:role].to_s, "content" => message[:content] } }
126
+ turns = request.messages.map do |message|
127
+ { "role" => message[:role].to_s, "content" => Content.of(message[:content]) }
128
+ end
121
129
  system ? [{ "role" => "system", "content" => system }] + turns : turns
122
130
  end
123
131
 
@@ -292,14 +300,25 @@ module Squishling
292
300
  def tokens_of(usage)
293
301
  return {} unless usage.is_a?(Hash)
294
302
 
303
+ cached = detail(usage, "prompt_tokens_details", "cached_tokens")
304
+ written = detail(usage, "prompt_tokens_details", "cache_write_tokens")
295
305
  {
296
- input_tokens: usage["prompt_tokens"],
306
+ input_tokens: uncached(usage["prompt_tokens"], cached, written),
297
307
  output_tokens: usage["completion_tokens"],
298
- cache_read_tokens: detail(usage, "prompt_tokens_details", "cached_tokens"),
308
+ cache_read_tokens: cached,
309
+ cache_write_tokens: written,
299
310
  thinking_tokens: detail(usage, "completion_tokens_details", "reasoning_tokens")
300
311
  }.select { |_, count| count.is_a?(Integer) }
301
312
  end
302
313
 
314
+ # prompt_tokens counts the tokens read from and written to the cache; input_tokens is the rest, as every adapter
315
+ # reports it (see Adapter::Response), so they aren't counted twice.
316
+ def uncached(prompt_tokens, *cached)
317
+ return prompt_tokens unless prompt_tokens.is_a?(Integer)
318
+
319
+ [prompt_tokens - cached.grep(Integer).sum, 0].max
320
+ end
321
+
303
322
  # A count inside a usage sub-object, which a server might send in any shape.
304
323
  def detail(usage, group, key)
305
324
  usage[group][key] if usage[group].is_a?(Hash)
@@ -0,0 +1,23 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Squishling
4
+ module Adapters
5
+ # A message's content as the Chat Completions API takes it: a String as is, or content parts (see
6
+ # Adapter::Request) as text and image_url parts, an image as a data: URI or its own URL.
7
+ module OpenAIContent
8
+ module_function
9
+
10
+ def of(value)
11
+ return value unless value.is_a?(Array)
12
+
13
+ value.map { |part| part[:type] == :image ? image(part[:image]) : { "type" => "text", "text" => part[:text] } }
14
+ end
15
+
16
+ def image(image)
17
+ url = { "url" => image.url || image.data_uri }
18
+ url["detail"] = image.detail.to_s if image.detail
19
+ { "type" => "image_url", "image_url" => url }
20
+ end
21
+ end
22
+ end
23
+ end
@@ -1,5 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require "stringio"
4
+
3
5
  module Squishling
4
6
  module Adapters
5
7
  # Sends requests through RubyLLM (https://rubyllm.com): OpenAI, Anthropic Claude, Google Gemini, AWS Bedrock,
@@ -36,9 +38,7 @@ module Squishling
36
38
  # released ones) are only usable when a provider is named, so RubyLLM is told to assume they exist.
37
39
  def complete(request)
38
40
  chat = build_chat(request)
39
- *history, last = request.messages
40
- history.each { |message| chat.add_message(role: message[:role], content: message[:content]) }
41
- response = guarded(request) { chat.ask(last[:content]) }
41
+ response = guarded(request) { replay_and_ask(chat, request) }
42
42
  Adapter::Response.new(content: response.content, model: response.model, tokens: tokens_of(response),
43
43
  finish_reason: response.finish_reason)
44
44
  end
@@ -47,6 +47,11 @@ module Squishling
47
47
  true
48
48
  end
49
49
 
50
+ # Images go to RubyLLM as attachments: the bytes, or the image's URL.
51
+ def images?
52
+ true
53
+ end
54
+
50
55
  # A System One judgment (RubyLLM.judge) on one step. The step's params are sent as provider options.
51
56
  # RubyLLM raises ArgumentError for a judgment it can't build (e.g. a model on a provider that takes none, or
52
57
  # a provider option its protocol reserves), and a bare RubyLLM::Error without an HTTP response for a provider
@@ -82,6 +87,43 @@ module Squishling
82
87
 
83
88
  private
84
89
 
90
+ # The conversation so far added to the chat, then its last message asked. Building an attachment can fetch an
91
+ # image's URL (RubyLLM reads the media type from the response when the URL has no extension), so the history is
92
+ # guarded like the request itself.
93
+ def replay_and_ask(chat, request)
94
+ *history, last = request.messages
95
+ history.each do |message|
96
+ text, attachments = split(message[:content])
97
+ chat.add_message({ role: message[:role], content: text, attachments: }.compact)
98
+ end
99
+ ask(chat, request, *split(last[:content]))
100
+ end
101
+
102
+ # RubyLLM checks a caching option against the provider when it renders the request, and raises ArgumentError for
103
+ # one it can't use. That is the developer's setting, so it is a setup mistake rather than a failed request.
104
+ def ask(chat, request, content, attachments = nil)
105
+ attachments ? chat.ask(content, with: attachments) : chat.ask(content)
106
+ rescue ArgumentError => e
107
+ raise unless request.cache && e.message.match?(/caching/i) && raised_by_ruby_llm?(e)
108
+
109
+ raise configuration_error(request,
110
+ "RubyLLM rejected the request, cache #{request.cache.inspect} (#{e.message})")
111
+ end
112
+
113
+ # A message's text and its images as RubyLLM attachments (nil when it has none).
114
+ def split(content)
115
+ return [content, nil] unless content.is_a?(Array)
116
+
117
+ text = content.filter_map { |part| part[:text] if part[:type] == :text }.join("\n\n")
118
+ images = content.filter_map { |part| attachment(part[:image]) if part[:type] == :image }
119
+ [text, images]
120
+ end
121
+
122
+ def attachment(image)
123
+ source = image.url? ? image.url : StringIO.new(image.data)
124
+ ::RubyLLM::Attachment.new(source, filename: image.filename, resolution: image.detail)
125
+ end
126
+
85
127
  def tokens_of(response)
86
128
  response.tokens ? response.tokens.to_h : {}
87
129
  end
@@ -106,6 +148,7 @@ module Squishling
106
148
  chat.with_instructions(request.instructions)
107
149
  chat.with_schema(request.schema)
108
150
  apply_params(chat, request)
151
+ apply_cache(chat, request)
109
152
  chat
110
153
  rescue ::RubyLLM::ModelNotFoundError, ::RubyLLM::ConfigurationError => e
111
154
  raise configuration_error(request, e.message)
@@ -124,6 +167,12 @@ module Squishling
124
167
  raise configuration_error(request, "invalid params #{params.keys.inspect} (#{e.message})")
125
168
  end
126
169
 
170
+ # Prompt caching is only asked for when the request carries it: off sends no cache controls. RubyLLM checks the
171
+ # options when it renders the request, so an unusable one is reported by #ask.
172
+ def apply_cache(chat, request)
173
+ chat.with_caching(request.cache) if request.cache
174
+ end
175
+
127
176
  # true: the model's default thinking; false: off; a Hash: { effort:, budget:, display: }.
128
177
  def apply_thinking(chat, thinking)
129
178
  thinking.is_a?(Hash) ? chat.with_thinking(**thinking) : chat.with_thinking(thinking)
@@ -33,17 +33,20 @@ module Squishling
33
33
  # threads, so the totals are taken under a lock. A response without token counts adds nothing, so a provider that
34
34
  # reports no usage never exhausts a budget.
35
35
  class Tally
36
- def initialize(budget)
36
+ def initialize(budget, cache_reads: false)
37
37
  @budget = budget
38
+ @cache_reads = cache_reads
38
39
  @used = { input_tokens: 0, output_tokens: 0 }
39
40
  @lock = Mutex.new
40
41
  end
41
42
 
42
- # Counts a response's tokens: an Adapter::Response, or a judgment (see Observer.usage).
43
+ # Counts a response's tokens: an Adapter::Response, or a judgment (see Observer.usage). The input total includes
44
+ # the tokens written to the prompt cache, and those read from it only when cache_reads is set; adapters report
45
+ # both apart from input_tokens.
43
46
  def add(response)
44
47
  usage = Observer.usage(response)
45
48
  @lock.synchronize do
46
- @used[:input_tokens] += count(usage.input_tokens)
49
+ @used[:input_tokens] += input_count(usage)
47
50
  @used[:output_tokens] += count(usage.output_tokens)
48
51
  end
49
52
  response
@@ -63,6 +66,11 @@ module Squishling
63
66
 
64
67
  private
65
68
 
69
+ def input_count(usage)
70
+ total = count(usage.input_tokens) + count(usage.cache_write_tokens)
71
+ @cache_reads ? total + count(usage.cache_read_tokens) : total
72
+ end
73
+
66
74
  def count(tokens)
67
75
  tokens.is_a?(Integer) && tokens.positive? ? tokens : 0
68
76
  end
@@ -0,0 +1,33 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Squishling
4
+ # Prompt caching: whether a request asks the provider to cache the stable prompt (the purpose and the input note in
5
+ # the system prompt), layered config -> class -> method -> squish! like generation params, and per escalation step.
6
+ # A level declares true, false, or a Hash of options (ttl: "1h"), and nil leaves it to the level above. What a
7
+ # request carries is false (no cache controls) or a Hash of options ({} for the provider's default). See
8
+ # docs/configuration.md.
9
+ module Cache
10
+ module_function
11
+
12
+ # One level's value, validated: nil (inherit), true, false, or a frozen Hash with Symbol keys. Explicit provider
13
+ # caches (id:) are not supported: an adapter holds no state between requests.
14
+ def normalize(value, label)
15
+ return value if value.nil? || [true, false].include?(value)
16
+ unless value.is_a?(Hash)
17
+ raise ConfigurationError, "#{label} must be true, false, or a Hash of options, got #{value.inspect}"
18
+ end
19
+
20
+ options = value.transform_keys(&:to_sym)
21
+ raise ConfigurationError, "#{label}: id: (an explicit provider cache) isn't supported" if options.key?(:id)
22
+
23
+ options.freeze
24
+ end
25
+
26
+ # What the request carries: the last level that declares a value wins (a Hash replaces, it doesn't merge), and no
27
+ # level at all means off. true is the provider's default options.
28
+ def resolve(*layers)
29
+ value = layers.reverse.find { |layer| !layer.nil? }
30
+ value == true ? {}.freeze : value || false
31
+ end
32
+ end
33
+ end
@@ -15,6 +15,9 @@ module Squishling
15
15
  # parent's provider.
16
16
  # params: are generation params merged over the configured defaults (see Configuration#default_params):
17
17
  # squishling params: { temperature: 0.1, top_p: 0.9 }
18
+ # cache: asks the provider to cache the stable prompt (true by default, see Cache); false opts the class out, and
19
+ # a Hash such as { ttl: "1h" } passes options through:
20
+ # squishling cache: false
18
21
  # append_to_purpose: adds sections after the purpose (see #append_to_purpose):
19
22
  # squishling append_to_purpose: ["The Ruby that handles well-formed input:", self]
20
23
  # harness: chooses how the escalation is used (see Harness):
@@ -29,7 +32,7 @@ module Squishling
29
32
  # squawk_on: limits which attempts reach the hook: :all (the default), :rejections, :retries, :final, or a
30
33
  # list of them (any one holding runs the hook):
31
34
  # squishling squawk: hook, squawk_on: %i[rejections final]
32
- def squishling(model: nil, escalation: nil, provider: nil, params: nil, harness: nil, purpose: nil,
35
+ def squishling(model: nil, escalation: nil, provider: nil, params: nil, cache: nil, harness: nil, purpose: nil,
33
36
  append_to_purpose: nil, output_schema: nil, squawk: nil, squawk_on: nil, max_total_output_tokens: nil,
34
37
  max_total_input_tokens: nil)
35
38
  path = ModelPath.declare(model, escalation, to_s)
@@ -44,8 +47,7 @@ module Squishling
44
47
  # provider meant for its parent's.
45
48
  @squishling_model_path = path if path
46
49
  @squishling_provider = provider if provider || path
47
- @squishling_params = Params.normalize(params, "#{self} params") if params
48
- @squishling_harness = Harness.normalize(harness, to_s) unless harness.nil?
50
+ declare_generation(params, cache, harness)
49
51
  self.purpose(purpose) if purpose
50
52
  self.append_to_purpose(append_to_purpose) unless append_to_purpose.nil?
51
53
  self.output_schema(output_schema) if output_schema
@@ -76,6 +78,11 @@ module Squishling
76
78
  squishling_lookup(:@squishling_provider)
77
79
  end
78
80
 
81
+ # The class's (or nearest ancestor's) cache setting (see Cache), nil when none declared it.
82
+ def squishling_cache
83
+ squishling_lookup(:@squishling_cache)
84
+ end
85
+
79
86
  def squishling_harness
80
87
  squishling_lookup(:@squishling_harness)
81
88
  end
@@ -171,13 +178,14 @@ module Squishling
171
178
  # string :priority
172
179
  # end
173
180
  def squish(*names, purpose: nil, append_to_purpose: nil, output_schema: nil, model: nil, escalation: nil,
174
- provider: nil, params: nil, harness: nil, when: nil, fallback: nil, validate: nil, squawk: nil,
175
- squawk_on: nil, max_total_output_tokens: nil, max_total_input_tokens: nil, &schema_block)
181
+ provider: nil, params: nil, cache: nil, harness: nil, when: nil, fallback: nil, validate: nil,
182
+ squawk: nil, squawk_on: nil, max_total_output_tokens: nil, max_total_input_tokens: nil, &schema_block)
176
183
  schema = schema_block ? Schematist::Schema.create(&schema_block) : output_schema
177
184
  model = ModelPath.declare(model, escalation, "#{self} squish")
178
185
  raise ConfigurationError, "#{self} squish: provider: needs a model: or escalation:" if provider && !model
179
186
 
180
187
  params &&= Params.normalize(params, "#{self} squish params")
188
+ cache = Cache.normalize(cache, "#{self} squish cache")
181
189
  harness = Harness.normalize(harness, "#{self} squish") unless harness.nil?
182
190
  unless append_to_purpose.nil?
183
191
  append_to_purpose = Appendices.normalize(append_to_purpose, "#{self} squish append_to_purpose")
@@ -185,7 +193,7 @@ module Squishling
185
193
  squawk = Squawk.validate(squawk, "#{self} squish")
186
194
  squawk_on = Squawk.validate_on(squawk_on, "#{self} squish")
187
195
  budget = Budget.build("#{self} squish", output: max_total_output_tokens, input: max_total_input_tokens)
188
- options = { purpose:, append_to_purpose:, output_schema: schema, model:, provider:, params:, harness:,
196
+ options = { purpose:, append_to_purpose:, output_schema: schema, model:, provider:, params:, cache:, harness:,
189
197
  predicate: binding.local_variable_get(:when), fallback:, validator: validate, squawk:,
190
198
  squawk_on:, budget: }.compact
191
199
 
@@ -216,6 +224,13 @@ module Squishling
216
224
 
217
225
  private
218
226
 
227
+ # nil leaves a level unset (so the parent's applies); false for cache: is stored, to opt the class out.
228
+ def declare_generation(params, cache, harness)
229
+ @squishling_params = Params.normalize(params, "#{self} params") if params
230
+ @squishling_cache = Cache.normalize(cache, "#{self} cache") unless cache.nil?
231
+ @squishling_harness = Harness.normalize(harness, to_s) unless harness.nil?
232
+ end
233
+
219
234
  # nil leaves a level unset (so the parent's applies); false for squawk: is stored, to silence it.
220
235
  def declare_squawk(squawk, squawk_on)
221
236
  @squishling_squawk = Squawk.validate(squawk, to_s) unless squawk.nil?
@@ -24,6 +24,14 @@ module Squishling
24
24
  # adapter for its provider; any other key (top_p, seed, ...) is passed to the provider as-is.
25
25
  attr_reader :default_params
26
26
 
27
+ # Whether requests ask the provider to cache the stable prompt: true (the default), false, or a Hash of options
28
+ # such as { ttl: "1h" } (see Cache). Overridable per class, per method, per escalation step, and per squish! call.
29
+ attr_reader :default_cache
30
+
31
+ # Whether the tokens a request reads from the provider's prompt cache count toward max_total_input_tokens: false
32
+ # (the default) leaves them out, true counts them. Tokens written to the cache always count (see Budget).
33
+ attr_reader :budget_counts_cache_reads
34
+
27
35
  # How every squishling class that doesn't declare its own harness uses its escalation (see Harness):
28
36
  # :escalation (the default), :squishsum, :judged_squishsum, a harness you registered, or a Hash with type: and
29
37
  # its options.
@@ -57,8 +65,19 @@ module Squishling
57
65
  # gem is available. Built when assigned, so a mistake fails at setup rather than on the first request.
58
66
  attr_reader :adapter
59
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
+
60
77
  def initialize
61
78
  @adapter = nil
79
+ @adapters = {}.freeze
80
+ @adapter_override = nil
62
81
  @detected_adapter = nil
63
82
  @adapter_lock = Mutex.new
64
83
  @observer = nil
@@ -67,6 +86,8 @@ module Squishling
67
86
  @default_model_path = nil
68
87
  @default_provider = nil
69
88
  @default_params = {}
89
+ @default_cache = true
90
+ @budget_counts_cache_reads = false
70
91
  @default_harness = nil
71
92
  @logger = nil
72
93
  @squawk = nil
@@ -93,6 +114,37 @@ module Squishling
93
114
  end
94
115
  end
95
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
+
96
148
  # The adapter requests go through: the configured one, else RubyLLM's (when its gem is available) built on first
97
149
  # use. Raises ConfigurationError when there is neither.
98
150
  def resolved_adapter
@@ -131,6 +183,21 @@ module Squishling
131
183
  @default_params = Params.normalize(params, "default_params")
132
184
  end
133
185
 
186
+ # nil restores the default (true).
187
+ def default_cache=(cache)
188
+ @default_cache = cache.nil? || Cache.normalize(cache, "default_cache")
189
+ end
190
+
191
+ # true or false; unlike default_cache=, nil is not accepted.
192
+ def budget_counts_cache_reads=(counts)
193
+ unless [true, false].include?(counts)
194
+ raise ConfigurationError,
195
+ "Squishling.configure: budget_counts_cache_reads must be true or false, got #{counts.inspect}"
196
+ end
197
+
198
+ @budget_counts_cache_reads = counts
199
+ end
200
+
134
201
  def default_harness=(harness)
135
202
  @default_harness = harness.nil? ? nil : Harness.normalize(harness, "default_harness")
136
203
  end
@@ -146,5 +213,19 @@ module Squishling
146
213
  def max_retries=(_value)
147
214
  raise ConfigurationError, MAX_RETRIES_REMOVED
148
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
149
230
  end
150
231
  end
@@ -13,8 +13,8 @@ module Squishling
13
13
  attr_reader :klass, :name, :call_context, :handed_off
14
14
 
15
15
  def initialize(klass:, name:, purpose: nil, append_to_purpose: nil, output_schema: nil, model: nil,
16
- provider: nil, params: nil, harness: nil, predicate: nil, fallback: nil, validator: nil, squawk: nil,
17
- squawk_on: nil, budget: nil, call_context: {}, handed_off: false)
16
+ provider: nil, params: nil, cache: nil, harness: nil, predicate: nil, fallback: nil, validator: nil,
17
+ squawk: nil, squawk_on: nil, budget: nil, call_context: {}, handed_off: false)
18
18
  @klass = klass
19
19
  @name = name
20
20
  @purpose = purpose
@@ -23,6 +23,7 @@ module Squishling
23
23
  @model = model
24
24
  @provider = provider
25
25
  @params = params
26
+ @cache = cache
26
27
  @harness = harness
27
28
  @predicate = predicate
28
29
  @fallback = fallback
@@ -37,15 +38,16 @@ module Squishling
37
38
  # This definition with one call's overrides on top. The output schema, predicate, fallback, and validator
38
39
  # can't be overridden: the call must still return the method's result type.
39
40
  def for_call(purpose: nil, append_to_purpose: nil, context: nil, model: nil, escalation: nil,
40
- provider: nil, params: nil, harness: nil, max_total_output_tokens: nil, max_total_input_tokens: nil)
41
+ provider: nil, params: nil, cache: nil, harness: nil, max_total_output_tokens: nil,
42
+ max_total_input_tokens: nil)
41
43
  call_path = ModelPath.declare(model, escalation, "#{label} squish!")
42
44
  raise ConfigurationError, "#{label}: squish! provider: needs a model: or escalation:" if provider && !call_path
43
- unless context.nil? || (context.is_a?(Hash) && context.each_key.all?(NAME_KEY))
44
- raise ConfigurationError, "#{label}: squish! context: must be a Hash with String or Symbol keys"
45
- end
45
+
46
+ check_context!(context)
46
47
 
47
48
  appended = Appendices.normalize(append_to_purpose, "#{label} squish!") unless append_to_purpose.nil?
48
49
  call_params = params && Params.normalize(params, "#{label} squish! params")
50
+ call_cache = Cache.normalize(cache, "#{label} squish! cache")
49
51
  call_harness = Harness.normalize(harness, "#{label} squish!") unless harness.nil?
50
52
  call_budget = Budget.build("#{label} squish!", output: max_total_output_tokens, input: max_total_input_tokens)
51
53
  self.class.new(
@@ -56,6 +58,7 @@ module Squishling
56
58
  model: call_path || @model, provider: call_path ? provider : @provider,
57
59
  # merge, not Params.resolve: a nil at the method level must still unset the class's key.
58
60
  params: call_params ? (@params || {}).merge(call_params) : @params,
61
+ cache: [call_cache, @cache].find { |level| !level.nil? },
59
62
  harness: call_harness || @harness, budget: @budget.merge(call_budget),
60
63
  call_context: @call_context.merge((context || {}).transform_keys(&:to_sym)),
61
64
  handed_off: true # only squish! builds a definition this way; it is not part of a declared one
@@ -101,7 +104,7 @@ module Squishling
101
104
  else
102
105
  0
103
106
  end
104
- ModelPath.steps(eligible, provider:, params:, turn:)
107
+ ModelPath.steps(eligible, provider:, params:, cache:, turn:)
105
108
  end
106
109
 
107
110
  # The steps and provider of the first level (method, class, or config) that declares a model or escalation, or
@@ -139,6 +142,12 @@ module Squishling
139
142
  Params.resolve(Squishling.config.default_params, klass.squishling_params, @params)
140
143
  end
141
144
 
145
+ # Prompt caching: false, or the options to ask the provider for (see Cache). The config default, overridden by the
146
+ # class, then the method (and a squish! call).
147
+ def cache
148
+ Cache.resolve(Squishling.config.default_cache, klass.squishling_cache, @cache)
149
+ end
150
+
142
151
  # The token limits of one call (see Budget): config defaults, overridden limit by limit by the class, then by the
143
152
  # method (and a squish! call).
144
153
  def budget
@@ -247,6 +256,12 @@ module Squishling
247
256
 
248
257
  private
249
258
 
259
+ def check_context!(context)
260
+ return if context.nil? || (context.is_a?(Hash) && context.each_key.all?(NAME_KEY))
261
+
262
+ raise ConfigurationError, "#{label}: squish! context: must be a Hash with String or Symbol keys"
263
+ end
264
+
250
265
  # Values JSON can't represent (NaN, Infinity, cycles) are invalid output, not a raw JSON error.
251
266
  def jsonify_return(attrs)
252
267
  [Schema.jsonify(attrs), []]