emb 0.4.3.pre6 → 0.5.0.pre1

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.
data/lib/emb/commands.rb CHANGED
@@ -101,7 +101,10 @@ module Emb
101
101
  schema = normalize_decode(decode)
102
102
  return Emb.build_script_loader(self, argv, schema) if lazy?
103
103
 
104
- parse_script_reply(send_command(*argv), multi: argv[3].to_i > 1, decode: schema)
104
+ Emb::Telemetry.embed_call(operation: 'script', model: argv[1], texts: argv[3].to_i,
105
+ format: nil, mode: 'eager') do
106
+ parse_script_reply(send_command(*argv), multi: argv[3].to_i > 1, decode: schema)
107
+ end
105
108
  end
106
109
 
107
110
  # Parse Redis INFO section text into a nested Hash:
@@ -3,7 +3,7 @@
3
3
  module Emb
4
4
  class Configuration
5
5
  OPTIONS = %i[
6
- host port url pool lazy batch_size driver protocol
6
+ host port url pool lazy batch_size max_image_batch_bytes driver protocol
7
7
  connect_timeout read_timeout write_timeout reconnect_attempts
8
8
  ].freeze
9
9
 
@@ -36,6 +36,19 @@ module Emb
36
36
  @protocol = value
37
37
  end
38
38
 
39
+ # Deferred image calls retain their encoded bytes until the scope is
40
+ # forced: README.md#images. Must be a positive Integer (32 MiB by default).
41
+ def max_image_batch_bytes=(value)
42
+ self.class.validate_image_batch_bytes!(value)
43
+ @max_image_batch_bytes = value
44
+ end
45
+
46
+ def self.validate_image_batch_bytes!(value)
47
+ return if value.is_a?(Integer) && value.positive?
48
+
49
+ raise ArgumentError, "max_image_batch_bytes must be a positive Integer (got #{value.inspect})"
50
+ end
51
+
39
52
  def initialize
40
53
  self.host = 'localhost'
41
54
  self.port = 6379
@@ -43,6 +56,23 @@ module Emb
43
56
  self.pool = 5
44
57
  self.lazy = false
45
58
  self.batch_size = 512
59
+ # Deferred image payloads are bounded by total encoded bytes as well as
60
+ # by batch_size; the default matches the server's per-image byte cap.
61
+ apply_image_defaults
62
+ apply_network_defaults
63
+ end
64
+
65
+ def to_h
66
+ OPTIONS.to_h { |key| [key, public_send(key)] }
67
+ end
68
+
69
+ private
70
+
71
+ def apply_image_defaults
72
+ self.max_image_batch_bytes = 32 * 1024 * 1024
73
+ end
74
+
75
+ def apply_network_defaults
46
76
  self.driver = nil
47
77
  self.protocol = 2
48
78
  self.connect_timeout = nil
@@ -62,9 +92,5 @@ module Emb
62
92
  # retried.
63
93
  self.reconnect_attempts = 0
64
94
  end
65
-
66
- def to_h
67
- OPTIONS.to_h { |key| [key, public_send(key)] }
68
- end
69
95
  end
70
96
  end
@@ -21,12 +21,20 @@ module Emb
21
21
 
22
22
  attr_reader :pools
23
23
 
24
+ # Thread-local label of the instance that last served a command, read by
25
+ # telemetry right after a command returns. host:port only: a redis URL can
26
+ # carry a password in its userinfo, which must never reach a span.
27
+ LAST_INSTANCE = :emb_last_instance
28
+
29
+ def self.last_instance = Thread.current[LAST_INSTANCE]
30
+
24
31
  def initialize(size, urls, redis_options)
25
32
  @pools = urls.map do |url|
26
33
  RoundRobinPool.new(size) do
27
34
  RedisClient.new(url: url, **redis_options)
28
35
  end
29
36
  end
37
+ @labels = urls.map { |url| instance_label(url) }
30
38
  @next_instance = 0
31
39
  @instance_mutex = Mutex.new
32
40
  end
@@ -36,7 +44,7 @@ module Emb
36
44
  idx = pick_instance
37
45
  last_error = nil
38
46
  attempts.times do
39
- return perform_command(@pools[idx], args)
47
+ return perform_command(@pools[idx], args, @labels[idx])
40
48
  rescue PRESEND_CONNECTION_ERROR => e
41
49
  last_error = e
42
50
  idx = (idx + 1) % @pools.size if @pools.size > 1
@@ -46,6 +54,20 @@ module Emb
46
54
 
47
55
  private
48
56
 
57
+ # host[:port] of a redis URL. Never the URL text itself: its userinfo can
58
+ # hold a password and its query can hold one. Parsed by hand rather than
59
+ # with URI, which accepts some credential shapes as host and port.
60
+ # nil when nothing is left (no URL configured) so the attribute is absent.
61
+ def instance_label(url)
62
+ return nil if url.nil?
63
+
64
+ label = url.to_s.split(/[?#]/, 2).first.split('://', 2).last.to_s
65
+ userinfo = label.rindex('@')
66
+ label = label[(userinfo + 1)..] if userinfo
67
+ label = label.split('/').first.to_s
68
+ label unless label.empty?
69
+ end
70
+
49
71
  def pick_instance
50
72
  return 0 if @pools.size == 1
51
73
 
@@ -56,7 +78,8 @@ module Emb
56
78
  end
57
79
  end
58
80
 
59
- def perform_command(pool, args)
81
+ def perform_command(pool, args, label)
82
+ Thread.current[LAST_INSTANCE] = label if Emb::Telemetry.available?
60
83
  debug = Emb.debug?
61
84
  started = Process.clock_gettime(Process::CLOCK_MONOTONIC) if debug
62
85
  result = pool.with { |r| r.call(*args) }
data/lib/emb/errors.rb CHANGED
@@ -14,4 +14,9 @@ module Emb
14
14
  @attempts = attempts
15
15
  end
16
16
  end
17
+
18
+ # Raised when deferring another image call would exceed the pending scope's
19
+ # `batch_size` image count or its `max_image_batch_bytes` total. The image is
20
+ # not queued or sent; force the pending values or start a new scope.
21
+ class ImageBatchLimitError < StandardError; end
17
22
  end
@@ -0,0 +1,119 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'batch_loader'
4
+ require_relative 'image_command'
5
+
6
+ module Emb
7
+ # Deferred image batching: the item layout, scope bounds, compatible-group
8
+ # shares, and ordered reply resolution. Kept out of BatchDispatch (which
9
+ # stays under its Metrics::ModuleLength budget) and out of BATCH_BLOCK, which
10
+ # only partitions items and hands image work here.
11
+ module ImageBatch
12
+ # Identity sentinel in slot 1 of an image batch item. Items are
13
+ # [client, ITEM, model, images, format, output_names]; a unique object
14
+ # matched with #equal? cannot collide with a model name.
15
+ ITEM = Object.new
16
+
17
+ module_function
18
+
19
+ # Registers one deferred image call, refusing it before queue insertion
20
+ # when the pending scope would exceed either bound. An identical pending
21
+ # item already carries this payload (batch-loader dedupes it to one wire
22
+ # item), so a repeat call is not charged against the bound again.
23
+ def build(client, model, images, format:, names:)
24
+ item = [client, ITEM, model, images, format, names]
25
+ check_limits!(client, images) unless pending_items&.include?(item)
26
+ loader = BatchLoader.for(item).batch(default_value: [], key: Emb::BATCH_KEY, &Emb::BATCH_BLOCK)
27
+ Telemetry::Deferred.record(
28
+ item, Telemetry.entry_for(client, operation: 'image', model: model, texts: images.size, format: format)
29
+ )
30
+ loader
31
+ end
32
+
33
+ # Groups only compatible calls (model, format, projection). The scope bound
34
+ # already caps the pending scope at batch_size images, so one group is one
35
+ # EMB.IMG share; there is no chunk to split.
36
+ def shares(items)
37
+ items.group_by { |item| [item[2], item[4], item[5]] }.values
38
+ end
39
+
40
+ # One EMB.IMG carrying every image of the slice in deferral order.
41
+ def args(slice)
42
+ first = slice.first
43
+ ImageCommand.args(first[2], slice.flat_map { |item| item[3] }, format: first[4], names: first[5])
44
+ end
45
+
46
+ # Maps the reply's per-image entries back onto each item, preserving the
47
+ # eager shape: a Hash for a one-image call, an Array of Hashes for several,
48
+ # nil for a failed or truncated image.
49
+ def resolve(loader, slice, results)
50
+ expected = slice.sum { |item| item[3].size }
51
+ raise ShortReplyError, "expected #{expected} image reply entries, got #{results.size}" if results.size < expected
52
+
53
+ offset = 0
54
+ slice.each do |item|
55
+ value, offset = decode_item(item, results, offset)
56
+ loader.call(item, value)
57
+ Telemetry::Deferred.resolve(item)
58
+ end
59
+ end
60
+
61
+ # One item's slice of the reply, decoded per image, in the eager shape.
62
+ def decode_item(item, results, offset)
63
+ images = item[3]
64
+ decoded = results[offset, images.size].map do |entry|
65
+ entry.nil? ? nil : ImageCommand.decode(entry, item[4])
66
+ end
67
+ [images.size == 1 ? decoded.first : decoded, offset + images.size]
68
+ end
69
+
70
+ # Bytes this client's pending scope can still hold. The deferred path bounds
71
+ # IO reads by it, so the read itself refuses a stream over the limit.
72
+ def remaining_bytes(client)
73
+ _, used = pending_usage(client)
74
+ _, max_bytes = limits(client)
75
+ [max_bytes - used, 0].max
76
+ end
77
+
78
+ # Enforces both bounds against the items already pending in this thread's
79
+ # batch scope. Deriving the usage from batch-loader's own pending set (and
80
+ # not a second counter) means the existing scope cleanup releases it,
81
+ # including when a request or job raises.
82
+ def check_limits!(client, images)
83
+ count, bytes = pending_usage(client)
84
+ max_count, max_bytes = limits(client)
85
+ if count + images.size > max_count
86
+ raise ImageBatchLimitError,
87
+ "deferred image scope would exceed batch_size (#{max_count} images)"
88
+ end
89
+ return unless bytes + images.sum(&:bytesize) > max_bytes
90
+
91
+ raise ImageBatchLimitError,
92
+ "deferred image scope would exceed max_image_batch_bytes (#{max_bytes} bytes)"
93
+ end
94
+
95
+ def pending_usage(client)
96
+ items = pending_items
97
+ return [0, 0] unless items
98
+
99
+ items.each_with_object([0, 0]) { |item, totals| add_usage(totals, item, client) }
100
+ end
101
+
102
+ def pending_items
103
+ BatchLoader::Executor.current&.items_by_block&.[](Emb::BATCH_PENDING_KEY)
104
+ end
105
+
106
+ def add_usage(totals, item, client)
107
+ return unless item[1].equal?(ITEM) && item[0].equal?(client)
108
+
109
+ totals[0] += item[3].size
110
+ totals[1] += item[3].sum(&:bytesize)
111
+ end
112
+
113
+ def limits(client)
114
+ count = client.respond_to?(:batch_size) && client.batch_size
115
+ bytes = client.respond_to?(:max_image_batch_bytes) && client.max_image_batch_bytes
116
+ [count || Emb.configuration.batch_size, bytes || Emb.configuration.max_image_batch_bytes]
117
+ end
118
+ end
119
+ end
@@ -0,0 +1,64 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'values_reply'
4
+
5
+ module Emb
6
+ # The image command surface shared by Proxy (eager and deferred EMB.IMG), the
7
+ # deferred batch dispatcher, and MultiProxy (EMB.IMGMULTI): keyword placement,
8
+ # format validation, and keyed reply decoding, so the callers cannot drift.
9
+ module ImageCommand
10
+ FORMATS = %i[binary values].freeze
11
+
12
+ module_function
13
+
14
+ def validate_format!(format)
15
+ return format if FORMATS.include?(format)
16
+
17
+ raise ArgumentError, "unknown format #{format.inspect} (expected :binary or :values)"
18
+ end
19
+
20
+ # EMB.IMG <model> [VALUES] [OUTPUTS name,...] <bytes>...
21
+ def args(model, images, format:, names:)
22
+ command = ['EMB.IMG', model.to_s]
23
+ command << 'VALUES' if format == :values
24
+ command << 'OUTPUTS' << names.join(',') unless names.empty?
25
+ command.concat(images)
26
+ end
27
+
28
+ # EMB.IMGMULTI [VALUES] [OUTPUTS name,...] <model> <bytes> <model> <bytes>...
29
+ def multi_args(pairs, format:, names: [])
30
+ command = ['EMB.IMGMULTI']
31
+ command << 'VALUES' if format == :values
32
+ command << 'OUTPUTS' << names.join(',') unless names.empty?
33
+ pairs.each { |model, bytes| command << model.to_s << bytes }
34
+ command
35
+ end
36
+
37
+ # One image's keyed reply (a flat name/value array under RESP2, a Hash under
38
+ # RESP3) decoded for the requested format.
39
+ def decode(entry, format)
40
+ format == :values ? decode_values_map(entry) : decode_blob_map(entry)
41
+ end
42
+
43
+ def decode_blob_map(entry)
44
+ image_pairs(entry).to_h { |name, value| [name, value&.unpack('e*')] }
45
+ end
46
+
47
+ # Under VALUES an EMB.IMGMULTI pair map carries its model beside the
48
+ # outputs (docs/commands.md); that entry is a plain string, not an envelope.
49
+ def decode_values_map(entry)
50
+ image_pairs(entry).to_h do |name, value|
51
+ next [name, value] if name == 'model'
52
+
53
+ envelope = Emb::ValuesReply.parse(value)
54
+ [name, envelope.merge(values: Emb::ValuesReply.rows(envelope[:shape], envelope[:values]))]
55
+ end
56
+ end
57
+
58
+ def image_pairs(entry)
59
+ return entry if entry.is_a?(Hash)
60
+
61
+ Array(entry).each_slice(2).to_h
62
+ end
63
+ end
64
+ end
@@ -0,0 +1,31 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Emb
4
+ # Reads the three item layouts a batch scope can hold: [client, model, text,
5
+ # format] for embeds, [client, SCRIPT_ITEM, argv, decode] for scripts, and
6
+ # [client, ImageBatch::ITEM, model, images, format, names] for images. Split
7
+ # out of BatchDispatch to keep that module within its length budget.
8
+ module ItemShape
9
+ def script_item?(item) = item[1].equal?(SCRIPT_ITEM)
10
+
11
+ def image_item?(item) = item[1].equal?(ImageBatch::ITEM)
12
+
13
+ def embed_item?(item)
14
+ !script_item?(item) && !image_item?(item)
15
+ end
16
+
17
+ def item_model(item)
18
+ return item[2][1] if script_item?(item)
19
+ return item[2] if image_item?(item)
20
+
21
+ item[1]
22
+ end
23
+
24
+ def item_text_count(item)
25
+ return item[2][3].to_i if script_item?(item)
26
+ return item[3].size if image_item?(item)
27
+
28
+ Array(item[2]).size
29
+ end
30
+ end
31
+ end
data/lib/emb/multi.rb CHANGED
@@ -1,6 +1,11 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require_relative 'image_command'
4
+
3
5
  module Emb
6
+ # Eager multi-model batching: text and image calls collected in one block and
7
+ # sent as EMB.MULTI / EMB.IMGMULTI round trips. The explicit block is the
8
+ # opt-in, so it never defers, even under a lazy client (same as text).
4
9
  class MultiProxy
5
10
  def initialize(client)
6
11
  @client = client
@@ -11,20 +16,56 @@ module Emb
11
16
  PairCollector.new(@pairs, name.to_sym)
12
17
  end
13
18
 
19
+ # Results come back in submission order, one per call (one per image for a
20
+ # multi-image call): a text vector, or an image output-name Hash, with nil
21
+ # for a failed or truncated image pair.
14
22
  def run
15
23
  chunk = @client.respond_to?(:batch_size) && @client.batch_size ? @client.batch_size : Emb.configuration.batch_size
24
+ results = Array.new(@pairs.size)
25
+ text, images = @pairs.each_with_index.to_a.partition { |pair, _| pair[:kind] == :text }
26
+ send_texts(text, results, chunk)
27
+ send_images(images, results, chunk)
28
+ results
29
+ end
16
30
 
17
- # Chunk at batch_size pairs per EMB.MULTI so a single command stays well
18
- # under the server's max_pairs cap and within client read timeouts.
19
- @pairs.each_slice(chunk).flat_map do |slice|
20
- args = slice.flat_map { |pair| [pair[:model].to_s, pair[:text]] }
31
+ private
32
+
33
+ def send_texts(indexed, results, chunk)
34
+ indexed.each_slice(chunk) do |slice|
35
+ args = slice.flat_map { |pair, _| [pair[:model].to_s, pair[:text]] }
36
+ replies = @client.send_command('EMB.MULTI', *args)
37
+ slice.each_with_index { |(_, index), i| results[index] = replies[i]&.unpack('e*') }
38
+ end
39
+ end
40
+
41
+ # One EMB.IMGMULTI per compatible group (format and projection), chunked by
42
+ # batch_size like the text path.
43
+ def send_images(indexed, results, chunk)
44
+ indexed.group_by { |pair, _| [pair[:format], pair[:names]] }.each_value do |group|
45
+ send_image_group(group, results, chunk)
46
+ end
47
+ end
21
48
 
22
- @client
23
- .send_command('EMB.MULTI', *args)
24
- .map { |entry| entry&.unpack('e*') }
49
+ def send_image_group(group, results, chunk)
50
+ format = group.first.first[:format]
51
+ group.each_slice(chunk) do |slice|
52
+ replies = @client.send_command(*image_args(slice))
53
+ slice.each_with_index { |(_, index), i| results[index] = image_value(replies[i], format) }
25
54
  end
26
55
  end
27
56
 
57
+ # The group's projection rides on every pair's argv: a share is built only
58
+ # from pairs that asked for the same outputs.
59
+ def image_args(slice)
60
+ first = slice.first.first
61
+ pairs = slice.map { |pair, _| [pair[:model], pair[:bytes]] }
62
+ ImageCommand.multi_args(pairs, format: first[:format], names: first[:names])
63
+ end
64
+
65
+ def image_value(entry, format)
66
+ entry.nil? ? nil : ImageCommand.decode(entry, format)
67
+ end
68
+
28
69
  class PairCollector
29
70
  def initialize(pairs, model)
30
71
  @pairs = pairs
@@ -32,7 +73,18 @@ module Emb
32
73
  end
33
74
 
34
75
  def [](text)
35
- @pairs << { model: @model, text: text }
76
+ @pairs << { kind: :text, model: @model, text: text.dup }
77
+ end
78
+
79
+ # The same arguments as Proxy#image. Each image becomes its own pair, so
80
+ # the block's result holds one Hash per image in submission order.
81
+ def image(bytes, *more, format: :binary, outputs: nil)
82
+ format = ImageCommand.validate_format!(format)
83
+ names = Array(outputs).map { |name| name.to_s.dup.freeze }
84
+ [bytes, *more].each do |payload|
85
+ @pairs << { kind: :image, model: @model, bytes: Proxy.coerce_image_bytes(payload),
86
+ format: format, names: names }
87
+ end
36
88
  end
37
89
  end
38
90
  end
data/lib/emb/proxy.rb CHANGED
@@ -1,5 +1,6 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require_relative 'image_command'
3
4
  require_relative 'values_reply'
4
5
 
5
6
  module Emb
@@ -21,9 +22,15 @@ module Emb
21
22
  if @client.lazy?
22
23
  return Emb.build_batch_loader(@client, @name, texts.empty? ? text : [text, *texts], format: format)
23
24
  end
24
- return values_query(text, texts) if format == :values
25
25
 
26
- unpack_set(@client.send_command('EMB', @name.to_s, text, *texts))
26
+ Emb::Telemetry.embed_call(operation: 'embed', model: @name, texts: 1 + texts.size,
27
+ format: format, mode: 'eager') do
28
+ if format == :values
29
+ values_query(text, texts)
30
+ else
31
+ unpack_set(@client.send_command('EMB', @name.to_s, text, *texts))
32
+ end
33
+ end
27
34
  end
28
35
 
29
36
  def inspect
@@ -36,41 +43,74 @@ module Emb
36
43
  #
37
44
  # Emb[:clip].image(File.binread('cat.jpg'))
38
45
  # Emb[:clip].image(io1, io2) # IO objects are read
46
+ # Emb[:dino].image(bytes, outputs: ['patches'])
39
47
  #
40
- # format: :binary (default) returns the float32-unpacked vectors from the
41
- # compact BLOB wire (nil for a failed/truncated slot); format: :values
42
- # returns the decoded dtype/shape/values envelope. The float32 reply decode
43
- # is the same `unpack('e*')` path text embeddings use.
44
- def image(image_bytes, *more, format: :binary)
48
+ # The reply is keyed by the model's configured output names (String keys,
49
+ # as the server sends them): one image returns a Hash of name => value,
50
+ # several return an Array of those Hashes
51
+ # (nil for a failed or truncated slot). format: :binary (default) unpacks
52
+ # the BLOB wire into float32 arrays; format: :values returns the decoded
53
+ # dtype/shape/values envelope (plus grid for a token output). outputs:
54
+ # narrows the projection and may name any subset of the configured outputs.
55
+ def image(image_bytes, *more, format: :binary, outputs: nil)
45
56
  format = normalize_format(format)
46
- images = [image_bytes, *more].map { |bytes| self.class.coerce_image_bytes(bytes) }
47
-
48
- if format == :values
49
- reply = @client.send_command('EMB.IMG', @name.to_s, 'VALUES', *images)
50
- envelope = Emb::ValuesReply.parse(reply)
51
- return envelope if images.size == 1
57
+ names = Array(outputs).map { |name| name.to_s.dup.freeze }
58
+ images = coerce_images([image_bytes, *more])
59
+ return Emb.build_image_loader(@client, @name, images, format: format, names: names) if deferred?
52
60
 
53
- return envelope.merge(values: Emb::ValuesReply.rows(envelope[:shape], envelope[:values]))
61
+ Emb::Telemetry.embed_call(operation: 'image', model: @name, texts: images.size,
62
+ format: format, mode: 'eager') do
63
+ image_reply(images, format, names)
54
64
  end
65
+ end
55
66
 
56
- reply = @client.send_command('EMB.IMG', @name.to_s, *images)
57
- return unpack_embedding(reply) if images.size == 1
58
-
59
- Array(reply).map { |entry| entry.nil? ? nil : unpack_embedding(entry) }
67
+ # coerce_image_bytes normalizes an image argument to a fresh binary String
68
+ # without transcoding: a String's bytes are copied exactly (encoding label
69
+ # set to ASCII-8BIT), and an IO is read fully — or, with a limit, read only
70
+ # up to it so an oversized stream is never materialized. The caller's
71
+ # object is never touched, so a later mutation cannot change a deferred
72
+ # request that captured this value.
73
+ def self.coerce_image_bytes(bytes, limit: nil)
74
+ return bytes.to_s.b unless bytes.respond_to?(:read)
75
+
76
+ data = read_image_bytes(bytes, limit)
77
+ data ? data.force_encoding(Encoding::BINARY) : ''.b
60
78
  end
61
79
 
62
- # coerce_image_bytes normalizes an image argument to a binary byte string
63
- # without transcoding: a String's bytes are preserved exactly (only the
64
- # encoding label is set to ASCII-8BIT), and an IO is read fully.
65
- def self.coerce_image_bytes(bytes)
66
- data = bytes.respond_to?(:read) ? bytes.read : bytes
67
- data = data.to_s
68
- data = data.dup if data.frozen?
69
- data.force_encoding(Encoding::BINARY)
80
+ def self.read_image_bytes(io, limit)
81
+ return io.read if limit.nil?
82
+
83
+ data = io.read(limit + 1)
84
+ return data if data.nil? || data.bytesize <= limit
85
+
86
+ raise ImageBatchLimitError, "image bytes would exceed max_image_batch_bytes (#{limit} bytes)"
70
87
  end
71
88
 
72
89
  private
73
90
 
91
+ # A deferred call reads each IO against what its pending scope can still
92
+ # hold, so an oversized stream raises instead of being materialized.
93
+ def coerce_images(inputs)
94
+ budget = deferred? ? ImageBatch.remaining_bytes(@client) : nil
95
+ inputs.map do |bytes|
96
+ data = self.class.coerce_image_bytes(bytes, limit: budget)
97
+ budget = [budget - data.bytesize, 0].max if budget
98
+ data
99
+ end
100
+ end
101
+
102
+ def deferred?
103
+ @client.respond_to?(:lazy?) && @client.lazy?
104
+ end
105
+
106
+ def image_reply(images, format, names)
107
+ reply = @client.send_command(*ImageCommand.args(@name, images, format: format, names: names))
108
+ return nil if reply.nil? && images.size == 1
109
+ return ImageCommand.decode(reply, format) if images.size == 1
110
+
111
+ Array(reply).map { |entry| entry.nil? ? nil : ImageCommand.decode(entry, format) }
112
+ end
113
+
74
114
  # One packed vector for a single text, an array for several; a null slot
75
115
  # (failed/truncated position) maps to nil.
76
116
  def unpack_set(raw)
@@ -80,16 +120,8 @@ module Emb
80
120
  result.size == 1 ? result.first : result
81
121
  end
82
122
 
83
- def unpack_embedding(entry)
84
- entry&.unpack('e*')
85
- end
86
-
87
123
  def normalize_format(format)
88
- unless %i[binary values].include?(format)
89
- raise ArgumentError, "unknown format #{format.inspect} (expected :binary or :values)"
90
- end
91
-
92
- format
124
+ ImageCommand.validate_format!(format)
93
125
  end
94
126
 
95
127
  def values_query(text, texts)