eleven_rb 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: ed711abcce18771ad13f10bcb29754605be61f7d02f7114f0e0b28b0dad4d556
4
- data.tar.gz: 146285726bc80b0c3eab0b307a7ec4b788a8f3465903992bb12fc2b34bc1694b
3
+ metadata.gz: 34de9ec2892de8dec87b1bfe6337516288f37db698f1ad4f5919a0c3ff8d5bb9
4
+ data.tar.gz: 829ad63126553c0828253b41e58f25b1141751a617ed57ee6fcb2e48c47e662f
5
5
  SHA512:
6
- metadata.gz: 6bf8e216c83287bb099e4a6bbed4ef718329f361fb7dfb4c70bf122f2512c74916eb1540fe6a1dfd4ae01e0edc53edc05408a017946f504c09611a54a6c2370b
7
- data.tar.gz: 1839c52e3adf4efed58c410f08fa5c5e4818fde0964922e0752019b6606d726ed66a4f48a767b4e2110aa3b0cf98e7f4666eaef64552ec9f0f976378b1ef5094
6
+ metadata.gz: 980e55ff51d0c558deffa4c543f3da5db31a9e46cd339af314d481807d105cf5469bc3510e5fde9b3d63ff27a7b049078adfde6984830ebf53484115e8956bf2
7
+ data.tar.gz: 0a4638a7215d5cda2a539be65e863db94a8713e0d761c40067e1304305388158e781c63c633a24ab4f072011b558bfe5cd101a4c646927f003ccd8c57fde978d
data/CHANGELOG.md CHANGED
@@ -7,6 +7,48 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [1.2.0] - 2026-12-02
11
+
12
+ - Fixed streaming chunk delivery, error propagation and response callbacks. Speech and dialogue support `stream_with_timestamps`.
13
+ - Raised v4 and v4 Turbo Text to Speech limits to 100,000 characters. Added professional clone strength, audio effects and the effects catalog.
14
+ - Migrated voice listing to cursor-paginated v2. Voice conversion uses the Voice Changer HTTP endpoints and supports streaming.
15
+ - Upgraded music to `music_v2_5` and sound effects to `eleven_text_to_sound_v3`. Saved v1 plans convert to chunks for v2 generation. Music supports song IDs, audio references, inpainting uploads and video scoring with optional ZIP output.
16
+ - Music and sound-effect callback data now includes requested seconds and provider-reported credits. The USD estimate is nil for these endpoints.
17
+ - Added Scribe v3 recorded transcription and Scribe v3 Live WebSocket sessions.
18
+
19
+ ## [1.1.0] - 2026-09-30
20
+
21
+ ### Added
22
+
23
+ - Eleven v4 support (`eleven_v4`, `eleven_v4_turbo`) across Text-to-Speech and Text-to-Dialogue
24
+ - `ElevenRb::ModelCapabilities` — per model-family table of honoured voice settings, max text length, SSML `<break>` support, audio-tag support and continuity support (`for`, `supported_voice_settings`, `max_text_length`, `supports?`)
25
+ - `Objects::VoiceSettings.for_model(model_id, overrides)` → `[settings, dropped_keys]`, building only the settings a model honours
26
+ - `Configuration#strict_voice_settings` (default `false`): raise `ValidationError` instead of warning when a voice setting the model ignores is passed
27
+ - Optional TTS keywords on `generate`, `stream` and `generate_with_timestamps` (omitted from the body when nil): `language_code`, `apply_text_normalization`, `seed`, `previous_text`, `next_text`, `previous_request_ids`, `next_request_ids`, `pronunciation_dictionary_locators`, `use_pvc_as_ivc`
28
+ - Response metadata: `Objects::Audio#request_id`, `#character_cost` (from the `request-id` / `character-cost` headers) and `#dropped_settings`; `on_audio_generated` also receives `request_id:` (nil for streams)
29
+ - `TextToSpeech#generate_with_timestamps` now also returns `normalized_alignment`, `request_id` and `character_cost`
30
+ - `TextToDialogue#generate_with_timestamps` (`POST /v1/text-to-dialogue/with-timestamps`) returning `audio`, `alignment`, `normalized_alignment`, `voice_segments` and `request_id`
31
+ - Text-to-Dialogue keywords `use_pvc_as_ivc`, `previous_text`, `future_text`, `previous_request_ids`, `next_request_ids`, `pronunciation_dictionary_locators`; a logger warning above `RECOMMENDED_MAX_TEXT_LENGTH` (2,000 characters)
32
+ - `HTTP::Client#post(..., with_meta: true)` returning `{ body:, headers: }`, and `Resources::Base#post_with_meta` / `#post_binary_with_meta`
33
+ - `Models#find(model_id)`
34
+ - `Objects::Model#model_rates`, `#maximum_text_length_per_request`, `#requires_alpha_access`, `#supported_voice_settings`
35
+ - `CostInfo::COST_PER_1K_CHARS` entries for `eleven_v4` ($0.30), `eleven_v4_turbo` ($0.15) and `eleven_v3_conversational` ($0.15)
36
+ - `opus_*` output formats map to the `ogg` extension and `audio/ogg` content type
37
+
38
+ ### Changed
39
+
40
+ - Voice settings are filtered per model: known keys a model ignores (`stability`, `similarity_boost`, `style`, `use_speaker_boost`, `speed` minus the model's supported set) are dropped from the request (logged, and listed on `audio.dropped_settings`); unknown voice-setting keys pass through untouched on every model, so a new API field is never swallowed. `eleven_v3` / `eleven_v4` now send only `stability` and `similarity_boost` by default; `eleven_multilingual_v2` requests are byte-identical to 1.0.0. Override keys are symbolized and nil values removed (a nil override is never reported as dropped)
41
+ - Text length is capped per model (`ModelCapabilities.max_text_length`): 5,000 for `eleven_v3`, 10,000 for `eleven_v4` and `eleven_multilingual_v2`, 30,000 / 40,000 for the flash and turbo models. `TextToSpeech::MAX_TEXT_LENGTH` stays defined but is no longer the cap
42
+ - `TextToDialogue::DEFAULT_MODEL` is now `eleven_v4`
43
+ - Text-to-Dialogue's hard text cap now follows the model (10,000 characters on `eleven_v4`, 5,000 on `eleven_v3`) instead of a flat 5,000; `TextToDialogue::MAX_TEXT_LENGTH` stays defined but is no longer the cap
44
+ - `Models#latest` returns `eleven_v4`, else `eleven_v3`, else the default model
45
+ - `TextToSpeech::OUTPUT_FORMATS` refreshed to the current list (documentation only, not validated)
46
+ - Callbacks that declare their keywords explicitly (no `**rest`) receive only the keywords they declare, so callbacks written for 1.0.0 keep working as new keywords are added
47
+
48
+ ### Fixed
49
+
50
+ - `Models#list` (and everything built on it: `get`, `default`, `latest`, `multilingual`, `turbo`, `tts_capable`, `ids`, `TTSAdapter#list_models`) recursed until `SystemStackError`, because `Models#get(model_id)` shadowed `Resources::Base#get`
51
+
10
52
  ## [1.0.0] - 2026-03-10
11
53
 
12
54
  ### Added
data/README.md CHANGED
@@ -11,6 +11,7 @@ A Ruby client for the [ElevenLabs](https://try.elevenlabs.io/qyk2j8gumrjz) Text-
11
11
  - Text-to-Speech generation and streaming
12
12
  - Speech-to-Speech voice conversion
13
13
  - Text-to-Dialogue multi-speaker generation with audio tags
14
+ - Eleven v4 support, with per-model voice-settings filtering and text caps
14
15
  - Sound effects generation from text descriptions
15
16
  - Music generation from prompts or composition plans
16
17
  - Voice management (list, get, create, update, delete)
@@ -74,7 +75,7 @@ audio.save_to_file("output.mp3")
74
75
  audio = client.tts.generate(
75
76
  "Hello world",
76
77
  voice_id: "voice_id",
77
- model_id: "eleven_v3", # Most expressive, 70+ languages, audio tags
78
+ model_id: "eleven_v4", # Most expressive; audio tags; see "Eleven v4" below
78
79
  voice_settings: {
79
80
  stability: 0.5,
80
81
  similarity_boost: 0.75
@@ -88,8 +89,83 @@ File.open("output.mp3", "wb") do |file|
88
89
  file.write(chunk)
89
90
  end
90
91
  end
92
+
93
+ # Character timestamps
94
+ result = client.tts.generate_with_timestamps("Hello world", voice_id: "voice_id")
95
+ result[:audio] # => ElevenRb::Objects::Audio
96
+ result[:alignment] # => { "characters" => [...], "character_start_times_seconds" => [...], ... }
97
+ result[:normalized_alignment]
98
+ result[:request_id] # from the request-id response header
99
+ result[:character_cost] # Integer, from the character-cost response header
100
+ ```
101
+
102
+ Optional keywords on `generate`, `stream` and `generate_with_timestamps` (each is left out of the request when nil):
103
+ `language_code`, `apply_text_normalization`, `seed`, `previous_text`, `next_text`, `previous_request_ids`,
104
+ `next_request_ids`, `pronunciation_dictionary_locators`, `use_pvc_as_ivc`.
105
+
106
+ The `audio_effects:` keyword on speech and dialogue calls accepts ElevenLabs’ effect settings.
107
+ Read the available presets with `client.audio_effects.catalog`. For incremental alignment use
108
+ `stream_with_timestamps` on either resource. Each yielded event is a hash with string keys.
109
+
110
+ ```ruby
111
+ client.tts.stream_with_timestamps("Hello world", voice_id: "voice_id") do |event|
112
+ output_io.write(Base64.strict_decode64(event.fetch("audio_base64")))
113
+ collect_alignment(event["alignment"])
114
+ end
91
115
  ```
92
116
 
117
+ ### Eleven v4
118
+
119
+ `eleven_v4` (and the cheaper, faster `eleven_v4_turbo`) accept up to 100,000 characters per Text to Speech request.
120
+
121
+ ```ruby
122
+ audio = client.tts.generate(
123
+ "[sighs] Right... let's try that one more time.",
124
+ voice_id: "voice_id",
125
+ model_id: "eleven_v4",
126
+ voice_settings: { stability: 0.5, similarity_boost: 0.75 },
127
+ seed: 42, # more consistent re-rolls
128
+ previous_text: "That did not go to plan.", # continuity with the take before
129
+ next_text: "Here we go." # ...and the one after
130
+ )
131
+ audio.request_id # pass as previous_request_ids: / next_request_ids: on neighbouring takes
132
+ audio.character_cost
133
+ audio.dropped_settings # => [] (voice settings the gem removed, see below)
134
+ ```
135
+
136
+ - **Use `stability` and `similarity_boost` for v4.** For a professional voice clone fine-tuned on v4, `clone_strength` (0–1) controls how closely the voice follows its training samples. Omitting it uses the voice’s stored setting. The API accepts `speed`, `style` and
137
+ `use_speaker_boost` on v4 and silently ignores them, so the gem drops them from the request, logs a
138
+ warning through `logger`, and lists them on `audio.dropped_settings`. Set
139
+ `strict_voice_settings: true` on the client to raise `ElevenRb::Errors::ValidationError` instead.
140
+ Only those known keys are ever dropped: a voice-setting key the gem does not know passes through
141
+ unchanged on every model, so new API fields keep working.
142
+ Pace a v4 take with the text (ellipses, pause tags), not `speed`.
143
+ - **SSML `<break time="…"/>` tags are ignored** by v4 (no pause is produced). Use an audio tag or
144
+ punctuation for pauses.
145
+ - **Audio tags** go in square brackets inside the text: `[sighs]`, `[whispers]`, `[laughs]`,
146
+ `[short pause]`. Note that tags appear in the returned alignment like any other characters.
147
+ - **Continuity**: `previous_text` / `next_text` (or `previous_request_ids` / `next_request_ids`) tell the
148
+ model what surrounds a take, so stitched takes keep a consistent delivery.
149
+ - **`seed`** can improve consistency across takes.
150
+
151
+ `ElevenRb::ModelCapabilities` answers these questions for any model id:
152
+
153
+ ```ruby
154
+ ElevenRb::ModelCapabilities.supported_voice_settings("eleven_v4") # => [:stability, :similarity_boost, :clone_strength]
155
+ ElevenRb::ModelCapabilities.max_text_length("eleven_v3") # => 5000
156
+ ElevenRb::ModelCapabilities.supports?("eleven_v4", :audio_tags) # => true
157
+ ElevenRb::ModelCapabilities.supports?("eleven_v4", :ssml_break) # => false
158
+ ```
159
+
160
+ | Model family | Voice settings honoured | Max chars | Audio tags | SSML breaks |
161
+ |---|---|---|---|---|
162
+ | `eleven_v4`, `eleven_v4_turbo` | stability, similarity_boost, clone_strength | 100,000 | yes | no |
163
+ | `eleven_v3` | stability, similarity_boost | 5,000 | yes | no |
164
+ | `eleven_v3_conversational` | stability, similarity_boost, use_speaker_boost | 5,000 | yes | no |
165
+ | `eleven_flash_v2_5`, `eleven_turbo_v2_5` | all five (incl. style, speed) | 40,000 | no | yes |
166
+ | `eleven_flash_v2`, `eleven_turbo_v2` | all five | 30,000 | no | yes |
167
+ | `eleven_multilingual_v2` and others | all five | 10,000 | no | yes |
168
+
93
169
  ### Speech-to-Speech
94
170
 
95
171
  ```ruby
@@ -123,30 +199,42 @@ audio = client.text_to_dialogue.generate([
123
199
  ])
124
200
  audio.save_to_file("dialogue.mp3")
125
201
 
126
- # With options
202
+ # With options (the default model is eleven_v4)
127
203
  audio = client.dialogue.generate(
128
204
  inputs,
129
- model_id: "eleven_v3",
205
+ model_id: "eleven_v4",
130
206
  language_code: "en",
131
- settings: { stability: 0.5 },
207
+ settings: { stability: 0.5, similarity: 0.75 }, # sent to the API unchanged
132
208
  seed: 42,
209
+ previous_text: "Earlier in the scene...",
133
210
  output_format: "mp3_44100_192"
134
211
  )
212
+
213
+ # With timestamps and per-speaker segments
214
+ result = client.dialogue.generate_with_timestamps(inputs)
215
+ result[:audio] # => ElevenRb::Objects::Audio
216
+ result[:alignment] # character timings
217
+ result[:voice_segments] # which voice speaks when
218
+ result[:request_id]
135
219
  ```
136
220
 
221
+ The gem applies a separate dialogue cap (10,000 characters for `eleven_v4`, 5,000 for `eleven_v3`); above
222
+ 2,000 characters the gem logs a warning, since shorter dialogue requests give more reliable results.
223
+
137
224
  ### Audio Tags
138
225
 
139
- The `eleven_v3` model supports inline audio tags for expressive speech:
226
+ The `eleven_v4` and `eleven_v3` models support inline audio tags, in square brackets, for expressive speech
227
+ (`ElevenRb::ModelCapabilities.supports?(model_id, :audio_tags)`):
140
228
 
141
229
  ```ruby
142
230
  audio = client.tts.generate(
143
231
  "[excited] Oh wow, this is AMAZING! [laughs] I can't believe it...",
144
232
  voice_id: "voice_id",
145
- model_id: "eleven_v3"
233
+ model_id: "eleven_v4"
146
234
  )
147
235
  ```
148
236
 
149
- Supported tags include `[laughs]`, `[whispers]`, `[sighs]`, `[excited]`, `[sarcastic]`, `[curious]`, `[pause]`, and more. Use CAPS for emphasis, `...` for pauses, and `—` for interruptions. See the [ElevenLabs v3 documentation](https://elevenlabs.io/docs/guides/audio-tags) for the full list.
237
+ Supported tags include `[laughs]`, `[whispers]`, `[sighs]`, `[excited]`, `[sarcastic]`, `[curious]`, `[short pause]`, and more. Use CAPS for emphasis, `...` for pauses, and `—` for interruptions. See the [ElevenLabs audio tags documentation](https://elevenlabs.io/docs/guides/audio-tags) for the full list.
150
238
 
151
239
  ### Sound Effects
152
240
 
@@ -198,10 +286,52 @@ end
198
286
  audio = client.generate_music("chill acoustic guitar")
199
287
  ```
200
288
 
289
+ Music defaults to `music_v2_5` and sound effects to `eleven_text_to_sound_v3`. Pass
290
+ `model_id:` to request a particular version. A saved v1 plan with `sections` converts
291
+ to v2 `chunks` during generation. Use `music.migrate_plan(plan)` to inspect the
292
+ converted plan. Source audio intervals become reference chunks. For a source with exclusion ranges, split the reference into chunks or pass `model_id: "music_v1"` to use the original format while available.
293
+
294
+ ```ruby
295
+ song = client.music.generate("Acoustic intro and chorus", store_for_inpainting: true)
296
+ edited = client.music.generate(composition_plan: { chunks: [
297
+ { song_id: song.song_id, range: { start_ms: 0, end_ms: 3000 } },
298
+ { text: "[Chorus]\nCome back home", duration_ms: 8000, positive_styles: ["acoustic"] }
299
+ ] })
300
+ uploaded = client.music.upload("previous-song.mp3") # song_id and extracted composition plan
301
+ tracks = client.music.video_to_music(videos: ["clip.mp4"], add_sfx: true, separate_tracks: true)
302
+ tracks.save_to_file("soundtrack.zip")
303
+ ```
304
+
305
+ Music and sound-effect callbacks include `credits` when the provider returns a charge
306
+ and `requested_duration_seconds` when the request specifies a duration. Their USD
307
+ `estimated_cost` is nil because per-account credit prices vary.
308
+
309
+ ### Transcription
310
+
311
+ ```ruby
312
+ transcript = client.scribe.transcribe("interview.mp3", diarize: true)
313
+ transcript.fetch("words").each { |word| puts [word["speaker_id"], word["text"]].join(" ") }
314
+
315
+ client.scribe.realtime(audio_format: "pcm_16000", include_timestamps: true) do |session|
316
+ session.send_audio(pcm_bytes, sample_rate: 16_000, commit: true)
317
+ loop do
318
+ event = session.read_event
319
+ break unless event
320
+ puts event["text"]
321
+ break if event["message_type"] == "committed_transcript_with_timestamps"
322
+ end
323
+ end
324
+ ```
325
+
326
+ `transcribe` accepts a path, a rewindable IO, or `source_url:`. The default models
327
+ are `scribe_v3` for recordings and `scribe_v3_live` for live transcription. A block
328
+ closes the live session automatically. A caller that opens a session without a block
329
+ must call `close`. The live API returns provider errors as events with a `message_type`.
330
+
201
331
  ### Voice Management
202
332
 
203
333
  ```ruby
204
- # List all voices
334
+ # Collect all pages from the v2 voices endpoint
205
335
  voices = client.voices.list
206
336
  voices.each { |v| puts v.display_name }
207
337
 
@@ -289,7 +419,7 @@ client = ElevenRb::Client.new(
289
419
  Sentry.capture_exception(error, extra: { path: path })
290
420
  },
291
421
 
292
- # Cost tracking
422
+ # Cost tracking (add request_id: to also receive the API's request id)
293
423
  on_audio_generated: ->(audio:, voice_id:, text:, cost_info:) {
294
424
  UsageRecord.create!(
295
425
  characters: cost_info[:character_count],
@@ -311,8 +441,11 @@ client = ElevenRb::Client.new(
311
441
  models = client.models.list
312
442
  models.each { |m| puts "#{m.name} (#{m.model_id})" }
313
443
 
314
- # Get the latest/most capable model
315
- client.models.latest # => "eleven_v3"
444
+ # Find one model
445
+ client.models.find("eleven_v4") # => ElevenRb::Objects::Model (get is an alias)
446
+
447
+ # Get the latest/most capable model: eleven_v4, else eleven_v3, else the default
448
+ client.models.latest.model_id # => "eleven_v4"
316
449
 
317
450
  # Get multilingual models
318
451
  client.models.multilingual
@@ -343,7 +476,8 @@ client = ElevenRb::Client.new(
343
476
  open_timeout: 10, # Connection timeout
344
477
  max_retries: 3, # Max retry attempts
345
478
  retry_delay: 1.0, # Base delay between retries
346
- logger: Rails.logger # Optional logger
479
+ logger: Rails.logger, # Optional logger (receives dropped-setting warnings)
480
+ strict_voice_settings: false # true: raise instead of dropping settings a model ignores
347
481
  )
348
482
  ```
349
483
 
@@ -28,6 +28,10 @@ module ElevenRb
28
28
 
29
29
  # Trigger a callback if it's configured
30
30
  #
31
+ # A callback that names its keywords explicitly (no `**rest`) receives only
32
+ # the keywords it declares, so callbacks written before a keyword was added
33
+ # (e.g. `request_id:` on on_audio_generated in 1.1.0) keep working.
34
+ #
31
35
  # @param callback_name [Symbol] the name of the callback
32
36
  # @param kwargs [Hash] keyword arguments to pass to the callback
33
37
  # @return [Object, nil] the return value of the callback, or nil
@@ -36,12 +40,32 @@ module ElevenRb
36
40
  return unless callback.respond_to?(:call)
37
41
 
38
42
  begin
39
- callback.call(**kwargs)
43
+ callback.call(**accepted_callback_kwargs(callback, kwargs))
40
44
  rescue StandardError => e
41
45
  # Don't let callback errors break the main flow
42
46
  warn "[ElevenRb] Callback error in #{callback_name}: #{e.message}"
43
47
  nil
44
48
  end
45
49
  end
50
+
51
+ private
52
+
53
+ def accepted_callback_kwargs(callback, kwargs)
54
+ params = callback_parameters(callback)
55
+ return kwargs if params.nil? || params.any? { |type, _| type == :keyrest }
56
+
57
+ accepted = params.filter_map { |type, name| name if %i[key keyreq].include?(type) }
58
+ return kwargs if accepted.empty?
59
+
60
+ kwargs.slice(*accepted)
61
+ end
62
+
63
+ def callback_parameters(callback)
64
+ return callback.parameters if callback.respond_to?(:parameters)
65
+
66
+ callback.method(:call).parameters
67
+ rescue NameError
68
+ nil
69
+ end
46
70
  end
47
71
  end
@@ -86,6 +86,16 @@ module ElevenRb
86
86
  @speech_to_speech ||= Resources::SpeechToSpeech.new(http_client)
87
87
  end
88
88
  alias sts speech_to_speech
89
+ alias voice_changer speech_to_speech
90
+
91
+ def audio_effects
92
+ @audio_effects ||= Resources::AudioEffects.new(http_client)
93
+ end
94
+
95
+ def speech_to_text
96
+ @speech_to_text ||= Resources::SpeechToText.new(http_client)
97
+ end
98
+ alias scribe speech_to_text
89
99
 
90
100
  # Sound effects resource
91
101
  #
@@ -21,12 +21,13 @@ module ElevenRb
21
21
  open_timeout: 10,
22
22
  max_retries: 3,
23
23
  retry_delay: 1.0,
24
- retry_statuses: [429, 500, 502, 503, 504].freeze
24
+ retry_statuses: [429, 500, 502, 503, 504].freeze,
25
+ strict_voice_settings: false
25
26
  }.freeze
26
27
 
27
28
  attr_accessor :api_key, :base_url, :timeout, :open_timeout,
28
29
  :max_retries, :retry_delay, :retry_statuses,
29
- :logger
30
+ :logger, :strict_voice_settings
30
31
 
31
32
  # Initialize a new configuration
32
33
  #
@@ -39,6 +40,8 @@ module ElevenRb
39
40
  # @option options [Float] :retry_delay Base delay between retries in seconds (default: 1.0)
40
41
  # @option options [Array<Integer>] :retry_statuses HTTP status codes to retry (default: [429, 500, 502, 503, 504])
41
42
  # @option options [Logger] :logger Logger instance for debug output
43
+ # @option options [Boolean] :strict_voice_settings Raise instead of warn when a voice setting the
44
+ # model does not honour is passed (default: false)
42
45
  # @option options [Proc] :on_request Callback before each request
43
46
  # @option options [Proc] :on_response Callback after successful response
44
47
  # @option options [Proc] :on_error Callback when an error occurs
@@ -87,7 +90,8 @@ module ElevenRb
87
90
  timeout: timeout,
88
91
  open_timeout: open_timeout,
89
92
  max_retries: max_retries,
90
- retry_delay: retry_delay
93
+ retry_delay: retry_delay,
94
+ strict_voice_settings: strict_voice_settings
91
95
  }
92
96
  end
93
97
  end
@@ -2,6 +2,8 @@
2
2
 
3
3
  require 'httparty'
4
4
  require 'json'
5
+ require 'net/http/post/multipart'
6
+ require 'mini_mime'
5
7
 
6
8
  module ElevenRb
7
9
  module HTTP
@@ -32,9 +34,11 @@ module ElevenRb
32
34
  # @param path [String] the API path
33
35
  # @param body [Hash] request body
34
36
  # @param response_type [Symbol] :json or :binary
35
- # @return [Hash, Array, String] parsed response
36
- def post(path, body = {}, response_type: :json)
37
- request(:post, path, body: body, response_type: response_type)
37
+ # @param with_meta [Boolean] when true, return `{ body:, headers: }` instead of the body alone
38
+ # (headers as a Hash of lower-cased String keys to String values)
39
+ # @return [Hash, Array, String] parsed response (or `{ body:, headers: }` with with_meta)
40
+ def post(path, body = {}, response_type: :json, with_meta: false)
41
+ request(:post, path, body: body, response_type: response_type, with_meta: with_meta)
38
42
  end
39
43
 
40
44
  # Make a DELETE request
@@ -51,8 +55,9 @@ module ElevenRb
51
55
  # @param params [Hash] form parameters including files
52
56
  # @param response_type [Symbol] :json or :binary
53
57
  # @return [Hash, String] parsed JSON or binary response
54
- def post_multipart(path, params, response_type: :json)
55
- request(:post, path, body: params, multipart: true, response_type: response_type)
58
+ def post_multipart(path, params, response_type: :json, with_meta: false, &block)
59
+ request(:post, path, body: params, multipart: true, response_type: response_type,
60
+ with_meta: with_meta, stream: !block.nil?, &block)
56
61
  end
57
62
 
58
63
  # Make a streaming POST request
@@ -68,9 +73,9 @@ module ElevenRb
68
73
  private
69
74
 
70
75
  def request(method, path, body: nil, params: nil, response_type: :json, multipart: false, stream: false,
71
- attempt: 1, &block)
76
+ attempt: 1, with_meta: false, &block)
72
77
  config.validate!
73
- url = "#{config.base_url}#{path}"
78
+ url = url_for(path)
74
79
  start_time = Time.now
75
80
 
76
81
  # Trigger before request callback
@@ -80,21 +85,17 @@ module ElevenRb
80
85
  response = execute_request(method, url, body, params, multipart, stream, &block)
81
86
  duration = ((Time.now - start_time) * 1000).round(2)
82
87
 
83
- # For streaming, we've already processed the data
84
- return nil if stream
85
-
86
88
  # Trigger after response callback
87
89
  config.trigger(:on_response, method: method, path: path, response: response, duration: duration)
88
90
 
89
- # Return binary data directly
90
- return response.body if response_type == :binary && response.success?
91
+ return normalize_headers(response) if stream
91
92
 
92
- handle_response(response)
93
+ build_result(response, response_type, with_meta)
93
94
  rescue Errors::RateLimitError => e
94
95
  config.trigger(:on_rate_limit, retry_after: e.retry_after, error: e)
95
- handle_retry(e, method, path, body, params, response_type, multipart, stream, attempt, &block)
96
+ handle_retry(e, method, path, body, params, response_type, multipart, stream, attempt, with_meta, &block)
96
97
  rescue Errors::ServerError => e
97
- handle_retry(e, method, path, body, params, response_type, multipart, stream, attempt, &block)
98
+ handle_retry(e, method, path, body, params, response_type, multipart, stream, attempt, with_meta, &block)
98
99
  rescue Errors::Base => e
99
100
  config.trigger(:on_error, error: e, method: method, path: path,
100
101
  context: { body: sanitize_body_for_logging(body) })
@@ -107,22 +108,42 @@ module ElevenRb
107
108
  end
108
109
  end
109
110
 
111
+ def url_for(path)
112
+ base = config.base_url.delete_suffix('/')
113
+ base = base.sub(%r{/v\d+\z}, '') if path.match?(%r{\A/v\d+/})
114
+ "#{base}#{path}"
115
+ end
116
+
117
+ def build_result(response, response_type, with_meta)
118
+ # Return binary data directly
119
+ result = if response_type == :binary && response.success?
120
+ response.body
121
+ else
122
+ handle_response(response)
123
+ end
124
+
125
+ with_meta ? { body: result, headers: normalize_headers(response) } : result
126
+ end
127
+
110
128
  def execute_request(method, url, body, params, multipart, stream, &block)
111
- options = build_options(body, params, multipart, stream, &block)
112
-
113
- case method
114
- when :get
115
- self.class.get(url, options)
116
- when :post
117
- self.class.post(url, options)
118
- when :delete
119
- self.class.delete(url, options)
120
- else
121
- raise ArgumentError, "Unknown HTTP method: #{method}"
129
+ options = build_options(body, params, multipart)
130
+ if stream
131
+ error_body = +''.b
132
+ response = self.class.post(url, options.merge(stream_body: true)) do |fragment|
133
+ if (200..299).cover?(fragment.code)
134
+ block.call(fragment.to_s)
135
+ elsif error_body.bytesize < 65_536
136
+ error_body << fragment.to_s.b.byteslice(0, 65_536 - error_body.bytesize)
137
+ end
138
+ end
139
+ handle_error_response(response, error_body) unless response.success?
140
+ return response
122
141
  end
142
+
143
+ self.class.public_send(method, url, options)
123
144
  end
124
145
 
125
- def build_options(body, params, multipart, stream, &block)
146
+ def build_options(body, params, multipart)
126
147
  options = {
127
148
  headers: headers(multipart),
128
149
  timeout: config.timeout,
@@ -131,17 +152,17 @@ module ElevenRb
131
152
 
132
153
  options[:query] = params if params && !params.empty?
133
154
 
134
- if body && !body.empty?
135
- options[:body] = if multipart
136
- build_multipart_body(body)
137
- else
138
- body.to_json
139
- end
140
- end
141
-
142
- if stream && block_given?
143
- options[:stream_body] = true
144
- options[:on_data] = block
155
+ if multipart
156
+ fields = body.transform_values do |value|
157
+ value.is_a?(Array) ? value.map { |item| multipart_value(item) } : multipart_value(value)
158
+ end
159
+ parts = fields.key?(:additional_formats) ? { additional_formats: { 'Content-Type' => 'application/json' } } : {}
160
+ form = Net::HTTP::Post::Multipart.new('/', fields, parts: parts)
161
+ options[:body_stream] = form.body_stream
162
+ options[:headers]['Content-Type'] = form['Content-Type']
163
+ options[:headers]['Content-Length'] = form['Content-Length']
164
+ elsif body && !body.empty?
165
+ options[:body] = body.to_json
145
166
  end
146
167
 
147
168
  options
@@ -156,22 +177,14 @@ module ElevenRb
156
177
  h
157
178
  end
158
179
 
159
- def build_multipart_body(params)
160
- body = {}
180
+ def multipart_value(value)
181
+ return value unless value.respond_to?(:read)
161
182
 
162
- params.each do |key, value|
163
- case key.to_sym
164
- when :files
165
- # Handle file array
166
- Array(value).each_with_index do |file, index|
167
- body["files[#{index}]"] = file
168
- end
169
- else
170
- body[key.to_s] = value
171
- end
172
- end
173
-
174
- body
183
+ value.rewind
184
+ path = value.respond_to?(:path) && value.path ? File.basename(value.path) : 'upload.bin'
185
+ filename = path.gsub(/["\r\n]/, '_')
186
+ type = MiniMime.lookup_by_filename(filename)&.content_type || 'application/octet-stream'
187
+ Multipart::Post::UploadIO.new(value, type, filename)
175
188
  end
176
189
 
177
190
  def handle_response(response)
@@ -180,9 +193,10 @@ module ElevenRb
180
193
  handle_error_response(response)
181
194
  end
182
195
 
183
- def handle_error_response(response)
196
+ def handle_error_response(response, raw_body = response.body)
184
197
  status = response.code
185
- body = parse_error_body(response.body)
198
+ body = parse_json(raw_body)
199
+ body = { 'message' => body.to_s } unless body.is_a?(Hash)
186
200
  message = extract_error_message(body)
187
201
 
188
202
  error_class = case status
@@ -210,7 +224,7 @@ module ElevenRb
210
224
  raise error_class.new(message, **error_kwargs)
211
225
  end
212
226
 
213
- def handle_retry(error, method, path, body, params, response_type, multipart, stream, attempt, &block)
227
+ def handle_retry(error, method, path, body, params, response_type, multipart, stream, attempt, with_meta, &block)
214
228
  raise error if attempt > config.max_retries || !config.retry_statuses.include?(error.http_status)
215
229
 
216
230
  delay = if error.is_a?(Errors::RateLimitError) && error.retry_after
@@ -224,7 +238,17 @@ module ElevenRb
224
238
  sleep(delay)
225
239
 
226
240
  request(method, path,
227
- body: body, params: params, response_type: response_type, multipart: multipart, stream: stream, attempt: attempt + 1, &block)
241
+ body: body, params: params, response_type: response_type, multipart: multipart, stream: stream,
242
+ attempt: attempt + 1, with_meta: with_meta, &block)
243
+ end
244
+
245
+ # Response headers as a plain Hash of lower-cased String keys to String values
246
+ # (HTTParty exposes multi-value arrays; the first value is kept)
247
+ def normalize_headers(response)
248
+ raw = response.headers.respond_to?(:to_hash) ? response.headers.to_hash : response.headers.to_h
249
+ raw.each_with_object({}) do |(key, value), out|
250
+ out[key.to_s.downcase] = value.is_a?(Array) ? value.first : value
251
+ end
228
252
  end
229
253
 
230
254
  def wrap_error(error)
@@ -246,10 +270,6 @@ module ElevenRb
246
270
  {}
247
271
  end
248
272
 
249
- def parse_error_body(body)
250
- parse_json(body)
251
- end
252
-
253
273
  def extract_error_message(body)
254
274
  detail = body['detail']
255
275
  case detail
@@ -263,16 +283,12 @@ module ElevenRb
263
283
  end
264
284
 
265
285
  def sanitize_body_for_logging(body)
266
- return nil if body.nil?
267
-
268
286
  # Remove any sensitive data or large binary content
269
- if body.is_a?(Hash)
270
- body.transform_values do |v|
271
- v.is_a?(File) ? "[FILE: #{v.path}]" : v
272
- end
273
- else
274
- body
275
- end
287
+ return body.map { |item| sanitize_body_for_logging(item) } if body.is_a?(Array)
288
+ return body.transform_values { |item| sanitize_body_for_logging(item) } if body.is_a?(Hash)
289
+ return '[FILE]' if body.respond_to?(:read)
290
+
291
+ body
276
292
  end
277
293
  end
278
294
  end