ai-lite 1.1.0 → 1.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +4 -4
- data/CHANGELOG.md +25 -6
- data/README.md +392 -23
- data/lib/ai_lite/claude/chat.rb +73 -0
- data/lib/ai_lite/claude/configuration.rb +22 -0
- data/lib/ai_lite/claude.rb +82 -0
- data/lib/ai_lite/gemini/chat.rb +8 -5
- data/lib/ai_lite/gemini/configuration.rb +7 -1
- data/lib/ai_lite/gemini/images.rb +1 -1
- data/lib/ai_lite/gemini/models.rb +1 -1
- data/lib/ai_lite/gemini/speech.rb +108 -0
- data/lib/ai_lite/gemini/streaming.rb +34 -5
- data/lib/ai_lite/gemini/tokens.rb +53 -0
- data/lib/ai_lite/gemini/tool_calling.rb +66 -0
- data/lib/ai_lite/gemini/transcription.rb +66 -0
- data/lib/ai_lite/gemini.rb +21 -3
- data/lib/ai_lite/openai/streaming.rb +11 -7
- data/lib/ai_lite/openai/tokens.rb +38 -0
- data/lib/ai_lite/openai/tool_calling.rb +71 -0
- data/lib/ai_lite/openai.rb +22 -15
- data/lib/ai_lite/version.rb +1 -1
- data/lib/ai_lite.rb +1 -0
- data/test/ai_lite_test.rb +5 -5
- data/test/claude_test.rb +156 -0
- data/test/gemini_images_test.rb +6 -6
- data/test/gemini_models_test.rb +1 -1
- data/test/gemini_speech_test.rb +199 -0
- data/test/gemini_test.rb +1 -1
- data/test/gemini_transcription_test.rb +123 -0
- data/test/package_test.rb +52 -0
- data/test/token_counting_test.rb +173 -0
- data/test/tool_calling_test.rb +270 -0
- metadata +26 -8
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
require_relative "test_helper"
|
|
2
|
+
require "tmpdir"
|
|
3
|
+
|
|
4
|
+
class GeminiSpeechTest < Minitest::Test
|
|
5
|
+
Response = Struct.new(:code, :body)
|
|
6
|
+
class Http
|
|
7
|
+
attr_accessor :open_timeout, :read_timeout
|
|
8
|
+
attr_reader :request_received
|
|
9
|
+
def initialize(response)
|
|
10
|
+
@response = response
|
|
11
|
+
end
|
|
12
|
+
def request(request)
|
|
13
|
+
@request_received = request
|
|
14
|
+
raise @response if @response.is_a?(Exception)
|
|
15
|
+
@response
|
|
16
|
+
end
|
|
17
|
+
end
|
|
18
|
+
|
|
19
|
+
def setup
|
|
20
|
+
AiLite::Gemini.reset_configuration!
|
|
21
|
+
AiLite::OpenAI.reset_configuration!
|
|
22
|
+
@client = AiLite::Gemini.new(api_key: "gemini-key", timeout: 9)
|
|
23
|
+
end
|
|
24
|
+
|
|
25
|
+
def with_http(raw = {}, status = "200")
|
|
26
|
+
response = raw.is_a?(Exception) ? raw : Response.new(status, raw.is_a?(String) ? raw : JSON.generate(raw))
|
|
27
|
+
http = Http.new(response)
|
|
28
|
+
original = Net::HTTP.method(:start)
|
|
29
|
+
Net::HTTP.define_singleton_method(:start) do |host, port, use_ssl:, &block|
|
|
30
|
+
raise "Wrong provider host" unless host == "generativelanguage.googleapis.com" && port == 443 && use_ssl
|
|
31
|
+
block.call(http)
|
|
32
|
+
end
|
|
33
|
+
yield http
|
|
34
|
+
ensure
|
|
35
|
+
Net::HTTP.define_singleton_method(:start, original)
|
|
36
|
+
end
|
|
37
|
+
|
|
38
|
+
PCM = "\x00\x00\xff\x7f".b
|
|
39
|
+
WAV = "RIFF".b + [36 + PCM.bytesize].pack("V") + "WAVEfmt ".b +
|
|
40
|
+
[16, 1, 1, 24000, 48000, 2, 16].pack("VvvVVvv") + "data".b + [PCM.bytesize].pack("V") + PCM
|
|
41
|
+
|
|
42
|
+
def speech_body(bytes = WAV, mime = "audio/wav")
|
|
43
|
+
{ "id" => "speech-123", "status" => "completed", "steps" => [
|
|
44
|
+
{ "type" => "thought", "content" => [{ "type" => "audio", "data" => "ignored" }] },
|
|
45
|
+
{ "type" => "model_output", "content" => [
|
|
46
|
+
{ "type" => "text", "text" => "Here is the audio" },
|
|
47
|
+
{ "type" => "audio", "mime_type" => mime, "data" => [bytes].pack("m0") }
|
|
48
|
+
] }
|
|
49
|
+
], "usage" => { "total_tokens" => 5 } }
|
|
50
|
+
end
|
|
51
|
+
|
|
52
|
+
def test_default_payload_transport_and_binary_envelope
|
|
53
|
+
with_http(speech_body) do |http|
|
|
54
|
+
result = @client.speak("Hello")
|
|
55
|
+
assert_equal({ "content" => WAV, "status" => 200, "error" => nil, "raw" => nil,
|
|
56
|
+
"response_id" => "speech-123" }, result)
|
|
57
|
+
assert_equal Encoding::BINARY, result["content"].encoding
|
|
58
|
+
request = http.request_received
|
|
59
|
+
assert_equal "/v1beta/interactions", request.path
|
|
60
|
+
assert_equal "gemini-key", request["x-goog-api-key"]
|
|
61
|
+
assert_equal 9, http.read_timeout
|
|
62
|
+
payload = JSON.parse(request.body)
|
|
63
|
+
assert_equal "gemini-3.8-flash-tts", payload["model"]
|
|
64
|
+
assert_equal [{ "type" => "user_input", "content" => [{ "type" => "text", "text" => "Hello" }] }], payload["input"]
|
|
65
|
+
assert_equal({ "speech_config" => [{ "voice" => "Kore" }] }, payload["generation_config"])
|
|
66
|
+
assert_equal({ "type" => "audio", "mime_type" => "audio/wav" }, payload["response_format"])
|
|
67
|
+
end
|
|
68
|
+
end
|
|
69
|
+
|
|
70
|
+
def test_keywords_native_options_precedence_and_no_mutation
|
|
71
|
+
options = { "model" => "ignored", input: "ignored", store: false,
|
|
72
|
+
generation_config: { temperature: 0.5, speech_config: [{ voice: "ignored" }] },
|
|
73
|
+
response_format: { type: "text", mime_type: "audio/wav", sample_rate: 16000 } }
|
|
74
|
+
original = Marshal.dump(options)
|
|
75
|
+
with_http(speech_body(PCM, "audio/l16;rate=16000")) do |http|
|
|
76
|
+
result = @client.speak("Hello", model: "custom-tts", voice: "Puck", instructions: "Speak calmly",
|
|
77
|
+
response_format: "pcm", options: options, debug: true)
|
|
78
|
+
assert_equal PCM, result["content"]
|
|
79
|
+
assert_equal 5, result.dig("raw", "usage", "total_tokens")
|
|
80
|
+
payload = JSON.parse(http.request_received.body)
|
|
81
|
+
assert_equal "custom-tts", payload["model"]
|
|
82
|
+
assert_equal false, payload["store"]
|
|
83
|
+
assert_equal [{ "voice" => "Puck" }], payload.dig("generation_config", "speech_config")
|
|
84
|
+
assert_equal 0.5, payload.dig("generation_config", "temperature")
|
|
85
|
+
refute payload["generation_config"].key?("max_output_tokens")
|
|
86
|
+
assert_equal [{ "type" => "speech_metadata", "style" => "Speak calmly" }], payload.dig("input", 0, "content", 0, "annotations")
|
|
87
|
+
assert_equal({ "type" => "audio", "mime_type" => "audio/l16", "sample_rate" => 16000 }, payload["response_format"])
|
|
88
|
+
end
|
|
89
|
+
assert_equal original, Marshal.dump(options)
|
|
90
|
+
end
|
|
91
|
+
|
|
92
|
+
def test_file_output_and_base64_priority
|
|
93
|
+
Dir.mktmpdir do |dir|
|
|
94
|
+
path = File.join(dir, "speech.wav")
|
|
95
|
+
with_http(speech_body) do
|
|
96
|
+
result = @client.speak("Hello", output_path: path)
|
|
97
|
+
assert_equal({ "path" => path, "bytes" => WAV.bytesize, "format" => "wav" }, result["content"])
|
|
98
|
+
assert_equal WAV, File.binread(path)
|
|
99
|
+
end
|
|
100
|
+
with_http(speech_body) do
|
|
101
|
+
result = @client.speak("Hello", output_path: path, base64: true)
|
|
102
|
+
assert_equal [WAV].pack("m0"), result["content"]
|
|
103
|
+
assert_equal WAV, File.binread(path)
|
|
104
|
+
end
|
|
105
|
+
with_http(speech_body) do
|
|
106
|
+
result = @client.speak("Hello", output_path: File.join(dir, "missing", "speech.wav"), debug: true)
|
|
107
|
+
refute_nil result["error"]
|
|
108
|
+
assert_nil result["content"]
|
|
109
|
+
assert_equal "speech-123", result["response_id"]
|
|
110
|
+
refute_nil result["raw"]
|
|
111
|
+
end
|
|
112
|
+
end
|
|
113
|
+
with_http(speech_body) { assert_equal [WAV].pack("m0"), @client.speak("Hello", base64: true)["content"] }
|
|
114
|
+
end
|
|
115
|
+
|
|
116
|
+
def test_supported_formats_and_native_format_option
|
|
117
|
+
{ "pcm" => "audio/l16", "mulaw" => "audio/mulaw", "alaw" => "audio/alaw" }.each do |format, mime|
|
|
118
|
+
with_http(speech_body(PCM, mime)) do |http|
|
|
119
|
+
assert_equal PCM, @client.speak("Hello", response_format: format)["content"]
|
|
120
|
+
assert_equal mime, JSON.parse(http.request_received.body).dig("response_format", "mime_type")
|
|
121
|
+
end
|
|
122
|
+
end
|
|
123
|
+
with_http(speech_body(PCM, "audio/l16")) do |http|
|
|
124
|
+
assert_nil @client.speak("Hello", options: { response_format: { mime_type: "audio/l16" } })["error"]
|
|
125
|
+
assert_equal "audio/l16", JSON.parse(http.request_received.body).dig("response_format", "mime_type")
|
|
126
|
+
end
|
|
127
|
+
end
|
|
128
|
+
|
|
129
|
+
def test_configuration_class_delegation_and_model_checks
|
|
130
|
+
original = AiLite::OpenAI.configured_models
|
|
131
|
+
AiLite::Gemini.configure { |c| c.api_key = "key"; c.speech_model = "configured-tts"; c.speech_voice = "Puck" }
|
|
132
|
+
assert_equal "Kore", @client.speech_voice
|
|
133
|
+
assert_equal "gemini-3.8-flash-tts", @client.speech_model
|
|
134
|
+
override = AiLite::Gemini.new(speech_model: "override", speech_voice: "Zephyr")
|
|
135
|
+
assert_equal ["override", "Zephyr"], [override.speech_model, override.speech_voice]
|
|
136
|
+
snapshot = AiLite::Gemini.configured_models
|
|
137
|
+
snapshot["speech"].replace("changed")
|
|
138
|
+
assert_equal "configured-tts", AiLite::Gemini.configuration.speech_model
|
|
139
|
+
with_http(speech_body) do |http|
|
|
140
|
+
assert_equal WAV, AiLite::Gemini.speak("Hello")["content"]
|
|
141
|
+
payload = JSON.parse(http.request_received.body)
|
|
142
|
+
assert_equal "configured-tts", payload["model"]
|
|
143
|
+
assert_equal [{ "voice" => "Puck" }], payload.dig("generation_config", "speech_config")
|
|
144
|
+
end
|
|
145
|
+
with_http({ "models" => [{ "name" => "models/configured-tts" }] }) do
|
|
146
|
+
assert_equal true, AiLite::Gemini.check_configured_models.dig("content", "speech", "available")
|
|
147
|
+
end
|
|
148
|
+
assert_equal original, AiLite::OpenAI.configured_models
|
|
149
|
+
end
|
|
150
|
+
|
|
151
|
+
def test_invalid_inputs_rejected_before_http
|
|
152
|
+
with_http do |http|
|
|
153
|
+
[nil, " ", [], {}].each { |value| refute_nil @client.speak(value)["error"] }
|
|
154
|
+
[{ voice: "" }, { instructions: [] }, { response_format: "mp3" }, { options: nil },
|
|
155
|
+
{ options: { stream: true } }, { options: { "background" => true } },
|
|
156
|
+
{ options: { generation_config: [] } }, { options: { response_format: nil } },
|
|
157
|
+
{ options: { response_format: { mime_type: "audio/mpeg" } } }].each do |kwargs|
|
|
158
|
+
refute_nil @client.speak("Hello", **kwargs)["error"]
|
|
159
|
+
end
|
|
160
|
+
assert_nil http.request_received
|
|
161
|
+
end
|
|
162
|
+
end
|
|
163
|
+
|
|
164
|
+
def test_errors_and_malformed_audio_preserve_existing_file
|
|
165
|
+
bad_data = speech_body
|
|
166
|
+
bad_data["steps"][1]["content"][1]["data"] = "invalid!"
|
|
167
|
+
missing_data = speech_body
|
|
168
|
+
missing_data["steps"][1]["content"][1].delete("data")
|
|
169
|
+
many = speech_body
|
|
170
|
+
many["steps"][1]["content"] << many["steps"][1]["content"][1].dup
|
|
171
|
+
responses = ["bad JSON", [], {}, IOError.new("Disconnected"), bad_data, missing_data, many,
|
|
172
|
+
speech_body("", "audio/wav"), speech_body("not wav"), speech_body(PCM, "audio/unknown"),
|
|
173
|
+
speech_body.merge("steps" => []), speech_body.merge("steps" => nil)]
|
|
174
|
+
%w[failed incomplete cancelled requires_action queued in_progress].each do |state|
|
|
175
|
+
responses << speech_body.merge("status" => state)
|
|
176
|
+
end
|
|
177
|
+
Dir.mktmpdir do |dir|
|
|
178
|
+
path = File.join(dir, "existing.wav")
|
|
179
|
+
File.binwrite(path, "original")
|
|
180
|
+
responses.each do |raw|
|
|
181
|
+
with_http(raw) do
|
|
182
|
+
result = @client.speak("Hello", output_path: path)
|
|
183
|
+
refute_nil result["error"]
|
|
184
|
+
assert_nil result["content"]
|
|
185
|
+
assert_nil result["raw"]
|
|
186
|
+
assert_equal "original", File.binread(path)
|
|
187
|
+
end
|
|
188
|
+
end
|
|
189
|
+
end
|
|
190
|
+
%w[403 200].each do |status|
|
|
191
|
+
with_http({ "error" => { "message" => "Denied" } }, status) do
|
|
192
|
+
result = @client.speak("Hello", debug: true)
|
|
193
|
+
assert_equal "Denied", result["error"]
|
|
194
|
+
assert_equal status.to_i, result["status"]
|
|
195
|
+
refute_nil result["raw"]
|
|
196
|
+
end
|
|
197
|
+
end
|
|
198
|
+
end
|
|
199
|
+
end
|
data/test/gemini_test.rb
CHANGED
|
@@ -130,7 +130,7 @@ class GeminiTest < Minitest::Test
|
|
|
130
130
|
assert_same openai, AiLite::OpenAI.client
|
|
131
131
|
assert_equal "openai-key", openai.api_key
|
|
132
132
|
refute AiLite::Gemini < AiLite::OpenAI
|
|
133
|
-
%i[moderate
|
|
133
|
+
%i[moderate].each { |method| refute_respond_to gemini, method }
|
|
134
134
|
with_http do
|
|
135
135
|
assert_equal "Hello", AiLite::Gemini.chat("Hello")["content"]
|
|
136
136
|
end
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
require_relative "test_helper"
|
|
2
|
+
require "tmpdir"
|
|
3
|
+
|
|
4
|
+
class GeminiTranscriptionTest < Minitest::Test
|
|
5
|
+
Response = Struct.new(:code, :body)
|
|
6
|
+
|
|
7
|
+
def setup
|
|
8
|
+
AiLite::Gemini.reset_configuration!
|
|
9
|
+
@client = AiLite::Gemini.new(api_key: "key")
|
|
10
|
+
@dir = Dir.mktmpdir
|
|
11
|
+
@path = File.join(@dir, "sample.WAV")
|
|
12
|
+
File.binwrite(@path, "RIFF\x00\xff".b)
|
|
13
|
+
end
|
|
14
|
+
|
|
15
|
+
def teardown
|
|
16
|
+
FileUtils.remove_entry(@dir)
|
|
17
|
+
AiLite::Gemini.reset_configuration!
|
|
18
|
+
end
|
|
19
|
+
|
|
20
|
+
def body(text = "Hello!")
|
|
21
|
+
{ "id" => "transcript-1", "status" => "completed", "steps" => [
|
|
22
|
+
{ "type" => "thought", "content" => [{ "type" => "text", "text" => "ignore" }] },
|
|
23
|
+
{ "type" => "model_output", "content" => [{ "type" => "text", "text" => text }] }
|
|
24
|
+
] }
|
|
25
|
+
end
|
|
26
|
+
|
|
27
|
+
def with_response(raw = body, code = "200")
|
|
28
|
+
original = Net::HTTP.method(:start)
|
|
29
|
+
test = self
|
|
30
|
+
Net::HTTP.define_singleton_method(:start) do |host, port, use_ssl:, &block|
|
|
31
|
+
test.assert_equal "generativelanguage.googleapis.com", host
|
|
32
|
+
test.assert_equal 443, port
|
|
33
|
+
test.assert use_ssl
|
|
34
|
+
http = Object.new
|
|
35
|
+
http.define_singleton_method(:open_timeout=) { |_| }
|
|
36
|
+
http.define_singleton_method(:read_timeout=) { |_| }
|
|
37
|
+
http.define_singleton_method(:request) do |request|
|
|
38
|
+
test.instance_variable_set(:@request, request)
|
|
39
|
+
raise raw if raw.is_a?(Exception)
|
|
40
|
+
Response.new(code, raw.is_a?(String) ? raw : JSON.generate(raw))
|
|
41
|
+
end
|
|
42
|
+
block.call(http)
|
|
43
|
+
end
|
|
44
|
+
yield
|
|
45
|
+
ensure
|
|
46
|
+
Net::HTTP.define_singleton_method(:start, original)
|
|
47
|
+
end
|
|
48
|
+
|
|
49
|
+
def test_transport_and_plain_text_envelope
|
|
50
|
+
with_response(body('{"spoken":true}')) do
|
|
51
|
+
result = @client.transcribe(@path)
|
|
52
|
+
assert_equal({ "content" => '{"spoken":true}', "error" => nil, "status" => 200,
|
|
53
|
+
"response_id" => "transcript-1", "raw" => nil }, result)
|
|
54
|
+
assert_equal "/v1beta/interactions", @request.path
|
|
55
|
+
assert_equal "key", @request["x-goog-api-key"]
|
|
56
|
+
payload = JSON.parse(@request.body)
|
|
57
|
+
assert_equal "gemini-3.5-transcribe", payload["model"]
|
|
58
|
+
assert_equal File.binread(@path), payload["input"][0]["data"].unpack1("m0")
|
|
59
|
+
assert_equal "audio/wav", payload["input"][0]["mime_type"]
|
|
60
|
+
refute payload.key?("generation_config")
|
|
61
|
+
end
|
|
62
|
+
end
|
|
63
|
+
|
|
64
|
+
def test_configuration_delegation_options_and_debug
|
|
65
|
+
AiLite::Gemini.configure { |c| c.api_key = "key"; c.transcription_model = "configured" }
|
|
66
|
+
options = { model: "ignored", input: "ignored", store: false,
|
|
67
|
+
generation_config: { transcription_config: { language_codes: ["en-US"] } } }
|
|
68
|
+
before = Marshal.dump(options)
|
|
69
|
+
with_response do
|
|
70
|
+
result = AiLite::Gemini.transcribe(@path, options: options, debug: true)
|
|
71
|
+
assert_nil result["error"]
|
|
72
|
+
assert_equal body, result["raw"]
|
|
73
|
+
payload = JSON.parse(@request.body)
|
|
74
|
+
assert_equal "configured", payload["model"]
|
|
75
|
+
assert_equal false, payload["store"]
|
|
76
|
+
assert_equal ["en-US"], payload.dig("generation_config", "transcription_config", "language_codes")
|
|
77
|
+
end
|
|
78
|
+
assert_equal before, Marshal.dump(options)
|
|
79
|
+
client = AiLite::Gemini.new(transcription_model: "constructor")
|
|
80
|
+
assert_equal "constructor", client.configured_models["transcription"]
|
|
81
|
+
with_response do
|
|
82
|
+
client.transcribe(@path, model: "override", mime_type: "audio/l16;rate=24000")
|
|
83
|
+
assert_equal "override", JSON.parse(@request.body)["model"]
|
|
84
|
+
assert_equal "audio/l16;rate=24000", JSON.parse(@request.body).dig("input", 0, "mime_type")
|
|
85
|
+
end
|
|
86
|
+
end
|
|
87
|
+
|
|
88
|
+
def test_invalid_inputs_do_not_send_requests
|
|
89
|
+
[nil, "missing.wav", @dir].each do |path|
|
|
90
|
+
assert_equal "unknown", @client.transcribe(path)["status"]
|
|
91
|
+
end
|
|
92
|
+
[ { options: nil }, { options: { stream: true } }, { options: { background: true } },
|
|
93
|
+
{ mime_type: "audio/unknown" } ].each do |args|
|
|
94
|
+
refute_nil @client.transcribe(@path, **args)["error"]
|
|
95
|
+
end
|
|
96
|
+
File.binwrite(@path, "")
|
|
97
|
+
assert_match(/empty/, @client.transcribe(@path)["error"])
|
|
98
|
+
File.open(@path, "wb") { |file| file.truncate(15_000_001) }
|
|
99
|
+
assert_match(/under 20 MB/, @client.transcribe(@path)["error"])
|
|
100
|
+
File.binwrite(@path, "small")
|
|
101
|
+
assert_match(/under 20 MB/, @client.transcribe(@path, options: { extra: "x" * 20_000_000 })["error"])
|
|
102
|
+
end
|
|
103
|
+
|
|
104
|
+
def test_errors_and_malformed_responses
|
|
105
|
+
[ [403, { "error" => { "message" => "Denied" } }], [200, { "error" => "Oops" }],
|
|
106
|
+
[200, []], [200, "invalid json"], [200, body.merge("status" => "failed")],
|
|
107
|
+
[200, body.merge("status" => "in_progress")], [200, body.merge("steps" => [])],
|
|
108
|
+
[200, body.merge("steps" => nil)], [200, IOError.new("Disconnected")] ].each do |code, raw|
|
|
109
|
+
with_response(raw, code.to_s) do
|
|
110
|
+
result = @client.transcribe(@path, debug: true)
|
|
111
|
+
assert_nil result["content"]
|
|
112
|
+
refute_nil result["error"]
|
|
113
|
+
end
|
|
114
|
+
end
|
|
115
|
+
end
|
|
116
|
+
|
|
117
|
+
def test_empty_transcript_and_multiple_text_parts
|
|
118
|
+
with_response(body("")) { assert_equal "", @client.transcribe(@path)["content"] }
|
|
119
|
+
raw = body("Hello ")
|
|
120
|
+
raw["steps"].last["content"] << { "type" => "text", "text" => "world." }
|
|
121
|
+
with_response(raw) { assert_equal "Hello world.", @client.transcribe(@path)["content"] }
|
|
122
|
+
end
|
|
123
|
+
end
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
require_relative "test_helper"
|
|
2
|
+
require "tmpdir"
|
|
3
|
+
require "fileutils"
|
|
4
|
+
require "open3"
|
|
5
|
+
require "rbconfig"
|
|
6
|
+
|
|
7
|
+
class PackageTest < Minitest::Test
|
|
8
|
+
def test_built_gem_loads_without_runtime_dependencies
|
|
9
|
+
root = File.expand_path("..", __dir__)
|
|
10
|
+
spec = Gem::Specification.load(File.join(root, "ai-lite.gemspec"))
|
|
11
|
+
assert_empty spec.runtime_dependencies
|
|
12
|
+
|
|
13
|
+
Dir.mktmpdir("ai-lite-package") do |dir|
|
|
14
|
+
source = File.join(dir, "source")
|
|
15
|
+
installed = File.join(dir, "installed")
|
|
16
|
+
FileUtils.mkdir_p(source)
|
|
17
|
+
(spec.files + ["ai-lite.gemspec"]).each do |file|
|
|
18
|
+
destination = File.join(source, file)
|
|
19
|
+
FileUtils.mkdir_p(File.dirname(destination))
|
|
20
|
+
FileUtils.cp(File.join(root, file), destination)
|
|
21
|
+
end
|
|
22
|
+
output, status = Open3.capture2e(RbConfig.ruby, "-rrubygems/gem_runner", "-e", "Gem::GemRunner.new.run(ARGV)", "--", "build", "ai-lite.gemspec", chdir: source)
|
|
23
|
+
assert status.success?, output
|
|
24
|
+
package = File.join(source, "ai-lite-#{spec.version}.gem")
|
|
25
|
+
output, status = Open3.capture2e(RbConfig.ruby, "-rrubygems/gem_runner", "-e", "Gem::GemRunner.new.run(ARGV)", "--", "install", package,
|
|
26
|
+
"--local", "--install-dir", installed, "--no-document", "--ignore-dependencies")
|
|
27
|
+
assert status.success?, output
|
|
28
|
+
|
|
29
|
+
%w[ai_lite ai_lite/openai ai_lite/gemini ai_lite/claude].each do |entry|
|
|
30
|
+
output, status = Open3.capture2e(
|
|
31
|
+
{ "GEM_HOME" => installed, "GEM_PATH" => installed, "RUBYLIB" => nil, "RUBYOPT" => nil },
|
|
32
|
+
RbConfig.ruby, "-e", <<~'RUBY', entry, installed, chdir: dir
|
|
33
|
+
require ARGV.fetch(0)
|
|
34
|
+
spec = Gem.loaded_specs.fetch("ai-lite")
|
|
35
|
+
abort "Loaded outside isolated installation" unless File.realpath(spec.full_gem_path).start_with?(File.realpath(ARGV.fetch(1)) + "/")
|
|
36
|
+
abort "Unexpected runtime dependencies" unless spec.runtime_dependencies.empty?
|
|
37
|
+
[:OpenAI, :Gemini, :Claude].each do |name|
|
|
38
|
+
next unless AiLite.const_defined?(name, false)
|
|
39
|
+
client = AiLite.const_get(name).new(api_key: "package-test-key")
|
|
40
|
+
methods = name == :Claude ? [:chat] : [:chat, :chat_stream, :embed, :image, :speak, :transcribe, :count_tokens, :configured_models]
|
|
41
|
+
methods.each do |method|
|
|
42
|
+
abort "Missing #{name}.#{method}" unless client.respond_to?(method)
|
|
43
|
+
end
|
|
44
|
+
abort "Missing chat model" unless client.model
|
|
45
|
+
end
|
|
46
|
+
RUBY
|
|
47
|
+
)
|
|
48
|
+
assert status.success?, "#{entry}: #{output}"
|
|
49
|
+
end
|
|
50
|
+
end
|
|
51
|
+
end
|
|
52
|
+
end
|
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
require_relative "test_helper"
|
|
2
|
+
|
|
3
|
+
class TokenCountingTest < Minitest::Test
|
|
4
|
+
Response = Struct.new(:code, :body)
|
|
5
|
+
class Http
|
|
6
|
+
attr_accessor :open_timeout, :read_timeout
|
|
7
|
+
attr_reader :request_received
|
|
8
|
+
def initialize(response)
|
|
9
|
+
@response = response
|
|
10
|
+
end
|
|
11
|
+
def request(request)
|
|
12
|
+
@request_received = request
|
|
13
|
+
raise @response if @response.is_a?(Exception)
|
|
14
|
+
@response
|
|
15
|
+
end
|
|
16
|
+
end
|
|
17
|
+
|
|
18
|
+
def setup
|
|
19
|
+
[AiLite::OpenAI, AiLite::Gemini].each(&:reset_configuration!)
|
|
20
|
+
end
|
|
21
|
+
|
|
22
|
+
def teardown
|
|
23
|
+
[AiLite::OpenAI, AiLite::Gemini].each(&:reset_configuration!)
|
|
24
|
+
end
|
|
25
|
+
|
|
26
|
+
def providers
|
|
27
|
+
[[AiLite::OpenAI, "input_tokens", "api.openai.com", "/v1/responses/input_tokens"],
|
|
28
|
+
[AiLite::Gemini, "totalTokens", "generativelanguage.googleapis.com", "/v1beta/models/chosen:countTokens"]]
|
|
29
|
+
end
|
|
30
|
+
|
|
31
|
+
def with_http(raw, code = "200")
|
|
32
|
+
http = Http.new(raw.is_a?(Exception) ? raw : Response.new(code, raw.is_a?(String) ? raw : JSON.generate(raw)))
|
|
33
|
+
original = Net::HTTP.method(:start)
|
|
34
|
+
test = self
|
|
35
|
+
Net::HTTP.define_singleton_method(:start) do |host, port, use_ssl:, &block|
|
|
36
|
+
test.instance_variable_set(:@host, host)
|
|
37
|
+
test.assert_equal 443, port
|
|
38
|
+
test.assert use_ssl
|
|
39
|
+
block.call(http)
|
|
40
|
+
end
|
|
41
|
+
yield http
|
|
42
|
+
ensure
|
|
43
|
+
Net::HTTP.define_singleton_method(:start, original)
|
|
44
|
+
end
|
|
45
|
+
|
|
46
|
+
def test_default_transport_and_standard_envelope
|
|
47
|
+
providers.each do |provider, field, host, path|
|
|
48
|
+
client = provider.new(api_key: "provider-key", model: "chosen", timeout: 7, max_output_tokens: 99)
|
|
49
|
+
with_http({ field => 12 }) do |http|
|
|
50
|
+
assert_equal({ "content" => 12, "error" => nil, "response_id" => nil, "raw" => nil, "status" => 200 }, client.count_tokens("Hello"))
|
|
51
|
+
assert_equal host, @host
|
|
52
|
+
assert_instance_of Net::HTTP::Post, http.request_received
|
|
53
|
+
assert_equal path, http.request_received.path
|
|
54
|
+
assert_equal "application/json", http.request_received["Content-Type"]
|
|
55
|
+
assert_equal 7, http.open_timeout
|
|
56
|
+
assert_equal 7, http.read_timeout
|
|
57
|
+
payload = JSON.parse(http.request_received.body)
|
|
58
|
+
if provider == AiLite::OpenAI
|
|
59
|
+
assert_equal "Bearer provider-key", http.request_received["Authorization"]
|
|
60
|
+
assert_nil http.request_received["x-goog-api-key"]
|
|
61
|
+
assert_equal({ "model" => "chosen", "input" => "Hello" }, payload)
|
|
62
|
+
else
|
|
63
|
+
assert_equal "provider-key", http.request_received["x-goog-api-key"]
|
|
64
|
+
assert_nil http.request_received["Authorization"]
|
|
65
|
+
assert_equal({ "contents" => [{ "parts" => [{ "text" => "Hello" }] }] }, payload)
|
|
66
|
+
end
|
|
67
|
+
end
|
|
68
|
+
end
|
|
69
|
+
end
|
|
70
|
+
|
|
71
|
+
def test_zero_debug_and_class_configuration
|
|
72
|
+
providers.each do |provider, field, _, _|
|
|
73
|
+
provider.configure { |c| c.api_key = "key"; c.model = "configured" }
|
|
74
|
+
assert_equal "configured", provider.client.model
|
|
75
|
+
with_http({ field => 0, "details" => { "cached" => 0 } }) do |http|
|
|
76
|
+
result = provider.count_tokens("", debug: true, model: "override")
|
|
77
|
+
assert_equal 0, result["content"]
|
|
78
|
+
assert_nil result["error"]
|
|
79
|
+
assert_equal({ field => 0, "details" => { "cached" => 0 } }, result["raw"])
|
|
80
|
+
if provider == AiLite::OpenAI
|
|
81
|
+
assert_equal "override", JSON.parse(http.request_received.body)["model"]
|
|
82
|
+
else
|
|
83
|
+
assert_equal "/v1beta/models/override:countTokens", http.request_received.path
|
|
84
|
+
end
|
|
85
|
+
end
|
|
86
|
+
end
|
|
87
|
+
assert_equal "configured", AiLite::OpenAI.configuration.model
|
|
88
|
+
end
|
|
89
|
+
|
|
90
|
+
def test_openai_history_media_instructions_and_native_options
|
|
91
|
+
input = [{ role: "user", content: [{ type: "input_text", text: "Describe" },
|
|
92
|
+
{ type: "input_image", image_url: "https://example.com/a.png" }] }]
|
|
93
|
+
options = { "model" => "ignored", input: "ignored", instructions: "ignored",
|
|
94
|
+
previous_response_id: "ignored", tools: [{ type: "function", name: "lookup", parameters: {} }] }
|
|
95
|
+
original = Marshal.dump([input, options])
|
|
96
|
+
with_http({ "input_tokens" => 100 }) do |http|
|
|
97
|
+
result = AiLite::OpenAI.new(api_key: "key").count_tokens(input, model: "selected", instructions: "Be concise",
|
|
98
|
+
previous_response_id: "resp_123", options: options)
|
|
99
|
+
assert_nil result["error"]
|
|
100
|
+
payload = JSON.parse(http.request_received.body)
|
|
101
|
+
assert_equal "selected", payload["model"]
|
|
102
|
+
assert_equal JSON.parse(JSON.generate(input)), payload["input"]
|
|
103
|
+
assert_equal "Be concise", payload["instructions"]
|
|
104
|
+
assert_equal "resp_123", payload["previous_response_id"]
|
|
105
|
+
assert_equal "lookup", payload.dig("tools", 0, "name")
|
|
106
|
+
end
|
|
107
|
+
assert_equal original, Marshal.dump([input, options])
|
|
108
|
+
end
|
|
109
|
+
|
|
110
|
+
def test_gemini_history_media_and_nested_native_options
|
|
111
|
+
input = [{ role: "user", parts: [{ text: "Hello" }] }, { role: "model", parts: [{ text: "Hi" }] },
|
|
112
|
+
{ role: "user", parts: [{ inlineData: { mimeType: "image/png", data: "AAAA" } }] }]
|
|
113
|
+
options = { contents: "ignored", generateContentRequest: { model: "ignored", contents: [],
|
|
114
|
+
systemInstruction: { parts: [{ text: "ignored" }] }, tools: [{ functionDeclarations: [{ name: "lookup" }] }] } }
|
|
115
|
+
original = Marshal.dump([input, options])
|
|
116
|
+
with_http({ "totalTokens" => 100 }) do |http|
|
|
117
|
+
result = AiLite::Gemini.new(api_key: "key").count_tokens(input, model: "models/selected", instructions: "Be concise", options: options)
|
|
118
|
+
assert_nil result["error"]
|
|
119
|
+
assert_equal "/v1beta/models/selected:countTokens", http.request_received.path
|
|
120
|
+
payload = JSON.parse(http.request_received.body)
|
|
121
|
+
refute payload.key?("contents")
|
|
122
|
+
assert_equal "models/selected", payload.dig("generateContentRequest", "model")
|
|
123
|
+
assert_equal JSON.parse(JSON.generate(input)), payload.dig("generateContentRequest", "contents")
|
|
124
|
+
assert_equal "Be concise", payload.dig("generateContentRequest", "systemInstruction", "parts", 0, "text")
|
|
125
|
+
assert_equal "lookup", payload.dig("generateContentRequest", "tools", 0, "functionDeclarations", 0, "name")
|
|
126
|
+
end
|
|
127
|
+
assert_equal original, Marshal.dump([input, options])
|
|
128
|
+
with_http({ "totalTokens" => 5 }) do |http|
|
|
129
|
+
AiLite::Gemini.new(api_key: "key").count_tokens({ parts: [{ text: "Hi" }] }, instructions: "Be brief")
|
|
130
|
+
assert_equal "Hi", JSON.parse(http.request_received.body).dig("generateContentRequest", "contents", 0, "parts", 0, "text")
|
|
131
|
+
end
|
|
132
|
+
end
|
|
133
|
+
|
|
134
|
+
def test_api_errors_invalid_counts_and_raw_visibility
|
|
135
|
+
providers.each do |provider, field, _, _|
|
|
136
|
+
client = provider.new(api_key: "key")
|
|
137
|
+
[ ["429", { "error" => { "message" => "Rate limited" } }], ["200", { "error" => "Failed" }],
|
|
138
|
+
["200", []], ["200", "not json"], ["200", {}], ["200", { field => -1 }],
|
|
139
|
+
["200", { field => 1.5 }], ["200", { field => "12" }], ["200", { field => nil }],
|
|
140
|
+
["200", IOError.new("Disconnected")] ].each do |code, raw|
|
|
141
|
+
with_http(raw, code) do
|
|
142
|
+
result = client.count_tokens("Hello", debug: true)
|
|
143
|
+
assert_nil result["content"]
|
|
144
|
+
refute_nil result["error"]
|
|
145
|
+
assert_equal(raw.is_a?(Exception) ? "unknown" : code.to_i, result["status"])
|
|
146
|
+
assert_equal raw, result["raw"] unless raw.is_a?(Exception)
|
|
147
|
+
end
|
|
148
|
+
end
|
|
149
|
+
with_http({ "error" => { "message" => "Denied" } }, "403") do
|
|
150
|
+
result = client.count_tokens("Hello")
|
|
151
|
+
assert_equal "Denied", result["error"]
|
|
152
|
+
assert_nil result["raw"]
|
|
153
|
+
end
|
|
154
|
+
end
|
|
155
|
+
end
|
|
156
|
+
|
|
157
|
+
def test_invalid_inputs_never_make_a_request
|
|
158
|
+
with_http(RuntimeError.new("Unexpected network call")) do |http|
|
|
159
|
+
providers.each do |provider, _, _, _|
|
|
160
|
+
client = provider.new(api_key: "key")
|
|
161
|
+
[nil, 12, ["text"]].each { |input| refute_nil client.count_tokens(input)["error"] }
|
|
162
|
+
refute_nil client.count_tokens("Hello", options: nil)["error"]
|
|
163
|
+
refute_nil client.count_tokens("Hello", instructions: 1)["error"]
|
|
164
|
+
end
|
|
165
|
+
gemini = AiLite::Gemini.new(api_key: "key")
|
|
166
|
+
["../bad", "name?key=x", "", 12].each { |model| refute_nil gemini.count_tokens("Hi", model: model)["error"] }
|
|
167
|
+
refute_nil gemini.count_tokens({ type: "text", text: "Interactions format" })["error"]
|
|
168
|
+
refute_nil gemini.count_tokens("Hi", options: { generateContentRequest: nil })["error"]
|
|
169
|
+
refute_nil gemini.count_tokens("Hi", options: { previous_interaction_id: "id" })["error"]
|
|
170
|
+
assert_nil http.request_received
|
|
171
|
+
end
|
|
172
|
+
end
|
|
173
|
+
end
|