ai-lite 1.0.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: d320744aa3ea523ee76415327cad74343186881e21e28910b6b13a556d46eef3
4
- data.tar.gz: e93d793fdeeefb1c8a2498906b48826934eee3981cadeb4f7073005e0140bd41
3
+ metadata.gz: c1427bc74d68c52cb7cdd5cf8ecc62ea185c0f2322d7829f054d9a8977f3491f
4
+ data.tar.gz: 7048de5a911123687ba4e3e85c0bcf5aa7e7e5b3265ec864a3381b337bafba13
5
5
  SHA512:
6
- metadata.gz: 4fa921ce3f81bdaed04e0facab46c8efdb863b98299d9452ba9f6bdac90d3a9f302e5850e067529b7d66f9552ff41945bb75f38257d6515ba761673c0d8f71d5
7
- data.tar.gz: 0575ce9fb53e2f419940c08a6626a4d528a5661d7cef2e5cbca7c3b9b22587c0288ea4db37b69d6bf03fd8d470c66de68df6515fb226ceb77483b2beb91a90ab
6
+ metadata.gz: 4455d3fdf5ba4dfea65c864a67ccd1f55043c94984848e9d9241c04b835b3596dd4f0dca7a252e307c9b56355c039265be7e401ee308ca5972a927ad895347d5
7
+ data.tar.gz: 58a3b7c8fb9b87913b2bad8671ebbd1a6474f7d51d9f3491c180c34a489f582b954ac966507e2e624c5c0af3ae6353d751b37a0182655c26e95457ffb872c610
data/CHANGELOG.md CHANGED
@@ -1,6 +1,30 @@
1
1
  # Changelog
2
2
 
3
- ## 1.0.0 (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
21
+
22
+ - Add Gemini image generation with base64 results, optional file output, native
23
+ options, image model configuration, and model checks.
24
+ - Add Gemini text embeddings for single and multiple inputs, with dimensions,
25
+ embedding model configuration, model checks, and the standard result envelope.
26
+
27
+ ## 1.0.0
4
28
 
5
29
  - Introduce independent `AiLite::OpenAI` and `AiLite::Gemini` providers.
6
30
  - Preserve documented legacy OpenAI entry points through `AiLite`, with deprecation
@@ -13,6 +37,3 @@
13
37
  - Document model-list limitations, provider-specific debug output, and migration.
14
38
  - Treat failed/incomplete OpenAI generations as errors even when HTTP status is 200.
15
39
  - Handle fragmented UTF-8 and mixed SSE line endings in both stream parsers.
16
-
17
- Gemini embeddings, image generation, speech, file transcription, additional
18
- providers, and async convenience methods are deferred beyond v1.
data/README.md CHANGED
@@ -1,44 +1,226 @@
1
1
  # AI Lite
2
2
 
3
- AI Lite is a pure Ruby, dependency-light client with separate OpenAI and Gemini providers.
4
- OpenAI supports the full utility methods below; Gemini supports chat and streaming with text and structured media input.
3
+ AI Lite is a lightweight, pure Ruby client for OpenAI and Gemini. Both providers
4
+ support chat, streaming, embeddings, image generation, speech, transcription, token counting, and model availability
5
+ checks through simple interfaces and a consistent result format.
5
6
 
6
- It is built for Rails apps and plain Ruby projects where installing a full OpenAI SDK is too heavy, incompatible, or unnecessary. It is especially useful in legacy Rails apps where Rails, ActiveSupport, Ruby, or HTTP-client dependency constraints make larger client libraries difficult to add.
7
-
8
- Use AI Lite when you want a small OpenAI client that works without tying your app to a specific Rails version or a larger dependency stack.
7
+ It is built for Rails apps and plain Ruby projects that need AI features with
8
+ minimal dependencies. It is especially useful in legacy Rails apps where Ruby,
9
+ Rails, or HTTP-client dependency constraints make larger SDKs difficult to add.
9
10
 
10
11
  This gem is intentionally small:
11
12
 
12
13
  - No Rails dependency
13
- - No official OpenAI gem dependency
14
+ - No provider SDK dependency
14
15
  - No Faraday, HTTParty, ActiveSupport, or connection pool dependency
15
- - Uses only Ruby stdlib: `Net::HTTP`, `URI`, `JSON`, `Base64`, and `SecureRandom`
16
+ - Uses only Ruby stdlib: `Net::HTTP`, `URI`, `JSON`, and `SecureRandom`
16
17
 
17
- It is not meant to replace the official OpenAI SDK. It is a small wrapper for projects that only need a few clean interfaces:
18
+ Choose a provider and call the methods your app needs:
18
19
 
19
20
  ```ruby
20
- ai.chat("Say hello")
21
- ai.moderate("User submitted text")
22
- ai.embed("Text to vectorize")
23
- ai.image("A simple app icon")
24
- ai.speak("Read this aloud")
25
- ai.transcribe("tmp/meeting.mp3")
21
+ require "ai_lite"
22
+
23
+ openai = AiLite::OpenAI.new # Reads OPENAI_API_KEY
24
+ gemini = AiLite::Gemini.new # Reads GEMINI_API_KEY
25
+
26
+ openai.chat("Say hello")
27
+ gemini.chat("Say hello")
28
+
29
+ openai.embed("Text to vectorize")
30
+ gemini.embed("Text to vectorize")
31
+
32
+ openai.image("A simple app icon")
33
+ gemini.image("A simple app icon")
26
34
  ```
27
35
 
36
+ Each provider has independent configuration and native API options. OpenAI also
37
+ supports moderation; Gemini supports structured
38
+ media input and a YouTube helper. The table below lists the available methods.
39
+
28
40
  ## Provider support
29
41
 
30
42
  | Method | OpenAI | Gemini |
31
43
  | --- | --- | --- |
32
- | `chat`, `chat_stream` | Yes | Yes |
44
+ | `chat`, `chat_stream`, `count_tokens` | Yes | Yes |
33
45
  | Four model helpers | Yes | Yes |
34
46
  | `youtube` | No | Yes |
35
- | `moderate`, `embed`, `image`, `speak`, `transcribe` | Yes | Not implemented |
47
+ | `embed`, `image`, `speak`, `transcribe` | Yes | Yes |
48
+ | `moderate` | Yes | Not implemented |
36
49
 
37
50
  Unsupported provider methods are absent and raise Ruby's `NoMethodError` if called.
38
51
  Configure providers during application startup; do not mutate shared configuration
39
52
  or client headers while requests are running. The gem does not provide automatic
40
53
  retries, worker threads, or a background-job queue.
41
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
+
42
224
  ## Gemini
43
225
 
44
226
  ```ruby
@@ -58,6 +240,11 @@ does not load `.env` automatically.
58
240
  AiLite::Gemini.configure do |config|
59
241
  config.api_key = ENV["GEMINI_API_KEY"]
60
242
  config.model = "gemini-3.8-flash"
243
+ config.embedding_model = "gemini-embedding-001"
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"
61
248
  config.timeout = 120
62
249
  config.max_output_tokens = 2000
63
250
  end
@@ -89,8 +276,8 @@ OpenAI-style role/message arrays are not automatically translated.
89
276
  Multi-turn continuation uses the familiar keyword:
90
277
 
91
278
  ```ruby
92
- first = gemini.chat("My name is William.")
93
- 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"])
94
281
  ```
95
282
 
96
283
  `instructions:` maps to `system_instruction`; `previous_response_id:` maps to
@@ -112,15 +299,168 @@ and [API reference](https://ai.google.dev/api/interactions-api).
112
299
  Results use the standard `content`, `response_id`, `status`, `error`, and `raw`
113
300
  keys. Text is extracted only from `model_output` steps; JSON-looking text is
114
301
  parsed. `debug: true` retains the complete response, including non-text output,
115
- tool calls, and usage. Non-completed interactions (including `requires_action`)
116
- 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
117
304
  executed automatically. Input/API/transport errors return an error envelope;
118
305
  constructing a client without a key raises `ArgumentError`.
119
306
 
120
- Gemini embeddings and image/speech methods are not implemented yet. Use `chat_stream` for streaming; `chat` rejects
307
+ Use `chat_stream` for streaming; `chat` rejects
121
308
  `stream: true`. Both methods reject `background: true` before sending a request.
122
309
  Legacy `AiLite` entry points still use OpenAI.
123
310
 
311
+ ### Gemini embeddings
312
+
313
+ `embed` mirrors OpenAI's text input and return shape: a string returns one numeric
314
+ vector in `content`; an array returns a list of vectors in input order, including
315
+ an array containing just one string.
316
+
317
+ ```ruby
318
+ gemini = AiLite::Gemini.new
319
+ result = gemini.embed("Text to vectorize")
320
+ result["content"] # [0.12, -0.34, ...]
321
+
322
+ gemini.embed(["First text", "Second text"], dimensions: 768)
323
+ AiLite::Gemini.embed("Search query", options: { taskType: "RETRIEVAL_QUERY" })
324
+ ```
325
+
326
+ The default is `gemini-embedding-001`. Override it with `embedding_model:` in the
327
+ constructor, `config.embedding_model`, or `model:` per call. Both bare model IDs
328
+ and `models/` prefixes are accepted. Model checks include the embedding model.
329
+
330
+ Single strings use `embedContent`; arrays use one synchronous `batchEmbedContents`
331
+ request. `dimensions:` maps to `outputDimensionality`. Native request fields in
332
+ `options:` apply to each input; explicit model, input, and dimensions take precedence.
333
+ See Google's [embedding API reference](https://ai.google.dev/api/embeddings).
334
+
335
+ Gemini returns numeric vectors; `encoding_format:` may be omitted or set to
336
+ `"float"`. Other formats return an error envelope. Empty inputs and invalid dimensions
337
+ also return errors before making a request. `debug: true` retains the provider
338
+ response and any usage metadata in `raw`; `response_id` is `nil` for embeddings.
339
+
340
+ ### Gemini image generation
341
+
342
+ ```ruby
343
+ gemini = AiLite::Gemini.new
344
+ result = gemini.image("A cat astronaut on the moon", output_path: "tmp/cat.jpg")
345
+ result["content"] # Base64 image data, also returned when saving to a file
346
+
347
+ AiLite::Gemini.image("A mountain landscape", options: {
348
+ response_format: { type: "image", aspect_ratio: "16:9", image_size: "2K" }
349
+ })
350
+ ```
351
+
352
+ The default image model is `gemini-nano-banana-2.1`. Set `config.image_model`,
353
+ pass `image_model:` to the constructor, or override `model:` per call.
354
+ Model checks include this setting. Requests use the Interactions API, with native
355
+ settings passed through `options:`. Explicit prompt and model take precedence.
356
+ Image requests do not inherit the chat output-token limit.
357
+
358
+ Like OpenAI's `image`, `content` contains the first generated image as base64.
359
+ Only image blocks from `model_output` steps are selected. `output_path:` saves
360
+ its decoded bytes; the parent directory must already exist. Files retain the
361
+ provider's encoding: the filename does not convert the image. Use `debug: true`
362
+ to inspect MIME type, additional images, text, and usage in `raw`. Gemini can return
363
+ JPEG data even when the output filename ends in `.png`; choose the extension to
364
+ match the returned image MIME type. AI Lite does not transcode images.
365
+
366
+ The initial interface accepts a text prompt, `model:`, `output_path:`, `debug:`,
367
+ and `options:`. OpenAI-specific size, quality, background, and output format
368
+ keywords are not shared; use Gemini's native `response_format` options as above.
369
+ Streaming and background execution are rejected. Failed/incomplete interactions,
370
+ missing or invalid image data, and file-write errors return error envelopes.
371
+ See Google's [image generation guide](https://ai.google.dev/gemini-api/docs/image-generation).
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
+
124
464
  ### Gemini model checks
125
465
 
126
466
  ```ruby
@@ -129,7 +469,7 @@ result = gemini.available_models
129
469
  puts result["content"] unless result["error"]
130
470
 
131
471
  gemini.model_available?("gemini-3.8-flash") # true / false / nil on lookup failure
132
- gemini.configured_models # { "chat" => "gemini-3.8-flash" }
472
+ gemini.configured_models # Includes chat, embedding, image, speech, and transcription models
133
473
  gemini.check_configured_models # Standard envelope containing a report
134
474
 
135
475
  # All four also work at class level:
@@ -699,7 +1039,7 @@ Use `base64: true` when you want text-safe audio data that can be transported in
699
1039
  ```ruby
700
1040
  result = ai.speak("Hello from AI Lite", base64: true)
701
1041
 
702
- File.binwrite("tmp/hello.mp3", Base64.decode64(result["content"]))
1042
+ File.binwrite("tmp/hello.mp3", result["content"].unpack1("m0"))
703
1043
  ```
704
1044
 
705
1045
  `speak` sends a `POST` request to `/v1/audio/speech` with:
@@ -717,6 +1057,10 @@ The default speech model is `gpt-4o-mini-tts`.
717
1057
  The default speech voice is `alloy`.
718
1058
  The default response format is `mp3`.
719
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
+
720
1064
  Set `voice` per call when you want a different built-in voice:
721
1065
 
722
1066
  ```ruby
@@ -924,7 +1268,21 @@ result = ai.chat("Say hello", debug: true)
924
1268
 
925
1269
  ## Development
926
1270
 
927
- 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:
928
1286
 
929
1287
  ```sh
930
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
@@ -2,15 +2,25 @@ class AiLite
2
2
  class Gemini
3
3
  API_BASE_URL = "https://generativelanguage.googleapis.com/v1beta".freeze
4
4
  DEFAULT_MODEL = "gemini-3.8-flash".freeze
5
+ DEFAULT_EMBEDDING_MODEL = "gemini-embedding-001".freeze
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
5
10
  DEFAULT_TIMEOUT = 120
6
11
  DEFAULT_MAX_OUTPUT_TOKENS = 2000
7
12
 
8
13
  class Configuration
9
- attr_accessor :api_key, :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
10
15
 
11
16
  def initialize
12
17
  @api_key = nil
13
18
  @model = DEFAULT_MODEL
19
+ @embedding_model = DEFAULT_EMBEDDING_MODEL
20
+ @image_model = DEFAULT_IMAGE_MODEL
21
+ @speech_model = DEFAULT_SPEECH_MODEL
22
+ @speech_voice = DEFAULT_SPEECH_VOICE
23
+ @transcription_model = DEFAULT_TRANSCRIPTION_MODEL
14
24
  @timeout = DEFAULT_TIMEOUT
15
25
  @max_output_tokens = DEFAULT_MAX_OUTPUT_TOKENS
16
26
  end
@@ -0,0 +1,58 @@
1
+ class AiLite
2
+ class Gemini
3
+ module Embeddings
4
+ def embed(input, model: nil, dimensions: nil, encoding_format: nil, debug: false, options: {})
5
+ response = nil
6
+ raw = nil
7
+ multiple = input.is_a?(Array)
8
+ texts = multiple ? input : [input]
9
+ unless !texts.empty? && texts.all? { |text| text.is_a?(String) && !text.strip.empty? }
10
+ raise ArgumentError, "input must be a nonempty string or array of nonempty strings"
11
+ end
12
+ unless dimensions.nil? || (dimensions.is_a?(Integer) && dimensions > 0)
13
+ raise ArgumentError, "dimensions must be a positive integer"
14
+ end
15
+ unless encoding_format.nil? || encoding_format == "float"
16
+ raise ArgumentError, "Gemini embeddings only support encoding_format: float"
17
+ end
18
+ model_id = model || embedding_model
19
+ unless model_id.is_a?(String) && model_id.match?(%r{\A(?:models/)?[A-Za-z0-9._-]+\z})
20
+ raise ArgumentError, "model must be a Gemini model ID"
21
+ end
22
+ resource = "models/#{model_id.delete_prefix('models/')}"
23
+ settings = options.each_with_object({}) { |(key, value), result| result[key.to_s] = value }
24
+ settings["outputDimensionality"] = dimensions if dimensions
25
+ requests = texts.map do |text|
26
+ settings.merge("model" => resource, "content" => { "parts" => [{ "text" => text }] })
27
+ end
28
+ action = multiple ? "batchEmbedContents" : "embedContent"
29
+ payload = multiple ? { "requests" => requests } : requests.first
30
+ response = post_json(payload, endpoint: "#{API_BASE_URL}/#{resource}:#{action}")
31
+ raw = response.body
32
+ raw = JSON.parse(raw)
33
+ raise "Invalid Gemini embedding response: expected an object" unless raw.is_a?(Hash)
34
+ if !response.code.to_i.between?(200, 299) || raw["error"]
35
+ return result_envelope(status: response.code.to_i, error: error_message(raw), raw: raw, debug: debug)
36
+ end
37
+ embeddings = multiple ? raw["embeddings"] : [raw["embedding"]]
38
+ unless embeddings.is_a?(Array) && embeddings.length == texts.length
39
+ raise "Invalid Gemini embedding response: unexpected embedding count"
40
+ end
41
+ vectors = embeddings.map do |entry|
42
+ values = entry["values"] if entry.is_a?(Hash)
43
+ unless values.is_a?(Array) && !values.empty? && values.all? { |value| value.is_a?(Numeric) }
44
+ raise "Invalid Gemini embedding response: expected numeric values"
45
+ end
46
+ values
47
+ end
48
+ result_envelope(status: response.code.to_i, content: multiple ? vectors : vectors.first,
49
+ raw: raw, debug: debug)
50
+ rescue StandardError => e
51
+ result_envelope(status: response ? response.code.to_i : "unknown", error: e.message, raw: raw, debug: debug)
52
+ end
53
+ end
54
+
55
+ include Embeddings
56
+ private_constant :Embeddings
57
+ end
58
+ end