The official Ruby SDK for ElevenLabs. ElevenLabs brings the most compelling, rich and lifelike voices to creators and developers in just a few lines of code.
Check out the HTTP API documentation. A full reference for this library is available here.
This SDK requires Ruby >= 3.3.
gem install elevenlabs-ruby-sdkOr add it to your Gemfile:
gem "elevenlabs-ruby-sdk"-
Eleven v4 (
eleven_v4)- Highest quality and most expressive speech, with reliable voice cloning across long generations
- 90+ languages with consistent voice quality across language switches
- Up to 10,000 characters (~10 minutes of audio) per request
- Used via the Text to Dialogue API
-
Eleven v4 Turbo (
eleven_v4_turbo)- State-of-the-art real-time speech, with a median latency of ~100ms
- 90+ languages
- Ideal for voice agents and other latency-sensitive use cases
-
Eleven Multilingual v2 (
eleven_multilingual_v2)- Excels in stability, language diversity, and accent accuracy
- The most stable choice for long-form Text to Speech
- Supports 29 languages
-
Eleven Flash v2.5 (
eleven_flash_v2_5)- Ultra-low latency and lowest cost
- Supports 32 languages
For more detailed information about these models and others, visit the ElevenLabs Models documentation.
Instantiate and use the client with the following:
require "elevenlabs"
# Reads the API key from the ELEVENLABS_API_KEY environment variable.
# Pass it explicitly with Elevenlabs::Client.new(api_key: "YOUR_API_KEY") if you prefer.
client = Elevenlabs::Client.new
audio = client.text_to_speech.convert(
voice_id: "JBFqnCBsd6RMkjVDRZzb",
text: "The first move is what sets everything in motion.",
model_id: "eleven_multilingual_v2",
output_format: "mp3_44100_128"
)
# The response is a lazy stream. `read` returns the whole body in one call.
File.binwrite("output.mp3", audio.read)Eleven v4 and Eleven v4 Turbo are served through the Text to Dialogue API, which turns a list of speaker turns into a single expressive audio stream.
audio = client.text_to_dialogue.convert(
model_id: "eleven_v4",
output_format: "mp3_44100_128",
inputs: [
Elevenlabs::Types::DialogueInput.new(text: "[giggling] Knock knock", voice_id: "JBFqnCBsd6RMkjVDRZzb"),
Elevenlabs::Types::DialogueInput.new(text: "[curious] Who is there?", voice_id: "Aw4FAjKCGjjNkVhN1Xmq")
]
)
# Write each chunk as it arrives.
File.open("dialogue.mp3", "wb") do |file|
audio.each { |chunk| file.write(chunk) }
endList all your available voices with search.
response = client.voices.search
response.voices.each do |voice|
puts voice.name
endFor information about the structure of the voices output, please refer to the official ElevenLabs API documentation for Get Voices.
Stream audio in real-time, as it's being generated. convert and stream both return a lazy,
single-use Enumerator of binary chunks: the request is sent on the first iteration and each chunk
is yielded as it arrives, so playback or a file write can start before the server has finished.
audio = client.text_to_speech.stream(
voice_id: "JBFqnCBsd6RMkjVDRZzb",
text: "This is a... streaming voice.",
model_id: "eleven_multilingual_v2",
output_format: "mp3_44100_128"
)
audio.each do |chunk|
# Process each chunk as it arrives.
$stdout.write(chunk)
endIterating the stream a second time raises rather than re-sending the request. Call read to get the
whole body as one binary String instead, or to_a on the first pass to keep the chunks.
Image, video and text-to-speech generations, and template runs, finish asynchronously: create
returns at once and you poll get until the status is completed or failed. create_and_wait
does both. It takes the same parameters as create and returns the finished generation or run.
require "elevenlabs"
require "elevenlabs/flows/create_and_wait"
client = Elevenlabs::Client.new
image = client.flows.image.create_and_wait(
model_id: "gpt-image-2",
prompt: "A lighthouse at dusk",
wait_timeout_in_seconds: 300
)
puts image.content_url if image.status.to_s == "completed"
run = client.flows.templates.runs.create_and_wait(template_id: "TEMPLATE_ID", inputs: { "prompt" => "A lighthouse" })client.flows.video and client.flows.text_to_speech have the same method.
- Between status checks it waits as long as the server's
Retry-Afterheader asks, never less thanmin_poll_interval_in_seconds(default 3, at least 0.5), plus up to 20% jitter. wait_timeout_in_secondsbounds the whole wait. It defaults tonil, which waits indefinitely;0gives up straight after the create. When it runs out,Elevenlabs::Flows::FlowsWaitTimeoutErroris raised with theid(andtemplate_idfor a run) and thelast_response. The work keeps running: callgetto keep waiting.- A
failedgeneration or run is returned, not raised. Checkstatus. request_optionsapply to every request, exceptadditional_body_parameters, which only the create sends.
This is meant for scripts and quickstarts. In production, pass webhook to create and handle the
webhook event instead of holding a process open.
POST /v1/music/detailed returns the song's metadata and its audio file in one multipart/mixed
response. Require elevenlabs/music/compose_detailed and client.music.compose_detailed splits it for
you (without it, the method returns the raw multipart body):
require "elevenlabs"
require "elevenlabs/music/compose_detailed"
song = client.music.compose_detailed(
prompt: "Epic orchestral music with dramatic strings and powerful brass",
music_length_ms: 60_000,
)
puts song.json["song_metadata"]["title"]
File.binwrite(song.filename, song.audio)jsonis the metadata part as the API sends it:composition_plan,song_metadataandwords_timestamps.audiois the audio file's bytes andfilenamethe name the API suggests for it.song_idis set when the request passesstore_for_inpainting: true.
Require elevenlabs/agent_tools to define agent tools as chained Ruby instead of hand-written JSON.
build validates the tool and returns the Elevenlabs::Types::ToolRequestModel that
client.agents.tools.create and update accept; to_json_string writes the API format the
ElevenLabs CLI keeps in tool_configs/*.json.
require "elevenlabs"
require "elevenlabs/agent_tools"
include Elevenlabs::AgentTools
get_order = Tool.webhook("get_order", "Look up an order by the number the caller gives")
.get("https://api.example.com/orders/{order_id}")
.path_param("order_id", Schema.string.describe("The order number, e.g. A-1042"))
.query_param("include", Schema.string.constant("items"))
.header("Authorization", Header.secret("sec_orders_api"))
.assign("order_status", "order.status")
.options(response_timeout_secs: 10, pre_tool_speech: "force")
refund = Tool.webhook("issue_refund", "Refund an order the caller asked to return")
.post("https://api.example.com/refunds")
.body(
Schema.object
.property("order_id", Schema.string.from_variable("order_id"))
.property("reason", Schema.string.describe("Why the caller wants a refund").choices(%w[damaged late other]))
.property("note", Schema.string.describe("Anything else the caller said").optional)
)
transfer = SystemTool.transfer_to_number
.transfer("Caller asks for billing", Destination.phone("+15551234567"))
.transfer("Caller asks for a manager", Destination.sip_variable("manager_sip"), transfer_type: "sip_refer")
tool = client.agents.tools.create(**get_order.build.to_h)
File.write("tool_configs/issue_refund.json", refund.to_json_string)Tool.client(name, description)builds a client tool, withparam(name, schema)for its parameters.SystemTool.end_call,skip_turn,language_detection,play_keypad_touch_tone,voicemail_detection,knowledge_base,transfer_to_numberandtransfer_to_agentbuild system tools.Destinationis the workflow builder's, so both builders take the same destinations.- Every literal needs exactly one value source:
describe(the LLM provides it),from_variable,constant,system_providedoromit. Properties are required unless markedoptional. Schemas are values, so one can be reused across tools. - Webhook and client tools are created with
tools.createand attached to an agent by id inprompt.tool_ids. A system tool'sbuild_configis its entry in the agent'sprompt.built_in_tools. buildraisesElevenlabs::AgentTools::ToolValidationErrorlisting every problem at once; each issue has acode, amessageand apath. Passon_warning:to see warnings.Tool.from_jsonloads a tool config (a JSON string or a hash, or a request with atool_configkey) andTool.from_responsethe result oftools.get, so a tool can be edited and written back. Fields the builder doesn't model, and tool types it has no constructor for, round-trip unchanged.
Require elevenlabs/agent_builder to define a whole agent (its settings, its tools and its workflow) in
one place, and push it with client.agents.push, which creates or updates the tools and the agent in one
call. AgentProject reads and writes the ElevenLabs CLI's project layout, so a repo works with both the
SDK and the CLI.
require "elevenlabs"
require "elevenlabs/agent_builder"
include Elevenlabs::AgentBuilder
include Elevenlabs::AgentTools
include Elevenlabs::AgentWorkflows
show_order = Tool.client("show_order", "Show the order card")
.param("order_id", Schema.string.from_variable("order_id"))
wf = Workflow.new
wf.converse("triage", "Find out what the caller needs")
.when("Caller gave an order number")
.tool("lookup", [get_order]) # a Tool object: push fills in its id
.on_success
.converse("resolve", "Explain the order status")
agent = Agent.new(
"Support line",
prompt: "You are a support agent for Acme.",
first_message: "Hi, how can I help?",
tools: [SystemTool.end_call, show_order],
workflow: wf,
)
result = client.agents.push(agent) # creates get_order, show_order and the agent
client.agents.push(agent, agent_id: result.agent_id) # later: updates only what changed
project = AgentProject.open(".") # agents.json, tools.json, agent_configs/, tool_configs/
client.agents.push(agent, project: project) # the project records and reuses the ids
pulled = client.agents.pull("agent_123", project: project)pushvalidates first, so an invalid agent writes nothing. A tool counts as already on the server when the project records its id or, without a project, when the agent (agent_id) already uses a tool of that name. Tools other agents use are never touched. Unchanged tools aren't sent; tools the agent no longer uses are reported as"detached", not deleted.branch_id:andversion_description:update a branch or describe the new version.pushreturns anAgentPushResultwithagent_id,action("created"or"updated") andtools, each tool'sidandactionby name. If a request fails partway, it raisesAgentPushErrorwhoseresultlists what was already written; a project opened from a directory is saved even then.tool_ids:attaches existing tools by id, as they are.conversation_config:andplatform_settings:take any other setting, as the generated models or wire-format hashes, merged under the typed options.agent.validatechecks everything that needs no API key, raisingAgentValidationError(each issue has acode, amessageand apath).to_json(tool_ids:)gives the API-format config andbuild(tool_ids:)the generated create request.Agent.from_json(config, tools_by_id:)loads a CLIagent_configs/*.jsonfile. Settings the SDK doesn't model are kept and pushed.pullloads a live agent the same way, with its webhook and client tools asToolobjects, and writes it into the project if one is given.- Project files use the CLI's format (4-space JSON, sorted keys in config files, owner-only permissions).
Files nothing changed keep their exact text. YAML and TOML configs aren't supported yet and raise
AgentProjectError.
This SDK allows you to configure different environments for API requests. It defaults to the production environment.
client = Elevenlabs::Client.new(
base_url: Elevenlabs::Environment::PRODUCTION_US
)Available environments:
Elevenlabs::Environment::PRODUCTIONElevenlabs::Environment::PRODUCTION_USElevenlabs::Environment::PRODUCTION_EUElevenlabs::Environment::PRODUCTION_INDIAElevenlabs::Environment::PRODUCTION_SINGAPORE
When the API returns a non-success status code (4xx or 5xx), the SDK raises a subclass of
Elevenlabs::Errors::ResponseError. The HTTP status code is available via #code and the raw
response body via #body. Specific status codes raise named subclasses (for example
Elevenlabs::Errors::NotFoundError for a 404), so you can rescue the one you care about.
begin
client.text_to_speech.convert(...)
rescue Elevenlabs::Errors::NotFoundError => e
# Handle a 404 specifically.
rescue Elevenlabs::Errors::ResponseError => e
puts "API error occurred: #{e.message}"
puts "Status code: #{e.code}"
puts "Response body: #{e.body}"
# Optionally, re-raise the exception or handle accordingly.
endThe SDK is instrumented with automatic retries with exponential backoff. A request will be retried as long as the request is deemed retryable and the number of retry attempts has not grown larger than the configured retry limit (default: 2).
A request is deemed retryable when any of the following HTTP status codes is returned:
Configure the limit on the client:
client = Elevenlabs::Client.new(max_retries: 3)The open, read and write timeout defaults to 60 seconds. Set it on the client, or per call:
client = Elevenlabs::Client.new(timeout: 10)
client.text_to_speech.convert(..., request_options: { timeout: 2.5 })A request that exhausts its retries after timing out raises Elevenlabs::Errors::TimeoutError, and
one that never reached the server at all — refused connection, unresolvable host, failed TLS
handshake — raises Elevenlabs::Errors::ConnectionError. Both are subclasses of
Elevenlabs::Errors::ApiError, carry no status code (there was no response), and keep the underlying
transport exception on #cause.
Requests to a plain http:// URL are refused unless the host is localhost, so credentials are
never sent unencrypted by mistake. To reach a trusted http-only host, such as an internal proxy, opt
in on the client:
client = Elevenlabs::Client.new(
base_url: "http://proxy.internal:8080",
allow_insecure_http: true
)Every method accepts a request_options: hash to override behavior for a single call — a different
base URL, additional headers, or additional query parameters:
client.text_to_speech.convert(
...,
request_options: {
base_url: "https://staging.example.com",
timeout: 5,
additional_headers: { "X-Custom-Header" => "value" },
additional_query_parameters: { "trace" => "true" }
}
)client.dubbing.live(...) opens a connection and returns a DubbingSocket. Send with its typed
methods (or send), iterate the socket to read messages until the server closes it, and call close
when done. Passing a block connects the socket, yields it, and closes it automatically when the block
returns:
client.dubbing.live(target_language: "es", source_language: "en") do |socket|
socket.send_publish(...)
socket.each do |message|
# Handle each message.
end
endThe SDK has one socket per channel:
client.dubbing.livereturns aDubbingSocketclient.text_to_speech.realtimereturns aTextToSpeechSocketclient.text_to_dialogue.realtimereturns aTextToDialogueSocketclient.speech_to_text.realtimereturns aSpeechToTextSocketclient.speech_engine.upstreamreturns aSpeechEngineSocketclient.text_to_dialogue_multi_context.realtimereturns aTextToDialogueMultiContextSocketclient.text_to_speech_multi_context.realtimereturns aTextToSpeechMultiContextSocketclient.translation.realtimereturns aTranslationSocket
Reading blocks the thread, so run sockets in a CLI worker or a background thread, not inside a web request.
With no timeout, each and recv wait for the next message until the connection closes, so they
can hang on a server that goes quiet. Pass timeout: (seconds) to recv to give a read a deadline;
it returns nil when the timeout passes or the connection closes, and the connection stays usable:
socket = client.dubbing.live(target_language: "es", source_language: "en")
begin
while (message = socket.recv(timeout: 5))
# Handle each message.
end
ensure
socket.close
endExplore all models & languages.
While we value open-source contributions to this SDK, this library is generated programmatically. Additions made directly to this library would have to be moved over to our generation code, otherwise they would be overwritten upon the next generated release. Feel free to open a PR as a proof of concept, but know that we will not be able to merge it as-is. We suggest opening an issue first to discuss with us!
On the other hand, contributions to the README are always very welcome!
