typesafe-system-one 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: ebde5fe34664f89ec47798532b10acf88beae9853808f1466ba414cacb8f66b0
4
+ data.tar.gz: '0608c93c746244293894246027d47b4336701cad02a9bea0a7534f8e9870c5e5'
5
+ SHA512:
6
+ metadata.gz: 45a032e93f5d03e69778380d2d25718d2d3556cda2a1a966dc9ba0dc7825456850aa6eecfbc50bd5fa4aa3f236e99d1a7f3fb37f62d37c6323f2343241747843
7
+ data.tar.gz: 867effb7dec74676693eda09423e954c6699824834890429686ca223c26b7b35c4028d529e53b9224a07ecb4abd99e9ceb6446140cf3a390336fec9cf034f639
data/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ # Changelog
2
+
3
+ ## 0.1.0 (unreleased)
4
+
5
+ - Initial experimental release: `Client#ask` with Choice, Score, Noul and Box questions, image assets, and built-in retries.
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 NichiyaOba
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,118 @@
1
+ # typesafe-system-one
2
+
3
+ **Unofficial, experimental Ruby client for the [TypeSafe AI](https://typesafe.ai) System One API.**
4
+ This is a community prototype. It is not affiliated with, endorsed by, or supported by TypeSafe.
5
+ The API surface may change without notice before 1.0.
6
+
7
+ The client design follows the official Python SDK.
8
+
9
+ ## Installation
10
+
11
+ ```ruby
12
+ gem 'typesafe-system-one'
13
+ ```
14
+
15
+ Requires Ruby 3.3 or later. The only runtime dependency is Faraday 2.
16
+
17
+ ## Configuration
18
+
19
+ ```ruby
20
+ require 'typesafe/system_one'
21
+
22
+ client = TypeSafe::SystemOne::Client.new(
23
+ api_key: ENV['TYPESAFE_API_KEY'], # default
24
+ base_url: 'https://api.typesafe.ai', # default; or TYPESAFE_BASE_URL
25
+ model: 'jev-latest', # default; or TYPESAFE_DEFAULT_MODEL
26
+ timeout: 10 # seconds, default 10
27
+ )
28
+ ```
29
+
30
+ An empty API key raises `TypeSafe::SystemOne::ConfigurationError` before anything is sent.
31
+
32
+ ## Usage
33
+
34
+ All questions about one piece of content go in a single call. Question names are yours;
35
+ the response uses the same names.
36
+
37
+ ```ruby
38
+ Q = TypeSafe::SystemOne::Questions
39
+
40
+ response = client.ask(
41
+ state: { subject: 'Duplicate charge', message: 'I was charged twice. Please fix this ASAP.' },
42
+ questions: {
43
+ category: Q::Choice.new(
44
+ instructions: 'What is this ticket about?',
45
+ criteria: { billing: 'Payments and invoices', technical: 'Bugs and outages', other: nil }
46
+ ),
47
+ urgency: Q::Score.new(
48
+ instructions: 'How urgent is this message?',
49
+ criteria: ['Can wait', 'Needs attention this week', 'Needs attention today']
50
+ ),
51
+ is_billing: Q::Noul.new(
52
+ instructions: 'Is this message about billing?',
53
+ criteria: { true: 'Mentions a charge or invoice', false: 'Unrelated to payments' }
54
+ )
55
+ }
56
+ )
57
+
58
+ response.answers['category'].choice # => "billing"
59
+ response.answers['category'].probabilities # => { "billing" => 0.97, ... }
60
+ response.answers['urgency'].score # => 1.8
61
+ response.answers['is_billing'].noul # => 0.98
62
+ response.usage.input_tokens
63
+ ```
64
+
65
+ `state` can be a String, Hash, or Array. Pass `model:` to `ask` to override the client's model.
66
+
67
+ ### Box questions and images
68
+
69
+ ```ruby
70
+ image = TypeSafe::SystemOne::Image.from_file('photo.png') # png, jpg, jpeg
71
+
72
+ response = client.ask(
73
+ state: 'Photo: asset-1',
74
+ assets: { 'asset-1' => image },
75
+ questions: { logo: TypeSafe::SystemOne::Questions::Box.new(instructions: 'Locate the logo') }
76
+ )
77
+
78
+ box = response.answers['logo']
79
+ box.top; box.bottom; box.left; box.right # fractions (0-1) of image height / width
80
+ box.confidence # Float, or nil
81
+ ```
82
+
83
+ The placeholder key (`asset-1`) is replaced by the image wherever it appears inside a string in
84
+ `state`, instructions, or criteria. Image assets need a vision-language model.
85
+
86
+ ## Errors and retries
87
+
88
+ | Class | Raised when |
89
+ | --- | --- |
90
+ | `ConfigurationError` | the API key is empty |
91
+ | `APIError` | the server answered with a non-2xx status (`status`, `request_id`, `body`) |
92
+ | `ConnectionError` / `TimeoutError` | no response could be obtained |
93
+ | `ResponseError` | the response is not the expected JSON shape |
94
+
95
+ All inherit from `TypeSafe::SystemOne::Error`. Invalid questions or images raise `ArgumentError`.
96
+ Requests that carry `assets` are sent with `TypeSafe-Danger-Zone-Images: true`, the opt-in the API
97
+ requires for its experimental image support.
98
+
99
+ Error messages never include the request body (`state`). `APIError#body` and `#headers` are the
100
+ server's raw reply and may echo what you sent, so do not log them as-is.
101
+
102
+ Requests are retried up to 2 times on 408, 429, 5xx, connection failures, and timeouts.
103
+ `retry-after-ms` / `retry-after` are honored; otherwise the wait starts at 0.5 s and doubles
104
+ (max 5 s, 25% jitter). As in the official Python SDK, a retry is skipped when the time already
105
+ spent plus the next wait would reach 30 s. The last attempt can still run up to `timeout`, so one
106
+ call can take longer than 30 s in total. Like the official SDK, POST requests are retried, so a
107
+ request the server already processed may be sent (and billed) again.
108
+
109
+ ## Development
110
+
111
+ ```sh
112
+ bundle install
113
+ bundle exec rspec
114
+ ```
115
+
116
+ ## License
117
+
118
+ MIT
@@ -0,0 +1,20 @@
1
+ # frozen_string_literal: true
2
+
3
+ module TypeSafe
4
+ module SystemOne
5
+ module Answers
6
+ Box = Data.define(:top, :bottom, :left, :right, :confidence) do
7
+ def self.from_h(hash, label)
8
+ edges = Answers.fetch(hash, 'box', label, Hash)
9
+ new(
10
+ top: Answers.number(edges, 'top', label),
11
+ bottom: Answers.number(edges, 'bottom', label),
12
+ left: Answers.number(edges, 'left', label),
13
+ right: Answers.number(edges, 'right', label),
14
+ confidence: Answers.fetch(hash, 'confidence', label, Numeric, NilClass)
15
+ )
16
+ end
17
+ end
18
+ end
19
+ end
20
+ end
@@ -0,0 +1,17 @@
1
+ # frozen_string_literal: true
2
+
3
+ module TypeSafe
4
+ module SystemOne
5
+ module Answers
6
+ Choice = Data.define(:choice, :probabilities, :confidence) do
7
+ def self.from_h(hash, label)
8
+ new(
9
+ choice: Answers.fetch(hash, 'choice', label, String),
10
+ probabilities: Answers.fetch(hash, 'probabilities', label, Hash),
11
+ confidence: Answers.number(hash, 'confidence', label)
12
+ )
13
+ end
14
+ end
15
+ end
16
+ end
17
+ end
@@ -0,0 +1,13 @@
1
+ # frozen_string_literal: true
2
+
3
+ module TypeSafe
4
+ module SystemOne
5
+ module Answers
6
+ Noul = Data.define(:noul) do
7
+ def self.from_h(hash, label)
8
+ new(noul: Answers.number(hash, 'noul', label))
9
+ end
10
+ end
11
+ end
12
+ end
13
+ end
@@ -0,0 +1,18 @@
1
+ # frozen_string_literal: true
2
+
3
+ module TypeSafe
4
+ module SystemOne
5
+ module Answers
6
+ Score = Data.define(:score, :legend, :probabilities, :confidence) do
7
+ def self.from_h(hash, label)
8
+ new(
9
+ score: Answers.number(hash, 'score', label),
10
+ legend: Answers.fetch(hash, 'legend', label, Hash),
11
+ probabilities: Answers.fetch(hash, 'probabilities', label, Hash),
12
+ confidence: Answers.number(hash, 'confidence', label)
13
+ )
14
+ end
15
+ end
16
+ end
17
+ end
18
+ end
@@ -0,0 +1,37 @@
1
+ # frozen_string_literal: true
2
+
3
+ module TypeSafe
4
+ module SystemOne
5
+ module Answers
6
+ BUILDERS = {
7
+ 'choice' => Choice,
8
+ 'score' => Score,
9
+ 'noul' => Noul,
10
+ 'box' => Box
11
+ }.freeze
12
+
13
+ def self.build(hash, name:, expected_type:)
14
+ raise ResponseError, "Invalid answer for #{name.inspect}" unless hash.is_a?(Hash)
15
+
16
+ builder = BUILDERS[hash['type']]
17
+ raise ResponseError, "Unknown answer type #{hash['type'].inspect} for #{name.inspect}" unless builder
18
+ if hash['type'] != expected_type
19
+ raise ResponseError, "Answer type #{hash['type'].inspect} does not match question type #{expected_type.inspect} for #{name.inspect}"
20
+ end
21
+
22
+ builder.from_h(hash, name.to_s)
23
+ end
24
+
25
+ def self.fetch(hash, key, label, *classes)
26
+ value = hash[key]
27
+ return value if classes.any? { |klass| value.is_a?(klass) }
28
+
29
+ raise ResponseError, "Invalid response data at answers.#{label}.#{key}"
30
+ end
31
+
32
+ def self.number(hash, key, label)
33
+ fetch(hash, key, label, Numeric)
34
+ end
35
+ end
36
+ end
37
+ end
@@ -0,0 +1,220 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'faraday'
4
+ require 'json'
5
+ require 'time'
6
+ require 'timeout'
7
+
8
+ module TypeSafe
9
+ module SystemOne
10
+ class Client
11
+ DEFAULT_BASE_URL = 'https://api.typesafe.ai'
12
+ DEFAULT_MODEL = 'jev-latest'
13
+ DEFAULT_TIMEOUT = 10
14
+ PATH = '/v1/systemone'
15
+ MAX_RETRIES = 2
16
+ RETRYABLE_STATUSES = [408, 429, *500..599].freeze
17
+ BACKOFF_INITIAL = 0.5
18
+ BACKOFF_MAX = 5.0
19
+ BACKOFF_JITTER = 0.25
20
+ TOTAL_RETRY_BUDGET = 30.0
21
+ QUESTION_TYPES = [Questions::Choice, Questions::Score, Questions::Noul, Questions::Box].freeze
22
+ IMAGES_OPT_IN_HEADER = 'TypeSafe-Danger-Zone-Images'
23
+ USER_AGENT = "typesafe-system-one/#{VERSION} ruby/#{RUBY_VERSION}".freeze
24
+
25
+ def initialize(api_key: ENV.fetch('TYPESAFE_API_KEY', nil), base_url: nil, model: nil, timeout: DEFAULT_TIMEOUT)
26
+ @api_key = api_key.to_s.strip
27
+ @base_url = (base_url || env_or('TYPESAFE_BASE_URL', DEFAULT_BASE_URL)).chomp('/')
28
+ @model = model || env_or('TYPESAFE_DEFAULT_MODEL', DEFAULT_MODEL)
29
+ @timeout = timeout
30
+ end
31
+
32
+ def ask(state:, questions:, model: nil, assets: nil)
33
+ raise ConfigurationError, 'API key is empty; set TYPESAFE_API_KEY or pass api_key:' if @api_key.empty?
34
+ # Net::HTTP rejects such a header with an ArgumentError that quotes the whole value, i.e. the key.
35
+ raise ConfigurationError, 'API key contains control characters' if @api_key.match?(/[[:cntrl:]]/)
36
+
37
+ raise ArgumentError, 'state is required' if state.nil?
38
+
39
+ normalized = normalize_questions(questions)
40
+ body = build_body(state, normalized, model || @model, normalize_assets(assets))
41
+ headers = request_headers
42
+ headers[IMAGES_OPT_IN_HEADER] = 'true' if body.key?(:assets)
43
+ response = post_with_retries(JSON.generate(body), headers)
44
+ expected_types = normalized.transform_values { |question| question.to_h[:type] }
45
+ Response.from_h(parse_success(response), expected_types: expected_types)
46
+ end
47
+
48
+ def inspect
49
+ "#<#{self.class.name} base_url=#{@base_url.inspect} model=#{@model.inspect} timeout=#{@timeout} api_key=[REDACTED]>"
50
+ end
51
+ alias_method :to_s, :inspect
52
+
53
+ def pretty_print(printer)
54
+ printer.text(inspect)
55
+ end
56
+
57
+ private
58
+
59
+ def env_or(name, default)
60
+ value = ENV.fetch(name, nil).to_s.strip
61
+ value.empty? ? default : value
62
+ end
63
+
64
+ def normalize_questions(questions)
65
+ raise ArgumentError, 'questions must be a non-empty Hash' unless questions.is_a?(Hash) && !questions.empty?
66
+
67
+ names = questions.keys.map(&:to_s)
68
+ raise ArgumentError, 'question names must be unique after conversion to String' if names.uniq.size != names.size
69
+
70
+ questions.to_h do |name, question|
71
+ unless QUESTION_TYPES.any? { |type| question.is_a?(type) }
72
+ raise ArgumentError, "question #{name.to_s.inspect} must be a TypeSafe::SystemOne::Questions object"
73
+ end
74
+
75
+ [name.to_s, question]
76
+ end
77
+ end
78
+
79
+ def normalize_assets(assets)
80
+ return nil if assets.nil?
81
+ raise ArgumentError, 'assets must be a Hash of TypeSafe::SystemOne::Image' unless assets.is_a?(Hash)
82
+ return nil if assets.empty?
83
+ unless assets.values.all?(Image)
84
+ raise ArgumentError, 'assets must be a Hash of TypeSafe::SystemOne::Image'
85
+ end
86
+
87
+ normalized = assets.to_h { |key, image| [key.to_s, image] }
88
+ raise ArgumentError, 'asset names must be unique after conversion to String' if normalized.size != assets.size
89
+
90
+ normalized
91
+ end
92
+
93
+ def build_body(state, questions, model, assets)
94
+ body = {
95
+ model: model,
96
+ state: state,
97
+ questions: questions.transform_values(&:to_h)
98
+ }
99
+ body[:assets] = assets.transform_values(&:to_h) if assets
100
+ body
101
+ end
102
+
103
+ def connection
104
+ @connection ||= Faraday.new do |f|
105
+ f.options.timeout = @timeout
106
+ f.options.open_timeout = @timeout
107
+ f.adapter Faraday.default_adapter
108
+ end
109
+ end
110
+
111
+ def request_headers
112
+ {
113
+ 'Authorization' => "Bearer #{@api_key}",
114
+ 'Content-Type' => 'application/json',
115
+ 'Accept' => 'application/json',
116
+ 'User-Agent' => USER_AGENT
117
+ }
118
+ end
119
+
120
+ def post_with_retries(payload, headers)
121
+ started = monotonic_now
122
+ attempt = 0
123
+ begin
124
+ attempt += 1
125
+ perform(payload, headers)
126
+ rescue APIError, ConnectionError => e
127
+ delay = next_delay(e, attempt, started)
128
+ raise unless delay
129
+
130
+ pause(delay)
131
+ retry
132
+ end
133
+ end
134
+
135
+ # nil means give up: not retryable, out of attempts, or the wait would exceed the total budget.
136
+ def next_delay(error, attempt, started)
137
+ return nil unless attempt <= MAX_RETRIES && retryable?(error)
138
+
139
+ delay = retry_delay(error, attempt)
140
+ monotonic_now - started + delay < TOTAL_RETRY_BUDGET ? delay : nil
141
+ end
142
+
143
+ def retryable?(error)
144
+ return true if error.is_a?(ConnectionError)
145
+
146
+ RETRYABLE_STATUSES.include?(error.status)
147
+ end
148
+
149
+ def perform(payload, headers)
150
+ response = connection.post("#{@base_url}#{PATH}", payload, headers)
151
+ return response if response.status.between?(200, 299)
152
+
153
+ raise APIError.new(status: response.status, body: parse_error_body(response.body), headers: response.headers)
154
+ rescue Faraday::TimeoutError => e
155
+ raise TimeoutError, "Request timed out (timeout=#{@timeout}): #{e.class}"
156
+ rescue Faraday::ConnectionFailed, Faraday::SSLError => e
157
+ raise open_timeout_error if e.wrapped_exception.is_a?(::Timeout::Error)
158
+
159
+ raise ConnectionError, "Connection failed: #{e.class}"
160
+ rescue Faraday::Error => e
161
+ raise ConnectionError, "Request failed: #{e.class}"
162
+ end
163
+
164
+ # Faraday reports connect timeouts as ConnectionFailed wrapping Timeout::Error.
165
+ def open_timeout_error
166
+ TimeoutError.new("Request timed out (timeout=#{@timeout})")
167
+ end
168
+
169
+ def parse_error_body(raw)
170
+ return nil if raw.nil? || raw.empty?
171
+
172
+ JSON.parse(raw)
173
+ rescue JSON::ParserError
174
+ raw
175
+ end
176
+
177
+ def parse_success(response)
178
+ JSON.parse(response.body.to_s)
179
+ rescue JSON::ParserError
180
+ raise ResponseError, 'Response body is not valid JSON'
181
+ end
182
+
183
+ def retry_delay(error, attempt)
184
+ from_header = error.is_a?(APIError) ? retry_after_seconds(error.headers) : nil
185
+ from_header || backoff(attempt)
186
+ end
187
+
188
+ def backoff(attempt)
189
+ base = [BACKOFF_INITIAL * (2**(attempt - 1)), BACKOFF_MAX].min
190
+ (base * (1 - (rand * BACKOFF_JITTER))).round(3)
191
+ end
192
+
193
+ def retry_after_seconds(headers)
194
+ millis = Float(headers['retry-after-ms'].to_s.strip, exception: false)
195
+ return millis / 1000.0 if millis && millis >= 0 && millis.finite?
196
+
197
+ parse_retry_after(headers['retry-after'].to_s.strip)
198
+ end
199
+
200
+ def parse_retry_after(raw)
201
+ return nil if raw.empty?
202
+
203
+ seconds = Float(raw, exception: false)
204
+ return (seconds >= 0 && seconds.finite? ? seconds : nil) if seconds
205
+
206
+ [(Time.httpdate(raw) - Time.now), 0.0].max
207
+ rescue ArgumentError
208
+ nil
209
+ end
210
+
211
+ def monotonic_now
212
+ Process.clock_gettime(Process::CLOCK_MONOTONIC)
213
+ end
214
+
215
+ def pause(seconds)
216
+ sleep(seconds)
217
+ end
218
+ end
219
+ end
220
+ end
@@ -0,0 +1,88 @@
1
+ # frozen_string_literal: true
2
+
3
+ module TypeSafe
4
+ module SystemOne
5
+ MAX_ERROR_BODY_LENGTH = 200
6
+
7
+ class Error < StandardError; end
8
+
9
+ class ConfigurationError < Error; end
10
+
11
+ class ConnectionError < Error; end
12
+
13
+ class TimeoutError < ConnectionError; end
14
+
15
+ class ResponseError < Error; end
16
+
17
+ # The server may echo the request (state) back in fields we do not know, so only known message fields reach #message.
18
+ class APIError < Error
19
+ REQUEST_ID_HEADER = 'x-typesafe-request-id'
20
+
21
+ attr_reader :status, :body, :headers
22
+
23
+ def initialize(status:, body: nil, headers: {})
24
+ @status = status
25
+ @body = body
26
+ @headers = headers
27
+ super(build_message)
28
+ end
29
+
30
+ def request_id
31
+ headers[REQUEST_ID_HEADER]
32
+ end
33
+
34
+ def self.extract_message(body)
35
+ return nil unless body.is_a?(Hash)
36
+
37
+ from_error(body['error']) || from_text(body['message']) ||
38
+ from_text(body['detail']) || from_detail(body['detail'])
39
+ end
40
+
41
+ def self.from_text(value)
42
+ value.is_a?(String) ? value : nil
43
+ end
44
+
45
+ def self.from_error(error)
46
+ return error if error.is_a?(String)
47
+
48
+ error.is_a?(Hash) ? from_text(error['message']) : nil
49
+ end
50
+
51
+ def self.from_detail(detail)
52
+ return from_text(detail['message']) if detail.is_a?(Hash)
53
+ return nil unless detail.is_a?(Array)
54
+
55
+ parts = detail.filter_map { |entry| detail_part(entry) }
56
+ parts.empty? ? nil : parts.join('; ')
57
+ end
58
+
59
+ def self.detail_part(entry)
60
+ return nil unless entry.is_a?(Hash) && entry['msg'].is_a?(String)
61
+
62
+ loc = entry['loc']
63
+ path = loc.is_a?(Array) ? loc.reject { |item| item == 'body' }.join('.') : ''
64
+ path.empty? ? entry['msg'] : "#{path}: #{entry['msg']}"
65
+ end
66
+
67
+ private
68
+
69
+ def build_message
70
+ text = "#{status} #{detail_text}"
71
+ id = request_id
72
+ id ? "#{text} (request_id=#{id})" : text
73
+ end
74
+
75
+ def detail_text
76
+ extracted = self.class.extract_message(body)
77
+ return truncate(extracted) if extracted
78
+ return 'status code (no body)' if body.nil?
79
+
80
+ 'status code (unrecognized body)'
81
+ end
82
+
83
+ def truncate(text)
84
+ text.length > MAX_ERROR_BODY_LENGTH ? "#{text[0, MAX_ERROR_BODY_LENGTH]}…" : text
85
+ end
86
+ end
87
+ end
88
+ end
@@ -0,0 +1,37 @@
1
+ # frozen_string_literal: true
2
+
3
+ module TypeSafe
4
+ module SystemOne
5
+ IMAGE_FORMATS = %w[png jpg jpeg].freeze
6
+
7
+ Image = Data.define(:data, :format) do
8
+ def self.from_file(path)
9
+ extension = File.extname(path).delete_prefix('.').downcase
10
+ new(data: File.binread(path), format: extension)
11
+ end
12
+
13
+ def initialize(data:, format:)
14
+ normalized = format.to_s.downcase
15
+ unless IMAGE_FORMATS.include?(normalized)
16
+ raise ArgumentError, "format must be one of #{IMAGE_FORMATS.join(', ')}"
17
+ end
18
+ raise ArgumentError, 'data must be a non-empty String' unless data.is_a?(String) && !data.empty?
19
+
20
+ super(data: data, format: normalized)
21
+ end
22
+
23
+ def inspect
24
+ "#<data #{self.class.name} format=#{format.inspect} bytes=#{data.bytesize}>"
25
+ end
26
+ alias_method :to_s, :inspect
27
+
28
+ def pretty_print(printer)
29
+ printer.text(inspect)
30
+ end
31
+
32
+ def to_h
33
+ { type: 'image', format: format, data_base64: [data].pack('m0') }
34
+ end
35
+ end
36
+ end
37
+ end
@@ -0,0 +1,19 @@
1
+ # frozen_string_literal: true
2
+
3
+ module TypeSafe
4
+ module SystemOne
5
+ module Questions
6
+ Box = Data.define(:instructions) do
7
+ def initialize(instructions:)
8
+ raise ArgumentError, 'instructions is required' if instructions.nil?
9
+
10
+ super
11
+ end
12
+
13
+ def to_h
14
+ { type: 'box', instructions: instructions }
15
+ end
16
+ end
17
+ end
18
+ end
19
+ end
@@ -0,0 +1,27 @@
1
+ # frozen_string_literal: true
2
+
3
+ module TypeSafe
4
+ module SystemOne
5
+ MAX_CHOICE_CRITERIA = 255
6
+
7
+ module Questions
8
+ Choice = Data.define(:instructions, :criteria) do
9
+ def initialize(instructions:, criteria:)
10
+ raise ArgumentError, 'instructions is required' if instructions.nil?
11
+ unless criteria.is_a?(Hash) && (1..MAX_CHOICE_CRITERIA).cover?(criteria.size)
12
+ raise ArgumentError, "criteria must be a Hash with 1 to #{MAX_CHOICE_CRITERIA} entries"
13
+ end
14
+
15
+ normalized = criteria.transform_keys(&:to_s)
16
+ raise ArgumentError, 'criteria keys must be unique after conversion to String' if normalized.size != criteria.size
17
+
18
+ super(instructions: instructions, criteria: normalized.freeze)
19
+ end
20
+
21
+ def to_h
22
+ { type: 'choice', instructions: instructions, criteria: criteria }
23
+ end
24
+ end
25
+ end
26
+ end
27
+ end
@@ -0,0 +1,26 @@
1
+ # frozen_string_literal: true
2
+
3
+ module TypeSafe
4
+ module SystemOne
5
+ module Questions
6
+ Noul = Data.define(:instructions, :criteria) do
7
+ def initialize(instructions:, criteria: nil)
8
+ raise ArgumentError, 'instructions is required' if instructions.nil?
9
+ raise ArgumentError, 'criteria must be a Hash or nil' unless criteria.nil? || criteria.is_a?(Hash)
10
+
11
+ normalized = criteria&.transform_keys(&:to_s)
12
+ unknown = normalized ? normalized.keys - %w[true false] : []
13
+ raise ArgumentError, 'criteria keys must be true and/or false' unless unknown.empty?
14
+ raise ArgumentError, 'criteria keys must be unique' if normalized && normalized.size != criteria.size
15
+
16
+ super(instructions: instructions, criteria: normalized&.freeze)
17
+ end
18
+
19
+ def to_h
20
+ base = { type: 'noul', instructions: instructions }
21
+ criteria ? base.merge(criteria: criteria) : base
22
+ end
23
+ end
24
+ end
25
+ end
26
+ end
@@ -0,0 +1,22 @@
1
+ # frozen_string_literal: true
2
+
3
+ module TypeSafe
4
+ module SystemOne
5
+ module Questions
6
+ Score = Data.define(:instructions, :criteria) do
7
+ def initialize(instructions:, criteria:)
8
+ raise ArgumentError, 'instructions is required' if instructions.nil?
9
+ unless criteria.is_a?(Array) && !criteria.empty?
10
+ raise ArgumentError, 'criteria must be a non-empty Array'
11
+ end
12
+
13
+ super(instructions: instructions, criteria: criteria.dup.freeze)
14
+ end
15
+
16
+ def to_h
17
+ { type: 'score', instructions: instructions, criteria: criteria }
18
+ end
19
+ end
20
+ end
21
+ end
22
+ end
@@ -0,0 +1,22 @@
1
+ # frozen_string_literal: true
2
+
3
+ module TypeSafe
4
+ module SystemOne
5
+ Response = Data.define(:model, :answers, :usage) do
6
+ def self.from_h(hash, expected_types:)
7
+ raise ResponseError, 'Response body is not a JSON object' unless hash.is_a?(Hash)
8
+ raise ResponseError, 'Invalid response data at "model"' unless hash['model'].is_a?(String)
9
+
10
+ answers = hash['answers']
11
+ raise ResponseError, 'Invalid response data at "answers"' unless answers.is_a?(Hash)
12
+
13
+ built = expected_types.to_h do |name, type|
14
+ raise ResponseError, "Missing answer for question #{name.inspect}" unless answers.key?(name)
15
+
16
+ [name, Answers.build(answers[name], name: name, expected_type: type)]
17
+ end
18
+ new(model: hash['model'], answers: built.freeze, usage: Usage.from_h(hash['usage']))
19
+ end
20
+ end
21
+ end
22
+ end
@@ -0,0 +1,15 @@
1
+ # frozen_string_literal: true
2
+
3
+ module TypeSafe
4
+ module SystemOne
5
+ Usage = Data.define(:input_tokens, :output_tokens) do
6
+ def self.from_h(hash)
7
+ unless hash.is_a?(Hash) && hash['input_tokens'].is_a?(Integer) && hash['output_tokens'].is_a?(Integer)
8
+ raise ResponseError, 'Invalid response data at "usage"'
9
+ end
10
+
11
+ new(input_tokens: hash['input_tokens'], output_tokens: hash['output_tokens'])
12
+ end
13
+ end
14
+ end
15
+ end
@@ -0,0 +1,7 @@
1
+ # frozen_string_literal: true
2
+
3
+ module TypeSafe
4
+ module SystemOne
5
+ VERSION = '0.1.0'
6
+ end
7
+ end
@@ -0,0 +1,17 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'system_one/version'
4
+ require_relative 'system_one/errors'
5
+ require_relative 'system_one/image'
6
+ require_relative 'system_one/questions/choice'
7
+ require_relative 'system_one/questions/score'
8
+ require_relative 'system_one/questions/noul'
9
+ require_relative 'system_one/questions/box'
10
+ require_relative 'system_one/answers/choice'
11
+ require_relative 'system_one/answers/score'
12
+ require_relative 'system_one/answers/noul'
13
+ require_relative 'system_one/answers/box'
14
+ require_relative 'system_one/answers'
15
+ require_relative 'system_one/usage'
16
+ require_relative 'system_one/response'
17
+ require_relative 'system_one/client'
metadata ADDED
@@ -0,0 +1,79 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: typesafe-system-one
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - NichiyaOba
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2026-12-06 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: faraday
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '2.0'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '2.0'
27
+ description: An unofficial community Ruby client for the TypeSafe AI System One API
28
+ (choice, score, noul and box questions). Experimental; not affiliated with TypeSafe.
29
+ email:
30
+ executables: []
31
+ extensions: []
32
+ extra_rdoc_files: []
33
+ files:
34
+ - CHANGELOG.md
35
+ - LICENSE.txt
36
+ - README.md
37
+ - lib/typesafe/system_one.rb
38
+ - lib/typesafe/system_one/answers.rb
39
+ - lib/typesafe/system_one/answers/box.rb
40
+ - lib/typesafe/system_one/answers/choice.rb
41
+ - lib/typesafe/system_one/answers/noul.rb
42
+ - lib/typesafe/system_one/answers/score.rb
43
+ - lib/typesafe/system_one/client.rb
44
+ - lib/typesafe/system_one/errors.rb
45
+ - lib/typesafe/system_one/image.rb
46
+ - lib/typesafe/system_one/questions/box.rb
47
+ - lib/typesafe/system_one/questions/choice.rb
48
+ - lib/typesafe/system_one/questions/noul.rb
49
+ - lib/typesafe/system_one/questions/score.rb
50
+ - lib/typesafe/system_one/response.rb
51
+ - lib/typesafe/system_one/usage.rb
52
+ - lib/typesafe/system_one/version.rb
53
+ homepage: https://github.com/NichiyaOba/typesafe-sdk-ruby
54
+ licenses:
55
+ - MIT
56
+ metadata:
57
+ source_code_uri: https://github.com/NichiyaOba/typesafe-sdk-ruby
58
+ changelog_uri: https://github.com/NichiyaOba/typesafe-sdk-ruby/blob/main/CHANGELOG.md
59
+ rubygems_mfa_required: 'true'
60
+ post_install_message:
61
+ rdoc_options: []
62
+ require_paths:
63
+ - lib
64
+ required_ruby_version: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - ">="
67
+ - !ruby/object:Gem::Version
68
+ version: '3.3'
69
+ required_rubygems_version: !ruby/object:Gem::Requirement
70
+ requirements:
71
+ - - ">="
72
+ - !ruby/object:Gem::Version
73
+ version: '0'
74
+ requirements: []
75
+ rubygems_version: 3.5.3
76
+ signing_key:
77
+ specification_version: 4
78
+ summary: Unofficial, experimental Ruby client for the TypeSafe AI System One API
79
+ test_files: []