elevenlabs

package module
v1.0.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 25, 2026 License: MIT Imports: 11 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README ยถ

ElevenLabs Go Library

LOGO

fern shield Discord Twitter Go Reference

The official Go SDK for ElevenLabs. ElevenLabs brings the most compelling, rich and lifelike voices to creators and developers in just a few lines of code.

๐Ÿ“– API & Docs

Check out the HTTP API documentation. A full reference for this library is available here.

Requirements

This SDK requires Go 1.22 or later.

Install

go get github.com/elevenlabs/elevenlabs-go

Usage

Main Models
  1. 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
  2. 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
  3. 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
  4. 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:

package main

import (
	"context"
	"io"
	"log"
	"os"

	elevenlabs "github.com/elevenlabs/elevenlabs-go"
	elevenlabsclient "github.com/elevenlabs/elevenlabs-go/client"
	"github.com/elevenlabs/elevenlabs-go/types"
)

func main() {
	// Reads the API key from the ELEVENLABS_API_KEY environment variable.
	// Pass it explicitly with option.WithApiKey(elevenlabs.String("YOUR_API_KEY")) if you prefer.
	client := elevenlabsclient.NewClient()

	audio, err := client.TextToSpeech.Convert(
		context.Background(),
		"JBFqnCBsd6RMkjVDRZzb",
		&types.BodyTextToSpeechFull{
			Text:         "The first move is what sets everything in motion.",
			ModelId:      elevenlabs.String("eleven_multilingual_v2"),
			OutputFormat: types.ConvertTextToSpeechRequestOutputFormatMp344100128.Ptr(),
		},
	)
	if err != nil {
		log.Fatal(err)
	}

	file, err := os.Create("output.mp3")
	if err != nil {
		log.Fatal(err)
	}
	defer file.Close()

	// The response body streams as it arrives. io.Copy writes it to the file until the end.
	if _, err := io.Copy(file, audio); err != nil {
		log.Fatal(err)
	}
}

NewClient falls back to ELEVENLABS_API_KEY only when no key is passed. To set the key in code, use option.WithApiKey from github.com/elevenlabs/elevenlabs-go/option:

client := elevenlabsclient.NewClient(
	option.WithApiKey(elevenlabs.String("YOUR_API_KEY")),
)

Optional fields are pointers. elevenlabs.String, elevenlabs.Int, elevenlabs.Bool and the other helpers in the root package take a value and return a pointer to it, and enum constants in the types package have a Ptr() method.

Text to Dialogue (Eleven v4)

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, err := client.TextToDialogue.Convert(ctx, &types.BodyTextToDialogueMultiVoiceV1TextToDialoguePost{
	ModelId:      elevenlabs.String("eleven_v4"),
	OutputFormat: elevenlabs.String("mp3_44100_128"),
	Inputs: []*types.DialogueInput{
		{Text: "[giggling] Knock knock", VoiceId: "JBFqnCBsd6RMkjVDRZzb"},
		{Text: "[curious] Who is there?", VoiceId: "Aw4FAjKCGjjNkVhN1Xmq"},
	},
})
if err != nil {
	return err
}

file, err := os.Create("dialogue.mp3")
if err != nil {
	return err
}
defer file.Close()

_, err = io.Copy(file, audio)
return err
Music with metadata

client.Music.ComposeDetailedParsed composes a song and returns its metadata and audio file as separate fields. It takes the same arguments as ComposeDetailed. The API answers with a multipart/mixed body (a JSON part, then the audio), which the generated ComposeDetailed can't decode.

song, err := client.Music.ComposeDetailedParsed(ctx, &types.BodyComposeMusicWithADetailedResponseV1MusicDetailedPost{
	Prompt:        elevenlabs.String("Epic orchestral music with dramatic strings"),
	MusicLengthMs: elevenlabs.Int(60000),
})
if err != nil {
	return err
}

metadata, _ := song.JSON["song_metadata"].(map[string]any)
fmt.Println(metadata["title"])
return os.WriteFile(song.Filename, song.Audio, 0o644)

song.JSON holds the metadata part as the API sent it (composition_plan, song_metadata, words_timestamps and, with WithWaveformVisual, waveform_visual). song.Filename is the name the API suggests for the audio, or generated_music.mp3, and song.SongID is the song-id response header, sent when StoreForInpainting is set. The whole body is read before the method returns, so a context deadline or HTTP client Timeout covers the download. An error status returns a *core.APIError, as ComposeDetailed does; a body that isn't a complete multipart body with a JSON part and an audio part returns a *ComposeDetailedDecodeError from the music/client package.

Voices

List all your available voices with Search.

response, err := client.Voices.Search(ctx, &types.SearchVoicesRequest{})
if err != nil {
	return err
}
for _, voice := range response.Voices {
	if name := voice.GetName(); name != nil {
		fmt.Println(*name)
	}
}

For information about the structure of the voices output, please refer to the official ElevenLabs API documentation for Get Voices.

Streaming

Stream audio in real-time, as it's being generated. Convert and Stream both return an io.Reader over the live response body: each Read returns the bytes that have arrived so far, so playback or a file write can start before the server has finished.

audio, err := client.TextToSpeech.Stream(
	ctx,
	"JBFqnCBsd6RMkjVDRZzb",
	&types.StreamTextToSpeechRequest{
		Text:         "This is a... streaming voice.",
		ModelId:      elevenlabs.String("eleven_multilingual_v2"),
		OutputFormat: types.StreamTextToSpeechRequestOutputFormatMp344100128.Ptr(),
	},
)
if err != nil {
	return err
}

chunk := make([]byte, 32*1024)
for {
	n, err := audio.Read(chunk)
	if n > 0 {
		// Process each chunk as it arrives.
		os.Stdout.Write(chunk[:n])
	}
	if err == io.EOF {
		break
	}
	if err != nil {
		return err
	}
}

The reader can be read once. It releases the connection when it reaches io.EOF or a read error. If you stop reading early, close it (it also implements io.Closer) or cancel the request's context:

if closer, ok := audio.(io.Closer); ok {
	closer.Close()
}

Agent workflows as code

The agentworkflows package builds an agent's workflow in code instead of in the editor. Build returns the *types.AgentWorkflowRequestModel that client.Agents.Create and client.Agents.Update take, and ToJSONString returns the workflow as canonical JSON for storing in git. The output is byte-identical to the other ElevenLabs SDKs' builders for the same program.

import "github.com/elevenlabs/elevenlabs-go/agentworkflows"

wf := agentworkflows.New(nil)
triage := wf.Converse("triage", "Find out what the caller needs", nil)
triage.When(agentworkflows.ConditionLLM("Caller gave an order number", nil), nil).
	Tool("lookup_order", []string{"tool_get_order"}, nil).
	OnResult(agentworkflows.ResultBranches{
		Success: func(ok *agentworkflows.Branch) {
			ok.Converse("resolve", "Explain the order status", nil).End(nil)
		},
		Failure: func(failed *agentworkflows.Branch) { failed.GoTo("triage", nil) },
	})
triage.When(agentworkflows.ConditionLLM("Caller wants a human", nil), nil).
	Transfer("human", agentworkflows.DestinationPhone("+15551234567"), nil)

workflow, err := wf.Build(nil)
if err != nil {
	return err // a *agentworkflows.ValidationError listing every problem
}
agent, err := client.Agents.Create(ctx, &types.BodyCreateAgentV1ConvaiAgentsCreatePost{
	ConversationConfig: &types.ConversationalConfig{},
	Workflow:           workflow,
})

Chaining never fails: duplicate ids, unknown targets and options that don't apply to a node are all reported together by Build. To edit an existing workflow, load it with agentworkflows.FromAgent(agent) or agentworkflows.FromJSON(data); node ids, editor positions and edge order are kept.

Agent tools as code

The agenttools package builds webhook, client and system tools in code. Build returns the *types.ToolRequestModel that client.Agents.Tools.Create and client.Agents.Tools.Update take, and ToJSONString returns the tool as canonical JSON (the CLI's tool_configs/*.json format). The output is byte-identical to the other ElevenLabs SDKs' builders for the same program.

import "github.com/elevenlabs/elevenlabs-go/agenttools"

getOrder := agenttools.Webhook("get_order", "Look up an order by the number the caller gives").
	Get("https://api.example.com/orders/{order_id}").
	PathParam("order_id", agenttools.String().Describe("The order number, e.g. A-1042")).
	QueryParam("include", agenttools.String().Constant("items")).
	Header("Authorization", agenttools.HeaderSecret("sec_orders_api")).
	Assign("order_status", "order.status", nil).
	Options(&agenttools.ToolOptions{PreToolSpeech: types.PreToolSpeechModeForce.Ptr()})

request, err := getOrder.Build(nil)
if err != nil {
	return err // a *agenttools.ValidationError listing every problem
}
tool, err := client.Agents.Tools.Create(ctx, request)

transfer := agenttools.SystemTransferToNumber(nil).
	Transfer("Caller asks for billing", agenttools.DestinationPhone("+15551234567"), nil)
entry, err := transfer.BuildConfig(nil) // entry.System goes in the agent's prompt.built_in_tools

Params and bodies are agenttools.Schema values (String, Integer, Number, Bool, Object, Array); each literal needs one value source: Describe, FromVariable, Constant, SystemProvided or Omit. Schemas are values, so one can be reused across tools. To edit an existing tool, load it with agenttools.FromJSON(data) or agenttools.FromResponse(tool); fields the builder doesn't model, and tools of types it can't edit (such as MCP tools), are kept as loaded.

Agents as code

The agentbuilder package defines a whole agent in code: its settings, its tools and its workflow. client.Agents.Push creates or updates every webhook and client tool the agent uses, then the agent with their ids filled in, and client.Agents.Pull loads an existing agent back. Workflow tool nodes take the tools themselves, through agentworkflows.Options.Tools.

import (
	"github.com/elevenlabs/elevenlabs-go/agentbuilder"
	"github.com/elevenlabs/elevenlabs-go/agenttools"
	"github.com/elevenlabs/elevenlabs-go/agentworkflows"
)

getOrder := agenttools.Webhook("get_order", "Look up an order by its number").
	Get("https://api.example.com/orders/{order_id}").
	PathParam("order_id", agenttools.String().Describe("The order number"))

wf := agentworkflows.New(nil)
wf.Converse("triage", "Find out what the caller needs", nil).
	When(agentworkflows.ConditionLLM("Caller gave an order number", nil), nil).
	Tool("lookup", nil, &agentworkflows.Options{Tools: []agentworkflows.Tool{getOrder}})

prompt, greeting := "You are a support agent for Acme.", "Hi, how can I help?"
agent := agentbuilder.New("Support line", &agentbuilder.Options{
	Prompt:       &prompt,
	FirstMessage: &greeting,
	Tools:        []agenttools.Tool{agenttools.SystemEndCall()},
	Workflow:     wf,
})

result, err := client.Agents.Push(ctx, agent, nil) // creates get_order, then the agent
if err != nil {
	return err // a *agentbuilder.ValidationError before any request, or a *agentbuilder.PushError
}
// Later: update the same agent and tools.
_, err = client.Agents.Push(ctx, agent, &agentbuilder.PushOptions{AgentID: result.AgentID})

agent.Validate(nil) runs every check that needs no ids, so CI can check an agent without an API key. Tools the agent stops using are reported as detached, never deleted. If a request fails partway, the *agentbuilder.PushError lists what was already written.

To keep agents in a repository alongside the ElevenLabs CLI, use a project. It reads and writes the CLI's layout (agents.json, tools.json, agent_configs/, tool_configs/), records the ids, and leaves every file nothing changed exactly as it was:

project, err := agentbuilder.OpenProject(".")
if err != nil {
	return err
}
agent, err := project.Agent("Support line")
if err != nil {
	return err
}
agent.Update(&agentbuilder.Options{FirstMessage: &greeting})
_, err = client.Agents.Push(ctx, agent, &agentbuilder.PushOptions{Project: project}) // saves the project

pulled, err := client.Agents.Pull(ctx, "agent_123", &agentbuilder.PullOptions{Project: project})

Settings the SDK doesn't model, in a loaded config or tool, are kept and sent as they are. YAML and TOML configs, tests.json and creating branches aren't supported yet.

Flows

Flows image, video and text-to-speech generations, and flows template runs, are asynchronous: Create returns straight away with a pending status, and Get reports progress until the work is completed or failed. CreateAndWait does both. It polls Get at the pace the server asks for in its Retry-After header, never faster than MinPollInterval (3 seconds by default), and returns the final generation:

generation, err := client.Flows.Image.CreateAndWait(
	ctx,
	&types.ImageGenerationRequest{
		ModelId:   "gpt-image-2",
		GptImage2: &types.GptImage2Request{Prompt: "A lighthouse at dawn, watercolor"},
	},
	&flows.WaitOptions{WaitTimeout: 5 * time.Minute},
)
var timeoutErr *flows.WaitTimeoutError
if errors.As(err, &timeoutErr) {
	// Still running on the server: resume later with client.Flows.Image.Get(ctx, timeoutErr.ID).
	return err
}
if err != nil {
	return err
}
if completed := generation.GetCompleted(); completed != nil {
	fmt.Println(completed.ContentUrl)
} else if failed := generation.GetFailed(); failed != nil {
	fmt.Println("Generation failed:", failed.FailureReason, failed.ErrorMessage)
}

client.Flows.Video.CreateAndWait and client.Flows.TextToSpeech.CreateAndWait work the same way. For a template run, pass the template id; the run comes back with its Status and Outputs:

run, err := client.Flows.Templates.Runs.CreateAndWait(
	ctx,
	"TEMPLATE_ID",
	&templates.TemplateRunCreateRequest{
		Inputs: map[string]*types.TemplateRunInput{"prompt": {String: "A fox in the snow"}},
	},
	nil, // the default wait options: no timeout, 3-second minimum poll interval
)

A failed generation or run is returned with a nil error, so check its status. The error is a *flows.WaitTimeoutError (carrying ID, and TemplateID for a run) when WaitTimeout runs out, wraps ctx.Err() when the context is cancelled, and is the API error when the create call or a status check fails. Request options apply to the create call and to every status check, except option.WithBodyProperties, which only the create call gets.

CreateAndWait is meant for scripts and quickstarts. In production, set Webhook on the request and handle the webhook event instead of holding a process open.

Environments

This SDK allows you to configure different environments for API requests. It defaults to the production environment.

client := elevenlabsclient.NewClient(
	option.WithBaseURL(elevenlabs.Environments.ProductionUs),
)

Available environments:

  • elevenlabs.Environments.Production
  • elevenlabs.Environments.ProductionUs
  • elevenlabs.Environments.ProductionEu
  • elevenlabs.Environments.ProductionIndia
  • elevenlabs.Environments.ProductionSingapore

WithBaseURL also accepts any URL string, such as a staging server or a local mock.

Errors

When the API returns a non-success status code (4xx or 5xx), the method returns a *core.APIError (from github.com/elevenlabs/elevenlabs-go/core) as its error. The HTTP status code is in StatusCode, the response headers in Header and the raw response body in Body. Use errors.As to reach it, and compare StatusCode to handle a specific status:

_, err := client.TextToSpeech.Convert(ctx, "JBFqnCBsd6RMkjVDRZzb", request)

var apiErr *core.APIError
if errors.As(err, &apiErr) {
	fmt.Println("Status code:", apiErr.StatusCode)
	fmt.Println("Response body:", string(apiErr.Body))
	if apiErr.StatusCode == http.StatusNotFound {
		// Handle a 404 specifically.
	}
} else if err != nil {
	// The request never got a response: a network failure, or a cancelled or expired context.
	fmt.Println("Request failed:", err)
}

Webhooks

ElevenLabs signs each webhook it sends with your webhook secret. client.Webhooks.ConstructEvent verifies the ElevenLabs-Signature header and returns the decoded event as a map[string]any. Pass the raw request body exactly as received: re-encoding a decoded body changes the bytes and breaks verification.

http.HandleFunc("/webhooks/elevenlabs", func(w http.ResponseWriter, r *http.Request) {
	rawBody, err := io.ReadAll(r.Body)
	if err != nil {
		http.Error(w, "cannot read body", http.StatusBadRequest)
		return
	}

	event, err := client.Webhooks.ConstructEvent(
		rawBody,
		r.Header.Get("ElevenLabs-Signature"),
		os.Getenv("ELEVENLABS_WEBHOOK_SECRET"),
	)
	if err != nil {
		// Missing or invalid signature, or a timestamp older than 30 minutes.
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}
	fmt.Println(event["type"])
	w.WriteHeader(http.StatusOK)
})

webhooks.ConstructEvent (package github.com/elevenlabs/elevenlabs-go/webhooks) does the same without a client. Each failure is a sentinel error you can match with errors.Is, such as webhooks.ErrSignatureMismatch or webhooks.ErrTimestampOutsideTolerance.

WebSockets

client.TextToSpeech.Realtime(...) opens a connection and returns a *texttospeech.TextToSpeechSocket. Register handlers with its On... methods, call Start to begin delivering messages, send with its typed Send... methods (or SendText and SendBinary for raw frames), and call Close when done. Handlers run one at a time, in arrival order; messages that arrive before Start are held, not dropped.

socket, err := client.TextToSpeech.Realtime(
	ctx,
	&texttospeech.TextToSpeechConnectRequest{
		VoiceId:      "JBFqnCBsd6RMkjVDRZzb",
		ModelId:      elevenlabs.String("eleven_flash_v2_5"),
		OutputFormat: elevenlabs.String("mp3_44100_128"),
	},
	// Stay closed once the server finishes, instead of reconnecting.
	option.WithoutWebSocketReconnect(),
)
if err != nil {
	return err
}
defer socket.Close()

file, err := os.Create("realtime.mp3")
if err != nil {
	return err
}
defer file.Close()

done := make(chan struct{})
socket.OnReceiveMessage(func(message *types.ReceiveMessage) {
	if output := message.GetAudioOutput(); output != nil {
		chunk, err := base64.StdEncoding.DecodeString(output.GetAudio())
		if err == nil {
			file.Write(chunk)
		}
	}
})
socket.OnError(func(err error) {
	log.Println("socket error:", err)
})
socket.OnDisconnected(func(reason core.DisconnectReason) {
	close(done)
})
socket.Start()

for _, message := range []*types.SendMessage{
	{InitializeConnection: &types.InitializeConnection{}},
	{SendText: &types.SendText{Text: "Hello from the Go SDK. "}},
	{CloseConnection: &types.CloseConnection{}},
} {
	if err := socket.SendSendMessage(ctx, message); err != nil {
		return err
	}
}

// The server sends the remaining audio, then closes the connection.
<-done

The SDK has one socket per channel:

  • client.Dubbing.Live returns a *DubbingSocket (package github.com/elevenlabs/elevenlabs-go/dubbing/client)
  • client.TextToSpeech.Realtime returns a *texttospeech.TextToSpeechSocket
  • client.TextToDialogue.Realtime returns a *texttodialogue.TextToDialogueSocket
  • client.SpeechToText.Realtime returns a *SpeechToTextSocket (package github.com/elevenlabs/elevenlabs-go/speechtotext/client)
  • client.SpeechEngine.Upstream returns a *speechengine.SpeechEngineSocket
  • client.TextToDialogueMultiContext.Realtime returns a *texttodialoguemulticontext.TextToDialogueMultiContextSocket
  • client.TextToSpeechMultiContext.Realtime returns a *texttospeechmulticontext.TextToSpeechMultiContextSocket
  • client.Translation.Realtime returns a *translation.TranslationSocket

Every socket has the same lifecycle methods: OnConnected, OnDisconnected, OnError, Start, ReadyState, SendText, SendBinary and Close.

Reconnection

By default a socket reconnects whenever the connection is lost, including when the server closes it normally, and sends the handshake (credentials and connect parameters) again each time. Sends made while it is reconnecting wait for the new connection, bounded by their ctx. The default backoff starts at 1 second, grows by 1.3x per attempt up to 10 seconds, and keeps retrying until Close is called; each handshake attempt times out after 10 seconds.

Pass option.WithoutWebSocketReconnect() for a one-shot session that should stay closed, as in the example above, or tune the backoff with option.WithWebSocketReconnect. Zero fields keep their defaults:

socket, err := client.TextToSpeech.Realtime(
	ctx,
	request,
	option.WithWebSocketReconnect(core.ReconnectOptions{
		MinDelay:    500 * time.Millisecond,
		MaxDelay:    5 * time.Second,
		MaxAttempts: 5,
	}),
)

Speech Engine

With Speech Engine you host a WebSocket server and the ElevenLabs API connects to it: it sends you user transcripts, and you reply with text from your own LLM, which is spoken back to the user.

client.SpeechEngine.Create, Get, Update and Duplicate return a *speechengine.SpeechEngineResource. It carries the client's API key, which it uses to verify the JWT the API sends in the X-Elevenlabs-Speech-Engine-Authorization header of each connection.

import (
	"context"
	"log"
	"net/http"

	elevenlabsclient "github.com/elevenlabs/elevenlabs-go/client"
	"github.com/elevenlabs/elevenlabs-go/speechengine"
	"github.com/elevenlabs/elevenlabs-go/types"
)

client := elevenlabsclient.NewClient()

engine, err := client.SpeechEngine.Create(ctx, &types.CreateSpeechEngineRequest{
	SpeechEngine: &types.SpeechEngineConfig{WsUrl: "wss://your-server.example.com/ws"},
})
if err != nil {
	log.Fatal(err)
}

callbacks := speechengine.SpeechEngineCallbacks{
	OnTranscript: func(ctx context.Context, transcript []speechengine.ConversationMessage, session *speechengine.SpeechEngineSession) error {
		reply, err := myLLM.Generate(ctx, transcript)
		if err != nil {
			return err
		}
		return session.SendResponse(ctx, reply)
	},
}

// Mount the engine on an existing server, next to the rest of your app...
mux := http.NewServeMux()
engine.Attach(mux, "/ws", speechengine.SpeechEngineServerOptions{Callbacks: callbacks})
log.Fatal(http.ListenAndServe(":8080", mux))

// ...or run a standalone server on :3001 until ctx is cancelled.
// err = engine.Serve(ctx, speechengine.SpeechEngineServerOptions{Callbacks: callbacks})

To serve an engine that already exists without fetching it, use client.SpeechEngine.Resource("seng_...").

The ctx passed to OnTranscript is cancelled when the user interrupts (a newer transcript arrives), when the conversation ends, and when OnTranscript returns. Pass it to your LLM call so abandoned responses stop, and pass it to SendResponse, which uses it to tag the reply with the transcript it answers and sends nothing once the turn has been interrupted.

To stream a response, call session.SendResponseChunk(ctx, chunk) for each piece and then session.EndResponse(ctx), or hand a channel to session.SendResponseStream. A chunk is a string or an OpenAI, Anthropic or Gemini stream event (a struct, map or raw JSON), whose text is extracted for you.

The other callbacks are OnInit (the conversation ID), OnClose (the API ended the conversation), OnDisconnect (the connection is gone) and OnError.

To handle the WebSocket upgrade yourself, check the request with engine.VerifyRequest(r), accept it with github.com/coder/websocket, and run the conversation with speechengine.ServeSpeechEngineConn(ctx, conn, callbacks, nil). speechengine.VerifySpeechEngineJWT verifies a token on its own.

SpeechEngineServerOptions.DisableAuth accepts connections without verifying them. Only use it behind an IP allowlist that admits ElevenLabs alone.

Advanced

Retries

The 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 attempts has not grown larger than the configured limit (default: 2 attempts, that is the first request and one retry).

A request is deemed retryable when any of the following HTTP status codes is returned:

  • 408 (Timeout)
  • 429 (Too Many Requests)
  • 5XX (Internal Server Error)

Between attempts the SDK waits as long as the Retry-After or X-RateLimit-Reset response header asks, and otherwise backs off exponentially from 1 second, with jitter. No wait exceeds 60 seconds. A request that fails without a response, such as a refused connection, is not retried.

Set the limit on the client with option.WithMaxAttempts, or turn retries off for one call with option.WithoutRetries (WithMaxAttempts(0) falls back to the default):

client := elevenlabsclient.NewClient(
	option.WithMaxAttempts(3),
)

// Send this one request exactly once.
client.TextToSpeech.Convert(ctx, "JBFqnCBsd6RMkjVDRZzb", request, option.WithoutRetries())
Timeouts

The SDK sets no timeout of its own: without a custom HTTP client it uses Go's http.DefaultClient, which waits indefinitely. Bound a call with a context deadline, or set Timeout on an *http.Client that you pass to the client. Both limits also cover reading the response body, so leave room for long audio.

client := elevenlabsclient.NewClient(
	option.WithHTTPClient(&http.Client{Timeout: 60 * time.Second}),
)

ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
client.TextToSpeech.Convert(ctx, "JBFqnCBsd6RMkjVDRZzb", request)
Custom HTTP Client

This SDK is built to work with any instance of *http.Client (or any type with a Do(*http.Request) (*http.Response, error) method). By default, if no client is provided, the SDK uses http.DefaultClient. Pass your own, for example to set a proxy or transport, through option.WithHTTPClient:

httpClient := &http.Client{
	Transport: &http.Transport{
		Proxy: http.ProxyFromEnvironment,
	},
}

client := elevenlabsclient.NewClient(
	option.WithHTTPClient(httpClient),
)
Per-request Options

Every method accepts variadic opts ...option.RequestOption to override behavior for a single call โ€” a different base URL, additional headers, additional query parameters, or additional body properties. Passed to NewClient instead, the base URL, headers, API key, HTTP client and retry options apply to every call; query parameters and body properties take effect only per call.

client.TextToSpeech.Convert(
	ctx,
	"JBFqnCBsd6RMkjVDRZzb",
	request,
	option.WithBaseURL("https://staging.example.com"),
	option.WithHTTPHeader(http.Header{"X-Custom-Header": []string{"value"}}),
	option.WithQueryParameters(url.Values{"trace": []string{"true"}}),
	option.WithBodyProperties(map[string]interface{}{"extra_field": "value"}),
)
Raw Response

Each resource client that makes HTTP calls, such as client.TextToSpeech, has a WithRawResponse field with the same methods. They return a *core.Response holding the status code and response headers alongside the body:

response, err := client.TextToSpeech.WithRawResponse.Convert(ctx, "JBFqnCBsd6RMkjVDRZzb", request)
if err != nil {
	return err
}
fmt.Println(response.StatusCode)
fmt.Println(response.Header.Get("Content-Type"))
audio := response.Body // the io.Reader that Convert returns

Languages Supported

Explore all models & languages.

Contributing

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!

Documentation ยถ

Index ยถ

Constants ยถ

This section is empty.

Variables ยถ

View Source
var Environments = struct {
	Production          string
	ProductionUs        string
	ProductionEu        string
	ProductionIndia     string
	ProductionSingapore string
}{
	Production:          "https://api.elevenlabs.io",
	ProductionUs:        "https://api.us.elevenlabs.io",
	ProductionEu:        "https://api.eu.residency.elevenlabs.io",
	ProductionIndia:     "https://api.in.residency.elevenlabs.io",
	ProductionSingapore: "https://api.sg.residency.elevenlabs.io",
}

Environments defines all of the API environments. These values can be used with the WithBaseURL RequestOption to override the client's default environment, if any.

View Source
var ErrorCodes internal.ErrorCodes = internal.ErrorCodes{
	400: func(apiError *core.APIError) error {
		return &BadRequestError{
			APIError: apiError,
		}
	},
	401: func(apiError *core.APIError) error {
		return &UnauthorizedError{
			APIError: apiError,
		}
	},
	403: func(apiError *core.APIError) error {
		return &ForbiddenError{
			APIError: apiError,
		}
	},
	404: func(apiError *core.APIError) error {
		return &NotFoundError{
			APIError: apiError,
		}
	},
	409: func(apiError *core.APIError) error {
		return &ConflictError{
			APIError: apiError,
		}
	},
	422: func(apiError *core.APIError) error {
		return &UnprocessableEntityError{
			APIError: apiError,
		}
	},
	425: func(apiError *core.APIError) error {
		return &TooEarlyError{
			APIError: apiError,
		}
	},
}
View Source
var NewConfig = apiconfig.NewConfig

NewConfig creates a Config with spec-derived defaults.

View Source
var NewRetryConfig = apiconfig.NewRetryConfig

NewRetryConfig returns a RetryConfig initialized with spec-derived defaults.

View Source
var WithBaseURL = apiconfig.WithBaseURL

WithBaseURL returns a RequestOption that overrides BaseURL for a single request.

View Source
var WithRetryConfig = apiconfig.WithRetryConfig

WithRetryConfig returns a RequestOption that overrides the RetryConfig for a single request.

View Source
var WithTimeout = apiconfig.WithTimeout

WithTimeout returns a RequestOption that overrides Timeout for a single request.

Functions ยถ

func Bool ยถ

func Bool(b bool) *bool

Bool returns a pointer to the given bool value.

func Byte ยถ

func Byte(b byte) *byte

Byte returns a pointer to the given byte value.

func Bytes ยถ

func Bytes(b []byte) *[]byte

Bytes returns a pointer to the given []byte value.

func Complex64 ยถ

func Complex64(c complex64) *complex64

Complex64 returns a pointer to the given complex64 value.

func Complex128 ยถ

func Complex128(c complex128) *complex128

Complex128 returns a pointer to the given complex128 value.

func Float32 ยถ

func Float32(f float32) *float32

Float32 returns a pointer to the given float32 value.

func Float64 ยถ

func Float64(f float64) *float64

Float64 returns a pointer to the given float64 value.

func Int ยถ

func Int(i int) *int

Int returns a pointer to the given int value.

func Int8 ยถ

func Int8(i int8) *int8

Int8 returns a pointer to the given int8 value.

func Int16 ยถ

func Int16(i int16) *int16

Int16 returns a pointer to the given int16 value.

func Int32 ยถ

func Int32(i int32) *int32

Int32 returns a pointer to the given int32 value.

func Int64 ยถ

func Int64(i int64) *int64

Int64 returns a pointer to the given int64 value.

func MustParseDate ยถ

func MustParseDate(date string) time.Time

MustParseDate attempts to parse the given string as a date time.Time, and panics upon failure.

func MustParseDateTime ยถ

func MustParseDateTime(datetime string) time.Time

MustParseDateTime attempts to parse the given string as a datetime time.Time, and panics upon failure.

func Null ยถ

func Null[T any]() *param.Nullable[T]

Null returns a *param.Nullable[T] with IsNull set to true, signalling an explicit JSON null.

func Nullable ยถ

func Nullable[T any](v T) *param.Nullable[T]

Nullable returns a *param.Nullable[T] set to v โ€” use for nullable fields with a value.

func Ptr ยถ

func Ptr[T any](v T) *T

Ptr returns a pointer to v โ€” use when no type-specific helper exists.

func Rune ยถ

func Rune(r rune) *rune

Rune returns a pointer to the given rune value.

func String ยถ

func String(s string) *string

String returns a pointer to the given string value.

func Time ยถ

func Time(t time.Time) *time.Time

Time returns a pointer to the given time.Time value.

func UUID ยถ

func UUID(u uuid.UUID) *uuid.UUID

UUID returns a pointer to the given uuid.UUID value.

func Uint ยถ

func Uint(u uint) *uint

Uint returns a pointer to the given uint value.

func Uint8 ยถ

func Uint8(u uint8) *uint8

Uint8 returns a pointer to the given uint8 value.

func Uint16 ยถ

func Uint16(u uint16) *uint16

Uint16 returns a pointer to the given uint16 value.

func Uint32 ยถ

func Uint32(u uint32) *uint32

Uint32 returns a pointer to the given uint32 value.

func Uint64 ยถ

func Uint64(u uint64) *uint64

Uint64 returns a pointer to the given uint64 value.

func Uintptr ยถ

func Uintptr(u uintptr) *uintptr

Uintptr returns a pointer to the given uintptr value.

Types ยถ

type ApiError ยถ

type ApiError[T any] struct {
	Err      error
	Data     *T
	Body     []byte
	Raw      *http.Response
	Metadata ApiErrorMetadata
}

ApiError wraps API errors with detailed metadata including status code, headers, and raw response. It implements the error interface and provides structured access to error information.

func NewApiError ยถ

func NewApiError[T any](transportError *httptransport.ErrorResponse[T]) *ApiError[T]

NewApiError creates a new ApiError from an internal transport error. It extracts error details, body, status code, and headers into a user-facing error structure.

func (*ApiError[T]) Error ยถ

func (e *ApiError[T]) Error() string

Error implements the error interface, returning the error message string.

func (*ApiError[T]) GetBody ยถ

func (e *ApiError[T]) GetBody() []byte

GetBody returns the raw response body bytes from the error response. Returns nil if no response body was received.

func (*ApiError[T]) GetData ยถ

func (e *ApiError[T]) GetData() *T

GetData returns the deserialized error response data. Returns nil if unmarshaling failed or the response body was empty.

func (*ApiError[T]) Unwrap ยถ

func (e *ApiError[T]) Unwrap() error

Unwrap returns the underlying error, enabling errors.Is and errors.As to traverse the chain.

type ApiErrorMetadata ยถ

type ApiErrorMetadata struct {
	Headers    map[string]string
	StatusCode int
}

ApiErrorMetadata contains HTTP metadata associated with an error response.

type ApiResponse ยถ

type ApiResponse[T any] struct {
	Data     T
	Raw      *http.Response
	Metadata ApiResponseMetadata
}

ApiResponse is the user-facing wrapper for API responses. It contains the deserialized data, raw HTTP response, and metadata like headers and status code.

func NewApiResponse ยถ

func NewApiResponse[T any](resp *httptransport.Response[T]) *ApiResponse[T]

NewApiResponse creates a new response wrapper from an internal transport response. Extracts data and metadata into a user-facing structure.

func (*ApiResponse[T]) GetData ยถ

func (r *ApiResponse[T]) GetData() T

GetData returns the deserialized response data.

func (ApiResponse[T]) String ยถ

func (r ApiResponse[T]) String() string

String returns a JSON representation of the response for debugging. Returns an error message if JSON marshaling fails.

type ApiResponseMetadata ยถ

type ApiResponseMetadata struct {
	Headers    map[string]string
	StatusCode int
}

ApiResponseMetadata contains HTTP metadata from the API response. Includes status code and headers for inspection and debugging.

type BadRequestError ยถ

type BadRequestError struct {
	*core.APIError
	Body any
}

Invalid request

func (*BadRequestError) GetBody ยถ

func (b *BadRequestError) GetBody() any

func (*BadRequestError) MarshalJSON ยถ

func (b *BadRequestError) MarshalJSON() ([]byte, error)

func (*BadRequestError) UnmarshalJSON ยถ

func (b *BadRequestError) UnmarshalJSON(data []byte) error

func (*BadRequestError) Unwrap ยถ

func (b *BadRequestError) Unwrap() error

type Config ยถ

type Config = apiconfig.Config

Config holds all configuration parameters for the SDK client.

type ConflictError ยถ

type ConflictError struct {
	*core.APIError
	Body any
}

A generation for this preview is already in progress. Retry the request.

func (*ConflictError) GetBody ยถ

func (c *ConflictError) GetBody() any

func (*ConflictError) MarshalJSON ยถ

func (c *ConflictError) MarshalJSON() ([]byte, error)

func (*ConflictError) UnmarshalJSON ยถ

func (c *ConflictError) UnmarshalJSON(data []byte) error

func (*ConflictError) Unwrap ยถ

func (c *ConflictError) Unwrap() error

type FileParam ยถ

type FileParam struct {
	io.Reader
	// contains filtered or unexported fields
}

FileParam is a file type suitable for multipart/form-data uploads.

func NewFileParam ยถ

func NewFileParam(
	reader io.Reader,
	filename string,
	contentType string,
	opts ...FileParamOption,
) *FileParam

NewFileParam returns a *FileParam type suitable for multipart/form-data uploads. All file upload endpoints accept a simple io.Reader, which is usually created by opening a file via os.Open.

However, some endpoints require additional metadata about the file such as a specific Content-Type or custom filename. FileParam makes it easier to create the correct type signature for these endpoints.

func (*FileParam) ContentType ยถ

func (f *FileParam) ContentType() string

func (*FileParam) Name ยถ

func (f *FileParam) Name() string

type FileParamOption ยถ

type FileParamOption interface {
	// contains filtered or unexported methods
}

FileParamOption adapts the behavior of the FileParam. No options are implemented yet, but this interface allows for future extensibility.

type ForbiddenError ยถ

type ForbiddenError struct {
	*core.APIError
	Body any
}

Permission denied

func (*ForbiddenError) GetBody ยถ

func (f *ForbiddenError) GetBody() any

func (*ForbiddenError) MarshalJSON ยถ

func (f *ForbiddenError) MarshalJSON() ([]byte, error)

func (*ForbiddenError) UnmarshalJSON ยถ

func (f *ForbiddenError) UnmarshalJSON(data []byte) error

func (*ForbiddenError) Unwrap ยถ

func (f *ForbiddenError) Unwrap() error

type NotFoundError ยถ

type NotFoundError struct {
	*core.APIError
	Body any
}

Dubbing not found

func (*NotFoundError) GetBody ยถ

func (n *NotFoundError) GetBody() any

func (*NotFoundError) MarshalJSON ยถ

func (n *NotFoundError) MarshalJSON() ([]byte, error)

func (*NotFoundError) UnmarshalJSON ยถ

func (n *NotFoundError) UnmarshalJSON(data []byte) error

func (*NotFoundError) Unwrap ยถ

func (n *NotFoundError) Unwrap() error

type RequestOption ยถ

type RequestOption = apiconfig.RequestOption

RequestOption is a function that configures a single request.

type RetryConfig ยถ

type RetryConfig = apiconfig.RetryConfig

RetryConfig holds all runtime-configurable retry parameters.

type TooEarlyError ยถ

type TooEarlyError struct {
	*core.APIError
	Body any
}

Dubbing not ready

func (*TooEarlyError) GetBody ยถ

func (t *TooEarlyError) GetBody() any

func (*TooEarlyError) MarshalJSON ยถ

func (t *TooEarlyError) MarshalJSON() ([]byte, error)

func (*TooEarlyError) UnmarshalJSON ยถ

func (t *TooEarlyError) UnmarshalJSON(data []byte) error

func (*TooEarlyError) Unwrap ยถ

func (t *TooEarlyError) Unwrap() error

type UnauthorizedError ยถ

type UnauthorizedError struct {
	*core.APIError
	Body any
}

Authentication required

func (*UnauthorizedError) GetBody ยถ

func (u *UnauthorizedError) GetBody() any

func (*UnauthorizedError) MarshalJSON ยถ

func (u *UnauthorizedError) MarshalJSON() ([]byte, error)

func (*UnauthorizedError) UnmarshalJSON ยถ

func (u *UnauthorizedError) UnmarshalJSON(data []byte) error

func (*UnauthorizedError) Unwrap ยถ

func (u *UnauthorizedError) Unwrap() error

type UnprocessableEntityError ยถ

type UnprocessableEntityError struct {
	*core.APIError
	Body *types.HttpValidationError
}

Validation Error

func (*UnprocessableEntityError) GetBody ยถ

func (*UnprocessableEntityError) MarshalJSON ยถ

func (u *UnprocessableEntityError) MarshalJSON() ([]byte, error)

func (*UnprocessableEntityError) UnmarshalJSON ยถ

func (u *UnprocessableEntityError) UnmarshalJSON(data []byte) error

func (*UnprocessableEntityError) Unwrap ยถ

func (u *UnprocessableEntityError) Unwrap() error

Directories ยถ

Path Synopsis
Package agentbuilder writes ElevenLabs agents as code: an agent's settings, its tools and its workflow in one definition, pushed with client.Agents.Push and pulled with client.Agents.Pull, and stored in the ElevenLabs CLI's project layout with Project.
Package agentbuilder writes ElevenLabs agents as code: an agent's settings, its tools and its workflow in one definition, pushed with client.Agents.Push and pulled with client.Agents.Pull, and stored in the ElevenLabs CLI's project layout with Project.
llm
Package agenttools writes ElevenLabs agent tools as code: webhook, client and system tools.
Package agenttools writes ElevenLabs agent tools as code: webhook, client and system tools.
Package agentworkflows writes ElevenLabs agent workflows as code.
Package agentworkflows writes ElevenLabs agent workflows as code.
internal/flowswait
Package flowswait is the polling loop behind the flows CreateAndWait helpers.
Package flowswait is the polling loop behind the flows CreateAndWait helpers.
wirejson
Package wirejson is the canonical JSON layer shared by the hand-written agents-as-code builders (the workflow builder in agentworkflows and the tools builder in agenttools).
Package wirejson is the canonical JSON layer shared by the hand-written agents-as-code builders (the workflow builder in agentworkflows and the tools builder in agenttools).
ivc
pvc
Package webhooks manages workspace webhooks and verifies the webhooks that ElevenLabs sends to your server.
Package webhooks manages workspace webhooks and verifies the webhooks that ElevenLabs sends to your server.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL