fast-embeddings 0.1.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 ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 447574fabdcf463f9eea4094be52e55064f18030c4f058a27a211f04ddb2f11f
4
+ data.tar.gz: 4ba8cb1f013e2a238dd98460cceac7ea628e0b0edfa9ce15f7f083e649f18bca
5
+ SHA512:
6
+ metadata.gz: 8068b234b562dade5991fd4aa65caf68c437e7a973b24340f863fed8287b7d63e3837500243f1a596d4ac10fe81b0d9aa1d90d7cdcec6d84cbef998bc906d188
7
+ data.tar.gz: 6a7065e5c87ef0d3035ba4fd21e4fb531623bcdad2dbf33c938d6252ccade9229cd0e8d800ea9bf8bec5cd72cbbbb8fe3a0d5774b2f0ab2633bcd68160e7df88
data/CHANGELOG.md ADDED
@@ -0,0 +1,17 @@
1
+ # Changelog
2
+
3
+ Notable changes to the fast-embeddings gem. The format is prose-first,
4
+ one section per released version, newest first.
5
+
6
+ ## 0.1.0 (2026-11-24)
7
+
8
+ - Initial release: the pure OpenAI embeddings wire as a gem.
9
+ `Client#embed(model:, input:, api_key: nil)` POSTs `{base}/embeddings`
10
+ with the closed two-key body `{model, input}` and surfaces the reply's
11
+ `data` (in wire order, verbatim numbers, never re-sorted by index) and
12
+ `usage` (zeros when the provider omits it). Fiber-native on
13
+ async-http — the only runtime dependency — one persistent HTTP client
14
+ per instance, running inside the caller's reactor. Exactly one POST
15
+ attempt per call: no retry machinery, no batch policy, no model
16
+ catalog — slicing, retries, and model naming are the caller's.
17
+ Credentials ride per call and are never stored.
data/README.md ADDED
@@ -0,0 +1,81 @@
1
+ # fast-embeddings
2
+
3
+ `Fast::Embeddings` is a fast & focused HTTP client for OpenAI-compatible
4
+ embeddings APIs. It speaks `POST {base}/embeddings` — one request, one
5
+ JSON reply. It's implemented on top of [socketry/async-http] and won't
6
+ block your reactor.
7
+
8
+ ## Fast & Focused
9
+
10
+ This gem is laser focused on **just the embeddings API**.
11
+
12
+ It does:
13
+
14
+ * One POST per call with the closed two-key body `{model, input}`
15
+ * `data` surfaced in wire order, numbers verbatim, never re-sorted by
16
+ index (the caller zips embeddings to texts by `index`)
17
+ * `usage` surfaced per call (zeros when the provider omits it)
18
+ * A watchdog-bounded deadline and a frozen error taxonomy
19
+
20
+ There are also a bunch of things `Fast::Embeddings` _does not_ do:
21
+
22
+ * No model catalog — the caller owns model naming; the `model:` string
23
+ is opaque wire data
24
+ * No batch policy — the caller slices by its own `batch_max_texts` /
25
+ `input_max_chars` admission control; the gem never slices, truncates,
26
+ chunks, or re-orders `input`
27
+ * No retries — exactly one POST attempt per call; the caller retries
28
+ * No stored credentials — `api_key:` is a per-call kwarg, used for the
29
+ call and discarded, never retained on the instance
30
+ * No other API shapes, no universal translation, no dialects
31
+ * No synchronous requests, no wire extensions — ever
32
+
33
+ ## Installation
34
+
35
+ ```ruby
36
+ gem "fast-embeddings"
37
+ ```
38
+
39
+ The only runtime dependency is `async-http`.
40
+
41
+ ## Quickstart
42
+
43
+ ```ruby
44
+ require "fast/embeddings"
45
+
46
+ client = Fast::Embeddings::Client.new(base_url: "https://api.example.com/v1")
47
+
48
+ Async do |task| # fiber-native!
49
+ result = client.embed(
50
+ model: "text-embedding-3-small",
51
+ input: ["first text", "second text"],
52
+ api_key: ENV["API_KEY"], # optional; sent only when present and non-empty
53
+ )
54
+ result.data.each do |datum|
55
+ puts "index #{datum.index}: #{datum.embedding.size} dims"
56
+ end
57
+ puts "usage: #{result.usage.to_h.inspect}"
58
+ client.close
59
+ end
60
+ ```
61
+
62
+ ## Errors
63
+
64
+ Non-2xx replies map onto a frozen taxonomy; a lying 2xx body fails loud,
65
+ never silently.
66
+
67
+ | Class | Raised when |
68
+ |---|---|
69
+ | `BadRequestError` | HTTP 400 |
70
+ | `AuthenticationError` | HTTP 401 |
71
+ | `PermissionError` | HTTP 403 |
72
+ | `NotFoundError` | HTTP 404 |
73
+ | `RateLimitError` | HTTP 429 |
74
+ | `ServerError` | HTTP 5xx |
75
+ | `ApiError` | any other non-2xx (`#message` is `"<status>: <provider message>"`) |
76
+ | `TimeoutError` | no reply within `timeout:` |
77
+ | `ConnectionError` | network family (ECONNREFUSED, ECONNRESET, EOF, ...) |
78
+ | `ResponseError` | a 2xx body that is not valid embeddings JSON |
79
+ | `CancelledError` | the caller cancelled the task (deliberately NOT under `Error`) |
80
+
81
+ [socketry/async-http]: https://github.com/socketry/async-http
@@ -0,0 +1,176 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require "async"
5
+ require "async/http"
6
+
7
+ module Fast
8
+ module Embeddings
9
+ # ONE persistent Async::HTTP::Client per instance, fiber-native: every
10
+ # request runs INSIDE the caller's reactor — the client never creates
11
+ # its own.
12
+ class Client
13
+ DEFAULT_TIMEOUT = 30
14
+
15
+ # Deadline watchdog: armed before the POST, no re-arm — exactly one
16
+ # attempt per call. A fire cancels the waiting task; `fired` tells
17
+ # the deadline apart from a user's cancel (D8).
18
+ class Watchdog
19
+ def initialize(task, seconds)
20
+ @task = task
21
+ @seconds = seconds
22
+ @timer = nil
23
+ @fired = false
24
+ end
25
+
26
+ attr_reader :fired
27
+
28
+ def arm
29
+ stop
30
+ @fired = false
31
+ @timer = Async do
32
+ sleep @seconds
33
+ @fired = true
34
+ @task.cancel
35
+ end
36
+ end
37
+
38
+ def stop
39
+ @timer&.stop
40
+ @timer = nil
41
+ end
42
+ end
43
+
44
+ NETWORK_ERRORS = [
45
+ Errno::ECONNREFUSED, Errno::ECONNRESET, Errno::EPIPE, Errno::EHOSTUNREACH,
46
+ Errno::ENETUNREACH, Errno::ETIMEDOUT, EOFError, IOError, SocketError,
47
+ ].freeze
48
+
49
+ attr_reader :timeout
50
+
51
+ def initialize(base_url:, timeout: DEFAULT_TIMEOUT)
52
+ unless timeout.is_a?(Numeric) && timeout.positive?
53
+ raise ArgumentError, "timeout must be a positive Numeric"
54
+ end
55
+
56
+ @endpoint = Async::HTTP::Endpoint.parse(base_url)
57
+ @timeout = timeout
58
+ @client = Async::HTTP::Client.new(@endpoint)
59
+ @path = @endpoint.path.chomp("/") + "/embeddings"
60
+ end
61
+
62
+ def close
63
+ @client.close
64
+ nil
65
+ end
66
+
67
+ # POST {base}/embeddings, read the ONE JSON reply, return a Result.
68
+ # Runs inside the caller's task. Exactly ONE attempt — no retry
69
+ # machinery of any kind: retries are the caller's. The body is a
70
+ # CLOSED two-key set ({model, input}) in that key order; input
71
+ # crosses the wire VERBATIM, in order — the gem never slices,
72
+ # truncates, chunks, or re-orders it (batch discipline is the
73
+ # caller's). The credential, when given, is used for this call and
74
+ # discarded: no instance variable of this client ever holds it.
75
+ def embed(model:, input:, api_key: nil)
76
+ validate_model!(model)
77
+ validate_input!(input)
78
+ body = JSON.generate({model: model, input: input}) # key order: model, input
79
+
80
+ watchdog = Watchdog.new(Async::Task.current, @timeout)
81
+ response = nil
82
+ result = nil
83
+ begin
84
+ watchdog.arm
85
+ response = @client.post(@path, headers: headers_for(api_key), body: body)
86
+ raise_api_error(response) unless (200...300).cover?(response.status)
87
+ result = parse_result(response.body.read)
88
+ rescue Async::Cancel
89
+ raise(TimeoutError, "no data within #{@timeout}s") if watchdog.fired
90
+
91
+ raise CancelledError, "embed cancelled"
92
+ rescue *NETWORK_ERRORS => e
93
+ raise ConnectionError, "#{e.class}: #{e.message}"
94
+ ensure
95
+ finish_quietly(response) # nil-safe: no response yet, or an aborted read
96
+ watchdog.stop
97
+ end
98
+ raise TimeoutError, "no data within #{@timeout}s" if watchdog.fired # the post-ensure deadline raise
99
+
100
+ result
101
+ end
102
+
103
+ private
104
+
105
+ # Authorization is optional: sent only when a key is present and
106
+ # non-empty — a local engine needs none. The key lives in this
107
+ # local, never in an ivar.
108
+ def headers_for(api_key)
109
+ if api_key && !api_key.empty?
110
+ {
111
+ "authorization" => "Bearer #{api_key}",
112
+ "content-type" => "application/json",
113
+ "accept" => "application/json",
114
+ }
115
+ else
116
+ {"content-type" => "application/json", "accept" => "application/json"}
117
+ end
118
+ end
119
+
120
+ def validate_model!(model)
121
+ return if model.is_a?(String) && !model.empty?
122
+
123
+ raise ArgumentError, "model must be a non-empty String"
124
+ end
125
+
126
+ # A bare String also raises — the caller wraps; fail loud.
127
+ def validate_input!(input)
128
+ return if input.is_a?(Array) && !input.empty? && input.all?(String)
129
+
130
+ raise ArgumentError, "input must be a non-empty Array of Strings"
131
+ end
132
+
133
+ # Non-2xx: read the body, map to the frozen taxonomy.
134
+ def raise_api_error(response)
135
+ body = response.body.read
136
+ raise Errors.class_for_status(response.status, body).new(status: response.status, body: body)
137
+ end
138
+
139
+ # The 2xx body must not lie: a JSON Hash whose data is an Array of
140
+ # Hashes each carrying an Array embedding and an Integer index.
141
+ # Anything else raises ResponseError — never a silent
142
+ # mistranslation. data keeps WIRE ORDER (never re-sorted by
143
+ # index); the caller zips by index.
144
+ def parse_result(raw)
145
+ parsed = begin
146
+ JSON.parse(raw)
147
+ rescue JSON::ParserError
148
+ raise ResponseError, "embeddings reply is not JSON: #{raw[0, 120].inspect}"
149
+ end
150
+ raise ResponseError, "embeddings reply is not a JSON object" unless parsed.is_a?(Hash)
151
+
152
+ data = parsed["data"]
153
+ unless data.is_a?(Array) && data.all? { |entry| datum?(entry) }
154
+ raise ResponseError, "embeddings reply data is not an Array of {embedding, index} objects"
155
+ end
156
+
157
+ Result.new(
158
+ data: data.map { |entry| Datum.new(embedding: entry["embedding"], index: entry["index"]) },
159
+ usage: Usage.for_wire(parsed["usage"]),
160
+ )
161
+ end
162
+
163
+ def datum?(entry)
164
+ entry.is_a?(Hash) && entry["embedding"].is_a?(Array) && entry["index"].is_a?(Integer)
165
+ end
166
+
167
+ # Complete bodies return the connection to the pool; an aborted
168
+ # read (cancel/deadline) discards it. Nil-safe.
169
+ def finish_quietly(response)
170
+ response.finish
171
+ rescue StandardError, Async::Cancel
172
+ nil
173
+ end
174
+ end
175
+ end
176
+ end
@@ -0,0 +1,87 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Fast
4
+ module Embeddings
5
+ # The frozen error taxonomy (the completions house style, standalone
6
+ # per gem). CancelledError is deliberately NOT under Error so rescue
7
+ # ladders that catch the API error tree never swallow a cancellation.
8
+ class Error < StandardError; end
9
+
10
+ # Non-2xx responses map here. #message is
11
+ # "<status>: <provider message>" — the provider's error.message when
12
+ # the body parses, else the raw body truncated.
13
+ class ApiError < Error
14
+ attr_reader :status, :body
15
+
16
+ def initialize(status:, body: "")
17
+ @status = status
18
+ @body = body.to_s
19
+ super(Errors.api_message(status, @body))
20
+ end
21
+ end
22
+
23
+ class BadRequestError < ApiError; end # 400
24
+ class AuthenticationError < ApiError; end # 401
25
+ class PermissionError < ApiError; end # 403
26
+ class NotFoundError < ApiError; end # 404
27
+ class RateLimitError < ApiError; end # 429
28
+ class ServerError < ApiError; end # 5xx
29
+
30
+ # Deadline (watchdog fire): the caller's cancel surfaces as
31
+ # CancelledError, never this (the cancel-vs-fired discipline).
32
+ class TimeoutError < Error; end
33
+ # ECONNREFUSED/ECONNRESET/... — the network family (message form
34
+ # `"<class>: <message>"`).
35
+ class ConnectionError < Error; end
36
+
37
+ # A 2xx body that lies: it fails JSON.parse, parses to a non-Hash,
38
+ # or whose data is not an Array of Hashes each carrying an Array
39
+ # embedding and an Integer index. Fail loud, never silently
40
+ # mistranslate.
41
+ class ResponseError < Error; end
42
+
43
+ class CancelledError < StandardError; end # NOT < Error (D8)
44
+
45
+ # Internal: error classification helpers.
46
+ module Errors
47
+ STATUS_CLASSES = {
48
+ 401 => AuthenticationError,
49
+ 403 => PermissionError,
50
+ 404 => NotFoundError,
51
+ 429 => RateLimitError,
52
+ }.freeze
53
+
54
+ module_function
55
+
56
+ # Map a non-2xx status + body to the frozen class. A 400 stays a
57
+ # BadRequestError — there is no overflow machinery on this wire.
58
+ def class_for_status(status, body)
59
+ case status
60
+ when 400
61
+ BadRequestError
62
+ when 500..599
63
+ ServerError
64
+ else
65
+ STATUS_CLASSES.fetch(status, ApiError)
66
+ end
67
+ end
68
+
69
+ # ApiError#message: "<status>: <message>" — the provider's
70
+ # error.message when parseable, else the raw body truncated to
71
+ # ~500 chars.
72
+ def api_message(status, body)
73
+ "#{status}: #{provider_message(body)}"
74
+ end
75
+
76
+ def provider_message(body)
77
+ raw = body.to_s
78
+ parsed = JSON.parse(raw)
79
+ message = parsed["error"]["message"] if parsed.is_a?(Hash) && parsed["error"].is_a?(Hash)
80
+ message ||= parsed["message"] if parsed.is_a?(Hash)
81
+ message || raw[0, 500]
82
+ rescue JSON::ParserError, TypeError
83
+ raw[0, 500]
84
+ end
85
+ end
86
+ end
87
+ end
@@ -0,0 +1,80 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+
5
+ module Fast
6
+ module Embeddings
7
+ # Frozen value objects (the completions `Usage` house style:
8
+ # keyword init, freeze, to_h, ==). The wire's numbers arrive
9
+ # VERBATIM — no Float coercion, no reordering; the caller zips
10
+ # embeddings to its texts by index.
11
+ class Datum
12
+ attr_reader :embedding, :index
13
+
14
+ def initialize(embedding:, index:)
15
+ @embedding = embedding
16
+ @index = index
17
+ freeze
18
+ end
19
+
20
+ def to_h
21
+ {embedding:, index:}
22
+ end
23
+
24
+ def ==(other)
25
+ other.is_a?(Datum) && to_h == other.to_h
26
+ end
27
+ end
28
+
29
+ # Token accounting, surfaced per call — the spend surface the
30
+ # caller records at its embed call site. A missing or non-Hash wire
31
+ # usage yields zeros: the honest "the provider said nothing"
32
+ # posture.
33
+ class Usage
34
+ attr_reader :prompt_tokens, :total_tokens
35
+
36
+ def initialize(prompt_tokens: 0, total_tokens: 0)
37
+ @prompt_tokens = prompt_tokens
38
+ @total_tokens = total_tokens
39
+ freeze
40
+ end
41
+
42
+ # Surface what the wire said; zeros when it said nothing.
43
+ def self.for_wire(raw)
44
+ return ZERO unless raw.is_a?(Hash)
45
+
46
+ new(prompt_tokens: raw["prompt_tokens"] || 0, total_tokens: raw["total_tokens"] || 0)
47
+ end
48
+
49
+ def to_h
50
+ {prompt_tokens:, total_tokens:}
51
+ end
52
+
53
+ def ==(other)
54
+ other.is_a?(Usage) && to_h == other.to_h
55
+ end
56
+
57
+ ZERO = new.freeze
58
+ end
59
+
60
+ # The one embed-call outcome: data in WIRE ORDER (never re-sorted by
61
+ # index) plus the usage — the J-SPEND call site reads this per call.
62
+ class Result
63
+ attr_reader :data, :usage
64
+
65
+ def initialize(data:, usage:)
66
+ @data = data
67
+ @usage = usage
68
+ freeze
69
+ end
70
+
71
+ def to_h
72
+ {data:, usage:}
73
+ end
74
+
75
+ def ==(other)
76
+ other.is_a?(Result) && to_h == other.to_h
77
+ end
78
+ end
79
+ end
80
+ end
@@ -0,0 +1,7 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Fast
4
+ module Embeddings
5
+ VERSION = "0.1.0"
6
+ end
7
+ end
@@ -0,0 +1,19 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Fast::Embeddings — a fiber-native client for the OpenAI embeddings
4
+ # wire. One require loads the whole surface.
5
+ require "json"
6
+
7
+ require_relative "embeddings/version"
8
+ require_relative "embeddings/errors"
9
+ require_relative "embeddings/types"
10
+ require_relative "embeddings/client"
11
+
12
+ module Fast
13
+ # The embeddings wire, and nothing else: POST {base}/embeddings with
14
+ # {model, input}, one JSON reply back. Model naming belongs to the
15
+ # caller; batch discipline belongs to the caller; retries belong to
16
+ # the caller; credentials ride per call and are never stored.
17
+ module Embeddings
18
+ end
19
+ end
metadata ADDED
@@ -0,0 +1,67 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: fast-embeddings
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Eric Jacobs
8
+ bindir: bin
9
+ cert_chain: []
10
+ date: 1980-01-02 00:00:00.000000000 Z
11
+ dependencies:
12
+ - !ruby/object:Gem::Dependency
13
+ name: async-http
14
+ requirement: !ruby/object:Gem::Requirement
15
+ requirements:
16
+ - - "~>"
17
+ - !ruby/object:Gem::Version
18
+ version: '0.95'
19
+ type: :runtime
20
+ prerelease: false
21
+ version_requirements: !ruby/object:Gem::Requirement
22
+ requirements:
23
+ - - "~>"
24
+ - !ruby/object:Gem::Version
25
+ version: '0.95'
26
+ description: |
27
+ Fast::Embeddings speaks the OpenAI embeddings wire. One wire
28
+ protocol, one POST per call, one JSON reply back — no dialects, no
29
+ extensions. async-http is the only runtime dependency; credentials
30
+ ride per call and are never stored.
31
+ executables: []
32
+ extensions: []
33
+ extra_rdoc_files: []
34
+ files:
35
+ - CHANGELOG.md
36
+ - README.md
37
+ - lib/fast/embeddings.rb
38
+ - lib/fast/embeddings/client.rb
39
+ - lib/fast/embeddings/errors.rb
40
+ - lib/fast/embeddings/types.rb
41
+ - lib/fast/embeddings/version.rb
42
+ homepage: https://github.com/jetpks/fast-llm
43
+ licenses:
44
+ - MIT
45
+ metadata:
46
+ homepage_uri: https://github.com/jetpks/fast-llm
47
+ source_code_uri: https://github.com/jetpks/fast-llm
48
+ changelog_uri: https://github.com/jetpks/fast-llm/blob/main/gems/embeddings/CHANGELOG.md
49
+ rubygems_mfa_required: 'true'
50
+ rdoc_options: []
51
+ require_paths:
52
+ - lib
53
+ required_ruby_version: !ruby/object:Gem::Requirement
54
+ requirements:
55
+ - - ">="
56
+ - !ruby/object:Gem::Version
57
+ version: '3.4'
58
+ required_rubygems_version: !ruby/object:Gem::Requirement
59
+ requirements:
60
+ - - ">="
61
+ - !ruby/object:Gem::Version
62
+ version: 3.5.3
63
+ requirements: []
64
+ rubygems_version: 4.0.20
65
+ specification_version: 4
66
+ summary: A fiber-native client for the OpenAI embeddings wire.
67
+ test_files: []