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
checksums.yaml
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
---
|
|
2
2
|
SHA256:
|
|
3
|
-
metadata.gz:
|
|
4
|
-
data.tar.gz:
|
|
3
|
+
metadata.gz: 9b745990d626099d4241a118b3d1b86492c3e5f7ee6d2462ce9354c6e5f7d4a5
|
|
4
|
+
data.tar.gz: 29410ac136fe3eb8c07aa1a00b62f0a47f91693030ffec657a90bdd73c81415b
|
|
5
5
|
SHA512:
|
|
6
|
-
metadata.gz:
|
|
7
|
-
data.tar.gz:
|
|
6
|
+
metadata.gz: caf3d92566985f294ea04a53014c03ce9b9d5d57290e59a3b9fcbd8b7314dc7762ffa9cda830b680a671f0f6605abbcef15616ce8f682c55a452130fb492bc74
|
|
7
|
+
data.tar.gz: 5e1ab3f82a09b7f8e356b575b1ac6e4331296419a65e019f063ced9a8f295f9942006b23599e70e32c9073d0e73a40e3a35493641615c1d9e87cfc26bd5a13d9
|
data/CHANGELOG.md
CHANGED
|
@@ -1,14 +1,36 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
-
##
|
|
3
|
+
## 1.3.0 (2026-11-10)
|
|
4
|
+
|
|
5
|
+
- Begin Claude support with independent configuration, stdlib Messages transport,
|
|
6
|
+
synchronous chat, explicit history, replayable assistant messages, and tests.
|
|
7
|
+
Streaming, tool helpers, token counting, and model helpers remain pending.
|
|
8
|
+
|
|
9
|
+
## 1.2.0 (2026-11-02)
|
|
10
|
+
|
|
11
|
+
- Add `tools:` and `tool_results:` to OpenAI and Gemini chat and streaming,
|
|
12
|
+
normalized function calls, and manual tool-result continuation. Gemini
|
|
13
|
+
interactions awaiting valid function results are no longer reported as errors.
|
|
14
|
+
|
|
15
|
+
- Add `count_tokens` for OpenAI and Gemini using provider counting APIs, with
|
|
16
|
+
integer results, instructions, native inputs/options, and no tokenizer dependency.
|
|
17
|
+
- Add Gemini `transcribe` for local audio files using `gemini-3.5-transcribe`,
|
|
18
|
+
with inline size validation, native options, configuration, and model checks.
|
|
19
|
+
- Add Gemini single-speaker speech with voice/style controls, WAV and raw audio
|
|
20
|
+
formats, binary/base64/file output, speech configuration, and model checks.
|
|
21
|
+
- Preserve dependency-free loading on newer Ruby versions by using built-in
|
|
22
|
+
base64 packing/unpacking instead of requiring the separately packaged library.
|
|
23
|
+
- Expand Ruby compatibility CI to Ruby 2.6, 2.7, 3.0, 3.1, 3.2, 3.3, 3.4, and
|
|
24
|
+
4.0, and test isolated gem installation/loading.
|
|
25
|
+
|
|
26
|
+
## 1.1.0
|
|
4
27
|
|
|
5
28
|
- Add Gemini image generation with base64 results, optional file output, native
|
|
6
29
|
options, image model configuration, and model checks.
|
|
7
|
-
|
|
8
30
|
- Add Gemini text embeddings for single and multiple inputs, with dimensions,
|
|
9
31
|
embedding model configuration, model checks, and the standard result envelope.
|
|
10
32
|
|
|
11
|
-
## 1.0.0
|
|
33
|
+
## 1.0.0
|
|
12
34
|
|
|
13
35
|
- Introduce independent `AiLite::OpenAI` and `AiLite::Gemini` providers.
|
|
14
36
|
- Preserve documented legacy OpenAI entry points through `AiLite`, with deprecation
|
|
@@ -21,6 +43,3 @@
|
|
|
21
43
|
- Document model-list limitations, provider-specific debug output, and migration.
|
|
22
44
|
- Treat failed/incomplete OpenAI generations as errors even when HTTP status is 200.
|
|
23
45
|
- 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,19 +1,25 @@
|
|
|
1
1
|
# AI Lite
|
|
2
2
|
|
|
3
|
-
AI Lite is a lightweight, pure Ruby client for OpenAI and
|
|
4
|
-
|
|
5
|
-
checks through simple interfaces and a consistent result format.
|
|
3
|
+
AI Lite is a lightweight, pure Ruby client for OpenAI, Gemini, and Claude, built
|
|
4
|
+
entirely on the Ruby standard library with no runtime gem dependencies.
|
|
6
5
|
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
6
|
+
OpenAI and Gemini support chat, streaming, function calling, embeddings, image
|
|
7
|
+
generation, speech, transcription, token counting, and model availability checks.
|
|
8
|
+
Claude currently supports synchronous chat and explicit message history through
|
|
9
|
+
the same consistent result format. Claude support is available starting in v1.3.0.
|
|
10
|
+
|
|
11
|
+
Built for Rails apps and plain Ruby projects that want straightforward AI
|
|
12
|
+
integration without a larger SDK or framework. AI Lite handles the API calls
|
|
13
|
+
while you control your application's architecture.
|
|
14
|
+
|
|
15
|
+
Supports Ruby 2.6 through 4.0, with no Rails dependency or runtime gem dependencies.
|
|
10
16
|
|
|
11
17
|
This gem is intentionally small:
|
|
12
18
|
|
|
13
19
|
- No Rails dependency
|
|
14
20
|
- No provider SDK dependency
|
|
15
21
|
- No Faraday, HTTParty, ActiveSupport, or connection pool dependency
|
|
16
|
-
- Uses only Ruby stdlib: `Net::HTTP`, `URI`, `JSON`,
|
|
22
|
+
- Uses only Ruby stdlib: `Net::HTTP`, `URI`, `JSON`, and `SecureRandom`
|
|
17
23
|
|
|
18
24
|
Choose a provider and call the methods your app needs:
|
|
19
25
|
|
|
@@ -22,9 +28,11 @@ require "ai_lite"
|
|
|
22
28
|
|
|
23
29
|
openai = AiLite::OpenAI.new # Reads OPENAI_API_KEY
|
|
24
30
|
gemini = AiLite::Gemini.new # Reads GEMINI_API_KEY
|
|
31
|
+
claude = AiLite::Claude.new # Reads ANTHROPIC_API_KEY
|
|
25
32
|
|
|
26
33
|
openai.chat("Say hello")
|
|
27
34
|
gemini.chat("Say hello")
|
|
35
|
+
claude.chat("Say hello")
|
|
28
36
|
|
|
29
37
|
openai.embed("Text to vectorize")
|
|
30
38
|
gemini.embed("Text to vectorize")
|
|
@@ -34,24 +42,273 @@ gemini.image("A simple app icon")
|
|
|
34
42
|
```
|
|
35
43
|
|
|
36
44
|
Each provider has independent configuration and native API options. OpenAI also
|
|
37
|
-
supports moderation
|
|
45
|
+
supports moderation; Gemini supports structured
|
|
38
46
|
media input and a YouTube helper. The table below lists the available methods.
|
|
39
47
|
|
|
40
48
|
## Provider support
|
|
41
49
|
|
|
42
|
-
| Method | OpenAI | Gemini |
|
|
43
|
-
| --- | --- | --- |
|
|
44
|
-
| `chat
|
|
45
|
-
|
|
|
46
|
-
|
|
|
47
|
-
| `
|
|
48
|
-
| `
|
|
50
|
+
| Method | OpenAI | Gemini | Claude |
|
|
51
|
+
| --- | --- | --- | --- |
|
|
52
|
+
| `chat` | Yes | Yes | Yes; tool helpers pending |
|
|
53
|
+
| `chat_stream`, `count_tokens` | Yes | Yes | Not implemented |
|
|
54
|
+
| Four model helpers | Yes | Yes | Not implemented |
|
|
55
|
+
| `youtube` | No | Yes | Not implemented |
|
|
56
|
+
| `embed`, `image`, `speak`, `transcribe` | Yes | Yes | Not implemented |
|
|
57
|
+
| `moderate` | Yes | Not implemented | Not implemented |
|
|
49
58
|
|
|
50
59
|
Unsupported provider methods are absent and raise Ruby's `NoMethodError` if called.
|
|
51
60
|
Configure providers during application startup; do not mutate shared configuration
|
|
52
61
|
or client headers while requests are running. The gem does not provide automatic
|
|
53
62
|
retries, worker threads, or a background-job queue.
|
|
54
63
|
|
|
64
|
+
## Claude
|
|
65
|
+
|
|
66
|
+
`AiLite::Claude` supports synchronous chat and explicit message history starting
|
|
67
|
+
in v1.3.0. Claude streaming, normalized tool calls/results, token
|
|
68
|
+
counting, and model helpers are still pending.
|
|
69
|
+
|
|
70
|
+
```ruby
|
|
71
|
+
require "ai_lite/claude" # Also loaded by require "ai_lite"
|
|
72
|
+
|
|
73
|
+
claude = AiLite::Claude.new # Reads ANTHROPIC_API_KEY; does not load .env
|
|
74
|
+
result = claude.chat("Hello", max_output_tokens: 32,
|
|
75
|
+
options: { thinking: { type: "disabled" }, output_config: { effort: "low" } })
|
|
76
|
+
raise result["error"] if result["error"]
|
|
77
|
+
puts result["content"]
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
Defaults: `claude-haiku-5-5`, API version `2026-10-21`, 120-second timeout, and
|
|
81
|
+
2,000 maximum output tokens. Thinking settings are provider defaults unless
|
|
82
|
+
supplied through `options:`. The short example disables thinking and limits output
|
|
83
|
+
for inexpensive development checks; those options depend on the selected model.
|
|
84
|
+
|
|
85
|
+
The example above uses the default Haiku model. For `claude-sonnet-5-5`, use
|
|
86
|
+
`thinking: { type: "between_tools" }` instead of `disabled`:
|
|
87
|
+
|
|
88
|
+
```ruby
|
|
89
|
+
result = claude.chat("Reply only OK.", model: "claude-sonnet-5-5",
|
|
90
|
+
max_output_tokens: 32,
|
|
91
|
+
options: { thinking: { type: "between_tools" }, output_config: { effort: "low" } })
|
|
92
|
+
raise result["error"] if result["error"]
|
|
93
|
+
puts result["content"]
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
AI Lite passes these native options through to Claude; it does not translate
|
|
97
|
+
thinking settings between models. The API returns an error for unsupported settings.
|
|
98
|
+
|
|
99
|
+
```ruby
|
|
100
|
+
AiLite::Claude.configure do |config|
|
|
101
|
+
config.api_key = ENV["ANTHROPIC_API_KEY"]
|
|
102
|
+
config.model = "claude-haiku-5-5"
|
|
103
|
+
config.max_output_tokens = 256
|
|
104
|
+
# config.workspace_id = "wrkspc_..." # For keys that require workspace selection
|
|
105
|
+
end
|
|
106
|
+
AiLite::Claude.chat("Hello")
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
Constructor keywords override configuration, and `api_key:` falls back to
|
|
110
|
+
`ANTHROPIC_API_KEY`. Other providers' keys are never used. `api_version` and
|
|
111
|
+
`workspace_id` are configurable in both places. Missing credentials raise
|
|
112
|
+
`ArgumentError`; request, transport, and response failures use the normal error
|
|
113
|
+
envelope. `instructions:` maps to `system`, and `max_output_tokens:` maps to
|
|
114
|
+
`max_tokens`. Native options pass through without mutating the caller's hashes.
|
|
115
|
+
|
|
116
|
+
Claude's standard Messages API requires history on each turn:
|
|
117
|
+
|
|
118
|
+
```ruby
|
|
119
|
+
history = [{ role: "user", content: "My favorite color is blue." }]
|
|
120
|
+
first = claude.chat(history)
|
|
121
|
+
raise first["error"] if first["error"]
|
|
122
|
+
history << first["assistant_message"]
|
|
123
|
+
history << { role: "user", content: "What is my favorite color?" }
|
|
124
|
+
second = claude.chat(history)
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
The usual envelope is preserved, with `assistant_message` added for replay.
|
|
128
|
+
It contains the original assistant content blocks, including any thinking blocks
|
|
129
|
+
and signatures, even when `raw` is nil. Treat it as provider conversation data;
|
|
130
|
+
`content` remains the displayable text (or parsed JSON). `response_id` identifies
|
|
131
|
+
the message but cannot continue the conversation: `previous_response_id:` returns
|
|
132
|
+
an error. No conversation is stored inside the client.
|
|
133
|
+
|
|
134
|
+
Use `debug: true` for the full native response and usage. Truncation, refusals,
|
|
135
|
+
paused turns, and tool requests currently return a descriptive error while
|
|
136
|
+
preserving available text and assistant content. Only `end_turn` and
|
|
137
|
+
`stop_sequence` are handled as completed answers in this initial implementation.
|
|
138
|
+
Do not treat HTTP 200 alone as success. Native content blocks can be supplied in
|
|
139
|
+
message arrays; the gem does not upload or convert media.
|
|
140
|
+
|
|
141
|
+
Reference: [Claude Messages API](https://platform.claude.com/docs/en/api/messages/create).
|
|
142
|
+
|
|
143
|
+
## Function calling (OpenAI and Gemini)
|
|
144
|
+
|
|
145
|
+
Pass native tool definitions through `tools:` on `chat` or `chat_stream`.
|
|
146
|
+
Both providers accept the basic function definition below. Provider-specific
|
|
147
|
+
fields and built-in tools retain their native formats; `options:` remains the
|
|
148
|
+
escape hatch for settings such as tool choice.
|
|
149
|
+
|
|
150
|
+
```ruby
|
|
151
|
+
ai = AiLite::Gemini.new # Or AiLite::OpenAI.new
|
|
152
|
+
|
|
153
|
+
tools = [{
|
|
154
|
+
type: "function",
|
|
155
|
+
name: "lookup_order",
|
|
156
|
+
description: "Look up an order's shipping status",
|
|
157
|
+
parameters: {
|
|
158
|
+
type: "object",
|
|
159
|
+
properties: { order_id: { type: "integer" } },
|
|
160
|
+
required: ["order_id"],
|
|
161
|
+
additionalProperties: false
|
|
162
|
+
}
|
|
163
|
+
}]
|
|
164
|
+
|
|
165
|
+
result = ai.chat("Where is order 123?", tools: tools)
|
|
166
|
+
raise result["error"] if result["error"]
|
|
167
|
+
|
|
168
|
+
# When a function is requested:
|
|
169
|
+
# result["tool_calls"] => [
|
|
170
|
+
# { "id" => "call_123", "name" => "lookup_order",
|
|
171
|
+
# "arguments" => { "order_id" => 123 } }
|
|
172
|
+
# ]
|
|
173
|
+
```
|
|
174
|
+
|
|
175
|
+
A tool request is a successful chat result. `content` may be nil or contain text
|
|
176
|
+
alongside tool calls. The `tool_calls` key appears only when complete function
|
|
177
|
+
calls are present; existing text-only envelopes are unchanged. OpenAI call IDs
|
|
178
|
+
come from `call_id`, not the output item's `id`. Gemini IDs come from the
|
|
179
|
+
function-call step's `id`. Arguments are decoded into hashes without requiring
|
|
180
|
+
`debug: true`. Failed/incomplete responses do not expose executable tool calls.
|
|
181
|
+
|
|
182
|
+
Your application validates arguments, authorizes access, and executes only
|
|
183
|
+
functions it explicitly allows. For example, in a Rails controller:
|
|
184
|
+
|
|
185
|
+
```ruby
|
|
186
|
+
calls = result.fetch("tool_calls", [])
|
|
187
|
+
unless calls.empty?
|
|
188
|
+
outputs = calls.map do |call|
|
|
189
|
+
raise "Unsupported tool" unless call["name"] == "lookup_order"
|
|
190
|
+
order_id = call["arguments"].fetch("order_id")
|
|
191
|
+
raise "Invalid order ID" unless order_id.is_a?(Integer)
|
|
192
|
+
|
|
193
|
+
order = current_user.orders.find(order_id)
|
|
194
|
+
{ id: call["id"], name: call["name"], output: { status: order.status } }
|
|
195
|
+
end
|
|
196
|
+
|
|
197
|
+
result = ai.chat(
|
|
198
|
+
nil,
|
|
199
|
+
previous_response_id: result["response_id"],
|
|
200
|
+
tools: tools,
|
|
201
|
+
tool_results: outputs
|
|
202
|
+
)
|
|
203
|
+
raise result["error"] if result["error"]
|
|
204
|
+
end
|
|
205
|
+
|
|
206
|
+
puts result["content"]
|
|
207
|
+
# The model may request more tools; your app decides whether to continue.
|
|
208
|
+
```
|
|
209
|
+
|
|
210
|
+
`tool_results:` takes a nonempty array of `{ id:, name:, output: }` hashes,
|
|
211
|
+
requires `previous_response_id:`, and uses `nil` as the positional message.
|
|
212
|
+
Strings are sent as text; other JSON-compatible outputs are JSON-encoded.
|
|
213
|
+
The helper translates results into OpenAI `function_call_output` items or
|
|
214
|
+
Gemini `function_result` steps. Return a result for every requested call and
|
|
215
|
+
reuse the same provider/model and tool definitions. IDs refer to stored provider
|
|
216
|
+
state; when using stateless requests, pass native history/results as the
|
|
217
|
+
positional input instead. Preserve all provider-required history, including
|
|
218
|
+
reasoning/thought items and signatures; normalized `tool_calls` alone are not
|
|
219
|
+
full conversation history. Use non-streaming `chat` with `debug: true` for the full native response;
|
|
220
|
+
streaming debug output may contain partial metadata plus events.
|
|
221
|
+
|
|
222
|
+
`chat_stream` accepts the same tool keywords. Its block still receives text
|
|
223
|
+
only; complete tool calls are returned in the final envelope after streaming.
|
|
224
|
+
Do not execute streamed argument fragments. Class-level calls work too:
|
|
225
|
+
`AiLite::OpenAI.chat(...)` and `AiLite::Gemini.chat(...)`.
|
|
226
|
+
|
|
227
|
+
Explicit `tools:` overrides `options[:tools]`, including `tools: []` to clear
|
|
228
|
+
it. AI Lite does not execute functions, dispatch method names, retry tool calls,
|
|
229
|
+
or run an automatic agent loop. Built-in provider tools are passed through;
|
|
230
|
+
only custom `function_call` outputs are normalized into `tool_calls`.
|
|
231
|
+
|
|
232
|
+
See the [OpenAI function-calling guide](https://developers.openai.com/api/docs/guides/function-calling)
|
|
233
|
+
and [Gemini function-calling guide](https://ai.google.dev/gemini-api/docs/function-calling)
|
|
234
|
+
for native schemas and continuation requirements.
|
|
235
|
+
|
|
236
|
+
## Token counting (both providers)
|
|
237
|
+
|
|
238
|
+
```ruby
|
|
239
|
+
openai = AiLite::OpenAI.new
|
|
240
|
+
gemini = AiLite::Gemini.new
|
|
241
|
+
|
|
242
|
+
result = openai.count_tokens("Hello from AI Lite.")
|
|
243
|
+
result["content"] # Integer input-token count when error is nil
|
|
244
|
+
result["error"] # nil on success
|
|
245
|
+
|
|
246
|
+
gemini.count_tokens("Hello from AI Lite.", instructions: "Be concise.")
|
|
247
|
+
|
|
248
|
+
# Class-level methods use each provider's independent configuration:
|
|
249
|
+
AiLite::OpenAI.count_tokens("Hello")
|
|
250
|
+
AiLite::Gemini.count_tokens("Hello")
|
|
251
|
+
```
|
|
252
|
+
|
|
253
|
+
These are authenticated HTTP calls, not offline tokenizers. They count input
|
|
254
|
+
only, without generating an answer or predicting output tokens or a final bill.
|
|
255
|
+
Counts depend on the model and the supplied context. Both use the configured
|
|
256
|
+
chat `model` by default; pass `model:` to override it. No tokenizer gem is needed.
|
|
257
|
+
The standard envelope contains an integer `content`, a nil `response_id`, and
|
|
258
|
+
`raw` only with `debug: true`. Check `error` before using the count; zero is a
|
|
259
|
+
valid count, and failures return nil content. Chat output-token defaults are
|
|
260
|
+
not added to counting requests.
|
|
261
|
+
|
|
262
|
+
OpenAI uses `POST /v1/responses/input_tokens`. Pass a string or an array of native
|
|
263
|
+
Responses input items, including supported media and conversation history:
|
|
264
|
+
|
|
265
|
+
```ruby
|
|
266
|
+
openai.count_tokens(
|
|
267
|
+
[
|
|
268
|
+
{ role: "user", content: "Hello" },
|
|
269
|
+
{ role: "assistant", content: "Hi!" },
|
|
270
|
+
{ role: "user", content: "Tell me more." }
|
|
271
|
+
],
|
|
272
|
+
instructions: "Be concise."
|
|
273
|
+
)
|
|
274
|
+
# Count a continuation using a response ID from an earlier chat:
|
|
275
|
+
openai.count_tokens("Tell me more.", previous_response_id: previous_result["response_id"])
|
|
276
|
+
```
|
|
277
|
+
|
|
278
|
+
Gemini uses `POST /v1beta/models/{model}:countTokens`. Its structured inputs use
|
|
279
|
+
**Content objects with `parts`, not the Interactions objects accepted by `chat`**:
|
|
280
|
+
|
|
281
|
+
```ruby
|
|
282
|
+
gemini.count_tokens(
|
|
283
|
+
[
|
|
284
|
+
{ role: "user", parts: [{ text: "Hello" }] },
|
|
285
|
+
{ role: "model", parts: [{ text: "Hi!" }] },
|
|
286
|
+
{ role: "user", parts: [{ text: "Tell me more." }] }
|
|
287
|
+
],
|
|
288
|
+
instructions: "Be concise."
|
|
289
|
+
)
|
|
290
|
+
```
|
|
291
|
+
|
|
292
|
+
A single Gemini Content hash is also accepted. Media uses native `inlineData`
|
|
293
|
+
or `fileData` parts; the helper does not read or upload local files. Supply
|
|
294
|
+
conversation history explicitly: Gemini counting does not resolve
|
|
295
|
+
`previous_response_id` or `previous_interaction_id`. Preflight counts can differ
|
|
296
|
+
from a later generation's reported usage.
|
|
297
|
+
|
|
298
|
+
`options:` passes native counting API fields. OpenAI tool definitions go in
|
|
299
|
+
`options: { tools: [...] }`; Gemini tool definitions go in
|
|
300
|
+
`options: { generateContentRequest: { tools: [...] } }`. Gemini `instructions:`
|
|
301
|
+
builds `generateContentRequest.systemInstruction`. The helper owns the model
|
|
302
|
+
and input/contents fields; explicit keywords take precedence over matching
|
|
303
|
+
options without mutating the caller's hashes. Native fields keep each API's
|
|
304
|
+
spelling. Use the counting endpoint's options rather than copying every chat
|
|
305
|
+
option. New methods are exposed on the provider classes; there is no legacy
|
|
306
|
+
`AiLite.count_tokens` class shortcut.
|
|
307
|
+
|
|
308
|
+
See [OpenAI's counting guide](https://developers.openai.com/api/docs/guides/token-counting)
|
|
309
|
+
and [Gemini's counting API reference](https://ai.google.dev/api/tokens) for supported
|
|
310
|
+
inputs and native parameters.
|
|
311
|
+
|
|
55
312
|
## Gemini
|
|
56
313
|
|
|
57
314
|
```ruby
|
|
@@ -73,6 +330,9 @@ AiLite::Gemini.configure do |config|
|
|
|
73
330
|
config.model = "gemini-3.8-flash"
|
|
74
331
|
config.embedding_model = "gemini-embedding-001"
|
|
75
332
|
config.image_model = "gemini-nano-banana-2.1"
|
|
333
|
+
config.speech_model = "gemini-3.8-flash-tts"
|
|
334
|
+
config.speech_voice = "Kore"
|
|
335
|
+
config.transcription_model = "gemini-3.5-transcribe"
|
|
76
336
|
config.timeout = 120
|
|
77
337
|
config.max_output_tokens = 2000
|
|
78
338
|
end
|
|
@@ -104,8 +364,8 @@ OpenAI-style role/message arrays are not automatically translated.
|
|
|
104
364
|
Multi-turn continuation uses the familiar keyword:
|
|
105
365
|
|
|
106
366
|
```ruby
|
|
107
|
-
first = gemini.chat("My
|
|
108
|
-
second = gemini.chat("What is my
|
|
367
|
+
first = gemini.chat("My favorite color is blue.")
|
|
368
|
+
second = gemini.chat("What is my favorite color?", previous_response_id: first["response_id"])
|
|
109
369
|
```
|
|
110
370
|
|
|
111
371
|
`instructions:` maps to `system_instruction`; `previous_response_id:` maps to
|
|
@@ -127,12 +387,12 @@ and [API reference](https://ai.google.dev/api/interactions-api).
|
|
|
127
387
|
Results use the standard `content`, `response_id`, `status`, `error`, and `raw`
|
|
128
388
|
keys. Text is extracted only from `model_output` steps; JSON-looking text is
|
|
129
389
|
parsed. `debug: true` retains the complete response, including non-text output,
|
|
130
|
-
tool calls, and usage.
|
|
131
|
-
|
|
390
|
+
tool calls, and usage. `requires_action` with valid function calls returns
|
|
391
|
+
`tool_calls` without an error. Other non-completed interactions return an error; no tools are
|
|
132
392
|
executed automatically. Input/API/transport errors return an error envelope;
|
|
133
393
|
constructing a client without a key raises `ArgumentError`.
|
|
134
394
|
|
|
135
|
-
|
|
395
|
+
Use `chat_stream` for streaming; `chat` rejects
|
|
136
396
|
`stream: true`. Both methods reject `background: true` before sending a request.
|
|
137
397
|
Legacy `AiLite` entry points still use OpenAI.
|
|
138
398
|
|
|
@@ -198,6 +458,97 @@ Streaming and background execution are rejected. Failed/incomplete interactions,
|
|
|
198
458
|
missing or invalid image data, and file-write errors return error envelopes.
|
|
199
459
|
See Google's [image generation guide](https://ai.google.dev/gemini-api/docs/image-generation).
|
|
200
460
|
|
|
461
|
+
### Gemini speech
|
|
462
|
+
|
|
463
|
+
```ruby
|
|
464
|
+
gemini = AiLite::Gemini.new
|
|
465
|
+
result = gemini.speak("Hello from AI Lite.", output_path: "tmp/hello.wav")
|
|
466
|
+
result["content"] # { "path" => "tmp/hello.wav", "bytes" => ..., "format" => "wav" }
|
|
467
|
+
|
|
468
|
+
AiLite::Gemini.speak("Have a wonderful day!", voice: "Puck",
|
|
469
|
+
instructions: "Speak warmly and calmly", base64: true)
|
|
470
|
+
```
|
|
471
|
+
|
|
472
|
+
`speak` returns binary audio by default. With `output_path:`, it saves the audio
|
|
473
|
+
and returns path, byte count, and format. With `base64: true`, `content` is base64
|
|
474
|
+
instead; a supplied output path is still written. Parent directories must exist.
|
|
475
|
+
|
|
476
|
+
The defaults are `gemini-3.8-flash-tts`, voice `Kore`, and WAV output.
|
|
477
|
+
Configure `speech_model` and `speech_voice` globally or in the constructor;
|
|
478
|
+
`model:` and `voice:` override them per call. Model checks include the speech model.
|
|
479
|
+
`instructions:` supplies speaking style through speech metadata.
|
|
480
|
+
|
|
481
|
+
`response_format:` accepts `"wav"`, `"pcm"`, `"mulaw"`, or `"alaw"`.
|
|
482
|
+
This helper saves decoded provider bytes without transcoding; a filename extension
|
|
483
|
+
does not change the encoding. It does not support OpenAI's `speed:` or MP3 output.
|
|
484
|
+
See Google's [speech guide](https://ai.google.dev/gemini-api/docs/speech-generation)
|
|
485
|
+
for model-specific voices and formats.
|
|
486
|
+
|
|
487
|
+
Native options remain available, for example:
|
|
488
|
+
|
|
489
|
+
```ruby
|
|
490
|
+
gemini.speak("Hello", response_format: "pcm", options: {
|
|
491
|
+
response_format: { sample_rate: 16000 },
|
|
492
|
+
store: false
|
|
493
|
+
})
|
|
494
|
+
```
|
|
495
|
+
|
|
496
|
+
Explicit input, model, voice, and format take precedence. This single-speaker
|
|
497
|
+
helper owns `generation_config.speech_config`; any supplied speech configuration
|
|
498
|
+
is replaced with the selected voice. Other native generation settings pass through;
|
|
499
|
+
the chat output-token limit is not added. Streaming/background requests are rejected.
|
|
500
|
+
|
|
501
|
+
Only one inline audio block from completed model output is accepted. Missing,
|
|
502
|
+
invalid, unsupported, or multiple audio blocks return errors before writing a file.
|
|
503
|
+
`debug: true` includes the full provider response in `raw`, including audio and usage.
|
|
504
|
+
The standard envelope includes the interaction's `response_id` when available.
|
|
505
|
+
|
|
506
|
+
### Gemini transcription
|
|
507
|
+
|
|
508
|
+
```ruby
|
|
509
|
+
result = gemini.transcribe("tmp/gemini-speech-test.wav")
|
|
510
|
+
result["content"] # Transcript as a string
|
|
511
|
+
result["error"] # nil on success
|
|
512
|
+
|
|
513
|
+
# Class-level calls work too:
|
|
514
|
+
AiLite::Gemini.transcribe("tmp/meeting.mp3")
|
|
515
|
+
```
|
|
516
|
+
|
|
517
|
+
The default model is `gemini-3.5-transcribe`. Set `transcription_model` in
|
|
518
|
+
configuration or the constructor, or override it with `model:` per call.
|
|
519
|
+
The helper reads a local audio file and sends base64 audio to the Interactions
|
|
520
|
+
API. The complete JSON request must be under 20 MB, including base64 overhead
|
|
521
|
+
(roughly 15 MB of audio, less any options). Larger requests return an error;
|
|
522
|
+
this helper does not upload files through the Files API.
|
|
523
|
+
|
|
524
|
+
The filename extension selects the MIME type for WAV, MP3, AIFF, AAC, OGG,
|
|
525
|
+
FLAC, MPEG, M4A, L16/PCM, Opus, ALAW, MULAW, and WebM. Use `mime_type:` when
|
|
526
|
+
needed, including parameters for raw PCM such as `audio/l16;rate=24000`.
|
|
527
|
+
Audio is sent as supplied; the gem does not convert formats.
|
|
528
|
+
|
|
529
|
+
Language detection is automatic. Pass provider-specific settings through `options:`:
|
|
530
|
+
|
|
531
|
+
```ruby
|
|
532
|
+
result = gemini.transcribe(
|
|
533
|
+
"tmp/meeting.wav",
|
|
534
|
+
options: {
|
|
535
|
+
generation_config: {
|
|
536
|
+
transcription_config: { language_codes: ["en-US"] }
|
|
537
|
+
}
|
|
538
|
+
},
|
|
539
|
+
debug: true
|
|
540
|
+
)
|
|
541
|
+
result["content"] # Plain transcript, even when the spoken text looks like JSON
|
|
542
|
+
result["raw"] # Full provider response, including available annotations
|
|
543
|
+
```
|
|
544
|
+
|
|
545
|
+
See Google's [transcription guide](https://ai.google.dev/gemini-api/docs/transcribe)
|
|
546
|
+
for vocabulary hints, speaker labels, timestamps, and their compatibility rules.
|
|
547
|
+
Unlike OpenAI's transcription helper, this method does not accept `language:` or
|
|
548
|
+
`prompt:`; use native transcription settings instead. Streaming and background
|
|
549
|
+
transcription are not supported. Failed or incomplete responses return an error
|
|
550
|
+
in the standard envelope.
|
|
551
|
+
|
|
201
552
|
### Gemini model checks
|
|
202
553
|
|
|
203
554
|
```ruby
|
|
@@ -206,7 +557,7 @@ result = gemini.available_models
|
|
|
206
557
|
puts result["content"] unless result["error"]
|
|
207
558
|
|
|
208
559
|
gemini.model_available?("gemini-3.8-flash") # true / false / nil on lookup failure
|
|
209
|
-
gemini.configured_models # Includes chat, embedding, and
|
|
560
|
+
gemini.configured_models # Includes chat, embedding, image, speech, and transcription models
|
|
210
561
|
gemini.check_configured_models # Standard envelope containing a report
|
|
211
562
|
|
|
212
563
|
# All four also work at class level:
|
|
@@ -776,7 +1127,7 @@ Use `base64: true` when you want text-safe audio data that can be transported in
|
|
|
776
1127
|
```ruby
|
|
777
1128
|
result = ai.speak("Hello from AI Lite", base64: true)
|
|
778
1129
|
|
|
779
|
-
File.binwrite("tmp/hello.mp3",
|
|
1130
|
+
File.binwrite("tmp/hello.mp3", result["content"].unpack1("m0"))
|
|
780
1131
|
```
|
|
781
1132
|
|
|
782
1133
|
`speak` sends a `POST` request to `/v1/audio/speech` with:
|
|
@@ -794,6 +1145,10 @@ The default speech model is `gpt-4o-mini-tts`.
|
|
|
794
1145
|
The default speech voice is `alloy`.
|
|
795
1146
|
The default response format is `mp3`.
|
|
796
1147
|
|
|
1148
|
+
For the current list of built-in voices and model-specific voice support, see
|
|
1149
|
+
[OpenAI's text-to-speech guide](https://developers.openai.com/api/docs/guides/text-to-speech).
|
|
1150
|
+
AI Lite does not expose an OpenAI `available_voices` method.
|
|
1151
|
+
|
|
797
1152
|
Set `voice` per call when you want a different built-in voice:
|
|
798
1153
|
|
|
799
1154
|
```ruby
|
|
@@ -1001,7 +1356,21 @@ result = ai.chat("Say hello", debug: true)
|
|
|
1001
1356
|
|
|
1002
1357
|
## Development
|
|
1003
1358
|
|
|
1004
|
-
|
|
1359
|
+
Compatibility CI runs the full suite on Ruby 2.6, 2.7, 3.0, 3.1, 3.2, 3.3,
|
|
1360
|
+
3.4, and 4.0. Tests include building and installing the gem in isolation and
|
|
1361
|
+
loading both providers without third-party runtime gems. These are Ruby tests;
|
|
1362
|
+
they do not constitute a Rails integration matrix.
|
|
1363
|
+
|
|
1364
|
+
Install the test dependency (not a runtime dependency):
|
|
1365
|
+
|
|
1366
|
+
```sh
|
|
1367
|
+
# Ruby 2.6–3.4
|
|
1368
|
+
gem install minitest --version 5.15.0 --no-document
|
|
1369
|
+
# Ruby 4.0
|
|
1370
|
+
gem install minitest --version 5.27.0 --no-document
|
|
1371
|
+
```
|
|
1372
|
+
|
|
1373
|
+
Run the test suite from the repository root:
|
|
1005
1374
|
|
|
1006
1375
|
```sh
|
|
1007
1376
|
ruby -Ilib:test test/run.rb
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
class AiLite
|
|
2
|
+
class Claude
|
|
3
|
+
module Chat
|
|
4
|
+
def chat(message, model: nil, instructions: nil, max_output_tokens: nil, previous_response_id: nil, debug: false, options: {})
|
|
5
|
+
response = raw = response_id = nil
|
|
6
|
+
raise ArgumentError, "Claude requires explicit message history, not previous_response_id" unless previous_response_id.nil?
|
|
7
|
+
raise ArgumentError, "options must be a hash" unless options.is_a?(Hash)
|
|
8
|
+
payload = options.each_with_object({}) { |(key, value), result| result[key.to_s] = value }
|
|
9
|
+
if payload.key?("previous_response_id") || payload.key?("previous_interaction_id")
|
|
10
|
+
raise ArgumentError, "Claude requires explicit message history, not a previous response ID"
|
|
11
|
+
end
|
|
12
|
+
raise ArgumentError, "Claude streaming is not implemented yet" if payload["stream"]
|
|
13
|
+
unless instructions.nil? || instructions.is_a?(String)
|
|
14
|
+
raise ArgumentError, "instructions must be a string; use options[:system] for native blocks"
|
|
15
|
+
end
|
|
16
|
+
messages = message.is_a?(String) ? [{ "role" => "user", "content" => message }] : message
|
|
17
|
+
unless messages.is_a?(Array) && !messages.empty? && messages.all? { |item| item.is_a?(Hash) }
|
|
18
|
+
raise ArgumentError, "message must be a string or a nonempty array of Claude messages"
|
|
19
|
+
end
|
|
20
|
+
messages.each do |item|
|
|
21
|
+
role = item["role"] || item[:role]
|
|
22
|
+
content = item.key?("content") ? item["content"] : item[:content]
|
|
23
|
+
unless %w[user assistant system].include?(role) && (content.is_a?(String) || content.is_a?(Array))
|
|
24
|
+
raise ArgumentError, "Each Claude message requires a native role and string or array content"
|
|
25
|
+
end
|
|
26
|
+
end
|
|
27
|
+
limit = max_output_tokens || payload["max_tokens"] || self.max_output_tokens
|
|
28
|
+
raise ArgumentError, "max_output_tokens must be a nonnegative integer" unless limit.is_a?(Integer) && limit >= 0
|
|
29
|
+
payload.merge!("model" => model || self.model, "messages" => messages, "max_tokens" => limit)
|
|
30
|
+
payload["system"] = instructions unless instructions.nil?
|
|
31
|
+
response = post_json(payload, endpoint: "#{API_BASE_URL}/messages")
|
|
32
|
+
raw = response.body
|
|
33
|
+
raw = JSON.parse(raw)
|
|
34
|
+
raise "Invalid Claude response: expected an object" unless raw.is_a?(Hash)
|
|
35
|
+
response_id = raw["id"]
|
|
36
|
+
unless response.code.to_i.between?(200, 299) && !raw["error"]
|
|
37
|
+
return result_envelope(status: response.code.to_i, error: error_message(raw), response_id: response_id, raw: raw, debug: debug)
|
|
38
|
+
end
|
|
39
|
+
blocks = raw["content"]
|
|
40
|
+
unless raw["type"] == "message" && raw["role"] == "assistant" && blocks.is_a?(Array) && blocks.all? { |part| part.is_a?(Hash) }
|
|
41
|
+
raise "Invalid Claude response: expected an assistant message with content blocks"
|
|
42
|
+
end
|
|
43
|
+
text = blocks.select { |part| part["type"] == "text" }.map do |part|
|
|
44
|
+
raise "Invalid Claude text block" unless part["text"].is_a?(String)
|
|
45
|
+
part["text"]
|
|
46
|
+
end.join.strip
|
|
47
|
+
content = text.empty? ? nil : text
|
|
48
|
+
if content
|
|
49
|
+
begin
|
|
50
|
+
content = JSON.parse(text)
|
|
51
|
+
rescue JSON::ParserError
|
|
52
|
+
# Preserve ordinary text, matching the other providers.
|
|
53
|
+
end
|
|
54
|
+
end
|
|
55
|
+
reason = raw["stop_reason"]
|
|
56
|
+
error = unless %w[end_turn stop_sequence].include?(reason)
|
|
57
|
+
"Claude stopped with #{reason || 'no stop reason'}; inspect raw with debug: true"
|
|
58
|
+
end
|
|
59
|
+
result = result_envelope(status: response.code.to_i, content: content, error: error,
|
|
60
|
+
response_id: response_id, raw: raw, debug: debug)
|
|
61
|
+
# Preserve every content block for stateless replay, including thinking signatures.
|
|
62
|
+
result["assistant_message"] = { "role" => "assistant", "content" => blocks }
|
|
63
|
+
result
|
|
64
|
+
rescue StandardError => e
|
|
65
|
+
result_envelope(status: response ? response.code.to_i : "unknown", error: e.message,
|
|
66
|
+
response_id: response_id, raw: raw, debug: debug)
|
|
67
|
+
end
|
|
68
|
+
end
|
|
69
|
+
|
|
70
|
+
include Chat
|
|
71
|
+
private_constant :Chat
|
|
72
|
+
end
|
|
73
|
+
end
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
class AiLite
|
|
2
|
+
class Claude
|
|
3
|
+
API_BASE_URL = "https://api.anthropic.com/v1".freeze
|
|
4
|
+
DEFAULT_MODEL = "claude-haiku-5-5".freeze
|
|
5
|
+
DEFAULT_API_VERSION = "2026-10-21".freeze
|
|
6
|
+
DEFAULT_TIMEOUT = 120
|
|
7
|
+
DEFAULT_MAX_OUTPUT_TOKENS = 2000
|
|
8
|
+
|
|
9
|
+
class Configuration
|
|
10
|
+
attr_accessor :api_key, :model, :api_version, :workspace_id, :timeout, :max_output_tokens
|
|
11
|
+
|
|
12
|
+
def initialize
|
|
13
|
+
@api_key = nil
|
|
14
|
+
@model = DEFAULT_MODEL
|
|
15
|
+
@api_version = DEFAULT_API_VERSION
|
|
16
|
+
@workspace_id = nil
|
|
17
|
+
@timeout = DEFAULT_TIMEOUT
|
|
18
|
+
@max_output_tokens = DEFAULT_MAX_OUTPUT_TOKENS
|
|
19
|
+
end
|
|
20
|
+
end
|
|
21
|
+
end
|
|
22
|
+
end
|