elevenlabs

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Jun 29, 2026 License: MIT Imports: 12 Imported by: 0

README

elevenlabs-go

A small Go client for the ElevenLabs API.

This module currently focuses on speech-to-text workflows and a few account metadata endpoints:

  • create, retrieve, and delete transcripts
  • submit asynchronous transcript webhook jobs
  • stream audio to the realtime transcription WebSocket API
  • list models
  • read authenticated user metadata
  • inspect API errors and raw HTTP response metadata
  • retry replayable transient failures

Installation

go get github.com/emiliopalmerini/elevenlabs-go@v0.2.0

Import the package as:

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

Speech-to-text APIs live in their own subpackage:

import "github.com/emiliopalmerini/elevenlabs-go/speechtotext"

Quick Start

package main

import (
	"context"
	"fmt"
	"log"
	"os"

	"github.com/emiliopalmerini/elevenlabs-go/speechtotext"
)

func main() {
	ctx := context.Background()
	client := speechtotext.NewClient(os.Getenv("ELEVENLABS_API_KEY"))

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

	transcript, err := client.CreateTranscript(ctx, speechtotext.CreateTranscriptRequest{
		ModelID: "scribe_v1",
		File: &speechtotext.File{
			Name:   "audio.mp3",
			Reader: file,
		},
	})
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(transcript.Text)
}

You can also transcribe by URL:

transcript, err := client.CreateTranscript(ctx, speechtotext.CreateTranscriptRequest{
	ModelID:   "scribe_v1",
	SourceURL: "https://example.com/audio.mp3",
})

Advanced Transcript Options

CreateTranscriptRequest exposes ElevenLabs speech-to-text options such as language code, diarization, speaker count, keyterms, multichannel output, entity detection, redaction, additional formats, webhook metadata, and upload progress callbacks.

diarize := true

transcript, err := client.CreateTranscript(ctx, speechtotext.CreateTranscriptRequest{
	ModelID:      "scribe_v1",
	SourceURL:    "https://example.com/interview.mp3",
	LanguageCode: "en",
	Diarize:      &diarize,
	Keyterms:     []string{"ElevenLabs", "speech-to-text"},
})

For multichannel responses, Transcript.Chunks() returns the channel-level transcripts when present, otherwise a single chunk containing the transcript itself.

Webhook Transcripts

Use SubmitTranscriptWebhook when the transcript should be processed asynchronously by ElevenLabs:

resp, err := client.SubmitTranscriptWebhook(ctx, speechtotext.CreateTranscriptRequest{
	ModelID:   "scribe_v1",
	SourceURL: "https://example.com/audio.mp3",
	WebhookID: "your-webhook-id",
	WebhookMetadata: map[string]any{
		"job_id": "123",
	},
})
if err != nil {
	return err
}

fmt.Println(resp.TranscriptionID)

Realtime Transcription

Realtime transcription uses the package WebSocket session type:

session, err := client.ConnectRealtimeTranscript(ctx, speechtotext.RealtimeTranscriptRequest{
	ModelID:     "scribe_v1",
	AudioFormat: "pcm_16000",
})
if err != nil {
	return err
}
defer session.Close()

if err := session.SendAudioChunk(speechtotext.RealtimeAudioChunk{
	Audio:      pcmBytes,
	Commit:     true,
	SampleRate: 16000,
}); err != nil {
	return err
}

event, err := session.Receive()
if err != nil {
	return err
}

fmt.Println(event.Text)

The session can authenticate with the client API key or with a realtime token passed on RealtimeTranscriptRequest.Token.

Response Metadata

Methods ending in WithResponse return parsed data plus raw HTTP metadata:

resp, err := client.GetTranscriptWithResponse(ctx, "transcript-id")
if err != nil {
	return err
}

fmt.Println(resp.RawResponse.StatusCode)
fmt.Println(resp.RawResponse.Header.Get("request-id"))
fmt.Println(resp.Data.Text)

Error Handling

Non-2xx API responses return *elevenlabs.APIError when the response can be read:

transcript, err := client.GetTranscript(ctx, "transcript-id")
if err != nil {
	var apiErr *elevenlabs.APIError
	if errors.As(err, &apiErr) {
		fmt.Println(apiErr.StatusCode)
		fmt.Println(apiErr.Message)
		fmt.Println(apiErr.RequestID)
		return err
	}
	return err
}

fmt.Println(transcript.Text)

APIError keeps provider error fields, validation details, retry headers, and the raw response metadata.

Retries

Replayable requests retry transient status codes by default:

  • 429 Too Many Requests
  • 500 Internal Server Error
  • 502 Bad Gateway
  • 503 Service Unavailable
  • 504 Gateway Timeout

Customize or disable retries with client options:

client := speechtotext.NewClient(
	os.Getenv("ELEVENLABS_API_KEY"),
	elevenlabs.WithRetryConfig(elevenlabs.RetryConfig{
		MaxAttempts: 5,
	}),
)

noRetryClient := speechtotext.NewClient(
	os.Getenv("ELEVENLABS_API_KEY"),
	elevenlabs.WithoutRetries(),
)

File uploads are retried only when the upload body can be replayed.

Client Options

client := speechtotext.NewClient(
	os.Getenv("ELEVENLABS_API_KEY"),
	elevenlabs.WithHTTPClient(customHTTPClient),
	elevenlabs.WithBaseURL("https://api.elevenlabs.io"),
)

WithBaseURL is mainly useful for tests or custom API routing.

Development

Run the package checks with:

go test ./...
go vet ./...

Tagged releases are standard Go module versions:

git tag v0.1.0
git push origin v0.1.0

Consumers can then depend on the module with:

go get github.com/emiliopalmerini/elevenlabs-go@v0.2.0

Documentation

Overview

Package elevenlabs provides a small Go client for the ElevenLabs API.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func DecodeOptionalResponse added in v0.2.0

func DecodeOptionalResponse(body []byte) (any, error)

DecodeOptionalResponse decodes a JSON response body when one is present.

func DecodeResponse added in v0.2.0

func DecodeResponse(body []byte, out any) error

DecodeResponse decodes a JSON response body into out.

Types

type APIError

type APIError struct {
	StatusCode      int
	Status          string
	Message         string
	Body            []byte
	ProviderType    string
	ProviderCode    string
	ProviderStatus  string
	ProviderMessage string
	RequestID       string
	TraceID         string
	RetryAfter      string
	Validation      []ValidationError
	RawResponse     RawResponse
}

APIError is returned when the ElevenLabs API responds with a non-2xx status.

func (*APIError) Error

func (e *APIError) Error() string

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client is an ElevenLabs API client.

func NewClient

func NewClient(apiKey string, opts ...ClientOption) *Client

NewClient creates a Client that authenticates with apiKey.

func (*Client) AuthHeader added in v0.2.0

func (c *Client) AuthHeader() (http.Header, error)

AuthHeader returns the API key auth header for non-standard transports.

func (*Client) Do added in v0.2.0

func (c *Client) Do(ctx context.Context, build RequestBuilder, retryable bool) ([]byte, RawResponse, error)

Do executes requests with the client's retry policy.

func (*Client) Endpoint added in v0.2.0

func (c *Client) Endpoint(path string) (string, error)

Endpoint resolves an API path against the configured base URL.

func (*Client) GetJSON added in v0.2.0

func (c *Client) GetJSON(ctx context.Context, path string, out any) (RawResponse, error)

GetJSON sends a retryable GET request and decodes the JSON response.

func (*Client) GetUser

func (c *Client) GetUser(ctx context.Context) (*User, error)

GetUser gets information about the authenticated user.

func (*Client) GetUserWithResponse

func (c *Client) GetUserWithResponse(ctx context.Context) (*Response[*User], error)

GetUserWithResponse gets information about the authenticated user and returns HTTP response metadata.

func (*Client) ListModels

func (c *Client) ListModels(ctx context.Context) ([]Model, error)

ListModels gets the list of available models.

func (*Client) ListModelsWithResponse

func (c *Client) ListModelsWithResponse(ctx context.Context) (*Response[[]Model], error)

ListModelsWithResponse gets the list of available models and returns HTTP response metadata.

func (*Client) NewRequest added in v0.2.0

func (c *Client) NewRequest(ctx context.Context, method, path string, body io.Reader) (*http.Request, error)

NewRequest creates an authenticated API request against the configured base URL.

type ClientOption

type ClientOption func(*Client)

ClientOption configures a Client.

func WithBaseURL

func WithBaseURL(baseURL string) ClientOption

WithBaseURL overrides the ElevenLabs API base URL.

This is primarily useful for tests.

func WithHTTPClient

func WithHTTPClient(httpClient *http.Client) ClientOption

WithHTTPClient overrides the HTTP client used for requests.

func WithRetryConfig

func WithRetryConfig(cfg RetryConfig) ClientOption

WithRetryConfig overrides the retry policy used for replayable requests.

func WithoutRetries

func WithoutRetries() ClientOption

WithoutRetries disables automatic retries.

type Model

type Model struct {
	ModelID                            string          `json:"model_id"`
	Name                               string          `json:"name,omitempty"`
	CanBeFinetuned                     bool            `json:"can_be_finetuned,omitempty"`
	CanDoTextToSpeech                  bool            `json:"can_do_text_to_speech,omitempty"`
	CanDoVoiceConversion               bool            `json:"can_do_voice_conversion,omitempty"`
	CanUseStyle                        bool            `json:"can_use_style,omitempty"`
	CanUseSpeakerBoost                 bool            `json:"can_use_speaker_boost,omitempty"`
	ServesProVoices                    bool            `json:"serves_pro_voices,omitempty"`
	TokenCostFactor                    float64         `json:"token_cost_factor,omitempty"`
	Description                        string          `json:"description,omitempty"`
	RequiresAlphaAccess                bool            `json:"requires_alpha_access,omitempty"`
	MaxCharactersRequestFreeUser       int             `json:"max_characters_request_free_user,omitempty"`
	MaxCharactersRequestSubscribedUser int             `json:"max_characters_request_subscribed_user,omitempty"`
	MaximumTextLengthPerRequest        int             `json:"maximum_text_length_per_request,omitempty"`
	Languages                          []ModelLanguage `json:"languages,omitempty"`
	ModelRates                         *ModelRates     `json:"model_rates,omitempty"`
	ConcurrencyGroup                   string          `json:"concurrency_group,omitempty"`
}

Model contains metadata for an ElevenLabs model.

type ModelLanguage

type ModelLanguage struct {
	LanguageID string `json:"language_id"`
	Name       string `json:"name"`
}

ModelLanguage contains language metadata supported by a model.

type ModelRates

type ModelRates struct {
	CharacterCostMultiplier float64 `json:"character_cost_multiplier"`
	CostDiscountMultiplier  float64 `json:"cost_discount_multiplier,omitempty"`
}

ModelRates contains billing rate metadata for a model.

type RawResponse

type RawResponse struct {
	StatusCode int
	Status     string
	Header     http.Header
	URL        string
}

RawResponse contains HTTP response metadata.

It intentionally does not include the response body.

type RequestBuilder added in v0.2.0

type RequestBuilder func(context.Context) (*http.Request, error)

RequestBuilder builds an HTTP request for one attempt.

type Response

type Response[T any] struct {
	Data        T
	RawResponse RawResponse
}

Response contains parsed API data and HTTP response metadata.

type RetryConfig

type RetryConfig struct {
	MaxAttempts int
	BaseDelay   time.Duration
	MaxDelay    time.Duration
	StatusCodes []int
}

RetryConfig configures automatic retries for replayable requests.

MaxAttempts is the total number of attempts, including the initial request. Values less than or equal to 1 disable retries.

func DefaultRetryConfig

func DefaultRetryConfig() RetryConfig

DefaultRetryConfig returns the default retry policy.

type User

type User struct {
	UserID                      string            `json:"user_id,omitempty"`
	Subscription                *UserSubscription `json:"subscription,omitempty"`
	IsNewUser                   bool              `json:"is_new_user,omitempty"`
	XIAPIKey                    string            `json:"xi_api_key,omitempty"`
	CanUseDelayedPaymentMethods bool              `json:"can_use_delayed_payment_methods,omitempty"`
	IsOnboardingCompleted       bool              `json:"is_onboarding_completed,omitempty"`
	FirstName                   string            `json:"first_name,omitempty"`
	CreatedAt                   int64             `json:"created_at,omitempty"`
	SeatType                    string            `json:"seat_type,omitempty"`
	IsAPIKeyHashed              bool              `json:"is_api_key_hashed,omitempty"`
	XIAPIKeyPreview             string            `json:"xi_api_key_preview,omitempty"`
	ShowComplianceTerms         bool              `json:"show_compliance_terms,omitempty"`
	AvailableModels             []string          `json:"available_models,omitempty"`
	NextInvoice                 *UserInvoice      `json:"next_invoice,omitempty"`
}

User contains account metadata returned by the ElevenLabs user endpoint.

type UserInvoice

type UserInvoice struct {
	AmountDueCents         int64 `json:"amount_due_cents,omitempty"`
	NextPaymentAttemptUnix int64 `json:"next_payment_attempt_unix,omitempty"`
}

UserInvoice contains upcoming invoice metadata.

type UserSubscription

type UserSubscription struct {
	Tier                                string       `json:"tier,omitempty"`
	CharacterCount                      int64        `json:"character_count,omitempty"`
	CharacterLimit                      int64        `json:"character_limit,omitempty"`
	CanExtendCharacterLimit             bool         `json:"can_extend_character_limit,omitempty"`
	AllowedToExtendCharacterLimit       bool         `json:"allowed_to_extend_character_limit,omitempty"`
	NextCharacterCountResetUnix         int64        `json:"next_character_count_reset_unix,omitempty"`
	VoiceLimit                          int64        `json:"voice_limit,omitempty"`
	MaxVoiceAddEdits                    int64        `json:"max_voice_add_edits,omitempty"`
	VoiceAddEditCounter                 int64        `json:"voice_add_edit_counter,omitempty"`
	ProfessionalVoiceLimit              int64        `json:"professional_voice_limit,omitempty"`
	CanExtendVoiceLimit                 bool         `json:"can_extend_voice_limit,omitempty"`
	CanUseInstantVoiceCloning           bool         `json:"can_use_instant_voice_cloning,omitempty"`
	CanUseProfessionalVoiceCloning      bool         `json:"can_use_professional_voice_cloning,omitempty"`
	Currency                            string       `json:"currency,omitempty"`
	Status                              string       `json:"status,omitempty"`
	BillingPeriod                       string       `json:"billing_period,omitempty"`
	CharacterRefreshPeriod              string       `json:"character_refresh_period,omitempty"`
	NextInvoice                         *UserInvoice `json:"next_invoice,omitempty"`
	HasOpenInvoices                     bool         `json:"has_open_invoices,omitempty"`
	CanUsePVCInstantly                  bool         `json:"can_use_pvc_instantly,omitempty"`
	CanUseVoiceDesign                   bool         `json:"can_use_voice_design,omitempty"`
	CanUseInstantVoiceCloningTrial      bool         `json:"can_use_instant_voice_cloning_trial,omitempty"`
	CanUseProfessionalVoiceCloningTrial bool         `json:"can_use_professional_voice_cloning_trial,omitempty"`
}

UserSubscription contains subscription and quota metadata for a user.

type ValidationError

type ValidationError struct {
	Loc  []any  `json:"loc"`
	Msg  string `json:"msg"`
	Type string `json:"type"`
}

ValidationError contains validation details returned by the ElevenLabs API.

Directories

Path Synopsis
Package speechtotext provides ElevenLabs speech-to-text APIs.
Package speechtotext provides ElevenLabs speech-to-text APIs.

Jump to

Keyboard shortcuts

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