ai-lite 1.1.0 → 1.2.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 CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: a6b2ed589de27af46e6ce7babfb4a1ec32808ecfae567f29ed8db35bfd129f26
4
- data.tar.gz: ddee8996d702a77709b30bd9bb360994abfbc3e4875386db04b99241541a413d
3
+ metadata.gz: c1427bc74d68c52cb7cdd5cf8ecc62ea185c0f2322d7829f054d9a8977f3491f
4
+ data.tar.gz: 7048de5a911123687ba4e3e85c0bcf5aa7e7e5b3265ec864a3381b337bafba13
5
5
  SHA512:
6
- metadata.gz: 9591556daadccbb5107f8b52f6d5ca825232003336a87db144e41971ec9921282a38ea884928d0d1f5ee8ea4d84fb8b67698ddcfb1894f678ab2bc615a9dcdb8
7
- data.tar.gz: 24aa31e8ddaa48bf6876bc7e4375c212d46994d37709a32bb52c797b3618f0dc770fe831919039781c2f9529b40ff0c85b12c04dea4a7894c61fa4e8515fa282
6
+ metadata.gz: 4455d3fdf5ba4dfea65c864a67ccd1f55043c94984848e9d9241c04b835b3596dd4f0dca7a252e307c9b56355c039265be7e401ee308ca5972a927ad895347d5
7
+ data.tar.gz: 58a3b7c8fb9b87913b2bad8671ebbd1a6474f7d51d9f3491c180c34a489f582b954ac966507e2e624c5c0af3ae6353d751b37a0182655c26e95457ffb872c610
data/CHANGELOG.md CHANGED
@@ -1,14 +1,30 @@
1
1
  # Changelog
2
2
 
3
- ## Unreleased
3
+ ## 1.2.0 (2026-11-02)
4
+
5
+ - Add `tools:` and `tool_results:` to OpenAI and Gemini chat and streaming,
6
+ normalized function calls, and manual tool-result continuation. Gemini
7
+ interactions awaiting valid function results are no longer reported as errors.
8
+
9
+ - Add `count_tokens` for OpenAI and Gemini using provider counting APIs, with
10
+ integer results, instructions, native inputs/options, and no tokenizer dependency.
11
+ - Add Gemini `transcribe` for local audio files using `gemini-3.5-transcribe`,
12
+ with inline size validation, native options, configuration, and model checks.
13
+ - Add Gemini single-speaker speech with voice/style controls, WAV and raw audio
14
+ formats, binary/base64/file output, speech configuration, and model checks.
15
+ - Preserve dependency-free loading on newer Ruby versions by using built-in
16
+ base64 packing/unpacking instead of requiring the separately packaged library.
17
+ - Expand Ruby compatibility CI to Ruby 2.6, 2.7, 3.0, 3.1, 3.2, 3.3, 3.4, and
18
+ 4.0, and test isolated gem installation/loading.
19
+
20
+ ## 1.1.0
4
21
 
5
22
  - Add Gemini image generation with base64 results, optional file output, native
6
23
  options, image model configuration, and model checks.
7
-
8
24
  - Add Gemini text embeddings for single and multiple inputs, with dimensions,
9
25
  embedding model configuration, model checks, and the standard result envelope.
10
26
 
11
- ## 1.0.0 (unreleased)
27
+ ## 1.0.0
12
28
 
13
29
  - Introduce independent `AiLite::OpenAI` and `AiLite::Gemini` providers.
14
30
  - Preserve documented legacy OpenAI entry points through `AiLite`, with deprecation
@@ -21,6 +37,3 @@
21
37
  - Document model-list limitations, provider-specific debug output, and migration.
22
38
  - Treat failed/incomplete OpenAI generations as errors even when HTTP status is 200.
23
39
  - Handle fragmented UTF-8 and mixed SSE line endings in both stream parsers.
24
-
25
- Gemini image generation, speech, file transcription, additional
26
- providers, and async convenience methods are deferred beyond v1.
data/README.md CHANGED
@@ -1,7 +1,7 @@
1
1
  # AI Lite
2
2
 
3
3
  AI Lite is a lightweight, pure Ruby client for OpenAI and Gemini. Both providers
4
- support chat, streaming, embeddings, image generation, and model availability
4
+ support chat, streaming, embeddings, image generation, speech, transcription, token counting, and model availability
5
5
  checks through simple interfaces and a consistent result format.
6
6
 
7
7
  It is built for Rails apps and plain Ruby projects that need AI features with
@@ -13,7 +13,7 @@ This gem is intentionally small:
13
13
  - No Rails dependency
14
14
  - No provider SDK dependency
15
15
  - No Faraday, HTTParty, ActiveSupport, or connection pool dependency
16
- - Uses only Ruby stdlib: `Net::HTTP`, `URI`, `JSON`, `Base64`, and `SecureRandom`
16
+ - Uses only Ruby stdlib: `Net::HTTP`, `URI`, `JSON`, and `SecureRandom`
17
17
 
18
18
  Choose a provider and call the methods your app needs:
19
19
 
@@ -34,24 +34,193 @@ gemini.image("A simple app icon")
34
34
  ```
35
35
 
36
36
  Each provider has independent configuration and native API options. OpenAI also
37
- supports moderation, speech, and file transcription; Gemini supports structured
37
+ supports moderation; Gemini supports structured
38
38
  media input and a YouTube helper. The table below lists the available methods.
39
39
 
40
40
  ## Provider support
41
41
 
42
42
  | Method | OpenAI | Gemini |
43
43
  | --- | --- | --- |
44
- | `chat`, `chat_stream` | Yes | Yes |
44
+ | `chat`, `chat_stream`, `count_tokens` | Yes | Yes |
45
45
  | Four model helpers | Yes | Yes |
46
46
  | `youtube` | No | Yes |
47
- | `embed`, `image` | Yes | Yes |
48
- | `moderate`, `speak`, `transcribe` | Yes | Not implemented |
47
+ | `embed`, `image`, `speak`, `transcribe` | Yes | Yes |
48
+ | `moderate` | Yes | Not implemented |
49
49
 
50
50
  Unsupported provider methods are absent and raise Ruby's `NoMethodError` if called.
51
51
  Configure providers during application startup; do not mutate shared configuration
52
52
  or client headers while requests are running. The gem does not provide automatic
53
53
  retries, worker threads, or a background-job queue.
54
54
 
55
+ ## Function calling (OpenAI and Gemini)
56
+
57
+ Pass native tool definitions through `tools:` on `chat` or `chat_stream`.
58
+ Both providers accept the basic function definition below. Provider-specific
59
+ fields and built-in tools retain their native formats; `options:` remains the
60
+ escape hatch for settings such as tool choice.
61
+
62
+ ```ruby
63
+ ai = AiLite::Gemini.new # Or AiLite::OpenAI.new
64
+
65
+ tools = [{
66
+ type: "function",
67
+ name: "lookup_order",
68
+ description: "Look up an order's shipping status",
69
+ parameters: {
70
+ type: "object",
71
+ properties: { order_id: { type: "integer" } },
72
+ required: ["order_id"],
73
+ additionalProperties: false
74
+ }
75
+ }]
76
+
77
+ result = ai.chat("Where is order 123?", tools: tools)
78
+ raise result["error"] if result["error"]
79
+
80
+ # When a function is requested:
81
+ # result["tool_calls"] => [
82
+ # { "id" => "call_123", "name" => "lookup_order",
83
+ # "arguments" => { "order_id" => 123 } }
84
+ # ]
85
+ ```
86
+
87
+ A tool request is a successful chat result. `content` may be nil or contain text
88
+ alongside tool calls. The `tool_calls` key appears only when complete function
89
+ calls are present; existing text-only envelopes are unchanged. OpenAI call IDs
90
+ come from `call_id`, not the output item's `id`. Gemini IDs come from the
91
+ function-call step's `id`. Arguments are decoded into hashes without requiring
92
+ `debug: true`. Failed/incomplete responses do not expose executable tool calls.
93
+
94
+ Your application validates arguments, authorizes access, and executes only
95
+ functions it explicitly allows. For example, in a Rails controller:
96
+
97
+ ```ruby
98
+ calls = result.fetch("tool_calls", [])
99
+ unless calls.empty?
100
+ outputs = calls.map do |call|
101
+ raise "Unsupported tool" unless call["name"] == "lookup_order"
102
+ order_id = call["arguments"].fetch("order_id")
103
+ raise "Invalid order ID" unless order_id.is_a?(Integer)
104
+
105
+ order = current_user.orders.find(order_id)
106
+ { id: call["id"], name: call["name"], output: { status: order.status } }
107
+ end
108
+
109
+ result = ai.chat(
110
+ nil,
111
+ previous_response_id: result["response_id"],
112
+ tools: tools,
113
+ tool_results: outputs
114
+ )
115
+ raise result["error"] if result["error"]
116
+ end
117
+
118
+ puts result["content"]
119
+ # The model may request more tools; your app decides whether to continue.
120
+ ```
121
+
122
+ `tool_results:` takes a nonempty array of `{ id:, name:, output: }` hashes,
123
+ requires `previous_response_id:`, and uses `nil` as the positional message.
124
+ Strings are sent as text; other JSON-compatible outputs are JSON-encoded.
125
+ The helper translates results into OpenAI `function_call_output` items or
126
+ Gemini `function_result` steps. Return a result for every requested call and
127
+ reuse the same provider/model and tool definitions. IDs refer to stored provider
128
+ state; when using stateless requests, pass native history/results as the
129
+ positional input instead. Preserve all provider-required history, including
130
+ reasoning/thought items and signatures; normalized `tool_calls` alone are not
131
+ full conversation history. Use non-streaming `chat` with `debug: true` for the full native response;
132
+ streaming debug output may contain partial metadata plus events.
133
+
134
+ `chat_stream` accepts the same tool keywords. Its block still receives text
135
+ only; complete tool calls are returned in the final envelope after streaming.
136
+ Do not execute streamed argument fragments. Class-level calls work too:
137
+ `AiLite::OpenAI.chat(...)` and `AiLite::Gemini.chat(...)`.
138
+
139
+ Explicit `tools:` overrides `options[:tools]`, including `tools: []` to clear
140
+ it. AI Lite does not execute functions, dispatch method names, retry tool calls,
141
+ or run an automatic agent loop. Built-in provider tools are passed through;
142
+ only custom `function_call` outputs are normalized into `tool_calls`.
143
+
144
+ See the [OpenAI function-calling guide](https://developers.openai.com/api/docs/guides/function-calling)
145
+ and [Gemini function-calling guide](https://ai.google.dev/gemini-api/docs/function-calling)
146
+ for native schemas and continuation requirements.
147
+
148
+ ## Token counting (both providers)
149
+
150
+ ```ruby
151
+ openai = AiLite::OpenAI.new
152
+ gemini = AiLite::Gemini.new
153
+
154
+ result = openai.count_tokens("Hello from AI Lite.")
155
+ result["content"] # Integer input-token count when error is nil
156
+ result["error"] # nil on success
157
+
158
+ gemini.count_tokens("Hello from AI Lite.", instructions: "Be concise.")
159
+
160
+ # Class-level methods use each provider's independent configuration:
161
+ AiLite::OpenAI.count_tokens("Hello")
162
+ AiLite::Gemini.count_tokens("Hello")
163
+ ```
164
+
165
+ These are authenticated HTTP calls, not offline tokenizers. They count input
166
+ only, without generating an answer or predicting output tokens or a final bill.
167
+ Counts depend on the model and the supplied context. Both use the configured
168
+ chat `model` by default; pass `model:` to override it. No tokenizer gem is needed.
169
+ The standard envelope contains an integer `content`, a nil `response_id`, and
170
+ `raw` only with `debug: true`. Check `error` before using the count; zero is a
171
+ valid count, and failures return nil content. Chat output-token defaults are
172
+ not added to counting requests.
173
+
174
+ OpenAI uses `POST /v1/responses/input_tokens`. Pass a string or an array of native
175
+ Responses input items, including supported media and conversation history:
176
+
177
+ ```ruby
178
+ openai.count_tokens(
179
+ [
180
+ { role: "user", content: "Hello" },
181
+ { role: "assistant", content: "Hi!" },
182
+ { role: "user", content: "Tell me more." }
183
+ ],
184
+ instructions: "Be concise."
185
+ )
186
+ # Count a continuation using a response ID from an earlier chat:
187
+ openai.count_tokens("Tell me more.", previous_response_id: previous_result["response_id"])
188
+ ```
189
+
190
+ Gemini uses `POST /v1beta/models/{model}:countTokens`. Its structured inputs use
191
+ **Content objects with `parts`, not the Interactions objects accepted by `chat`**:
192
+
193
+ ```ruby
194
+ gemini.count_tokens(
195
+ [
196
+ { role: "user", parts: [{ text: "Hello" }] },
197
+ { role: "model", parts: [{ text: "Hi!" }] },
198
+ { role: "user", parts: [{ text: "Tell me more." }] }
199
+ ],
200
+ instructions: "Be concise."
201
+ )
202
+ ```
203
+
204
+ A single Gemini Content hash is also accepted. Media uses native `inlineData`
205
+ or `fileData` parts; the helper does not read or upload local files. Supply
206
+ conversation history explicitly: Gemini counting does not resolve
207
+ `previous_response_id` or `previous_interaction_id`. Preflight counts can differ
208
+ from a later generation's reported usage.
209
+
210
+ `options:` passes native counting API fields. OpenAI tool definitions go in
211
+ `options: { tools: [...] }`; Gemini tool definitions go in
212
+ `options: { generateContentRequest: { tools: [...] } }`. Gemini `instructions:`
213
+ builds `generateContentRequest.systemInstruction`. The helper owns the model
214
+ and input/contents fields; explicit keywords take precedence over matching
215
+ options without mutating the caller's hashes. Native fields keep each API's
216
+ spelling. Use the counting endpoint's options rather than copying every chat
217
+ option. New methods are exposed on the provider classes; there is no legacy
218
+ `AiLite.count_tokens` class shortcut.
219
+
220
+ See [OpenAI's counting guide](https://developers.openai.com/api/docs/guides/token-counting)
221
+ and [Gemini's counting API reference](https://ai.google.dev/api/tokens) for supported
222
+ inputs and native parameters.
223
+
55
224
  ## Gemini
56
225
 
57
226
  ```ruby
@@ -73,6 +242,9 @@ AiLite::Gemini.configure do |config|
73
242
  config.model = "gemini-3.8-flash"
74
243
  config.embedding_model = "gemini-embedding-001"
75
244
  config.image_model = "gemini-nano-banana-2.1"
245
+ config.speech_model = "gemini-3.8-flash-tts"
246
+ config.speech_voice = "Kore"
247
+ config.transcription_model = "gemini-3.5-transcribe"
76
248
  config.timeout = 120
77
249
  config.max_output_tokens = 2000
78
250
  end
@@ -104,8 +276,8 @@ OpenAI-style role/message arrays are not automatically translated.
104
276
  Multi-turn continuation uses the familiar keyword:
105
277
 
106
278
  ```ruby
107
- first = gemini.chat("My name is William.")
108
- second = gemini.chat("What is my name?", previous_response_id: first["response_id"])
279
+ first = gemini.chat("My favorite color is blue.")
280
+ second = gemini.chat("What is my favorite color?", previous_response_id: first["response_id"])
109
281
  ```
110
282
 
111
283
  `instructions:` maps to `system_instruction`; `previous_response_id:` maps to
@@ -127,12 +299,12 @@ and [API reference](https://ai.google.dev/api/interactions-api).
127
299
  Results use the standard `content`, `response_id`, `status`, `error`, and `raw`
128
300
  keys. Text is extracted only from `model_output` steps; JSON-looking text is
129
301
  parsed. `debug: true` retains the complete response, including non-text output,
130
- tool calls, and usage. Non-completed interactions (including `requires_action`)
131
- return an error rather than pretending the answer is complete; no tools are
302
+ tool calls, and usage. `requires_action` with valid function calls returns
303
+ `tool_calls` without an error. Other non-completed interactions return an error; no tools are
132
304
  executed automatically. Input/API/transport errors return an error envelope;
133
305
  constructing a client without a key raises `ArgumentError`.
134
306
 
135
- Gemini speech and file transcription methods are not implemented yet. Use `chat_stream` for streaming; `chat` rejects
307
+ Use `chat_stream` for streaming; `chat` rejects
136
308
  `stream: true`. Both methods reject `background: true` before sending a request.
137
309
  Legacy `AiLite` entry points still use OpenAI.
138
310
 
@@ -198,6 +370,97 @@ Streaming and background execution are rejected. Failed/incomplete interactions,
198
370
  missing or invalid image data, and file-write errors return error envelopes.
199
371
  See Google's [image generation guide](https://ai.google.dev/gemini-api/docs/image-generation).
200
372
 
373
+ ### Gemini speech
374
+
375
+ ```ruby
376
+ gemini = AiLite::Gemini.new
377
+ result = gemini.speak("Hello from AI Lite.", output_path: "tmp/hello.wav")
378
+ result["content"] # { "path" => "tmp/hello.wav", "bytes" => ..., "format" => "wav" }
379
+
380
+ AiLite::Gemini.speak("Have a wonderful day!", voice: "Puck",
381
+ instructions: "Speak warmly and calmly", base64: true)
382
+ ```
383
+
384
+ `speak` returns binary audio by default. With `output_path:`, it saves the audio
385
+ and returns path, byte count, and format. With `base64: true`, `content` is base64
386
+ instead; a supplied output path is still written. Parent directories must exist.
387
+
388
+ The defaults are `gemini-3.8-flash-tts`, voice `Kore`, and WAV output.
389
+ Configure `speech_model` and `speech_voice` globally or in the constructor;
390
+ `model:` and `voice:` override them per call. Model checks include the speech model.
391
+ `instructions:` supplies speaking style through speech metadata.
392
+
393
+ `response_format:` accepts `"wav"`, `"pcm"`, `"mulaw"`, or `"alaw"`.
394
+ This helper saves decoded provider bytes without transcoding; a filename extension
395
+ does not change the encoding. It does not support OpenAI's `speed:` or MP3 output.
396
+ See Google's [speech guide](https://ai.google.dev/gemini-api/docs/speech-generation)
397
+ for model-specific voices and formats.
398
+
399
+ Native options remain available, for example:
400
+
401
+ ```ruby
402
+ gemini.speak("Hello", response_format: "pcm", options: {
403
+ response_format: { sample_rate: 16000 },
404
+ store: false
405
+ })
406
+ ```
407
+
408
+ Explicit input, model, voice, and format take precedence. This single-speaker
409
+ helper owns `generation_config.speech_config`; any supplied speech configuration
410
+ is replaced with the selected voice. Other native generation settings pass through;
411
+ the chat output-token limit is not added. Streaming/background requests are rejected.
412
+
413
+ Only one inline audio block from completed model output is accepted. Missing,
414
+ invalid, unsupported, or multiple audio blocks return errors before writing a file.
415
+ `debug: true` includes the full provider response in `raw`, including audio and usage.
416
+ The standard envelope includes the interaction's `response_id` when available.
417
+
418
+ ### Gemini transcription
419
+
420
+ ```ruby
421
+ result = gemini.transcribe("tmp/gemini-speech-test.wav")
422
+ result["content"] # Transcript as a string
423
+ result["error"] # nil on success
424
+
425
+ # Class-level calls work too:
426
+ AiLite::Gemini.transcribe("tmp/meeting.mp3")
427
+ ```
428
+
429
+ The default model is `gemini-3.5-transcribe`. Set `transcription_model` in
430
+ configuration or the constructor, or override it with `model:` per call.
431
+ The helper reads a local audio file and sends base64 audio to the Interactions
432
+ API. The complete JSON request must be under 20 MB, including base64 overhead
433
+ (roughly 15 MB of audio, less any options). Larger requests return an error;
434
+ this helper does not upload files through the Files API.
435
+
436
+ The filename extension selects the MIME type for WAV, MP3, AIFF, AAC, OGG,
437
+ FLAC, MPEG, M4A, L16/PCM, Opus, ALAW, MULAW, and WebM. Use `mime_type:` when
438
+ needed, including parameters for raw PCM such as `audio/l16;rate=24000`.
439
+ Audio is sent as supplied; the gem does not convert formats.
440
+
441
+ Language detection is automatic. Pass provider-specific settings through `options:`:
442
+
443
+ ```ruby
444
+ result = gemini.transcribe(
445
+ "tmp/meeting.wav",
446
+ options: {
447
+ generation_config: {
448
+ transcription_config: { language_codes: ["en-US"] }
449
+ }
450
+ },
451
+ debug: true
452
+ )
453
+ result["content"] # Plain transcript, even when the spoken text looks like JSON
454
+ result["raw"] # Full provider response, including available annotations
455
+ ```
456
+
457
+ See Google's [transcription guide](https://ai.google.dev/gemini-api/docs/transcribe)
458
+ for vocabulary hints, speaker labels, timestamps, and their compatibility rules.
459
+ Unlike OpenAI's transcription helper, this method does not accept `language:` or
460
+ `prompt:`; use native transcription settings instead. Streaming and background
461
+ transcription are not supported. Failed or incomplete responses return an error
462
+ in the standard envelope.
463
+
201
464
  ### Gemini model checks
202
465
 
203
466
  ```ruby
@@ -206,7 +469,7 @@ result = gemini.available_models
206
469
  puts result["content"] unless result["error"]
207
470
 
208
471
  gemini.model_available?("gemini-3.8-flash") # true / false / nil on lookup failure
209
- gemini.configured_models # Includes chat, embedding, and image models
472
+ gemini.configured_models # Includes chat, embedding, image, speech, and transcription models
210
473
  gemini.check_configured_models # Standard envelope containing a report
211
474
 
212
475
  # All four also work at class level:
@@ -776,7 +1039,7 @@ Use `base64: true` when you want text-safe audio data that can be transported in
776
1039
  ```ruby
777
1040
  result = ai.speak("Hello from AI Lite", base64: true)
778
1041
 
779
- File.binwrite("tmp/hello.mp3", Base64.decode64(result["content"]))
1042
+ File.binwrite("tmp/hello.mp3", result["content"].unpack1("m0"))
780
1043
  ```
781
1044
 
782
1045
  `speak` sends a `POST` request to `/v1/audio/speech` with:
@@ -794,6 +1057,10 @@ The default speech model is `gpt-4o-mini-tts`.
794
1057
  The default speech voice is `alloy`.
795
1058
  The default response format is `mp3`.
796
1059
 
1060
+ For the current list of built-in voices and model-specific voice support, see
1061
+ [OpenAI's text-to-speech guide](https://developers.openai.com/api/docs/guides/text-to-speech).
1062
+ AI Lite does not expose an OpenAI `available_voices` method.
1063
+
797
1064
  Set `voice` per call when you want a different built-in voice:
798
1065
 
799
1066
  ```ruby
@@ -1001,7 +1268,21 @@ result = ai.chat("Say hello", debug: true)
1001
1268
 
1002
1269
  ## Development
1003
1270
 
1004
- Run the test suite:
1271
+ Compatibility CI runs the full suite on Ruby 2.6, 2.7, 3.0, 3.1, 3.2, 3.3,
1272
+ 3.4, and 4.0. Tests include building and installing the gem in isolation and
1273
+ loading both providers without third-party runtime gems. These are Ruby tests;
1274
+ they do not constitute a Rails integration matrix.
1275
+
1276
+ Install the test dependency (not a runtime dependency):
1277
+
1278
+ ```sh
1279
+ # Ruby 2.6–3.4
1280
+ gem install minitest --version 5.15.0 --no-document
1281
+ # Ruby 4.0
1282
+ gem install minitest --version 5.27.0 --no-document
1283
+ ```
1284
+
1285
+ Run the test suite from the repository root:
1005
1286
 
1006
1287
  ```sh
1007
1288
  ruby -Ilib:test test/run.rb
@@ -1,13 +1,13 @@
1
1
  class AiLite
2
2
  class Gemini
3
3
  module Chat
4
- def chat(message, model: nil, instructions: nil, previous_response_id: nil, max_output_tokens: nil, debug: false, options: {})
4
+ def chat(message, model: nil, instructions: nil, previous_response_id: nil, max_output_tokens: nil, tools: nil, tool_results: nil, debug: false, options: {})
5
5
  response = nil
6
6
  raw = nil
7
7
  response_id = nil
8
8
  payload = chat_payload(message, model: model, instructions: instructions,
9
9
  previous_response_id: previous_response_id,
10
- max_output_tokens: max_output_tokens, options: options)
10
+ max_output_tokens: max_output_tokens, options: options, tools: tools, tool_results: tool_results)
11
11
  response = post_interaction(payload)
12
12
  raw = response.body
13
13
  raw = JSON.parse(raw)
@@ -21,7 +21,7 @@ class AiLite
21
21
 
22
22
  error = if raw["error"]
23
23
  error_message(raw)
24
- elsif raw["status"] != "completed"
24
+ elsif raw["status"] != "completed" && !(raw["status"] == "requires_action" && !extract_tool_calls(raw).empty?)
25
25
  "Gemini interaction #{raw['status'] || 'has no status'}; inspect raw with debug: true"
26
26
  end
27
27
  steps = raw["steps"]
@@ -43,16 +43,19 @@ class AiLite
43
43
  text
44
44
  end
45
45
  end
46
- result_envelope(status: response.code.to_i, content: content, error: error,
46
+ result = result_envelope(status: response.code.to_i, content: content, error: error,
47
47
  response_id: response_id, raw: raw, debug: debug)
48
+ attach_tool_calls(result, raw)
48
49
  rescue StandardError => e
49
50
  result_envelope(status: response ? response.code.to_i : "unknown", error: e.message,
50
51
  response_id: response_id, raw: raw, debug: debug)
51
52
  end
52
53
  private
53
54
 
54
- def chat_payload(message, model:, instructions:, previous_response_id:, max_output_tokens:, options:, stream: false)
55
+ def chat_payload(message, model:, instructions:, previous_response_id:, max_output_tokens:, options:, stream: false, tools: nil, tool_results: nil)
55
56
  payload = options.each_with_object({}) { |(key, value), result| result[key.to_s] = value }
57
+ message = tool_result_input(message, tool_results, previous_response_id || payload["previous_interaction_id"])
58
+ apply_chat_tools(payload, tools)
56
59
  if (!stream && payload["stream"]) || payload["background"]
57
60
  raise ArgumentError, "Use chat_stream for streaming; background execution is not supported"
58
61
  end
@@ -4,17 +4,23 @@ class AiLite
4
4
  DEFAULT_MODEL = "gemini-3.8-flash".freeze
5
5
  DEFAULT_EMBEDDING_MODEL = "gemini-embedding-001".freeze
6
6
  DEFAULT_IMAGE_MODEL = "gemini-nano-banana-2.1".freeze
7
+ DEFAULT_SPEECH_MODEL = "gemini-3.8-flash-tts".freeze
8
+ DEFAULT_SPEECH_VOICE = "Kore".freeze
9
+ DEFAULT_TRANSCRIPTION_MODEL = "gemini-3.5-transcribe".freeze
7
10
  DEFAULT_TIMEOUT = 120
8
11
  DEFAULT_MAX_OUTPUT_TOKENS = 2000
9
12
 
10
13
  class Configuration
11
- attr_accessor :api_key, :model, :embedding_model, :image_model, :timeout, :max_output_tokens
14
+ attr_accessor :api_key, :model, :embedding_model, :image_model, :speech_model, :speech_voice, :transcription_model, :timeout, :max_output_tokens
12
15
 
13
16
  def initialize
14
17
  @api_key = nil
15
18
  @model = DEFAULT_MODEL
16
19
  @embedding_model = DEFAULT_EMBEDDING_MODEL
17
20
  @image_model = DEFAULT_IMAGE_MODEL
21
+ @speech_model = DEFAULT_SPEECH_MODEL
22
+ @speech_voice = DEFAULT_SPEECH_VOICE
23
+ @transcription_model = DEFAULT_TRANSCRIPTION_MODEL
18
24
  @timeout = DEFAULT_TIMEOUT
19
25
  @max_output_tokens = DEFAULT_MAX_OUTPUT_TOKENS
20
26
  end
@@ -38,7 +38,7 @@ class AiLite
38
38
  unless content.is_a?(String) && !content.empty?
39
39
  raise "No inline image data returned; inspect raw with debug: true"
40
40
  end
41
- bytes = Base64.strict_decode64(content)
41
+ bytes = content.unpack1("m0")
42
42
  raise "Empty image data returned" if bytes.empty?
43
43
 
44
44
  File.binwrite(output_path, bytes) if output_path
@@ -2,7 +2,7 @@ class AiLite
2
2
  class Gemini
3
3
  module Models
4
4
  def self.snapshot(source)
5
- { "chat" => source.model, "embedding" => source.embedding_model, "image" => source.image_model }.transform_values do |model|
5
+ { "chat" => source.model, "embedding" => source.embedding_model, "image" => source.image_model, "speech" => source.speech_model, "transcription" => source.transcription_model }.transform_values do |model|
6
6
  model.is_a?(String) ? model.dup : model
7
7
  end
8
8
  end
@@ -0,0 +1,108 @@
1
+ class AiLite
2
+ class Gemini
3
+ module Speech
4
+ FORMATS = { "wav" => "audio/wav", "pcm" => "audio/l16",
5
+ "mulaw" => "audio/mulaw", "alaw" => "audio/alaw" }.freeze
6
+
7
+ def speak(text, model: nil, voice: nil, instructions: nil, response_format: nil,
8
+ output_path: nil, base64: false, debug: false, options: {})
9
+ response = nil
10
+ raw = nil
11
+ response_id = nil
12
+ unless text.is_a?(String) && !text.strip.empty?
13
+ raise ArgumentError, "text must be a nonempty string"
14
+ end
15
+ unless instructions.nil? || instructions.is_a?(String)
16
+ raise ArgumentError, "instructions must be a string"
17
+ end
18
+ if response_format && !FORMATS.key?(response_format)
19
+ raise ArgumentError, "response_format must be wav, pcm, mulaw, or alaw"
20
+ end
21
+ selected_voice = voice || speech_voice
22
+ unless selected_voice.is_a?(String) && !selected_voice.strip.empty?
23
+ raise ArgumentError, "voice must be a nonempty string"
24
+ end
25
+ payload = speech_hash(options, "options")
26
+ if payload["stream"] || payload["background"]
27
+ raise ArgumentError, "speak does not support streaming or background execution"
28
+ end
29
+ generation = speech_hash(payload.fetch("generation_config", {}), "generation_config")
30
+ # The helper deliberately owns single-speaker voice selection.
31
+ generation["speech_config"] = [{ "voice" => selected_voice }]
32
+ format = speech_hash(payload.fetch("response_format", {}), "response_format option")
33
+ format["type"] = "audio"
34
+ format["mime_type"] = FORMATS.fetch(response_format) if response_format
35
+ format["mime_type"] ||= FORMATS.fetch("wav")
36
+ unless FORMATS.value?(format["mime_type"])
37
+ raise ArgumentError, "Unsupported speech MIME type"
38
+ end
39
+ part = { "type" => "text", "text" => text }
40
+ part["annotations"] = [{ "type" => "speech_metadata", "style" => instructions }] if instructions
41
+ payload.merge!("model" => model || speech_model,
42
+ "input" => [{ "type" => "user_input", "content" => [part] }],
43
+ "response_format" => format, "generation_config" => generation)
44
+ response = post_interaction(payload)
45
+ raw = response.body
46
+ raw = JSON.parse(raw)
47
+ raise "Invalid Gemini speech response: expected an object" unless raw.is_a?(Hash)
48
+
49
+ response_id = raw["id"]
50
+ if !response.code.to_i.between?(200, 299) || raw["error"]
51
+ return result_envelope(status: response.code.to_i, error: error_message(raw),
52
+ response_id: response_id, raw: raw, debug: debug)
53
+ end
54
+ unless raw["status"] == "completed"
55
+ raise "Gemini interaction #{raw['status'] || 'has no status'}; inspect raw with debug: true"
56
+ end
57
+ raise "Invalid Gemini speech response: expected steps" unless raw["steps"].is_a?(Array)
58
+
59
+ blocks = raw["steps"].flat_map do |step|
60
+ next [] unless step.is_a?(Hash) && step["type"] == "model_output"
61
+
62
+ step["content"].is_a?(Array) ? step["content"] : []
63
+ end.select { |block| block.is_a?(Hash) && block["type"] == "audio" }
64
+ # Joining WAV containers or silently dropping speech would corrupt the result.
65
+ raise "Expected one audio block; inspect raw with debug: true" unless blocks.length == 1
66
+
67
+ block = blocks.first
68
+ encoded = block["data"]
69
+ unless encoded.is_a?(String) && !encoded.empty?
70
+ raise "No inline audio data returned; inspect raw with debug: true"
71
+ end
72
+ mime = block["mime_type"].to_s.split(";").first.to_s.strip.downcase
73
+ actual_format = FORMATS.key(mime)
74
+ raise "Unsupported or missing audio MIME type: #{mime}" unless actual_format
75
+
76
+ audio = encoded.unpack1("m0")
77
+ raise "Empty audio data returned" if audio.empty?
78
+ if actual_format == "wav" && !(audio.bytesize >= 12 && audio.start_with?("RIFF") && audio.byteslice(8, 4) == "WAVE")
79
+ raise "Invalid WAV audio returned"
80
+ end
81
+ File.binwrite(output_path, audio) if output_path
82
+ content = if base64
83
+ [audio].pack("m0")
84
+ elsif output_path
85
+ { "path" => output_path, "bytes" => audio.bytesize, "format" => actual_format }
86
+ else
87
+ audio
88
+ end
89
+ result_envelope(status: response.code.to_i, content: content, response_id: response_id,
90
+ raw: raw, debug: debug)
91
+ rescue StandardError => e
92
+ result_envelope(status: response ? response.code.to_i : "unknown", error: e.message,
93
+ response_id: response_id, raw: raw, debug: debug)
94
+ end
95
+
96
+ private
97
+
98
+ def speech_hash(value, name)
99
+ raise ArgumentError, "#{name} must be a hash" unless value.is_a?(Hash)
100
+
101
+ value.each_with_object({}) { |(key, item), result| result[key.to_s] = item }
102
+ end
103
+ end
104
+
105
+ include Speech
106
+ private_constant :Speech
107
+ end
108
+ end